Python gi.repository.GLib.Variant() Examples

The following are 18 code examples of gi.repository.GLib.Variant(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module gi.repository.GLib , or try the search function .
Example #1
Source File: alttoolbar_rb3compat.py    From alternative-toolbar with GNU General Public License v3.0 6 votes vote down vote up
def set_active(self, value):
        """
        activate or deactivate a stateful action signal
        For consistency with earlier RB versions, this will fire the
        activate signal for the action

        :param value: `boolean` state value
        """

        if is_rb3(self.shell):
            self.action.change_state(GLib.Variant('b', value))
            self._current_state = value
            self._do_update_state = False
            self.activate()
            self._do_update_state = True
        else:
            self.action.set_active(value) 
Example #2
Source File: proxy_method.py    From pydbus with GNU Lesser General Public License v2.1 6 votes vote down vote up
def __call__(self, instance, *args, **kwargs):
		argdiff = len(args) - len(self._inargs)
		if argdiff < 0:
			raise TypeError(self.__qualname__ + " missing {} required positional argument(s)".format(-argdiff))
		elif argdiff > 0:
			raise TypeError(self.__qualname__ + " takes {} positional argument(s) but {} was/were given".format(len(self._inargs), len(args)))

		# Python 2 sux
		for kwarg in kwargs:
			if kwarg not in ("timeout",):
				raise TypeError(self.__qualname__ + " got an unexpected keyword argument '{}'".format(kwarg))
		timeout = kwargs.get("timeout", None)

		ret = instance._bus.con.call_sync(
			instance._bus_name, instance._path,
			self._iface_name, self.__name__, GLib.Variant(self._sinargs, args), GLib.VariantType.new(self._soutargs),
			0, timeout_to_glib(timeout), None).unpack()

		if len(self._outargs) == 0:
			return None
		elif len(self._outargs) == 1:
			return ret[0]
		else:
			return ret 
Example #3
Source File: proxy_property.py    From pydbus with GNU Lesser General Public License v2.1 5 votes vote down vote up
def __set__(self, instance, value):
		if instance is None or not self._writeable:
			raise AttributeError("can't set attribute")

		instance._object["org.freedesktop.DBus.Properties"].Set(self._iface_name, self.__name__, GLib.Variant(self._type, value)) 
Example #4
Source File: dbus.py    From btk with MIT License 5 votes vote down vote up
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])

        result = getattr(self, method_name)(*args)

        if type(result) is list:
            result = tuple(result)
        elif not type(result) is tuple:
            result = (result,)

        out_args = self.method_outargs[method_name]
        if out_args != '()':
            invocation.return_value(GLib.Variant(out_args, result)) 
Example #5
Source File: alttoolbar_rb3compat.py    From alternative-toolbar with GNU General Public License v3.0 5 votes vote down vote up
def set_state(self, value):
        """
        set the state of a stateful action - this is applicable only
        to RB2.99+
        """
        if is_rb3(self.shell) and self.action.props.state_type:
            self.action.change_state(GLib.Variant('b', value)) 
Example #6
Source File: registration.py    From pydbus with GNU Lesser General Public License v2.1 5 votes vote down vote up
def GetAll(self, interface_name):
		ret = {}
		for name, type in self.readable_properties.items():
			ns, local = name.rsplit(".", 1)
			if ns == interface_name:
				ret[local] = GLib.Variant(type, getattr(self.object, local))
		return ret 
Example #7
Source File: registration.py    From pydbus with GNU Lesser General Public License v2.1 5 votes vote down vote up
def __init__(self, object, interfaces):
		self.object = object

		self.outargs = {}
		for iface in interfaces:
			for method in iface.methods:
				self.outargs[iface.name + "." + method.name] = [arg.signature for arg in method.out_args]

		self.readable_properties = {}
		self.writable_properties = {}
		for iface in interfaces:
			for prop in iface.properties:
				if prop.flags & Gio.DBusPropertyInfoFlags.READABLE:
					self.readable_properties[iface.name + "." + prop.name] = prop.signature
				if prop.flags & Gio.DBusPropertyInfoFlags.WRITABLE:
					self.writable_properties[iface.name + "." + prop.name] = prop.signature

		for iface in interfaces:
			for signal in iface.signals:
				s_name = signal.name
				def EmitSignal(iface, signal):
					return lambda *args: self.SignalEmitted(iface.name, signal.name, GLib.Variant("(" + "".join(s.signature for s in signal.args) + ")", args))
				self._at_exit(getattr(object, signal.name).connect(EmitSignal(iface, signal)).__exit__)

		if "org.freedesktop.DBus.Properties" not in (iface.name for iface in interfaces):
			try:
				def onPropertiesChanged(iface, changed, invalidated):
					changed = {key: GLib.Variant(self.readable_properties[iface + "." + key], val) for key, val in changed.items()}
					args = GLib.Variant("(sa{sv}as)", (iface, changed, invalidated))
					self.SignalEmitted("org.freedesktop.DBus.Properties", "PropertiesChanged", args)
				self._at_exit(object.PropertiesChanged.connect(onPropertiesChanged).__exit__)
			except AttributeError:
				pass 
