def __init_network_config(self): if not os.path.exists(glib.get_user_config_dir()): os.mkdir(glib.get_user_config_dir()) self.config_file = os.path.join(glib.get_user_config_dir(), "network.conf") if not os.path.exists(self.config_file): open(self.config_file, "w").close() self.cf = ConfigParser.RawConfigParser() self.cf.optionxform = str self.cf.read(self.config_file) if "conn_priority" not in self.cf.sections(): self.cf.add_section("conn_priority") if WIRE_SECTION not in self.cf.sections(): self.cf.add_section(WIRE_SECTION) if WIRELESS_SECTION not in self.cf.sections(): self.cf.add_section(WIRELESS_SECTION) max_prio = 0 for conn_uuid in map(lambda x: x.settings_dict["connection"]["uuid"], self.list_connections()): if conn_uuid not in self.cf.options("conn_priority"): self.cf.set("conn_priority", conn_uuid, 0) if self.cf.getint("conn_priority", conn_uuid) > max_prio: max_prio = self.cf.getint("conn_priority", conn_uuid) if max_prio >= 1024: for conn_uuid in self.cf.options("conn_priority"): self.cf.set("conn_priority", conn_uuid, int(self.cf.getint("conn_priority", conn_uuid)/2)) self.cf.write(open(self.config_file, "w"))
def __init__(self, exposed_object, profile='default', use_config=True): """ Plugins(exposed_object, profile='default', use_config=True) -> Initialize the plugin class. """ super(Plugins, self).__init__() self._exposed_object = exposed_object self._use_config = use_config self._profile = profile self._plugin_dict = {} self._config_path = '%s/%s/%s' % \ (glib.get_user_config_dir(), APP_NAME, profile) self._plugin_path = '%s/%s/plugins' % \ (glib.get_user_config_dir(), APP_NAME) # Create user plugin directory if it does not exist. if not os.path.isdir(self._plugin_path): os.mkdir(self._plugin_path) self._config_filename = None self._path = [self._plugin_path] self._prefix = None self._config_dict = {}
def __init__(self, tab): """ Initialize the styles loader. """ self._path = '%s/%s/styles' % (get_user_config_dir(), APP_NAME) self._profile_path = '%s/%s/%s/styles' % \ (get_user_config_dir(), APP_NAME, profile) self._tab = tab self._log_func = tab.print_message self._enabled = True
def __init__(self, tab): """ Initialize the script runner. """ self._path = '%s/%s/scripts' % (get_user_config_dir(), APP_NAME) self._profile_path = '%s/%s/%s/scripts' % \ (get_user_config_dir(), APP_NAME, profile) self._tab = tab self._log_func = tab.print_message self._enabled = True
def save_config(config): path = os.path.join(glib.get_user_config_dir(), 'kobita') if not os.path.isdir(path): os.mkdir(path) path = os.path.join(path, 'config') with open(path, 'w') as f: json.dump(config, f)
def __init__(self, path=None): RawConfigParser.__init__(self) if path: self.location = path else: config_home = glib.get_user_config_dir() config_home = os.path.join(config_home, 'feattool') if not os.path.exists(config_home): os.makedirs(config_home) self.location = os.path.join(config_home, 'settings.ini') if not os.path.exists(self.location): open(self.location, "w").close() self._dirty = False self._saving = False try: self.read(self.location) except: pass #Save settings every 30 secs glib.timeout_add_seconds(30, self._timeout_save)
def __init__(self): # Command line args args = sys.argv[1:] testmode = True if "--test" in args else False root = os.path.dirname(__path__[0]) if testmode else sys.prefix debugmode = True if "--debug" in args else False __builtins__['log'] = logm.log_main if debugmode else logm.log_null # Directories and localization self.locale = locale.getlocale() maindir = os.path.join(root, 'share', 'euphorbia') datadir = os.path.join(glib.get_user_data_dir(), 'euphorbia') confdir = os.path.join(glib.get_user_config_dir(), 'euphorbia') cfgfile = os.path.join(confdir, 'euphorbia.cfg') locales = os.path.join(root, 'share', 'locale') gettext.install('euphorbia', locales) # Preferences self.prefm = prefs.PrefsManager(cfgfile, testmode) self.prefm.set_pref('system_maindir', maindir) self.prefm.set_pref('system_datadir', datadir) self.prefm.set_pref('system_confdir', confdir) # Load application self.plugm = exts.PluginsManager(self) self.gui = ui.EuphorbiaGUI(self) self._load_plugins() self.prefm.autoconnect_gtk(self.gui.win) # Open files given in command line args = [a for a in args if not a.startswith("--")] projfile = self.prefm.get_pref('files_lastprj') if len(args) > 0: for f in args: self.gui.do_open(f, 'all') elif self.prefm.get_pref('files_reopenprj') and projfile is not None: self.gui.do_open(projfile, 'project') else: self.gui.act_new()
def __init__(self, filename='bookmarks.xbel', profile='default'): super(BookmarksMenu, self).__init__() self._bookmarks_filename = '%s/%s/%s/%s' % \ (glib.get_user_config_dir(), APP_NAME, profile, filename) self._bookmarks = None self._completion_model = gtk.ListStore(str, str)
def get_config_folder(): '''获取设置文件夹''' config_folder = "%s/gmbox" % glib.get_user_config_dir() if config_folder is None: config_folder = "%s/config/" % PROGRAM_ROOT_PATH return config_folder
def full_sync(addressbook=None): my_settings = settings.get_settings() if my_settings['resource'] == "": return # sqlite3 database connection conn = sqlite3.connect(os.path.join(glib.get_user_config_dir(), 'pyaddressbook', 'addressbook.db')) # local_status 0=nothing, 1=locally new, 2=locally deleted, 3=locally modified conn.execute('CREATE TABLE if not exists vcards (etag text primary key unique not null, href text unique not null, vcard text not null, local_status smallint default 0)') conn.commit() available_href2etag = {} for href,etag in conn.execute('select href,etag from vcards where local_status<>1').fetchall(): available_href2etag[href] = etag cdav = carddav2.PyCardDAV(verify=my_settings['verify'], resource=my_settings['resource'], user=my_settings['user'], passwd=my_settings['passwd'], write_support=True) abook = cdav.get_abook() deleted_vcards = available_href2etag.copy() server_modified_vcards = {} for href,etag in abook.items(): if href in deleted_vcards: del deleted_vcards[href] if not href in available_href2etag or available_href2etag[href] != etag: server_modified_vcards[href] = etag # delete local vcards if they have been removed from the server side for href,etag in deleted_vcards.items(): print("Removing contact for href: %s" % href) conn.execute('delete from vcards where href=?', (href,)) if addressbook: addressbook.vcard_removed(href) # update local vcards that have been modified on the server side (regardless of the local status, i.e. locally modified vcards will be updated to the server side version) href_list = [ href for href,etag in server_modified_vcards.items() ] if len(href_list) > 0: print('Requesting modified/new vcards from server') dav_list = cdav._get_vcards(href_list) for dav in dav_list: href = dav['href'] status = dav['status'] etag = dav['etag'] vcard = dav['vcard'] print("Updating vcard for href %s since it was updated on the server-side" % href) if href in available_href2etag: conn.execute('update vcards set etag=?,href=?,vcard=?,local_status=0 where href=?', (etag,href,vcard,href)) if addressbook: addressbook.vcard_updated(href, vcard) else: conn.execute('INSERT INTO vcards VALUES (?,?,?,0)', (etag,href, vcard)) if addressbook: addressbook.vcard_added(href, etag, vcard) sync_local_changes(cdav, conn) if my_settings['write_vcf']: write_to_vcf(conn, my_settings['vcf_path']) conn.commit() conn.close()
def __init__(self, rootkey, initial): """Create a preferences object. Settings are initialised with 'initial' and then overriden from values in the ConfigParser database if available. rootkey : unused (retained for compatibility with existing gconf API) initial : a dictionary of string to Value objects. """ self.__dict__["_parser"] = ConfigParser.SafeConfigParser() self.__dict__["_listeners"] = [] self.__dict__["_prefs"] = initial self.__dict__["_type_mappings"] = { BOOL: self._parser.getboolean, INT: self._parser.getint, STRING: self._parser.get, FLOAT: self._parser.getfloat, LIST: self._parser.get, } if sys.platform == "win32": pref_dir = os.path.join(os.getenv("APPDATA"), "Meld") else: pref_dir = os.path.join(glib.get_user_config_dir(), "meld") if not os.path.exists(pref_dir): os.makedirs(pref_dir) self.__dict__["_file_path"] = os.path.join(pref_dir, "meldrc.ini") try: config_file = open(self._file_path, "r") try: self._parser.readfp(config_file) finally: config_file.close() except IOError: # One-way move of old preferences old_path = os.path.join(os.path.expanduser("~"), ".meld") old_file_path = os.path.join(old_path, "meldrc.ini") if os.path.exists(old_file_path): try: config_file = open(old_file_path, "r") try: self._parser.readfp(config_file) finally: config_file.close() new_config_file = open(self._file_path, "w") try: self._parser.write(new_config_file) finally: new_config_file.close() except IOError: pass for key, value in self._prefs.items(): if self._parser.has_option("DEFAULT", key): value.current = self._type_mappings[value.type]("DEFAULT", key)
def __init__(self, history_dir="history"): config_home = glib.get_user_config_dir() self.history_dir = os.path.join(config_home, 'fltsim', history_dir) if not os.path.exists(self.history_dir): os.makedirs(self.history_dir) self.documents = {} self.current_date = datetime.datetime.now().date() self.dates = []
def load_config(): path = os.path.join(glib.get_user_config_dir(), 'kobita') if not os.path.isdir(path): os.mkdir(path) return None path = os.path.join(path, 'config') if not os.path.isfile(path): return None with open(path) as f: return json.load(f)
def __init__(self, tab): """ Initialize the ad blocker. """ self._path = '%s/webbrowser' % get_user_config_dir() self._ad_pat = None self._tab = tab self._log_func = tab.print_message self._enabled = True self._file_watch = tab._file_watcher
def get_gimp_prefix(self): from lib import helpers homepath = helpers.expanduser_unicode(u'~') if sys.platform == 'win32': # using patched win32 glib using correct CSIDL_LOCAL_APPDATA import glib confpath = os.path.join(glib.get_user_config_dir().decode('utf-8'),'gimp-2.6') elif homepath == '~': confpath = os.path.join(prefix, 'UserData') else: confpath = os.path.join(homepath, '.gimp-2.6') return confpath
def load_config (): '''Check that config file exists, create it if it doesn't, and load it. ''' d = os.path.join (glib.get_user_config_dir (), 'xmarksthespot') f = os.path.join (d, 'config.txt') if not os.path.exists (d): os.makedirs (d) if not os.path.exists (f): handle = open (f, 'w') try: name = os.getlogin ().capitalize () except: # We're on Windows, or something else is wrong. # Don't bother, just use a default. name = 'Monty Python' handle.write ('''\ # Configuration for xmarksthespot. # Empty lines and lines starting with # are ignored. # The first words is the configuration option key. The rest of the line is the value. # Default settings when building a cartridge. # These are also used when playing from non-gwc source. Id 0 URL about:blank Device PocketPC PlayerName %s CompletionCode completion-code # Env settings. These are accessible to lua. env_Platform xmarksthespot env_CartFolder /whatever env_SyncFolder /whatever env_LogFolder /whatever env_PathSep / env_DeviceID Python env_Version 2.11-compatible env_Downloaded 0 # If the following are empty, they are filled automatically. env_CartFilename env_Device ''' % name) handle.close () ret = {} for l in open (f).readlines (): l = l.strip ().split (None, 1) if len (l) == 0 or l[0].startswith ('#'): continue ret[l[0]] = l[1] if len (l) > 1 else None override = os.getenv ('XMTT_' + l[0].upper ().replace ('-', '_')) if override is not None: ret[l[1]] = override if override != '' else None return ret
def __init_network_config(self): if not os.path.exists(glib.get_user_config_dir()): os.mkdir(glib.get_user_config_dir()) self.config_file = os.path.join(glib.get_user_config_dir(), "network.conf") if not os.path.exists(self.config_file): open(self.config_file, "w").close() self.cf = ConfigParser.RawConfigParser() self.cf.optionxform = str self.cf.read(self.config_file) if "conn_priority" not in self.cf.sections(): self.cf.add_section("conn_priority") if WIRE_SECTION not in self.cf.sections(): self.cf.add_section(WIRE_SECTION) if WIRELESS_SECTION not in self.cf.sections(): self.cf.add_section(WIRELESS_SECTION) max_prio = 0 for conn_uuid in map(lambda x: x.settings_dict["connection"]["uuid"], self.list_connections()): if conn_uuid not in self.cf.options("conn_priority"): self.cf.set("conn_priority", conn_uuid, 0) if self.cf.getint("conn_priority", conn_uuid) > max_prio: max_prio = self.cf.getint("conn_priority", conn_uuid) if max_prio >= 1024: for conn_uuid in self.cf.options("conn_priority"): self.cf.set( "conn_priority", conn_uuid, int(self.cf.getint("conn_priority", conn_uuid) / 2)) self.cf.write(open(self.config_file, "w"))
def __init__(self, tab): """ Initialize the movie catcher. """ self._log_func = tab.print_message self._send_download = tab._send_download self._movie_pat = None self._vid_ext_pat = None self._enabled = True self._path = '%s/webbrowser' % get_user_config_dir() self._tab = tab
def get_gimp_prefix(self): from lib import helpers homepath = helpers.expanduser_unicode(u"~") if sys.platform == "win32": # using patched win32 glib using correct CSIDL_LOCAL_APPDATA import glib confpath = os.path.join(glib.get_user_config_dir().decode("utf-8"), "gimp-2.6") elif homepath == "~": confpath = os.path.join(prefix, "UserData") else: confpath = os.path.join(homepath, ".gimp-2.6") return confpath
def save_settings(self): config_dir = os.path.join(glib.get_user_config_dir(), "procman-sheriff") if not os.path.exists(config_dir): os.makedirs(config_dir) self.config_fname = os.path.join(config_dir, "config") d = {} self.cmds_tv.save_settings(d) self.cmd_console.save_settings(d) self.hosts_tv.save_settings(d) try: pickle.dump(d, open(self.config_fname, "w")) except Exception, err: print err
def SyncerThread(queue, addressbook): while True: item = queue.get() if item == 'sync_local_changes': try: my_settings = settings.get_settings() if my_settings['resource'] != '': sqlConn = sqlite3.connect(os.path.join(glib.get_user_config_dir(), 'pyaddressbook', 'addressbook.db')) cdav = carddav2.PyCardDAV(verify=my_settings['verify'], resource=my_settings['resource'], user=my_settings['user'], passwd=my_settings['passwd'], write_support=True) sync_local_changes(cdav, sqlConn, addressbook) sqlConn.commit() sqlConn.close() except: print("Error occured while trying to sync changes. Exception details:\n", sys.exc_info()) if item == 'full_sync': try: print("Starting a full sync") full_sync(addressbook) except: print("Error occured while trying to do a full sync. Exception details:\n", sys.exc_info()) queue.task_done() if item == "STOP": break
def __init__(self): self._gps = gps.gps(mode=gps.WATCH_ENABLE|gps.WATCH_JSON|gps.WATCH_NEWSTYLE) self.wpList = gtk.TreeStore(object) self.settingsdir = os.path.join(glib.get_user_config_dir(),"lotse") if not os.path.exists(self.settingsdir): os.makedirs(self.settingsdir) self.load_persistent() self._position = Position() # Should not be none to not cause invalid calls self._sleek_position = Position() self._target = Waypoint() self.position_changed = Event() self.target_changed = Event() self.hanged_up = Event() self.update(None, None) #gobject.timeout_add(400, self.update) gobject.io_add_watch(self._gps.sock, gobject.IO_IN, self.update) gobject.io_add_watch(self._gps.sock, gobject.IO_ERR, self.handle_hangup) gobject.io_add_watch(self._gps.sock, gobject.IO_HUP, self.handle_hangup)
from setroubleshoot.util import * from setroubleshoot.html_util import html_to_text import re import dbus import slip.dbus.service from slip.dbus import polkit import report import report.io import report.io.GTKIO import report.accountmanager import gio GLADE_DIRECTORY = "/usr/share/setroubleshoot/gui/" OLD_PATH = os.environ['HOME'] + "/.setroubleshoot" PREF_PATH = glib.get_user_config_dir() + "/sealert.conf" UPDATE_PROGRAM = "/usr/bin/gpk-update-viewer" dict = { "file": "text-x-generic", "dir":"inode/directory", "chr_file":"inode/chardevice", "blk_file":"inode/blockdevice", "lnk_file":"inode/symlink", "sock_file":"inode/socket", "executable":"application/x-executable", "socket":"text-x-generic", "capability":"text-x-generic", "process":"text-x-generic", "*":"text-x-generic", }
import glib import gobject import pykka from mopidy import config as config_lib, exceptions from mopidy.audio import Audio from mopidy.core import Core from mopidy.internal import deps, process, timer, versioning logger = logging.getLogger(__name__) _default_config = [] for base in glib.get_system_config_dirs() + (glib.get_user_config_dir(),): _default_config.append(os.path.join(base, b'mopidy', b'mopidy.conf')) DEFAULT_CONFIG = b':'.join(_default_config) def config_files_type(value): return value.split(b':') def config_override_type(value): try: section, remainder = value.split(b'/', 1) key, value = remainder.split(b'=', 1) return (section.strip(), key.strip(), value.strip()) except ValueError: raise argparse.ArgumentTypeError(
import logging import os import re # pylint: disable = W0402 import string # pylint: enable = W0402 import sys import urllib import glib logger = logging.getLogger('mopidy.utils.path') XDG_CACHE_DIR = glib.get_user_cache_dir().decode('utf-8') XDG_CONFIG_DIR = glib.get_user_config_dir().decode('utf-8') XDG_DATA_DIR = glib.get_user_data_dir().decode('utf-8') XDG_MUSIC_DIR = glib.get_user_special_dir(glib.USER_DIRECTORY_MUSIC) if XDG_MUSIC_DIR: XDG_MUSIC_DIR = XDG_MUSIC_DIR.decode('utf-8') XDG_DIRS = { 'XDG_CACHE_DIR': XDG_CACHE_DIR, 'XDG_CONFIG_DIR': XDG_CONFIG_DIR, 'XDG_DATA_DIR': XDG_DATA_DIR, 'XDG_MUSIC_DIR': XDG_MUSIC_DIR, } DATA_PATH = os.path.join(unicode(XDG_DATA_DIR), 'mopidy') SETTINGS_PATH = os.path.join(unicode(XDG_CONFIG_DIR), 'mopidy') SETTINGS_FILE = os.path.join(unicode(SETTINGS_PATH), 'settings.py')
# -*- coding: UTF-8 -*- import os import pickle import json import gtk import sys import glob import shutil import glib PROGRAM_NAME = 'hotot' EXT_DIR_NAME = 'ext' CONF_DIR = os.path.join(glib.get_user_config_dir(), PROGRAM_NAME) DB_DIR = os.path.join(CONF_DIR, 'db') CACHE_DIR = os.path.join(glib.get_user_cache_dir(), PROGRAM_NAME) AVATAR_CACHE_DIR = os.path.join(CACHE_DIR, 'avatar') DATA_DIRS = [] DATA_BASE_DIRS = [ '/usr/local/share' , '/usr/share' , glib.get_user_data_dir() ] DATA_DIRS += [os.path.join(d, PROGRAM_NAME) for d in DATA_BASE_DIRS] DATA_DIRS.append(os.path.abspath('./data')) TEMPLATE = 'index.html'
def getUserConfigPrefix (): return join(get_user_config_dir(), pychess)
def __init__(self, lcm_obj): self.lcm_obj = lcm_obj self.cmds_update_scheduled = False self.config_filename = None self.script_done_action = None # deputy spawned by the sheriff self.spawned_deputy = None # create sheriff and subscribe to events self.sheriff = Sheriff(self.lcm_obj) self.sheriff.add_listener(self) self.script_manager = ScriptManager(self.sheriff) self.script_manager.add_listener(self) # update very soon gobject.timeout_add(100, lambda *s: self.deputies_ts.update() and False) gobject.timeout_add(100, lambda *s: self._schedule_cmds_update() and False) # and then periodically gobject.timeout_add(1000, self._check_spawned_deputy) gobject.timeout_add(1000, lambda *s: self._schedule_cmds_update() or True) # setup GUI self.builder = gtk.Builder() self.builder.add_from_file(find_procman_glade()) self.builder.connect_signals(self) self.window = self.builder.get_object("main_window") self.cmds_ts = cm.SheriffCommandModel(self.sheriff) self.cmds_tv = ctv.SheriffCommandTreeView(self.sheriff, self.script_manager, self.cmds_ts) # load save menu self.load_cfg_mi = self.builder.get_object("load_cfg_mi") self.save_cfg_mi = self.builder.get_object("save_cfg_mi") self.load_dlg = None self.save_dlg = None self.load_save_dir = None self.cfg_to_load = None if BUILD_PREFIX and os.path.exists("%s/data/procman" % BUILD_PREFIX): self.load_save_dir = "%s/data/procman" % BUILD_PREFIX # options menu self.is_observer_cmi = self.builder.get_object("is_observer_cmi") self.spawn_deputy_mi = self.builder.get_object("spawn_deputy_mi") self.terminate_spawned_deputy_mi = self.builder.get_object( "terminate_spawned_deputy_mi") self.procman_deputy_cmd = find_procman_deputy_cmd() if not self.procman_deputy_cmd: sys.stderr.write( "Can't find procman-deputy. Spawn Deputy disabled") self.spawn_deputy_mi.set_sensitive(False) # commands menu self.start_cmd_mi = self.builder.get_object("start_cmd_mi") self.stop_cmd_mi = self.builder.get_object("stop_cmd_mi") self.restart_cmd_mi = self.builder.get_object("restart_cmd_mi") self.remove_cmd_mi = self.builder.get_object("remove_cmd_mi") self.edit_cmd_mi = self.builder.get_object("edit_cmd_mi") self.new_cmd_mi = self.builder.get_object("new_cmd_mi") # scripts menu self.abort_script_mi = self.builder.get_object("abort_script_mi") self.edit_script_mi = self.builder.get_object("edit_script_mi") self.remove_script_mi = self.builder.get_object("remove_script_mi") self.scripts_menu = self.builder.get_object("scripts_menu") self.edit_scripts_menu = self.builder.get_object("edit_scripts_menu") self.remove_scripts_menu = self.builder.get_object( "remove_scripts_menu") vpane = self.builder.get_object("vpaned") sw = gtk.ScrolledWindow() sw.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC) hpane = self.builder.get_object("hpaned") hpane.pack1(sw, resize=True) sw.add(self.cmds_tv) cmds_sel = self.cmds_tv.get_selection() cmds_sel.connect("changed", self._on_cmds_selection_changed) # create a checkable item in the View menu for each column to toggle # its visibility in the treeview view_menu = self.builder.get_object("view_menu") for col in self.cmds_tv.get_columns(): name = col.get_title() col_cmi = gtk.CheckMenuItem(name) col_cmi.set_active(col.get_visible()) def on_activate(cmi, col_): should_be_visible = cmi.get_active() if col_.get_visible() != should_be_visible: col_.set_visible(should_be_visible) if col_ == self.cmds_tv.columns[0]: self.cmds_ts.set_populate_exec_with_group_name( not should_be_visible) self.cmds_ts.repopulate() def on_visibility_changed(col_, param, cmi_): is_visible = col_.get_visible() if is_visible != cmi_.get_active(): cmi_.set_active(is_visible) col_cmi.connect("activate", on_activate, col) col.connect("notify::visible", on_visibility_changed, col_cmi) view_menu.append(col_cmi) # setup the deputies treeview self.deputies_ts = ht.DeputyModel(self.sheriff) self.deputies_tv = ht.DeputyTreeView(self.sheriff, self.deputies_ts) sw = gtk.ScrolledWindow() sw.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC) hpane.pack2(sw, resize=False) sw.add(self.deputies_tv) gobject.timeout_add(1000, lambda *s: self.deputies_ts.update() or True) # stdout textview self.cmd_console = cc.SheriffCommandConsole(self.sheriff, self.lcm_obj) vpane.add2(self.cmd_console) # status bar self.statusbar = self.builder.get_object("statusbar") self.statusbar_context_script = self.statusbar.get_context_id("script") self.statusbar_context_main = self.statusbar.get_context_id("main") self.statusbar_context_script_msg = None config_dir = os.path.join(glib.get_user_config_dir(), "procman-sheriff") if not os.path.exists(config_dir): os.makedirs(config_dir) self.config_fname = os.path.join(config_dir, "config") self.load_settings() self.window.show_all()
import glib import gobject import pykka from mopidy import config as config_lib, exceptions from mopidy.audio import Audio from mopidy.core import Core from mopidy.internal import deps, process, timer, versioning logger = logging.getLogger(__name__) _default_config = [] for base in glib.get_system_config_dirs() + (glib.get_user_config_dir(), ): _default_config.append(os.path.join(base, b'mopidy', b'mopidy.conf')) DEFAULT_CONFIG = b':'.join(_default_config) def config_files_type(value): return value.split(b':') def config_override_type(value): try: section, remainder = value.split(b'/', 1) key, value = remainder.split(b'=', 1) return (section.strip(), key.strip(), value.strip()) except ValueError: raise argparse.ArgumentTypeError(
'DATA_DIR', 'init_locale', ) import os import glib import gettext def applize(package): return ' '.join([a.capitalize() for a in package.split('-')]) PACKAGE = 'ubuntu-tweak' VERSION = '0.5.1' DATA_DIR = '/usr/share/ubuntu-tweak/' APP = applize(PACKAGE) CONFIG_ROOT = os.path.join(glib.get_user_config_dir(), 'ubuntu-tweak') if not os.path.exists(CONFIG_ROOT): os.mkdir(CONFIG_ROOT) LANG = os.getenv('LANG').split('.')[0].lower().replace('_','-') if not __file__.startswith('/usr'): datadir = os.path.dirname(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) DATA_DIR = os.path.join(datadir, 'data') def init_locale(): global INIT try: INIT except:
def get_user_config_dir(): dirs = os.path.join(glib.get_user_config_dir(), "autostart") if not os.path.exists(dirs): os.mkdir(dirs) return dirs
# You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import os import glib import shutil PROGRAM_NAME = "deepin-individuation" homedir = os.path.expanduser("~") lastdir = homedir data_home = glib.get_user_data_dir() data_home = os.path.join(data_home, PROGRAM_NAME) config_home = glib.get_user_config_dir() config_home = os.path.join(config_home, PROGRAM_NAME) cache_home = glib.get_user_cache_dir() cache_home = os.path.join(cache_home, PROGRAM_NAME) data_dirs = os.getenv("XDG_DATA_DIRS") if data_dirs == None: data_dirs = "/usr/local/share/:/usr/share/" data_dirs = [os.path.join(d, PROGRAM_NAME) for d in data_dirs.split(":")] config_dirs = os.getenv("XDG_CONFIG_DIRS") if config_dirs == None: config_dirs = "/etc/xdg" config_dirs = [os.path.join(d, PROGRAM_NAME) for d in config_dirs.split(":")]
import platform import sys if not (2, 6) <= sys.version_info < (3,): sys.exit(u'Mopidy requires Python >= 2.6, < 3') import glib import os from subprocess import PIPE, Popen VERSION = (0, 6, 0) DATA_PATH = os.path.join(glib.get_user_data_dir(), 'mopidy') CACHE_PATH = os.path.join(glib.get_user_cache_dir(), 'mopidy') SETTINGS_PATH = os.path.join(glib.get_user_config_dir(), 'mopidy') SETTINGS_FILE = os.path.join(SETTINGS_PATH, 'settings.py') def get_version(): try: return get_git_version() except EnvironmentError: return get_plain_version() def get_git_version(): process = Popen(['git', 'describe'], stdout=PIPE, stderr=PIPE) if process.wait() != 0: raise EnvironmentError('Execution of "git describe" failed') version = process.stdout.read().strip() if version.startswith('v'): version = version[1:] return version
class ClipboardProtector(object): PASTIE_DATA_DIR = os.path.join(glib.get_user_data_dir(), 'pastie/') HISTORY_FILE = os.path.join(PASTIE_DATA_DIR, 'clipboard_history') PASTIE_CONFIG_DIR = os.path.join(glib.get_user_config_dir(), 'pastie/') PASTIE_ICON = os.path.join(PASTIE_CONFIG_DIR, 'pastie.svg') def __init__(self): # try to load custom icon from ~/.pastie/ pastieDir = os.path.join(os.path.expanduser('~'), '.pastie/') pastieIcon = os.path.expanduser('~/.pastie/pastie.svg') if os.path.isfile(pastieIcon) == True: self.indicator = appindicator.Indicator( "pastie", "pastie", appindicator.CATEGORY_OTHER, pastieDir) else: self.indicator = appindicator.Indicator( "pastie", "gtk-paste", appindicator.CATEGORY_OTHER) # set the indicator as active (pastie must be always shown) self.indicator.set_status(appindicator.STATUS_ACTIVE) # get the clipboard gdk atom self.clipboard = gtk.clipboard_get(gtk.gdk.SELECTION_CLIPBOARD) self.primary = gtk.clipboard_get(gtk.gdk.SELECTION_PRIMARY) # we use this to check if clipboard contents changed on special cases self.specials_text = "" self.primary_text = "" # create the history data strucure self.history = history.HistoryMenuItemCollector() # the menu will be updated when the "item-lenght-adjusted" signal in the history object is emitted self.history.connect("length-adjusted", self.update_menu) # ... and when data changes self.history.connect("data-change", self.update_menu) # load history if existent self.history.set_payload(self.recover_history()) # pastie might have been loaded after some contents were added to the X clipboard. # we check if ther's any. self.check() # select the first item in the history. if len(self.history) > 0: self.history[0].set_as_current() # set the gconf_client self.gconf_client = prefs.PrefsGConfClient() # register gconf preferences changes callback functions self.gconf_client.notify_add('show_quit_on_menu', self.update_menu) self.gconf_client.notify_add('show_preferences_on_menu', self.update_menu) self.gconf_client.notify_add('item_length', self.update_menu) self.gconf_client.notify_add('history_size', self.history.adjust_maxlen) self.gconf_client.notify_add('use_primary', self.toggle_primary) self.gconf_client.notify_add('sel_dialog_key', self.change_s_dialog_key) self.gconf_client.notify_add('prefs_dialog_key', self.change_prefs_dialog_key) # check clipboard changes on owner-change event self.clipboard.connect("owner-change", self.check) self.toggle_primary() # run an auxiloary loop for special cases (e.g., gvim) gobject.timeout_add(500, self.check_specials) # create the selection dialog and set the keyboard shortcut for it self.s_dialog = seldiag.SelectionDialog(self) self.prev_sel_dialog_key = prefs.get_sel_dialog_key() self.change_s_dialog_key() # set the preferences dialog's keyboard shortcut self.prev_prefs_dialog_key = prefs.get_prefs_dialog_key() self.change_prefs_dialog_key() # activate/deactivate primary selection def toggle_primary(self, a=None, b=None, c=None, d=None): if prefs.get_use_primary() == True: gobject.timeout_add(500, self.check_primary) # change the binding of the selection dialog def change_s_dialog_key(self, gconfclient=None, gconfentry=None, gconfvalue=None, d=None): try: keybinder.unbind(self.prev_sel_dialog_key) except: pass keybinder.bind(prefs.get_sel_dialog_key(), lambda: self.s_dialog.show()) self.prev_sel_dialog_key = prefs.get_sel_dialog_key() # change the binding of the preferences dialog def change_prefs_dialog_key(self, gconfclient=None, gconfentry=None, gconfvalue=None, d=None): try: keybinder.unbind(self.prev_prefs_dialog_key) except: pass keybinder.bind(prefs.get_prefs_dialog_key(), lambda: prefs.PreferencesDialog()) self.prev_prefs_dialog_key = prefs.get_prefs_dialog_key() # returns a list of history items from a XML file. def recover_history(self, input_file=HISTORY_FILE): tmp_list = [] try: history_tree = tree.parse(input_file) except IOError: # file doesn't exist return tmp_list except ExpatError: # file is empty or malformed return tmp_list except ParseError: # file is empty (not element found) return tmp_list for item in history_tree.findall("item"): if item.get("type") == "text": history_item = history.TextHistoryMenuItem(item.text) elif item.get("type") == "file": history_item = history.FileHistoryMenuItem(item.text) elif item.get("type") == "image": data = base64.b64decode(item.text) has_alpha = bool(item.get("has_alpha")) width = int(item.get("width")) height = int(item.get("height")) rowstride = int(item.get("rowstride")) pixbuf = gtk.gdk.pixbuf_new_from_data(data, gtk.gdk.COLORSPACE_RGB, \ has_alpha, 8, width, height, rowstride) history_item = history.ImageHistoryMenuItem(pixbuf) else: history_item = history.TextHistoryMenuItem(item.text) tmp_list.append(history_item) return tmp_list # saves the clipboard history to a XML file. called on program termination. def save_history(self, output_file=HISTORY_FILE): history_tree_root = tree.Element("clipboard") for item in self.history.data: history_tree_item = tree.SubElement(history_tree_root, "item") history_tree_item.set("id", hashlib.md5(item.payload).hexdigest()) if isinstance(item, history.TextHistoryMenuItem): item_type = "text" elif isinstance(item, history.FileHistoryMenuItem): item_type = "file" elif isinstance(item, history.ImageHistoryMenuItem): item_type = "image" else: item_type = "text" history_tree_item.set("type", item_type) if item_type == "image": history_tree_item.set("has_alpha", str(item.pixbuf.props.has_alpha)) history_tree_item.set("width", str(item.pixbuf.props.width)) history_tree_item.set("height", str(item.pixbuf.props.height)) history_tree_item.set("rowstride", str(item.pixbuf.props.rowstride)) history_tree_item.text = base64.b64encode(item.payload) else: history_tree_item.text = item.payload history_tree = tree.ElementTree(history_tree_root) history_tree.write(output_file, "UTF-8") # erase the clipboard history. the current contents of the clipoard will remain. def clean_history(self, event=None): self.history.empty(full=True) self.check() self.save_history() self.update_menu() def delete_current(self, event=None): self.clipboard.clear() self.history.delete_top() self.save_history() self.update_menu() def replace_current(self, data, event=None): self.clipboard.clear() self.history.replace_top(history.TextHistoryMenuItem(data)) self.save_history() self.update_menu() # check clipboard contents. def check(self, clipboard=None, event=None): if not self.clipboard.wait_for_targets(): # some programs (JEdit) don't set the targets, but still set the text... no_targetted_text = self.clipboard.wait_for_text() if no_targetted_text != None: # ... if that's the case, we add it self.history.add( history.TextHistoryMenuItem(no_targetted_text)) self.save_history() else: if self.history[0] != None: self.history[0].set_as_current() elif self.clipboard.wait_is_text_available(): clipboard_tmp = self.clipboard.wait_for_text() if clipboard_tmp not in ("", None): if 'PASS_TIMEOUT' in self.clipboard.wait_for_targets(): timeout = int( self.clipboard.wait_for_contents( 'PASS_TIMEOUT').data) * 1000 self.history.add( history.PasswordHistoryMenuItem(clipboard_tmp)) gobject.timeout_add(timeout, self.delete_current) elif self.clipboard.wait_is_uris_available(): self.history.add( history.FileHistoryMenuItem(clipboard_tmp)) else: self.history.add( history.TextHistoryMenuItem(clipboard_tmp)) self.save_history() elif self.clipboard.wait_is_image_available(): clipboard_contents = self.clipboard.wait_for_image() self.history.add(history.ImageHistoryMenuItem(clipboard_contents)) self.save_history() def check_specials(self): targets = self.clipboard.wait_for_targets() # if there are no targets, we simply return True if targets != None: # vim doesn't set the timestamp target, so we have to check for its changes. if '_VIM_TEXT' in targets: clipboard_tmp = self.clipboard.wait_for_text() if clipboard_tmp not in ( "", None) and clipboard_tmp != self.specials_text: self.history.add( history.TextHistoryMenuItem(clipboard_tmp)) self.specials_text = clipboard_tmp self.save_history() return True def check_primary(self): if prefs.get_use_primary() == True: mouse_modifiers = gtk.gdk.Display( None).get_pointer()[3].value_names if 'GDK_BUTTON1_MASK' not in mouse_modifiers: if 'GDK_SHIFT_MASK' not in mouse_modifiers: primary_targets = self.primary.wait_for_targets() if primary_targets != None: primary_tmp = self.primary.wait_for_text() if primary_tmp not in ( "", None) and primary_tmp != self.primary_text: self.history.add( history.PrimaryHistoryMenuItem(primary_tmp)) if prefs.get_synch_primary() == True: gtk.clipboard_get().set_text(primary_tmp) gtk.clipboard_get().store() self.primary_specials_text = primary_tmp self.save_history() return True else: return False def create_edit_dialog(self, event): edit_dialog = edit.ClipboardEditorDialog(self) def create_prefs_dialog(self, event): prefs_dialog = prefs.PreferencesDialog() # create and show the menu def update_menu(self, gconfclient=None, gconfentry=None, gconfvalue=None, d=None): menu = gtk.Menu() if len(self.history) > 0: for i in self.history: label = i.get_label() item = gtk.MenuItem(label, use_underline=False) item.connect("activate", i.set_as_current) menu.append(item) menu.append(gtk.SeparatorMenuItem()) if isinstance(self.history[0], history.TextHistoryMenuItem): edit_clipboard_menu = gtk.MenuItem(_("Edit clipboard")) edit_clipboard_menu.connect("activate", self.create_edit_dialog) menu.append(edit_clipboard_menu) if isinstance(self.history[0], history.ImageHistoryMenuItem) or \ isinstance(self.history[0], history.FileHistoryMenuItem): delete_current_menu = gtk.MenuItem(_("Remove current")) delete_current_menu.connect("activate", self.delete_current) menu.append(delete_current_menu) clean_menu = gtk.MenuItem(_("Clean history")) clean_menu.connect("activate", self.clean_history) menu.append(clean_menu) else: nothing_to_show_menu = gtk.MenuItem( _("Nothing in history or clipboards")) menu.append(nothing_to_show_menu) if prefs.get_show_prefs() == True: prefs_menu = gtk.MenuItem(_("Preferences") + u'\u2026') prefs_menu.connect("activate", self.create_prefs_dialog) menu.append(prefs_menu) if prefs.get_show_quit() == True: quit_menu = gtk.MenuItem(_("Quit")) quit_menu.connect("activate", lambda q: gtk.main_quit()) menu.append(quit_menu) menu.show_all() # attach this menu to the indicator self.indicator.set_menu(menu)
def get_paths(): join = os.path.join lib_shared='share/mypaint/' # note: some distros use lib64 instead, they have to edit this... lib_compiled='lib/mypaint/' # convert sys.argv to a list of unicode objects # (actually convertig sys.argv confuses gtk, thus we add a new variable) if sys.platform == 'win32': sys.argv_unicode = win32_unicode_argv() else: sys.argv_unicode = [s.decode(sys.getfilesystemencoding()) for s in sys.argv] scriptdir=os.path.dirname(sys.argv_unicode[0]) # this script is installed as $prefix/bin. We just need $prefix to continue. #pwd=os.getcwd() # why???? #dir_install=os.path.normpath(join(pwd,scriptdir)) # why???? dir_install=scriptdir # same, except maybe if scriptdir is relative... if os.path.basename(dir_install) == 'bin': prefix=os.path.dirname(dir_install) assert isinstance(prefix, unicode) libpath=join(prefix, lib_shared) libpath_compiled = join(prefix, lib_compiled) sys.path.insert(0, libpath) sys.path.insert(0, libpath_compiled) localepath = join(prefix, 'share/locale') localepath_brushlib = localepath extradata = join(prefix, 'share') elif sys.platform == 'win32': prefix=None # this is py2exe point of view, all executables in root of installdir # all path must be normalized to absolute path libpath = os.path.abspath(os.path.dirname(os.path.realpath(sys.argv_unicode[0]))) sys.path.insert(0, libpath) localepath = join(libpath, 'share/locale') localepath_brushlib = localepath extradata = join(libpath, 'share') else: # we are not installed prefix = None libpath = u'.' extradata = u'desktop' localepath = 'po' localepath_brushlib = 'brushlib/po' assert isinstance(libpath, unicode) try: # just for a nice error message from lib import mypaintlib except ImportError: print print "We are not correctly installed or compiled!" print 'script: "%s"' % sys.argv[0] if prefix: print 'deduced prefix: "%s"' % prefix print 'lib_shared: "%s"' % libpath print 'lib_compiled: "%s"' % libpath_compiled print raise # Ensure that pyGTK compatibility is setup before anything else from gui import pygtkcompat datapath = libpath if not os.path.isdir(join(datapath, 'brushes')): print 'Default brush collection not found! It should have been here:' print datapath raise sys.exit(1) from lib import helpers homepath = helpers.expanduser_unicode(u'~') if sys.platform == 'win32': # using patched win32 glib using correct CSIDL_LOCAL_APPDATA import glib confpath = os.path.join(glib.get_user_config_dir().decode('utf-8'),'mypaint') elif homepath == '~': confpath = join(prefix, 'UserData') else: confpath = join(homepath, '.mypaint/') assert isinstance(datapath, unicode) assert isinstance(confpath, unicode) assert isinstance(extradata, unicode) return datapath, extradata, confpath, localepath, localepath_brushlib
def main(datapath, extradata, oldstyle_confpath=None, version=MYPAINT_VERSION): """Run MyPaint with `sys.argv`, called from the "mypaint" script. :param datapath: The app's read-only data location. Where MyPaint should find its static data, e.g. UI definition XML, backgrounds, and brush definitions. $PREFIX/share/mypaint is usual. :param extradata: Extra search root for finding icons. Where to find the defaults for MyPaint's themeable UI icons. This will be used in addition to $XDG_DATA_DIRS for the purposes of icon lookup. Normally it's $PREFIX/share, to support unusual installations outside the usual locations. It should contain an icons/ subdirectory. :param oldstyle_confpath: Old-style merged config folder. If specified, all user-specific data that MyPaint writes is written here. If omitted, this data will be stored under the basedirs returned by glib.get_user_config_dir() for settings, and by glib.get_user_data_dir() for brushes and backgrounds. On Windows, these will be the same location. On POSIX systems, $HOME/.config/mypaint and $HOME/.local/share/mypaint are a typical division. :param version: full version string for display in the about box. The oldstyle_confpath parameter can also be overridden by command-line parameters. To support legacy MyPaint configuration dirs, call with oldstyle_confpath set to the expansion of ~/.mypaint. """ # Default logfile basename. # If it's relative, it's resolved relative to the user config path. default_logfile = None if sys.platform == 'win32': # http://gna.org/bugs/?17999 default_logfile = "mypaint_error.log" # Parse command line parser = OptionParser('usage: %prog [options] [FILE]') parser.add_option('-c', '--config', metavar='DIR', default=oldstyle_confpath, help='use old-style merged config directory DIR, e.g. ~/.mypaint') parser.add_option('-l', '--logfile', metavar='FILE', default=default_logfile, help='append Python stdout and stderr to FILE (rel. to config location)') parser.add_option('-t', '--trace', action="store_true", help='print all executed Python statements') parser.add_option('-f', '--fullscreen', action="store_true", help='start in fullscreen mode') parser.add_option("-V", '--version', action="store_true", help='print version information and exit') options, args = parser.parse_args(sys.argv_unicode[1:]) # XDG support for new users on POSIX platforms if options.config is None: encoding = 'utf-8' appsubdir = u"mypaint" basedir = glib.get_user_data_dir().decode(encoding) userdatapath = os.path.join(basedir, appsubdir) basedir = glib.get_user_config_dir().decode(encoding) userconfpath = os.path.join(basedir, appsubdir) else: userdatapath = options.config userconfpath = options.config # Log to the specified location # Prepend the data path if the user gave a relative location. if options.logfile: logfilepath = os.path.join(userdatapath, options.logfile) logdirpath, logfilebasename = os.path.split(logfilepath) if not os.path.isdir(logdirpath): os.makedirs(logdirpath) print 'Python prints are redirected to %s after this one.' % logfilepath sys.stdout = sys.stderr = open(logfilepath, 'a', 1) print '--- mypaint log %s ---' % time.strftime('%Y-%m-%d %H:%M:%S') if options.version: print "MyPaint version %s" % (version,) sys.exit(0) def run(): print 'DEBUG: user_datapath:', userdatapath print 'DEBUG: user_confpath:', userconfpath app = application.Application(args, app_datapath=datapath, app_extradatapath=extradata, user_datapath=userdatapath, user_confpath=userconfpath, version=version, fullscreen=options.fullscreen) # Recent gtk versions don't allow changing those menu shortcuts by # default. <rant>Sigh. This very useful feature used to be the # default behaviour even in the GIMP some time ago. I guess # assigning a keyboard shortcut without a complicated dialog # clicking marathon must have totally upset the people coming from # windows.</rant> gtksettings = pygtkcompat.gtk.settings_get_default() gtksettings.set_property('gtk-can-change-accels', True) import gtkexcepthook func = app.filehandler.confirm_destructive_action gtkexcepthook.quit_confirmation_func = func gtk.main() if options.trace: import trace tracer = trace.Trace(trace=1, count=0) tracer.runfunc(run) else: run()
import xdg.BaseDirectory sys.path.insert(0, os.path.abspath(os.path.dirname(__file__))) from Core import Core VERSION = '0.0.1' ROOT_DIR = os.path.abspath(os.path.join(__file__, '..', '..')) DATA_DIR = xdg.BaseDirectory.xdg_data_dirs DATA_DIR = [os.path.join(dir, 'sucker') for dir in DATA_DIR] DATA_DIR.insert(0, os.path.abspath(os.path.join(ROOT_DIR, 'data'))) def find_data(name): for dir in DATA_DIR: full_address = os.path.join(dir, name) if os.path.exists(full_address): return full_address CONFIG_DIR = os.path.join(glib.get_user_config_dir(), 'sucker') if not os.path.isdir(CONFIG_DIR): os.makedirs(CONFIG_DIR) PLUGIN_DIRS = xdg.BaseDirectory.xdg_data_dirs PLUGIN_DIRS = [os.path.join(dir, 'sucker/plugins') for dir in PLUGIN_DIRS] PLUGIN_DIRS.append(os.path.join(CONFIG_DIR, 'plugins')) PLUGIN_DIRS.append(os.path.join(ROOT_DIR, 'sucker/plugins')) PLUGIN_DIRS = [dir for dir in PLUGIN_DIRS if os.path.isdir(dir)]
if (isinstance(pykka.__version__, basestring) and not SV('1.0') <= SV(pykka.__version__) < SV('2.0')): sys.exit( u'Mopidy requires Pykka >= 1.0, < 2, but found %s' % pykka.__version__) import os import platform from subprocess import PIPE, Popen import glib __version__ = '0.8.1' DATA_PATH = os.path.join(str(glib.get_user_data_dir()), 'mopidy') CACHE_PATH = os.path.join(str(glib.get_user_cache_dir()), 'mopidy') SETTINGS_PATH = os.path.join(str(glib.get_user_config_dir()), 'mopidy') SETTINGS_FILE = os.path.join(SETTINGS_PATH, 'settings.py') def get_version(): try: return get_git_version() except EnvironmentError: return __version__ def get_git_version(): process = Popen(['git', 'describe'], stdout=PIPE, stderr=PIPE) if process.wait() != 0: raise EnvironmentError('Execution of "git describe" failed') version = process.stdout.read().strip() if version.startswith('v'): version = version[1:]
class GrammalecteConfig(DictConfig): """ A Grammalecte configuration for a given document. This configuration inherits from user and system configuration, if available. :Example: >>> config = GrammalecteConfig() >>> config.get_value(GrammalecteConfig.AUTO_ANALYZE_TIMER) 500 >>> config.set_value("top/sub", ["zero", {"1st": "1", "other": "yes"}]) >>> config.get_value("top/sub/1/other") 'yes' """ ############ # ALL CONFIGURATION CONSTANTS ARE HERE ############ LOCALE_DIR = "locale-dir" ANALYZE_OPTIONS = "analyze-options" AUTO_ANALYZE_ACTIVE = "auto-analyze-active" AUTO_ANALYZE_TIMER = "auto-analyze-timer" GRAMMALECTE_PYTHON_EXE = "g-python-exe" GRAMMALECTE_CLI = "g-cli" GRAMMALECTE_ANALYZE_PARAMS = "g-analyze-params" GRAMMALECTE_OPTIONS_PARAMS = "g-options-params" GRAMMALECTE_OPTIONS_REGEX = "g-options-regex" __CLI_PARAMS = "g-cli-params" __CLI_FILE = "file" __CLI_OPTS_ON = "on" __CLI_OPTS_OFF = "off" GRAMMALECTE_CLI_FILE = __CLI_PARAMS + "/" + __CLI_FILE GRAMMALECTE_CLI_OPTS_ON = __CLI_PARAMS + "/" + __CLI_OPTS_ON GRAMMALECTE_CLI_OPTS_OFF = __CLI_PARAMS + "/" + __CLI_OPTS_OFF GRAMMALECTE_OPTION_SPELLING = "_orth_" __DEFAULT_CONFIG = { ANALYZE_OPTIONS: {}, AUTO_ANALYZE_ACTIVE: False, AUTO_ANALYZE_TIMER: 500, GRAMMALECTE_PYTHON_EXE: "python3", GRAMMALECTE_CLI: "/opt/grammalecte/cli.py", __CLI_PARAMS: { __CLI_FILE: "-f", __CLI_OPTS_ON: "-on", __CLI_OPTS_OFF: "-off" }, GRAMMALECTE_ANALYZE_PARAMS: ["-j", "-cl", "-owe", "-ctx"], GRAMMALECTE_OPTIONS_PARAMS: ["-lo"], GRAMMALECTE_OPTIONS_REGEX: "^([a-zA-Z0-9]+):\s*(True|False)\s*(.*)$" } __PLUMA_CONFIG_FILE = "/pluma/grammalecte.conf" __SYSTEM_CONFIG_FILE = "/etc" + __PLUMA_CONFIG_FILE __USER_CONFIG_FILE = glib.get_user_config_dir() + __PLUMA_CONFIG_FILE __globalInstance = None def __init__(self, selfConfig = None): """ Initialize the plugin configuration. :param selfConfig: (optional) the selfConfig container. :type selfConfig: SelfConfigContainer """ # Initialize global instance if GrammalecteConfig.__globalInstance == None: defaultConfig = DictConfig(GrammalecteConfig.__DEFAULT_CONFIG) systemConfig = DictConfig(GrammalecteConfig.__SYSTEM_CONFIG_FILE, defaultConfig) GrammalecteConfig.__globalInstance = \ DictConfig(GrammalecteConfig.__USER_CONFIG_FILE, systemConfig) # Initialize local instance DictConfig.__init__(self, selfConfig, GrammalecteConfig.__globalInstance) @staticmethod def terminate(): """ Terminate usage of all configurations. This will save global configuration files if needed. """ if GrammalecteConfig.__globalInstance != None: GrammalecteConfig.__globalInstance.close() GrammalecteConfig.__globalInstance = None
from setuptools import setup, find_packages import os import os.path import glib def get_plugin_directory(): if os.getuid() == 0: return x # print("setuptools = dir %s" % dir(setuptools)) setup( name='scribes.python.rope', version='0.3.4', author='Anton Bobrov', author_email='*****@*****.**', description='Scribes plugin. Python code autocompleter', long_description=open('README.txt').read(), zip_safe=False, install_requires=['scribes.helpers>=0.5', 'rope>=0.9'], packages=find_packages(), include_package_data=True, namespace_packages=['scribes'], data_files=[(('%s/scribes/LanguagePlugins' % glib.get_user_config_dir()), ['PluginPythonRope.py'])], url='http://github.com/baverman/scribes-goodies', )
import string import threading import urllib import urlparse import glib from mopidy import compat, exceptions from mopidy.compat import queue from mopidy.utils import encoding logger = logging.getLogger(__name__) XDG_DIRS = { 'XDG_CACHE_DIR': glib.get_user_cache_dir(), 'XDG_CONFIG_DIR': glib.get_user_config_dir(), 'XDG_DATA_DIR': glib.get_user_data_dir(), 'XDG_MUSIC_DIR': glib.get_user_special_dir(glib.USER_DIRECTORY_MUSIC), } # XDG_MUSIC_DIR can be none, so filter out any bad data. XDG_DIRS = dict((k, v) for k, v in XDG_DIRS.items() if v is not None) def get_or_create_dir(dir_path): if not isinstance(dir_path, bytes): raise ValueError('Path is not a bytestring.') dir_path = expand_path(dir_path) if os.path.isfile(dir_path): raise OSError('A file with the same name as the desired dir, ' '"%s", already exists.' % dir_path)
# -*- coding: UTF-8 -*- import os import pickle import json import gtk import sys import glob import shutil import glib PROGRAM_NAME = 'hermelin' EXT_DIR_NAME = 'ext' THEME_DIR_NAME = 'theme' CONF_DIR = os.path.join(glib.get_user_config_dir(), PROGRAM_NAME) DB_DIR = os.path.join(CONF_DIR, 'db') CACHE_DIR = os.path.join(glib.get_user_cache_dir(), PROGRAM_NAME) AVATAR_CACHE_DIR = os.path.join(CACHE_DIR, 'avatar') DATA_DIRS = [] DATA_BASE_DIRS = ['/usr/local/share', '/usr/share', glib.get_user_data_dir()] DATA_DIRS += [os.path.join(d, PROGRAM_NAME) for d in DATA_BASE_DIRS] DATA_DIRS.append(os.path.abspath('./data')) TEMPLATE = 'index.html' settings = {}
import glob import gettext import pynotify from ubuntutweak import __version__ def applize(package): return ' '.join([a.capitalize() for a in package.split('-')]) PACKAGE = 'ubuntu-tweak' VERSION = __version__ DATA_DIR = '/usr/share/ubuntu-tweak/' APP = applize(PACKAGE) CONFIG_ROOT = os.path.join(glib.get_user_config_dir(), 'ubuntu-tweak') IS_INSTALLED = True if not os.path.exists(CONFIG_ROOT): os.makedirs(CONFIG_ROOT) try: LANG = os.getenv('LANG').split('.')[0].lower().replace('_', '-') except: LANG = 'en-us' if not __file__.startswith('/usr'): datadir = os.path.dirname( os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) DATA_DIR = os.path.join(datadir, 'data') IS_INSTALLED = False
""" Module for holding constants (and some variables with "fixed" values) used all over the program. """ import os.path import glib from constant_constants import * # Path of the program (bad assumption) TV_PATH = "/usr/bin/tunesviewer" TV_VERSION = "1.5" #also needs changing in debian conf file somewhere # Directory under which we write configuration files USER_PREFS_DIR = glib.get_user_config_dir() PREFS_DIR = os.path.join(USER_PREFS_DIR, "tunesviewer") PREFS_FILE = os.path.join(PREFS_DIR, "tunesviewer.conf") # Directory under which we write state data USER_DATA_DIR = glib.get_user_data_dir() DATA_DIR = os.path.join(USER_DATA_DIR, "tunesviewer") DATA_FILE = os.path.join(DATA_DIR, "state") # Holds current downloads, in case of crash, resumes. DATA_SOCKET = os.path.join(DATA_DIR, "tunesviewerLOCK") # Holds socket, so second app calls first instance with url. # Directory under which we write downloaded files DOWNLOADS_DIR = os.path.expanduser("~") # connection programs DEFAULT_OPENER = "vlc --http-user-agent=%s --http-caching=10000" % (USER_AGENT, )
def get_user_config_dir(): _confdir = glib.get_user_config_dir() return _confdir
class Screenkey(gtk.Window): STATE_FILE = os.path.join(glib.get_user_config_dir(), 'screenkey.json') def __init__(self, logger, options, show_settings=False): gtk.Window.__init__(self, gtk.WINDOW_POPUP) self.timer_hide = None self.timer_min = None self.logger = logger defaults = Options({ 'no_systray': False, 'timeout': 2.5, 'recent_thr': 0.1, 'compr_cnt': 3, 'ignore': [], 'position': 'bottom', 'persist': False, 'font_desc': 'Sans Bold', 'font_size': 'medium', 'font_color': 'white', 'bg_color': 'black', 'opacity': 0.8, 'key_mode': 'composed', 'bak_mode': 'baked', 'mods_mode': 'normal', 'mods_only': False, 'multiline': False, 'vis_shift': False, 'vis_space': True, 'geometry': None, 'screen': 0 }) self.options = self.load_state() if self.options is None: self.options = defaults else: # copy missing defaults for k, v in defaults.iteritems(): if k not in self.options: self.options[k] = v if options is not None: # override with values from constructor for k, v in options.iteritems(): if v is not None: self.options[k] = v self.set_keep_above(True) self.set_accept_focus(False) self.set_focus_on_map(False) self.label = gtk.Label() self.label.set_attributes(pango.AttrList()) self.label.set_ellipsize(pango.ELLIPSIZE_START) self.label.set_justify(gtk.JUSTIFY_CENTER) self.label.show() self.add(self.label) self.set_gravity(gtk.gdk.GRAVITY_CENTER) self.connect("configure-event", self.on_configure) scr = self.get_screen() scr.connect("size-changed", self.on_configure) scr.connect("monitors-changed", self.on_monitors_changed) self.set_active_monitor(self.options.screen) self.font = pango.FontDescription(self.options.font_desc) self.update_colors() self.update_label() self.labelmngr = None self.enabled = True self.on_change_mode() self.make_menu() self.make_about_dialog() self.make_preferences_dialog() if not self.options.no_systray: self.make_systray() self.connect("delete-event", self.quit) if show_settings: self.on_preferences_dialog() if self.options.persist: self.show() def quit(self, widget, data=None): self.labelmngr.stop() gtk.main_quit() def load_state(self): """Load stored options""" options = None try: with open(self.STATE_FILE, 'r') as f: options = Options(json.load(f)) self.logger.debug("Options loaded.") except IOError: self.logger.debug("file %s does not exists." % self.STATE_FILE) except ValueError: self.logger.debug("file %s is invalid." % self.STATE_FILE) # compatibility with previous versions (0.5) if options and options.key_mode == 'normal': options.key_mode = 'composed' return options def store_state(self, options): """Store options""" try: with open(self.STATE_FILE, 'w') as f: json.dump(options, f) self.logger.debug("Options saved.") except IOError: self.logger.debug("Cannot open %s." % self.STATE_FILE) def set_active_monitor(self, monitor): scr = self.get_screen() if monitor >= scr.get_n_monitors(): self.monitor = 0 else: self.monitor = monitor self.update_geometry() def on_monitors_changed(self, *_): self.set_active_monitor(self.monitor) def override_font_attributes(self, attr, text): window_width, window_height = self.get_size() lines = text.count('\n') + 1 attr.insert( pango.AttrSizeAbsolute((50 * window_height // lines // 100) * 1000, 0, -1)) attr.insert(pango.AttrFamily(self.font.get_family(), 0, -1)) attr.insert(pango.AttrWeight(self.font.get_weight(), 0, -1)) def update_label(self): attr = self.label.get_attributes() text = self.label.get_text() self.override_font_attributes(attr, text) self.label.set_attributes(attr) def update_colors(self): self.label.modify_fg(gtk.STATE_NORMAL, gtk.gdk.color_parse(self.options.font_color)) self.modify_bg(gtk.STATE_NORMAL, gtk.gdk.color_parse(self.options.bg_color)) self.set_opacity(self.options.opacity) def on_configure(self, *_): window_x, window_y = self.get_position() window_width, window_height = self.get_size() mask = gtk.gdk.Pixmap(None, window_width, window_height, 1) gc = gtk.gdk.GC(mask) gc.set_foreground(gtk.gdk.Color(pixel=0)) mask.draw_rectangle(gc, True, 0, 0, window_width, window_height) self.input_shape_combine_mask(mask, 0, 0) # set some proportional inner padding self.label.set_padding(window_width // 100, 0) self.update_label() def update_geometry(self, configure=False): if self.options.position == 'fixed' and self.options.geometry is not None: self.move(*self.options.geometry[0:2]) self.resize(*self.options.geometry[2:4]) return if self.options.geometry is not None: area_geometry = self.options.geometry else: geometry = self.get_screen().get_monitor_geometry(self.monitor) area_geometry = [ geometry.x, geometry.y, geometry.width, geometry.height ] if self.options.font_size == 'large': window_height = 24 * area_geometry[3] // 100 elif self.options.font_size == 'medium': window_height = 12 * area_geometry[3] // 100 else: window_height = 8 * area_geometry[3] // 100 self.resize(area_geometry[2], window_height) if self.options.position == 'top': window_y = area_geometry[1] + area_geometry[3] // 10 elif self.options.position == 'center': window_y = area_geometry[ 1] + area_geometry[3] // 2 - window_height // 2 else: window_y = area_geometry[ 1] + area_geometry[3] * 9 // 10 - window_height self.move(area_geometry[0], window_y) def on_statusicon_popup(self, widget, button, timestamp, data=None): if button == 3 and data: data.show() data.popup(None, None, gtk.status_icon_position_menu, 3, timestamp, widget) def show(self): self.update_geometry() super(Screenkey, self).show() def on_label_change(self, markup): attr, text, _ = pango.parse_markup(markup) self.override_font_attributes(attr, text) self.label.set_text(text) self.label.set_attributes(attr) if not self.get_property('visible'): self.show() if self.timer_hide: self.timer_hide.cancel() if self.options.timeout > 0: self.timer_hide = Timer(self.options.timeout, self.on_timeout_main) self.timer_hide.start() if self.timer_min: self.timer_min.cancel() self.timer_min = Timer(self.options.recent_thr * 2, self.on_timeout_min) self.timer_min.start() def on_timeout_main(self): if not self.options.persist: self.hide() self.label.set_text('') self.labelmngr.clear() def on_timeout_min(self): attr = self.label.get_attributes() attr.change(pango.AttrUnderline(pango.UNDERLINE_NONE, 0, -1)) self.label.set_attributes(attr) def restart_labelmanager(self): self.logger.debug("Restarting LabelManager.") if self.labelmngr: self.labelmngr.stop() self.labelmngr = LabelManager(self.on_label_change, logger=self.logger, key_mode=self.options.key_mode, bak_mode=self.options.bak_mode, mods_mode=self.options.mods_mode, mods_only=self.options.mods_only, multiline=self.options.multiline, vis_shift=self.options.vis_shift, vis_space=self.options.vis_space, recent_thr=self.options.recent_thr, compr_cnt=self.options.compr_cnt, ignore=self.options.ignore, pango_ctx=self.label.get_pango_context()) self.labelmngr.start() def on_change_mode(self): if not self.enabled: return self.restart_labelmanager() def on_show_keys(self, widget, data=None): self.enabled = widget.get_active() if self.enabled: self.logger.debug("Screenkey enabled.") self.restart_labelmanager() else: self.logger.debug("Screenkey disabled.") self.labelmngr.stop() def on_preferences_dialog(self, widget=None, data=None): self.prefs.show() def on_preferences_changed(self, widget=None, data=None): self.store_state(self.options) self.prefs.hide() return True def make_preferences_dialog(self): # TODO: switch to something declarative or at least clean-up the following mess self.prefs = prefs = gtk.Dialog(APP_NAME, None, gtk.DIALOG_DESTROY_WITH_PARENT, (gtk.STOCK_CLOSE, gtk.RESPONSE_CLOSE)) prefs.connect("response", self.on_preferences_changed) prefs.connect("delete-event", self.on_preferences_changed) def on_sb_time_changed(widget, data=None): self.options.timeout = widget.get_value() self.logger.debug("Timeout value changed: %f." % self.options.timeout) def on_cbox_sizes_changed(widget, data=None): index = widget.get_active() self.options.font_size = FONT_SIZES.keys()[index] self.update_geometry() self.logger.debug("Window size changed: %s." % self.options.font_size) def on_cbox_modes_changed(widget, data=None): index = widget.get_active() self.options.key_mode = KEY_MODES.keys()[index] self.on_change_mode() self.logger.debug("Key mode changed: %s." % self.options.key_mode) def on_cbox_bak_changed(widget, data=None): index = widget.get_active() self.options.bak_mode = BAK_MODES.keys()[index] self.on_change_mode() self.logger.debug("Bak mode changed: %s." % self.options.bak_mode) def on_cbox_mods_changed(widget, data=None): index = widget.get_active() self.options.mods_mode = MODS_MODES.keys()[index] self.on_change_mode() self.logger.debug("Mods mode changed: %s." % self.options.mods_mode) def on_cbox_modsonly_changed(widget, data=None): self.options.mods_only = widget.get_active() self.on_change_mode() self.logger.debug("Modifiers only changed: %s." % self.options.mods_only) def on_cbox_visshift_changed(widget, data=None): self.options.vis_shift = widget.get_active() self.on_change_mode() self.logger.debug("Visible Shift changed: %s." % self.options.vis_shift) def on_cbox_visspace_changed(widget, data=None): self.options.vis_space = widget.get_active() self.on_change_mode() self.logger.debug("Show Whitespace changed: %s." % self.options.vis_space) def on_cbox_position_changed(widget, data=None): index = widget.get_active() new_position = POSITIONS.keys()[index] if new_position == 'fixed': new_geom = on_btn_sel_geom(widget) if not new_geom: self.cbox_positions.set_active(POSITIONS.keys().index( self.options.position)) return elif self.options.position == 'fixed': # automatically clear geometry self.options.geometry = None self.options.position = new_position self.update_geometry() self.logger.debug("Window position changed: %s." % self.options.position) def on_cbox_screen_changed(widget, data=None): self.options.screen = widget.get_active() self.set_active_monitor(self.options.screen) self.logger.debug("Screen changed: %d." % self.options.screen) def on_cbox_persist_changed(widget, data=None): self.options.persist = widget.get_active() if not self.get_property('visible'): self.show() else: self.on_label_change(self.label.get_text()) self.logger.debug("Persistent changed: %s." % self.options.persist) def on_sb_compr_changed(widget, data=None): self.options.compr_cnt = widget.get_value_as_int() self.on_change_mode() self.logger.debug("Compress repeats value changed: %d." % self.options.compr_cnt) def on_cbox_compr_changed(widget, data=None): compr_enabled = widget.get_active() self.sb_compr.set_sensitive(compr_enabled) self.options.compr_cnt = self.sb_compr.get_value_as_int( ) if compr_enabled else 0 self.on_change_mode() self.logger.debug("Compress repeats value changed: %d." % self.options.compr_cnt) def on_btn_sel_geom(widget, data=None): try: ret = subprocess.check_output(['slop', '-f', '%x %y %w %h']) except subprocess.CalledProcessError: return False except OSError: msg = gtk.MessageDialog( parent=self, type=gtk.MESSAGE_ERROR, buttons=gtk.BUTTONS_OK, message_format="Error running \"slop\"") msg.format_secondary_markup( "\"slop\" is required for interactive selection. " "See <a href=\"https://github.com/naelstrof/slop\">" "https://github.com/naelstrof/slop</a>") msg.run() msg.destroy() return False self.options.geometry = map(int, ret.split(' ')) self.update_geometry() self.btn_reset_geom.set_sensitive(True) return True def on_btn_reset_geom(widget, data=None): self.options.geometry = None if self.options.position == 'fixed': self.options.position = 'bottom' self.cbox_positions.set_active(POSITIONS.keys().index( self.options.position)) self.update_geometry() widget.set_sensitive(False) def on_adj_opacity_changed(widget, data=None): self.options.opacity = widget.get_value() self.update_colors() def on_font_color_changed(widget, data=None): self.options.font_color = widget.get_color().to_string() self.update_colors() def on_bg_color_changed(widget, data=None): self.options.bg_color = widget.get_color().to_string() self.update_colors() def on_btn_font(widget, data=None): self.options.font_desc = widget.get_font_name() self.font = pango.FontDescription(self.options.font_desc) self.update_label() frm_main = gtk.Frame(_("Preferences")) frm_main.set_border_width(6) frm_time = gtk.Frame("<b>%s</b>" % _("Time")) frm_time.set_border_width(4) frm_time.get_label_widget().set_use_markup(True) frm_time.set_shadow_type(gtk.SHADOW_NONE) vbox_time = gtk.VBox(spacing=6) hbox_time = gtk.HBox() lbl_time1 = gtk.Label(_("Display for")) lbl_time2 = gtk.Label(_("seconds")) sb_time = gtk.SpinButton(digits=1) sb_time.set_increments(0.5, 1.0) sb_time.set_range(0.5, 10.0) sb_time.set_numeric(True) sb_time.set_update_policy(gtk.UPDATE_IF_VALID) sb_time.set_value(self.options.timeout) sb_time.connect("value-changed", on_sb_time_changed) hbox_time.pack_start(lbl_time1, expand=False, fill=False, padding=6) hbox_time.pack_start(sb_time, expand=False, fill=False, padding=4) hbox_time.pack_start(lbl_time2, expand=False, fill=False, padding=4) vbox_time.pack_start(hbox_time) chk_persist = gtk.CheckButton(_("Persistent window")) chk_persist.connect("toggled", on_cbox_persist_changed) chk_persist.set_active(self.options.persist) vbox_time.pack_start(chk_persist) frm_time.add(vbox_time) frm_time.show_all() frm_position = gtk.Frame("<b>%s</b>" % _("Position")) frm_position.set_border_width(4) frm_position.get_label_widget().set_use_markup(True) frm_position.set_shadow_type(gtk.SHADOW_NONE) vbox_position = gtk.VBox(spacing=6) lbl_screen = gtk.Label(_("Screen")) cbox_screen = gtk.combo_box_new_text() scr = self.get_screen() for n in range(scr.get_n_monitors()): cbox_screen.insert_text( n, '%d: %s' % (n, scr.get_monitor_plug_name(n))) cbox_screen.set_active(self.monitor) cbox_screen.connect("changed", on_cbox_screen_changed) hbox0_position = gtk.HBox() hbox0_position.pack_start(lbl_screen, expand=False, fill=False, padding=6) hbox0_position.pack_start(cbox_screen, expand=False, fill=False, padding=4) vbox_position.pack_start(hbox0_position) lbl_positions = gtk.Label(_("Position")) self.cbox_positions = cbox_positions = gtk.combo_box_new_text() cbox_positions.set_name('position') for key, value in enumerate(POSITIONS): cbox_positions.insert_text(key, value) cbox_positions.set_active(POSITIONS.keys().index( self.options.position)) cbox_positions.connect("changed", on_cbox_position_changed) self.btn_reset_geom = btn_reset_geom = gtk.Button(_("Reset")) btn_reset_geom.connect("clicked", on_btn_reset_geom) btn_reset_geom.set_sensitive(self.options.geometry is not None) hbox1_position = gtk.HBox() hbox1_position.pack_start(lbl_positions, expand=False, fill=False, padding=6) hbox1_position.pack_start(cbox_positions, expand=False, fill=False, padding=4) hbox1_position.pack_start(btn_reset_geom, expand=False, fill=False, padding=4) vbox_position.pack_start(hbox1_position) btn_sel_geom = gtk.Button(_("Select window/region")) btn_sel_geom.connect("clicked", on_btn_sel_geom) vbox_position.pack_start(btn_sel_geom) frm_aspect = gtk.Frame("<b>%s</b>" % _("Aspect")) frm_aspect.set_border_width(4) frm_aspect.get_label_widget().set_use_markup(True) frm_aspect.set_shadow_type(gtk.SHADOW_NONE) vbox_aspect = gtk.VBox(spacing=6) frm_position.add(vbox_position) hbox0_font = gtk.HBox() lbl_font = gtk.Label(_("Font")) btn_font = gtk.FontButton(self.options.font_desc) btn_font.set_use_size(False) btn_font.set_show_size(False) btn_font.connect("font-set", on_btn_font) hbox0_font.pack_start(lbl_font, expand=False, fill=False, padding=6) hbox0_font.pack_start(btn_font, expand=False, fill=False, padding=4) hbox2_aspect = gtk.HBox() lbl_sizes = gtk.Label(_("Size")) cbox_sizes = gtk.combo_box_new_text() cbox_sizes.set_name('size') for key, value in enumerate(FONT_SIZES): cbox_sizes.insert_text(key, value) cbox_sizes.set_active(FONT_SIZES.keys().index(self.options.font_size)) cbox_sizes.connect("changed", on_cbox_sizes_changed) hbox2_aspect.pack_start(lbl_sizes, expand=False, fill=False, padding=6) hbox2_aspect.pack_start(cbox_sizes, expand=False, fill=False, padding=4) hbox3_font_color = gtk.HBox() lbl_font_color = gtk.Label(_("Font color")) btn_font_color = gtk.ColorButton( color=gtk.gdk.color_parse(self.options.font_color)) btn_font_color.connect("color-set", on_font_color_changed) btn_bg_color = gtk.ColorButton( color=gtk.gdk.color_parse(self.options.bg_color)) btn_bg_color.connect("color-set", on_bg_color_changed) hbox3_font_color.pack_start(lbl_font_color, expand=False, fill=False, padding=6) hbox3_font_color.pack_start(btn_font_color, expand=False, fill=False, padding=4) hbox3_font_color.pack_start(btn_bg_color, expand=False, fill=False, padding=4) hbox4_aspect = gtk.HBox() lbl_opacity = gtk.Label(_("Opacity")) adj_opacity = gtk.Adjustment(self.options.opacity, 0.1, 1.0, 0.1, 0, 0) adj_opacity.connect("value-changed", on_adj_opacity_changed) adj_scale = gtk.HScale(adj_opacity) hbox4_aspect.pack_start(lbl_opacity, expand=False, fill=False, padding=6) hbox4_aspect.pack_start(adj_scale, expand=True, fill=True, padding=4) vbox_aspect.pack_start(hbox0_font) vbox_aspect.pack_start(hbox2_aspect) vbox_aspect.pack_start(hbox3_font_color) vbox_aspect.pack_start(hbox4_aspect) frm_aspect.add(vbox_aspect) frm_kbd = gtk.Frame("<b>%s</b>" % _("Keys")) frm_kbd.set_border_width(4) frm_kbd.get_label_widget().set_use_markup(True) frm_kbd.set_shadow_type(gtk.SHADOW_NONE) vbox_kbd = gtk.VBox(spacing=6) hbox_kbd = gtk.HBox() lbl_kbd = gtk.Label(_("Keyboard mode")) cbox_modes = gtk.combo_box_new_text() cbox_modes.set_name('mode') for key, value in enumerate(KEY_MODES): cbox_modes.insert_text(key, value) cbox_modes.set_active(KEY_MODES.keys().index(self.options.key_mode)) cbox_modes.connect("changed", on_cbox_modes_changed) hbox_kbd.pack_start(lbl_kbd, expand=False, fill=False, padding=6) hbox_kbd.pack_start(cbox_modes, expand=False, fill=False, padding=4) vbox_kbd.pack_start(hbox_kbd) hbox_kbd = gtk.HBox() lbl_kbd = gtk.Label(_("Backspace mode")) cbox_modes = gtk.combo_box_new_text() for key, value in enumerate(BAK_MODES): cbox_modes.insert_text(key, value) cbox_modes.set_active(BAK_MODES.keys().index(self.options.bak_mode)) cbox_modes.connect("changed", on_cbox_bak_changed) hbox_kbd.pack_start(lbl_kbd, expand=False, fill=False, padding=6) hbox_kbd.pack_start(cbox_modes, expand=False, fill=False, padding=4) vbox_kbd.pack_start(hbox_kbd) hbox_kbd = gtk.HBox() lbl_kbd = gtk.Label(_("Modifiers mode")) cbox_modes = gtk.combo_box_new_text() for key, value in enumerate(MODS_MODES): cbox_modes.insert_text(key, value) cbox_modes.set_active(MODS_MODES.keys().index(self.options.mods_mode)) cbox_modes.connect("changed", on_cbox_mods_changed) hbox_kbd.pack_start(lbl_kbd, expand=False, fill=False, padding=6) hbox_kbd.pack_start(cbox_modes, expand=False, fill=False, padding=4) vbox_kbd.pack_start(hbox_kbd) chk_kbd = gtk.CheckButton(_("Show Modifier sequences only")) chk_kbd.connect("toggled", on_cbox_modsonly_changed) chk_kbd.set_active(self.options.mods_only) vbox_kbd.pack_start(chk_kbd) chk_kbd = gtk.CheckButton(_("Always show Shift")) chk_kbd.connect("toggled", on_cbox_visshift_changed) chk_kbd.set_active(self.options.vis_shift) vbox_kbd.pack_start(chk_kbd) chk_vspace = gtk.CheckButton(_("Show Whitespace characters")) chk_vspace.set_active(self.options.vis_space) chk_vspace.connect("toggled", on_cbox_visspace_changed) vbox_kbd.pack_start(chk_vspace) hbox_compr = gtk.HBox() chk_compr = gtk.CheckButton(_("Compress repeats after")) chk_compr.set_active(self.options.compr_cnt > 0) chk_compr.connect("toggled", on_cbox_compr_changed) self.sb_compr = sb_compr = gtk.SpinButton(digits=0) sb_compr.set_increments(1, 1) sb_compr.set_range(1, 100) sb_compr.set_numeric(True) sb_compr.set_update_policy(gtk.UPDATE_IF_VALID) sb_compr.set_value(self.options.compr_cnt or 3) sb_compr.connect("value-changed", on_sb_compr_changed) hbox_compr.pack_start(chk_compr, expand=False, fill=False) hbox_compr.pack_start(sb_compr, expand=False, fill=False, padding=4) vbox_kbd.pack_start(hbox_compr) frm_kbd.add(vbox_kbd) hbox_main = gtk.HBox() vbox_main = gtk.VBox() vbox_main.pack_start(frm_time, False, False, 6) vbox_main.pack_start(frm_position, False, False, 6) vbox_main.pack_start(frm_aspect, False, False, 6) hbox_main.pack_start(vbox_main) vbox_main = gtk.VBox() vbox_main.pack_start(frm_kbd, False, False, 6) hbox_main.pack_start(vbox_main) frm_main.add(hbox_main) prefs.vbox.pack_start(frm_main) prefs.set_destroy_with_parent(True) prefs.set_resizable(False) prefs.set_has_separator(False) prefs.set_default_response(gtk.RESPONSE_CLOSE) prefs.vbox.show_all() def make_menu(self): self.menu = menu = gtk.Menu() show_item = gtk.CheckMenuItem(_("Show keys")) show_item.set_active(True) show_item.connect("toggled", self.on_show_keys) show_item.show() menu.append(show_item) preferences_item = gtk.ImageMenuItem(gtk.STOCK_PREFERENCES) preferences_item.connect("activate", self.on_preferences_dialog) preferences_item.show() menu.append(preferences_item) about_item = gtk.ImageMenuItem(gtk.STOCK_ABOUT) about_item.connect("activate", self.on_about_dialog) about_item.show() menu.append(about_item) separator_item = gtk.SeparatorMenuItem() separator_item.show() menu.append(separator_item) image = gtk.ImageMenuItem(gtk.STOCK_QUIT) image.connect("activate", self.quit) image.show() menu.append(image) menu.show() def make_systray(self): try: import appindicator self.systray = appindicator.Indicator( APP_NAME, 'indicator-messages', appindicator.CATEGORY_APPLICATION_STATUS) self.systray.set_status(appindicator.STATUS_ACTIVE) self.systray.set_attention_icon("indicator-messages-new") self.systray.set_icon("preferences-desktop-keyboard-shortcuts") self.systray.set_menu(self.menu) self.logger.debug("Using AppIndicator.") except ImportError: self.systray = gtk.StatusIcon() self.systray.set_from_icon_name( "preferences-desktop-keyboard-shortcuts") self.systray.connect("popup-menu", self.on_statusicon_popup, self.menu) self.logger.debug("Using StatusIcon.") def make_about_dialog(self): self.about = about = gtk.AboutDialog() about.set_program_name(APP_NAME) about.set_version(VERSION) about.set_copyright(""" Copyright(c) 2010-2012: Pablo Seminario <*****@*****.**> Copyright(c) 2015-2016: wave++ "Yuri D'Elia" <*****@*****.**> """) about.set_comments(APP_DESC) about.set_documenters(["José María Quiroga <*****@*****.**>"]) about.set_website(APP_URL) about.set_icon_name('preferences-desktop-keyboard-shortcuts') about.set_logo_icon_name('preferences-desktop-keyboard-shortcuts') about.connect("response", about.hide_on_delete) about.connect("delete-event", about.hide_on_delete) def on_about_dialog(self, widget, data=None): self.about.show()
from setuptools import setup, find_packages import os import os.path import glib def get_plugin_directory(): if os.getuid() == 0: return x # print("setuptools = dir %s" % dir(setuptools)) setup( name = 'scribes.python.rope', version = '0.3.4', author = 'Anton Bobrov', author_email = '*****@*****.**', description = 'Scribes plugin. Python code autocompleter', long_description = open('README.txt').read(), zip_safe = False, install_requires = ['scribes.helpers>=0.5', 'rope>=0.9'], packages = find_packages(), include_package_data = True, namespace_packages = ['scribes'], data_files = [ (('%s/scribes/LanguagePlugins' % glib.get_user_config_dir()), ['PluginPythonRope.py'] ) ], url = 'http://github.com/baverman/scribes-goodies', )
def main(datapath, extradata, oldstyle_confpath=None, version=MYPAINT_VERSION): """Run MyPaint with `sys.argv`, called from the "mypaint" script. :param datapath: The app's read-only data location. Where MyPaint should find its static data, e.g. UI definition XML, backgrounds, and brush definitions. $PREFIX/share/mypaint is usual. :param extradata: Extra search root for finding icons. Where to find the defaults for MyPaint's themeable UI icons. This will be used in addition to $XDG_DATA_DIRS for the purposes of icon lookup. Normally it's $PREFIX/share, to support unusual installations outside the usual locations. It should contain an icons/ subdirectory. :param oldstyle_confpath: Old-style merged config folder. If specified, all user-specific data that MyPaint writes is written here. If omitted, this data will be stored under the basedirs returned by glib.get_user_config_dir() for settings, and by glib.get_user_data_dir() for brushes and backgrounds. On Windows, these will be the same location. On POSIX systems, $HOME/.config/mypaint and $HOME/.local/share/mypaint are a typical division. :param version: full version string for display in the about box. The oldstyle_confpath parameter can also be overridden by command-line parameters. To support legacy MyPaint configuration dirs, call with oldstyle_confpath set to the expansion of ~/.mypaint. See `MYPAINT_VERSION` for details of what normally goes in `version`. """ # Default logfile basename. # If it's relative, it's resolved relative to the user config path. default_logfile = None if sys.platform == 'win32': # http://gna.org/bugs/?17999 default_logfile = "mypaint_error.log" # Parse command line parser = OptionParser('usage: %prog [options] [FILE]') parser.add_option( '-c', '--config', metavar='DIR', default=oldstyle_confpath, help='use old-style merged config directory DIR, e.g. ~/.mypaint') parser.add_option( '-l', '--logfile', metavar='FILE', default=default_logfile, help='log console messages to FILE (rel. to config location)') parser.add_option('-t', '--trace', action="store_true", help='print all executed Python statements') parser.add_option('-f', '--fullscreen', action="store_true", help='start in fullscreen mode') parser.add_option("-V", '--version', action="store_true", help='print version information and exit') options, args = parser.parse_args(sys.argv_unicode[1:]) # XDG support for new users on POSIX platforms if options.config is None: encoding = 'utf-8' appsubdir = u"mypaint" basedir = glib.get_user_data_dir().decode(encoding) userdatapath = os.path.join(basedir, appsubdir) basedir = glib.get_user_config_dir().decode(encoding) userconfpath = os.path.join(basedir, appsubdir) else: userdatapath = options.config userconfpath = options.config # Log to the specified location # Prepend the data path if the user gave a relative location. if options.logfile: logfilepath = os.path.join(userdatapath, options.logfile) logdirpath, logfilebasename = os.path.split(logfilepath) if not os.path.isdir(logdirpath): os.makedirs(logdirpath) logger.info("Copying log messages to %r", logfilepath) logfile_fp = open(logfilepath, 'a', 1) logfile_handler = logging.StreamHandler(logfile_fp) logfile_format = "%(asctime)s;%(levelname)s;%(name)s;%(message)s" logfile_handler.setFormatter(logging.Formatter(logfile_format)) root_logger = logging.getLogger(None) root_logger.addHandler(logfile_handler) # Classify this as a warning, since this is fairly evil. # Note: this hack doesn't catch every type of GTK3 error message. logger.warning("Redirecting stdout and stderr to %r", logfilepath) sys.stdout = sys.stderr = logfile_fp logger.info("Started logging to %r", logfilepath) if os.environ.get("MYPAINT_DEBUG", False): logger.critical("Test critical message, please ignore") warnings.resetwarnings() logging.captureWarnings(True) if options.version: # Output (rather than log) the version print "MyPaint version %s" % (version, ) sys.exit(0) def run(): logger.debug('user_datapath: %r', userdatapath) logger.debug('user_confpath: %r', userconfpath) app = application.Application(args, app_datapath=datapath, app_extradatapath=extradata, user_datapath=userdatapath, user_confpath=userconfpath, version=version, fullscreen=options.fullscreen) settings = gtk.Settings.get_default() dark = app.preferences.get("ui.dark_theme_variant", True) settings.set_property("gtk-application-prefer-dark-theme", dark) import gtkexcepthook func = app.filehandler.confirm_destructive_action gtkexcepthook.quit_confirmation_func = func # temporary workaround for gtk3 Ctrl-C bug: # https://bugzilla.gnome.org/show_bug.cgi?id=622084 import signal signal.signal(signal.SIGINT, signal.SIG_DFL) gtk.main() if options.trace: import trace tracer = trace.Trace(trace=1, count=0) tracer.runfunc(run) else: run()