def pixbuf_for_file(cls, file_path, icon_size): try: icon = gtk.gdk.pixbuf_new_from_file_at_size( file_path, icon_size, icon_size) return icon except GError: pretty.print_exc(__name__)
def _get_thumb_local(self): # try local filesystem uri = self.object[0]["location"] artist = self.object[0]["artist"].lower() album = self.object[0]["album"].lower() gfile = Gio.File.new_for_uri(uri) cdir = gfile.resolve_relative_path("../").get_path() # We don't support unicode ATM bs_artist_album = \ " - ".join([artist, album]) bs_artist_album2 = \ "-".join([artist, album]) #" - ".join([us.encode("ascii", "ignore") for us in (artist, album)]) cover_names = ( "cover.jpg", "album.jpg", "albumart.jpg", "cover.gif", "album.png", ".folder.jpg", "folder.jpg", bs_artist_album + ".jpg", bs_artist_album2 + ".jpg", ) try: for cover_name in os.listdir(cdir): if cover_name.lower() in cover_names: cfile = gfile.resolve_relative_path("../" + cover_name) return cfile.get_path() except OSError: pretty.print_exc(__name__) return None
def load_icon_from_func(plugin_name, icon_name, get_data_func, override=False): """ Load icon from @icon_data into the name @icon_name @get_data_func: function to retrieve the data if needed @override: override the icon theme """ if not override and icon_name in kupfer_locally_installed_names: pretty.print_debug(__name__, "Skipping existing", icon_name) return if not override and _default_theme.has_icon(icon_name): pretty.print_debug(__name__, "Skipping themed icon", icon_name) return try: icon_data = get_data_func() except: pretty.print_error( __name__, "Error loading icon %r for %r" % (icon_name, plugin_name)) pretty.print_exc(__name__) return for size in (SMALL_SZ, LARGE_SZ): pixbuf = get_pixbuf_from_data(icon_data, size, size) gtk.icon_theme_add_builtin_icon(icon_name, size, pixbuf) pretty.print_debug(__name__, "Loading icon", icon_name, "at", size, "for", plugin_name) kupfer_locally_installed_names.add(icon_name)
def get_icon_for_name(icon_name, icon_size, icon_names=[]): for i in get_icon(icon_name, icon_size): return i if not icon_names: icon_names = (icon_name, ) # Try the whole list of given names for load_name in icon_names: try: icon = _IconRenderer.pixbuf_for_name(load_name, icon_size) if icon: break elif icon_name in kupfer_icon_fallbacks: fallback_name = kupfer_icon_fallbacks[icon_name] icon = _IconRenderer.pixbuf_for_name(fallback_name, icon_size) if icon: break except Exception: pretty.print_exc(__name__) icon = None else: # if we did not reach 'break' in the loop return None # We store the first icon in the list, even if the match # found was later in the chain store_icon(icon_name, icon_size, icon) return icon
def _translate(text, lang): ''' Translate @text to @lang. ''' query_param = urllib.urlencode( dict(v="1.0", langpair="|" + lang, q=text.encode('utf-8'))) try: if ssl_support.is_supported(): conn = ssl_support.VerifiedHTTPSConnection(_GOOGLE_TRANSLATE_HOST, timeout=5) pretty.print_debug(__name__, "Connected to", _GOOGLE_TRANSLATE_HOST, "using SSL") else: conn = httplib.HTTPConnection(_GOOGLE_TRANSLATE_HOST, timeout=5) conn.request("POST", _GOOGLE_TRANSLATE_PATH, query_param, _HEADER) resp = conn.getresponse() if resp.status != 200: raise ValueError('invalid response %d, %s' % (resp.status, resp.reason)) response_data = resp.read() encoding = _parse_encoding_header(resp) response_data = response_data.decode(encoding, 'replace') pretty.print_debug(__name__, "Translate response:", repr(response_data)) try: resp = json_decoder(response_data) yield resp['responseData']['translatedText'], '' except: pretty.print_exc(__name__) yield text, '' except socket.timeout: yield _("Google Translate connection timed out"), "" except (httplib.HTTPException, ValueError), err: pretty.print_error(__name__, '_translate error', repr(text), lang, err) yield _("Error connecting to Google Translate"), ""
def pixbuf_for_file(cls, file_path, icon_size): try: icon = gtk.gdk.pixbuf_new_from_file_at_size(file_path, icon_size, icon_size) return icon except GError: pretty.print_exc(__name__)
def load_icon_from_func(plugin_name, icon_name, get_data_func, override=False): """ Load icon from @icon_data into the name @icon_name @get_data_func: function to retrieve the data if needed @override: override the icon theme """ if not override and icon_name in kupfer_locally_installed_names: pretty.print_debug(__name__, "Skipping existing", icon_name) return if not override and _default_theme.has_icon(icon_name): pretty.print_debug(__name__, "Skipping themed icon", icon_name) return try: icon_data = get_data_func() except: pretty.print_error(__name__, "Error loading icon %r for %r" % (icon_name, plugin_name)) pretty.print_exc(__name__) return for size in (SMALL_SZ, LARGE_SZ): pixbuf = get_pixbuf_from_data(icon_data, size, size) gtk.icon_theme_add_builtin_icon(icon_name, size, pixbuf) pretty.print_debug(__name__, "Loading icon", icon_name, "at", size, "for", plugin_name) kupfer_locally_installed_names.add(icon_name)
def _import_plugin_fake(modpath, error=None): """ Return an object that has the plugin info attributes we can rescue from a plugin raising on import. @error: If applicable, a tuple of exception info """ loader = pkgutil.get_loader(modpath) if not loader: return None code = loader.get_source(modpath) if not code: return None try: filename = loader.get_filename(modpath) except AttributeError: try: filename = loader.archive + loader.prefix except AttributeError: filename = "<%s>" % modpath env = {"__name__": modpath, "__file__": filename, "__builtins__": {"_": _}} code = _truncate_source(code, info_attributes) try: eval(compile(code, filename, "exec"), env) except Exception as exc: pretty.print_error(__name__, "When loading", modpath) pretty.print_exc(__name__) attributes = dict((k, env.get(k)) for k in info_attributes) attributes.update((k, env.get(k)) for k in ["__name__", "__file__"]) return FakePlugin(modpath, attributes, error)
def _translate(text, lang): ''' Translate @text to @lang. ''' query_param = urllib.urlencode(dict(v="1.0",langpair="|"+lang, q=text.encode('utf-8'))) try: if ssl_support.is_supported(): conn = ssl_support.VerifiedHTTPSConnection(_GOOGLE_TRANSLATE_HOST, timeout=5) pretty.print_debug(__name__, "Connected to", _GOOGLE_TRANSLATE_HOST, "using SSL") else: conn = httplib.HTTPConnection(_GOOGLE_TRANSLATE_HOST, timeout=5) conn.request("POST", _GOOGLE_TRANSLATE_PATH, query_param, _HEADER) resp = conn.getresponse() if resp.status != 200: raise ValueError('invalid response %d, %s' % (resp.status, resp.reason)) response_data = resp.read() encoding = _parse_encoding_header(resp) response_data = response_data.decode(encoding, 'replace') pretty.print_debug(__name__, "Translate response:", repr(response_data)) try: resp = json_decoder(response_data) yield resp['responseData']['translatedText'], '' except: pretty.print_exc(__name__) yield text, '' except socket.timeout: yield _("Google Translate connection timed out"), "" except (httplib.HTTPException, ValueError), err: pretty.print_error(__name__, '_translate error', repr(text), lang, err) yield _("Error connecting to Google Translate"), ""
def _create_dbus_connection(): try: sbus = dbus.SessionBus() proxy_obj = sbus.get_object(ACCOUNTMANAGER_IFACE, ACCOUNTMANAGER_PATH) dbus_iface = dbus.Interface(proxy_obj, DBUS_PROPS_IFACE) return dbus_iface except dbus.DBusException as exc: pretty.print_exc(__name__)
def update_icon(kobj, filepath): "Give @filepath a custom icon taken from @kobj" icon_key = "metadata::custom-icon" gfile = Gio.File.new_for_path(filepath) finfo = gfile.query_info(icon_key, Gio.FileQueryInfoFlags.NONE, None) custom_icon_uri = finfo.get_attribute_string(icon_key) if custom_icon_uri and Gio.File.new_for_uri(custom_icon_uri).query_exists(): return namespace = gfile.query_writable_namespaces() # FileAttributeInfoList if namespace.n_infos > 0: pretty.print_debug(__name__, "Updating icon for", filepath) thumb_filename = _write_thumbnail(gfile, kobj.get_pixbuf(128)) try: gfile.set_attribute_string(icon_key, Gio.File.new_for_path(thumb_filename).get_uri(), Gio.FileQueryInfoFlags.NONE, None) except GLib.GError: pretty.print_exc(__name__)
def update_icon(kobj, filepath): "Give @filepath a custom icon taken from @kobj" icon_key = "metadata::custom-icon" gfile = Gio.File.new_for_path(filepath) finfo = gfile.query_info(icon_key, Gio.FileQueryInfoFlags.NONE, None) custom_icon_uri = finfo.get_attribute_string(icon_key) if custom_icon_uri and Gio.File.new_for_uri( custom_icon_uri).query_exists(): return namespace = gfile.query_writable_namespaces() # FileAttributeInfoList if namespace.n_infos > 0: pretty.print_debug(__name__, "Updating icon for", filepath) thumb_filename = _write_thumbnail(gfile, kobj.get_pixbuf(128)) try: gfile.set_attribute_string( icon_key, Gio.File.new_for_path(thumb_filename).get_uri(), Gio.FileQueryInfoFlags.NONE, None) except GLib.GError: pretty.print_exc(__name__)
def decorate_item(cls, leaf): # FIXME: Very simplified .savedSearch parsing, so far we only support # the query, without additional filtering. The simplest form of # .savedSearch file is saved by nautilus as following: # <query version="1.0"> # <text>QUERY GOES HERE</text> # </query> if not leaf.object.endswith(".savedSearch"): return None try: et = ElementTree(file=leaf.object) query = et.getroot().find("text").text if not query: return None location_tag = et.getroot().find("location") location = location_tag.text if location_tag is not None else None return cls(query, location=location_uri(location)) except Exception: pretty.print_exc(__name__) return None
def get_plugin_info(): """Generator, yields dictionaries of plugin descriptions with at least the fields: name localized_name version description author """ for plugin_name in sorted(get_plugin_ids()): try: plugin = import_plugin_any(plugin_name) if not plugin: continue plugin = vars(plugin) except ImportError as e: pretty.print_error(__name__, "import plugin '%s':" % plugin_name, e) continue except Exception as e: pretty.print_error(__name__, "Could not load '%s'" % plugin_name) pretty.print_exc(__name__) continue localized_name = plugin.get("__kupfer_name__", None) desc = plugin.get("__description__", "") vers = plugin.get("__version__", "") author = plugin.get("__author__", "") # skip false matches; # all plugins have to have @localized_name if localized_name is None: continue yield { "name": plugin_name, "localized_name": localized_name, "version": vers, "description": desc or "", "author": author, "provides": (), }
def unimport_plugin(plugin_name): """Remove @plugin_name from the plugin list and dereference its python modules. """ # Run unimport hooks if plugin_name in _plugin_hooks: try: for callback, args in reversed(_plugin_hooks[plugin_name]): callback(*args) except: pretty.print_error(__name__, "Error finalizing", plugin_name) pretty.print_exc(__name__) del _plugin_hooks[plugin_name] del _imported_plugins[plugin_name] plugin_module_name = ".".join(_plugin_path(plugin_name)) pretty.print_debug(__name__, "Dereferencing module", plugin_module_name) if plugin_module_name in sys.modules: sys.modules.pop(plugin_module_name) for mod in list(sys.modules): if mod.startswith(plugin_module_name + "."): pretty.print_debug(__name__, "Dereferencing module", mod) sys.modules.pop(mod)
def _import_plugin_fake(modpath, error=None): """ Return an object that has the plugin info attributes we can rescue from a plugin raising on import. @error: If applicable, a tuple of exception info """ loader = pkgutil.get_loader(modpath) if not loader: return None code = loader.get_source(modpath) if not code: return None try: filename = loader.get_filename(modpath) except AttributeError: try: filename = loader.archive + loader.prefix except AttributeError: filename = "<%s>" % modpath env = { "__name__": modpath, "__file__": filename, "__builtins__": {"_": _} } code = _truncate_source(code, info_attributes) try: eval(compile(code, filename, "exec"), env) except Exception as exc: pretty.print_error(__name__, "When loading", modpath) pretty.print_exc(__name__) attributes = dict((k, env.get(k)) for k in info_attributes) attributes.update((k, env.get(k)) for k in ["__name__", "__file__"]) return FakePlugin(modpath, attributes, error)
def _translate(text, lang): ''' Translate @text to @lang. ''' query_param = urllib.urlencode(dict(v="1.0",langpair="|"+lang, q=text.encode('utf-8'))) word_classes = { # TRANS: Dictionary lookup word classes "noun": _("noun"), "verb": _("verb"), "adjective": _("adjective"), } try: conn = httplib.HTTPConnection(_GOOGLE_TRANSLATE_HOST) conn.connect() conn.sock.settimeout(10) # set timeout to 10 sec conn.request("POST", _GOOGLE_TRANSLATE_PATH, query_param, _HEADER) resp = conn.getresponse() if resp.status != 200: raise ValueError('invalid response %d, %s' % (resp.status, resp.reason)) response_data = resp.read() encoding = _parse_encoding_header(resp) response_data = response_data.decode(encoding, 'replace') pretty.print_debug(__name__, "Translate response:", repr(response_data)) try: resp = json_decoder(response_data) yield resp['responseData']['translatedText'], '' except: pretty.print_exc(__name__) yield text, '' except socket.timeout: yield _("Google Translate connection timed out"), "" except (httplib.HTTPException, ValueError), err: pretty.print_error(__name__, '_translate error', repr(text), lang, err) yield _("Error connecting to Google Translate"), ""
def exc_log(): pretty.print_exc(__name__)