def _load_languages(): ''' Load available languages from Google. Generator: (lang_code, lang name) ''' user_language = locale.getlocale(locale.LC_MESSAGES)[0] pretty.print_debug(__name__, '_load_languages') try: conn = httplib.HTTPConnection(_GOOGLE_TRANS_LANG_HOST) conn.connect() conn.sock.settimeout(10) # set timeout to 10 sec headers = { "Accept-Language": "%s, en;q=0.7" % user_language, } conn.request("GET", _GOOGLE_TRANS_LANG_PATH, headers=headers) resp = conn.getresponse() if resp.status != 200: raise ValueError('invalid response %d, %s' % (resp.status, resp.reason)) result = resp.read().decode(_parse_encoding_header(resp), "replace") result = _RE_GET_LANG_SELECT.findall(result) if result: for key, name in _RE_GET_LANG.findall(result[0]): yield key, name except socket.timeout: pretty.print_error(__name__, 'Timed out when loading languages') except (httplib.HTTPException, ValueError, socket.error), err: pretty.print_error(__name__, '_load_languages error', type(err), err)
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(plugin_name) if not plugin: continue plugin = vars(plugin) except ImportError, e: pretty.print_error(__name__, "import plugin '%s':" % plugin_name, e) 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 u"", "author": author, "provides": (), }
def parse_load_icon_list(icon_list_data, get_data_func, plugin_name=None): """ @icon_list_data: A bytestring whose lines identify icons @get_data_func: A function to return the data for a relative filename @plugin_name: plugin id, if applicable """ try: icon_list_string = icon_list_data.decode("utf-8") except UnicodeDecodeError as exc: pretty.print_error(__name__, "Malformed icon-list in plugin %r: %r" % (plugin_name, exc)) raise for line in icon_list_string.splitlines(): # ignore '#'-comments if line.startswith("#") or not line.strip(): continue fields = list(map(str.strip, line.split('\t'))) if len(fields) < 2: pretty.print_error(__name__, "Malformed icon-list line %r from %r" % (line, plugin_name)) continue icon_name, basename = fields[:2] override = ('!override' in fields) def wrap_get_data(): return get_data_func(basename) load_icon_from_func(plugin_name, icon_name, wrap_get_data, override)
def download_image(url): result = None try: f = urllib2.urlopen(url) result = f.read() except urllib2.HTTPError, err: pretty.print_error(__name__, 'download_image', url, err)
def show_url(url): """Open any @url with default viewer""" try: pretty.print_debug(__name__, "show_url", url) return Gtk.show_uri(Gdk.Screen.get_default(), url, Gtk.get_current_event_time()) except GLib.GError as exc: pretty.print_error(__name__, "Gtk.show_uri:", exc)
def bind_key(keystr, keybinding_target=KEYBINDING_DEFAULT): """ Bind @keystr, unbinding any previous key for @keybinding_target. If @keystr is a false value, any previous key will be unbound. """ keybinding_target = int(keybinding_target) if Keybinder is None: return False def callback(keystr): return GetKeyboundObject()._keybinding(keybinding_target) if not _is_sane_keybinding(keystr): pretty.print_error(__name__, "Refusing to bind key", repr(keystr)) return False succ = True if keystr: try: succ = Keybinder.bind(keystr, callback) pretty.print_debug(__name__, "binding", repr(keystr)) GetKeyboundObject().emit_bound_key_changed(keystr, True) except KeyError as exc: pretty.print_error(__name__, exc) succ = False if succ: old_keystr = get_currently_bound_key(keybinding_target) if old_keystr and old_keystr != keystr: Keybinder.unbind(old_keystr) pretty.print_debug(__name__, "unbinding", repr(old_keystr)) GetKeyboundObject().emit_bound_key_changed(old_keystr, False) _register_bound_key(keystr, keybinding_target) return succ
def _find_all_contacts(self, interface): bus = dbus.SessionBus() for valid_account in interface.Get(ACCOUNTMANAGER_IFACE, "ValidAccounts"): try: #ignore account errors account = bus.get_object(ACCOUNTMANAGER_IFACE, valid_account) connection_status = account.Get(ACCOUNT_IFACE, "ConnectionStatus") if connection_status != 0: continue connection_path = account.Get(ACCOUNT_IFACE, "Connection") bus_name = connection_path.replace("/", ".")[1:] connection = bus.get_object(bus_name, connection_path) connection.ListChannels( reply_handler=partial( self._reply_handle_channels, { 'connection': connection, 'bus_name': bus_name, 'bus': bus, 'valid_account': valid_account }), error_handler=lambda *args, **kwds: self. _error_handle_channels(*args, **kwds), ) except dbus.DBusException as exc: pretty.print_error(__name__, type(exc).__name__, exc)
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 _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 _connect_session_manager(self): bus = dbus.SessionBus() proxy_obj = bus.get_object('org.freedesktop.DBus', '/org/freedesktop/DBus') dbus_iface = dbus.Interface(proxy_obj, 'org.freedesktop.DBus') service_name = "org.gnome.SessionManager" obj_name = "/org/gnome/SessionManager" iface_name = service_name if not dbus_iface.NameHasOwner(service_name): self.output_debug("D-Bus name %s not found" % service_name) return False try: obj = bus.get_object(service_name, obj_name) except dbus.DBusException as e: pretty.print_error(__name__, e) return False smanager = dbus.Interface(obj, iface_name) app_id = version.PACKAGE_NAME startup_id = os.getenv("DESKTOP_AUTOSTART_ID") or "" self.client_id = smanager.RegisterClient(app_id, startup_id) self._session_ended = False self.output_debug("Connected to session as client", self.client_id, startup_id) private_iface_name = "org.gnome.SessionManager.ClientPrivate" bus.add_signal_receiver(self._query_end_session, "QueryEndSession", dbus_interface=private_iface_name) bus.add_signal_receiver(self._end_session_signal, "EndSession", dbus_interface=private_iface_name) bus.add_signal_receiver(self._stop_signal, "Stop", dbus_interface=private_iface_name) return True
def activate(self, leaf): expr = leaf.object.lstrip("= ") # try to add missing parantheses brackets_missing = expr.count("(") - expr.count(")") if brackets_missing > 0: expr += ")" * brackets_missing environment = dict(math.__dict__) environment.update(cmath.__dict__) # define some constants missing if self.last_result is not None: environment["_"] = self.last_result environment["help"] = Help() environment["kupfer"] = KupferSurprise("inf") # make the builtins inaccessible environment["__builtins__"] = {} pretty.print_debug(__name__, "Evaluating", repr(expr)) try: result = eval(expr, environment) resultstr = format_result(result) self.last_result = result except IgnoreResultException: return except Exception, exc: pretty.print_error(__name__, type(exc).__name__, exc) resultstr = unicode(exc)
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_notes_interface(activate=False): """Return the dbus proxy object for our Note Application. if @activate, we will activate it over d-bus (start if not running) """ bus = dbus.SessionBus() proxy_obj = bus.get_object('org.freedesktop.DBus', '/org/freedesktop/DBus') dbus_iface = dbus.Interface(proxy_obj, 'org.freedesktop.DBus') set_prog = __kupfer_settings__["notes_application"] programs = (set_prog, ) if set_prog else PROGRAM_IDS for program in programs: service_name, obj_name, iface_name = PROGRAM_SERIVCES[program] if not activate and not dbus_iface.NameHasOwner(service_name): continue try: searchobj = bus.get_object(service_name, obj_name) except dbus.DBusException, e: pretty.print_error(__name__, e) return notes = dbus.Interface(searchobj, iface_name) return notes
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, e: pretty.print_error(__name__, "import plugin '%s':" % plugin_name, e) 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 u"", "author": author, "provides": (), }
def _get_machine_info(vm_uuid, config_file): ''' load information about virtual machines from its configuration file. @param vm_uuid - uuid virtual machine @param config_file - path to vm configuration file ''' if not os.path.isfile(config_file): return None, None try: dtree = minidom.parse(config_file) machine_registry = dtree.getElementsByTagName('Machine')[0] os_type = machine_registry.getAttribute('OSType') name = machine_registry.getAttribute('name') description = None for machine_registry_child in machine_registry.childNodes: if machine_registry_child.nodeName == 'Description': if machine_registry_child.hasChildNodes(): description = machine_registry_child.firstChild.nodeValue break return (name, description or os_type) except StandardError, err: pretty.print_error(__name__, '_get_machine_info', vm_uuid, 'error' + \ config_file, err)
def thread_do(self): gd_client = picasa_login() if not gd_client: return progress_dialog = ProgressDialogController( _("Uploading Pictures"), _("Uploading pictures to Picasa Web Album"), max_value=self._files_albums_count ) progress_dialog.show() try: upass = __kupfer_settings__["userpass"] progress = 0 for files, album_id, album_name in self._files_to_upload: # create album if album_id is None: progress_dialog.update(progress, _("Creating album:"), album_name) album = gd_client.InsertAlbum(title=album_name, summary=_("Album created by Kupfer")) album_id = album.gphoto_id.text progress += 1 # send files album_url = ALBUM_URL % (upass.username, album_id) for filename in files: pretty.print_debug(__name__, "upload: sending", filename) progress_dialog.update(progress, _("File:"), utils.get_display_path_for_bytestring(filename)) if progress_dialog.aborted: pretty.print_debug(__name__, "upload: abort") break # send file gd_client.InsertPhotoSimple(album_url, os.path.basename(filename), "", filename) pretty.print_debug(__name__, "upload: file sended", filename) progress += 1 except (gdata.service.Error, gdata.photos.service.GooglePhotosException), err: pretty.print_error(__name__, "upload error", err)
def activate(self, leaf, iobj): bus = dbus.SessionBus() interface = _create_dbus_connection() for valid_account in interface.Get(ACCOUNTMANAGER_IFACE, "ValidAccounts"): #ignore fails by account try: account = bus.get_object(ACCOUNTMANAGER_IFACE, valid_account) connection_status = account.Get(ACCOUNT_IFACE, "ConnectionStatus") if connection_status != 0: continue if iobj.object == "offline": false = dbus.Boolean(0, variant_level=1) account.Set(ACCOUNT_IFACE, "Enabled", false) else: connection_path = account.Get(ACCOUNT_IFACE, "Connection") connection_iface = connection_path.replace("/", ".")[1:] connection = bus.get_object(connection_iface, connection_path) simple_presence = dbus.Interface(connection, SIMPLE_PRESENCE_IFACE) simple_presence.SetPresence(iobj.object, _STATUSES.get(iobj.object)) except dbus.DBusException as exc: pretty.print_error(__name__, type(exc).__name__, exc)
def get_contacts(): ''' load all contacts ''' pretty.print_debug(__name__, 'get_contacts start') contacts = None start_time = time.time() try: gd_client = get_gclient() if gd_client is None: return None contacts = [] query = gdata.contacts.service.ContactsQuery() query.max_results = 9999 # load all contacts for entry in gd_client.GetContactsFeed(query.ToUri()).entry: common_name = kupferstring.tounicode(entry.title.text) for email in entry.email: if email.address: image = None if __kupfer_settings__['loadicons']: image = gd_client.GetPhoto(entry) email = email.address contacts.append(GoogleContact(email, common_name or email, image)) except (gdata.service.BadAuthentication, gdata.service.CaptchaRequired), err: pretty.print_error(__name__, 'get_contacts error', 'authentication error', err) contacts = [InvalidCredentialsLeaf(__name__, __kupfer_name__)]
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 parse_load_icon_list(icon_list_data, get_data_func, plugin_name=None): """ @icon_list_data: A bytestring whose lines identify icons @get_data_func: A function to return the data for a relative filename @plugin_name: plugin id, if applicable """ try: icon_list_string = icon_list_data.decode("utf-8") except UnicodeDecodeError as exc: pretty.print_error( __name__, "Malformed icon-list in plugin %r: %r" % (plugin_name, exc)) raise for line in icon_list_string.splitlines(): # ignore '#'-comments if line.startswith("#") or not line.strip(): continue fields = list(map(str.strip, line.split('\t'))) if len(fields) < 2: pretty.print_error( __name__, "Malformed icon-list line %r from %r" % (line, plugin_name)) continue icon_name, basename = fields[:2] override = ('!override' in fields) def wrap_get_data(): return get_data_func(basename) load_icon_from_func(plugin_name, icon_name, wrap_get_data, override)
def get_contacts(): ''' load all contacts ''' pretty.print_debug(__name__, 'get_contacts start') contacts = None start_time = time.time() try: gd_client = get_gclient() if gd_client is None: return None contacts = [] query = gdata.contacts.service.ContactsQuery() query.max_results = 9999 # load all contacts for entry in gd_client.GetContactsFeed(query.ToUri()).entry: common_name = kupferstring.tounicode(entry.title.text) for email in entry.email: if email.address: image = None if __kupfer_settings__['loadicons']: image = gd_client.GetPhoto(entry) email = email.address contacts.append( GoogleContact(email, common_name or email, image)) except (gdata.service.BadAuthentication, gdata.service.CaptchaRequired), err: pretty.print_error(__name__, 'get_contacts error', 'authentication error', err) contacts = [InvalidCredentialsLeaf(__name__, __kupfer_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 _create_dbus_connection(activate=False): interface = _create_dbus_connection_gtg(_IFACE_NAME2, _OBJECT_NAME2, _SERVICE_NAME2, activate) if interface is None: pretty.print_error(__name__, 'Cannot connect to GTG via DBus') if activate: raise NotAvailableError(_("Getting Things GNOME")) return interface
def get_public_url(cls, filepath): dbox = cls() dbox._connect() try: res = dbox._send_command('get_public_link', {'path': filepath}) except Exception, err: pretty.print_error(err) raise DropboxError(err)
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_error(__name__, type(exc).__name__, exc)
def _get_object_session(): ''' get new session to vm ''' vbox, session = None, None try: vbox = vboxapi.VirtualBoxManager(None, None) session = vbox.mgr.getSessionObject(vbox.vbox) except Exception, err: pretty.print_error(__name__, 'virtualbox: get session error ', err)
def launch_commandline(cli, name=None, in_terminal=False): " Raises SpawnError " argv = desktop_parse.parse_argv(cli) pretty.print_error(__name__, "Launch commandline is deprecated ") pretty.print_debug(__name__, "Launch commandline (in_terminal=", in_terminal, "):", argv, sep="") if in_terminal: return spawn_in_terminal(argv) return spawn_async(argv)
def __init__(self): self._friends = None self._authenticated = False try: self.bus = bus = dbus.Bus() except dbus.DBusException, err: pretty.print_error(__name__, 'Skype', '__init__', err) return
def get_tracker_filequery(query, operation_err=False, **kwargs): searchobj = get_searchobject(*versions[use_version], operation_err=operation_err) if searchobj is None: pretty.print_error(__name__, "Could not connect to Tracker") return () queryfunc = version_query[use_version] return queryfunc(searchobj, query, **kwargs)
def activate(self, leaf): if type(leaf) == AppLeaf: cmd = "%s %s" %(__kupfer_settings__["sudo_command"], leaf.object.get_commandline()) ret = launch_commandline(cmd) if ret: return ret pretty.print_error(__name__, "Unable to run command(s)", cmd) elif type(leaf) == FileLeaf: self.activate_multiple((leaf, ))
def _create_dbus_connection(activate=False): interface, apiver = _create_dbus_connection_gtg(_IFACE_NAME, _OBJECT_NAME, _SERVICE_NAME, activate), 1 if interface is None: interface, apiver = _create_dbus_connection_gtg( _IFACE_NAME2, _OBJECT_NAME2, _SERVICE_NAME2, activate), 2 if interface is None: pretty.print_error('Cannot connect to GTG via DBus') return interface, apiver
def _get_existing_session(vm_uuid): ''' get existing session by machine uuid ''' vbox, session = None, None try: vbox = vboxapi.VirtualBoxManager(None, None) session = vbox.mgr.getSessionObject(vbox.vbox) except Exception, err: pretty.print_error(__name__, 'virtualbox: get session error', vm_uuid, err)
def get_contacts(): ''' load all contacts ''' pretty.print_debug(__name__, 'get_contacts start') start_time = time.time() num_contacts = 0 try: gd_client = get_gclient() if gd_client is None: return query = gdata.contacts.service.ContactsQuery() query.max_results = 9999 # load all contacts for entry in gd_client.GetContactsFeed(query.ToUri()).entry: if not entry.email: # skip contacts without email continue num_contacts += 1 common_name = kupferstring.tounicode(entry.title.text) primary_mail_key = {contacts.EMAIL_KEY: entry.email[0].address} contact_id = None try: contact_id = entry.id.text.split('/')[-1] except: pass image = None if __kupfer_settings__['loadicons']: # Sometimes GetPhoto can't find appropriate image (404) try: image = gd_client.GetPhoto(entry) except: pass for email in entry.email: if email.address: email_str = email.address yield GoogleContact(email_str, common_name or email_str, image, contact_id, REL_LIST_EMAIL.get(email.rel)) if not __kupfer_settings__['loadadditional']: continue for phone in entry.phone_number: if phone.text: yield contacts.PhoneContact(phone.text, common_name, REL_LIST_PHONE.get(phone.rel), slots=primary_mail_key, image=image) for address in entry.postal_address: if address.text: yield contacts.AddressContact(address.text, common_name, REL_LIST_PHONE.get(address.rel), slots=primary_mail_key, image=image) for im in entry.im: im_id = im.text or im.address protocol = im.protocol or im.rel if im_id and protocol in REL_LIST_IM: yield REL_LIST_IM[protocol](im_id, common_name, slots=primary_mail_key, image=image) except (gdata.service.BadAuthentication, gdata.service.CaptchaRequired), err: pretty.print_error(__name__, 'get_contacts error', 'authentication error', err) yield InvalidCredentialsLeaf(__name__, __kupfer_name__)
def _create_dbus_connection(activate=False): interface, apiver = _create_dbus_connection_gtg(_IFACE_NAME, _OBJECT_NAME, _SERVICE_NAME, activate), 1 if interface is None: interface, apiver = _create_dbus_connection_gtg(_IFACE_NAME2, _OBJECT_NAME2, _SERVICE_NAME2, activate), 2 if interface is None: pretty.print_error('Cannot connect to GTG via DBus') return interface, apiver
def activate(self, leaf, ctx=None): if type(leaf) == AppLeaf: cmd = "%s %s" % (__kupfer_settings__["sudo_command"], leaf.object.get_commandline()) ret = utils.launch_commandline(cmd) if ret: return ret pretty.print_error(__name__, "Unable to run command(s)", cmd) elif type(leaf) == FileLeaf: self.activate_multiple((leaf, ), ctx)
def show_url(url): """Open any @url with default viewer""" from gtk import show_uri, get_current_event_time from gtk.gdk import screen_get_default from glib import GError try: pretty.print_debug(__name__, "show_url", url) return show_uri(screen_get_default(), url, get_current_event_time()) except GError, exc: pretty.print_error(__name__, "gtk.show_uri:", exc)
def launch_argv_with_fallbacks(commands, print_error=True): """Try the sequence of @commands with utils.spawn_async, and return with the first successful command. return False if no command is successful and log an error """ for argv in commands: ret = utils.spawn_async(argv) if ret: return ret pretty.print_error(__name__, "Unable to run command(s)", commands) return False
def _get_thunar_trash(): """Return the dbus proxy object for Thunar we will activate it over d-bus (start if not running) """ bus = dbus.SessionBus() try: proxy_obj = bus.get_object(SERVICE_NAME, OBJECT_PATH) except dbus.DBusException, e: pretty.print_error(__name__, e) return
def launch_argv_with_fallbacks(commands, print_error=True): """Try the sequence of @commands with utils.spawn_async, and return with the first successful command. return False if no command is successful and log an error """ for argv in commands: pretty.print_error(__name__, 'command: ', argv) subprocess.Popen(argv, shell=True, stdout=subprocess.PIPE) pretty.print_error(__name__, "Unable to run command(s)", commands) return False
def _get_amarok(): """ Return the dbus proxy object for Amarok we will activate it over d-bus (start if not running) """ bus = dbus.SessionBus() try: amarok_obj = bus.get_object(SERVICE_NAME, OBJECT_PATH) except dbus.DBusException, e: pretty.print_error(__name__, e) return
def _execute_machine_action(vm_uuid, action): ''' Start virtual machine @param vm_uuid - uuid of virtual machine @param action - function called on vbox session ''' vbox, session = _get_existing_session(vm_uuid) try: action(session.console) except Exception, err: pretty.print_error(__name__, "_execute_machine_action:", repr(action), " vm:", vm_uuid, "error", err)
def get_unique_id(obj): if obj is None: return None if hasattr(obj, "qf_id"): return str(qfurl.qfurl(obj)) if getattr(obj, SERIALIZABLE_ATTRIBUTE, None) is not None: try: return SerializedObject(obj) except pickle.PicklingError, exc: pretty.print_error(__name__, type(exc).__name__, exc) return None
def _get_object_session(): ''' get new session to vm ''' pretty.print_debug(__name__, '_get_object_session start') vbox, session = None, None try: vbox = vboxapi.VirtualBoxManager(None, None) session = vbox.mgr.getSessionObject(vbox.vbox) except Exception as err: pretty.print_error(__name__, 'virtualbox: get session error ', err) pretty.print_debug(__name__, '_get_object_session finished', vbox, session) return vbox, session
def show_url(url): """Open any @url with default viewer""" try: # xdg-open does a better job than gtk.show_uri at choosing my default # web browser, and returns faster than webbrowser.open if re.match(r"\Ahttps?", url): return subprocess.call(['xdg-open', url]) pretty.print_debug(__name__, "show_url", url) return Gtk.show_uri(Gdk.Screen.get_default(), url, Gtk.get_current_event_time()) except GLib.GError as exc: pretty.print_error(__name__, "Gtk.show_uri:", exc)