def _cache_database(): global globs, magic, aliases, inheritance, _cache_uptodate _cache_uptodate = True aliases = {} # Maps alias Mime types to canonical names inheritance = defaultdict(set) # Maps to sets of parent mime types. # Load aliases for path in BaseDirectory.load_data_paths(os.path.join("mime", "aliases")): with open(path, "r") as f: for line in f: alias, canonical = line.strip().split(None, 1) aliases[alias] = canonical # Load filename patterns (globs) globs = GlobDB() for path in BaseDirectory.load_data_paths(os.path.join("mime", "globs2")): globs.merge_file(path) globs.finalise() # Load magic sniffing data magic = MagicDB() for path in BaseDirectory.load_data_paths(os.path.join("mime", "magic")): magic.merge_file(path) magic.finalise() # Load subclasses for path in BaseDirectory.load_data_paths(os.path.join("mime", "subclasses")): with open(path, "r") as f: for line in f: sub, parent = line.strip().split(None, 1) inheritance[sub].add(parent)
def _cache_database(): global globs, magic, aliases, inheritance, _cache_uptodate _cache_uptodate = True aliases = {} # Maps alias Mime types to canonical names inheritance = defaultdict(set) # Maps to sets of parent mime types. # Load aliases for path in BaseDirectory.load_data_paths(os.path.join('mime', 'aliases')): with open(path, 'r') as f: for line in f: alias, canonical = line.strip().split(None, 1) aliases[alias] = canonical # Load filename patterns (globs) globs = GlobDB() for path in BaseDirectory.load_data_paths(os.path.join('mime', 'globs2')): globs.merge_file(path) globs.finalise() # Load magic sniffing data magic = MagicDB() for path in BaseDirectory.load_data_paths(os.path.join('mime', 'magic')): magic.merge_file(path) magic.finalise() # Load subclasses for path in BaseDirectory.load_data_paths( os.path.join('mime', 'subclasses')): with open(path, 'r') as f: for line in f: sub, parent = line.strip().split(None, 1) inheritance[sub].add(parent)
def _cache_database(): global exts, globs, literals, magic, aliases, inheritance, _cache_uptodate _cache_uptodate = True exts = {} # Maps extensions to types globs = [] # List of (glob, type) pairs literals = {} # Maps literal names to types aliases = {} # Maps alias Mime types to canonical names inheritance = defaultdict(set) # Maps to sets of parent mime types. magic = MagicDB() def _import_glob_file(path): """Loads name matching information from a MIME directory.""" with open(path) as f: for line in f: if line.startswith('#'): continue line = line[:-1] type_name, pattern = line.split(':', 1) mtype = lookup(type_name) if pattern.startswith('*.'): rest = pattern[2:] if not ('*' in rest or '[' in rest or '?' in rest): if rest not in exts: exts[rest] = mtype continue if '*' in pattern or '[' in pattern or '?' in pattern: globs.append((pattern, mtype)) else: literals[pattern] = mtype for path in BaseDirectory.load_data_paths(os.path.join('mime', 'globs')): _import_glob_file(path) for path in BaseDirectory.load_data_paths(os.path.join('mime', 'magic')): magic.mergeFile(path) # Sort globs by length globs.sort(key=lambda x: len(x[0])) # Load aliases for path in BaseDirectory.load_data_paths(os.path.join('mime', 'aliases')): with open(path, 'r') as f: for line in f: alias, canonical = line.strip().split(None, 1) aliases[alias] = canonical # Load subclasses for path in BaseDirectory.load_data_paths( os.path.join('mime', 'subclasses')): with open(path, 'r') as f: for line in f: sub, parent = line.strip().split(None, 1) inheritance[sub].add(parent)
def _cache_database(): global exts, globs, literals, magic, aliases, inheritance, _cache_uptodate _cache_uptodate = True exts = {} # Maps extensions to types globs = [] # List of (glob, type) pairs literals = {} # Maps literal names to types aliases = {} # Maps alias Mime types to canonical names inheritance = defaultdict(set) # Maps to sets of parent mime types. magic = MagicDB() def _import_glob_file(path): """Loads name matching information from a MIME directory.""" with open(path) as f: for line in f: if line.startswith('#'): continue line = line[:-1] type_name, pattern = line.split(':', 1) mtype = lookup(type_name) if pattern.startswith('*.'): rest = pattern[2:] if not ('*' in rest or '[' in rest or '?' in rest): if rest not in exts: exts[rest] = mtype continue if '*' in pattern or '[' in pattern or '?' in pattern: globs.append((pattern, mtype)) else: literals[pattern] = mtype for path in BaseDirectory.load_data_paths(os.path.join('mime', 'globs')): _import_glob_file(path) for path in BaseDirectory.load_data_paths(os.path.join('mime', 'magic')): magic.mergeFile(path) # Sort globs by length globs.sort(key=lambda x: len(x[0]) ) # Load aliases for path in BaseDirectory.load_data_paths(os.path.join('mime', 'aliases')): with open(path, 'r') as f: for line in f: alias, canonical = line.strip().split(None, 1) aliases[alias] = canonical # Load subclasses for path in BaseDirectory.load_data_paths(os.path.join('mime', 'subclasses')): with open(path, 'r') as f: for line in f: sub, parent = line.strip().split(None, 1) inheritance[sub].add(parent)
def get_load_path() -> Path: """Return the path to the database file. :return: The path to the database. :raise tp.exceptions.DatabaseNotFoundError: If the database isn't found. """ importlib.reload(BaseDirectory) for db_dir in BaseDirectory.load_data_paths(DB_FILE.parent): db_path = Path(db_dir, DB_FILE.name) if db_path.exists(): return db_path raise exceptions.DatabaseNotFoundError( 'Unable to find a database. A database should be present at one of ' 'the following paths: ' + ', '.join( (str(db_dir) for db_dir in BaseDirectory.load_data_paths(DB_FILE.parent))))
def get_data_file(filename, package=PACKAGE_NAME): """ Return path to @filename if it exists anywhere in the data paths, else raise ResourceLookupError. """ data_paths = [] try: from . import version_subst except ImportError: first_datadir = os.path.abspath("%s/../data" % (os.path.dirname(__file__))) else: first_datadir = os.path.join(version_subst.DATADIR, package) data_paths.append(first_datadir) for data_path in base.load_data_paths(package): if not data_path in data_paths: data_paths.append(data_path) for direc in data_paths: file_path = os.path.join(direc, filename) if os.path.exists(file_path): return file_path if package == PACKAGE_NAME: raise ResourceLookupError("Resource %s not found" % filename) else: raise ResourceLookupError("Resource %s in package %s not found" % (filename, package))
def get_runnable_entries(): directories = list(BaseDirectory.load_data_paths('applications')) try: cachemt = path.getmtime(dmenu_cache) except FileNotFoundError: pass else: if all(path.getmtime(directory) <= cachemt for directory in directories): with suppress(EOFError): with open(dmenu_cache, 'rb') as fp: while True: yield pickle.load(fp) return yield from cacher(sorted((entry for entry in (DesktopEntry(path.join(dirpath, filename)) for directory in directories for dirpath, _, filenames in walk(directory) for filename in filenames if filename.endswith('.desktop')) if entry.getType() == 'Application' and entry.hasKey('Exec') and 'true' not in {entry.getNoDisplay(), entry.getHidden()}), key=lambda entry: entry.getName().casefold()))
def handler_manager(self, src=None): # Activate window of running instance, if any try: screen = Wnck.Screen.get_default() screen.force_update() for window in screen.get_windows(): if window.get_class_instance_name() == "boincmgr": window.activate(time.time()) return finally: window = None screen = None Wnck.shutdown() # Launch via desktop for desktop in xdg.load_data_paths(osp.join("applications", "boinc-manager.desktop")): Gio.DesktopAppInfo.new_from_filename(desktop).launch([], None) return # Launch via executable try: subprocess.Popen(["boincmgr"], cwd="/var/lib/boinc-client") return except OSError: pass
def get_data_file(filename, package=PACKAGE_NAME): """ Return path to @filename if it exists anywhere in the data paths, else raise ResourceLookupError. """ data_paths = [] try: from . import version_subst except ImportError: first_datadir = "./data" else: first_datadir = os.path.join(version_subst.DATADIR, package) data_paths.append(first_datadir) for data_path in base.load_data_paths(package): if not data_path in data_paths: data_paths.append(data_path) for direc in data_paths: file_path = os.path.join(direc, filename) if os.path.exists(file_path): return file_path if package == PACKAGE_NAME: raise ResourceLookupError("Resource %s not found" % filename) else: raise ResourceLookupError("Resource %s in package %s not found" % (filename, package))
def get_last_end_date(workspace_id): """Retrieve the last "end date" (for report queries) for a workspace. :param workspace_id: ID of workspace to retrieve last end date for. :type workspace_id: str | int :return: Last used end date for the workspace or ``None`` if no end date has been stored yet. :rtype: None | datetime.datetime :raises OSError: If a data file exists, but cannot be read. :raises json.JSONDecodeError: If the data file is corrupt (contains invalid JSON data). :raises ValueError: If the data file is corrupt (contains invalid date which cannot be parsed). :raises OverflowError: If the data file is corrupt (contains invalid date which cannot be parsed). """ # See http://stackoverflow.com/q/1450957 workspace_id = str(workspace_id) for data_dir in BaseDirectory.load_data_paths(APP_SHORTNAME): path = os.path.join(data_dir, END_DATES_FILENAME) if not os.path.isfile(path): continue with open(path, "r") as fh: data = json.load(fh) if workspace_id in data: return dateutil.parser.parse(data[workspace_id]) # Else try the next data file. # No data files yet. return None
def on_checkautostart_toggled(self, widget): KUPFER_DESKTOP = "kupfer.desktop" AUTOSTART_KEY = "X-GNOME-Autostart-enabled" autostart_dir = base.save_config_path("autostart") autostart_file = os.path.join(autostart_dir, KUPFER_DESKTOP) if not os.path.exists(autostart_file): desktop_files = list(base.load_data_paths("applications", KUPFER_DESKTOP)) if not desktop_files: self.output_error("Installed kupfer desktop file not found!") return desktop_file_path = desktop_files[0] # Read installed file and modify it dfile = desktop.DesktopEntry(desktop_file_path) executable = dfile.getExec() ## append no-splash if "--no-splash" not in executable: executable += " --no-splash" dfile.set("Exec", executable) else: dfile = desktop.DesktopEntry(autostart_file) activestr = str(bool(widget.get_active())).lower() self.output_debug("Setting autostart to", activestr) dfile.set(AUTOSTART_KEY, activestr) ## remove the format specifiers executable = dfile.getExec().replace("%F", "") dfile.set("Exec", executable) dfile.write(filename=autostart_file)
def on_checkautostart_toggled(self, widget): KUPFER_DESKTOP = "kupfer.desktop" AUTOSTART_KEY = "X-GNOME-Autostart-enabled" autostart_dir = base.save_config_path("autostart") autostart_file = os.path.join(autostart_dir, KUPFER_DESKTOP) if not os.path.exists(autostart_file): desktop_files = list( base.load_data_paths("applications", KUPFER_DESKTOP)) if not desktop_files: self.output_error("Installed kupfer desktop file not found!") return desktop_file_path = desktop_files[0] # Read installed file and modify it dfile = desktop.DesktopEntry(desktop_file_path) executable = dfile.getExec() ## append no-splash if "--no-splash" not in executable: executable += " --no-splash" dfile.set("Exec", executable) else: dfile = desktop.DesktopEntry(autostart_file) activestr = str(bool(widget.get_active())).lower() self.output_debug("Setting autostart to", activestr) dfile.set(AUTOSTART_KEY, activestr) ## remove the format specifiers executable = dfile.getExec().replace("%F", "") dfile.set("Exec", executable) dfile.write(filename=autostart_file)
def _getXdgApplicationFiles(): """Provide a list of the application files, with full paths. Specification: http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html""" files = [] # Loop over the directories in $XDG_DATA_DIRS (essentially; see xdg doc) for directory in BaseDirectory.load_data_paths("applications"): files.extend([os.path.join(directory,filename) for filename in os.listdir(directory)]) return files
def getPrograms(): return { desktop.getName(): desktop for desktop in (DesktopEntry(dfile) for dfile in itertools.chain( *(glob(os.path.join(path, '*.desktop')) for path in BaseDirectory.load_data_paths('applications')))) if not desktop.getHidden() }
def get_previous_ads_file(): folder = next(BaseDirectory.load_data_paths(DATA_FOLDER_NAME)) files = sorted(os.listdir(folder), reverse=True) if len(files) == 0: return None newest_file = files[0] filepath = os.path.join(folder, newest_file) return filepath
def find_desktop_entry(cmd): desktop_files = [] desktop_dirs = list(BaseDirectory.load_data_paths('applications')) for d in desktop_dirs: desktop_files += [DesktopEntry.DesktopEntry(os.path.join(d, name)) for name in os.listdir(d) if name.endswith(".desktop")] matches = [entry for entry in desktop_files if cmd.lower() in entry.getName().lower()] return matches[0]
def getPrograms(): return { name + ((" - " + generic) if generic else ""): desktop for name, generic, desktop in ( (desktop.getName(), desktop.getGenericName(), desktop) for desktop in (DesktopEntry(dfile) for dfile in itertools.chain( *(glob(os.path.join(path, '*.desktop')) for path in BaseDirectory.load_data_paths('applications')))) if not desktop.getHidden()) }
def app_data_directory(name): ''' Get the root application data directory. Look for sibling data folder to detect non installed run ''' path = os.path.abspath(os.path.join(os.path.dirname(__file__),'..', 'data')) if (os.path.exists(path)): return path else: paths = BaseDirectory.load_data_paths(name) return paths[0]
def _generic(): entries = OrderedDict() seen = set() for mapps in itertools.chain(BaseDirectory.load_data_paths("applications/mimeapps.list"), BaseDirectory.load_data_paths("applications/defaults.list")): if mapps in seen: continue seen.add(mapps) with open(mapps) as mf: for l in mf: if l.startswith(mimetype): filenames = l.split("=")[1].strip().split(";") for dfile in filenames: if dfile: dpath = BaseDirectory.load_data_paths("applications", dfile) dpath = list(dpath) if dpath: entry = DesktopEntry.DesktopEntry(dpath[0]) entries[dfile] = entry return entries.values()
def installed() -> Mapping[str, Path]: """Get currently installed datasets. :return: A mapping in the form ``{dataset_name: dataset_path}``. """ result = {} importlib.reload(BaseDirectory) for datasets_dir in BaseDirectory.load_data_paths(DATASETS_DIR): for dataset_dir in Path(datasets_dir).glob('*'): result[dataset_dir.name] = dataset_dir return result
def getPrograms(): return { desktop.getName() : desktop for desktop in ( DesktopEntry(dfile) for dfile in itertools.chain(*( glob(os.path.join(path, '*.desktop')) for path in BaseDirectory.load_data_paths('applications') )) ) if not desktop.getHidden() }
def _get_xdg_application_files(self): """Provide a list of the application files, with full paths. Specification: http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html""" files = [] # Loop over the directories in $XDG_DATA_DIRS (essentially; see xdg doc for info) for directory in BaseDirectory.load_data_paths("applications"): files.extend([os.path.join(directory,filename) for filename in os.listdir(directory)]) return files
def getPrograms(): return { name + ((" - " + generic) if generic else ""): desktop for name, generic, desktop in ( (desktop.getName(), desktop.getGenericName(), desktop) for desktop in ( DesktopEntry(dfile) for dfile in itertools.chain(*( glob(os.path.join(path, '*.desktop')) for path in BaseDirectory.load_data_paths('applications') )) ) if not desktop.getHidden() ) }
def _load(self): "Loads comment for current language. Use get_comment() instead." resource = os.path.join('mime', self.media, self.subtype + '.xml') for path in BaseDirectory.load_data_paths(resource): doc = minidom.parse(path) if doc is None: continue for comment in doc.documentElement.getElementsByTagNameNS(FREE_NS, 'comment'): lang = comment.getAttributeNS(XML_NAMESPACE, 'lang') or 'en' goodness = 1 + (lang in xdg.Locale.langs) if goodness > self._comment[0]: self._comment = (goodness, _get_node_data(comment)) if goodness == 2: return
def install_path(self): """Return the path to where this dataset is installed. :return: The path to where this dataset is installed. :raise movie_recommender.exceptions.DatasetAbsentError: If the dataset is not installed. """ for data_dir in BaseDirectory.load_data_paths(XDG_RESOURCE): candidate_path = os.path.join(data_dir, self.name) if os.path.exists(candidate_path): return candidate_path raise exceptions.DatasetAbsentError( f'Dataset {self.name} is not installed.')
def get_applications(self): """Returns a dictionary object for each application""" result = {} datadirs = list(BaseDirectory.load_data_paths('applications')) for application in self.apps: for datadir in datadirs: filename = os.path.join(datadir, application) if os.path.exists(filename): desktop_entry = DesktopEntry.DesktopEntry(filename) break else: desktop_entry = None result[application] = desktop_entry return result
def _load(self): "Loads comment for current language. Use get_comment() instead." resource = os.path.join('mime', self.media, self.subtype + '.xml') for path in BaseDirectory.load_data_paths(resource): doc = minidom.parse(path) if doc is None: continue for comment in doc.documentElement.getElementsByTagNameNS( FREE_NS, 'comment'): lang = comment.getAttributeNS(XML_NAMESPACE, 'lang') or 'en' goodness = 1 + (lang in xdg.Locale.langs) if goodness > self._comment[0]: self._comment = (goodness, _get_node_data(comment)) if goodness == 2: return
def install_path(self) -> Path: """Return the path to where this dataset is installed. :return: The path to where this dataset is installed. :raise tp.exceptions.DatasetNotFoundError: If the dataset is not installed. """ importlib.reload(BaseDirectory) for datasets_dir in BaseDirectory.load_data_paths(DATASETS_DIR): candidate_path = Path(datasets_dir, self.name) if candidate_path.exists(): return candidate_path raise exceptions.DatasetNotFoundError( f"Dataset {self.name} isn't installed.")
def _gnome(): proc = subprocess.Popen(["gvfs-mime", "--query", mimetype], stdout=subprocess.PIPE) res = proc.communicate()[0].decode().splitlines() entries = itertools.takewhile(lambda s: s[0] in " \t" and s.endswith(".desktop"), res[2:]) entries = [s.strip() for s in entries] for i, entry in enumerate(entries): if entry.startswith("kde4-"): entries[i] = "kde4/" + entry[5:] entries = map(lambda s: next(BaseDirectory.load_data_paths( "applications/" + s)), entries) entries = map(DesktopEntry.DesktopEntry, entries) return entries
def get_data_file(filename): """ Return path to @filename if it exists anywhere in the data paths, else return None """ # Add "./data" in workdir for running from builddir data_paths = [] data_paths.append("./data") data_paths.extend(base.load_data_paths(PACKAGE_NAME)) for direc in data_paths: file_path = os.path.join(direc, filename) if os.path.exists(file_path): return file_path return None
def get_icon(name): def add_icon_search_path(path): current = QIcon.themeSearchPaths() if path not in current: current.append(path) QIcon.setThemeSearchPaths(current) # default search path doesn't seem to include XDG_DATA_HOME for path in xbd.load_data_paths('icons'): add_icon_search_path(path) # XDG will hardcode /usr* without ever considering virtualenvs # sys.prefix may refer to the virtualenv, so let's look there too add_icon_search_path(os.path.join(sys.prefix, 'share', 'icons')) return QIcon.fromTheme(name)
def get_load_path(): """Return the path to Movie Recommender's database. :return: The path to the database, if it is found. :raises movie_recommender.exceptions.DatabaseNotFoundError: If no database is found. """ for db_dir in BaseDirectory.load_data_paths(XDG_RESOURCE): db_path = Path(db_dir, DB_NAME) if db_path.exists(): return str(db_path) raise exceptions.DatabaseNotFoundError( 'Movie Recommender is unable to find a database. A database should be ' 'present at one of the following paths: ' + ', '.join((str(Path(db_dir, XDG_RESOURCE, DB_NAME)) for db_dir in BaseDirectory.xdg_config_dirs)))
def list_icon_themes(): themes = OrderedDict() dirs = BaseDirectory.load_data_paths("icons") seen = set() for d in dirs: if d in seen: continue seen.add(d) thlist = os.listdir(d) for th in thlist: idx = os.path.join(d, th, "index.theme") if os.path.exists(idx): ini = IniFile.IniFile(idx) if (ini.hasGroup("Icon Theme") and ini.hasKey("Directories", "Icon Theme") and not ini.get("Hidden", group="Icon Theme") == "true"): themes[th] = ini return sorted(themes.keys())
def shinah(): fore = list() for grant in BaseDirectory.load_data_paths(r'vim'): fore.append(grant) # print >> stderr, ('%02u entries' % len(fore)) if len(fore) == 1: zop = re.compile(r'^' + fore[0] + '/vim[^/]+$') for sd, d, f in os.walk(fore[0] , topdown = True): # if sd.endswith('lang'): break if len(d) >= 12: print >> stderr, ('%s is likely parent, looking at %s' % (sd,d)) fore.append(sd) elif sd != fore[0]: print >> stderr, ('%s is not a version-dir, skipping' % sd) d[:] = [dir for dir in d if (dir == fore[0] or zop.search(os.path.join(sd,dir)))] # print >> stderr, ('Remaining: %s' % d) return fore
def set_autostart(active): AUTOSTART_KEY = "X-GNOME-Autostart-enabled" autostart_dir = base.save_config_path("autostart") autostart_file = os.path.join(autostart_dir, REDSHIFT_DESKTOP) if not os.path.exists(autostart_file): desktop_files = list(base.load_data_paths("applications", REDSHIFT_DESKTOP)) if not desktop_files: raise IOError("Installed redshift desktop file not found!") return desktop_file_path = desktop_files[0] # Read installed file and modify it dfile = desktop.DesktopEntry(desktop_file_path) else: dfile = desktop.DesktopEntry(autostart_file) activestr = str(bool(active)).lower() # print "Setting autostart to %s" % activestr dfile.set(AUTOSTART_KEY, activestr) dfile.write(filename=autostart_file)
def set_autostart(active): AUTOSTART_KEY = "X-GNOME-Autostart-enabled" autostart_dir = base.save_config_path("autostart") autostart_file = os.path.join(autostart_dir, REDSHIFT_DESKTOP) if not os.path.exists(autostart_file): desktop_files = list( base.load_data_paths("applications", REDSHIFT_DESKTOP)) if not desktop_files: raise IOError("Installed redshift desktop file not found!") return desktop_file_path = desktop_files[0] # Read installed file and modify it dfile = desktop.DesktopEntry(desktop_file_path) else: dfile = desktop.DesktopEntry(autostart_file) activestr = str(bool(active)).lower() # print "Setting autostart to %s" % activestr dfile.set(AUTOSTART_KEY, activestr) dfile.write(filename=autostart_file)
def load_plugins (self, config): for p in config: plugin_paths = list (bd.load_data_paths ('river', p['name'] + '.py')) if not plugin_paths: continue m = imp.load_source('river-plugins-' + p['name'], plugin_paths[0]) self.plugins[p['name']] = {} self.plugins[p['name']]['new_entry'] = m.new_entry self.plugins[p['name']]['download_started'] = m.download_started self.plugins[p['name']]['download_complete'] = m.download_complete self.plugins[p['name']]['download_update'] = m.download_update self.plugins[p['name']]['download_error'] = m.download_error self.plugins[p['name']]['shutdown'] = m.shutdown self.plugins[p['name']]['data'] = {'config': p['config']} m.init (self.plugins[p['name']]['data'])
def get_xdg_file(): """ Obtain the desktop entry file with the configuration about this indicator :return: """ autostart_dir = base.save_config_path("autostart") autostart_file = os.path.join(autostart_dir, "indicator-bitcoin.desktop") if not os.path.exists(autostart_file): desktop_files = list( base.load_data_paths("applications", "indicator-bitcoin.desktop")) if len(desktop_files) == 0 or not os.path.exists(desktop_files[0]): return None, None copyfile(desktop_files[0], autostart_file) return desktop.DesktopEntry(autostart_file), autostart_file
def __init__(self, folder): """Find a folder from the settings""" self.folder = folder # Get info from the settings schema folder_path = PATH_FOLDER.format(folder=folder) self.settings = Gio.Settings.new_with_path(schema_id=SCHEMA_FOLDER, path=folder_path) self.name = self.settings.get_string(OPTION_FOLDER_NAME) self.translate = self.settings.get_boolean(OPTION_FOLDER_TRANSLATE) self.apps = self.settings.get_strv(OPTION_FOLDER_APPS) self.categories = self.settings.get_strv(OPTION_FOLDER_CATEGORIES) self.desktop_entry = None # Find desktop directory file if self.name.endswith('.directory'): datadirs = BaseDirectory.load_data_paths('desktop-directories') for datadir in datadirs: filename = os.path.join(datadir, self.name) if os.path.exists(filename): self.desktop_entry = DesktopEntry.DesktopEntry(filename) break
def _merge_remote_with_local(self, remote_skills): """Merge the skills found in the repo with those installed locally.""" all_skills = [] skill_dirs = [] for directory in BaseDirectory.load_data_paths('mycroft/skills'): # Make sure we don't add the XDG save data path twice if directory != self.skills_dir: skill_dirs.append(directory) skill_dirs.append(self.skills_dir) for skills_dir in skill_dirs: for skill_file in glob(path.join(skills_dir, '*', '__init__.py')): skill = SkillEntry.from_folder(path.dirname(skill_file), msm=self, use_cache=False) if skill.id in remote_skills: skill.attach(remote_skills.pop(skill.id)) all_skills.append(skill) all_skills.extend(remote_skills.values()) return all_skills
def get_autostart(): AUTOSTART_KEY = "X-GNOME-Autostart-enabled" autostart_dir = base.save_config_path("autostart") autostart_file = os.path.join(autostart_dir, REDSHIFT_DESKTOP) if not os.path.exists(autostart_file): desktop_files = list( base.load_data_paths("applications", REDSHIFT_DESKTOP)) if not desktop_files: raise IOError("Installed redshift desktop file not found!") desktop_file_path = desktop_files[0] # Read installed file and modify it dfile = desktop.DesktopEntry(desktop_file_path) dfile.set(AUTOSTART_KEY, "false") dfile.write(filename=autostart_file) return False else: dfile = desktop.DesktopEntry(autostart_file) if dfile.get(AUTOSTART_KEY) == 'false': return False else: return True
def get_autostart(): AUTOSTART_KEY = "X-GNOME-Autostart-enabled" autostart_dir = base.save_config_path("autostart") autostart_file = os.path.join(autostart_dir, REDSHIFT_DESKTOP) if not os.path.exists(autostart_file): desktop_files = list(base.load_data_paths("applications", REDSHIFT_DESKTOP)) if not desktop_files: raise IOError("Installed redshift desktop file not found!") desktop_file_path = desktop_files[0] # Read installed file and modify it dfile = desktop.DesktopEntry(desktop_file_path) dfile.set(AUTOSTART_KEY, "false") dfile.write(filename=autostart_file) return False else: dfile = desktop.DesktopEntry(autostart_file) if dfile.get(AUTOSTART_KEY) == 'false': return False else: return True
def install_mime_info(application, package_file): """Copy 'package_file' as ``~/.local/share/mime/packages/<application>.xml.`` If package_file is None, install ``<app_dir>/<application>.xml``. If already installed, does nothing. May overwrite an existing file with the same name (if the contents are different)""" application += '.xml' with open(package_file) as f: new_data = f.read() # See if the file is already installed package_dir = os.path.join('mime', 'packages') resource = os.path.join(package_dir, application) for x in BaseDirectory.load_data_paths(resource): try: with open(x) as f: old_data = f.read() except: continue if old_data == new_data: return # Already installed global _cache_uptodate _cache_uptodate = False # Not already installed; add a new copy # Create the directory structure... new_file = os.path.join(BaseDirectory.save_data_path(package_dir), application) # Write the file... with open(new_file, 'w') as f: f.write(new_data) # Update the database... command = 'update-mime-database' if os.spawnlp(os.P_WAIT, command, command, BaseDirectory.save_data_path('mime')): os.unlink(new_file) raise Exception("The '%s' command returned an error code!\n" \ "Make sure you have the freedesktop.org shared MIME package:\n" \ "http://standards.freedesktop.org/shared-mime-info/" % command)
def install_mime_info(application, package_file): """Copy 'package_file' as ``~/.local/share/mime/packages/<application>.xml.`` If package_file is None, install ``<app_dir>/<application>.xml``. If already installed, does nothing. May overwrite an existing file with the same name (if the contents are different)""" application += '.xml' new_data = open(package_file).read() # See if the file is already installed package_dir = os.path.join('mime', 'packages') resource = os.path.join(package_dir, application) for x in BaseDirectory.load_data_paths(resource): try: old_data = open(x).read() except: continue if old_data == new_data: return # Already installed global _cache_uptodate _cache_uptodate = False # Not already installed; add a new copy # Create the directory structure... new_file = os.path.join(BaseDirectory.save_data_path(package_dir), application) # Write the file... open(new_file, 'w').write(new_data) # Update the database... command = 'update-mime-database' if os.spawnlp(os.P_WAIT, command, command, BaseDirectory.save_data_path('mime')): os.unlink(new_file) raise Exception("The '%s' command returned an error code!\n" \ "Make sure you have the freedesktop.org shared MIME package:\n" \ "http://standards.freedesktop.org/shared-mime-info/" % command)
def open_autostart_file(): autostart_dir = base.save_config_path("autostart") autostart_file = os.path.join(autostart_dir, REDSHIFT_DESKTOP) if not os.path.exists(autostart_file): desktop_files = list(base.load_data_paths("applications", REDSHIFT_DESKTOP)) if not desktop_files: raise IOError("Installed redshift desktop file not found!") desktop_file_path = desktop_files[0] # Read installed file dfile = desktop.DesktopEntry(desktop_file_path) for key, values in AUTOSTART_KEYS: dfile.set(key, values[False]) dfile.write(filename=autostart_file) else: dfile = desktop.DesktopEntry(autostart_file) return dfile, autostart_file
def open_autostart_file(): autostart_dir = base.save_config_path("autostart") autostart_file = os.path.join(autostart_dir, REDSHIFT_DESKTOP) if not os.path.exists(autostart_file): desktop_files = list( base.load_data_paths("applications", REDSHIFT_DESKTOP)) if not desktop_files: raise IOError("Installed redshift desktop file not found!") desktop_file_path = desktop_files[0] # Read installed file dfile = desktop.DesktopEntry(desktop_file_path) for key, values in AUTOSTART_KEYS: dfile.set(key, values[False]) dfile.write(filename=autostart_file) else: dfile = desktop.DesktopEntry(autostart_file) return dfile, autostart_file
def init(): global _converters for convertersDir in BaseDirectory.load_data_paths("mup/converters"): _converters.extend(_loadConvertersFromDir(convertersDir)) try: from .markdownconverter import MarkdownConverter _converters.append(MarkdownConverter()) except ImportError: logging.info('Failed to load internal Markdown converter, skipping.') try: from .rstconverter import RstConverter _converters.append(RstConverter()) except ImportError: logging.info('Failed to load internal rST converter, skipping.') _converters.append(HtmlConverter()) _converters.sort(key=lambda x: x.name) return _converters
def on_checkautostart_toggled(self, widget): KUPFER_DESKTOP = "kupfer.desktop" AUTOSTART_KEY = "X-GNOME-Autostart-enabled" autostart_dir = base.save_config_path("autostart") autostart_file = os.path.join(autostart_dir, KUPFER_DESKTOP) if not os.path.exists(autostart_file): desktop_files = list(base.load_data_paths("applications", KUPFER_DESKTOP)) if not desktop_files: self.output_error("Installed kupfer desktop file not found!") return desktop_file_path = desktop_files[0] # Read installed file and modify it try: dfile = desktop.DesktopEntry(desktop_file_path) except xdg_e.ParsingError, exception: pretty.print_error(__name__, exception) return executable = dfile.getExec() ## append no-splash if "--no-splash" not in executable: executable += " --no-splash" dfile.set("Exec", executable)
def on_checkautostart_toggled(self, widget): KUPFER_DESKTOP = "kupfer.desktop" AUTOSTART_KEY = "X-GNOME-Autostart-enabled" autostart_dir = base.save_config_path("autostart") autostart_file = os.path.join(autostart_dir, KUPFER_DESKTOP) if not os.path.exists(autostart_file): desktop_files = list( base.load_data_paths("applications", KUPFER_DESKTOP)) if not desktop_files: self.output_error("Installed kupfer desktop file not found!") return desktop_file_path = desktop_files[0] # Read installed file and modify it try: dfile = desktop.DesktopEntry(desktop_file_path) except xdg_e.ParsingError, exception: pretty.print_error(__name__, exception) return executable = dfile.getExec() ## append no-splash if "--no-splash" not in executable: executable += " --no-splash" dfile.set("Exec", executable)
def get_data_paths(): # Add "./data" in workdir for running from builddir data_paths = [] data_paths.append("./data") data_paths.extend(base.load_data_paths(PACKAGE_NAME)) return data_paths
import configparser from xdg import BaseDirectory from pathlib import Path global_config = Path('/etc//xdg/noterc') _xdg_first_config = BaseDirectory.load_first_config('note') if _xdg_first_config: local_config = Path(_xdg_first_config) / 'noterc' else: local_config = Path(os.path.expanduser('~/.noterc')) _xdg_data = None # Just take the first one: '$HOME/.local/share/note' if list(BaseDirectory.load_data_paths('note')): _xdg_data = list(BaseDirectory.load_data_paths('note'))[0] if _xdg_data: DATA_PATH = Path(_xdg_data) else: DATA_PATH = Path(os.path.expanduser('~/.note')) # Initialize config parser object # Read global config first, overwrite with local config config = configparser.ConfigParser() config.read([str(global_config), str(local_config)]) # fix #14 if 'data' not in config.sections(): config.add_section('data')
def get_data_dirs(name="", package=PACKAGE_NAME): """ Iterate over all data dirs of @name that exist """ return base.load_data_paths(os.path.join(package, name))
def get_resource_paths(*resources): return [path for path in BaseDirectory.load_data_paths(*resources)]
def xdg_static_folder(): for path in BaseDirectory.load_data_paths('pbs'): return path return 'static'
def get_resource_paths(self, *resources): return [p for p in BaseDirectory.load_data_paths(*resources)]