def __file_monitor_changed_cb(self, monitor, one_file, other_file, event_type): if event_type == Gio.FileMonitorEvent.CREATED or \ event_type == Gio.FileMonitorEvent.ATTRIBUTE_CHANGED: self.add_bundle(one_file.get_path(), set_favorite=True) elif event_type == Gio.FileMonitorEvent.DELETED: self.remove_bundle(one_file.get_path()) for root in GLib.get_system_data_dirs(): root = os.path.join(root, 'sugar', 'activities') try: os.listdir(root) except OSError: logging.debug('Can not find GLib system dir %s', root) continue activity_dir = os.path.basename(one_file.get_path()) try: bundle = bundle_from_dir(os.path.join(root, activity_dir)) except MalformedBundleException: continue if bundle is not None: path = bundle.get_path() if path is not None: self.add_bundle(path)
def get_system_bundles(self, bundle_id): """ Searches for system bundles (eg. those in /usr/share/sugar/activities) with a given bundle id. Prams: * bundle_id (string): the bundle id to look for Returns a list of ActivityBundle or ContentBundle objects, or an empty list if there are none found. """ bundles = [] for root in GLib.get_system_data_dirs(): root = os.path.join(root, 'sugar', 'activities') try: dir_list = os.listdir(root) except OSError: logging.debug('Can not find GLib system dir %s', root) continue for activity_dir in dir_list: try: bundle = bundle_from_dir(os.path.join(root, activity_dir)) except MalformedBundleException: continue if bundle.get_bundle_id() == bundle_id: bundles.append(bundle) return bundles
def getDirectoryPath(file_id): """Return the path to the system-installed .directory file.""" for path in GLib.get_system_data_dirs(): file_path = os.path.join(path, 'desktop-directories', file_id) if os.path.isfile(file_path): return file_path return None
def getItemPath(file_id): """Return the path to the system-installed .desktop file.""" for path in GLib.get_system_data_dirs(): file_path = os.path.join(path, 'applications', file_id) if os.path.isfile(file_path): return file_path return None
def _find_bundles(): global bundle_icons info_files = [] for root in GLib.get_system_data_dirs(): info_files += glob.glob(os.path.join(root, 'sugar', 'activities', '*.activity', 'activity', 'activity.info')) for path in info_files: fd = open(path, 'rb') cp = ConfigParser() cp.readfp(fd) section = 'Activity' if cp.has_option(section, 'bundle_id'): bundle_id = cp.get(section, 'bundle_id') else: continue if cp.has_option(section, 'icon'): icon = cp.get(section, 'icon') dirname = os.path.dirname(path) bundle_icons[bundle_id] = os.path.join(dirname, icon + '.svg')
def __init__(self, keyboard_type='touch', keyboard_file=None, keyboard_level=None): GObject.GObject.__init__(self) settings = AntlerSettings() self.set_show_tabs(False) ctx = self.get_style_context() ctx.add_class("antler-keyboard-window") use_system = settings.use_system use_system.connect("value-changed", self._on_use_system_theme_changed) self._app_css_provider = Gtk.CssProvider() self._load_style( self._app_css_provider, "style.css", [GLib.get_user_data_dir()] + list(GLib.get_system_data_dirs())) if not use_system.value: Gtk.StyleContext.add_provider_for_screen( Gdk.Screen.get_default(), self._app_css_provider, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION) self._user_css_provider = Gtk.CssProvider() self._load_style(self._user_css_provider, "user-style.css", [GLib.get_user_data_dir()]) Gtk.StyleContext.add_provider_for_screen( Gdk.Screen.get_default(), self._user_css_provider, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION + 1) self.scanner = Caribou.Scanner() self.set_keyboard_model(keyboard_type, keyboard_file, keyboard_level)
def __init__(self, keyboard_type='touch', keyboard_file=None, keyboard_level=None): GObject.GObject.__init__(self) settings = AntlerSettings() self.set_show_tabs(False) ctx = self.get_style_context() ctx.add_class("antler-keyboard-window") use_system = settings.use_system use_system.connect("value-changed", self._on_use_system_theme_changed) self._app_css_provider = Gtk.CssProvider() self._load_style(self._app_css_provider, "style.css", [GLib.get_user_data_dir()] + list(GLib.get_system_data_dirs())) if not use_system.value: Gtk.StyleContext.add_provider_for_screen( Gdk.Screen.get_default(), self._app_css_provider, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION) self._user_css_provider = Gtk.CssProvider() self._load_style(self._user_css_provider, "user-style.css", [GLib.get_user_data_dir()]) Gtk.StyleContext.add_provider_for_screen( Gdk.Screen.get_default(), self._user_css_provider, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION + 1) self.scanner = Caribou.Scanner() self.set_keyboard_model(keyboard_type, keyboard_file, keyboard_level)
def list_gtk_themes(): """Lists all available GTK theme. :rtype: [str] """ builtin_themes = [ theme[:-1] for theme in Gio.resources_enumerate_children( "/org/gtk/libgtk/theme", Gio.ResourceFlags.NONE) ] theme_search_dirs = [ Path(data_dir) / "themes" for data_dir in GLib.get_system_data_dirs() ] theme_search_dirs.append(Path(GLib.get_user_data_dir()) / "themes") theme_search_dirs.append(Path(GLib.get_home_dir()) / ".themes") fs_themes = [] for theme_search_dir in theme_search_dirs: if not theme_search_dir.exists(): continue for theme_dir in theme_search_dir.iterdir(): if (not (theme_dir / "gtk-3.0" / "gtk.css").exists() and not (theme_dir / "gtk-3.0" / "gtk-dark.css").exists() and not (theme_dir / "gtk-3.20" / "gtk.css").exists() and not (theme_dir / "gtk-3.20" / "gtk-dark.css").exists()): continue fs_themes.append(theme_dir.as_posix().split("/")[-1]) return sorted(set(builtin_themes + fs_themes))
def get_session_file(session): system_data_dirs = GLib.get_system_data_dirs() session_dirs = OrderedSet( os.path.join(data_dir, session) for data_dir in system_data_dirs for session in {"wayland-sessions", "xsessions"}) session_files = OrderedSet( os.path.join(dir, session + ".desktop") for dir in session_dirs if os.path.exists(os.path.join(dir, session + ".desktop"))) # Deal with duplicate wayland-sessions and xsessions. # Needed for the situation in gnome-session, where there's # a xsession named the same as a wayland session. if any(map(is_session_wayland, session_files)): session_files = OrderedSet(session for session in session_files if is_session_wayland(session)) else: session_files = OrderedSet(session for session in session_files if is_session_xsession(session)) if len(session_files) == 0: logging.warning("No session files are found.") sys.exit(0) else: return session_files[0]
def __init__(self): logging.debug('STARTUP: Loading the bundle registry') GObject.GObject.__init__(self) self._mime_defaults = self._load_mime_defaults() # Queue of bundles to be installed/upgraded self._install_queue = _InstallQueue(self) # Bundle installation happens in a separate thread, which needs # access to _bundles. Protect all _bundles access with a lock. self._lock = Lock() self._bundles = [] # hold a reference to the monitors so they don't get disposed self._gio_monitors = [] dirs = [env.get_user_activities_path(), env.get_user_library_path()] for data_dir in GLib.get_system_data_dirs(): dirs.append(os.path.join(data_dir, "sugar", "activities")) for activity_dir in dirs: self._scan_directory(activity_dir) directory = Gio.File.new_for_path(activity_dir) monitor = directory.monitor_directory( flags=Gio.FileMonitorFlags.NONE, cancellable=None) monitor.connect('changed', self.__file_monitor_changed_cb) self._gio_monitors.append(monitor) self._last_defaults_mtime = [] self._favorite_bundles = [] for i in range(desktop.get_number_of_views()): self._favorite_bundles.append({}) self._last_defaults_mtime.append(-1) client = GConf.Client.get_default() self._protected_activities = [] # FIXME, gconf_client_get_list not introspectable #681433 protected_activities = client.get( '/desktop/sugar/protected_activities') for gval in protected_activities.get_list(): activity_id = gval.get_string() self._protected_activities.append(activity_id) if self._protected_activities is None: self._protected_activities = [] try: self._load_favorites() except Exception: logging.exception('Error while loading favorite_activities.') self._merge_default_favorites() self._desktop_model = desktop.get_model() self._desktop_model.connect('desktop-view-icons-changed', self.__desktop_view_icons_changed_cb)
def get_resource_dirs(self, resource): dirs = [ os.path.join(dir, resource) for dir in itertools.chain(GLib.get_system_data_dirs()) ] dirs += [os.path.join(os.path.expanduser("~"), ".{}".format(resource))] return [dir for dir in dirs if os.path.isdir(dir)]
def get_desktop_id(desktop_file): """ Gets a desktop-id from a .desktop file path""" datadirs = [(i if i[-1] == '/' else i+'/') + 'applications/' for i in \ GLib.get_system_data_dirs() + [GLib.get_user_data_dir()]] for dir in datadirs: if desktop_file.startswith(dir): return desktop_file[len(dir):].replace('/', '-') return desktop_file
def xdg_get_system_data_dirs(): """http://standards.freedesktop.org/basedir-spec/latest/""" if os.name == "nt": from gi.repository import GLib return map(fsnative, GLib.get_system_data_dirs()) data_dirs = os.getenv("XDG_DATA_DIRS") if data_dirs: return map(os.path.abspath, data_dirs.split(":")) else: return ("/usr/local/share/", "/usr/share/")
def getSystemLauncherPath(basename): """Return the system-installed path to a .desktop or .directory file.""" if basename.endswith('.desktop'): check_dir = "applications" else: check_dir = "desktop-directories" for path in GLib.get_system_data_dirs(): path = os.path.join(path, check_dir) filename = os.path.join(path, basename) if os.path.isfile(filename): return filename return None
def get_data_dirs(self): dirs = [] for directory in GLib.get_system_data_dirs(): path = os.path.join(directory, self.data_dir) if os.path.isdir(path): dirs.append(path) path = os.path.join(path, "layouts") if os.path.isdir(path): dirs.append(path) path = os.path.join(GLib.get_user_data_dir(), self.data_dir) if os.path.isdir(path): dirs.append(path) return list(set(dirs))
def test_xdg_dirs(self): d = GLib.get_user_data_dir() self.assertTrue('/' in d, d) d = GLib.get_user_special_dir(GLib.USER_DIRECTORY_DESKTOP) self.assertTrue('/' in d, d) # also works with backwards compatible enum names self.assertEqual(GLib.get_user_special_dir(GLib.UserDirectory.DIRECTORY_MUSIC), GLib.get_user_special_dir(GLib.USER_DIRECTORY_MUSIC)) for d in GLib.get_system_config_dirs(): self.assertTrue('/' in d, d) for d in GLib.get_system_data_dirs(): self.assertTrue(isinstance(d, str), d)
def read(self): self._groups.clear() pathes = [] pathes += GLib.get_system_data_dirs() pathes += GLib.get_system_config_dirs() pathes.append(os.path.dirname(os.path.dirname(self._output_path))) files = [] for path in pathes: files += sorted( iglob( os.path.join(path, self._base_dir, self._base_name + '.d', '*.conf'))) files.append(os.path.join(path, self._base_dir, self._base_name)) for path in filter(os.path.isfile, files): config_file = configparser.RawConfigParser(strict=False, allow_no_value=True) try: if not config_file.read(path): continue except configparser.Error as e: print(e, file=sys.stderr) continue for groupname, values in config_file.items(): if groupname == 'DEFAULT': continue if groupname not in self._groups: self._groups[groupname] = Config.ConfigGroup(self) group = self._groups[groupname] for key, value in values.items(): if value is None: print( '[{group}] {key}: Keys without values are not allowed' .format(group=groupname, key=key), file=sys.stderr) continue if key.startswith('-'): key = key[1:] value = None if key in group._items: values = group._items[key] if value is not None or values: values.append((path, value)) elif value is not None: group._items[key] = [(path, value)]
def __init__(self): logging.debug('STARTUP: Loading the bundle registry') GObject.GObject.__init__(self) self._mime_defaults = self._load_mime_defaults() # Queue of bundles to be installed/upgraded self._install_queue = _InstallQueue(self) # Bundle installation happens in a separate thread, which needs # access to _bundles. Protect all _bundles access with a lock. self._lock = Lock() self._bundles = [] # hold a reference to the monitors so they don't get disposed self._gio_monitors = [] dirs = [env.get_user_activities_path(), env.get_user_library_path()] for data_dir in GLib.get_system_data_dirs(): dirs.append(os.path.join(data_dir, "sugar", "activities")) for activity_dir in dirs: self._scan_directory(activity_dir) directory = Gio.File.new_for_path(activity_dir) monitor = directory.monitor_directory( flags=Gio.FileMonitorFlags.NONE, cancellable=None) monitor.connect('changed', self.__file_monitor_changed_cb) self._gio_monitors.append(monitor) self._favorite_bundles = [] for i in range(desktop.get_number_of_views()): self._favorite_bundles.append({}) settings = Gio.Settings('org.sugarlabs') self._protected_activities = settings.get_strv('protected-activities') try: self._load_favorites() except Exception: logging.exception('Error while loading favorite_activities.') self._hidden_activities = [] self._load_hidden_activities() self._convert_old_favorites() self._scan_new_favorites() self._desktop_model = desktop.get_model() self._desktop_model.connect('desktop-view-icons-changed', self.__desktop_view_icons_changed_cb)
def test_xdg_dirs(self): d = GLib.get_user_data_dir() self.assertTrue('/' in d, d) d = GLib.get_user_special_dir(GLib.USER_DIRECTORY_DESKTOP) self.assertTrue('/' in d, d) # also works with backwards compatible enum names self.assertEqual( GLib.get_user_special_dir(GLib.UserDirectory.DIRECTORY_MUSIC), GLib.get_user_special_dir(GLib.USER_DIRECTORY_MUSIC)) for d in GLib.get_system_config_dirs(): self.assertTrue('/' in d, d) for d in GLib.get_system_data_dirs(): self.assertTrue(isinstance(d, str), d)
def get_resource_dirs(resource): """Returns a list of all known resource dirs for a given resource. :param str resource: Name of the resource (e.g. "themes") :return: A list of resource dirs """ dirs = [os.path.join(dir, resource) for dir in itertools.chain(GLib.get_system_data_dirs(), (gtweak.DATA_DIR, GLib.get_user_data_dir()))] dirs += [os.path.join(os.path.expanduser("~"), ".{}".format(resource))] return [dir for dir in dirs if os.path.isdir(dir)]
def xdg_get_system_data_dirs(): """http://standards.freedesktop.org/basedir-spec/latest/""" if os.name == "nt": from gi.repository import GLib dirs = [] for dir_ in GLib.get_system_data_dirs(): dirs.append(glib2fsn(dir_)) return dirs data_dirs = os.getenv("XDG_DATA_DIRS") if data_dirs: return list(map(os.path.abspath, data_dirs.split(":"))) else: return ("/usr/local/share/", "/usr/share/")
def xdg_get_system_data_dirs(): """http://standards.freedesktop.org/basedir-spec/latest/""" if os.name == "nt": from gi.repository import GLib dirs = [] for dir_ in GLib.get_system_data_dirs(): dirs.append(glib2fsn(dir_)) return dirs data_dirs = os.getenv("XDG_DATA_DIRS") if data_dirs: return [os.path.abspath(d) for d in data_dirs.split(":")] else: return ("/usr/local/share/", "/usr/share/")
def get_resource_dirs(resource): """Returns a list of all known resource dirs for a given resource. :param str resource: Name of the resource (e.g. "themes") :return: A list of resource dirs """ dirs = [ os.path.join(dir, resource) for dir in itertools.chain(GLib.get_system_data_dirs(), GUAKE_THEME_DIR, GLib.get_user_data_dir()) ] dirs += [os.path.join(os.path.expanduser("~"), ".{}".format(resource))] return [Path(dir) for dir in dirs if os.path.isdir(dir)]
def _list_gtk_themes(self): dirs = [ Gtk.rc_get_theme_dir(), os.path.join(GLib.get_user_data_dir(), 'themes'), os.path.join(GLib.get_home_dir(), '.themes') ] for dir in GLib.get_system_data_dirs(): dirs.append(os.path.join(dir, 'themes')) themes = set() for dir in dirs: for f in glob(os.path.join(dir, '*', 'index.theme')): themes.add(f.split(os.path.sep)[-2]) return themes
def test_xdg_dirs(self): d = GLib.get_user_data_dir() self.assertTrue(os.path.sep in d, d) d = GLib.get_user_special_dir(GLib.UserDirectory.DIRECTORY_DESKTOP) self.assertTrue(os.path.sep in d, d) with warnings.catch_warnings(): warnings.simplefilter('ignore', PyGIDeprecationWarning) # also works with backwards compatible enum names self.assertEqual(GLib.get_user_special_dir(GLib.UserDirectory.DIRECTORY_MUSIC), GLib.get_user_special_dir(GLib.USER_DIRECTORY_MUSIC)) for d in GLib.get_system_config_dirs(): self.assertTrue(os.path.sep in d, d) for d in GLib.get_system_data_dirs(): self.assertTrue(isinstance(d, str), d)
def get_resource_dirs(resource): """Returns a list of all known resource dirs for a given resource. :param str resource: Name of the resource (e.g. "themes") :return: A list of resource dirs """ dirs = [ os.path.join(dir, resource) for dir in itertools.chain(GLib.get_system_data_dirs(), GUAKE_THEME_DIR, GLib.get_user_data_dir()) ] dirs += [os.path.join(os.path.expanduser("~"), f".{resource}")] return [Path(dir) for dir in dirs if os.path.isdir(dir)]
def get_locale_dirs(): if os.name == 'nt': return path = gettext.find(DOMAIN) if path is not None: # gettext can find the location itself # so we don’t need the localedir return if Path('/app/share/run-as-flatpak').exists(): # Check if we run as flatpak return [Path('/app/share/')] data_dirs = [GLib.get_user_data_dir()] + GLib.get_system_data_dirs() return [Path(dir_) for dir_ in data_dirs]
def read(self): self._groups.clear() pathes = [] pathes += GLib.get_system_data_dirs() pathes += GLib.get_system_config_dirs() pathes.append(os.path.dirname(os.path.dirname(self._output_path))) files = [] for path in pathes: files += sorted(iglob(os.path.join(path, self._base_dir, self._base_name + '.d', '*.conf'))) files.append(os.path.join(path, self._base_dir, self._base_name)) for path in filter(os.path.isfile, files): config_file = configparser.RawConfigParser(strict=False, allow_no_value=True) try: if not config_file.read(path): continue except configparser.Error as e: print(e, file=sys.stderr) continue for groupname, values in config_file.items(): if groupname == 'DEFAULT': continue if groupname not in self._groups: self._groups[groupname] = Config.ConfigGroup(self) group = self._groups[groupname] for key, value in values.items(): if value is None: print('[{group}] {key}: Keys without values are not allowed'.format( group=groupname, key=key), file=sys.stderr) continue if key.startswith('-'): key = key[1:] value = None if key in group._items: values = group._items[key] if value is not None or values: values.append((path, value)) elif value is not None: group._items[key] = [(path, value)]
def __init__(self): logging.debug('STARTUP: Loading the bundle registry') GObject.GObject.__init__(self) self._mime_defaults = self._load_mime_defaults() self._bundles = [] # hold a reference to the monitors so they don't get disposed self._gio_monitors = [] dirs = [env.get_user_activities_path()] for data_dir in GLib.get_system_data_dirs(): dirs.append(os.path.join(data_dir, "sugar", "activities")) for activity_dir in dirs: self._scan_directory(activity_dir) directory = Gio.File.new_for_path(activity_dir) monitor = directory.monitor_directory( flags=Gio.FileMonitorFlags.NONE, cancellable=None) monitor.connect('changed', self.__file_monitor_changed_cb) self._gio_monitors.append(monitor) self._last_defaults_mtime = -1 self._favorite_bundles = {} client = GConf.Client.get_default() self._protected_activities = [] # FIXME, gconf_client_get_list not introspectable #681433 protected_activities = client.get( '/desktop/sugar/protected_activities') for gval in protected_activities.get_list(): activity_id = gval.get_string() self._protected_activities.append(activity_id) if self._protected_activities is None: self._protected_activities = [] try: self._load_favorites() except Exception: logging.exception('Error while loading favorite_activities.') self._merge_default_favorites()
def __init__(self): logging.debug('STARTUP: Loading the bundle registry') GObject.GObject.__init__(self) self._mime_defaults = self._load_mime_defaults() self._bundles = [] # hold a reference to the monitors so they don't get disposed self._gio_monitors = [] dirs = [env.get_user_activities_path()] for data_dir in GLib.get_system_data_dirs(): dirs.append(os.path.join(data_dir, "sugar", "activities")) for activity_dir in dirs: self._scan_directory(activity_dir) directory = Gio.File.new_for_path(activity_dir) monitor = directory.monitor_directory( \ flags=Gio.FileMonitorFlags.NONE, cancellable=None) monitor.connect('changed', self.__file_monitor_changed_cb) self._gio_monitors.append(monitor) self._last_defaults_mtime = -1 self._favorite_bundles = {} client = GConf.Client.get_default() self._protected_activities = [] # FIXME, gconf_client_get_list not introspectable #681433 protected_activities = client.get( '/desktop/sugar/protected_activities') for gval in protected_activities.get_list(): activity_id = gval.get_string() self._protected_activities.append(activity_id) if self._protected_activities is None: self._protected_activities = [] try: self._load_favorites() except Exception: logging.exception('Error while loading favorite_activities.') self._merge_default_favorites()
def load_policy_map(self): """ Load policy list file """ policy_map = None for dirpath in GLib.get_system_data_dirs(): logging.debug("Looking for chromium policies file at %s" % dirpath) filepath = os.path.join(dirpath, 'fleet-commander-logger/fc-chromium-policies.json') try: with open(filepath, 'r') as fd: contents = fd.read() policy_map = json.loads(contents) fd.close() logging.debug('Loaded chromium policies file at %s' % filepath) break except Exception as e: logging.debug('Can not open chromium policies file at %s: %s' % (filepath, e)) return policy_map
def __find_data_file(self, filename): """Find the full path for the specified data file.""" path = os.path.join(os.getcwd(), 'data', filename) if os.path.exists(path): return path path = os.path.join(os.getcwd(), os.path.pardir, 'data', filename) if os.path.exists(path): return os.path.abspath(path) path = os.path.join(os.getcwd(), os.path.pardir, os.path.pardir, 'data', filename) if os.path.exists(path): return os.path.abspath(path) for folder in GLib.get_system_data_dirs(): path = os.path.join(folder, 'ubuntuone-installer', filename) if os.path.exists(path): return path
def __find_thumbnailers(self): path_list = GLib.get_system_data_dirs() path_list.append(GLib.get_user_data_dir()) file_list = [] for path in path_list: file_list.extend( glob.glob(os.path.join(path, "thumbnailers", "*.thumbnailer"))) for filename in file_list: kf = GLib.KeyFile() try: kf.load_from_file(filename, GLib.KeyFileFlags.NONE) cmd = kf.get_string("Thumbnailer Entry", "Exec") mime_types = kf.get_string_list("Thumbnailer Entry", "MimeType") except GLib.GError: continue if cmd and mime_types: for mime_type in mime_types: self.all_mime_types[mime_type] = cmd
def convert_desktop_file_to_installed_location(app_install_data_file_path, pkgname): """ returns the installed desktop file path that corresponds to the given app-install-data file path, and will also check directly for the desktop file that corresponds to a given pkgname. """ if app_install_data_file_path and pkgname: # "normal" case installed_desktop_file_path = app_install_data_file_path.replace( "app-install/desktop/" + pkgname + ":", "applications/") if os.path.exists(installed_desktop_file_path): return installed_desktop_file_path # next, try case where a subdirectory is encoded in the app-install # desktop filename, e.g. kde4_soundkonverter.desktop installed_desktop_file_path = installed_desktop_file_path.replace( APP_INSTALL_PATH_DELIMITER, "/") if os.path.exists(installed_desktop_file_path): return installed_desktop_file_path # lastly, just try checking directly for the desktop file based on the # pkgname itself for the case of for-purchase items, etc. if pkgname: datadirs = GLib.get_system_data_dirs() for dir in datadirs: path = "%s/applications/%s.desktop" % (dir, pkgname) if os.path.exists(path): return path # files in the extras archive have their desktop filenames prepended # by "extras-", so we check for that also (LP: #1012877) for dir in datadirs: path = "%s/applications/extras-%s.desktop" % (dir, pkgname) if os.path.exists(path): return path LOG.warn("Could not determine the installed desktop file path for " "app-install desktop file: '%s'" % app_install_data_file_path) return ""
def get_gir_dirs(): from gi.repository import GLib dirs = GLib.get_system_data_dirs() return [os.path.join(d, "gir-1.0") for d in dirs]
from setuptools import setup, find_packages from gi.repository import GLib from pathlib import Path import os sys_data_dir = Path(GLib.get_system_data_dirs()[-1]) schema_dir = str(sys_data_dir / 'glib-2.0' / 'schemas') app_dir = str(sys_data_dir / 'applications') app_data_dir = str(sys_data_dir / 'passman') help_dir = str(sys_data_dir / 'help' / 'C' / 'passman') help_media_dir = str(sys_data_dir / 'help' / 'C' / 'passman' / 'media') help_walk = list(os.walk('help')) dirpath, dirnames, filenames = help_walk[0] dirpath = Path(dirpath) help_files = [str(dirpath / filename) for filename in filenames] dirpath, dirnames, filenames = help_walk[1] dirpath = Path(dirpath) help_media_files = [str(dirpath / filename) for filename in filenames] with open('README.rst', encoding='utf-8') as f: f.readline() f.readline() f.readline() long_description = f.read() setup( name='PassMan', # Versions should comply with PEP440. For a discussion on single-sourcing # the version across setup.py and the project code, see
class ShellThemeTweak(Gtk.Box, Tweak): THEME_EXT_NAME = "*****@*****.**" THEME_GSETTINGS_SCHEMA = "org.gnome.shell.extensions.user-theme" THEME_GSETTINGS_NAME = "name" THEME_GSETTINGS_DIR = os.path.join(GLib.get_user_data_dir(), "gnome-shell", "extensions", THEME_EXT_NAME, "schemas") LEGACY_THEME_DIR = os.path.join(GLib.get_home_dir(), ".themes") THEME_DIR = os.path.join(GLib.get_user_data_dir(), "themes") def __init__(self, **options): Gtk.Box.__init__(self, orientation=Gtk.Orientation.HORIZONTAL) Tweak.__init__(self, _("Shell theme"), _("Install custom or user themes for gnome-shell"), **options) #check the shell is running and the usertheme extension is present error = _("Unknown error") self._shell = _shell if self._shell is None: logging.warning("Shell not running", exc_info=True) error = _("Shell not running") else: try: extensions = self._shell.list_extensions() if ShellThemeTweak.THEME_EXT_NAME in extensions and extensions[ ShellThemeTweak.THEME_EXT_NAME]["state"] == 1: #check the correct gsettings key is present try: if os.path.exists(ShellThemeTweak.THEME_GSETTINGS_DIR): self._settings = GSettingsSetting( ShellThemeTweak.THEME_GSETTINGS_SCHEMA, schema_dir=ShellThemeTweak.THEME_GSETTINGS_DIR) else: self._settings = GSettingsSetting( ShellThemeTweak.THEME_GSETTINGS_SCHEMA) name = self._settings.get_string( ShellThemeTweak.THEME_GSETTINGS_NAME) ext = extensions[ShellThemeTweak.THEME_EXT_NAME] logging.debug("Shell user-theme extension\n%s" % pprint.pformat(ext)) error = None except: logging.warning( "Could not find user-theme extension in %s" % ','.join(extensions.keys()), exc_info=True) error = _( "Shell user-theme extension incorrectly installed") else: error = _("Shell user-theme extension not enabled") except Exception, e: logging.warning("Could not list shell extensions", exc_info=True) error = _("Could not list shell extensions") if error: cb = build_combo_box_text(None) build_label_beside_widget(self.name, cb, warning=error, hbox=self) self.widget_for_size_group = cb else: #include both system, and user themes #note: the default theme lives in /system/data/dir/gnome-shell/theme # and not themes/, so add it manually later dirs = [ os.path.join(d, "themes") for d in GLib.get_system_data_dirs() ] dirs += [ShellThemeTweak.THEME_DIR] dirs += [ShellThemeTweak.LEGACY_THEME_DIR] valid = walk_directories(dirs, lambda d: os.path.exists(os.path.join(d, "gnome-shell")) and \ os.path.exists(os.path.join(d, "gnome-shell", "gnome-shell.css"))) #the default value to reset the shell is an empty string valid.extend(("", )) #build a combo box with all the valid theme options #manually add Adwaita to represent the default cb = build_combo_box_text( self._settings.get_string( ShellThemeTweak.THEME_GSETTINGS_NAME), *make_combo_list_with_default( valid, "", default_text=_("<i>Default</i>"))) cb.connect('changed', self._on_combo_changed) self._combo = cb #a filechooser to install new themes chooser = FileChooserButton(_("Select a theme"), True, ["application/zip"]) chooser.connect("file-set", self._on_file_set) build_label_beside_widget(self.name, chooser, cb, hbox=self) self.widget_for_size_group = cb
def on_module_selected(self): if self.loaded: return print "Loading Screensaver module" self.proc = None schema = "org.cinnamon.desktop.screensaver" self.settings = Gio.Settings.new(schema) self.sidePage.stack = SettingsStack() self.sidePage.add_widget(self.sidePage.stack) # Screensaver page = SettingsPage() self.sidePage.stack.add_titled(page, "screensaver", _("Screensaver")) settings = page.add_section(_("Select screensaver")) self.scrollWindow = Gtk.ScrolledWindow() self.tree_view = Gtk.TreeView() # uuid, name, description, path, type self.model = Gtk.ListStore(str, str, str, str, str) self.tree_view.set_model(self.model) self.tree_view.set_tooltip_column(2) self.scrollWindow.set_min_content_height(140) renderer = Gtk.CellRendererText.new() renderer.set_property("xpad", 30) name_column = Gtk.TreeViewColumn("Name", renderer, text=1) name_column.set_expand(True) name_column.set_property("sizing", Gtk.TreeViewColumnSizing.FIXED) self.tree_view.append_column(name_column) self.tree_view.set_headers_visible(False) self.tree_view.connect("row-activated", self.on_row_activated) self.tree_view.set_activate_on_single_click(True) self.scrollWindow.add(self.tree_view) settings.box.add(self.scrollWindow) self.socket_box = Gtk.Box() self.socket_box.override_background_color(Gtk.StateFlags.NORMAL, Gdk.RGBA(0, 0, 0, 1)) page.pack_start(self.socket_box, True, True, 0) self.current_name = self.settings.get_string("screensaver-name") if self.current_name == "*****@*****.**": self.current_name = self.settings.get_string("screensaver-webkit-theme") iter = self.model.append(["", _("Blank screen"), _("Blank screen"), "", "default"]) if self.current_name == "": self.tree_view.get_selection().select_iter(iter) self.on_row_activated(self.tree_view, self.model.get_path(iter), None) dirs = [os.path.expanduser("~/.local/share/cinnamon-screensaver/screensavers")] + \ [os.path.join(x, "cinnamon-screensaver/screensavers/") for x in GLib.get_system_data_dirs()] things = [] for directory in dirs: if not os.path.isdir(directory): continue things += [os.path.join(directory, x) for x in os.listdir(directory)] for path in things: if not os.path.isdir(path): continue # Recurse inside if it is webkit if os.path.basename(path.rstrip('/')) == "*****@*****.**": webkits = [os.path.join(path, x) for x in os.listdir(path)] for theme in webkits: if os.path.basename(theme) == 'main': self.webkit_executable = theme continue if not os.path.isdir(theme): continue self.parse_dir(theme, path, "webkit") continue if os.path.basename(path.rstrip('/')) == "*****@*****.**": if os.path.exists(os.path.join(path, 'main')): self.xscreensaver_executable = os.path.join(path, 'main') if self.xscreensaver_executable is not None: for theme in sorted(os.listdir("/usr/lib/xscreensaver")): iter = self.model.append([theme, "Xscreensaver: %s" % theme.capitalize(), theme, theme, "xscreensaver"]) self.parse_dir(path, path, "standalone") self.socket_box.connect("map", lambda x: self.on_row_activated(None, None, None)) # Settings page = SettingsPage() self.sidePage.stack.add_titled(page, "settings", _("Settings")) settings = page.add_section(_("Lock settings")) size_group = Gtk.SizeGroup.new(Gtk.SizeGroupMode.HORIZONTAL) widget = GSettingsSwitch(_("Lock the computer when put to sleep"), "org.cinnamon.settings-daemon.plugins.power", "lock-on-suspend") widget.set_tooltip_text(_("Enable this option to require a password when the computer wakes up from suspend")) settings.add_row(widget) widget = GSettingsSwitch(_("Lock the computer when the screen turns off"), schema, "lock-enabled") widget.set_tooltip_text(_("Enable this option to require a password when the screen turns itself off, or when the screensaver activates after a period of inactivity")) settings.add_row(widget) widget = GSettingsComboBox(_("Delay before locking the screen"), schema, "lock-delay", LOCK_DELAY_OPTIONS, valtype="uint", size_group=size_group) widget.set_tooltip_text(_("This option defines the amount of time to wait before locking the screen, after showing the screensaver or after turning off the screen")) settings.add_reveal_row(widget, schema, "lock-enabled") widget = GSettingsComboBox(_("Lock the computer when inactive"), "org.cinnamon.desktop.session", "idle-delay", LOCK_INACTIVE_OPTIONS, valtype="uint", size_group=size_group) widget.set_tooltip_text(_("This option defines the amount of time to wait before locking the screen, when the computer is not being used")) settings.add_row(widget) settings = page.add_section(_("Away message")) widget = GSettingsEntry(_("Show this message when the screen is locked"), schema, "default-message") widget.set_child_packing(widget.content_widget, True, True, 0, Gtk.PackType.START) widget.set_tooltip_text(_("This is the default message displayed on your lock screen")) settings.add_row(widget) settings.add_row(GSettingsFontButton(_("Font"), "org.cinnamon.desktop.screensaver", "font-message")) widget = GSettingsSwitch(_("Ask for a custom message when locking the screen from the menu"), schema, "ask-for-away-message") widget.set_tooltip_text(_("This option allows you to type a message each time you lock the screen from the menu")) settings.add_row(widget) # Date page = SettingsPage() self.sidePage.stack.add_titled(page, "date", _("Date")) settings = page.add_section(_("Date and Time")) size_group = Gtk.SizeGroup.new(Gtk.SizeGroupMode.HORIZONTAL) widget = GSettingsSwitch(_("Use a custom date and time format"), schema, "use-custom-format") settings.add_row(widget) widget = GSettingsEntry(_("Time Format"), schema, "time-format", size_group=size_group) settings.add_reveal_row(widget, schema, "use-custom-format") widget = GSettingsEntry(_("Date Format: "), schema, "date-format", size_group=size_group) settings.add_reveal_row(widget, schema, "use-custom-format") widget = GSettingsFontButton(_("Time Font"), "org.cinnamon.desktop.screensaver", "font-time", size_group=size_group) settings.add_row(widget) widget = GSettingsFontButton(_("Date Font"), "org.cinnamon.desktop.screensaver", "font-date", size_group=size_group) settings.add_row(widget)
def gather_screensavers(self): row = ScreensaverRow("", _("Screen Locker"), _("The standard cinnamon lock screen"), "", "default") self.add_row(row) if self.current_name == "": self.list_box.select_row(row) dirs = [os.path.expanduser("~/.local/share/cinnamon-screensaver/screensavers")] + \ [os.path.join(x, "cinnamon-screensaver/screensavers/") for x in GLib.get_system_data_dirs()] things = [] for directory in dirs: if not os.path.isdir(directory): continue things += [os.path.join(directory, x) for x in os.listdir(directory)] for path in things: if not os.path.isdir(path): continue # Recurse inside if it is webkit if os.path.basename(path.rstrip('/')) == "*****@*****.**": webkits = [os.path.join(path, x) for x in os.listdir(path)] for theme in webkits: if os.path.basename(theme) == 'main': self.webkit_executable = theme continue if not os.path.isdir(theme): continue self.parse_dir(theme, path, "webkit") continue if os.path.basename(path.rstrip('/')) == "*****@*****.**": if os.path.exists(os.path.join(path, 'main')): self.xscreensaver_executable = os.path.join(path, 'main') continue self.parse_dir(path, path, "standalone") if self.xscreensaver_executable is not None and os.path.exists(XSCREENSAVER_PATH): xscreensavers = [] try: gettext.install("xscreensaver", "/usr/share/locale") for item in sorted(os.listdir(XSCREENSAVER_PATH)): if not item.endswith(".xml"): continue path = os.path.join(XSCREENSAVER_PATH, item) try: tree = ElementTree.parse(path); root = tree.getroot() name = root.attrib["name"] label = root.attrib["_label"] description = root.find("_description").text.strip() label = _(label) description = _(description) row = ScreensaverRow(name, label, description, XSCREENSAVER_PATH, "xscreensaver") xscreensavers.append(row) except Exception, detail: print "Unable to parse xscreensaver information at %s: %s" % (path, detail) xscreensavers = sorted(xscreensavers, key=lambda x: x.name) for xscreensaver in xscreensavers: self.add_row(xscreensaver) if self.current_name == "xscreensaver-" + xscreensaver.uuid: self.list_box.select_row(xscreensaver) gettext.install("cinnamon", "/usr/share/locale") except Exception, detail: print "Unable to parse xscreensaver hacks: %s" % detail
for source in glob.iglob(os.path.join('i18n', '*.po')): code, _, _ = os.path.basename(source).rpartition('.') output = os.path.join('locale', code, 'LC_MESSAGES') if not os.path.exists(output): os.makedirs(output) output = os.path.join(output, NAME + '.mo') subprocess.call(('msgfmt', '-o', output, source)) path = os.path.join('autostart', 'pointer-config.desktop') subprocess.call(('intltool-merge', '-d', 'i18n', path + '.in', path)) path = os.path.join('applications', 'pointer-config.desktop') subprocess.call(('intltool-merge', '-d', 'i18n', path + '.in', path)) except OSError: sys.exit('msgfmt or intltool-merge missing') conf = filter(GLib.path_is_absolute, GLib.get_system_config_dirs())[0] data = filter(GLib.path_is_absolute, GLib.get_system_data_dirs())[0] data_file = list() append = lambda d, f: data_file.append(('/'.join(d), ('/'.join(f),))) for path in glob.iglob(os.path.join('locale', '*', 'LC_MESSAGES')): append((data, path), (path, NAME + '.mo')) append((conf, 'autostart'), ('autostart', NAME + '.desktop')) append((data, 'applications'), ('applications', NAME + '.desktop')) append((data, 'doc', NAME), ('COPYING',)) append((data, 'doc', NAME), ('README',)) append((data, 'glib-2.0/schemas'), ('Pointer.Config.gschema.xml',)) append((data, NAME), (NAME, NAME + '.glade')) setup( name=NAME, version='0.0.2',
def startup(self, application): self.display = Gdk.Display.get_default() self.manager = self.display.get_device_manager() self.screen = Gdk.Screen.get_default() # device-added works in Gdk_test.py but not here # self.manager.connect('device-added', self.device_changed) # self.manager.connect('device-changed', self.device_changed) self.screen.connect("monitors-changed", self.monitors_changed) self.screen.connect("size-changed", self.reset_outline) name = "pointer-config" alt = [GLib.get_user_data_dir()] + list(GLib.get_system_data_dirs()) alt = filter(GLib.path_is_absolute, alt) path = [GLib.build_filenamev((p, "locale")) for p in alt] path = [p for p in path if gettext.find(name, p)] + [None] gettext.bindtextdomain(name, path[0]) gettext.textdomain(name) gettext.install(name, path[0]) _ = gettext.lgettext GLib.set_application_name(_("Pointer Config")) for sub in alt: builder = Gtk.Builder() builder.set_translation_domain(name) path = GLib.build_filenamev((sub, name, name + ".glade")) try: builder.add_from_file(path) break except GLib.GError: pass else: sys.exit("failed to load " + name + ".glade") builder.connect_signals(self) self.outline = Outline() obj = ( "window_main", "store_type", "combo_rotation", "store_rotation", "check_left", "spin_left", "check_top", "spin_top", "check_width", "spin_width", "check_height", "spin_height", "button_cursor", "radio_absolute", "radio_relative", "tree_properties", "store_properties", "column_properties", "text_properties", "selection_properties", "grid_options", "check_auto", "check_outline", "button_colour", "spin_size", "button_apply", "dialog_about", "menu_status", ) for name in obj: setattr(self, name, builder.get_object(name)) path = "/pointer-config/" self.settings = Gio.Settings(application.get_application_id(), path) param = dict() for key, _ in self.store_type: child = self.settings.get_child(key) if child.get_boolean("auto"): param[key] = get_params(child) call_xinput(self.manager.list_devices(Gdk.DeviceType.SLAVE), param) self.add_window(self.window_main)
from . foggerconfig import get_data_file, get_data_path from . consts import DEFAULT_APP_ICON __all__ = ('FogApp', 'FogAppManager',) op = os.path logger = logging.getLogger('fogger_lib') USER_DATA_DIR = GLib.get_user_data_dir() DESKTOP_DIR = op.join(USER_DATA_DIR, 'applications') CONF_PATH = op.join(GLib.get_user_config_dir(), 'fogger') CACHE_PATH = op.join(GLib.get_user_cache_dir(), 'fogger') AUTOSTART_PATH = op.join(GLib.get_user_config_dir(), 'autostart') USER_ICON_PATH = op.join(USER_DATA_DIR, 'icons') BASE_APP_PATHS = [USER_DATA_DIR, get_data_path()] BASE_APP_PATHS += list(GLib.get_system_data_dirs()) APP_PATHS = [op.join(P, 'fogapps') for P in BASE_APP_PATHS] USER_APP_PATH = op.join(GLib.get_user_data_dir(), 'fogapps') class FogApp(object): name = None url = None icon = None uuid = None path = '' _window_size = (1024, 768) _maximized = False __style_cache = __script_cache = '' DEBUG = False
def getItemPath(file_id): for path in GLib.get_system_data_dirs(): file_path = os.path.join(path, 'applications', file_id) if os.path.isfile(file_path): return file_path return None
def _get_desktop_files(self): dirs = [gtweak.DATA_DIR, GLib.get_user_data_dir()] dirs.extend(GLib.get_system_data_dirs()) return [os.path.join(d, "applications", self.desktop_filename) for d in dirs]
def getDirectoryPath(file_id): for path in GLib.get_system_data_dirs(): file_path = os.path.join(path, 'desktop-directories', file_id) if os.path.isfile(file_path): return file_path return None