Example #8
Source File: settings.py    From Authenticator with GNU General Public License v2.0 5 votes vote down vote up
def window_position(self, position):
        """
        Set the window position.

        :param position: [x, y] window's position
        :type position: list
        """
        position = GLib.Variant('ai', list(position))
        self.set_value('window-position', position) 
Example #9
Source File: method_call_context.py    From pydbus with GNU Lesser General Public License v2.1 5 votes vote down vote up
def check_authorization(self, action_id, details, interactive=False):
		return AuthorizationResult(*self.bus.polkit_authority.CheckAuthorization(('system-bus-name', {'name': GLib.Variant("s", self.sender)}), action_id, details, 1 if interactive else 0, '')) 
Example #10
Source File: vimiv_testcase.py    From vimiv with MIT License 5 votes vote down vote up
def init_test(self, paths=None, to_set=None, values=None, debug=False):
        """Initialize a testable vimiv object saved as self.vimiv.

        Args:
            paths: Paths passed to vimiv.
            to_set: List of settings to be set.
            values: List of values for settings to be set.
        """
        self.working_directory = os.getcwd()
        # Create vimiv class with settings, paths, ...
        self.vimiv = Vimiv(True)  # True for running_tests
        self.settings = settings
        self.vimiv.debug = debug
        options = GLib.VariantDict.new()
        bool_true = GLib.Variant("b", True)
        options.insert_value("temp-basedir", bool_true)
        self.vimiv.do_handle_local_options(options)
        # Set the required settings
        if to_set:
            for i, setting in enumerate(to_set):
                self.settings.override(setting, values[i])
        self.vimiv.register()
        self.vimiv.do_startup(self.vimiv)
        if paths:
            # Create a list of Gio.Files for vimiv.do_open
            files = [Gio.File.new_for_path(path) for path in paths]
            self.vimiv.do_open(files, len(paths), "")
        else:
            self.vimiv.activate_vimiv(self.vimiv) 
Example #11
Source File: app_test.py    From vimiv with MIT License 5 votes vote down vote up
def test_handle_local_options(self):
        """Handle commandline arguments."""
        # We need to catch information from standard output

        # Get version should print information to standard output and return 0
        option_version = GLib.VariantDict.new()
        bool_true = GLib.Variant("b", True)
        option_version.insert_value("version", bool_true)
        returncode = self.vimiv.do_handle_local_options(option_version)
        if not hasattr(sys.stdout, "getvalue"):
            self.fail("Need to run test in buffered mode.")
        # In pylint we do not run in buffered mode but this is checked with
        # hasattr just above.
        # pylint:disable=no-member
        output = sys.stdout.getvalue().strip()
        self.assertIn("vimiv", output)
        self.assertEqual(returncode, 0)
        # Set some different options and test if they were handled correctly
        options = GLib.VariantDict.new()
        options.insert_value("shuffle", bool_true)
        double_22 = GLib.Variant("d", 2.2)
        options.insert_value("slideshow-delay", double_22)
        string_geom = GLib.Variant("s", "400x400")
        options.insert_value("geometry", string_geom)
        returncode = self.vimiv.do_handle_local_options(options)
        self.assertEqual(returncode, -1)
        self.assertTrue(self.settings["shuffle"].get_value())
        self.assertFalse(self.settings["start_slideshow"].get_value())
        self.assertAlmostEqual(self.settings["slideshow_delay"].get_value(),
                               2.2)
        self.assertEqual(self.settings["geometry"].get_value(), (400, 400)) 
Example #12
Source File: settings.py    From Audio-Cutter with GNU General Public License v3.0 5 votes vote down vote up
def window_position(self, position):
        """Set the window position."""
        position = GLib.Variant('ai', list(position))
        Logger.debug("[Settings] Window position is set to: "
                     "{}".format(list(position)))
        self.set_value('window-position', position) 
Example #13
Source File: test_dbus_utils.py    From uchroma with GNU Lesser General Public License v3.0 5 votes vote down vote up
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}' 
Example #14
Source File: test_dbus_utils.py    From uchroma with GNU Lesser General Public License v3.0 5 votes vote down vote up
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)' 
Example #15
Source File: modules.py    From gpt with GNU General Public License v3.0 5 votes vote down vote up
def on_local_option(self, app, option):
        self.calc_sa = False
        if option.contains("version"):
            print("GPT:    {}".format(__version__))
            print("Python: {}".format(sys.version[:5]))
            print("GTK+:   {}.{}.{}".format(Gtk.MAJOR_VERSION,
                                            Gtk.MINOR_VERSION,
                                            Gtk.MICRO_VERSION,
                                            ))
            print(_("Application executed from {}".format(cli.install_dir)))
            return 0    # quit
        elif option.contains("cli"):
            cli.help()
            cli.shell()
            return 0
        elif option.contains("default"):
            self.load_stack_application_window()
        elif option.contains("alt-gui-compact"):
            self.load_application_window()
        elif option.contains("alt-gui-ext"):
            self.load_player_window()
        elif option.contains("tl-calc"):
            tlc.standalone()
            return 0
        else:
            # insert key do option GLibVariantDict
            option.insert_value("default", GLib.Variant("u", True))
            self.on_local_option(app, option)

        # contiunue with loading the app
        return -1 
