Beispiel #1
0
 def activate(self, leaf):
     torrent_hash = str(leaf.hid)
     tc = _connect_rpc()
     if tc:
         tc.stop_torrent(torrent_hash)
     else:
         raise OperationError(_get_error_msg())
Beispiel #2
0
def mpris_connection(bus_name, activate=False, operation_error=True):
    try:
        obj = dbus.SessionBus().get_object(bus_name, MPRIS_OBJ)
        if obj:
            return dbus.Interface(obj, MPRIS_PLAYER)
    except dbus.exceptions.DBusException as err:
        raise OperationError(str(err))
Beispiel #3
0
    def launch(self, files=(), paths=(), activate=False, ctx=None):
        """
		Launch the represented application

		@files: a seq of GFiles (gio.File)
		@paths: a seq of bytestring paths
		@activate: activate instead of start new
		"""
        if self.serverid is not None:
            argv = [VIM, '--servername', self.serverid, '--remote']
        else:
            argv = [VIM]
        if files:
            paths = [f.get_path() or f.get_uri() for f in files]
        if paths:
            argv.extend(paths)
        if paths or self.serverid is None:
            try:
                utils.spawn_async_raise(argv)
            except utils.SpawnError as exc:
                raise OperationError(exc)
        if self.serverid:
            ## focus the window we opened
            def error_handler(exc):
                ctx.register_late_error(OperationError(exc))

            proxy_obj = get_plugin_service_obj(PLUGID)
            if proxy_obj:
                proxy_obj.Foreground(self.serverid,
                                     reply_handler=_dummy_handler,
                                     error_handler=error_handler)
Beispiel #4
0
 def get_items(self):
     try:
         query = urllib.urlencode({'q': self.query})
         if ssl_support.is_supported():
             conn = ssl_support.VerifiedHTTPSConnection(SEARCH_HOST,
                                                        timeout=5)
             self.output_debug("Connected to", SEARCH_HOST, "using SSL")
         else:
             conn = httplib.HTTPConnection(SEARCH_HOST, timeout=5)
         conn.request("GET", SEARCH_PATH + query)
         response = conn.getresponse()
         ctype = response.getheader("content-type", default="")
         parts = ctype.split("charset=", 1)
         encoding = parts[-1] if len(parts) > 1 else "UTF-8"
         search_results = response.read().decode(encoding)
         response.close()
     except (IOError, httplib.HTTPException) as exc:
         raise OperationError(unicode(exc))
     results = json_decoder(search_results)
     data = results['responseData']
     more_results_url = data['cursor']['moreResultsUrl']
     total_results = data['cursor'].get('estimatedResultCount', 0)
     for h in data['results']:
         uq_url = urllib.unquote(h['url'])
         uq_title = _xml_unescape(h['titleNoFormatting'])
         yield UrlLeaf(uq_url, uq_title)
     yield CustomDescriptionUrl(
         more_results_url,
         _('Show More Results For "%s"') % self.query,
         _("%s total found") % total_results)
Beispiel #5
0
def _get_nemo():
    bus = dbus.SessionBus()
    try:
        proxy_obj = bus.get_object(SERVICE_NAME, FO_OBJECT)
    except dbus.DBusException as exc:
        raise OperationError(exc)
    iface_obj = dbus.Interface(proxy_obj, FO_IFACE)
    return iface_obj
Beispiel #6
0
 def activate(self, leaf):
     clip = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)
     interface.copy_to_clipboard(leaf, clip)
     xte_paste_argv = ['xte', INIT_DELAY, 'keydown Control_L',
                       'key v', 'keyup Control_L']
     try:
         utils.spawn_async_raise(xte_paste_argv)
     except utils.SpawnError as exc:
         raise OperationError(exc)
Beispiel #7
0
 def activate(self, leaf):
     text = leaf.object
     dict_id = __kupfer_settings__["dictionary"]
     dict_argv = list(dictionaries[dict_id])
     dict_argv[-1] = dict_argv[-1] + text
     try:
         utils.spawn_async_notify_as(dict_id + ".desktop", dict_argv)
     except utils.SpawnError as exc:
         raise OperationError(exc)
Beispiel #8
0
 def activate(self, leaf, obj):
     sfile = gio.File(leaf.object)
     bname = sfile.get_basename()
     dfile = gio.File(os_path.join(obj.object, bname))
     try:
         ret = sfile.move(dfile, flags=gio.FILE_COPY_ALL_METADATA)
         self.output_debug("Move %s to %s (ret: %s)" % (sfile, dfile, ret))
     except gio.Error, exc:
         raise OperationError(unicode(exc))
Beispiel #9
0
 def activate(self, leaf, obj):
     sfile = gio.File(leaf.object)
     dest = os_path.join(os_path.dirname(leaf.object), obj.object)
     dfile = gio.File(dest)
     try:
         ret = sfile.move(dfile)
         self.output_debug("Move %s to %s (ret: %s)" % (sfile, dfile, ret))
     except gio.Error, exc:
         raise OperationError(unicode(exc))
