def startfile(filepath, operation="open"): """os.startfile / g_app_info_launch_default_for_uri compat This has the similar semantics to os.startfile, where it's supported: it launches the given file or folder path with the default app. On Windows, operation can be set to "edit" to use the default editor for a file. The operation parameter is ignored on other systems, and GIO's equivalent routine is used. The relevant app is started in the background, and there are no means for getting its pid. """ try: if os.name == 'nt': os.startfile(filepath, operation) # raises: WindowsError else: uri = GLib.filename_to_uri(filepath) Gio.app_info_launch_default_for_uri(uri, None) # raises: GError return True except: logger.exception( "Failed to launch the default application for %r (op=%r)", filepath, operation, ) return False
def determine_content_type(filename): ''' Determines the content type for a file. Returns either a string like 'application/pdf' or None if the type could not be determined. For files with a file extension, this function normally does only look at the filename, but if this is not sufficient for determining the content-type, the file can also be opened. ''' # Try the fast content type first gfile = Gio.file_new_for_path(filename) info = gfile.query_info(Gio.FILE_ATTRIBUTE_STANDARD_FAST_CONTENT_TYPE, Gio.FileQueryInfoFlags.NONE, None) content_type = info.get_attribute_as_string(Gio.FILE_ATTRIBUTE_STANDARD_FAST_CONTENT_TYPE) # If that did not work, try the full content-type determination if Gio.content_type_is_unknown(content_type): info = gfile.query_info(Gio.FILE_ATTRIBUTE_STANDARD_CONTENT_TYPE, Gio.FileQueryInfoFlags.NONE, None) content_type = info.get_attribute_as_string(Gio.FILE_ATTRIBUTE_STANDARD_CONTENT_TYPE) if Gio.content_type_is_unknown(content_type): content_type = None return content_type
def restore_session(self, window): uris = [] active_uri = '' uris = self.settings.get_value('uris') active_uri = self.settings.get_string('active-uri') set_active_uri = False if uris: # Close initial blank document if len(window.get_documents()) <= 1: tab = window.get_active_tab() if tab: doc = tab.get_document() if doc and doc.is_untouched(): window.close_tab(tab) # No other documents loaded, so safe to # restore the active URI from previous session set_active_uri = True # Create tabs for saved uris as necessary for uri in uris: location = Gio.file_new_for_uri(uri) tab = window.get_tab_from_location(location) if not tab: window.create_tab_from_location(location, \ None, 0, 0, False, False) if active_uri and set_active_uri: # Switch to the saved active URI location = Gio.file_new_for_uri(active_uri) tab = window.get_tab_from_location(location) if tab: window.set_active_tab(tab)
def start(self): if not pylirc: return p = select.poll() p.register(self.socket, select.POLLIN | select.POLLERR | select.POLLHUP | select.POLLNVAL) Gio.io_scheduler_push_job(self._do_poll, p, GLib.PRIORITY_DEFAULT, None)
def do_get_targets_async(self, cancellable, callback, data): task = Gio.Task.new(self, cancellable, callback) task.set_priority(GLib.PRIORITY_LOW) task.targets = [] context = self.get_context() build_system = Ide.BuildSystem.from_context(context) build_manager = Ide.BuildManager.from_context(context) pipeline = build_manager.get_pipeline() if pipeline is None or type(build_system) != WafBuildSystem: task.return_error(GLib.Error('No access to waf build system', domain=GLib.quark_to_string(Gio.io_error_quark()), code=Gio.IOErrorEnum.NOT_SUPPORTED)) return # For some reason, "waf list" outputs on stderr launcher = build_system._create_launcher(pipeline) launcher.set_flags(Gio.SubprocessFlags.STDOUT_SILENCE | Gio.SubprocessFlags.STDERR_PIPE) launcher.set_cwd(pipeline.get_srcdir()) launcher.push_argv('list') try: subprocess = launcher.spawn(cancellable) subprocess.communicate_utf8_async(None, cancellable, self.communicate_cb, task) except Exception as ex: task.return_error(GLib.Error(repr(ex), domain=GLib.quark_to_string(Gio.io_error_quark()), code=Gio.IOErrorEnum.FAILED))
def get_svg(model): resource = Gio.resources_lookup_data('/org/freedesktop/Piper/svgs/svg-lookup.ini', Gio.ResourceLookupFlags.NONE) data = resource.get_data() config = configparser.ConfigParser() config.read_string(data.decode('utf-8'), source='svg-lookup.ini') assert config.sections() filename = 'fallback.svg' if model.startswith('usb:') or model.startswith('bluetooth:'): bus, vid, pid, version = model.split(':') # Where the version is 0 (virtually all devices) we drop it. This # way the DeviceMatch lines are less confusing. if int(version) == 0: usbid = ':'.join([bus, vid, pid]) else: usbid = model for s in config.sections(): matches = config[s]['DeviceMatch'].split(';') if usbid in matches: filename = config[s]['Svg'] break resource = Gio.resources_lookup_data('/org/freedesktop/Piper/svgs/{}'.format(filename), Gio.ResourceLookupFlags.NONE) return resource.get_data()
def __init__(self): self.extension_point = Gio.io_extension_point_register ("cinnamon-control-center-1") self.modules = [] architecture = platform.machine() paths = ["/usr/lib"] # On x86 archs, iterate through multiple paths # For instance, on a Mint i686 box, the path is actually /usr/lib/i386-linux-gnu x86archs = ["i386", "i486", "i586", "i686"] if architecture in x86archs: for arch in x86archs: paths += ["/usr/lib/%s" % arch, "/usr/lib/%s-linux-gnu" % arch] elif architecture == "x86_64": paths += ["/usr/lib/x86_64", "/usr/lib/x86_64-linux-gnu", "/usr/lib64"] else: paths += ["/usr/lib/%s" % architecture, "/usr/lib/%s-linux-gnu" % architecture] for path in paths: path = os.path.join(path, "cinnamon-control-center-1/panels") if os.path.exists(path): try: self.modules = self.modules + Gio.io_modules_load_all_in_directory(path) except Exception, e: print "capi failed to load multiarch modules from %s: " % path, e
def __init__(self, bus, path): _IdleObject.__init__(self) self.con = Gio.bus_get_sync(Gio.BusType.SESSION, None) Gio.bus_own_name_on_connection(self.con, 'org.scarlett', Gio.BusNameOwnerFlags.NONE, None, None) Server.__init__(self, bus, path) super(ScarlettListener, self).__init__() self.dbus_stack = [] self.config = scarlett_config.Config() self._message = 'This is the DBusServer' self._status_ready = " ScarlettListener is ready" self._status_kw_match = " ScarlettListener caught a keyword match" self._status_cmd_match = " ScarlettListener caught a command match" self._status_stt_failed = " ScarlettListener hit Max STT failures" self._status_cmd_start = " ScarlettListener emitting start command" self._status_cmd_fin = " ScarlettListener Emitting Command run finish" self._status_cmd_cancel = " ScarlettListener cancel speech Recognition" self.dbus_stack.append(bus) self.dbus_stack.append(path) logger.debug("Inside self.dbus_stack") pp.pprint(self.dbus_stack)
def on_unload(self): Gio.bus_unwatch_name(self._connman_watch_id) self._connman_proxy = None if self._iom: GLib.source_remove(self._iom) if self._fd: os.close(self._fd)
def on_gac_open_directory_activate(self, action): selection = self._get_selected(self.lss_problems) if selection: Gio.app_info_launch_default_for_uri( 'file://' + selection[0].problem_id, None) self._builder.menu_problem_item.popdown() self._builder.menu_multiple_problems.popdown()
def os_save_subtitles(self, filename): if self.model.lock.acquire(False) == False: return True if self.model.subtitles: # Delete all previous cached subtitle for this file for ext in SUBTITLES_EXT: fp = Gio.file_new_for_path(filename[:-3] + ext) if fp.query_exists(None): fp.delete(None) fp = Gio.file_new_for_uri (filename) suburi = fp.get_uri () subFile = fp.replace ('', False, Gio.FileCreateFlags.REPLACE_DESTINATION, None) subFile.write (self.model.subtitles, None) subFile.close (None) self.model.lock.release() self.dialog.get_window().set_cursor(None) self.on_close_clicked (None) if suburi: self.totem.set_current_subtitle(suburi) return False
def __init__(self, app): self.con = Gio.bus_get_sync(Gio.BusType.SESSION, None) Gio.bus_own_name_on_connection(self.con, 'org.mpris.MediaPlayer2.GnomeMusic', Gio.BusNameOwnerFlags.NONE, None, None) super().__init__(self.con, '/org/mpris/MediaPlayer2') self.app = app self.player = app.props.player self.player.connect( 'song-changed', self._on_current_song_changed) self.player.connect('notify::state', self._on_player_state_changed) self.player.connect('notify::repeat-mode', self._on_repeat_mode_changed) self.player.connect('seek-finished', self._on_seek_finished) self.player.connect( 'playlist-changed', self._on_player_playlist_changed) self.player_toolbar = app.get_active_window()._player_toolbar self.player_toolbar.connect( 'thumbnail-updated', self._on_thumbnail_updated) playlists = Playlists.get_default() playlists.connect('playlist-created', self._on_playlists_count_changed) playlists.connect('playlist-deleted', self._on_playlists_count_changed) grilo.connect('ready', self._on_grilo_ready) self.playlists = [] self._player_previous_type = None self._path_list = [] self._metadata_list = [] self._previous_playback_status = "Stopped"
def on_dbus_connection_finnish(self, cancellable, result): self._bus = Gio.bus_get_finish(result) watch = Gio.bus_watch_name(Gio.BusType.SYSTEM, self.nm_manager_name, Gio.BusNameWatcherFlags.NONE, self.on_name_appeared, self.on_name_vanished) self.watch_id = watch
def __init__(self, data_dir, address, name, unique_name, connection_is_bus=True): self.data_dir = data_dir signal_dict = { 'treeview_row_activated_cb': self.__treeview_row_activated_cb, 'treeview_row_expanded_cb': self.__treeview_row_expanded_cb, 'button_reload_clicked_cb': self.__button_reload_clicked_cb, } self.address = address # can be Gio.BusType.SYSTEM or Gio.BusType.SYSTEM or other address self.name = name # the well-known name or None self.unique_name = unique_name # the unique name or None self.connection_is_bus = connection_is_bus # is it a bus or a p2p connection? # setup UI ui = UILoader(self.data_dir, UILoader.UI_INTROSPECTION) self.introspect_box = ui.get_root_widget() # this is the main box with the treeview self.__spinner = ui.get_widget('spinner') # progress during the introspection self.__scrolledwindow = \ ui.get_widget('scrolledwindow') # the scrolledwindow contains the treeview self.__treemodel = ui.get_widget('treestore') self.__treemodel.set_sort_func(0, self.__sort_model) self.__treemodel.set_sort_column_id(0, Gtk.SortType.ASCENDING) self.__treeview = ui.get_widget('treeview') self.__label_name = ui.get_widget('label_name') self.__label_unique_name = ui.get_widget('label_unique_name') self.__label_address = ui.get_widget('label_address') self.__messagedialog = ui.get_widget('messagedialog') self.__messagedialog.connect("close", self.__messagedialog_close_cb) # connect signals ui.connect_signals(signal_dict) if self.connection_is_bus: # we expect a bus connection if self.address == Gio.BusType.SYSTEM or self.address == Gio.BusType.SESSION: self.connection = Gio.bus_get_sync(self.address, None) self.__label_address.set_text( Gio.dbus_address_get_for_bus_sync(self.address, None)) elif Gio.dbus_is_address(self.address): self.connection = Gio.DBusConnection.new_for_address_sync( self.address, Gio.DBusConnectionFlags.AUTHENTICATION_CLIENT | Gio.DBusConnectionFlags.MESSAGE_BUS_CONNECTION, None, None) self.__label_address.set_text(self.address) else: self.connection = None raise Exception("Invalid bus address '%s'" % (self.address)) else: # we have a peer-to-peer connection if Gio.dbus_is_supported_address(self.address): self.connection = Gio.DBusConnection.new_for_address_sync( self.address, Gio.DBusConnectionFlags.AUTHENTICATION_CLIENT, None, None) self.__label_address.set_text(self.address) else: self.connection = None raise Exception("Invalid p2p address '%s'" % (self.address)) # start processing data self.introspect_start()
def __init__(self): # First, try with logind try: bus = Gio.bus_get_sync(Gio.BusType.SYSTEM, None) bus.call_sync("org.freedesktop.login1", "/org/freedesktop/login1", "org.freedesktop.login1.Manager", "PowerOff", GLib.Variant_boolean('(bb)', (False, False)), None, Gio.DBusCallFlags.NONE, -1, None) except: failure = True if (failure): failure = False # If it fails, try with ConsoleKit try: bus = Gio.bus_get_sync(Gio.BusType.SYSTEM, None) bus.call_sync("org.freedesktop.ConsoleKit", "/org/freedesktop/ConsoleKit/Manager", "org.freedesktop.ConsoleKit.Manager", "Stop", None, None, Gio.DBusCallFlags.NONE, -1, None) except: failure = True if (failure): failure = False # If it fails, try with HAL try: bus = Gio.bus_get_sync(Gio.BusType.SYSTEM, None) bus.call_sync("org.freedesktop.Hal", "/org/freedesktop/Hal/devices/computer", "org.freedesktop.Hal.Device.SystemPowerManagement", "Shutdown", None, None, Gio.DBusCallFlags.NONE, -1, None) except: failure = True
def on_archive_gbutton_clicked(self, button, window): tags = [tag for tag in self.tag_settings] for tag in tags: file_uris = self.tracker.tagged_files(tag) if file_uris: errors = 0 for f in file_uris: try: source_file = Gio.file_new_for_uri(f) target_file = Gio.file_new_for_uri("/".join((self.tag_settings[tag][1], source_file.get_basename()))) tag_removed = self.tracker.remove_tag(f, tag) if tag_removed: source_file.move(target_file, Gio.FileCopyFlags.NONE, None, None, None) button.set_sensitive(False) button.set_label("Nothing to Archive") else: raise Exception("Unable to remove tag") except: self.tracker.add_tag(f, tag) errors +=1 raise if errors: dialog = Gtk.MessageDialog(window, 0, Gtk.MessageType.ERROR, Gtk.ButtonsType.OK, "No Files Archived") dialog.format_secondary_text("There was an error when trying to move $s files to the archive" % errors) dialog.run() dialog.destroy()
def update_model(self, filter=False, all=False): self.model.clear() mainwindow = self.get_toplevel().window if mainwindow: mainwindow.set_cursor(Gdk.Cursor.new(Gdk.CursorType.WATCH)) while Gtk.events_pending (): Gtk.main_iteration () theme = Gtk.IconTheme.get_default() for type in Gio.content_types_get_registered(): if filter and filter != type.split('/')[0]: continue pixbuf = icon.get_from_mime_type(type) description = Gio.content_type_get_description(type) app = Gio.app_info_get_default_for_type(type, False) if app: appname = app.get_name() applogo = icon.get_from_app(app) elif all and not app: appname = _('None') applogo = None else: continue self.model.append((type, pixbuf, description, applogo, appname)) if mainwindow: mainwindow.set_cursor(None)
def gio_copy_in_place(self, file): "helper that copies the file to the local system via gio" gio_file = Gio.file_new_for_path(file) if (gio_file.get_uri_scheme() == "file"): return file if (os.getuid()==0): self.show_alert(Gtk.MessageType.ERROR, _("Can not download as root"), _("Remote packages can not be downloaded when " "running as root. Please try again as a " "normal user.")) sys.exit(1) # Download the file temp_file_name = os.path.join(tempfile.mkdtemp(),os.path.basename(file)) gio_dest = Gio.file_new_for_path(temp_file_name) try: # download gio_cancellable = Gio.Cancellable() self.button_cancel_download.connect("clicked", self.on_button_cancel_download_clicked, gio_cancellable) self.dialog_gio_download.set_transient_for(self.window_main) self.dialog_gio_download.show() self.label_action.set_text(_("Downloading package")) if gio_file.copy(gio_dest, 0, gio_cancellable, self.gio_progress_callback, 0): file = gio_dest.get_path() self.dialog_gio_download.hide() except Exception as e: self.show_alert(Gtk.MessageType.ERROR, _("Download failed"), _("Downloading the package failed: " "file '%s' '%s'") % (file, e)) sys.exit(1) return file
def __default__(filename, view): """Edit file: edit <filename>""" doc = view.get_buffer() cwd = os.getcwd() if not doc.is_untitled(): cwd = doc.get_file().get_location().get_parent().get_path() else: cwd = os.path.expanduser('~/') if not os.path.isabs(filename): filename = os.path.join(cwd, filename) matches = glob.glob(filename) files = [] if matches: for match in matches: files.append(Gio.file_new_for_path(match)) else: files.append(Gio.file_new_for_path(filename)) if files: window = view.get_toplevel() Gedit.commands_load_locations(window, files, None, 0, 0) return commander.commands.result.HIDE
def _save_subtitles (self, download_thread, filename): if not download_thread.done: return True subtitles = download_thread.get_subtitles () if subtitles: # Delete all previous cached subtitle for this file for ext in SUBTITLES_EXT: subtitle_file = Gio.file_new_for_path (filename[:-3] + ext) if subtitle_file.query_exists (None): subtitle_file.delete (None) subtitle_file = Gio.file_new_for_uri (filename) suburi = subtitle_file.get_uri () flags = Gio.FileCreateFlags.REPLACE_DESTINATION sub_file = subtitle_file.replace ('', False, flags, None) sub_file.write (subtitles, None) sub_file.close (None) self._dialog.get_window ().set_cursor (None) self._close_dialog () if suburi: self._xplayer.set_current_subtitle (suburi) return False
def update_model(self, filter=False, all=False): self.model.clear() theme = Gtk.IconTheme.get_default() for mime_type in Gio.content_types_get_registered(): if filter and filter != mime_type.split('/')[0]: continue # TODO why enabling this will make ui freeze even I try to add @post_ui # while Gtk.events_pending (): # Gtk.main_iteration () pixbuf = icon.get_from_mime_type(mime_type) description = Gio.content_type_get_description(mime_type) app = Gio.app_info_get_default_for_type(mime_type, False) if app: appname = app.get_name() applogo = icon.get_from_app(app) elif all and not app: appname = _('None') applogo = None else: continue self.model.append((mime_type, pixbuf, description, applogo, appname))
def _save_selected_subtitle (self, filename=None): cursor = Gdk.Cursor.new (Gdk.CursorType.WATCH) self._dialog.get_window ().set_cursor (cursor) model, rows = self._tree_view.get_selection ().get_selected_rows () if rows: subtitle_iter = model.get_iter (rows[0]) subtitle_id = model.get_value (subtitle_iter, 3) subtitle_format = model.get_value (subtitle_iter, 1) if not filename: bpath = GLib.get_user_cache_dir() + sep bpath += 'xplayer' + sep directory = Gio.file_new_for_path (bpath + 'subtitles' + sep) if not directory.query_exists (None): directory.make_directory_with_parents (None); subtitle_file = Gio.file_new_for_path (self._filename) movie_name = subtitle_file.get_basename ().rpartition ('.')[0] filename = directory.get_uri () + sep filename += movie_name + '.' + subtitle_format thread = DownloadThread (self._model, subtitle_id) thread.start () GObject.idle_add (self._save_subtitles, thread, filename) self._progress.set_text (_(u'Downloading the subtitles…')) GLib.timeout_add (350, self._progress_bar_increment, thread) else: #warn user! pass
def on_folder_clicked(self, widget): dialog = Gtk.FileChooserDialog("Please choose a playback folder", self.window, Gtk.FileChooserAction.SELECT_FOLDER, (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL, Gtk.STOCK_OPEN, Gtk.ResponseType.OK)) response = dialog.run() if response == Gtk.ResponseType.OK: folder = dialog.get_current_folder() filelist = list() for i in os.listdir(folder): fpath = os.path.join(folder, i) content_type, val = Gio.content_type_guess(filename=fpath, data=None) print(fpath, content_type, Gio.content_type_is_a(content_type, 'audio/*') or Gio.content_type_is_a(content_type, 'image/*') or Gio.content_type_is_a(content_type, 'video/*')) if Gio.content_type_is_a(content_type, 'audio/*') or Gio.content_type_is_a(content_type, 'image/*') or Gio.content_type_is_a(content_type, 'video/*'): filelist.append(fpath) filelist = sorted(filelist) if (len(filelist)): self.model.clear() for i in range(len(filelist)): print("model append ", len(self.model), i, filelist[i]) self.model.append([i, filelist[i]]) tp = Gtk.TreePath.new_from_indices([0]) iter = self.model.get_iter(tp) self.selection.select_iter(iter) elif response == Gtk.ResponseType.CANCEL: print("Cancel clicked") dialog.destroy()
def _add_items_for_single_cell(self, model, value): if model.is_blob_value(value): content_type = Gio.content_type_guess(None, value)[0] if Gio.app_info_get_all_for_type(content_type): item = Gtk.MenuItem('View contents') item.connect( 'activate', lambda *a: self.view_blob_contents(value, content_type)) item.show() self.cell_menu.append(item) item = Gtk.MenuItem('Save contents') item.connect( 'activate', lambda *a: self.save_blob_contents(value, content_type)) item.show() self.cell_menu.append(item) else: item = Gtk.MenuItem('Copy value to clipboard') item.connect('activate', lambda *a: self.copy_value_to_clipboard(value)) item.show() self.cell_menu.append(item) item = Gtk.MenuItem('View value') item.connect('activate', lambda *a: self.view_value(value)) item.show() self.cell_menu.append(item)
def __init__(self, app): self.con = Gio.bus_get_sync(Gio.BusType.SESSION, None) Gio.bus_own_name_on_connection(self.con, 'org.mpris.MediaPlayer2.GnomeMusic', Gio.BusNameOwnerFlags.NONE, None, None) super().__init__(self.con, '/org/mpris/MediaPlayer2') self.app = app self.player = app.get_active_window().player self.player.connect('current-changed', self._on_current_changed) self.player.connect('thumbnail-updated', self._on_thumbnail_updated) self.player.connect('playback-status-changed', self._on_playback_status_changed) self.player.connect('repeat-mode-changed', self._on_repeat_mode_changed) self.player.connect('volume-changed', self._on_volume_changed) self.player.connect('prev-next-invalidated', self._on_prev_next_invalidated) self.player.connect('seeked', self._on_seeked) self.player.connect('playlist-changed', self._on_playlist_changed) playlists = Playlists.get_default() playlists.connect('playlist-created', self._on_playlists_count_changed) playlists.connect('playlist-deleted', self._on_playlists_count_changed) grilo.connect('ready', self._on_grilo_ready) self.playlists = [] self.playlist = None self.playlist_insert_handler = 0 self.playlist_delete_handler = 0 self.first_song_handler = 0
def register(self, name, port, stype): """Register the service with avahi. Can be called multiple times and will update the service entry each time. In case Avahi isn't running or ready, the service will be registered when it is ready. Can raise AvahiError """ try: GLib.Variant('q', port) # guint16 except OverflowError as e: raise AvahiError(e) self.name = name self._real_name = name self.port = port self.stype = stype try: bus = Gio.bus_get_sync(Gio.BusType.SYSTEM, None) if not self._watch: self._watch = Gio.bus_watch_name_on_connection( bus, self.DBUS_NAME, Gio.BusNameWatcherFlags.NONE, self._owner_appeared, self._owner_vanished) else: self._try_update_service() except GLib.Error as e: raise AvahiError(e)
def stop (self): if self.process is None: # Seems that it didn't even start... return start = time.time() if self.process.poll() == None: GLib.source_remove(self.process_watch_timeout) self.process_watch_timeout = 0 self.process.terminate() while self.process.poll() == None: time.sleep(0.1) if time.time() > (start + REASONABLE_TIMEOUT): log ("[%s] Failed to terminate, sending kill!" % self.PROCESS_NAME) self.process.kill() self.process.wait() log ("[%s] stopped." % self.PROCESS_NAME) # Run the loop until the bus name appears, or the process dies. self.loop.run () Gio.bus_unwatch_name(self._bus_name_watch_id) self.process = None
def unwatch_all(self): for (handle, name) in self.owned_names: if status.Debug: print("Releasing dbus name: %s" % name) Gio.bus_unown_name(handle) self.owned_names = []
def cb_loadfile(self, path, args): if args[0] == 1.0 and args[0] < len(self.model): model, iter = self.selection.get_selected() filename = model[iter][Application.COL_FILEPATH] content_type, val = Gio.content_type_guess(filename=filename, data=None) if (Gio.content_type_is_a(content_type, 'image/*')): self.oscbridge.send_command('loadfile "mf://%s"'%(filename)) self.oscbridge.send_command('loadfile "%s"'%(filename))
def enabled(self): try: bus = Gio.bus_get_sync(Gio.BusType.SESSION, None) self.__watch = Gio.bus_watch_name_on_connection( bus, self.DBUS_NAME, Gio.BusNameWatcherFlags.NONE, self.__owner_appeared, self.__owner_vanished) except GLib.Error: pass
def run(self, procedure, run_mode, image, drawable, args, run_data): if run_mode == Gimp.RunMode.INTERACTIVE: gi.require_version('Gtk', '3.0') from gi.repository import Gtk gi.require_version('Gdk', '3.0') from gi.repository import Gdk Gimp.ui_init("palette-offset.py") dialog = Gimp.Dialog(use_header_bar=True, title=_("Exercise a goat (Python 3)"), role="goat-exercise-Python3") dialog.add_button("_Cancel", Gtk.ResponseType.CANCEL) dialog.add_button("_Source", Gtk.ResponseType.APPLY) dialog.add_button("_OK", Gtk.ResponseType.OK) geometry = Gdk.Geometry() geometry.min_aspect = 0.5 geometry.max_aspect = 1.0 dialog.set_geometry_hints(None, geometry, Gdk.WindowHints.ASPECT) box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=2) dialog.get_content_area().add(box) box.show() # XXX We use printf-style string for sharing the localized # string. You may just use recommended Python format() or # any style you like in your plug-ins. head_text = ("This plug-in is an exercise in '%s' to " "demo plug-in creation.\nCheck out the last " "version of the source code online by clicking " "the \"Source\" button." % ("Python 3")) label = Gtk.Label(label=head_text) box.pack_start(label, False, False, 1) label.show() contents = None # Get the file contents Python-style instead of using # GLib.file_get_contents() which returns bytes result, and # when converting to string, get newlines as text contents. # Rather than wasting time to figure this out, use Python # core API! with open(os.path.realpath(__file__), 'r') as f: contents = f.read() if contents is not None: scrolled = Gtk.ScrolledWindow() scrolled.set_vexpand(True) box.pack_start(scrolled, True, True, 1) scrolled.show() view = Gtk.TextView() view.set_wrap_mode(Gtk.WrapMode.WORD) view.set_editable(False) buffer = view.get_buffer() buffer.set_text(contents, -1) scrolled.add(view) view.show() while (True): response = dialog.run() if response == Gtk.ResponseType.OK: dialog.destroy() break elif response == Gtk.ResponseType.APPLY: Gio.app_info_launch_default_for_uri(url, None) continue else: dialog.destroy() return procedure.new_return_values( Gimp.PDBStatusType.CANCEL, GLib.Error()) intersect, x, y, width, height = drawable.mask_intersect() if intersect: Gegl.init(None) buffer = drawable.get_buffer() shadow_buffer = drawable.get_shadow_buffer() graph = Gegl.Node() input = graph.create_child("gegl:buffer-source") input.set_property("buffer", buffer) invert = graph.create_child("gegl:invert") output = graph.create_child("gegl:write-buffer") output.set_property("buffer", shadow_buffer) input.link(invert) invert.link(output) output.process() # This is extremely important in bindings, since we don't # unref buffers. If we don't explicitly flush a buffer, we # may left hanging forever. This step is usually done # during an unref(). shadow_buffer.flush() drawable.merge_shadow(True) drawable.update(x, y, width, height) Gimp.displays_flush() return procedure.new_return_values(Gimp.PDBStatusType.SUCCESS, GLib.Error())
def get_gender(): settings = Gio.Settings('org.sugarlabs.user') return settings.get_string('gender')
def on_module_selected(self): if not self.loaded: print "Loading Backgrounds module" self.sidePage.stack = SettingsStack() self.sidePage.add_widget(self.sidePage.stack) self.shown_collection = None # Which collection is displayed in the UI self._background_schema = Gio.Settings( schema="org.cinnamon.desktop.background") self._slideshow_schema = Gio.Settings( schema="org.cinnamon.desktop.background.slideshow") self._slideshow_schema.connect("changed::slideshow-enabled", self.on_slideshow_enabled_changed) self.add_folder_dialog = Gtk.FileChooserDialog( title=_("Add Folder"), action=Gtk.FileChooserAction.SELECT_FOLDER, buttons=(Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL, Gtk.STOCK_OPEN, Gtk.ResponseType.OK)) self.xdg_pictures_directory = os.path.expanduser("~/Pictures") xdg_config = os.path.expanduser("~/.config/user-dirs.dirs") if os.path.exists(xdg_config) and os.path.exists( "/usr/bin/xdg-user-dir"): path = subprocess.check_output(["xdg-user-dir", "PICTURES"]).rstrip("\n") if os.path.exists(path): self.xdg_pictures_directory = path self.get_user_backgrounds() # Images mainbox = Gtk.Box.new(Gtk.Orientation.HORIZONTAL, 2) mainbox.expand = True mainbox.set_border_width(8) self.sidePage.stack.add_titled(mainbox, "images", _("Images")) left_vbox = Gtk.Box.new(Gtk.Orientation.VERTICAL, 0) right_vbox = Gtk.Box.new(Gtk.Orientation.VERTICAL, 0) folder_scroller = Gtk.ScrolledWindow.new(None, None) folder_scroller.set_shadow_type(Gtk.ShadowType.IN) folder_scroller.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC) folder_scroller.set_property("min-content-width", 150) self.folder_tree = Gtk.TreeView.new() self.folder_tree.set_headers_visible(False) folder_scroller.add(self.folder_tree) button_toolbar = Gtk.Toolbar.new() button_toolbar.set_icon_size(1) Gtk.StyleContext.add_class( Gtk.Widget.get_style_context(button_toolbar), "inline-toolbar") self.add_folder_button = Gtk.ToolButton.new(None, None) self.add_folder_button.set_icon_name("list-add-symbolic") self.add_folder_button.set_tooltip_text(_("Add new folder")) self.add_folder_button.connect("clicked", lambda w: self.add_new_folder()) self.remove_folder_button = Gtk.ToolButton.new(None, None) self.remove_folder_button.set_icon_name("list-remove-symbolic") self.remove_folder_button.set_tooltip_text( _("Remove selected folder")) self.remove_folder_button.connect("clicked", lambda w: self.remove_folder()) button_toolbar.insert(self.add_folder_button, 0) button_toolbar.insert(self.remove_folder_button, 1) image_scroller = Gtk.ScrolledWindow.new(None, None) image_scroller.set_shadow_type(Gtk.ShadowType.IN) image_scroller.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC) self.icon_view = ThreadedIconView() image_scroller.add(self.icon_view) self.icon_view.connect("selection-changed", self.on_wallpaper_selection_changed) right_vbox.pack_start(image_scroller, True, True, 0) left_vbox.pack_start(folder_scroller, True, True, 0) left_vbox.pack_start(button_toolbar, False, False, 0) mainbox.pack_start(left_vbox, False, False, 2) mainbox.pack_start(right_vbox, True, True, 2) left_vbox.set_border_width(2) right_vbox.set_border_width(2) self.collection_store = Gtk.ListStore( bool, # is separator str, # Icon name str, # Display name str, # Path str) # Type of collection cell = Gtk.CellRendererText() cell.set_alignment(0, 0) pb_cell = Gtk.CellRendererPixbuf() self.folder_column = Gtk.TreeViewColumn() self.folder_column.pack_start(pb_cell, False) self.folder_column.pack_start(cell, True) self.folder_column.add_attribute(pb_cell, "icon-name", 1) self.folder_column.add_attribute(cell, "text", 2) self.folder_column.set_alignment(0) self.folder_tree.append_column(self.folder_column) self.folder_tree.connect("cursor-changed", self.on_folder_source_changed) self.get_system_backgrounds() tree_separator = [True, None, None, None, None] self.collection_store.append(tree_separator) if len(self.user_backgrounds) > 0: for item in self.user_backgrounds: self.collection_store.append(item) self.folder_tree.set_model(self.collection_store) self.folder_tree.set_row_separator_func(self.is_row_separator, None) self.get_initial_path() # Settings page = SettingsPage() settings = page.add_section(_("Background Settings")) size_group = Gtk.SizeGroup.new(Gtk.SizeGroupMode.HORIZONTAL) self.sidePage.stack.add_titled(page, "settings", _("Settings")) widget = GSettingsSwitch( _("Play backgrounds as a slideshow"), "org.cinnamon.desktop.background.slideshow", "slideshow-enabled") settings.add_row(widget) widget = GSettingsSpinButton( _("Delay"), "org.cinnamon.desktop.background.slideshow", "delay", _("minutes"), 1, 1440) settings.add_reveal_row( widget, "org.cinnamon.desktop.background.slideshow", "slideshow-enabled") widget = GSettingsSwitch( _("Play images in random order"), "org.cinnamon.desktop.background.slideshow", "random-order") settings.add_reveal_row( widget, "org.cinnamon.desktop.background.slideshow", "slideshow-enabled") widget = GSettingsComboBox(_("Picture aspect"), "org.cinnamon.desktop.background", "picture-options", BACKGROUND_PICTURE_OPTIONS, size_group=size_group) settings.add_row(widget) widget = GSettingsComboBox(_("Background gradient"), "org.cinnamon.desktop.background", "color-shading-type", BACKGROUND_COLOR_SHADING_TYPES, size_group=size_group) settings.add_reveal_row(widget, "org.cinnamon.desktop.background", "picture-options", PICTURE_OPTIONS_NEEDS_COLOR) widget = GSettingsColorChooser(_("Gradient start color"), "org.cinnamon.desktop.background", "primary-color", legacy_string=True, size_group=size_group) settings.add_reveal_row(widget, "org.cinnamon.desktop.background", "picture-options", PICTURE_OPTIONS_NEEDS_COLOR) self._background_schema.connect("changed::picture-options", self.update_secondary_revealer) self._background_schema.connect("changed::color-shading-type", self.update_secondary_revealer) widget = GSettingsColorChooser(_("Gradient end color"), "org.cinnamon.desktop.background", "secondary-color", legacy_string=True, size_group=size_group) self.secondary_color_revealer = settings.add_reveal_row(widget) self.update_secondary_revealer(self._background_schema, None)
def __init__(self) -> None: super().__init__() self.scheduler = FifoScheduler() self.num_panes = 0 self.view_action_group = Gio.SimpleActionGroup() self._state = ComparisonState.Normal
def __init__(self, app, file_handler): self.group_lists = {} self.app = app self.visible_group = None self.dragged_note = None self.file_handler = file_handler self.file_handler.connect('group-changed', self.on_list_changed) self.builder = Gtk.Builder.new_from_file( '/usr/share/sticky/manager.ui') self.window = self.builder.get_object('main_window') self.group_list = self.builder.get_object('group_list') self.note_view = self.builder.get_object('note_view') def create_group_entry(item): widget = Gtk.ListBoxRow() widget.drag_dest_set( Gtk.DestDefaults.MOTION | Gtk.DestDefaults.HIGHLIGHT, NOTE_TARGETS, Gdk.DragAction.MOVE) widget.connect('drag-drop', self.handle_drop) widget.item = item box = Gtk.Box() widget.add(box) label = Gtk.Label(label=item.name, halign=Gtk.Align.START, margin=5) box.pack_start(label, True, True, 10) if item.is_default: box.pack_end( Gtk.Image.new_from_icon_name('emblem-default-symbolic', Gtk.IconSize.BUTTON), False, False, 10) elif item.visible: box.pack_end( Gtk.Image.new_from_icon_name('group-visible-symbolic', Gtk.IconSize.BUTTON), False, False, 10) return widget self.group_model = Gio.ListStore() self.group_list.bind_model(self.group_model, create_group_entry) self.group_list.connect('row-selected', self.generate_previews) self.builder.get_object('new_note').connect('clicked', self.new_note) self.builder.get_object('remove_note').connect('clicked', self.remove_note) self.builder.get_object('preview_group').connect( 'clicked', self.preview_group) self.builder.get_object('set_default').connect('clicked', self.set_default) main_menu = Gtk.Menu() item = Gtk.MenuItem(label=_("New Group")) item.connect('activate', self.new_group) main_menu.append(item) item = Gtk.MenuItem(label=_("Remove Group")) item.connect('activate', self.remove_group) main_menu.append(item) main_menu.append(Gtk.SeparatorMenuItem(visible=True)) item = Gtk.MenuItem(label=_("Back Up Notes")) item.connect('activate', self.file_handler.save_backup) main_menu.append(item) item = Gtk.MenuItem(label=_("Back Up To File")) item.connect('activate', self.file_handler.backup_to_file) main_menu.append(item) item = Gtk.MenuItem(label=_("Restore Backup")) item.connect('activate', self.file_handler.restore_backup) main_menu.append(item) main_menu.append(Gtk.SeparatorMenuItem(visible=True)) item = Gtk.MenuItem(label=_("Settings")) item.connect('activate', self.app.open_settings_window) main_menu.append(item) main_menu.show_all() self.builder.get_object('menu_button').set_popup(main_menu) self.generate_group_list() self.window.show_all()
def get_publish_information(): settings = Gio.Settings('org.sugarlabs.collaboration') publish = settings.get_boolean('publish-gadget') return publish
def get_jabber(): settings = Gio.Settings('org.sugarlabs.collaboration') return settings.get_string('jabber-server')
error_handler=on_register_failed) def unregister_agent(self, agent_path): def on_unregistered(): dprint(agent_path) def on_unregister_failed(error): dprint(agent_path, error) self._interface.UnregisterAgent(agent_path, reply_handler=on_unregistered, error_handler=on_unregister_failed) if __name__ == '__main__': settings = Gio.Settings("org.blueberry") if settings.get_boolean("obex-enabled"): try: dbus.mainloop.glib.DBusGMainLoop(set_as_default=True) mainloop = GObject.MainLoop() service = TransferService() service.load() cont = True while cont: try: mainloop.run() except KeyboardInterrupt: service.unload() cont = False except Exception as e: dprint("Something went wrong in blueberry-obex-agent: %s" % e)
def get_timezone(): settings = Gio.Settings('org.sugarlabs.date') return settings.get_string('timezone')
def __init__(self, object, button): """ Init widget @param object as Track/Album @param button as Gtk.Button """ Gtk.Grid.__init__(self) self.__object = object self.__button = button can_launch = False if self.__object.is_web: if Type.CHARTS in self.__object.genre_ids: if isinstance(self.__object, Album): save = HoverWidget('document-save-symbolic', self.__save_object) save.set_tooltip_text(_("Save into collection")) save.set_margin_end(10) save.show() self.add(save) else: trash = HoverWidget('user-trash-symbolic', self.__remove_object) if isinstance(self.__object, Album): trash.set_tooltip_text(_("Remove album")) else: trash.set_tooltip_text(_("Remove track")) trash.set_margin_end(10) trash.show() self.add(trash) else: # Check portal for tag editor try: bus = Gio.bus_get_sync(Gio.BusType.SESSION, None) proxy = Gio.DBusProxy.new_sync(bus, Gio.DBusProxyFlags.NONE, None, 'org.gnome.Lollypop.Portal', '/org/gnome/LollypopPortal', 'org.gnome.Lollypop.Portal', None) can_launch = proxy.call_sync('CanLaunchTagEditor', None, Gio.DBusCallFlags.NO_AUTO_START, 500, None)[0] except: print("You are missing lollypop-portal: " "https://github.com/gnumdk/lollypop-portal") if can_launch: edit = HoverWidget('document-properties-symbolic', self.__edit_tags) edit.set_tooltip_text(_("Modify information")) edit.set_margin_end(10) edit.show() self.add(edit) if Type.CHARTS not in self.__object.genre_ids: playlist = HoverWidget('view-list-symbolic', self.__show_playlist_manager) playlist.set_tooltip_text(_("Playlists")) playlist.show() self.add(playlist) if isinstance(self.__object, Album): if Lp().player.album_in_queue(self.__object): queue = HoverWidget('list-remove-symbolic', self.__add_to_queue) queue.set_tooltip_text(_("Remove from queue")) else: queue = HoverWidget('list-add-symbolic', self.__add_to_queue) queue.set_tooltip_text(_("Add to queue")) queue.set_margin_start(10) queue.show() self.add(queue) else: if self.__object.is_web: web = Gtk.LinkButton(self.__object.uri) icon = Gtk.Image.new_from_icon_name('web-browser-symbolic', Gtk.IconSize.MENU) web.set_image(icon) web.get_style_context().add_class('no-padding') web.set_margin_start(5) web.set_tooltip_text(self.__object.uri) web.show_all() uri = "https://www.youtube.com/results?search_query=%s" %\ (self.__object.artists[0] + " " + self.__object.name,) search = Gtk.LinkButton(uri) icon = Gtk.Image.new_from_icon_name('edit-find-symbolic', Gtk.IconSize.MENU) search.set_image(icon) search.get_style_context().add_class('no-padding') search.set_tooltip_text(uri) search.show_all() self.add(web) self.add(search) if Type.CHARTS not in self.__object.genre_ids: rating = RatingWidget(object) rating.set_margin_top(5) rating.set_margin_end(10) rating.set_margin_bottom(5) rating.set_property('halign', Gtk.Align.END) rating.set_property('hexpand', True) rating.show() loved = LovedWidget(object) loved.set_margin_end(5) loved.set_margin_top(5) loved.set_margin_bottom(5) loved.show() self.add(rating) self.add(loved)
# the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA # from gi.repository import Gio bus = Gio.bus_get_sync(Gio.BusType.SESSION, None) connection = Gio.DBusProxy.new_sync(bus, Gio.DBusProxyFlags.NONE, None, 'org.hexchat.service', '/org/hexchat/Remote', 'org.hexchat.connection', None) path = connection.Connect('(ssss)', 'example.py', 'Python example', 'Example of a D-Bus client written in python', '1.0') hexchat = Gio.DBusProxy.new_sync(bus, Gio.DBusProxyFlags.NONE, None, 'org.hexchat.service', path, 'org.hexchat.plugin', None) # Note the type before every arguement, this must be done. # Type requirements are listed in our docs and characters are listed in the dbus docs. # s = string, u = uint, i = int, etc. channels = hexchat.ListGet('(s)', "channels")
def create_headerbar(self): """Create the headerbar""" hbar = Gtk.HeaderBar() hbar.props.show_close_button = True hbar.props.title = APP_NAME box = Gtk.Box() Gtk.StyleContext.add_class(box.get_style_context(), "linked") if os.name == 'nt': icon_size = Gtk.IconSize.BUTTON else: icon_size = Gtk.IconSize.LARGE_TOOLBAR # create the preview button self.preview_button = Gtk.Button.new_from_icon_name( 'edit-find', icon_size) self.preview_button.set_always_show_image(True) self.preview_button.connect( 'clicked', lambda *dummy: self.preview_or_run_operations(False)) self.preview_button.set_tooltip_text( _("Preview files in the selected operations (without deleting any files)")) # TRANSLATORS: This is the preview button on the main window. It # previews changes. self.preview_button.set_label(_('Preview')) box.add(self.preview_button) # create the delete button self.run_button = Gtk.Button.new_from_icon_name( 'edit-clear-all', icon_size) self.run_button.set_always_show_image(True) # TRANSLATORS: This is the clean button on the main window. # It makes permanent changes: usually deleting files, sometimes # altering them. self.run_button.set_label(_('Clean')) self.run_button.set_tooltip_text( _("Clean files in the selected operations")) self.run_button.connect("clicked", self.run_operations) box.add(self.run_button) # stop cleaning self.stop_button = Gtk.Button.new_from_icon_name( 'process-stop', icon_size) self.stop_button.set_always_show_image(True) self.stop_button.set_label(_('Abort')) self.stop_button.set_tooltip_text( _('Abort the preview or cleaning process')) self.stop_button.set_sensitive(False) self.stop_button.connect('clicked', self.cb_stop_operations) box.add(self.stop_button) hbar.pack_start(box) # Add hamburger menu on the right. # This is not needed for Microsoft Windows because other code places its # menu on the left side. if os.name == 'nt': return hbar menu_button = Gtk.MenuButton() icon = Gio.ThemedIcon(name="open-menu-symbolic") image = Gtk.Image.new_from_gicon(icon, Gtk.IconSize.BUTTON) builder = Gtk.Builder() builder.add_from_file(bleachbit.app_menu_filename) menu_button.set_menu_model(builder.get_object('app-menu')) menu_button.add(image) hbar.pack_end(menu_button) return hbar
def do_query_procedures(self): # Localization self.set_translation_domain( "gimp30-python", Gio.file_new_for_path(Gimp.locale_directory())) return ["goat-exercise-python"]
def save_album_artwork(self, data, album_id): """ Save data for album id @param data as bytes @param album id as int """ try: album = Album(album_id) arturi = None # Check portal for kid3-cli can_set_cover = False try: bus = Gio.bus_get_sync(Gio.BusType.SESSION, None) proxy = Gio.DBusProxy.new_sync( bus, Gio.DBusProxyFlags.NONE, None, 'org.gnome.Lollypop.Portal', '/org/gnome/LollypopPortal', 'org.gnome.Lollypop.Portal', None) can_set_cover = proxy.call_sync( 'CanSetCover', None, Gio.DBusCallFlags.NO_AUTO_START, 500, None)[0] except: print("You are missing lollypop-portal: " "https://github.com/gnumdk/lollypop-portal") save_to_tags = Lp().settings.get_value('save-to-tags') and\ can_set_cover and not album.is_web uri_count = Lp().albums.get_uri_count(album.uri) filename = self.get_album_cache_name(album) + ".jpg" if save_to_tags: t = Thread(target=self.__save_artwork_tags, args=(data, album)) t.daemon = True t.start() store_path = self._STORE_PATH + "/" + filename if album.uri == "" or is_readonly(album.uri): arturi = GLib.filename_to_uri(store_path) # Many albums with same path, suffix with artist_album name elif uri_count > 1: arturi = album.uri + "/" + filename favorite_uri = album.uri + "/" + self.__favorite favorite = Lio.File.new_for_uri(favorite_uri) if favorite.query_exists(): favorite.trash() else: arturi = album.uri + "/" + self.__favorite f = Lio.File.new_for_uri(arturi) # Update cover file if exists even if we have written to tags if not save_to_tags or f.query_exists(): stream = Gio.MemoryInputStream.new_from_data(data, None) pixbuf = GdkPixbuf.Pixbuf.new_from_stream_at_scale( stream, ArtSize.MONSTER, ArtSize.MONSTER, True, None) stream.close() pixbuf.savev(store_path, "jpeg", ["quality"], [str(Lp().settings.get_value( 'cover-quality').get_int32())]) dst = Lio.File.new_for_uri(arturi) src = Lio.File.new_for_path(store_path) src.move(dst, Gio.FileCopyFlags.OVERWRITE, None, None) del pixbuf self.clean_album_cache(album) GLib.idle_add(self.album_artwork_update, album.id) except Exception as e: print("Art::save_album_artwork(): %s" % e)
def _add_default_conn(self): """ If there's no cached connections, or any requested on the command line, try to determine a default URI and open it, first checking if libvirt is running """ manager = self._get_manager() log.debug("Trying to start libvirtd through systemd") unitname = "libvirtd.service" libvirtd_installed = False libvirtd_active = False unitpath = None # Fetch all units from systemd try: bus = Gio.bus_get_sync(Gio.BusType.SYSTEM, None) systemd = Gio.DBusProxy.new_sync(bus, 0, None, "org.freedesktop.systemd1", "/org/freedesktop/systemd1", "org.freedesktop.systemd1.Manager", None) units = systemd.ListUnits() log.debug("Successfully listed units via systemd") except Exception: units = [] log.exception("Couldn't connect to systemd") libvirtd_installed = os.path.exists("/var/run/libvirt") libvirtd_active = os.path.exists("/var/run/libvirt/libvirt-sock") # Check if libvirtd is installed and running for unitinfo in units: if unitinfo[0] != unitname: continue libvirtd_installed = True libvirtd_active = unitinfo[3] == "active" unitpath = unitinfo[6] break log.debug("libvirtd_installed=%s libvirtd_active=%s unitpath=%s", libvirtd_installed, libvirtd_active, unitpath) # If it's not running, try to start it try: if unitpath and libvirtd_installed and not libvirtd_active: unit = Gio.DBusProxy.new_sync( bus, 0, None, "org.freedesktop.systemd1", unitpath, "org.freedesktop.systemd1.Unit", None) if not self.config.CLITestOptions.first_run: unit.Start("(s)", "fail") time.sleep(2) libvirtd_active = True except Exception: log.exception("Error starting libvirtd") if self.config.CLITestOptions.first_run: log.debug("--test-first-run, using uri=None to trigger error") tryuri = None else: tryuri = vmmCreateConn.default_uri() log.debug("Probed default URI=%s", tryuri) # Manager fail message msg = "" if not libvirtd_installed: msg += _("The libvirtd service does not appear to be installed. " "Install and run the libvirtd service to manage " "virtualization on this host.") elif not libvirtd_active: msg += _("libvirtd is installed but not running. Start the " "libvirtd service to manage virtualization on this host.") if not tryuri or "qemu" not in tryuri: if msg: msg += "\n\n" msg += _("Could not detect a default hypervisor. Make " "sure the appropriate QEMU/KVM virtualization " "packages are installed to manage virtualization " "on this host.") if msg: msg += "\n\n" msg += _("A virtualization connection can be manually " "added via File->Add Connection") if (tryuri is None or not libvirtd_installed or not libvirtd_active): manager.set_startup_error(msg) return # Launch idle callback to connect to default URI def idle_connect(): def _open_completed(c, ConnectError): if ConnectError: self._handle_conn_error(c, ConnectError) conn = vmmConnectionManager.get_instance().add_conn(tryuri) conn.set_autoconnect(True) conn.connect_once("open-completed", _open_completed) conn.open() self.idle_add(idle_connect)
#!/usr/bin/env python3 # from http://cheesehead-techblog.blogspot.fi/2012/11/dbus-tutorial-gobject-introspection.html import gi.repository from gi.repository import Gio, GLib # Create the DBus message destination = 'org.freedesktop.NetworkManager' path = '/org/freedesktop/NetworkManager/ActiveConnection/19' interface = 'org.freedesktop.DBus.Properties' method = 'GetAll' args = GLib.Variant( '(ss)', ('org.freedesktop.NetworkManager.Connection.Active', 'None')) answer_fmt = GLib.VariantType.new('(v)') proxy_prpty = Gio.DBusCallFlags.NONE timeout = -1 cancellable = None # Connect to DBus, send the DBus message, and receive the reply bus = Gio.bus_get_sync(Gio.BusType.SYSTEM, None) reply = bus.call_sync(destination, path, interface, method, args, answer_fmt, proxy_prpty, timeout, cancellable) # Convert the result value to a useful python object and print [print(item[0], item[1]) for item in result.unpack()[0].items()]
def run(self): self.window = Gtk.Window(Gtk.WindowType.TOPLEVEL) self.window.set_title("Melange") self.window.set_icon_name("system-search") self.window.set_default_size(1000, 400) self.window.set_position(Gtk.WindowPosition.MOUSE) # I can't think of a way to reliably detect if the window # is active to determine if we need to present or hide # in show(). Since the window briefly loses focus during # shortcut press we'd be unable to detect it at that time. # Keeping the window on top ensures the window is never # obscured so we can just hide if visible. self.window.set_keep_above(True) self.window.connect("delete_event", self.onDelete) self.window.connect("key-press-event", self.onKeyPress) self._minimized = False self.window.connect("window-state-event", self.onWindowState) numRows = 3 numColumns = 6 table = Gtk.Table(numRows, numColumns, False) self.window.add(table) self.notebook = Gtk.Notebook() self.notebook.set_tab_pos(Gtk.PositionType.BOTTOM) self.notebook.show() self.notebook.set_show_border(True) self.notebook.set_show_tabs(True) label = Gtk.Label("Melange") label.set_markup("<u>Melange - Cinnamon Debugger</u> ") label.show() self.notebook.set_action_widget(label, Gtk.PackType.END) self.pages = {} self.customPages = {} self.createPage("Results", "results") self.createPage("Inspect", "inspect") # self.createPage("Memory", "memory") - TODO: re-implement get_memory_info from cjs self.createPage("Windows", "windows") self.createPage("Extensions", "extensions") self.createPage("Log", "log") table.attach(self.notebook, 0, numColumns, 0, 1) column = 0 pickerButton = pageutils.ImageButton("gtk-color-picker", Gtk.IconSize.SMALL_TOOLBAR) pickerButton.connect("clicked", self.onPickerClicked) table.attach(pickerButton, column, column + 1, 1, 2, 0, 0, 2) column += 1 table.attach(Gtk.Label("Exec:"), column, column + 1, 1, 2, 0, 0, 3) column += 1 self.commandline = CommandLine() table.attach(self.commandline, column, column + 1, 1, 2, Gtk.AttachOptions.EXPAND | Gtk.AttachOptions.FILL, 0, 3, 2) column += 1 self.statusLabel = Gtk.Label("Status") self.statusLabel.set_markup( " <span foreground='red'>[ Cinnamon is OFFLINE! ]</span> ") self.statusLabel.set_tooltip_text( "The connection to cinnamon is broken") self.statusLabel.set_no_show_all(True) table.attach(self.statusLabel, column, column + 1, 1, 2, 0, 0, 1) column += 1 settings = Gio.Settings("org.cinnamon.desktop.keybindings") arr = settings.get_strv("looking-glass-keybinding") accel = "" done_one = False for element in arr: if done_one: accel += ", " accel += element.replace("<", "<").replace(">", ">") if not done_one: done_one = True keybinding = Gtk.Label() keybinding.set_markup('<i>Toggle shortcut: %s</i>' % accel) actionButton = self.createActionButton() box = Gtk.HBox() box.pack_start(keybinding, False, False, 3) box.pack_start(actionButton, False, False, 3) table.attach(box, column, column + 1, 1, 2, 0, 0, 1) self.activatePage("results") self.statusLabel.hide() self.window.set_focus(self.commandline)
root = tree.getroot() etree.register_namespace('', namespaces["ob"]) try: theme = root.find("ob:theme", namespaces=namespaces).find("ob:name", namespaces=namespaces).text except: raise Exception("Unable to find theme.") # Get current vera-color if Gio.SettingsSchemaSource.get_default().lookup( "org.semplicelinux.vera.desktop", True) == None: raise Exception("Schema org.semplicelinux.vera.desktop not available.") settings = Gio.Settings("org.semplicelinux.vera.desktop") vera_color_enabled = settings.get_boolean("vera-color-enabled") if vera_color_enabled: vera_color = settings.get_string("vera-color") rgba = Gdk.RGBA() rgba.parse(vera_color) # http://wrhansen.blogspot.it/2012/09/how-to-convert-gdkrgba-to-hex-string-in.html vera_color = "#{0:02x}{1:02x}{2:02x}".format(int(rgba.red * 255), int(rgba.green * 255), int(rgba.blue * 255)) else: vera_color = "#000000" # Now that we have the theme name, we should search for the base theme found = False for directory in (os.path.expanduser("~/.themes"), "/usr/share/themes"):
def _add_search_box(self): """ --------------------------------------| | Revealer | | |-----------------------------------| | | Frame | | | |---------------------------------| | | | HBox | | | | |---| |-------| |----| |------| | | | | | x | | Entry | |Prev| | Next | | | | | |---| |-------| |----| |------| | --------------------------------------| """ self.search_revealer = Gtk.Revealer() self.search_frame = Gtk.Frame(name="search-frame") self.search_box = Gtk.HBox() # Search self.search_close_btn = Gtk.Button() self.search_close_btn.set_can_focus(False) close_icon = Gio.ThemedIcon(name="window-close-symbolic") close_image = Gtk.Image.new_from_gicon(close_icon, Gtk.IconSize.BUTTON) self.search_close_btn.set_image(close_image) self.search_entry = Gtk.SearchEntry() self.search_prev_btn = Gtk.Button() self.search_prev_btn.set_can_focus(False) prev_icon = Gio.ThemedIcon(name="go-up-symbolic") prev_image = Gtk.Image.new_from_gicon(prev_icon, Gtk.IconSize.BUTTON) self.search_prev_btn.set_image(prev_image) self.search_next_btn = Gtk.Button() self.search_next_btn.set_can_focus(False) next_icon = Gio.ThemedIcon(name="go-down-symbolic") next_image = Gtk.Image.new_from_gicon(next_icon, Gtk.IconSize.BUTTON) self.search_next_btn.set_image(next_image) # Pack into box self.search_box.pack_start(self.search_close_btn, False, False, 0) self.search_box.pack_start(self.search_entry, False, False, 0) self.search_box.pack_start(self.search_prev_btn, False, False, 0) self.search_box.pack_start(self.search_next_btn, False, False, 0) # Add into frame self.search_frame.add(self.search_box) # Frame self.search_frame.set_margin_end(12) self.search_frame.get_style_context().add_class("background") css_provider = Gtk.CssProvider() css_provider.load_from_data(b"#search-frame border {" b" padding: 5px 5px 5px 5px;" b" border: none;" b"}") Gtk.StyleContext.add_provider_for_screen( Gdk.Screen.get_default(), css_provider, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION, ) # Add to revealer self.search_revealer.add(self.search_frame) self.search_revealer.set_transition_duration(500) self.search_revealer.set_transition_type( Gtk.RevealerTransitionType.CROSSFADE) self.search_revealer.set_valign(Gtk.Align.END) self.search_revealer.set_halign(Gtk.Align.END) # Welcome to the overlay self.add_overlay(self.search_revealer) # Events self.search_entry.connect("key-press-event", self.on_search_entry_keypress) self.search_entry.connect("changed", self.set_search) self.search_entry.connect("activate", self.do_search) self.search_entry.connect("focus-in-event", self.on_search_entry_focus_in) self.search_entry.connect("focus-out-event", self.on_search_entry_focus_out) self.search_next_btn.connect("clicked", self.on_search_next_clicked) self.search_prev_btn.connect("clicked", self.on_search_prev_clicked) self.search_close_btn.connect("clicked", self.close_search_box) self.search_prev = True # Search revealer visible def search_revealer_show_cb(widget): if not widget.get_child_revealed(): widget.hide() self.search_revealer.hide() self.search_revealer_show_cb_id = self.search_revealer.connect( "show", search_revealer_show_cb) self.search_frame.connect("unmap", lambda x: self.search_revealer.hide())
def _open_application(self, mime_type, filename): app_info = Gio.app_info_get_default_for_type(mime_type, False) gfile = Gio.File.new_for_path(filename) app_info.launch([gfile])
def __init__(self): self.settings = Gio.Settings("com.linuxmint.updates") self.cache = apt.Cache() self.priority_updates_available = False self.load_rules()
def restore(self): settings = Gio.Settings('org.sugarlabs.speech') self._pitch = settings.get_int('pitch') self._rate = settings.get_int('rate') logging.debug('loading speech configuration pitch %s rate %s', self._pitch, self._rate)
def run(self): self.window = Gtk.Window(type=Gtk.WindowType.TOPLEVEL) self.window.set_title("Melange") self.window.set_icon_name("system-search") self.window.set_default_size(1000, 400) self.window.set_position(Gtk.WindowPosition.MOUSE) # I can't think of a way to reliably detect if the window # is active to determine if we need to present or hide # in show(). Since the window briefly loses focus during # shortcut press we'd be unable to detect it at that time. # Keeping the window on top ensures the window is never # obscured so we can just hide if visible. self.window.set_keep_above(True) self.window.connect("delete_event", self.onDelete) self.window.connect("key-press-event", self.onKeyPress) self._minimized = False self.window.connect("window-state-event", self.onWindowState) numRows = 3 numColumns = 6 table = Gtk.Table(n_rows=numRows, n_columns=numColumns, homogeneous=False) table.set_margin_start(6) table.set_margin_end(6) table.set_margin_top(6) table.set_margin_bottom(6) self.window.add(table) self.notebook = Gtk.Notebook() self.notebook.set_tab_pos(Gtk.PositionType.BOTTOM) self.notebook.show() self.notebook.set_show_border(True) self.notebook.set_show_tabs(True) label = Gtk.Label(label="Melange") label.set_markup("<u>Melange - Cinnamon Debugger</u> ") label.show() self.notebook.set_action_widget(label, Gtk.PackType.END) self.pages = {} self.customPages = {} self.createPage("Results", "results") self.createPage("Inspect", "inspect") # self.createPage("Memory", "memory") - TODO: re-implement get_memory_info from cjs self.createPage("Windows", "windows") self.createPage("Extensions", "extensions") self.createPage("Log", "log") table.attach(self.notebook, 0, numColumns, 0, 1) column = 0 pickerButton = pageutils.ImageButton("color-select-symbolic") pickerButton.set_tooltip_text("Select an actor to inspect") pickerButton.connect("clicked", self.onPickerClicked) table.attach(pickerButton, column, column + 1, 1, 2, 0, 0, 2) column += 1 fullGc = pageutils.ImageButton("user-trash-full-symbolic") fullGc.set_tooltip_text("Invoke garbage collection") # ignore signal arg fullGc.connect('clicked', lambda source: lookingGlassProxy.FullGc()) table.attach(fullGc, column, column + 1, 1, 2, 0, 0, 2) column += 1 self.commandline = CommandLine() self.commandline.set_tooltip_text("Evaluate javascript") table.attach(self.commandline, column, column + 1, 1, 2, Gtk.AttachOptions.EXPAND | Gtk.AttachOptions.FILL, 0, 3, 2) column += 1 self.statusLabel = Gtk.Label(label="Status") self.statusLabel.set_markup( " <span foreground='red'>[ Cinnamon is OFFLINE! ]</span> ") self.statusLabel.set_tooltip_text( "The connection to cinnamon is broken") self.statusLabel.set_no_show_all(True) table.attach(self.statusLabel, column, column + 1, 1, 2, 0, 0, 1) column += 1 box = Gtk.HBox() settings = Gio.Settings(schema="org.cinnamon.desktop.keybindings") arr = settings.get_strv("looking-glass-keybinding") if len(arr) > 0: # only the first mapped keybinding [accelKey, mask] = Gtk.accelerator_parse(arr[0]) if accelKey == 0 and mask == 0: # failed to parse, fallback to plain accel string label = Gtk.Label(label=arr[0]) else: label = Gtk.Label( label=Gtk.accelerator_get_label(accelKey, mask)) label.set_tooltip_text("Toggle shortcut") box.pack_start(label, False, False, 3) actionButton = self.createActionButton() box.pack_start(actionButton, False, False, 3) table.attach(box, column, column + 1, 1, 2, 0, 0, 1) self.activatePage("results") self.statusLabel.hide() self.window.set_focus(self.commandline)
def startup_cb(self): logger.debug("Starting") self.event_loop = gasyncio.GAsyncIOEventLoop() self.event_loop.start_slave_loop() self.sigint_source = GLib.unix_signal_add(GLib.PRIORITY_DEFAULT, signal.SIGINT, lambda: self.quit() or True) self.excepthook_orig, sys.excepthook = sys.excepthook, self.excepthook self.menubar = Gio.Menu() self.set_menubar(self.menubar) self.unit_manager = unit.UnitManager() self.unit_manager.set_target('config') default_units = [ 'config', 'menubar', 'misc', 'profiles', 'server', 'partition', 'persistent', 'playback', 'tango-velours', 'component', 'window', 'components.current', 'components.playqueue', 'components.browser', 'components.search', 'components.stream', 'components.playlist', 'components.command', 'components.log', 'components.savedsearch' ] self.unit_manager.get_unit('config').config.access( 'units', default_units) self.unit_manager.set_target( *self.unit_manager.get_unit('config').config.units) self.unit_misc = self.unit_manager.get_unit('misc') self.unit_server = self.unit_manager.get_unit('server') self.unit_persistent = self.unit_manager.get_unit('persistent') self.unit_component = self.unit_manager.get_unit('component') self.unit_window = self.unit_manager.get_unit('window') self.action_aggregator = self.unit_manager.create_aggregator( 'app.action', self.action_added_cb, self.action_removed_cb), self.menu_aggregator = self.unit_manager.create_aggregator( 'app.menu', self.menu_added_cb, self.menu_removed_cb), self.user_action_aggregator = self.unit_manager.create_aggregator( 'app.user-action', self.user_action_added_cb, self.user_action_removed_cb) self.unit_misc.connect('notify::block-fragile-accels', self.notify_block_fragile_accels_cb) self.ampd = self.unit_server.ampd.sub_executor() self.notification = Gio.Notification.new(_("MPD status")) self.notification_task = None self.session_inhibit_cookie = None self.systemd_inhibit_fd = None self.unit_server.ampd_server_properties.connect( 'notify::state', self.set_inhibit) self.unit_persistent.connect('notify::protected', self.set_inhibit) self.add_action(resource.Action('new-window', self.new_window_cb)) self.add_action(resource.Action('close-window', self.close_window_cb)) self.add_action(resource.Action('help', self.help_cb)) self.add_action(resource.Action('about', self.about_cb)) self.add_action( resource.Action('notify', self.task_hold_app(self.action_notify_cb))) self.add_action(resource.Action('quit', self.quit)) self.add_action( resource.Action('component-start', self.component_start_cb, parameter_type=GLib.VariantType.new('s'))) self.add_action( resource.Action('component-start-new-window', self.component_start_cb, parameter_type=GLib.VariantType.new('s'))) self.add_action( resource.Action('component-stop', self.component_stop_cb)) # self.add_action(resource.Action('BAD', self.THIS_IS_BAD_cb)) self.unit_server.ampd_connect()
def __init__(self): Gtk.Window.__init__(self, title="Shutdown Helper") Gtk.Window.set_default_icon_name("system-shutdown") self.set_size_request(200, 300) hb = Gtk.HeaderBar() hb.set_show_close_button(True) hb.props.title = "Shutdown Helper" #hb.props.subtitle = "Are you sure you're done?" hb.set_decoration_layout(":close") self.set_titlebar(hb) grid = Gtk.Grid() self.add(grid) #main_label = Gtk.Label(label= ' ') #main_label.connect("hilighted", self.egg) #main_label.set_justify(Gtk.Justification.CENTER) stop = Gtk.Button.new_with_mnemonic("_Shut _Down") stop.connect("clicked", self.off) stop.set_hexpand(True) stop.set_vexpand(True) redo = Gtk.Button.new_with_mnemonic("_Reboot") redo.connect("clicked", self.repwr) redo.set_hexpand(True) redo.set_vexpand(True) slp = Gtk.Button.new_with_mnemonic("_Sleep") slp.connect("clicked", self.sleep) slp.set_hexpand(True) slp.set_vexpand(True) lock = Gtk.Button.new_with_mnemonic("_Lock") lock.connect("clicked", self.padlock) lock.set_hexpand(True) lock.set_vexpand(True) lgout = Gtk.Button.new_with_mnemonic("_Log _Out") lgout.connect("clicked", self.skill) lgout.set_hexpand(True) lgout.set_vexpand(True) quit = Gtk.Button.new_with_mnemonic("_Cancel") quit.connect("clicked", self.done) quit.set_hexpand(True) quit.set_vexpand(True) mini_btns = Gtk.IconSize.BUTTON stop_mini = Gtk.Button() stop_mini_icon = Gio.ThemedIcon(name="system-shutdown") stop_mini_img = Gtk.Image.new_from_gicon(stop_mini_icon, mini_btns) stop_mini.add(stop_mini_img) stop_mini.connect("clicked", self.off) redo_mini = Gtk.Button() redo_mini_icon = Gio.ThemedIcon(name="system-restart") redo_mini_img = Gtk.Image.new_from_gicon(redo_mini_icon, mini_btns) redo_mini.add(redo_mini_img) redo_mini.connect("clicked", self.repwr) slp_mini = Gtk.Button() slp_mini_icon = Gio.ThemedIcon(name="sleep") slp_mini_img = Gtk.Image.new_from_gicon(slp_mini_icon, mini_btns) slp_mini.add(slp_mini_img) slp_mini.connect("clicked", self.sleep) lock_mini = Gtk.Button() lock_mini_icon = Gio.ThemedIcon(name="lock") lock_mini_img = Gtk.Image.new_from_gicon(lock_mini_icon, mini_btns) lock_mini.add(lock_mini_img) lock_mini.connect("clicked", self.padlock) lgout_mini = Gtk.Button() lgout_mini_icon = Gio.ThemedIcon(name="system-log-out") lgout_mini_img = Gtk.Image.new_from_gicon(lgout_mini_icon, mini_btns) lgout_mini.add(lgout_mini_img) lgout_mini.connect("clicked", self.skill) hb.pack_start(stop_mini) hb.pack_start(redo_mini) hb.pack_start(slp_mini) hb.pack_start(lock_mini) hb.pack_start(lgout_mini) grid.add(stop) grid.attach_next_to(redo, stop, down, 1, 2) grid.attach_next_to(slp, redo, down, 1, 2) grid.attach_next_to(lock, slp, down, 1, 2) grid.attach_next_to(lgout, lock, down, 1, 2) grid.attach_next_to(quit, lgout, down, 1, 2)
age = (AGES[i] + AGES[i + 1]) / 2. if birth_age < age: return AGES[i] return None def print_age(): print get_age() def set_age(age): """Set the age and an approximate birth timestamp age: e.g. 8 birth_timestamp: time - age * #seconds per year """ try: i = int(age) except ValueError, e: logging.error('set_age: %s' % (e)) i = None if i is None or i < 1: raise ValueError(_('Age must be a positive integer.')) birth_timestamp = calculate_birth_timestamp(age) settings = Gio.Settings('org.sugarlabs.user') settings.set_int('birth-timestamp', birth_timestamp) return
def __init__(self, library): super().__init__(spacing=6) self.set_orientation(Gtk.Orientation.VERTICAL) self._register_instance() if self.__model is None: self._init_model(library) self._cover_cancel = Gio.Cancellable() sw = ScrolledWindow() sw.set_shadow_type(Gtk.ShadowType.IN) self.view = view = AllTreeView() view.set_headers_visible(False) model_sort = AlbumSortModel(model=self.__model) model_filter = AlbumFilterModel(child_model=model_sort) self.__bg_filter = background_filter() self.__filter = None model_filter.set_visible_func(self.__parse_query) render = Gtk.CellRendererPixbuf() self.__cover_column = column = Gtk.TreeViewColumn("covers", render) column.set_visible(config.getboolean("browsers", "album_covers")) column.set_sizing(Gtk.TreeViewColumnSizing.FIXED) column.set_fixed_width(get_cover_size() + 12) render.set_property('height', get_cover_size() + 8) render.set_property('width', get_cover_size() + 8) def cell_data_pb(column, cell, model, iter_, no_cover): item = model.get_value(iter_) if item.album is None: surface = None elif item.cover: pixbuf = item.cover pixbuf = add_border_widget(pixbuf, self.view) surface = get_surface_for_pixbuf(self, pixbuf) # don't cache, too much state has an effect on the result self.__last_render_surface = None else: surface = no_cover if self.__last_render_surface == surface: return self.__last_render_surface = surface cell.set_property("surface", surface) column.set_cell_data_func(render, cell_data_pb, self._no_cover) view.append_column(column) render = Gtk.CellRendererText() column = Gtk.TreeViewColumn("albums", render) column.set_sizing(Gtk.TreeViewColumnSizing.FIXED) if view.supports_hints(): render.set_property('ellipsize', Pango.EllipsizeMode.END) def cell_data(column, cell, model, iter_, data): album = model.get_album(iter_) if album is None: text = "<b>%s</b>\n" % _("All Albums") text += numeric_phrase("%d album", "%d albums", len(model) - 1) markup = text else: markup = self.display_pattern % album if self.__last_render == markup: return self.__last_render = markup cell.markup = markup cell.set_property('markup', markup) column.set_cell_data_func(render, cell_data) view.append_column(column) view.get_selection().set_mode(Gtk.SelectionMode.MULTIPLE) view.set_rules_hint(True) view.set_search_equal_func(self.__search_func, None) view.set_search_column(0) view.set_model(model_filter) sw.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC) sw.add(view) view.connect('row-activated', self.__play_selection) self.__sig = view.connect( 'selection-changed', util.DeferredSignal(self.__update_songs, owner=view)) targets = [("text/x-quodlibet-songs", Gtk.TargetFlags.SAME_APP, 1), ("text/uri-list", 0, 2)] targets = [Gtk.TargetEntry.new(*t) for t in targets] view.drag_source_set(Gdk.ModifierType.BUTTON1_MASK, targets, Gdk.DragAction.COPY) view.connect("drag-data-get", self.__drag_data_get) connect_obj(view, 'popup-menu', self.__popup, view, library) self.accelerators = Gtk.AccelGroup() search = SearchBarBox(completion=AlbumTagCompletion(), accel_group=self.accelerators) search.connect('query-changed', self.__update_filter) connect_obj(search, 'focus-out', lambda w: w.grab_focus(), view) self.__search = search prefs = PreferencesButton(self, model_sort) search.pack_start(prefs, False, True, 0) self.pack_start(Align(search, left=6, top=6), False, True, 0) self.pack_start(sw, True, True, 0) self.connect("destroy", self.__destroy) self.enable_row_update(view, sw, self.__cover_column) self.connect('key-press-event', self.__key_pressed, library.librarian) if app.cover_manager: connect_destroy(app.cover_manager, "cover-changed", self._cover_changed) self.show_all()
def __init__(self, app, file=None, buffer=None, transparent_mode=True): self.title = _("Paint") super().__init__(application=app, title=self.title) self.set_default_icon_name(package.get_name()) self.set_default_size(DEFAULT_WIDTH, DEFAULT_HEIGHT) self.headerbar = Gtk.HeaderBar(title=self.title, show_close_button=True) self.set_titlebar(self.headerbar) common_buttons = { "edit-undo-symbolic": (self.undo_callback, _('Undo')), "edit-redo-symbolic": (self.redo_callback, _('Redo')), "edit-cut-symbolic": (self.cut_callback, _('Cut')), "edit-copy-symbolic": (self.copy_callback, _('Copy')), "edit-paste-symbolic": (self.paste_callback, _('Paste')) } for name, (method, tooltip) in common_buttons.items(): button = Gtk.Button().new() icon = Gio.ThemedIcon(name=name) image = Gtk.Image.new_from_gicon(icon, Gtk.IconSize.BUTTON) button.add(image) button.connect("clicked", method) button.set_tooltip_text(tooltip) button.set_can_focus(False) self.headerbar.pack_start(button) # See https://gitlab.gnome.org/GNOME/Initiatives/-/wikis/App-Menu-Retirement self.menu_button = Gtk.MenuButton() hamburger_icon = Gio.ThemedIcon(name="open-menu-symbolic") image = Gtk.Image.new_from_gicon(hamburger_icon, Gtk.IconSize.BUTTON) self.menu_button.add(image) builder = Gtk.Builder() builder.set_translation_domain(package.get_name()) builder.add_from_resource(package.APP_PATH + '/gtk/menu.ui') self.menu_button.set_menu_model(builder.get_object('app-menu')) self.menu_button.set_can_focus(False) self.headerbar.pack_end(self.menu_button) self.save_button = Gtk.Button.new_with_mnemonic(_("_Save")) self.save_button.connect("clicked", self.save_callback) self.save_button.set_tooltip_text(_('Save the current file')) self.save_button.set_can_focus(False) self.headerbar.pack_end(self.save_button) color_button = Gtk.ColorButton.new_with_rgba(Gdk.RGBA(0, 0, 0, 1)) color_button.connect('color-set', self.color_set_callback) color_button.set_tooltip_text(_('Select the current color')) color_button.set_can_focus(False) self.headerbar.pack_end(color_button) self.tool_button = Gtk.Button.new() image = Gtk.Image.new_from_icon_name('pencil-symbolic', Gtk.IconSize.BUTTON) self.tool_button.add(image) self.tool_button.connect("clicked", self.tool_set_callback) self.tool_button.set_tooltip_text(_('Select the current tool')) self.tool_button.set_can_focus(False) self.headerbar.pack_end(self.tool_button) self.style_button = Gtk.Button.new() image = Gtk.Image.new_from_icon_name('1px-symbolic-symbolic', Gtk.IconSize.BUTTON) self.style_button.add(image) self.style_button.connect("clicked", self.style_set_callback) self.style_button.set_tooltip_text(_('Select the current line width')) self.style_button.set_can_focus(False) self.headerbar.pack_end(self.style_button) overlay = Gtk.Overlay() self.add(overlay) scrolled_window = Gtk.ScrolledWindow() scrolled_window.set_hexpand(True) scrolled_window.set_vexpand(True) scrolled_window.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC) self.buffer = None if file: buffer = self._load_file(file) else: self.file = None self.paintview = PaintView(buffer) self.buffer = self.paintview.get_buffer() self.buffer.set_transparent_mode(transparent_mode) self.buffer.connect_after("modified-changed", self.on_modified_changed) self.paintview.connect_after("style-changed", self.on_style_changed) self.paintview.connect_after("tool-changed", self.on_tool_changed) scrolled_window.add(self.paintview) overlay.add(scrolled_window) self.connect_after("key-press-event", self.on_key_press_event) self.connect_after('button-press-event', self.on_mouse_press) self.add_events(Gdk.EventMask.BUTTON_PRESS_MASK) actions = { "menu": self.menu_callback, "new": self.new_callback, "open": self.open_callback, "save": self.save_callback, "saveas": self.save_as_callback, "close": self.close_callback, "closeall": self.close_all_callback, "undo": self.undo_callback, "redo": self.redo_callback, "cut": self.cut_callback, "copy": self.copy_callback, "paste": self.paste_callback, "selectall": self.select_all_callback, "font": self.font_callback, "background-color": self.background_color_callback, "help": self.help_callback, "about": self.about_callback, } for name, method in actions.items(): action = Gio.SimpleAction.new(name, None) action.connect("activate", method) self.add_action(action) self.connect("delete-event", self.on_delete_event) action = Gio.SimpleAction.new_stateful("antialias", None, GLib.Variant.new_boolean(False)) action.connect("activate", self.antialias_callback) self.add_action(action) action = Gio.SimpleAction.new_stateful( "transparent-selection-mode", None, GLib.Variant.new_boolean(transparent_mode)) action.connect("activate", self.transparent_selection_mode_callback) self.add_action(action) self.paintview.grab_focus()
def get_color(): settings = Gio.Settings('org.sugarlabs.user') return settings.get_string('color')
def watch_name_owner(cls, appeared_handler, vanished_handler): Gio.bus_watch_name(Gio.BusType.SESSION, cls.__bus_name, Gio.BusNameWatcherFlags.NONE, appeared_handler, vanished_handler)