我们从Python开源项目中,提取了以下47个代码示例,用于说明如何使用gi.repository.GLib.Variant()。
def Set( self ): print( '\r\n\r\n[GTK]' ) if self.verbose: print( '{0} Setting gsettings proxy mode to manual'.format( self.date() ) ) self.mode.set_string( 'mode', 'manual' ) if self.verbose: print( '{0} Setting http proxy for gsettings on {1}:{2}'.format( self.date(), self.host, self.port ) ) self.http_proxy.set_value( 'host', GLib.Variant( 's', self.http ) ) self.http_proxy.set_value( 'port', GLib.Variant( 'i', int( self.port ) ) ) if self.verbose: print( '{0} Setting https proxy for gsettings on {1}:{2}'.format( self.date(), self.host, self.port ) ) self.https_proxy.set_value( 'host', GLib.Variant( 's', self.http ) ) self.https_proxy.set_value( 'port', GLib.Variant( 'i', int( self.port ) ) ) super( GTK, self ).Set()
def on_mcg_connect(self, connected): if connected: GObject.idle_add(self._connect_connected) self._mcg.load_playlist() self._mcg.load_albums() self._mcg.get_status() self._connect_action.set_state(GLib.Variant.new_boolean(True)) self._play_action.set_enabled(True) self._clear_playlist_action.set_enabled(True) self._panel_action.set_enabled(True) else: GObject.idle_add(self._connect_disconnected) self._connect_action.set_state(GLib.Variant.new_boolean(False)) self._play_action.set_enabled(False) self._clear_playlist_action.set_enabled(False) self._panel_action.set_enabled(False)
def on_mcg_status(self, state, album, pos, time, volume, error): # Album GObject.idle_add(self._panels[Window._PANEL_INDEX_COVER].set_album, album) # State if state == 'play': GObject.idle_add(self._header_bar.set_play) GObject.idle_add(self._panels[Window._PANEL_INDEX_COVER].set_play, pos, time) self._play_action.set_state(GLib.Variant.new_boolean(True)) elif state == 'pause' or state == 'stop': GObject.idle_add(self._header_bar.set_pause) GObject.idle_add(self._panels[Window._PANEL_INDEX_COVER].set_pause) self._play_action.set_state(GLib.Variant.new_boolean(False)) # Volume GObject.idle_add(self._header_bar.set_volume, volume) # Error if error is None: self._infobar.hide() else: self._show_error(error)
def variant_to_value(variant): ''' Convert a GLib variant to a value ''' # pylint: disable=unidiomatic-typecheck if type(variant) != GLib.Variant: return variant type_string = variant.get_type_string() if type_string == 's': return variant.get_string() elif type_string == 'i': return variant.get_int32() elif type_string == 'b': return variant.get_boolean() elif type_string == 'as': # In the latest pygobject3 3.3.4 or later, g_variant_dup_strv # returns the allocated strv but in the previous release, # it returned the tuple of (strv, length) if type(GLib.Variant.new_strv([]).dup_strv()) == tuple: return variant.dup_strv()[0] else: return variant.dup_strv() else: print('error: unknown variant type: %s' %type_string) return variant
def variant_to_value(variant): '''Returns the value of a GLib.Variant ''' # pylint: disable=unidiomatic-typecheck if type(variant) != GLib.Variant: return variant type_string = variant.get_type_string() if type_string == 's': return variant.get_string() elif type_string == 'i': return variant.get_int32() elif type_string == 'b': return variant.get_boolean() elif type_string == 'as': # In the latest pygobject3 3.3.4 or later, g_variant_dup_strv # returns the allocated strv but in the previous release, # it returned the tuple of (strv, length) if type(GLib.Variant.new_strv([]).dup_strv()) == tuple: return variant.dup_strv()[0] else: return variant.dup_strv() else: print('error: unknown variant type: %s' %type_string) return variant
def set_arrow_keys_reopen_preedit(self, mode, update_dconf=True): '''Sets whether the arrow keys are allowed to reopen a preëdit :param mode: Whether arrow keys can reopen a preëdit :type mode: boolean :param update_dconf: Whether to write the change to dconf. Set this to False if this method is called because the dconf key changed to avoid endless loops when the dconf key is changed twice in a short time. :type update_dconf: boolean ''' if DEBUG_LEVEL > 1: sys.stderr.write( "set_arrow_keys_reopen_preedit(%s, update_dconf = %s)\n" %(mode, update_dconf)) if mode == self._arrow_keys_reopen_preedit: return self._arrow_keys_reopen_preedit = mode if update_dconf: self._config.set_value( self._config_section, 'arrowkeysreopenpreedit', GLib.Variant.new_boolean(mode))
def set_tab_enable(self, mode, update_dconf=True): '''Sets the “Tab enable” mode :param mode: Whether to show a candidate list only when typing Tab :type mode: boolean :param update_dconf: Whether to write the change to dconf. Set this to False if this method is called because the dconf key changed to avoid endless loops when the dconf key is changed twice in a short time. :type update_dconf: boolean ''' if DEBUG_LEVEL > 1: sys.stderr.write( "set_tab_enable(%s, update_dconf = %s)\n" %(mode, update_dconf)) if mode == self._tab_enable: return self._tab_enable = mode if update_dconf: self._config.set_value( self._config_section, 'tabenable', GLib.Variant.new_boolean(mode))
def new(cls, action_name, obj, property_name): default = obj.get_property(property_name) self = cls.__new__(cls) self.obj = obj self.property_name = property_name if isinstance(default, str): self.type_name = "s" param_type = GLib.VariantType.new("s") elif isinstance(default, bool): self.type_name = "b" param_type = None else: raise AssertionError("Don't know what to do with {}".format(type(default))) self.action = Gio.SimpleAction.new_stateful(action_name, param_type, GLib.Variant(self.type_name, default)) if isinstance(default, str): self.action.connect('change-state', self.change_state) elif isinstance(default, bool): self.action.connect('activate', self.activate) obj.connect('notify::' + property_name, self.changed) return self.action
def __init__(self, app, ui): self.__app = app self.__ui = ui self.__rating = None self.__cozy_id = 0 self.__metadata = {"mpris:trackid": GLib.Variant( "o", "/org/mpris/MediaPlayer2/TrackList/NoTrack")} self.__track_id = self.__get_media_id(0) self.__bus = Gio.bus_get_sync(Gio.BusType.SESSION, None) Gio.bus_own_name_on_connection(self.__bus, self.__MPRIS_COZY, Gio.BusNameOwnerFlags.NONE, None, None) Server.__init__(self, self.__bus, self.__MPRIS_PATH) bus = get_gst_bus() bus.connect("message", self.__on_gst_message) #Lp().player.connect("current-changed", self.__on_current_changed) #Lp().player.connect("seeked", self.__on_seeked) #Lp().player.connect("status-changed", self.__on_status_changed) #Lp().player.connect("volume-changed", self.__on_volume_changed)
def GetAll(self, interface): ret = {} if interface == self.__MPRIS_IFACE: for property_name in ["CanQuit", "CanRaise", "HasTrackList", "Identity", "DesktopEntry", "SupportedUriSchemes", "SupportedMimeTypes"]: ret[property_name] = self.Get(interface, property_name) elif interface == self.__MPRIS_PLAYER_IFACE: for property_name in ["PlaybackStatus", "Metadata", "Position", "CanGoNext", "CanGoPrevious", "CanPlay", "CanPause", "CanSeek", "CanControl"]: ret[property_name] = self.Get(interface, property_name) elif interface == self.__MPRIS_RATINGS_IFACE: ret["HasRatingsExtension"] = GLib.Variant("b", False) return ret
def __on_current_changed(self): current_track_id = get_current_track().id if current_track_id and current_track_id >= 0: self.__cozy_id = current_track_id else: self.__cozy_id = 0 # We only need to recalculate a new trackId at song changes. self.__track_id = self.__get_media_id(self.__cozy_id) self.__rating = None self.__update_metadata() properties = {"Metadata": GLib.Variant("a{sv}", self.__metadata), "CanPlay": GLib.Variant("b", True), "CanPause": GLib.Variant("b", True), "CanGoNext": GLib.Variant("b", True), "CanGoPrevious": GLib.Variant("b", True)} try: self.PropertiesChanged(self.__MPRIS_PLAYER_IFACE, properties, []) except Exception as e: print("MPRIS::__on_current_changed(): %s" % e)
def switch_repeat_status(self, action, parameter): action.set_state(GLib.Variant.new_boolean(not action.get_state())) self.repeat = action.get_state().get_boolean() # player = self.shell.props.shell_player # if self.repeat: # ret, shuffle, self.repeat_all = player.get_playback_state() # player.set_playback_state(shuffle, 1) # else: # ret, shuffle, repeat_all = player.get_playback_state() # player.set_playback_state(shuffle, self.repeat_all) # Looks like there is a bug on gstreamer player and a seg fault # happens as soon as the 'eos' callback is called. # https://bugs.launchpad.net/ubuntu/+source/rhythmbox/+bug/1239218 # However, newer Rhythmbox versions do not suffer from it anymore
def do_activate(self): self.__action = Gio.SimpleAction.new_stateful('repeatone', None, GLib.Variant('b', False)) self.__action.connect('activate', self.switch_repeat_status) app = Gio.Application.get_default() app.add_action(self.__action) item = Gio.MenuItem() item.set_label(_("Repeat current song")) # Keyboard shortcut item.set_attribute_value('accel', GLib.Variant("s", "<Ctrl>E")) item.set_detailed_action('app.repeatone') app.add_plugin_menu_item('edit', 'repeatone', item) self.repeat = False self.shell = self.object self.one_song_state_normal, self.one_song_state_eos = range(2) self.one_song_state = self.one_song_state_normal player = self.shell.props.shell_player player.connect('playing-song-changed', self.on_song_change) player.props.player.connect('eos', self.on_gst_player_eos) # player.connect('elapsed-changed', self.on_elapsed_change)
def set_window_size(self, size): size = GLib.Variant('ai', list(size)) self.set_value('window-size', size)
def set_window_postion(self, position): position = GLib.Variant('ai', list(position)) self.set_value('window-position', position)
def test_special_types(): obj, sig = dbus_prepare(Color.NewFromHtml('black')) assert obj == '#000000' assert sig == 's' obj, sig = dbus_prepare(Int(5)) assert isinstance(obj, dict) assert sig == 'a{sv}' for value in obj.values(): assert isinstance(value, GLib.Variant) obj, sig = dbus_prepare(EnumTest) assert isinstance(obj, tuple) assert sig == '(sss)'
def test_dicts(): simple = {'first': 1, 'second': 2} obj, sig = dbus_prepare(simple) assert obj == simple assert sig == 'a{sn}' obj, sig = dbus_prepare(simple, variant=True) for value in obj.values(): assert isinstance(value, GLib.Variant) assert sig == 'a{sv}' mixed = {'first': 'string here', 'second': 2, 'third': (2, 2)} obj, sig = dbus_prepare(mixed) for value in obj.values(): assert isinstance(value, GLib.Variant) assert sig == 'a{sv}' nested = {'first': {'nested1': 1}, 'second': {'nested2': 2}} obj, sig = dbus_prepare(nested) assert obj == nested assert sig == 'a{sa{sn}}' nested['second']['nested2'] = 'blah' obj, sig = dbus_prepare(nested) print('obj=%s sig=%s' % (obj, sig)) assert isinstance(obj, dict) assert isinstance(obj['first'], GLib.Variant) assert isinstance(obj['first']['nested1'], int) assert sig == 'a{sv}'
def on_destroy(self, window): self._settings.set_value(Window.SETTING_WINDOW_SIZE, GLib.Variant('ai', list(self._size)))
def _set_menu_visible_panel(self): panels = [panel.get() for panel in self._panels] panel_index_selected = panels.index(self._stack.get_visible_child()) self._panel_action.set_state(GLib.Variant.new_string(str(panel_index_selected)))
def _do_express_interest(self, proxy, interface, interest): # XXX parse interest to see if we're requesting the first chunk self.first_segment = 0 if (self._segments): self.current_segment = self.first_segment = self._segments.index(defaults.SegmentState.UNSENT) or 0 logger.debug('STARTING AT %s', self.first_segment) self.interest = interest if self.filename: # did we already have an open file descriptor for this ? if yes, # we'd better close it here and reopen so that we're sure we get # a fresh fd. self.fd.close() # we prepare the file where we're going to write the data self.filename = '.edd-file-cache-' + interest.replace('/', '%') sendout_fd = open(self.filename, 'w+b') self.fd = open(self.filename, 'r+b') logger.debug('opened fd: %s', self.fd) fd_list = Gio.UnixFDList() fd_id = fd_list.append(sendout_fd.fileno()) assert(self.filename) assert(self.fd) interface.connect('progress', self._on_progress) interface.call_request_interest(interest, GLib.Variant('h', fd_id), self.first_segment, fd_list=fd_list, callback=self._on_request_interest_complete, user_data=interest)
def set_dictionary_names(self, dictionary_names, update_dconf=True): '''Set current dictionary names :param dictionary_names: List of names of dictionaries to use :type dictionary_names: List of strings :param update_dconf: Whether to write the change to dconf. Set this to False if this method is called because the dconf key changed to avoid endless loops when the dconf key is changed twice in a short time. :type update_dconf: boolean ''' if dictionary_names == self._dictionary_names: # nothing to do return self._dictionary_names = dictionary_names self.db.hunspell_obj.set_dictionary_names(dictionary_names) if self._emoji_predictions: if (not self.emoji_matcher or self.emoji_matcher.get_languages() != dictionary_names): self.emoji_matcher = itb_emoji.EmojiMatcher( languages=dictionary_names) if not self.is_empty(): self._update_ui() if update_dconf: self._config.set_value( self._config_section, 'dictionary', GLib.Variant.new_string(','.join(dictionary_names)))
def set_add_direct_input(self, mode, update_dconf=True): '''Set the current value of the “Add direct input” mode :param mode: Whether “Add direct input” mode is on or off :type mode: boolean :param update_dconf: Whether to write the change to dconf. Set this to False if this method is called because the dconf key changed to avoid endless loops when the dconf key is changed twice in a short time. :type update_dconf: boolean ''' imes = self.get_current_imes() dictionary_names = self.db.hunspell_obj.get_dictionary_names() self._add_direct_input = mode if mode: if 'NoIme' not in imes: imes.append('NoIme') if 'en_GB' not in dictionary_names: dictionary_names.append('en_GB') else: imes = [x for x in imes if x != 'NoIme'] if not imes: imes = ['NoIme'] # always keep the first dictionary, i.e. always keep # the original one from the config file dictionary_names = ( [dictionary_names[0]] + [x for x in dictionary_names[1:] if x != 'en_GB']) self.set_dictionary_names(dictionary_names, update_dconf=True) self.set_current_imes(imes, update_dconf=True) if update_dconf: self._config.set_value( self._config_section, 'adddirectinput', GLib.Variant.new_boolean(mode))
def set_emoji_prediction_mode(self, mode, update_dconf=True): '''Sets the emoji prediction mode :param mode: Whether to switch emoji prediction on or off :type mode: boolean :param update_dconf: Whether to write the change to dconf. Set this to False if this method is called because the dconf key changed to avoid endless loops when the dconf key is changed twice in a short time. :type update_dconf: boolean ''' if DEBUG_LEVEL > 1: sys.stderr.write( "set_emoji_prediction_mode(%s, update_dconf = %s)\n" %(mode, update_dconf)) if mode == self._emoji_predictions: return self._emoji_predictions = mode self._init_or_update_property_menu( self.emoji_prediction_mode_menu, mode) if (self._emoji_predictions and (not self.emoji_matcher or self.emoji_matcher.get_languages() != self._dictionary_names)): self.emoji_matcher = itb_emoji.EmojiMatcher( languages=self._dictionary_names) self._update_ui() if update_dconf: self._config.set_value( self._config_section, 'emojipredictions', GLib.Variant.new_boolean(mode))
def set_off_the_record_mode(self, mode, update_dconf=True): '''Sets the “Off the record” mode :param mode: Whether to prevent saving input to the user database or not :type mode: boolean :param update_dconf: Whether to write the change to dconf. Set this to False if this method is called because the dconf key changed to avoid endless loops when the dconf key is changed twice in a short time. :type update_dconf: boolean ''' if DEBUG_LEVEL > 1: sys.stderr.write( "set_off_the_record_mode(%s, update_dconf = %s)\n" %(mode, update_dconf)) if mode == self._off_the_record: return self._off_the_record = mode self._init_or_update_property_menu( self.off_the_record_mode_menu, mode) self._update_ui() # because of the indicator in the auxiliary text if update_dconf: self._config.set_value( self._config_section, 'offtherecord', GLib.Variant.new_boolean(mode))
def set_auto_commit_characters(self, auto_commit_characters, update_dconf=True): '''Sets the auto commit characters :param auto_commit_characters: The characters which trigger a commit with an extra space :type auto_commit_characters: string :param update_dconf: Whether to write the change to dconf. Set this to False if this method is called because the dconf key changed to avoid endless loops when the dconf key is changed twice in a short time. :type update_dconf: boolean ''' if DEBUG_LEVEL > 1: sys.stderr.write( "set_auto_commit_characters(%s, update_dconf = %s)\n" %(auto_commit_characters, update_dconf)) if auto_commit_characters == self._auto_commit_characters: return self._auto_commit_characters = auto_commit_characters if update_dconf: self._config.set_value( self._config_section, 'autocommitcharacters', GLib.Variant.new_string(auto_commit_characters))
def set_page_size(self, page_size, update_dconf=True): '''Sets the page size of the lookup table :param page_size: The page size of the lookup table :type mode: integer >= 1 and <= 9 :param update_dconf: Whether to write the change to dconf. Set this to False if this method is called because the dconf key changed to avoid endless loops when the dconf key is changed twice in a short time. :type update_dconf: boolean ''' if DEBUG_LEVEL > 1: sys.stderr.write( "set_page_size(%s, update_dconf = %s)\n" %(page_size, update_dconf)) if page_size == self._page_size: return if page_size >= 1 and page_size <= 9: self._page_size = page_size self._lookup_table.set_page_size(self._page_size) self.reset() if update_dconf: self._config.set_value( self._config_section, 'pagesize', GLib.Variant.new_int32(page_size))
def set_lookup_table_orientation(self, orientation, update_dconf=True): '''Sets the page size of the lookup table :param orientation: The orientation of the lookup table :type mode: integer >= 0 and <= 2 :param update_dconf: Whether to write the change to dconf. Set this to False if this method is called because the dconf key changed to avoid endless loops when the dconf key is changed twice in a short time. :type update_dconf: boolean ''' if DEBUG_LEVEL > 1: sys.stderr.write( "set_lookup_table_orientation(%s, update_dconf = %s)\n" %(orientation, update_dconf)) if orientation == self._lookup_table_orientation: return if orientation >= 0 and orientation <= 2: self._lookup_table_orientation = orientation self._lookup_table.set_orientation(self._lookup_table_orientation) self.reset() if update_dconf: self._config.set_value( self._config_section, 'lookuptableorientation', GLib.Variant.new_int32(orientation))
def set_min_char_complete(self, min_char_complete, update_dconf=True): '''Sets the minimum number of characters to try completion :param min_char_complete: The minimum number of characters to type before completion is tried. :type mode: integer >= 1 and <= 9 :param update_dconf: Whether to write the change to dconf. Set this to False if this method is called because the dconf key changed to avoid endless loops when the dconf key is changed twice in a short time. :type update_dconf: boolean ''' if DEBUG_LEVEL > 1: sys.stderr.write( "set_min_char_complete(%s, update_dconf = %s)\n" %(min_char_complete, update_dconf)) if min_char_complete == self._min_char_complete: return if min_char_complete >= 1 and min_char_complete <= 9: self._min_char_complete = min_char_complete self.reset() if update_dconf: self._config.set_value( self._config_section, 'mincharcomplete', GLib.Variant.new_int32(min_char_complete))
def set_show_number_of_candidates(self, mode, update_dconf=True): '''Sets the “Show number of candidates” mode :param mode: Whether to show the number of candidates in the auxiliary text :type mode: boolean :param update_dconf: Whether to write the change to dconf. Set this to False if this method is called because the dconf key changed to avoid endless loops when the dconf key is changed twice in a short time. :type update_dconf: boolean ''' if DEBUG_LEVEL > 1: sys.stderr.write( "set_show_number_of_candidates(%s, update_dconf = %s)\n" %(mode, update_dconf)) if mode == self._show_number_of_candidates: return self._show_number_of_candidates = mode self.reset() if update_dconf: self._config.set_value( self._config_section, 'shownumberofcandidates', GLib.Variant.new_boolean(mode))
def set_show_status_info_in_auxiliary_text(self, mode, update_dconf=True): '''Sets the “Show status info in auxiliary text” mode :param mode: Whether to show status information in the auxiliary text. Currently the status information which can be displayed there is whether emoji mode and off-the-record mode are on or off and which input method is currently used for the preëdit text. :type mode: boolean :param update_dconf: Whether to write the change to dconf. Set this to False if this method is called because the dconf key changed to avoid endless loops when the dconf key is changed twice in a short time. :type update_dconf: boolean ''' if DEBUG_LEVEL > 1: sys.stderr.write( "set_show_status_info_in_auxiliary_text" + "(%s, update_dconf = %s)\n" %(mode, update_dconf)) if mode == self._show_status_info_in_auxiliary_text: return self._show_status_info_in_auxiliary_text = mode self.reset() if update_dconf: self._config.set_value( self._config_section, 'showstatusinfoinaux', GLib.Variant.new_boolean(mode))
def configure(self, output_requests, persistent=False): outputs, crtcs = self._configure(output_requests, [], []) params = GLib.Variant('(uba(uiiiuaua{sv})a(ua{sv}))', (self.serial, persistent, crtcs, outputs)) res = self.proxy.call('ApplyConfiguration', params, Gio.DBusConnectionFlags.NONE, -1, None, None) if res is not None: print(res)
def aio_offset(i): if i is None: return {} return {'offset': GLib.Variant('q', i)}
def readwrite_param(Cls, offset): if offset is None: return {} else: return {"offset": GLib.Variant('q', offset)}
def fallback_set_accels(self, detailed_action_name, accels): if '::' in detailed_action_name: action_name, parameter = detailed_action_name.split('::', 1) parameter = GLib.Variant('s', parameter) else: action_name, parameter = detailed_action_name, None for accel in accels: self.add_accelerator(accel, action_name, parameter)
def activate(self, action, value): new_state = not action.get_state().unpack() action.set_state(GLib.Variant(self.type_name, new_state)) self.obj.set_property(self.property_name, new_state)
def changed(self, widget, param_spec): new_value = self.obj.get_property(self.property_name) new_state = GLib.Variant(self.type_name, new_value) if self.action.get_state() != new_state: self.action.set_state(new_state)
def virtual_midnight_set(self, *args): try: vm = parse_time(self.virtual_midnight_entry.get_text()) except ValueError: self.virtual_midnight_changed() else: h, m = self.gsettings.get_value('virtual-midnight') if (h, m) != (vm.hour, vm.minute): self.gsettings.set_value('virtual-midnight', GLib.Variant('(ii)', (vm.hour, vm.minute)))
def on_method_call(self, connection, sender, object_path, interface_name, method_name, parameters, invocation): args = list(parameters.unpack()) for i, sig in enumerate(self.method_inargs[method_name]): if sig is "h": msg = invocation.get_message() fd_list = msg.get_unix_fd_list() args[i] = fd_list.get(args[i]) try: result = getattr(self, method_name)(*args) # out_args is atleast (signature1). # We therefore always wrap the result as a tuple. # Refer to https://bugzilla.gnome.org/show_bug.cgi?id=765603 result = (result,) out_args = self.method_outargs[method_name] if out_args != "()": variant = GLib.Variant(out_args, result) invocation.return_value(variant) else: invocation.return_value(None) except: pass
def Seeked(self, position): self.__bus.emit_signal( None, self.__MPRIS_PATH, self.__MPRIS_PLAYER_IFACE, "Seeked", GLib.Variant.new_tuple(GLib.Variant("x", position)))
def Get(self, interface, property_name): if property_name in ["CanQuit", "CanRaise", "CanSeek", "CanControl", "HasRatingsExtension"]: return GLib.Variant("b", True) elif property_name == "HasTrackList": return GLib.Variant("b", False) elif property_name == "Identity": return GLib.Variant("s", "Cozy") elif property_name == "DesktopEntry": return GLib.Variant("s", "com.github.geigi.cozy") elif property_name == "SupportedUriSchemes": return GLib.Variant("as", ["file"]) elif property_name == "SupportedMimeTypes": return GLib.Variant("as", ["application/ogg", "audio/x-vorbis+ogg", "audio/x-flac", "audio/mpeg"]) elif property_name == "PlaybackStatus": return GLib.Variant("s", self.__get_status()) elif property_name == "Metadata": return GLib.Variant("a{sv}", self.__metadata) elif property_name == "Position": return GLib.Variant( "x", get_current_duration()) elif property_name in ["CanGoNext", "CanGoPrevious", "CanPlay", "CanPause"]: return GLib.Variant("b", get_current_track() is not None)
def __get_media_id(self, track_id): """ TrackId's must be unique even up to the point that if you repeat a song it must have a different TrackId. """ track_id = track_id + randint(10000000, 90000000) return GLib.Variant("o", "/de/geigi/Cozy/TrackId/%s" % track_id)
def __update_metadata(self): track = get_current_track() if self.__get_status() == "Stopped": self.__metadata = {"mpris:trackid": GLib.Variant( "o", "/org/mpris/MediaPlayer2/TrackList/NoTrack")} else: self.__metadata["mpris:trackid"] = self.__track_id track_number = track.number if track_number is None: track_number = 1 self.__metadata["xesam:trackNumber"] = GLib.Variant("i", track_number) self.__metadata["xesam:title"] = GLib.Variant( "s", track.name) self.__metadata["xesam:album"] = GLib.Variant( "s", track.book.name) self.__metadata["xesam:artist"] = GLib.Variant( "s", track.book.author) self.__metadata["mpris:length"] = GLib.Variant( "x", track.length * 1000 * 1000) self.__metadata["xesam:url"] = GLib.Variant( "s", "file:///" + track.file) cover_path = "/tmp/cozy_mpris.jpg" pixbuf = get_cover_pixbuf(track.book) if pixbuf is not None: pixbuf.savev(cover_path, "jpeg", ["quality"], ["90"]) if cover_path is not None: self.__metadata["mpris:artUrl"] = GLib.Variant( "s", "file://" + cover_path)
def __on_status_changed(self, data=None): properties = {"PlaybackStatus": GLib.Variant("s", self.__get_status())} self.PropertiesChanged(self.__MPRIS_PLAYER_IFACE, properties, [])
def set_current_imes(self, imes, update_dconf=True): '''Set current list of input methods :param imes: List of input methods :type imes: List of strings :param update_dconf: Whether to write the change to dconf. Set this to False if this method is called because the dconf key changed to avoid endless loops when the dconf key is changed twice in a short time. :type update_dconf: boolean ''' if imes == self._current_imes: # nothing to do return if len(imes) > self._current_imes_max: sys.stderr.write( 'Trying to set more than the allowed maximum of %s ' %self._current_imes_max + 'input methods.\n' + 'Trying to set: %s\n' %imes + 'Really setting: %s\n' %imes[:self._current_imes_max]) imes = imes[:self._current_imes_max] if set(imes) != set(self._current_imes): # Input methods have been added or removed from the list # of current input methods. Initialize the # transliterators. If only the order of the input methods # has changed, initialising the transliterators is not # necessary (and neither is updating the transliterated # strings necessary). self._current_imes = imes self._init_transliterators() else: self._current_imes = imes self._update_preedit_ime_menu_dicts() self._init_or_update_property_menu_preedit_ime( self.preedit_ime_menu, current_mode=0) if not self.is_empty(): self._update_ui() if self._remember_last_used_preedit_ime and update_dconf: self._config.set_value( self._config_section, 'inputmethod', GLib.Variant.new_string(','.join(imes)))
def set_proxy_settings(self, mode): ''' Set proxy values :param mode: "manual" or "none" :type mode: str ''' gsettings = Gio.Settings.new("org.gnome.system.proxy") gsettings.set_value( "mode", GLib.Variant('s', mode)) msg = "Proxy has been set to %s" % mode notify(msg) logger.info(msg) if mode == 'manual': if self.proxy_ignore != self.PROXYIGNORE: # GLib.Variant('as', ['localhost', '127.0.0.0/8', '::1']) gsettings = Gio.Settings.new("org.gnome.system.proxy") gsettings.set_value( "ignore-hosts", GLib.Variant('as', self.PROXYIGNORE)) if self.proxy_http_url != self.PROXY: gsettings = Gio.Settings.new("org.gnome.system.proxy.http") gsettings.set_value( "host", GLib.Variant('s', self.PROXY)) gsettings.set_value( "port", GLib.Variant('i', self.PROXYPORT)) gsettings = Gio.Settings.new("org.gnome.system.proxy.https") gsettings.set_value( "host", GLib.Variant('s', self.PROXY)) gsettings.set_value( "port", GLib.Variant('i', self.PROXYPORT)) gsettings = Gio.Settings.new("org.gnome.system.proxy.ftp") gsettings.set_value( "host", GLib.Variant('s', self.PROXY)) gsettings.set_value( "port", GLib.Variant('i', self.PROXYPORT)) logger.debug("Values : PROXY: %s, PORT: %s" % ( self.PROXY, self.PROXYPORT)) logger.debug("Ignoring proxy for : %s" % (str.join( ',', self.PROXYIGNORE))) self.get_proxy_settings()
def load_settings(self): self.gsettings = Gio.Settings.new("org.gtimelog") self.gsettings.bind('detail-level', self, 'detail-level', Gio.SettingsBindFlags.DEFAULT) self.gsettings.bind('show-task-pane', self.task_pane, 'visible', Gio.SettingsBindFlags.DEFAULT) self.gsettings.bind('hours', self.log_view, 'hours', Gio.SettingsBindFlags.DEFAULT) self.gsettings.bind('office-hours', self.log_view, 'office-hours', Gio.SettingsBindFlags.DEFAULT) self.gsettings.bind('name', self.report_view, 'name', Gio.SettingsBindFlags.DEFAULT) self.gsettings.bind('sender', self.sender_entry, 'text', Gio.SettingsBindFlags.DEFAULT) self.gsettings.bind('list-email', self.recipient_entry, 'text', Gio.SettingsBindFlags.DEFAULT) self.gsettings.bind('report-style', self.report_view, 'report-style', Gio.SettingsBindFlags.DEFAULT) self.gsettings.bind('remote-task-list', self.app.actions.refresh_tasks, 'enabled', Gio.SettingsBindFlags.DEFAULT) self.gsettings.bind('gtk-completion', self.task_entry, 'gtk-completion-enabled', Gio.SettingsBindFlags.DEFAULT) self.gsettings.connect('changed::remote-task-list', self.load_tasks) self.gsettings.connect('changed::task-list-url', self.load_tasks) self.gsettings.connect('changed::task-list-edit-url', self.update_edit_tasks_availability) self.gsettings.connect('changed::virtual-midnight', self.virtual_midnight_changed) self.update_edit_tasks_availability() x, y = self.gsettings.get_value('window-position') w, h = self.gsettings.get_value('window-size') tpp = self.gsettings.get_int('task-pane-position') self.resize(w, h) if (x, y) != (-1, -1): self.move(x, y) self.paned.set_position(tpp) self.paned.connect('notify::position', self.delay_store_window_size) self.connect("configure-event", self.delay_store_window_size) if not self.gsettings.get_boolean('settings-migrated'): old_settings = Settings() old_settings.load() if old_settings.summary_view: self.gsettings.set_string('detail-level', 'summary') elif old_settings.chronological: self.gsettings.set_string('detail-level', 'chronological') else: self.gsettings.set_string('detail-level', 'grouped') self.gsettings.set_boolean('show-task-pane', old_settings.show_tasks) self.gsettings.set_double('hours', old_settings.hours) self.gsettings.set_double('office-hours', old_settings.office_hours) self.gsettings.set_string('name', old_settings.name) self.gsettings.set_string('sender', old_settings.sender) self.gsettings.set_string('list-email', old_settings.email) self.gsettings.set_string('report-style', old_settings.report_style) self.gsettings.set_string('task-list-url', old_settings.task_list_url) self.gsettings.set_boolean('remote-task-list', bool(old_settings.task_list_url)) for arg in old_settings.edit_task_list_cmd.split(): if arg.startswith(('http://', 'https://')): self.gsettings.set_string('task-list-edit-url', arg) vm = old_settings.virtual_midnight self.gsettings.set_value('virtual-midnight', GLib.Variant('(ii)', (vm.hour, vm.minute))) self.gsettings.set_boolean('gtk-completion', bool(old_settings.enable_gtk_completion)) self.gsettings.set_boolean('settings-migrated', True) log.info(_('Settings from {filename} migrated to GSettings (org.gtimelog)').format(filename=old_settings.get_config_file())) mark_time('settings loaded')