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()
python类Variant()的实例源码
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))