def on_set_clicked( self, widget ): x = self.option_combo.get_active() y = self.colorscheme.get_active() path = GLib.get_home_dir() + "/.wallpapers/" current_walls = fileList( path ) if( len(current_walls.file_names_only) > 0 ): filepath = current_walls.file_names_only[x] colorscheme_file = current_walls.file_names_only[y] colorscheme = "." + colorscheme_file + ".Xres" colorscheme_sample = "." + current_walls.file_names_only[y] + ".sample.png" if( not os.path.isfile( path + colorscheme ) or not os.path.isfile( path + colorscheme_sample ) ): print( ":: " + path + colorscheme + " NOT FOUND" ) print( ":: GENERATING COLORS" ) call( [ "wpcscript", "add", path + filepath ] ) self.pixbuf_sample = GdkPixbuf.Pixbuf.new_from_file_at_size( path + colorscheme_sample, width=500, height=500 ) self.sample.set_from_pixbuf( self.pixbuf_sample ) Popen( [ "wpcscript", "change", filepath ] ) Popen( [ "xrdb", "-merge", path + colorscheme] ) init_file = open( GLib.get_home_dir() + "/.wallpapers/wp_init.sh", "w" ) init_file.writelines( [ "#!/bin/bash\n", "wpcscript change " + filepath + " && " ] ) init_file.writelines( "xrdb -merge " + path + colorscheme + "\n" ) init_file.close() Popen( [ "chmod", "+x", GLib.get_home_dir() + "/.wallpapers/wp_init.sh" ] ) if( os.path.isfile(GLib.get_home_dir() + "/.themes/colorbamboo/openbox-3/themerc.base") ): execute_gcolorchange( colorscheme_file )
def colorscheme_box_change( self, widget ): x = self.colorscheme.get_active() current_walls = fileList( GLib.get_home_dir() + "/.wallpapers" ) selected_file = current_walls.file_names_only[x] selected_sample = "." + selected_file + ".sample.png" samplepath = GLib.get_home_dir() + "/.wallpapers/" + selected_sample self.pixbuf_sample = GdkPixbuf.Pixbuf.new_from_file_at_size( samplepath, width=500, height=500 ) self.sample.set_from_pixbuf( self.pixbuf_sample )
def combo_box_change( self, widget ): x = self.option_combo.get_active() self.colorscheme.set_active( x ) current_walls = fileList( GLib.get_home_dir() + "/.wallpapers" ) selected_file = current_walls.file_names_only[x] selected_sample = "." + selected_file + ".sample.png" filepath = GLib.get_home_dir() + "/.wallpapers/" + selected_file samplepath = GLib.get_home_dir() + "/.wallpapers/" + selected_sample self.pixbuf_preview = GdkPixbuf.Pixbuf.new_from_file_at_scale( filepath, width=500, height=333, preserve_aspect_ratio=False ) self.preview.set_from_pixbuf( self.pixbuf_preview )
def combo_box_change( self, widget ): self.done_lbl.set_text( "" ) x = self.option_combo.get_active() self.auto_button.set_sensitive( True ) self.ok_button.set_sensitive( True ) current_walls = fileList( GLib.get_home_dir() + "/.wallpapers" ) selected_file = current_walls.file_names_only[x] selected_sample = "." + selected_file + ".sample.png" sample_path = GLib.get_home_dir() + "/.wallpapers/" + selected_sample self.color_list = read_colors( selected_file ) for x in range( 0, 16 ): self.button_list[x].set_label( self.color_list[x] ) self.button_list[x].set_sensitive( True ) self.pixbuf_sample = GdkPixbuf.Pixbuf.new_from_file_at_size( sample_path, width=500, height=300 ) self.sample.set_from_pixbuf( self.pixbuf_sample )
def on_set_clicked( self, widget ): print( "Set" ) x = self.option_combo.get_active() y = self.colorscheme.get_active() path = GLib.get_home_dir() + "/.wallpapers/" current_walls = fileList( path ) filepath = current_walls.file_names_only[x] colorscheme = current_walls.file_names_only[y] call( [ "wp", "change", filepath ] ) call( [ "xrdb", "-merge", GLib.get_home_dir() + "/.wallpapers/." + colorscheme + ".Xres" ] ) call( [ "sh", "-c", "echo -n \"wp change "+ filepath +" && \" > ~/.wallpapers/wp_init.sh" ] ) call( [ "sh", "-c", "echo \"xrdb -merge "+ path + "." + colorscheme + ".Xres" + "\" >> ~/.wallpapers/wp_init.sh" ] ) call( [ "chmod", "+x", GLib.get_home_dir() + "/.wallpapers/wp_init.sh" ] ) if( os.path.isfile(GLib.get_home_dir() + "/.themes/colorbamboo/openbox-3/themerc.base") ): execute_gcolorchange( colorscheme )
def delete_button_clicked_cb (self, button): listItr = self.listStore.get_iter_first () while (listItr != None): if (self.listStore.get_value (listItr, m.DELETE) == True): recName = self.listStore.get_value (listItr, m.TITLE) recDate = self.listStore.get_value (listItr, m.DATE) dialog = Gtk.MessageDialog(self.mainWindow, 0, Gtk.MessageType.WARNING, Gtk.ButtonsType.OK_CANCEL, "Move '"+recName+"' to trash?") dialog.format_secondary_text( "This operation cannot be undone.") response = dialog.run() if response == Gtk.ResponseType.OK: shutil.move (self.projectDir+"/"+recDate, GLib.get_home_dir ()+"/.local/share/Trash/files/") # Remove moves the current iter and True if it has moved # onto the next item false if not dialog.destroy () if (self.listStore.remove (listItr) == True): continue else: listItr = None continue dialog.destroy () listItr = self.listStore.iter_next (listItr)
def __init__(self): self.operation = Gtk.PrintOperation() print_data = {'filename': os.path.abspath(__file__), 'font_size': 12.0, 'lines_per_page': 0, 'lines': None, 'num_lines': 0, 'num_pages': 0 } self.operation.connect('begin-print', self.begin_print, print_data) self.operation.connect('draw-page', self.draw_page, print_data) self.operation.connect('end-print', self.end_print, print_data) self.operation.set_use_full_page(False) self.operation.set_unit(Gtk.Unit.POINTS) self.operation.set_embed_page_setup(True) settings = Gtk.PrintSettings() dir = GLib.get_user_special_dir(GLib.UserDirectory.DIRECTORY_DOCUMENTS) if dir is None: dir = GLib.get_home_dir() ext = '.pdf' uri = "file://%s/gtk-demo%s" % (dir, ext) settings.set(Gtk.PRINT_SETTINGS_OUTPUT_URI, uri) self.operation.set_print_settings(settings)
def get_userinfo(self): dict = {} dict['username'] = GLib.get_user_name() dict['homedir'] = GLib.get_home_dir() dict['shell'] = GLib.getenv('SHELL') dict['lang'] = GLib.getenv('LANG') return dict['username'], dict['homedir'],dict['shell'],dict['lang']
def on_export_document_as(self, action, *params): file_name = self.editor.file_name or None dialog = FileSaveDialog(self) if self.renderer.get_parser() == 'json': dialog.add_filter_json() else: dialog.add_filter_html() dialog.add_filter_all() dialog.set_do_overwrite_confirmation(True) if file_name is None: dialog.set_current_folder(GLib.get_home_dir()) else: dialog.set_current_name(file_name[:file_name.rfind('.')]) if dialog.run() == Gtk.ResponseType.ACCEPT: extensions = getattr(dialog.get_filter(), 'extensions', ()) file_name = dialog.get_filename() ex_ok = False for extension in extensions: if file_name.lower().endswith(extension): ex_ok = True break if not ex_ok and extensions: file_name += extensions[0] with open(file_name, "w+", encoding="utf-8") as output: data = self.renderer.render_output()[1].strip() if version_info.major == 2: output.write(data.encode("utf-8")) else: # python 3.x output.write(data) dialog.destroy()
def do_gtk_bookmarks(self): if self.showGTKBookmarks: bookmarksFile = os.path.join(GLib.get_user_config_dir(), "gtk-3.0", "bookmarks") if not os.path.exists(bookmarksFile): bookmarksFile = os.path.join(GLib.get_home_dir(), ".gtk-bookmarks") if not os.path.exists(bookmarksFile): return bookmarks = [] with open(bookmarksFile, "r") as f: for line in f: #line = line.replace('file://', '') line = line.rstrip() if not line: continue parts = line.split(' ', 1) if len(parts) == 2: path, name = parts elif len(parts) == 1: path = parts[0] name = os.path.basename(os.path.normpath(path)) bookmarks.append((name, path)) for name, path in bookmarks: name = unquote(name) currentbutton = easyButton("folder", self.iconsize, [name], -1, -1) currentbutton.connect("clicked", self.launch_gtk_bookmark, path) currentbutton.show() self.placesBtnHolder.pack_start(currentbutton, False, False, 0)
def __init__( self ): Gtk.Window.__init__( self, title = "wpgtk v2.1" ) filepath = GLib.get_home_dir() + "/.wallpapers/" current_walls = fileList( filepath ) current_walls.show_files_only() image_name = filepath + ".current" image_name = os.path.realpath( image_name ) #these variables are just to get the image and preview of current wallpaper route_list = image_name.split( "/", image_name.count("/") ) file_name = route_list[4] sample_name = filepath + "." + file_name + ".sample.png" option_list = Gtk.ListStore( str ) for elem in list(current_walls.files): option_list.append( [elem] ) self.option_combo = Gtk.ComboBox.new_with_model( option_list ) self.renderer_text = Gtk.CellRendererText() self.option_combo.pack_start( self.renderer_text, True ) self.option_combo.add_attribute( self.renderer_text, "text", 0 ) self.option_combo.set_entry_text_column( 0 ) self.textbox = Gtk.Label() self.textbox.set_text( "Select colorscheme" ) self.colorscheme = Gtk.ComboBox.new_with_model( option_list ) self.colorscheme.pack_start( self.renderer_text, True ) self.colorscheme.add_attribute( self.renderer_text, "text", 0 ) self.colorscheme.set_entry_text_column( 0 ) self.set_border_width( 10 ) self.grid = Gtk.Grid() self.grid.set_column_homogeneous( 1 ) self.grid.set_row_spacing( 10 ) self.grid.set_column_spacing( 10 ) self.add( self.grid ) self.preview = Gtk.Image() self.sample = Gtk.Image() if( os.path.isfile( image_name ) ): self.pixbuf_preview = GdkPixbuf.Pixbuf.new_from_file_at_scale( image_name, width=500, height=333, preserve_aspect_ratio=False ) self.pixbuf_sample = GdkPixbuf.Pixbuf.new_from_file_at_size( sample_name, width=500, height=500 ) self.preview.set_from_pixbuf( self.pixbuf_preview ) self.sample.set_from_pixbuf( self.pixbuf_sample ) self.add_button = Gtk.Button( label = "Add" ) self.set_button = Gtk.Button( label = "Set" ) self.rm_button = Gtk.Button( label = "Remove" ) self.grid.attach( self.option_combo, 1, 1, 2, 1 ) #adds to first cell in grid self.grid.attach( self.colorscheme, 1, 2, 2, 1 ) self.grid.attach( self.set_button, 3, 1, 1, 1 ) self.grid.attach( self.add_button, 3, 2, 2, 1 ) self.grid.attach( self.rm_button, 4, 1, 1, 1 ) self.grid.attach( self.preview, 1, 3, 4, 1 ) self.grid.attach( self.sample, 1, 4, 4, 1 ) self.add_button.connect( "clicked", self.on_add_clicked ) self.set_button.connect( "clicked", self.on_set_clicked ) self.rm_button.connect( "clicked", self.on_rm_clicked ) self.option_combo.connect( "changed", self.combo_box_change ) self.colorscheme.connect( "changed", self.colorscheme_box_change ) self.entry = Gtk.Entry() self.current_walls = Gtk.ComboBox()
def location(self, value: Gio.File): # Keep showing the same path if the new location still appears in it. if self._path is None or not self._path.has_prefix(value): self._path = value self._current = value parts = [] position = None # Index of the current location. file = self._path while file: if parts: parts.append(" ") if file.equal(self._current): position = len(parts) # Treat the home folder as the root, unless the current location # hasn't been reached yet. if position is not None and GLib.get_home_dir() == file.get_path(): parts.append(" ~ ") break name = file.query_info(Gio.FILE_ATTRIBUTE_STANDARD_DISPLAY_NAME, Gio.FileQueryInfoFlags.NONE, None).get_display_name() parts.append(" {} ".format(name)) file = file.get_parent() parts[position] = ('path-bar current', parts[position]) parts.reverse() self.original_widget.set_text(parts)
def __init__(self): self.operation = Gtk.PrintOperation() print_data = { "filename": os.path.abspath(__file__), "font_size": 12.0, "lines_per_page": 0, "lines": None, "num_lines": 0, "num_pages": 0, } self.operation.connect("begin-print", self.begin_print, print_data) self.operation.connect("draw-page", self.draw_page, print_data) self.operation.connect("end-print", self.end_print, print_data) self.operation.set_use_full_page(False) self.operation.set_unit(Gtk.Unit.POINTS) self.operation.set_embed_page_setup(True) settings = Gtk.PrintSettings() dir = GLib.get_user_special_dir(GLib.UserDirectory.DIRECTORY_DOCUMENTS) if dir is None: dir = GLib.get_home_dir() if settings.get(Gtk.PRINT_SETTINGS_OUTPUT_FILE_FORMAT) == "ps": ext = ".ps" elif settings.get(Gtk.PRINT_SETTINGS_OUTPUT_FILE_FORMAT) == "svg": ext = ".svg" else: ext = ".pdf" uri = "file://%s/gtk-demo%s" % (dir, ext) settings.set(Gtk.PRINT_SETTINGS_OUTPUT_URI, uri) self.operation.set_print_settings(settings)
def __init__(self, canvas): self.operation = Gtk.PrintOperation() print_data = {"canvas": canvas, "font_size": 10.0, "lines": None, "num_pages": 0} self.operation.connect("begin-print", self.begin_print, print_data) self.operation.connect("draw-page", self.draw_page, print_data) self.operation.connect("end-print", self.end_print, print_data) self.operation.set_use_full_page(False) self.operation.set_unit(Gtk.Unit.POINTS) self.operation.set_embed_page_setup(True) settings = Gtk.PrintSettings() dir = GLib.get_user_special_dir(GLib.UserDirectory.DIRECTORY_DOCUMENTS) if dir is None: dir = GLib.get_home_dir() if settings.get(Gtk.PRINT_SETTINGS_OUTPUT_FILE_FORMAT) == "ps": ext = ".ps" elif settings.get(Gtk.PRINT_SETTINGS_OUTPUT_FILE_FORMAT) == "svg": ext = ".svg" else: ext = ".pdf" # base_name = os.path.splitext(os.path.basename(out_file_path))[0] uri = "file://{:s}/plot{:s}".format(dir, ext) settings.set(Gtk.PRINT_SETTINGS_OUTPUT_URI, uri) self.operation.set_print_settings(settings)
def __init__( self, connmgr, datadir=GLib.get_home_dir() + "/.mozilla/firefox", namespace="org.mozilla.firefox"): logging.debug( "Initializing firefox logger with namespace %s at %s" % ( namespace, datadir)) self.connmgr = connmgr self.datadir = datadir self.namespace = namespace self.profiles_path = self.datadir + '/profiles.ini' self.monitored_preferences = {} self.file_monitors = {} # Testing facilities self.default_profile_initialized = False self.test_profiles_file_updated = False self.default_profile_prefs_initialized = False self.test_prefs_file_updated = False logging.debug( "Constructing FirefoxLogger with data directory %s" % self.datadir) self.connmgr = connmgr # Monitor profiles file self._setup_profiles_file_monitor()
def on_rm_clicked( self, widget ): x = self.option_combo.get_active() current_walls = fileList( GLib.get_home_dir() + "/.wallpapers" ) if( len(current_walls.file_names_only) > 0 ): filepath = current_walls.file_names_only[x] call( [ "wpcscript", "rm", filepath ] ) call( [ "rm", GLib.get_home_dir() + "/.wallpapers/" + "." + filepath + ".sample.png" ] ) option_list = Gtk.ListStore( str ) current_walls = fileList( filepath ) for elem in list(current_walls.files): option_list.append( [elem] ) self.option_combo.set_model( option_list ) self.option_combo.set_entry_text_column( 0 ) self.colorscheme.set_model( option_list ) self.colorscheme.set_entry_text_column( 0 ) self.cpage.update_combo( option_list )
def __init__(self, out_file_path): self.operation = Gtk.PrintOperation() print_data = {'filename': out_file_path, 'font_size': 10.0, 'lines': None, 'num_pages': 0 } self.operation.connect('begin-print', self.begin_print, print_data) self.operation.connect('draw-page', self.draw_page, print_data) self.operation.connect('end-print', self.end_print, print_data) self.operation.set_use_full_page(False) self.operation.set_unit(Gtk.Unit.POINTS) self.operation.set_embed_page_setup(True) settings = Gtk.PrintSettings() dir = GLib.get_user_special_dir(GLib.UserDirectory.DIRECTORY_DOCUMENTS) if dir is None: dir = GLib.get_home_dir() if settings.get(Gtk.PRINT_SETTINGS_OUTPUT_FILE_FORMAT) == 'ps': ext = '.ps' elif settings.get(Gtk.PRINT_SETTINGS_OUTPUT_FILE_FORMAT) == 'svg': ext = '.svg' else: ext = '.pdf' base_name = os.path.splitext(os.path.basename(out_file_path))[0] uri = "file://{:s}/{:s}{:s}".format(dir, base_name, ext) settings.set(Gtk.PRINT_SETTINGS_OUTPUT_URI, uri) self.operation.set_print_settings(settings)
def import_chromium(self, chrome): """ Chromium/Chrome importer As Eolie doesn't sync with Chromium, we do not handle parent guid and just import parents as tags @param chrome as bool """ try: self.thread_lock.acquire() SqlCursor.add(self) import json homedir = GLib.get_home_dir() if chrome: path = homedir + "/.config/chrome/Default/Bookmarks" else: path = homedir + "/.config/chromium/Default/Bookmarks" f = Gio.File.new_for_path(path) if not f.query_exists(): return (status, content, tag) = f.load_contents(None) if status: data = content.decode("utf-8") j = json.loads(data) parents = [] # Setup initial parents for root in j["roots"]: parents.append(("", j["roots"][root]["children"])) # Walk parents and children while parents: (parent_name, children) = parents.pop(0) bookmarks = [] for child in children: if child["type"] == "folder": parents.append((child["name"], child["children"])) elif child["type"] == "url": bookmarks.append((child["name"], child["url"])) position = 0 for bookmark in bookmarks: tags = [parent_name] title = bookmark[0] uri = bookmark[1] if not uri.startswith('http') or not title: continue uri = uri.rstrip('/') rowid = self.get_id(uri) if rowid is None: # Add bookmark bookmark_id = self.add(title, uri, None, tags, 0, False) # Set position self.set_position(bookmark_id, position, False) position += 1 with SqlCursor(self) as sql: sql.commit() SqlCursor.remove(self) except Exception as e: print("DatabaseBookmarks::import_chromium:", e) finally: self.thread_lock.release()
def get_userinfo(self): dict = {} dict['username'] = GLib.get_user_name() dict['homedir'] = GLib.get_home_dir() dict['terminal'] = GLib.getenv('SHELL') dict['lang'] = GLib.getenv('LANG') return dict['username'], dict['homedir'], dict['terminal'], dict[ 'lang']
def _create_launcher(self): flags = Gio.SubprocessFlags.STDIN_PIPE | Gio.SubprocessFlags.STDOUT_PIPE if not DEV_MODE: flags |= Gio.SubprocessFlags.STDERR_SILENCE launcher = Ide.SubprocessLauncher() launcher.set_flags(flags) launcher.set_cwd(GLib.get_home_dir()) launcher.set_run_on_host(True) return launcher
def _on_term_child_exited(self, term, status): """Called when the shell is terminated. Args: term -- The VTE terminal (self.term). """ if not self._respawn_lock: if self._path == "": self._path = GLib.get_home_dir() self.shell_pid = self.term.spawn_sync(Vte.PtyFlags.DEFAULT, self._path, [terminal_or_default()], None, GLib.SpawnFlags.SEARCH_PATH, None, None, None)[1]
def get_project_dir(self, project_name): # TODO: configurable project dirs parent_dir = os.path.join(GLib.get_home_dir(), 'Projects') try: os.makedirs(parent_dir) except: pass return Gio.File.new_for_path(os.path.join(parent_dir, project_name))
def GetRemoteMachineAvatar(self, request, context): logging.debug("Server RPC: GetRemoteMachineAvatar from '%s'" % request.readable_name) path = os.path.join(GLib.get_home_dir(), ".face") if os.path.exists(path): return transfers.load_file_in_chunks(path) else: context.abort(code=grpc.StatusCode.NOT_FOUND, details='.face file not found!')
def on_switch_btn_clicked(self, w): self.main_path = os.path.expanduser(self.path_entry.props.text) if not os.path.exists(self.main_path): os.makedirs(self.main_path) is_gui = self.check_gui(self.template) self.project_full_path = os.path.join(self.main_path, self.project_name) # Create template class on main button click and call start() function if self.language == 'Python': from .python_template import PythonTemplate self.complete_template = PythonTemplate(is_gui, self.project_id, self.project_name, self.project_full_path, self.is_git, self.license) elif self.language == 'Rust': from .rust_template import RustTemplate self.complete_template = RustTemplate(is_gui, self.project_id, self.project_name, self.project_full_path, self.is_git, self.license) elif self.language == 'C': from .c_template import CTemplate self.complete_template = CTemplate(is_gui, self.project_id, self.project_name, self.project_full_path, self.is_git, self.license) elif self.language == 'JS': if self.template == 'GNOME Extension': from .gnome_extension_template import GnomeExtensionTemplate self.complete_template = GnomeExtensionTemplate( self.ext_name, self.ext_uuid, self.ext_description, self.is_git) self.project_full_path = os.path.join( GLib.get_home_dir(), constants['GNOME_EXTENSION_PATH'], self.ext_uuid) else: from .js_template import JsTemplate self.complete_template = JsTemplate(is_gui, self.project_id, self.project_name, self.project_full_path, self.is_git, self.license) if path.exists(self.project_full_path): self.path_exists_revealer.props.reveal_child = True return else: if self.path_exists_revealer.props.reveal_child: self.path_exists_revealer.props.reveal_child = False self.complete_template.start() self.main_view.set_visible_child_name('page1')
def __init__(self): database_file = GLib.get_home_dir( ) + '/.config/Authenticator/database.db' if create_file(database_file): logging.debug("Creating database file %s " % database_file) self.conn = sqlite3.connect(database_file) if not self.is_table_exists(): logging.debug( "SQL: Table 'accounts' does not exists, creating it now...") self.create_table() logging.debug("SQL: Table 'accounts' created successfully")
def on_rm_clicked(self, widget): x = self.option_combo.get_active() current_walls = FileList(GLib.get_home_dir() + '/.wallpapers') if (len(current_walls.file_names_only) > 0): FILEPATH = current_walls.file_names_only[x] call(['wpcscript', 'rm', FILEPATH]) call([ 'rm', GLib.get_home_dir() + '/.wallpapers/' + '.' + FILEPATH + '.sample.png' ]) option_list = Gtk.ListStore(str) current_walls = FileList(FILEPATH) for elem in list(current_walls.files): option_list.append([elem]) self.option_combo.set_model(option_list) self.option_combo.set_entry_text_column(0) self.colorscheme.set_model(option_list) self.colorscheme.set_entry_text_column(0) self.cpage.update_combo(option_list)
def on_rm_clicked(self, widget): x = self.option_combo.get_active() current_walls = fileList(GLib.get_home_dir() + "/.wallpapers") if (len(current_walls.file_names_only) > 0): filepath = current_walls.file_names_only[x] call(["wpcscript", "rm", filepath]) call([ "rm", GLib.get_home_dir() + "/.wallpapers/" + "." + filepath + ".sample.png" ]) option_list = Gtk.ListStore(str) current_walls = fileList(filepath) for elem in list(current_walls.files): option_list.append([elem]) self.option_combo.set_model(option_list) self.option_combo.set_entry_text_column(0) self.colorscheme.set_model(option_list) self.colorscheme.set_entry_text_column(0) self.cpage.update_combo(option_list)
def get_saving_location(self): video_directory = self.settings.get_string('saving-location') filename = f"Kooha-{strftime('%Y-%m-%d-%H:%M:%S', localtime())}" video_format = self.settings.get_string('video-format') if self.settings.get_string("saving-location") == "default": video_directory = GLib.get_user_special_dir( GLib.UserDirectory.DIRECTORY_VIDEOS) if not os.path.exists(video_directory): video_directory = GLib.get_home_dir() return (f"{video_directory}/{filename}.{video_format}", video_directory)
def on_auto_click( self, widget ): current_walls = fileList( GLib.get_home_dir() + "/.wallpapers" ) self.color_list = self.color_list[:8:] + [ add_brightness( x, 50 ) for x in self.color_list[:8:] ] for x in range( 0, 16 ): self.button_list[x].set_label( self.color_list[x] ) write_tmp( self.color_list ) os.system( "wpcscript tmp 1>/dev/null" ) sample_path = filepath + ".tmp.sample.png" self.pixbuf_sample = GdkPixbuf.Pixbuf.new_from_file_at_size( sample_path, width=500, height=300 ) self.sample.set_from_pixbuf( self.pixbuf_sample ) self.done_lbl.set_text( "Auto-adjust done" )
def __init__(self, path): valid = re.compile('^[^\.](.*\.png$|.*\.jpg$|.*\.jpeg$|.*\.jpe$)') self.files = [] self.file_names_only = [] number_list = [] elem_counter = 1 for (dirpath, dirnames, filenames) in walk(GLib.get_home_dir() + "/.wallpapers"): self.files.extend(filenames) self.files = [elem for elem in self.files if valid.fullmatch(elem)] self.file_names_only = self.files
class ManageDeskletsPage(ManageSpicesPage): directories = [("%s/.local/share/cinnamon/desklets") % GLib.get_home_dir(), "/usr/share/cinnamon/desklets"] collection_type = "desklet" installed_page_title = _("Installed desklets") instance_button_text = _("Add") remove_button_text = _("Remove") uninstall_button_text = _("Uninstall") restore_button_text = _("Remove all") def __init__(self, parent, spices, window): super(ManageDeskletsPage, self).__init__(parent, self.collection_type, spices, window)
def get_default_folders(self): folders = {} folders[GLib.get_user_special_dir(GLib.USER_DIRECTORY_DESKTOP)] = 'user-desktop.svg' folders[GLib.get_user_special_dir(GLib.USER_DIRECTORY_DOCUMENTS)] = 'folder-documents.svg' folders[GLib.get_user_special_dir(GLib.USER_DIRECTORY_DOWNLOAD)] = 'folder-download.svg' folders[GLib.get_user_special_dir(GLib.USER_DIRECTORY_MUSIC)] = 'folder-music.svg' folders[GLib.get_user_special_dir(GLib.USER_DIRECTORY_PICTURES)] = 'folder-pictures.svg' folders[GLib.get_user_special_dir(GLib.USER_DIRECTORY_PUBLIC_SHARE)] = 'folder-publicshare.svg' folders[GLib.get_user_special_dir(GLib.USER_DIRECTORY_TEMPLATES)] = 'folder-templates.svg' folders[GLib.get_user_special_dir(GLib.USER_DIRECTORY_VIDEOS)] = 'folder-video.svg' folders[GLib.get_home_dir()] = 'folder-home.svg' return folders
def main(): if len(sys.argv) > 1: xmlfile = sys.argv[1] else: try: local_dir = os.path.join(GLib.get_user_data_dir(), "gtg") flatpak_dir = os.path.join(GLib.get_home_dir(), '.var', 'app', 'org.gnome.GTG', 'data', 'gtg') local_xml = os.path.join(local_dir, "gtg_data.xml") flatpak_xml = os.path.join(flatpak_dir, "gtg_data.xml") try: local_xml_time = os.path.getmtime(local_xml) except OSError: local_xml_time = 0 try: flatpak_xml_time = os.path.getmtime(flatpak_xml) except OSError: flatpak_xml_time = 0 if local_xml_time == flatpak_xml_time: if os.path.exists(flatpak_xml): xmlfile = flatpak_xml elif os.path.exists(local_xml): xmlfile = local_xml else: print("Could not find the data file in default locations") raise Exception("Could not find data file in default " "locations") elif local_xml_time < flatpak_xml_time: xmlfile = flatpak_xml elif local_xml_time > flatpak_xml_time: xmlfile = local_xml else: print("This should not happen") print("Reading tasks from %s" % (xmlfile)) except Exception: print() usage() if len(sys.argv) > 2: outputfile = sys.argv[2] else: # Use a reasonable default, and write out where it's sent outputfile = "/tmp/gtg_data.xml" print("Saving anonymized tasks to %s" % (outputfile)) anonymize(xmlfile, outputfile)
def PopulatePlugins(self): PluginPane = Gtk.EventBox() PluginPane.show() PaneLadder = Gtk.Box(orientation=Gtk.Orientation.VERTICAL) PluginPane.add(PaneLadder) ImageBox = Gtk.EventBox() ImageBox.show() self.pluginlist = self.settings.get_strv("plugins-list") self.plugins = {} self.showCategoryMenu = self.settings.get_boolean("show-category-menu") try: MyPlugin = pluginclass(self, self.showCategoryMenu) except Exception as e: print(e) MyPlugin.content_holder.show() VBox1 = Gtk.Box(orientation=Gtk.Orientation.VERTICAL) VBox1.show() #Add plugin to Plugin Box under heading button MyPlugin.content_holder.reparent(VBox1) #Add plugin to main window PaneLadder.pack_start(VBox1, True, True, 0) PaneLadder.show() if MyPlugin.window: MyPlugin.window.destroy() try: if hasattr(MyPlugin, 'do_plugin'): MyPlugin.do_plugin() heightPath = os.path.join(GLib.get_home_dir(), ".windowHeight") if os.path.exists(heightPath): f = open(heightPath, "r") lines = f.readlines() length = lines[0] MyPlugin.windowHeight = int(length) f.close() MyPlugin.content_holder.set_size_request(345, MyPlugin.windowHeight) except Exception as e: print(e) self.plugins["menu"] = MyPlugin self.paneholder.pack_start(ImageBox, False, False, 0) self.paneholder.pack_start(PluginPane, False, False, 0)
def combo_box_change(self, widget): self.done_lbl.set_text("") x = self.option_combo.get_active() self.auto_button.set_sensitive(True) self.ok_button.set_sensitive(True) current_walls = FileList(GLib.get_home_dir() + "/.wallpapers") selected_file = current_walls.file_names_only[x] selected_sample = "." + selected_file + ".sample.png" sample_path = GLib.get_home_dir() + "/.wallpapers/" + selected_sample self.color_list = read_colors(selected_file) for x in range(0, 16): color = Gdk.color_parse('#' + self.color_list[x]) if get_darkness(self.color_list[x]) < 100: fgcolor = Gdk.color_parse('#FFFFFF') else: fgcolor = Gdk.color_parse('#101010') self.button_list[x].set_label(self.color_list[x]) self.button_list[x].set_sensitive(True) self.button_list[x].modify_bg(Gtk.StateType.NORMAL, color) self.button_list[x].modify_fg(Gtk.StateType.NORMAL, fgcolor) self.pixbuf_sample = GdkPixbuf.Pixbuf.new_from_file_at_size( sample_path, width=500, height=300) self.sample.set_from_pixbuf(self.pixbuf_sample)
def on_rm_clicked( self, widget ): print( "rm" ) x = self.option_combo.get_active() current_walls = fileList( GLib.get_home_dir() + "/.wallpapers" ) filepath = current_walls.file_names_only[x] call( [ "wp", "rm", filepath ] ) option_list = Gtk.ListStore( str ) current_walls = fileList( filepath ) for elem in list(current_walls.files): option_list.append( [elem] ) self.option_combo.set_model( option_list ) self.option_combo.set_entry_text_column( 0 ) self.colorscheme.set_model( option_list ) self.colorscheme.set_entry_text_column( 0 )
class ManageExtensionsPage(ManageSpicesPage): directories = [ ("%s/.local/share/cinnamon/extensions") % GLib.get_home_dir() ] collection_type = "extension" installed_page_title = _("Installed extensions") instance_button_text = _("Enable") remove_button_text = _("Disable") uninstall_button_text = _("Uninstall") restore_button_text = _("Disable all") def __init__(self, parent, spices, window): super(ManageExtensionsPage, self).__init__(parent, self.collection_type, spices, window)
def on_auto_click(self, widget): current_walls = fileList(GLib.get_home_dir() + "/.wallpapers") self.color_list = self.color_list[:8:] + [ add_brightness(x, 50) for x in self.color_list[:8:] ] for x in range(0, 16): self.button_list[x].set_label(self.color_list[x]) write_tmp(self.color_list) os.system("wpcscript tmp 1>/dev/null") sample_path = filepath + ".tmp.sample.png" self.pixbuf_sample = GdkPixbuf.Pixbuf.new_from_file_at_size( sample_path, width=500, height=300) self.sample.set_from_pixbuf(self.pixbuf_sample) self.done_lbl.set_text("Auto-adjust done")
def on_connect_btn_clicked_standalone(self, button): working_dir = os.path.dirname(self.standalone_path) if self.is_connected: self.conn_mgr.disconnect(self.on_disconnect) return True is_vpn_running = self.conn_mgr.get_connection_status() logger.debug("is_vpn_running={}".format(is_vpn_running)) if is_vpn_running: dlg = self.builder.get_object("openvpn_running_dlg") dlg.run() return False log_file = os.path.join(self.EOVPN_CONFIG_DIR, "session.log") config_file = self.standalone_path auth_file = None crt = None if os.path.isfile(os.path.join(working_dir, "auth.txt")): auth_file = os.path.join(working_dir, "auth.txt") #1st preference else: if self.get_setting(self.SETTING.REQ_AUTH): auth_file = os.path.join(self.EOVPN_CONFIG_DIR, "auth.txt") #2nd preference crt_re = re.compile(r'.crt|cert') files = os.listdir(working_dir) crt_result = list(filter(crt_re.findall, files)) crt_filename = None if len(crt_result) >= 1: crt_filename = crt_result[-1] crt = os.path.join(working_dir, crt_filename) if self.se_enforcing and (self.get_setting(self.SETTING.MANAGER) != "openvpn"): home_dir = GLib.get_home_dir() se_friendly_path = os.path.join(home_dir, ".cert") if not os.path.exists(se_friendly_path): os.mkdir(se_friendly_path) shutil.copy(crt, se_friendly_path) crt = os.path.join(se_friendly_path, crt_filename) logger.debug("se friendly crt={}".format(crt)) self.conn_mgr.connect(config_file, auth_file, crt, log_file, self.on_connect)
class DatabaseExceptions: """ Adblock exceptions """ if GLib.getenv("XDG_DATA_HOME") is None: __LOCAL_PATH = GLib.get_home_dir() + "/.local/share/eolie" else: __LOCAL_PATH = GLib.getenv("XDG_DATA_HOME") + "/eolie" DB_PATH = "%s/exceptions.db" % __LOCAL_PATH # SQLite documentation: # In SQLite, a column with type INTEGER PRIMARY KEY # is an alias for the ROWID. # Here, we define an id INT PRIMARY KEY but never feed it, # this make VACUUM not destroy rowids... __create_exceptions = '''CREATE TABLE exceptions ( id INTEGER PRIMARY KEY, uri TEXT NOT NULL )''' def __init__(self): """ Create database tables or manage update if needed """ self.__cancellable = Gio.Cancellable.new() f = Gio.File.new_for_path(self.DB_PATH) # Lazy loading if not empty if not f.query_exists(): try: d = Gio.File.new_for_path(self.__LOCAL_PATH) if not d.query_exists(): d.make_directory_with_parents() # Create db schema with SqlCursor(self) as sql: sql.execute(self.__create_exceptions) sql.commit() except Exception as e: print("DatabaseExceptions::__init__(): %s" % e) def get_cursor(self): """ Return a new sqlite cursor """ try: c = sqlite3.connect(self.DB_PATH, 600.0) return c except Exception as e: print(e) exit(-1)
def on_rm_clicked(self, widget): x = self.option_combo.get_active() current_walls = FileList(GLib.get_home_dir() + '/.wallpapers') if (len(current_walls.file_names_only) > 0): FILENAME = current_walls.file_names_only[x] delete_theme(FILENAME) option_list = Gtk.ListStore(str) current_walls = FileList(FILENAME) for elem in list(current_walls.files): option_list.append([elem]) self.option_combo.set_model(option_list) self.option_combo.set_entry_text_column(0) self.colorscheme.set_model(option_list) self.colorscheme.set_entry_text_column(0) self.cpage.update_combo(option_list)
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 _create_launcher(self): """ Creates a launcher to be used by the vala service. In the future, we might be able to rely on the runtime for the tooling. Maybe even the program if flatpak-builder has prebuilt our dependencies. """ flags = Gio.SubprocessFlags.STDIN_PIPE | Gio.SubprocessFlags.STDOUT_PIPE if not DEV_MODE: flags |= Gio.SubprocessFlags.STDERR_SILENCE launcher = Ide.SubprocessLauncher() launcher.set_flags(flags) launcher.set_cwd(GLib.get_home_dir()) return launcher
def __init__( self, path ): self.files = [] self.file_names_only = [] number_list = [] elem_counter = 1 for( dirpath, dirnames, filenames ) in walk( GLib.get_home_dir() + "/.wallpapers" ): self.files.extend( filenames ) self.files = [ elem for elem in self.files if not ".Xres" in elem ] self.files = [ elem for elem in self.files if not ".sample" in elem ] self.files = [ elem for elem in self.files if not ".colors" in elem ] self.files = [ elem for elem in self.files if not ".current" in elem ] self.files = [ elem for elem in self.files if not ".sh" in elem ] # filter function goes up there self.file_names_only = self.files
def __init__(self, connmgr, homedir=GLib.get_home_dir()): logging.debug("Constructing GSettingsLogger") self._testing_loop = None self.homedir = homedir self.connmgr = connmgr self.path_to_known_schema = {} self.relocatable_schemas = [] self.past_keys_for_path = {} self.found_schemas_for_path = {} self.dconf_subscription_id = 0 self.schema_source = Gio.SettingsSchemaSource.get_default() # Create file for LibreOffice dconf writes dconfwrite = Gio.File.new_for_path( os.path.join(self.homedir, self.LIBREOFFICE_DCONF_PATH)) if not dconfwrite.query_exists(None): GLib.mkdir_with_parents(dconfwrite.get_parent().get_path(), 483) try: dconfwrite.create(Gio.FileCreateFlags.NONE, None) except Exception as e: logging.error( "Could not create file %s: %s" % ( dconfwrite.get_path(), e)) # Populate a table of paths to schema ids. We can do this up # front for fixed-path schemas. For relocatable schemas we have to # wait for a change to occur and then try to derive the schema from # the path and key(s) in the change notification. logging.debug("Caching known schemas") for schema_name in Gio.Settings.list_schemas(): #for schema_name in self.schema_source.list_schemas(True): schema = self.schema_source.lookup(schema_name, True) path = schema.get_path() logging.debug("Adding schema %s: %s" % (path, schema_name)) self.path_to_known_schema[path] = schema_name self.relocatable_schemas = Gio.Settings.list_relocatable_schemas() Gio.bus_watch_name( Gio.BusType.SESSION, self.BUS_NAME, Gio.BusNameWatcherFlags.NONE, self._bus_name_appeared_cb, self._bus_name_disappeared_cb)
def __init__(self, path): self.files = [] self.file_names_only = [] number_list = [] elem_counter = 1 for (dirpath, dirnames, filenames) in walk(GLib.get_home_dir() + "/.wallpapers"): self.files.extend(filenames) self.files = [elem for elem in self.files if not ".Xres" in elem] self.files = [elem for elem in self.files if not ".sample" in elem] self.files = [elem for elem in self.files if not ".colors" in elem] self.files = [elem for elem in self.files if not ".current" in elem] self.files = [elem for elem in self.files if not ".sh" in elem] # filter function goes up there self.file_names_only = self.files
def on_ok_click( self, widget ): current_walls = FileList( GLib.get_home_dir() + "/.wallpapers" ) if( len(current_walls.file_names_only) > 0 ): x = self.option_combo.get_active() write_colors( current_walls.file_names_only[x], self.color_list ) tmpfile = FILEPATH + ".tmp.sample.png" if( os.path.isfile(tmpfile) ): os.system( "mv " + FILEPATH + ".tmp.sample.png " + FILEPATH + "sample/" + current_walls.file_names_only[x] + ".sample.png" ) self.done_lbl.set_text( "Changes saved" ) x = self.parent.colorscheme.get_active() selected_file = current_walls.file_names_only[x] selected_sample = "sample/" + selected_file + ".sample.png" sample_path = FILEPATH + selected_sample self.parent.pixbuf_sample = GdkPixbuf.Pixbuf.new_from_file_at_size( sample_path, width=500, height=300 ) self.parent.sample.set_from_pixbuf( self.pixbuf_sample )
def all_icons_theme_name(): result = [] locations = [ l for l in [ "/usr/share/icons", "/usr/local/icons", GLib.get_user_data_dir() + "/icons", GLib.get_home_dir() + "/.icons" ] if os.path.isdir(l) ] for location in locations: for folder in os.listdir(location): f = os.path.join(location, folder) if os.path.isdir(f): if "index.theme" in os.listdir(f): result.append(folder) return result
def home_substitute(filename): """ Replace home directory with '~'. If ‘filename’ refers to a file in the user’s home directory, return ‘filename’ with the home directory path replaced by '~', otherwise return ‘filename’ unmodified. ‘filename’ should be an absolute path. """ home = GLib.get_home_dir() if not home: return filename if filename.startswith(home): return '~' + filename[len(home):] else: return filename
def on_ok_click( self, widget ): current_walls = fileList( GLib.get_home_dir() + "/.wallpapers" ) if( len(current_walls.file_names_only) > 0 ): x = self.option_combo.get_active() write_colors( current_walls.file_names_only[x], self.color_list ) tmpfile = filepath + ".tmp.sample.png" if( os.path.isfile(tmpfile) ): os.system( "mv " + filepath + ".tmp.sample.png " + filepath + "." + current_walls.file_names_only[x] + ".sample.png" ) self.done_lbl.set_text( "Changes saved" ) x = self.parent.colorscheme.get_active() selected_file = current_walls.file_names_only[x] selected_sample = "." + selected_file + ".sample.png" sample_path = filepath + selected_sample self.parent.pixbuf_sample = GdkPixbuf.Pixbuf.new_from_file_at_size( sample_path, width=500, height=300 ) self.parent.sample.set_from_pixbuf( self.pixbuf_sample )
def to_xfconf(self, xfconf): session_bus = Gio.BusType.SESSION conn = Gio.bus_get_sync(session_bus, None) destination = 'org.xfce.Panel' path = '/org/xfce/Panel' interface = destination dbus_proxy = Gio.DBusProxy.new_sync(conn, 0, None, destination, path, interface, None) if dbus_proxy is not None: # Reset all properties to make sure old settings are invalidated try: xfconf.call_sync( 'ResetProperty', GLib.Variant('(ssb)', ('xfce4-panel', '/', True)), 0, -1, None) except GLib.Error: # pylint: disable=E0712 pass for (pp, pv) in sorted(self.properties.items()): xfconf.call_sync( 'SetProperty', GLib.Variant('(ssv)', ('xfce4-panel', pp, pv)), 0, -1, None) panel_path = os.path.join(GLib.get_home_dir(), '.config/xfce4/panel/') for d in self.desktops: bytes = self.get_desktop_source_file(d).read() mkdir_p(panel_path + os.path.dirname(d)) f = open(panel_path + d, 'wb') f.write(bytes) f.close() try: dbus_proxy.call_sync('Terminate', GLib.Variant('(b)', ('xfce4-panel', )), 0, -1, None) except GLib.GError: # pylint: disable=E0712 pass if self.check_whiskermenu(): f = open(whiskermenu_path, 'wb') f.write(self.whiskermenu_data) f.close()
def _create_launcher(self): """ Creates a launcher to be used by the rust service. This needs to be run on the host because we do not currently bundle rust inside our flatpak. In the future, we might be able to rely on the runtime for the tooling. Maybe even the program if flatpak-builder has prebuilt our dependencies. """ launcher = Ide.SubprocessLauncher() launcher.set_flags( Gio.SubprocessFlags.STDIN_PIPE | Gio.SubprocessFlags.STDOUT_PIPE | Gio.SubprocessFlags.STDERR_SILENCE ) launcher.set_cwd(GLib.get_home_dir()) launcher.set_run_on_host(True) return launcher
def __init__(self): Clip.__init__(self) self.table = EasyTable(items=((Gtk.Label(label=_('Current user:'******'Home directory:')), Gtk.Label(label=GLib.get_home_dir())), (Gtk.Label(label=_('Shell:')), Gtk.Label(label=GLib.getenv('SHELL'))), (Gtk.Label(label=_('Language:')), Gtk.Label(label=GLib.getenv('LANG')))), xpadding=12, ypadding=2) self.add_content(self.table) self.show_all()
def __init__(self): Clip.__init__(self) self.table = EasyTable(items=( (Gtk.Label(label=_('Current user:'******'Home directory:')), Gtk.Label(label=GLib.get_home_dir())), (Gtk.Label(label=_('Shell:')), Gtk.Label(label=GLib.getenv('SHELL'))), (Gtk.Label(label=_('Language:')), Gtk.Label(label=GLib.getenv('LANG')))), xpadding=12, ypadding=2) self.add_content(self.table) self.show_all()
def __init__(self): self.operation = Gtk.PrintOperation() print_data = {'filename': 'printing.py', 'font_size': 12.0, 'lines_per_page': 0, 'lines': None, 'num_lines': 0, 'num_pages': 0 } self.operation.connect('begin-print', self.begin_print, print_data) self.operation.connect('draw-page', self.draw_page, print_data) self.operation.connect('end-print', self.end_print, print_data) self.operation.set_use_full_page(False) self.operation.set_unit(Gtk.Unit.POINTS) self.operation.set_embed_page_setup(True) settings = Gtk.PrintSettings() dir = GLib.get_user_special_dir(GLib.UserDirectory.DIRECTORY_DOCUMENTS) if dir is None: dir = GLib.get_home_dir() if settings.get(Gtk.PRINT_SETTINGS_OUTPUT_FILE_FORMAT) == 'ps': ext = '.ps' elif settings.get(Gtk.PRINT_SETTINGS_OUTPUT_FILE_FORMAT) == 'svg': ext = '.svg' else: ext = '.pdf' uri = "file://%s/gtk-demo%s" % (dir, ext); settings.set(Gtk.PRINT_SETTINGS_OUTPUT_URI, uri) self.operation.set_print_settings(settings) try: self.operation.run(Gtk.PrintOperationAction.PRINT_DIALOG, None) except GLib.Error as e: dialog = Gtk.MessageDialog(None, 0, Gtk.MessageType.ERROR, Gtk.ButtonsType.CLOSE, e.message) dialog.run() dialog.destroy()
def __init__(self, parentapp): GObject.GObject.__init__(self) gnomeglade.Component.__init__(self, "tab-placeholder.ui", "new_comparison_tab") self.map_widgets_into_lists(["file_chooser", "dir_chooser", "vc_chooser"]) self.button_types = [self.button_type_file, self.button_type_dir, self.button_type_vc] self.diff_methods = (parentapp.append_filediff, parentapp.append_dirdiff, parentapp.append_vcview) self.diff_type = -1 default_path = GLib.get_home_dir() for chooser in self.file_chooser: chooser.set_current_folder(default_path) self.widget.show()
def signal_metadata(self, url, artist=None, title=None): """ Get the lyrics using mutagen and give them to the callback. Keyword arguments: url -- location of the music file artist -- name of the song's artist, not used if the url is None title -- title of the song, not used if the url is None """ # default values to return path = None full_title = None lyrics = 'No lyrics' # if url is null, send an empty message with the default values # (happens when the player has just started and is not playing) # if not, extract lyrics if url != None: # decode path from url path = urllib.parse.urlparse(url).path path = urllib.parse.unquote(path) # extract the artist name and title # then create a window title from them full_title = artist + ' - ' + title try: # extract the lyrics from the file using mutagen tags = mutagen.id3.ID3(path) lyrics_tag = tags.getall('USLT') if len(lyrics_tag) > 0: lyrics = lyrics_tag[0].text except mutagen.id3.ID3NoHeaderError: # no lyrics in the file pass # do not return /home/username if we can replace it with '~' home = GLib.get_home_dir() if path.startswith(home): path = path.replace(home, '~', 1) self.callback_func(path, full_title, lyrics)