Example #16
Source File: screenshot.py    From Authenticator with GNU General Public License v2.0 5 votes vote down vote up
def area(filename=None):
        """
            Take a screen shot of an area and save it to a specific filename
            Using GNOME Shell Screenshot Interface.
            :param filename: output filename
            :type filename: str
        """
        if not filename:
            filename = path.join(GLib.get_user_cache_dir(),
                                 path.basename(NamedTemporaryFile().name))
        bus = Gio.bus_get_sync(Gio.BusType.SESSION, None)
        screen_proxy = Gio.DBusProxy.new_sync(bus,
                                              Gio.DBusProxyFlags.NONE,
                                              None,
                                              GNOMEScreenshot.interface,
                                              GNOMEScreenshot.path,
                                              GNOMEScreenshot.interface,
                                              None)
        x, y, width, height = screen_proxy.call_sync('SelectArea', None, Gio.DBusCallFlags.NONE,
                                                     -1, None).unpack()

        args = GLib.Variant('(iiiibs)', (x, y, width, height, False, filename
                                         )
                            )
        screenshot = screen_proxy.call_sync('ScreenshotArea', args,
                                            Gio.DBusCallFlags.NONE, -1, None)
        success, filename = screenshot.unpack()
        if success:
            return filename
        return None 
Example #17
Source File: registration.py    From pydbus with GNU Lesser General Public License v2.1 4 votes vote down vote up
def call_method(self, connection, sender, object_path, interface_name, method_name, parameters, invocation):
		try:
			try:
				outargs = self.outargs[interface_name + "." + method_name]
				method = getattr(self.object, method_name)
			except KeyError:
				if interface_name == "org.freedesktop.DBus.Properties":
					if method_name == "Get":
						method = self.Get
						outargs = ["v"]
					elif method_name == "GetAll":
						method = self.GetAll
						outargs = ["a{sv}"]
					elif method_name == "Set":
						method = self.Set
						outargs = []
					else:
						raise
				else:
					raise

			sig = signature(method)

			kwargs = {}
			if "dbus_context" in sig.parameters and sig.parameters["dbus_context"].kind in (Parameter.POSITIONAL_OR_KEYWORD, Parameter.KEYWORD_ONLY):
				kwargs["dbus_context"] = MethodCallContext(invocation)

			result = method(*parameters, **kwargs)

			if len(outargs) == 0:
				invocation.return_value(None)
			elif len(outargs) == 1:
				invocation.return_value(GLib.Variant("(" + "".join(outargs) + ")", (result,)))
			else:
				invocation.return_value(GLib.Variant("(" + "".join(outargs) + ")", result))

		except Exception as e:
			logger = logging.getLogger(__name__)
			logger.exception("Exception while handling %s.%s()", interface_name, method_name)

			#TODO Think of a better way to translate Python exception types to DBus error types.
			e_type = type(e).__name__
			if not "." in e_type:
				e_type = "unknown." + e_type
			invocation.return_dbus_error(e_type, str(e)) 
Example #18
Source File: alttoolbar_rb3compat.py    From alternative-toolbar with GNU General Public License v3.0 4 votes vote down vote up
def add_app_menuitems(self, ui_string, group_name, menu='tools'):
            """
            utility function to add application menu items.

            For RB2.99 all application menu items are added to the "tools"
            section of the application menu. All Actions are assumed to be of
            action_type "app".

            For RB2.98 or less, it is added however the UI_MANAGER string
            is defined.

            :param ui_string: `str` is the Gtk UI definition.  There is not an
            equivalent UI definition in RB2.99 but we can parse out menu items
            since this string is in XML format

            :param group_name: `str` unique name of the ActionGroup to add menu
            items to
            :param menu: `str` RB2.99 menu section to add to - nominally either
              'tools' or 'view'
            """
            if is_rb3(self.shell):
                root = ET.fromstring(ui_string)
                for elem in root.findall(".//menuitem"):
                    action_name = elem.attrib['action']

                    group = self._action_groups[group_name]
                    act = group.get_action(action_name)

                    item = Gio.MenuItem()
                    item.set_detailed_action('app.' + action_name)
                    item.set_label(act.label)
                    item.set_attribute_value("accel", GLib.Variant("s",
                                                                   act.accel))
                    app = Gio.Application.get_default()
                    index = menu + action_name
                    app.add_plugin_menu_item(menu,
                                             index, item)
                    self._uids[index] = menu
            else:
                uim = self.shell.props.ui_manager
                self._uids.append(uim.add_ui_from_string(ui_string))
                uim.ensure_update()