def on_checkbutton_sound_toggled(self, widget, data=None): if self.check.get_active(): # write the string True to file content = True s = str(content) # create file the filename title = "config" data_dir = GLib.get_user_data_dir() pomidor_dir = os.path.join(data_dir, "pomidor") filename = os.path.join(pomidor_dir, title) # write the data GLib.mkdir_with_parents(pomidor_dir, 0o700) GLib.file_set_contents(filename, s) else: # write the string False to file content = False s = str(content) # create file the filename title = "config" data_dir = GLib.get_user_data_dir() pomidor_dir = os.path.join(data_dir, "pomidor") filename = os.path.join(pomidor_dir, title) # write the data GLib.mkdir_with_parents(pomidor_dir, 0o700) GLib.file_set_contents(filename, s)
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 xdg_data_home(*subdirs): """Gets the directory for storing the user's data: presets, plugins, etc.""" default_base = os.path.join(GLib.get_user_data_dir(), "pitivi") base = os.getenv("PITIVI_USER_DATA_DIR", default_base) path = os.path.join(base, *subdirs) os.makedirs(path, exist_ok=True) return path
class ListStore: FILE = GLib.get_user_data_dir() + "/teatime.js" def __init__(self, obj): self._obj = obj self.load() def load(self): try: f = file(self.FILE) for t in json.load(f): self.append(t) except: pass else: f.close() def save(self): f = file(self.FILE, "w") json.dump([t[0] for t in self._obj][0:-1], f) f.close() def __getitem__(self, k): return self._obj[k][0] def __setitem__(self, k, v): self._obj[k][0] = v def append(self, v): self._obj.append((v,))
def _on_plugin_folder_btn_clicked(self, btn): folder = os.path.join(GLib.get_user_data_dir(), 'turtlico/turtlico/plugins') try: if os.path.exists(folder): if not os.path.isdir(folder): raise Exception( _('Path "{}" does exist but it is not a folder.')) else: os.makedirs(folder) except Exception as e: dialog = Gtk.MessageDialog(modal=True, transient_for=self, text=str(e), buttons=Gtk.ButtonsType.OK) def callback(dialog, reposne): dialog.close() dialog.connect('response', callback) dialog.show() return Gtk.show_uri(self, f'file://{folder}', Gdk.CURRENT_TIME)
def __init__(self, app): """Create the necessary objects and settings. Args: app: The main vimiv application to interact with. """ super().__init__(app) datadir = os.path.join(GLib.get_user_data_dir(), "vimiv") os.makedirs(datadir, exist_ok=True) self.filename = os.path.join(datadir, "vimiv.log") self.terminal = sys.stderr # Redirect stderr in debug mode so it is written to the log file as well if app.debug: sys.stderr = self # Create a new log file at startup with open(self.filename, "w") as f: f.write("Vimiv log written to " + self.filename.replace(os.getenv("HOME"), "~") + "\n") self.write_separator() # Header containing version and Gtk version information = self.get_component(Information) self.write_message("Version", information.get_version()) self.write_message("Python", sys.version.split()[0]) gtk_version = str(Gtk.get_major_version()) + "." \ + str(Gtk.get_minor_version()) + "." \ + str(Gtk.get_micro_version()) self.write_message("GTK", gtk_version) self.write_separator() # Start time self.write_message("Started", "time")
def create_launcher(game_slug, game_name, desktop=False, menu=False): """Create .desktop file.""" desktop_dir = GLib.get_user_special_dir(GLib.UserDirectory.DIRECTORY_DESKTOP) launcher_content = dedent( """ [Desktop Entry] Type=Application Name=%s Icon=%s Exec=lutris lutris:%s Categories=Game """ % (game_name, "lutris_" + game_slug, game_slug) ) launcher_filename = "%s.desktop" % game_slug tmp_launcher_path = os.path.join(CACHE_DIR, launcher_filename) tmp_launcher = open(tmp_launcher_path, "w") tmp_launcher.write(launcher_content) tmp_launcher.close() os.chmod( tmp_launcher_path, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC | stat.S_IRGRP | stat.S_IWGRP | stat.S_IXGRP ) if desktop: shutil.copy(tmp_launcher_path, os.path.join(desktop_dir, launcher_filename)) if menu: menu_path = os.path.join(GLib.get_user_data_dir(), "applications") shutil.copy(tmp_launcher_path, os.path.join(menu_path, launcher_filename)) os.remove(tmp_launcher_path)
def update_desktop_icons(): """Update Icon for GTK+ desktop manager Other desktop manager icon cache commands must be added here if needed """ if find_executable("gtk-update-icon-cache"): logger.debug("Updating GTK icon cache...") os.system("gtk-update-icon-cache -tf %s" % os.path.join(GLib.get_user_data_dir(), "icons", "hicolor"))
def on_bible_translation_changed(self, settings, key): base_file = settings.get_string("bible-translation") self.p = BibleParser(os.path.join(GLib.get_user_data_dir(), base_file)) self.p.loadAll() self.Bible = self.p.bible self.UpdateBooks()
def populate_bubble_menu(self): bubble_menu_folders = [ os.path.join(os.path.split(__file__)[0], "..", "bubbles"), os.path.join(GLib.get_user_data_dir(), "graven", "bubbles") ] bubble_files = [] for f in bubble_menu_folders: if os.path.isdir(f): bubble_files += glob.glob(os.path.join(f, "*.bubble.svg")) if not bubble_files: self.btnbubble.destroy() return bubblemenu = Gtk.Menu.new() for f in bubble_files: mi = Gtk.MenuItem.new() pb = GdkPixbuf.Pixbuf.new_from_file_at_size(f, 100, 75) mimg = Gtk.Image.new_from_pixbuf(pb) mi.add(mimg) s2c = svg2cairo.SVG2Cairo() s2c.set_svg_as_filename_async( f) # this will load in the background mi.connect("activate", self.bubble_chosen, s2c) bubblemenu.append(mi) self.btnbubble.set_popup(bubblemenu) bubblemenu.show_all() if self.img: self.btnbubble.set_sensitive(True) else: self.btnbubble.set_sensitive(False)
def install_libraries(logger=None, overwrite=True): if logger: log = logger else: log = distutils.log if GLib: user_data_folder = GLib.get_user_data_dir() else: user_data_folder = os.path.join(os.path.expanduser('~'), '.local', 'share') user_library_path = os.path.join(user_data_folder, 'rafcon', 'libraries') library_path = os.path.join(rafcon_root_path, "share", "libraries") if os.path.exists(user_library_path): if not overwrite: return try: log.info("Removing old RAFCON libraries in {}".format( user_library_path)) shutil.rmtree(user_library_path) except (EnvironmentError, shutil.Error) as e: log.error("Could not remove old RAFCON libraries in {}: {}".format( user_library_path, e)) return try: log.info("Installing RAFCON libraries to {}".format(user_library_path)) shutil.copytree(library_path, user_library_path) except (IOError, shutil.Error) as e: log.error("Could not install RAFCON libraries: {}".format(e))
def activate(self, prefsDir=None, customSettings={}): debug.println(debug.LEVEL_FINEST, 'INFO: Activating settings manager') self.customizedSettings.update(customSettings) self._prefsDir = prefsDir \ or os.path.join(GLib.get_user_data_dir(), "orca") # Load the backend and the default values self._backend = self.backendModule.Backend(self._prefsDir) self._setDefaultGeneral() self._setDefaultPronunciations() self._setDefaultKeybindings() self.general = self.defaultGeneral.copy() if not self.isFirstStart(): self.general.update(self._backend.getGeneral()) self.pronunciations = self.defaultPronunciations.copy() self.keybindings = self.defaultKeybindings.copy() # If this is the first time we launch Orca, there is no user settings # yet, so we need to create the user config directories and store the # initial default settings # self._createDefaults() debug.println(debug.LEVEL_FINEST, 'INFO: Settings manager activated') # Set the active profile and load its stored settings if self.profile is None: self.profile = self.general.get('startingProfile')[1] self.setProfile(self.profile)
def prefs_clear_data_click(self, _): self.change_button_stack_state(False) cd_dlg = Gtk.MessageDialog(buttons=Gtk.ButtonsType.YES_NO, modal=True, parent=self.application_window) cd_dlg.set_markup("<big>Warning</big>") cd_dlg.format_secondary_text( "This cannot be reversed, and will delete your secrets.\n" "The program will exit when finished.\n" "Are you sure you want to continue?") cd_resp = cd_dlg.run() if cd_resp == Gtk.ResponseType.YES: try: cache_dir = GLib.get_user_data_dir() # Remove the database os.remove(f"{cache_dir}/authwallet.db") self.settings.set_value("obscure-secrets", GLib.Variant('b', True)) self.settings.set_value("dark-theme", GLib.Variant('b', False)) # Exit the program exit() except IOError: self.display_error( "Could not remove all keys.\nThis could be a permissions error", log=False) cd_dlg.destroy() elif cd_resp == Gtk.ResponseType.NO: cd_dlg.destroy() self.hb_lstack.set_visible_child_name("hbls_back")
def install_youtube_dl(): try: path = GLib.get_user_data_dir() + "/lollypop/python" argv = ["pip3", "install", "-t", path, "-U", "youtube-dl"] GLib.spawn_sync(None, argv, [], GLib.SpawnFlags.SEARCH_PATH, None) except Exception as e: Logger.error("install_youtube_dl: %s" % e)
def finish_initializing(self, builder): """Called when we're finished initializing. finish_initalizing should be called after parsing the ui definition and creating a OpenDialog object with it in order to finish initializing the start of the new OpenDialog instance. """ # Get a reference to the builder and set up the signals. self.builder = builder self.ui = builder.get_ui(self) #get the jotty document names data_dir = GLib.get_user_data_dir() jotty_dir = os.path.join(data_dir, "jotty") filenames = os.listdir(jotty_dir) #put them into a grid dicts = [{ 'Name': x, 'File': os.path.join(jotty_dir, x) } for x in filenames] self.grid = DictionaryGrid(dictionaries=dicts, keys=['Name']) #add grid to dialog self.grid.show() self.ui.box1.pack_end(self.grid, True, True, 0)
def create_launcher(game_slug, game_id, game_name, desktop=False, menu=False): """Create a .desktop file.""" desktop_dir = ( GLib.get_user_special_dir(GLib.UserDirectory.DIRECTORY_DESKTOP) ) launcher_content = dedent( """ [Desktop Entry] Type=Application Name={} Icon={} Exec=lutris lutris:rungameid/{} Categories=Game """.format(game_name, 'lutris_{}'.format(game_slug), game_id) ) launcher_filename = get_xdg_basename(game_slug, game_id, legacy=False) tmp_launcher_path = os.path.join(CACHE_DIR, launcher_filename) tmp_launcher = open(tmp_launcher_path, "w") tmp_launcher.write(launcher_content) tmp_launcher.close() os.chmod(tmp_launcher_path, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC | stat.S_IRGRP | stat.S_IWGRP | stat.S_IXGRP) if desktop: shutil.copy(tmp_launcher_path, os.path.join(desktop_dir, launcher_filename)) if menu: menu_path = os.path.join(GLib.get_user_data_dir(), 'applications') shutil.copy(tmp_launcher_path, os.path.join(menu_path, launcher_filename)) os.remove(tmp_launcher_path)
def xdg_data_home(autocreate=True): """ Get the directory for storing the user's data: presets, plugins, etc. """ default = os.path.join(GLib.get_user_data_dir(), "pitivi") path = os.getenv("PITIVI_USER_DATA_DIR", default) return get_dir(path, autocreate)
def create_launcher(game_slug, game_id, game_name, desktop=False, menu=False): """Create a .desktop file.""" desktop_dir = ( GLib.get_user_special_dir(GLib.UserDirectory.DIRECTORY_DESKTOP) ) launcher_content = dedent( """ [Desktop Entry] Type=Application Name={} Icon={} Exec=lutris lutris:{} Categories=Game """.format(game_name, 'lutris_{}'.format(game_slug), game_id) ) launcher_filename = get_xdg_basename(game_slug, game_id, legacy=False) tmp_launcher_path = os.path.join(CACHE_DIR, launcher_filename) tmp_launcher = open(tmp_launcher_path, "w") tmp_launcher.write(launcher_content) tmp_launcher.close() os.chmod(tmp_launcher_path, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC | stat.S_IRGRP | stat.S_IWGRP | stat.S_IXGRP) if desktop: shutil.copy(tmp_launcher_path, os.path.join(desktop_dir, launcher_filename)) if menu: menu_path = os.path.join(GLib.get_user_data_dir(), 'applications') shutil.copy(tmp_launcher_path, os.path.join(menu_path, launcher_filename)) os.remove(tmp_launcher_path)
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 update_desktop_icons(): """Update Icon for GTK+ desktop manager Other desktop manager icon cache commands must be added here if needed """ gtk_update_icon_cache = system.find_executable("gtk-update-icon-cache") if gtk_update_icon_cache: os.system("gtk-update-icon-cache -tf %s" % os.path.join(GLib.get_user_data_dir(), "icons", "hicolor"))
def update_desktop_icons(): """Update Icon for GTK+ desktop manager Other desktop manager icon cache commands must be added here if needed """ if find_executable("gtk-update-icon-cache"): execute(["gtk-update-icon-cache", "-tf", os.path.join(GLib.get_user_data_dir(), "icons/hicolor")], quiet=True) execute(["gtk-update-icon-cache", "-tf", os.path.join(settings.RUNTIME_DIR, "icons/hicolor")], quiet=True)
def __init__(self): GObject.GObject.__init__(self) self.playlist_path = GLib.build_filenamev([GLib.get_user_data_dir(), "gnome-music", "playlists"]) if not (GLib.file_test(self.playlist_path, GLib.FileTest.IS_DIR)): GLib.mkdir_with_parents(self.playlist_path, int("0755", 8)) self.options = Grl.OperationOptions() self.options.set_flags(Grl.ResolutionFlags.FAST_ONLY | Grl.ResolutionFlags.IDLE_RELAY) self.full_options = Grl.OperationOptions() self.full_options.set_flags(Grl.ResolutionFlags.FULL | Grl.ResolutionFlags.IDLE_RELAY) self.sources = {} self.tracker = None self.changed_media_ids = [] self.pending_event_id = 0 self.registry = Grl.Registry.get_default() self.registry.connect('source_added', self._on_source_added) self.registry.connect('source_removed', self._on_source_removed) try: self.registry.load_all_plugins() except GLib.GError: logger.error('Failed to load plugins.') if self.tracker is not None: logger.debug("tracker found")
def finish_initializing(self, builder): """Called when we're finished initializing. finish_initalizing should be called after parsing the ui definition and creating a SettingsDialog object with it in order to finish initializing the start of the new SettingsDialog instance. """ # Get a reference to the builder and set up the signals. self.builder = builder self.ui = builder.get_ui(self) self.check = self.builder.get_object('checkbutton_sound') # Write the file first time userpath = GLib.get_user_data_dir() fullpath = userpath + "/pomidor/config" # read file and set False or True to self.check.set_active() # try to get the data from the file if it exists try: success, text = GLib.file_get_contents(fullpath) if success and text == "True": self.check.set_active(True) else: self.check.set_active(False) except Exception: print "There is no file!"
def setup_environment(): """Ensures that the environmental variable RAFCON_LIB_PATH is existent """ try: from gi.repository import GLib user_data_folder = GLib.get_user_data_dir() except ImportError: user_data_folder = join(os.path.expanduser("~"), ".local", "share") rafcon_root_path = dirname(realpath(rafcon.__file__)) user_library_folder = join(user_data_folder, "rafcon", "libraries") # The RAFCON_LIB_PATH points to a path with common RAFCON libraries # If the env variable is not set, we have to determine it. In the future, this should always be # ~/.local/share/rafcon/libraries, but for backward compatibility, also a relative RAFCON path is supported if not os.environ.get('RAFCON_LIB_PATH', None): if exists(user_library_folder): os.environ['RAFCON_LIB_PATH'] = user_library_folder else: os.environ['RAFCON_LIB_PATH'] = join(dirname(dirname(rafcon_root_path)), 'share', 'libraries') # Install dummy _ builtin function in case i18.setup_l10n() is not called if sys.version_info >= (3,): import builtins as builtins23 else: import __builtin__ as builtins23 if "_" not in builtins23.__dict__: builtins23.__dict__["_"] = lambda s: s
def get_data_dir(): data_dir_path = GLib.get_user_data_dir() # Check if inside flatpak sandbox is_flatpak = os.path.exists( os.path.join(GLib.get_user_runtime_dir(), 'flatpak-info')) if is_flatpak: return data_dir_path base_path = data_dir_path data_dir_path = os.path.join(base_path, 'komikku') if not os.path.exists(data_dir_path): os.mkdir(data_dir_path) # Until version 0.11.0, data files (chapters, database) were stored in a wrong place must_be_moved = [ 'komikku.db', 'komikku_backup.db', ] for server in get_servers_list(include_disabled=True): must_be_moved.append(server['id']) for name in must_be_moved: data_path = os.path.join(base_path, name) if os.path.exists(data_path): os.rename(data_path, os.path.join(data_dir_path, name)) return data_dir_path
def get_menu_launcher_path(game_slug, game_id): """Return the path to a XDG menu launcher, prioritizing legacy paths if they exist """ menu_dir = os.path.join(GLib.get_user_data_dir(), "applications") return os.path.join( menu_dir, get_xdg_basename(game_slug, game_id, base_dir=menu_dir))
def __init__(self, app): """Create the necessary objects. Args: app: The main vimiv application to interact with. """ super().__init__(app) self.app = app # Create tags directory self.directory = os.path.join(GLib.get_user_data_dir(), "vimiv", "Tags") os.makedirs(self.directory, exist_ok=True) # If there are tags in the old location, move them to the new one # TODO remove this in a new version, assigned for 0.10 old_directory = os.path.expanduser("~/.vimiv/Tags") if os.path.isdir(old_directory): old_tags = os.listdir(old_directory) for f in old_tags: old_path = os.path.join(old_directory, f) new_path = os.path.join(self.directory, f) os.rename(old_path, new_path) message = "Moved tags from the old directory %s " \ "to the new location %s." % (old_directory, self.directory) error_message(message, running_tests=self.app.running_tests) os.rmdir(old_directory) self.last = ""
def __init__(self) -> None: self._paths = {} # type: Dict[str, PathTuple] self.profile = '' self.profile_separation = False self.custom_config_root = None # type: Optional[Path] if os.name == 'nt': if gajim.IS_PORTABLE: application_path = Path(sys.executable).parent self.config_root = self.cache_root = self.data_root = \ application_path.parent / 'UserData' else: # Documents and Settings\[User Name]\Application Data\Gajim self.config_root = self.cache_root = self.data_root = \ Path(os.environ['appdata']) / 'Gajim' else: self.config_root = Path(GLib.get_user_config_dir()) / 'gajim' self.cache_root = Path(GLib.get_user_cache_dir()) / 'gajim' self.data_root = Path(GLib.get_user_data_dir()) / 'gajim' import pkg_resources basedir = Path(pkg_resources.resource_filename("gajim", ".")) source_paths = [ ('DATA', basedir / 'data'), ('STYLE', basedir / 'data' / 'style'), ('EMOTICONS', basedir / 'data' / 'emoticons'), ('GUI', basedir / 'data' / 'gui'), ('ICONS', basedir / 'data' / 'icons'), ('HOME', Path.home()), ('PLUGINS_BASE', basedir / 'data' / 'plugins'), ] for path in source_paths: self.add(*path)
def __init__(self): GObject.GObject.__init__(self) self.playlist_path = GLib.build_filenamev([GLib.get_user_data_dir(), "gnome-music", "playlists"]) if not (GLib.file_test(self.playlist_path, GLib.FileTest.IS_DIR)): GLib.mkdir_with_parents(self.playlist_path, int("0755", 8)) self.options = Grl.OperationOptions() self.options.set_resolution_flags(Grl.ResolutionFlags.FAST_ONLY | Grl.ResolutionFlags.IDLE_RELAY) self.full_options = Grl.OperationOptions() self.full_options.set_resolution_flags(Grl.ResolutionFlags.FULL | Grl.ResolutionFlags.IDLE_RELAY) self.sources = {} self.blacklist = ['grl-filesystem', 'grl-bookmarks', 'grl-metadata-store', 'grl-podcasts'] self.tracker = None self.changed_media_ids = [] self.pending_event_id = 0 self.changes_pending = {'Albums': False, 'Artists': False, 'Songs': False} self.pending_changed_medias = [] self.registry = Grl.Registry.get_default() self.sparqltracker = TrackerWrapper().tracker
def activate(self, prefsDir=None, customSettings={}): debug.println(debug.LEVEL_FINEST, 'INFO: Activating settings manager') self.customizedSettings.update(customSettings) self._prefsDir = prefsDir \ or os.path.join(GLib.get_user_data_dir(), "orca") # Load the backend and the default values self._backend = self.backendModule.Backend(self._prefsDir) self._setDefaultGeneral() self._setDefaultPronunciations() self._setDefaultKeybindings() self.defaultGeneralValues = getRealValues(self.defaultGeneral) self.general = self.defaultGeneralValues.copy() if not self.isFirstStart(): self.general.update(self._backend.getGeneral()) self.pronunciations = self.defaultPronunciations.copy() self.keybindings = self.defaultKeybindings.copy() # If this is the first time we launch Orca, there is no user settings # yet, so we need to create the user config directories and store the # initial default settings # self._createDefaults() debug.println(debug.LEVEL_FINEST, 'INFO: Settings manager activated') # Set the active profile and load its stored settings if self.profile is None: self.profile = self.general.get('startingProfile')[1] self.setProfile(self.profile)
def run(self): GLib.idle_add(self.parent.set_sensitive, False) GLib.idle_add(self.spinner.start) done = False fonts_folder = GLib.get_user_data_dir() + "/fonts" os.makedirs(fonts_folder, exist_ok=True) for dirname, folders, files in os.walk(self.location): for file_ in files: if file_.lower().endswith("ttf") or file_.lower().endswith( "otf") or file_.lower().endswith("fon"): file_ = os.path.join(dirname, file_) try: copy2(file_, fonts_folder) done = True except Exception as e: print(e) #GLib.idle_add(self.parent.set_sensitive,True) #return False if done: subprocess.call("chmod 755 -R {}/*".format(fonts_folder), shell=True) subprocess.call("fc-cache -fv", shell=True) GLib.idle_add(self.spinner.stop) GLib.idle_add(self.parent.set_sensitive, True) if done: if self.refresh_fuction: GLib.idle_add(self.refresh_fuction) return True
def __init__(self): super().__init__() self.playlist_path = GLib.build_filenamev( [GLib.get_user_data_dir(), "gnome-music", "playlists"]) if not (GLib.file_test(self.playlist_path, GLib.FileTest.IS_DIR)): GLib.mkdir_with_parents(self.playlist_path, int("0755", 8)) Grl.init(None) self.options = Grl.OperationOptions() self.options.set_resolution_flags(Grl.ResolutionFlags.FAST_ONLY | Grl.ResolutionFlags.IDLE_RELAY) self.full_options = Grl.OperationOptions() self.full_options.set_resolution_flags( Grl.ResolutionFlags.FULL | Grl.ResolutionFlags.IDLE_RELAY) self.sources = {} self.blacklist = [ 'grl-filesystem', 'grl-bookmarks', 'grl-metadata-store', 'grl-podcasts', 'grl-spotify-cover' ] self.tracker = None self.changed_media_ids = [] self.pending_event_id = 0 self.changes_pending = { 'Albums': False, 'Artists': False, 'Songs': False } self.pending_changed_medias = [] self.registry = Grl.Registry.get_default() self.sparqltracker = TrackerWrapper().tracker
def get_app_dir(self): user_dir = GLib.get_user_data_dir() gm_dir = user_dir + "/gitmarks" if not os.path.isdir(gm_dir): os.makedirs(gm_dir) return gm_dir
def _get_valid_key_themes(self): dirs = ( os.path.join(gtweak.DATA_DIR, "themes"), os.path.join(GLib.get_user_data_dir(), "themes"), os.path.join(os.path.expanduser("~"), ".themes")) valid = walk_directories(dirs, lambda d: os.path.isfile(os.path.join(d, "gtk-3.0", "gtk-keys.css")) and \ os.path.isfile(os.path.join(d, "gtk-2.0-key", "gtkrc"))) return valid
def _get_valid_cursor_themes(self): dirs = ( os.path.join(gtweak.DATA_DIR, "icons"), os.path.join(GLib.get_user_data_dir(), "icons"), os.path.join(os.path.expanduser("~"), ".icons")) valid = walk_directories(dirs, lambda d: os.path.isdir(d) and \ os.path.exists(os.path.join(d, "cursors"))) return valid
def _get_valid_key_themes(self): dirs = (os.path.join(gtweak.DATA_DIR, "themes"), os.path.join(GLib.get_user_data_dir(), "themes"), os.path.join(os.path.expanduser("~"), ".themes")) valid = walk_directories(dirs, lambda d: os.path.isfile(os.path.join(d, "gtk-3.0", "gtk-keys.css")) and \ os.path.isfile(os.path.join(d, "gtk-2.0-key", "gtkrc"))) return valid
def get_menu_launcher_path(game_slug, game_id): """Return the path to a XDG menu launcher, prioritizing legacy paths if they exist """ menu_dir = os.path.join(GLib.get_user_data_dir(), "applications") return os.path.join( menu_dir, get_xdg_basename(game_slug, game_id, base_dir=menu_dir) )
def _website_data_manager(self): from os import path as P print("Creating WebsiteDataManager...") app_id = self.application.get_application_id() cache_dir = P.join(GLib.get_user_cache_dir(), "revolt", app_id) data_dir = P.join(GLib.get_user_data_dir(), "revolt", app_id) return WebKit2.WebsiteDataManager(base_cache_directory=cache_dir, base_data_directory=data_dir)
def __init__(self): self.logger = logging.getLogger('Main') self.logger.setLevel(logging.DEBUG) logging_path = "{}/Noted/Main".format(GLib.get_user_data_dir()) self.handler = logging.FileHandler(logging_path) formatter = logging.Formatter('%(asctime)s - %(name)s - %(message)s') self.handler.setFormatter(formatter) self.logger.addHandler(self.handler)
def _get_valid_cursor_themes(self): dirs = (os.path.join(gtweak.DATA_DIR, "icons"), os.path.join(GLib.get_user_data_dir(), "icons"), os.path.join(os.path.expanduser("~"), ".icons")) valid = walk_directories(dirs, lambda d: os.path.isdir(d) and \ os.path.exists(os.path.join(d, "cursors"))) return valid
class GnomeShell: EXTENSION_STATE = { "ENABLED" : 1, "DISABLED" : 2, "ERROR" : 3, "OUT_OF_DATE" : 4, "DOWNLOADING" : 5, "INITIALIZED" : 6, } EXTENSION_TYPE = { "SYSTEM" : 1, "PER_USER" : 2 } DATA_DIR = os.path.join(GLib.get_user_data_dir(), "gnome-shell") EXTENSION_DIR = os.path.join(GLib.get_user_data_dir(), "gnome-shell", "extensions") def __init__(self, shellproxy, shellsettings): self._proxy = shellproxy self._settings = shellsettings def _execute_js(self, js): result, output = self._proxy.proxy.Eval('(s)', js) if not result: raise Exception(output) return output def restart(self): self._execute_js('global.reexec_self();') def reload_theme(self): self._execute_js('const Main = imports.ui.main; Main.loadTheme();') def uninstall_extension(self, uuid): pass @property def mode(self): return self._proxy.mode @property def version(self): return self._proxy.version
def _get_valid_themes(self): """ Only shows themes that have variations for gtk+-3 and gtk+-2 """ dirs = ( os.path.join(gtweak.DATA_DIR, "themes"), os.path.join(GLib.get_user_data_dir(), "themes"), os.path.join(os.path.expanduser("~"), ".themes")) valid = walk_directories(dirs, lambda d: os.path.exists(os.path.join(d, "gtk-2.0")) and \ os.path.exists(os.path.join(d, "gtk-3.0"))) return valid
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 update_desktop_icons(): """Update Icon for GTK+ desktop manager Other desktop manager icon cache commands must be added here if needed """ gtk_update_icon_cache = system.find_executable("gtk-update-icon-cache") if gtk_update_icon_cache: os.system( "gtk-update-icon-cache -tf %s" % os.path.join(GLib.get_user_data_dir(), "icons", "hicolor") )
def xdg_get_data_home(): if os.name == "nt": from gi.repository import GLib return glib2fsn(GLib.get_user_data_dir()) data_home = os.getenv("XDG_DATA_HOME") if data_home: return os.path.abspath(data_home) else: return os.path.join(os.path.expanduser("~"), ".local", "share")
def finish_initializing(self, builder): # pylint: disable=E1002 """Set up the main window""" super(PomidorWindow, self).finish_initializing(builder) self.AboutDialog = AboutPomidorDialog self.SettingsDialog = SettingsDialog # Code for other initialization actions should be added here. self.initialize_quicklist() self.timeout_id = None self.time = 0 self.minimizeonclicked = 1 self.say = Salert() self.pbutton = self.builder.get_object("pbutton") self.sbutton = self.builder.get_object("sbutton") self.lbutton = self.builder.get_object("lbutton") self.timelabel = self.builder.get_object("timelabel") # Optionally play sound userpath = GLib.get_user_data_dir() fullpath = userpath + "/pomidor/config" # plus app path # run only once when window initialized if os.path.exists(fullpath): pass else: print "No file. Create file now." # set True by deafault is sound notification enabled content = True s = str(content) # create the filename title = "config" data_dir = GLib.get_user_data_dir() pomidor_dir = os.path.join(data_dir, "pomidor") filename = os.path.join(pomidor_dir, title) # write the data GLib.mkdir_with_parents(pomidor_dir, 0o700) GLib.file_set_contents(filename, s)
def init(): global _init_error force_dot_dir = False # Get user folder locations global _dot_dir, _xdg_config_dir, _xdg_data_dir, _xdg_cache_dir # Dot folder _dot_dir = os.getenv("HOME") + "/.flowblade/" # XDG folders _xdg_config_dir = os.path.join(GLib.get_user_config_dir(), "flowblade") _xdg_data_dir = os.path.join(GLib.get_user_data_dir(), "flowblade") _xdg_cache_dir = os.path.join(GLib.get_user_cache_dir(), "flowblade") # Testing print _xdg_config_dir print _xdg_data_dir print _xdg_cache_dir # Make sure XDG dirs data is available and usable by trying to create XDG folders try: _maybe_create_xdg_dirs() except Exception as e: _init_error = "Could not create XDG folders: " + str(e) force_dot_dir = True # Determine if this a clean install or do we need to copy files fron dot dir to XDG dirs # We think existance of prefs files will tell us what the state of the system is. _dot_prefs_file_exists = os.path.exists(_dot_dir + "prefs" ) _xdg_prefs_file_exists = os.path.exists(_xdg_config_dir + "/prefs") # If previous install exits and no data in XDG dirs, we need to copy existing data. if _dot_prefs_file_exists == True and _xdg_prefs_file_exists == False: print "userfolders.init(): .flowblade/ data exists, we need to copy to XDG folders." global _copy_needed _copy_needed = True else: print "XDG user data exists." # Set folders and maybe create them global _user_dirs # If we could not create XDG dirs, we will use dot dirs if force_dot_dir == True: print "userfolders.init(): UNABLE TO CREATE XDG FOLDERS! Usinf .flowblade dir forced!" global _dot_dir_was_forced _dot_dir_was_forced = True _user_dirs = USING_DOT_DIRS _maybe_create_dot_dirs() return #_user_dirs = USING_DOT_DIRS # Testing _user_dirs = USING_XDG_DIRS
def data(filename): """Return path for storing data file with given name. Ensures the directory and file exists. """ data_path = path.join(GLib.get_user_data_dir(), "netscramble") if not path.exists(data_path): makedirs(data_path) file_path = path.join(data_path, filename) if not path.exists(file_path): f = open(file_path, "w") f.close() return file_path
def __init__(self): ant.fs.manager.Application.__init__(self) GObject.GObject.__init__(self) self.path = os.path.join(GLib.get_user_data_dir(), self.PRODUCT_NAME) utils.makedirs(self.path) self.status = Garmin.Status.NONE self.device = None self.funcs = [] self.loop = None self.timeout_source = None
def get_menu_launcher_path(game_slug, game_id): """Return the path to a XDG menu launcher, prioritizing legacy paths if they exist """ menu_dir = os.path.join(GLib.get_user_data_dir(), 'applications') menu_path = os.path.join( menu_dir, get_xdg_basename(game_slug, game_id, legacy=True) ) if system.path_exists(menu_path): return menu_path return os.path.join( menu_dir, get_xdg_basename(game_slug, game_id, legacy=False) )
def open(self): "Open the DB (if needed)" if self.db is None: doc_db_path = os.path.join(GLib.get_user_data_dir(), 'gnome-builder', 'jedi', 'girdoc.db') try: os.makedirs(os.path.dirname(doc_db_path)) except: pass self.db = sqlite3.connect(doc_db_path) self.cursor = self.db.cursor() # Create the tables if they don't exist to prevent exceptions later on self.cursor.execute('CREATE TABLE IF NOT EXISTS doc (symbol text, library_version text, doc text, gir_file text)') self.cursor.execute('CREATE TABLE IF NOT EXISTS girfiles (file text, last_modified integer)')
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 setup(self): self.cfg_dir = GLib.get_user_config_dir() self.cfg_dir = os.path.join(self.cfg_dir, 'clipon') self.cfg_file = os.path.join(self.cfg_dir, 'clipon.conf') if not os.path.exists(self.cfg_dir): os.mkdir(self.cfg_dir, 0o700) data_dir = GLib.get_user_data_dir() data_dir = os.path.join(data_dir, 'clipon') self.log_file = os.path.join(data_dir, 'clipon.log') if not os.path.exists(data_dir): os.mkdir(data_dir, 0o700) init_log(self.log_file)
def _get_valid_themes(self): """ Only shows themes that have variations for gtk+-3 and gtk+-2 """ gtk_ver = Gtk.MINOR_VERSION if gtk_ver % 2: # Want even number gtk_ver += 1 dirs = ( os.path.join(gtweak.DATA_DIR, "themes"), os.path.join(GLib.get_user_data_dir(), "themes"), os.path.join(os.path.expanduser("~"), ".themes")) valid = walk_directories(dirs, lambda d: os.path.exists(os.path.join(d, "gtk-2.0")) and \ (os.path.exists(os.path.join(d, "gtk-3.0")) or \ os.path.exists(os.path.join(d, "gtk-3.{}".format(gtk_ver))))) return valid
def create_lockfile(): """Create lockfile handler.""" lock_file = '{}/bleeter/lock'.format(GLib.get_user_data_dir()) # Create directory for state storage mkdir(os.path.dirname(lock_file)) if os.path.exists(lock_file): message = \ 'Another instance is running or {!r} is stale'.format(lock_file) usage_note(message) raise IOError(message) with open(lock_file, 'w') as f: f.write(str(os.getpid())) atexit.register(os.unlink, lock_file)
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 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 on_mnu_save_activate(self, widget, date=None): print "saveing" ## get the title for the note #title = self.ui.entry1.get_text() ##get the string #buff = self.ui.textview1.get_buffer() #start_iter = buff.get_start_iter() #end_iter = buff.get_end_iter() #text = buff.get_text(start_iter, end_iter, True) ##create the filename #data_dir = GLib.get_user_data_dir() #jotty_dir = os.path.join(data_dir, "jotty") #filename = os.path.join(jotty_dir, title) ##write the data #GLib.mkdir_with_parents(jotty_dir, 0o700) #GLib.file_set_contents(filename, text) #get the title from the user saver = SaveDialog() result = saver.run() title = saver.title_text() saver.destroy() if result != Gtk.ResponseType.OK: return #get the string buff = self.ui.textview1.get_buffer() start_iter = buff.get_start_iter() end_iter = buff.get_end_iter() text = buff.get_text(start_iter, end_iter, True) #create the filename data_dir = GLib.get_user_data_dir() jotty_dir = os.path.join(data_dir, "jotty") print title filename = os.path.join(jotty_dir, title) #write the data GLib.mkdir_with_parents(jotty_dir, 0o700) GLib.file_set_contents(filename, text)
def __init__(self): super().__init__() self.playlist_path = GLib.build_filenamev([GLib.get_user_data_dir(), "gnome-music", "playlists"]) if not (GLib.file_test(self.playlist_path, GLib.FileTest.IS_DIR)): GLib.mkdir_with_parents(self.playlist_path, int("0755", 8)) Grl.init(None) self.options = Grl.OperationOptions() self.options.set_resolution_flags(Grl.ResolutionFlags.FAST_ONLY | Grl.ResolutionFlags.IDLE_RELAY) self.full_options = Grl.OperationOptions() self.full_options.set_resolution_flags(Grl.ResolutionFlags.FULL | Grl.ResolutionFlags.IDLE_RELAY) self.props.sources = {} self.blacklist = [ 'grl-filesystem', 'grl-bookmarks', 'grl-metadata-store', 'grl-podcasts', 'grl-spotify-cover' ] self.tracker = None self.changed_media_ids = [] self.pending_event_id = 0 self.changes_pending = {'Albums': False, 'Artists': False, 'Songs': False} self.pending_changed_medias = [] self._thumbnail_sources = [] self._thumbnail_sources_timeout = None self.registry = Grl.Registry.get_default() self._tracker_wrapper = TrackerWrapper() self.tracker_sparql = self._tracker_wrapper.props.tracker self._tracker_wrapper.bind_property( "tracker-available", self, "tracker-available", GObject.BindingFlags.BIDIRECTIONAL | GObject.BindingFlags.SYNC_CREATE) self._find_sources()