Beispiel #10
0
 def perform_trigger(cls, ctx, target):
     try:
         keystr, name, id_ = cls.instance.trigger_table[target]
     except KeyError:
         raise OperationError("Trigger '%s' does not exist" % (target, ))
     obj = puid.resolve_unique_id(id_)
     if obj is None:
         return
     return obj.run(ctx)
Beispiel #11
0
 def thread_do(self):
     try:
         # FIXME: This should be async
         self.output_debug("Copy %s to %s" % (self.gsource, self.gdest))
         ret = self.gsource.copy(self.gdest, Gio.FileCopyFlags.ALL_METADATA,
                                 None, None, None)
         self.output_debug("Copy ret %r" % (ret, ))
     except GLib.Error as exc:
         raise OperationError(exc.message)
Beispiel #12
0
 def get_subcatalog_matches(subcatalog, pat, recursive, paths):
     if len(paths) > 1000:
         raise OperationError("Globbing wayy too many objects")
     for content in subcatalog.content_source().get_leaves():
         if recursive and content.has_content():
             get_subcatalog_matches(content, pat, recursive, paths)
         else:
             if re.match(pat, str(content), flags=re.I):
                 paths.append(content)
Beispiel #13
0
def load_image_max_size(filename, w, h):
    pl = gtk.gdk.PixbufLoader()
    pl.connect("size-prepared", _set_size, w, h)
    try:
        with open(filename, "rb") as f:
            shutil.copyfileobj(f, pl)
        pl.close()
    except (glib.GError, EnvironmentError) as exc:
        raise OperationError(exc)
    return pl.get_pixbuf()
Beispiel #14
0
 def activate(self, trash):
     gfile = gio.File(TRASH_URI)
     failed = []
     for info in gfile.enumerate_children("standard::*,trash::*"):
         name = info.get_name()
         if not gfile.get_child(name).delete():
             failed.append(name)
     if failed:
         err = _("Could not delete files:\n    ")
         raise OperationError(err + '\n    '.join(failed))
Beispiel #15
0
def get_searchobject(sname, opath, sinface, operation_err=False):
    bus = dbus.SessionBus()
    searchobj = None
    try:
        tobj = bus.get_object(sname, opath)
        searchobj = dbus.Interface(tobj, sinface)
    except dbus.DBusException as exc:
        if operation_err:
            raise OperationError(exc)
        pretty.print_debug(__name__, exc)
    return searchobj
Beispiel #16
0
 def activate(self, leaf, iobj, ctx):
     sfile = gio.File(leaf.object)
     dpath = os_path.join(iobj.object, os_path.basename(leaf.object))
     dfile = gio.File(dpath)
     try:
         ret = sfile.copy_async(dfile,
                                self._finish_callback,
                                user_data=(dfile, ctx),
                                flags=gio.FILE_COPY_ALL_METADATA)
         self.output_debug("Copy %s to %s (ret: %s)" % (sfile, dfile, ret))
     except gio.Error, exc:
         raise OperationError(unicode(exc))
Beispiel #17
0
 def activate(self, leaf):
     gfile = Gio.File.new_for_uri(leaf.object["location"])
     try:
         path = gfile.get_path()
     except Exception as exc:
         # On utf-8 decode error
         # FIXME: Unrepresentable path
         raise OperationError(exc)
     if path:
         result = FileLeaf(path)
         if result.is_valid():
             return result
Beispiel #18
0
 def activate(self, leaf, obj):
     sfile = leaf.get_gfile()
     dest = os_path.join(os_path.dirname(leaf.object), obj.object)
     dfile = Gio.File.new_for_path(dest)
     try:
         ret = sfile.move(dfile, Gio.FileCopyFlags.ALL_METADATA, None, None,
                          None)
         self.output_debug("Move %s to %s (ret: %s)" % (sfile, dfile, ret))
     except GLib.Error as exc:
         raise OperationError(str(exc))
     else:
         return FileLeaf(dfile.get_path())
Beispiel #19
0
def finish_command(ctx, acommand, stdout, stderr, post_result=True):
	"""Show async error if @acommand returns error output & error status.
	Else post async result if @post_result.
	"""
	max_error_msg=512
	pretty.print_debug(__name__, "Exited:", acommand)
	if acommand.exit_status != 0 and not stdout and stderr:
		errstr = kupferstring.fromlocale(stderr)[:max_error_msg]
		ctx.register_late_error(OperationError(errstr))
	elif post_result:
		leaf = TextLeaf(kupferstring.fromlocale(stdout))
		ctx.register_late_result(leaf)
