def activate(self, leaf): gfile = Gio.File.new_for_uri(leaf.object["location"]) path = gfile.get_path() if path: result = FileLeaf(path) if result.is_valid(): return result
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
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 raise NotAvailableError(str(leaf))
def get_text_items(self, text): # Find directories or files if self._is_local_file_url(text): leaf = FileLeaf.from_uri(text) if leaf and leaf.is_valid(): yield leaf else: prefix = os.path.expanduser("~/") ufilepath = text if os.path.isabs(text) else os.path.join( prefix, text) filepath = os.path.normpath(ufilepath) if os.access(filepath, os.R_OK): yield FileLeaf(filepath)
def _get_items(max_days, for_app_names=None): """ for_app_names: set of candidate app names, or None. """ def first_word(s): return s.split(None, 1)[0] for file_path, _modified, item in RecentsSource._get(max_days): if for_app_names: apps = item.get_applications() in_low_apps = any(A.lower() in for_app_names for A in apps) in_execs = any( first_word(item.get_application_info(A)[0]) in for_app_names for A in apps) if not in_low_apps and not in_execs: continue if for_app_names: accept_item = True for app_id, sort_table in SEPARATE_APPS.items(): if app_id in for_app_names: _, ext = path.splitext(file_path) ext = ext.lower() if ext in sort_table and sort_table[ ext] not in for_app_names: accept_item = False break if not accept_item: continue yield FileLeaf(file_path)
def get_text_items(self, text): # Find directories or files prefix = os.path.expanduser("~/") ufilepath = text if os.path.isabs(text) else os.path.join(prefix, text) filepath = os.path.normpath(ufilepath) if os.access(filepath, os.R_OK): yield FileLeaf(filepath)
def get_text_items(self, text): # Find directories or files prefix = os.path.expanduser(u"~/") ufilepath = text if os.path.isabs(text) else os.path.join(prefix, text) # use filesystem encoding here filepath = gobject.filename_from_utf8(os.path.normpath(ufilepath)) if os.access(filepath, os.R_OK): yield FileLeaf(filepath)
def _finish_callback(self, gfile, result, data): self.output_debug("Finished copying", gfile) dfile, ctx = data try: gfile.copy_finish(result) except gio.Error: ctx.register_late_error() else: ctx.register_late_result(FileLeaf(dfile.get_path()))
class RecentsSource(AppLeafContentMixin, Source, PicklingHelperMixin): appleaf_content_id = "abiword" def __init__(self, name=None): if not name: name = _("Abiword Recent Items") super(RecentsSource, self).__init__(name) self.unpickle_finish() def pickle_prepare(self): # monitor is not pickleable self.monitor = None def unpickle_finish(self): """Set up change monitor""" abifile = self._get_abiword_file() if not abifile: return gfile = gio.File(abifile) self.monitor = gfile.monitor_file(gio.FILE_MONITOR_NONE, None) if self.monitor: self.monitor.connect("changed", self._changed) def _changed(self, monitor, file1, file2, evt_type): """Change callback; something changed""" if evt_type in (gio.FILE_MONITOR_EVENT_CREATED, gio.FILE_MONITOR_EVENT_DELETED, gio.FILE_MONITOR_EVENT_CHANGED): self.mark_for_update() def _get_abiword_file(self): abifile = os.path.expanduser("~/.AbiSuite/AbiWord.Profile") if not os.path.exists(abifile): return None return abifile def get_items(self): abifile = self._get_abiword_file() if not abifile: self.output_debug("Abiword profile not found at", abifile) return try: uris = list(get_abiword_files(abifile)) except EnvironmentError, exc: self.output_error(exc) return for uri in uris: gfile = gio.File(uri) if not gfile.query_exists(): continue if gfile.get_path(): leaf = FileLeaf(gfile.get_path()) else: leaf = UrlLeaf(gfile.get_uri(), gfile.get_basename()) yield leaf
def reply(results): ret = [] new_file = Gio.File.new_for_uri for result in results: try: ret.append(FileLeaf(new_file(result[0]).get_path())) except Exception: # This very vague exception is from getpath continue ctx.register_late_result( TrackerQuerySource(query, search_results=ret))
def _create_history_leaf(path): ''' Create leaf from file url ''' if not path: return None gfile = gio.File(path) if not gfile.query_exists(): None if gfile.get_path(): return FileLeaf(gfile.get_path()) return UrlLeaf(path, gfile.get_basename())
def get_items(self): with closing(sqlite3.connect(self.metadata_file, timeout=1)) as conn: curs = conn.cursor() curs.execute( "select format, name from data " "where book=? " "order by format", (self.book_id, )) for format_, name in curs: yield FileLeaf( os.path.join(self.path, name + "." + format_.lower()))
def activate(self, leaf, iobj): outfile, outpath = \ utils.get_destfile_in_directory(iobj.object, _("Empty File")) try: l_text = kupferstring.tolocale(leaf.object) outfile.write(l_text) if not l_text.endswith(b"\n"): outfile.write(b"\n") finally: outfile.close() return FileLeaf(outpath)
def activate(self, leaf, obj, ctx): size = self._make_size(obj.object) fpath = leaf.object dirname = os_path.dirname(fpath) head, ext = os_path.splitext(os_path.basename(fpath)) filename = "%s_%s%s" % (head, size, ext) dpath = utils.get_destpath_in_directory(dirname, filename) argv = ["convert", "-scale", ('%s' % size), fpath, dpath] runtimehelper.register_async_file_result(ctx, dpath) spawn_operation_err(argv) return FileLeaf(dpath)
def activate(self, leaf): orig_path = leaf.get_orig_path() if not orig_path: return orig_gfile = gio.File(orig_path) cur_gfile = leaf.get_gfile() if orig_gfile.query_exists(): raise IOError("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) pretty.print_debug(__name__, "Move ret=%s" % (ret, )) return FileLeaf(orig_gfile.get_path())
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())
def get_text_items(self, text): # Find directories or files if text.startswith("file:///"): leaf = FileLeaf.from_uri(text) if leaf and leaf.is_valid(): yield leaf else: prefix = os.path.expanduser("~/") ufilepath = text if os.path.isabs(text) else os.path.join(prefix, text) filepath = os.path.normpath(ufilepath) if os.access(filepath, os.R_OK): yield FileLeaf(filepath)
def activate(self, leaf): # Try to find the __file__ attribute for the plugin # It will fail for files inside zip packages, but that is # uncommon for now. # Additionally, it will fail for fake plugins plugin_id = leaf.object["name"] filename = plugins.get_plugin_attribute(plugin_id, "__file__") if not filename: return leaf root, ext = os.path.splitext(filename) if ext.lower() == ".pyc" and os.path.exists(root + ".py"): return FileLeaf(root + ".py") if not os.path.exists(filename): # handle modules in zip or eggs import pkgutil pfull = "kupfer.plugin." + plugin_id loader = pkgutil.get_loader(pfull) if loader: return TextLeaf(loader.get_source(pfull)) return FileLeaf(filename)
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())
def activate(self, leaf, ctx): fpath = leaf.object dirname = os_path.dirname(fpath) head, ext = os_path.splitext(os_path.basename(fpath)) filename = "%s_%s%s" % (head, self.rotation, ext) dpath = utils.get_destpath_in_directory(dirname, filename) argv = [ "jpegtran", "-copy", "all", "-rotate", self.rotation, "-outfile", dpath, fpath ] runtimehelper.register_async_file_result(ctx, dpath) spawn_operation_err(argv) return FileLeaf(dpath)
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())
def get_file_results_sparql(searchobj, query, max_items): clean_query = sparql_escape(query) sql = u"""SELECT tracker:coalesce (nie:url (?s), ?s) WHERE { ?s fts:match "%s*" . ?s tracker:available true . } ORDER BY tracker:weight(?s) OFFSET 0 LIMIT %d""" % (clean_query, int(max_items)) pretty.print_debug(__name__, "Searching for %s (%s)", repr(clean_query), repr(query)) pretty.print_debug(__name__, sql) results = searchobj.SparqlQuery(sql) gio_File = gio.File for result in results: yield FileLeaf(gio_File(result[0]).get_path())
def _get_places(self, fileloc): for line in open(fileloc): if not line.strip(): continue items = line.split(None, 1) uri = items[0] gfile = Gio.File.new_for_uri(uri) if len(items) > 1: title = items[1].strip() else: disp = gfile.get_parse_name() title = path.basename(disp) locpath = gfile.get_path() if locpath: yield FileLeaf(locpath, title) else: yield UrlLeaf(gfile.get_uri(), title)
def get_items(self): viminfofile = os.path.expanduser(self.vim_viminfo_file) if not os.path.exists(viminfofile): self.output_debug("Viminfo not found at", viminfofile) return try: filepaths = list(get_vim_files(viminfofile)) except EnvironmentError: self.output_exc() return for filepath in filepaths: # The most confusing glib function # takes a unicode string and returns a # filesystem-encoded bytestring. yield FileLeaf(glib.filename_from_utf8(filepath))
def activate(self, leaf, iobj): if iobj.object is not None: # Copy the template to destination directory basename = os.path.basename(iobj.object) tmpl_gfile = Gio.File.new_for_path(iobj.object) destpath = utils.get_destpath_in_directory(leaf.object, basename) destfile = Gio.File.new_for_path(destpath) tmpl_gfile.copy(destfile, Gio.FileCopyFlags.ALL_METADATA, None, None, None) elif isinstance(iobj, NewFolder): filename = str(iobj) destpath = utils.get_destpath_in_directory(leaf.object, filename) os.makedirs(destpath) else: # create new empty file filename = str(iobj) f, destpath = utils.get_destfile_in_directory(leaf.object, filename) f.close() return FileLeaf(destpath)
def activate(self, leaf, iobj): if iobj.object is not None: # Copy the template to destination directory basename = os.path.basename(iobj.object) tmpl_gfile = gio.File(iobj.object) destpath = utils.get_destpath_in_directory(leaf.object, basename) destfile = gio.File(destpath) tmpl_gfile.copy(destfile, flags=gio.FILE_COPY_ALL_METADATA) elif isinstance(iobj, NewFolder): filename = unicode(iobj) destpath = utils.get_destpath_in_directory(leaf.object, filename) os.makedirs(destpath) else: # create new empty file filename = unicode(iobj) f, destpath = utils.get_destfile_in_directory(leaf.object, filename) f.close() return FileLeaf(destpath)
def get_file_results_sparql(searchobj, query, max_items=50, order_by="rank", **kwargs): clean_query = sparql_escape(query) sql = ("""SELECT tracker:coalesce (nie:url (?s), ?s) WHERE { ?s fts:match "%s" . ?s tracker:available true . } %s OFFSET 0 LIMIT %d""" % (clean_query, ORDER_BY[order_by], int(max_items))) pretty.print_debug(__name__, sql) results = searchobj.SparqlQuery(sql, **kwargs) if results is None: return new_file = Gio.File.new_for_uri for result in results: try: yield FileLeaf(new_file(result[0]).get_path()) except Exception: # This very vague exception is from getpath continue
def get_file_results_sparql(searchobj, query, max_items=50, order_by="rank", location=None, **kwargs): clean_query = sparql_escape(query) if location: location_filter = \ 'FILTER(tracker:uri-is-descendant ("%s", nie:url (?s)))' % sparql_escape(location) else: location_filter = "" sql = ("""SELECT tracker:coalesce (nie:url (?s), ?s) WHERE { ?s fts:match "%(query)s" . ?s tracker:available true . %(location_filter)s } %(order_by)s OFFSET 0 LIMIT %(limit)d""" % dict(query=clean_query, location_filter=location_filter, order_by=ORDER_BY[order_by], limit=int(max_items))) pretty.print_debug(__name__, sql) results = searchobj.SparqlQuery(sql, **kwargs) if results is None: return new_file = Gio.File.new_for_uri for result in results: try: yield FileLeaf(new_file(result[0]).get_path()) except Exception: # This very vague exception is from getpath continue
def _get_items(cls, max_days, for_application_named=None): manager = recent_manager_get_default() items = manager.get_items() item_leaves = [] for item in items: if for_application_named: low_apps = [A.lower() for A in item.get_applications()] if for_application_named.lower() not in low_apps: continue day_age = item.get_age() if max_days >= 0 and day_age > max_days: continue if not item.exists(): continue uri = item.get_uri() name = item.get_short_name() if item.is_local(): leaf = FileLeaf(gio.File(uri).get_path()) else: leaf = UrlLeaf(uri, name) item_leaves.append((leaf, item.get_modified())) for lf, date in sorted(item_leaves, key=lambda t: t[1], reverse=True): yield lf
def get_gicon(self): file_gicon = FileLeaf.get_gicon(self) return icons.ComposedIcon("text-x-generic-template", file_gicon)
def get_actions(self): yield CreateDocumentIn() for a in FileLeaf.get_actions(self): yield a
def __init__(self, path): basename = glib.filename_display_basename(path) nameroot, ext = os.path.splitext(basename) FileLeaf.__init__(self, path, _("%s template") % nameroot)
def __init__(self, paths): files = [FileLeaf(path) for path in paths] MultipleLeaf.__init__(self, files, _("Clipboard Files"))
def __init__(self, filepath): """@filepath is a filesystem byte string `str`""" FileLeaf.__init__(self, filepath, _('Clipboard File'))
def changed(self, monitor, gfile1, gfile2, event): if event == gio.FILE_MONITOR_EVENT_CHANGES_DONE_HINT: self.ctx.register_late_result(FileLeaf(gfile1.get_path())) self.monitor.disconnect(self.callback_id) self.monitor = None
def __init__(self, filepath): """@filepath is a filesystem byte string `str`""" basename = gobject.filename_display_basename(filepath) FileLeaf.__init__(self, filepath, _('Selected File "%s"') % basename)