Beispiel #20
0
 def activate(self, leaf):
     text = interface.get_text_representation(leaf)
     xte_paste_argv = ['xte', 'usleep 300000']
     # replace all newlines with 'key Return'
     for line in text.splitlines(True):
         xte_paste_argv.append("str " + line.rstrip("\r\n"))
         if line.endswith("\n"):
             xte_paste_argv.append("key Return")
     try:
         utils.spawn_async_raise(xte_paste_argv)
     except utils.SpawnError as exc:
         raise OperationError(exc)
Beispiel #21
0
 def activate(self, leaf, obj):
     sfile = leaf.get_gfile()
     bname = sfile.get_basename()
     dfile = obj.get_gfile().get_child(bname)
     try:
         ret = sfile.move(dfile, Gio.FileCopyFlags.ALL_METADATA, None, None,
                          None)
         self.output_debug("Move %s to %s (ret: %s)" % (sfile, dfile, ret))
     except GLib.Error as exc:
         raise OperationError(str(exc))
     else:
         return FileLeaf(dfile.get_path())
Beispiel #22
0
 def activate(self, leaf):
     orig_path = leaf.get_orig_path()
     if not orig_path:
         return
     orig_gfile = Gio.File.new_for_path(orig_path)
     cur_gfile = leaf.get_gfile()
     if orig_gfile.query_exists():
         raise OperationError("Target file exists at %s" %
                              orig_gfile.get_path())
     pretty.print_debug(__name__, "Move %s to %s" % (cur_gfile, orig_gfile))
     ret = cur_gfile.move(orig_gfile, Gio.FileCopyFlags.ALL_METADATA, None,
                          None, None)
     pretty.print_debug(__name__, "Move ret=%s" % (ret, ))
     return FileLeaf(orig_gfile.get_path())
Beispiel #23
0
    def activate_multiple(self, objects):
        xte_sendkey_argv = ['xte', INIT_DELAY]
        iterobjects = iter(objects)
        for obj in iterobjects:
            xte_sendkey_argv.extend(self.make_keystr_arguments(obj.object))
            break
        for obj in iterobjects:
            xte_sendkey_argv.append(INTER_DELAY)
            xte_sendkey_argv.extend(self.make_keystr_arguments(obj.object))

        try:
            utils.spawn_async_raise(xte_sendkey_argv)
        except utils.SpawnError as exc:
            raise OperationError(exc)
Beispiel #24
0
	def activate(self, leaf, ctx):
		def success_cb():
			pretty.print_debug(__name__, "Successful D-Bus method call")

		def err_cb(exc):
			exc_info = (type(exc), exc, None)
			ctx.register_late_error(exc_info)

		gwibber = _get_interface(True)
		if gwibber:
			gwibber.SendMessage(leaf.object,
			                    reply_handler=success_cb, error_handler=err_cb)
		else:
			pretty.print_error(__name__, "Gwibber Service not found as:",
			                   (SERVICE_NAME, OBJ_NAME, IFACE_NAME))
			raise OperationError(_("Unable to activate Gwibber service"))
Beispiel #25
0
 def make_keystr_arguments(self, keystr):
     keys, orig_mods = Gtk.accelerator_parse(keystr)
     m = {
         Gdk.ModifierType.SHIFT_MASK: "Shift_L",
         Gdk.ModifierType.CONTROL_MASK: "Control_L",
         Gdk.ModifierType.SUPER_MASK: "Super_L",
         Gdk.ModifierType.MOD1_MASK: "Alt_L",
     }
     mod_names = []
     mods = orig_mods
     for mod in m:
         if mod & mods:
             mod_names.append(m[mod])
             mods &= ~mod
     if mods != 0:
         raise OperationError("Keys not yet implemented: %s" %
                 Gtk.accelerator_get_label(keys, orig_mods))
     key_arg = 'key %s' % (Gdk.keyval_name(keys), )
     mods_down = ['keydown ' + n for n in mod_names]
     mods_up = ['keyup ' + n for n in reversed(mod_names)]
     return mods_down + [key_arg] + mods_up
Beispiel #26
0
	def activate(self, leaf):
		gfile = gio.File(leaf.object)
		try:
			gfile.trash()
		except gio.Error as exc:
			raise OperationError(exc)
Beispiel #27
0
def spawn_async(argv):
    try:
        utils.spawn_async_raise(argv)
    except utils.SpawnError as exc:
        raise OperationError(exc)
Beispiel #28
0
 def activate(self, leaf):
     try:
         utils.spawn_async_raise([TRACKER_GUI_SEARCH, leaf.object])
     except utils.SpawnError as exc:
         raise OperationError(exc)
Beispiel #29
0
 def activate(self, leaf):
     text = leaf.object
     try:
         utils.spawn_async_raise(['devhelp', '--search=%s' % text])
     except utils.SpawnError as exc:
         raise OperationError(exc)
Beispiel #30
0
def spawn_operation_err(argv):
    try:
        utils.spawn_async_raise(argv)
    except SpawnError as exc:
        raise OperationError(exc.args[0].message)