def __init__(self, path=None): """ Builds a mapping object. Parameters: path - scans the path for building a mapping object if the needed files where found. If None it builds an empty mapping. If some of the needed files wasn't found it tries to build a mapping with the found info. The Mapping.info_filename and Mapping.mapping_filename class attributes marks the requiered filenames for the metadata file and wminput config file respectively. The Mapping.mapping_filename file must contain wminput config file code The Mapping.info_filename follows XDG DesktopEntry syntax. The Mapping.info_filename contains the source of the optional associated icon. If no icon found or no icon directive it falls back to default icon. There are three posibilities for icon setting: - An absolute path where the icon it's stored - Icon filename if it's stored in the same dir as Mapping.info_filename - Theme-icon-name for auto-getting the icon from the icon theme """ self.__path = path # Getting freedesktop definition file self.__info = DesktopEntry() if path and os.path.exists(os.path.join(path, Mapping.info_filename)): self.__info.parse(os.path.join(path, Mapping.info_filename)) else: self.__info.new(self.info_filename) self.__info.set("Type", "Wiican Mapping") # Getting wminput mapping file if path and os.path.exists(os.path.join(path, Mapping.mapping_filename)): mapping_fp = open(os.path.join(path, Mapping.mapping_filename), "r") self.__mapping = mapping_fp.read() mapping_fp.close() else: self.__mapping = "" # Getting icon file path icon_name = self.__info.getIcon() if path and icon_name in os.listdir(path): # Icon included self.set_icon(os.path.join(path, icon_name)) elif getIconPath(icon_name): # Theme icon self.set_icon(getIconPath(icon_name)) else: # Default icon self.set_icon(ICON_DEFAULT)
def _find_icon(self, icon_name, size=128): icon_theme = Gtk.IconTheme.get_default() gtk_icon_info = icon_theme.lookup_icon(icon_name, 128, 0) if gtk_icon_info: icon_path = gtk_icon_info.get_filename() else: icon_path = getIconPath(icon_name, size) if (icon_path and re.match("^.*\.svg$", icon_path)) or not icon_path: gtk_icon_info = icon_theme.lookup_icon("exec", 128, 0) if gtk_icon_info: icon_path = gtk_icon_info.get_filename() else: icon_path = getIconPath(icon_name, size) return Clutter.Texture.new_from_file(icon_path)
def _find_icon(self, icon_name, size = 128): icon_theme = Gtk.IconTheme.get_default() gtk_icon_info = icon_theme.lookup_icon(icon_name, 128, 0) if gtk_icon_info: icon_path = gtk_icon_info.get_filename() else: icon_path = getIconPath(icon_name, size) if (icon_path and re.match("^.*\.svg$", icon_path)) or not icon_path: gtk_icon_info = icon_theme.lookup_icon("exec", 128, 0) if gtk_icon_info: icon_path = gtk_icon_info.get_filename() else: icon_path = getIconPath(icon_name, size) return Clutter.Texture.new_from_file(icon_path)
def get_icon(self, icon_name, icon_size): """Workaround for Qt not implementing a fallback chain in fromTheme""" # Always let the cache service requests first if icon_name in self.icon_cache: return self.icon_cache[icon_name] # Skip right to the fallback if it's None or an empty string if icon_name: # Give Qt the opportunity to make a fool out of itself if os.path.isfile(icon_name): icon = QIcon(icon_name) else: icon = QIcon.fromTheme(icon_name) # Resort to PyXDG to walk the fallback chain properly # TODO: Better resolution handling if not icon or icon.isNull(): icon = QIcon( getIconPath(icon_name, icon_size, theme=QIcon.themeName())) else: icon = None if not icon or icon.isNull(): icon = self.lookup_local(icon_name) # If we still couldn't get a result, retrieve the fallback icon in a # way which will allow a cache entry here without duplication if not icon or icon.isNull() and icon_name != self.fallback_name: icon = self.get_icon(self.fallback_name, icon_size) # Populate the cache icon = self.ensure_icon_size(icon, icon_size) self.icon_cache[icon_name] = icon return icon
def __new__(cls, desk): desk = DesktopEntry(str(a)) name = desk.getName() icon = getIconPath(desk.getIcon()) exe = shlex.split(re.sub('%[fFuUdDnNickvm]', '', desk.getExec())) launch = partial(QProcess.startDetached, exe[0], exe[1:]) return super().__new__(cls, name, icon, launch)
def data(self, index, role): # print("RecollQuery.data: row %d, role: %s" % (index.row(),role)) if not index.isValid(): return None if index.row() < 0: return None if index.row() >= len(self.searchResults): return None d = self.getdoc(index) # d = self.searchResults[index.row()] if role == recollQueryModel.Role_FILE_NAME: return d['filename'] elif role == recollQueryModel.Role_LOCATION: return d['url'] elif role == recollQueryModel.Role_FILE_SIMPLE_CONTENT: # return d['abstract'] if d is None: print("No Doc") return groups = self.query.getgroups() # meths=HlMeths(groups) # tabs=self.query.makedocabstract(d,methods=meths) tabs = self.query.makedocabstract(d) tabs = self.query.highlight(tabs) return tabs elif role == recollQueryModel.Role_FILE_ICON: # icon=d['icon'] desktop = getDesktopFile(d['url']) if desktop is None: return "" icon = desktop.getIcon() path = getIconPath(icon) print("path:", path) # print("path:",path) return path elif role == recollQueryModel.Role_FILE_EXEC: desktop = getDesktopFile(d['url']) if desktop is None: return "" return desktop.getExec().split(" ")[0] elif role == recollQueryModel.Role_DESKTOP_NAME: desktop = getDesktopFile(d['url']) if desktop is None: return "" return desktop.getName() elif role == recollQueryModel.Role_DESKTOP_DESC: desktop = getDesktopFile(d['url']) if desktop is None: return "" desc = desktop.getComment() if len(desc.strip()) == 0: desc = desktop.getGenericName() return desc return ""
def get_icon(self): """ Gets the associated icon. If no icon found or no icon directive it falls back to default icon. """ icon_name = self.__info.getIcon() # Icon included if self.__path and icon_name in os.listdir(self.__path): return os.path.join(self.__path, icon_name) # Theme icon elif getIconPath(icon_name): return getIconPath(icon_name) # Default icon else: return ICON_DEFAULT
def f(): if name is None: return None res = getIconPath(name) logger.debug("Resolving %s: %s", name, "failed" if res is None else "succeeded") return res
def _load_icon_for_mime(self, mimeType): if not hasImageSupport: return None iconPath = getIconPath(mimeType, size=16, theme=session.config.get('iconTheme'), extensions=["png", "xpm"]) if iconPath: iconImage = Image.open(iconPath) return ImageTk.PhotoImage(iconImage) return None
def _get_xdg_icon(self, icon_name): if not has_xdg: return path = getIconPath(icon_name, theme=self.icon_theme, extensions=["png", "svg"]) if not path: return None return Img.from_path(path)
def update_application_colours(executor): base_colour_scheme = load_base_colour_scheme() colour_scheme_futures = {} wmclass_colour_schemes = defaultdict(list) kdeglobals = ConfigParser() kdeglobals.read(os.path.join(xdg_config_home, "kdeglobals")) icon_theme = kdeglobals["Icons"]["Theme"] for wmclass, icon_name in get_wmclass_icons().items(): if icon_name is None: colour_scheme = None else: icon_path = getIconPath(icon_name, theme=icon_theme) if icon_path is None or not os.path.isfile(icon_path): colour_scheme = None else: colour_scheme = get_colour_scheme_name( icon_name.replace(os.sep, "_").replace(".", "_") ) future = executor.submit(get_colours_for_icon, icon_path) colour_scheme_futures[future] = (colour_scheme, icon_path) wmclass_colour_schemes[colour_scheme].append(wmclass) remove_colour_schemes() broken_colour_schemes = {None} new_colour_schemes = [] for future in concurrent.futures.as_completed(colour_scheme_futures): colour_scheme, icon_path = colour_scheme_futures[future] try: icon_colours = future.result() except Exception: logger.exception("Error processing icon: {}".format(icon_path)) broken_colour_schemes.add(colour_scheme) else: new_colour_schemes.append((colour_scheme, icon_colours)) add_colour_schemes(base_colour_scheme, new_colour_schemes) kwin_rule_updates = [] for colour_scheme, wmclasses in wmclass_colour_schemes.items(): if colour_scheme in broken_colour_schemes: colour_scheme = None for wmclass in wmclasses: kwin_rule_updates.append((wmclass, colour_scheme)) update_kwin_rules(sorted(kwin_rule_updates))
def _lookup_icon(self, name): """ Search for the icon corresponding to one command. """ self.icons_files[name] = None # if the software_name is directly an absolute path icon file if os.path.isabs(name): # name start with '/' thus it's an absolute path root, ext = os.path.splitext(name) if ext == '.png': self.icons_files[name] = name if os.path.isfile(name) else None else: # try to add the extension self.icons_files[name] = name + '.png' if os.path.isfile(name + '.png') else None else: self.icons_files[name] = getIconPath(name) # no search method found an icon, so default icon if self.icons_files[name] is None: self.icons_files[name] = self.default_icon
def main(args): args =args[1:] if len(args )!=1: print("takes one argument") return try: desktop =DesktopEntry() desktop.parse(args[0]) except: print("parse error" ,args[0]) name =desktop.getName() name =''.join(lazy_pinyin(name)) AppName=desktop.getName() NoDisplay=False; if len(AppName)==0: AppName=desktop.getGenericName AppComment=desktop.getComment() AppIcon=desktop.getIcon() if not os.path.exists(AppIcon): ip=getIconPath(AppIcon,theme="deepin") # if ip is None: # ip=getIconPath(AppIcon,theme="hicolor") else: ip=AppIcon if ip is None: #TODO add defauult icon ip="test" pass AppIcon=ip NoDisplay=desktop.getNoDisplay() onlydi=desktop.getOnlyShowIn() if NoDisplay is True or len(onlydi)>0: AppIcon="" AppName="" AppComment="" NoDisplay="true" else: NoDisplay="false" print(''' <html><head> <title>''' +name+ '''</title> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8" > <meta name="AppName" content="'''+AppName+'''" /> <meta name="AppComment" content="'''+AppComment+'''" /> <meta name="AppIcon" content="'''+AppIcon+'''" /> <meta name="AppNoDisplay" content="'''+NoDisplay+'''" /> </head> <body> '''+AppName+''' </body> </html> ''')
def test_find_icon_exists(self): print("Finding an icon that probably exists:") print(getIconPath("firefox"))
def test_find_icon_nonexistant(self): icon = getIconPath("oijeorjewrjkngjhbqefew") assert icon is None, "%r is not None" % icon
def get_icon(self, icon): """Return icon filename""" from xdg.IconTheme import getIconPath return getIconPath(icon, theme=self.theme, extensions=["svg"])
# Create application QT and create WebView app = QApplication([]) web = QWebView() # Get current theme command = "kreadconfig --group 'Icons' --key 'Theme'" theme = subprocess.getoutput(command) # Set Title title = _("Kaiana Control Panel") web.setWindowTitle(title) # Set icon icon = QIcon() icon.addFile(getIconPath('preferences-system', theme=theme, size=16), QSize(16,16)) icon.addFile(getIconPath('preferences-system', theme=theme, size=32), QSize(32,32)) icon.addFile(getIconPath('preferences-system', theme=theme, size=64), QSize(64,64)) icon.addFile(getIconPath('preferences-system', theme=theme, size=256), QSize(256,256)) web.setWindowIcon(icon) # Get dimensions from config file config = ConfigParser() configFile = None configFilePath = os.getenv("HOME") + "/.kcenter/conf" width, height = 800, 600 x = y = None if os.path.exists(configFilePath): config.read(configFilePath) width = config.get('window','width') if config.has_option('window','width') else width
from ..util.executables import Roles try: # Python 3.x from configparser import RawConfigParser from configparser import Error as CP_Error # pylint: disable=E0611 except ImportError: # Python 2.x from ConfigParser import RawConfigParser from ConfigParser import Error as CP_Error BACKEND_NAME = "ScummVM" RC_PATH = os.path.expanduser('~/.scummvmrc') # Let this get subbed in elsewhere so our dependency on PyXDG is more decoupled from xdg.IconTheme import getIconPath DEFAULT_ICON = getIconPath("scummvm", 128) log = logging.getLogger(__name__) # TODO: Deduplicate all of this stuff with residualvm.py def _parse_list(args): """Parse C{scummvm --list-targets} for a list of available games""" try: rows = subprocess.check_output(['scummvm'] + args) if isinstance(rows, bytes): rows = rows.decode('utf-8') rows = rows.strip().split('\n')[2:]
from .common import InstalledGameEntry, GameLauncher from ..util.executables import Roles try: # Python 3.x from configparser import RawConfigParser from configparser import Error as CP_Error # pylint: disable=E0611 except ImportError: # Python 2.x from ConfigParser import RawConfigParser from ConfigParser import Error as CP_Error BACKEND_NAME = "ResidualVM" RC_PATH = os.path.expanduser('~/.residualvmrc') # Let this get subbed in elsewhere so our dependency on PyXDG is more decoupled from xdg.IconTheme import getIconPath DEFAULT_ICON = getIconPath("residualvm", 128) log = logging.getLogger(__name__) def _get_games_list(): """Parse C{residualvm --list-targets} for a list of available games""" try: rows = subprocess.check_output(['residualvm', '--list-targets']) if isinstance(rows, bytes): rows = rows.decode('utf-8') rows = rows.strip().split('\n')[2:] return dict(row.split(None, 1) for row in rows) except subprocess.CalledProcessError: log.info("Could not retrieve list of games from ResidualVM")
from .common import InstalledGameEntry, GameLauncher from ..util.executables import Roles try: # Python 3.x from configparser import RawConfigParser from configparser import Error as CP_Error # pylint: disable=E0611 except ImportError: # Python 2.x from ConfigParser import RawConfigParser from ConfigParser import Error as CP_Error BACKEND_NAME = "ScummVM" RC_PATH = os.path.expanduser('~/.scummvmrc') # Let this get subbed in elsewhere so our dependency on PyXDG is more decoupled from xdg.IconTheme import getIconPath DEFAULT_ICON = getIconPath("scummvm", 128) log = logging.getLogger(__name__) # TODO: Deduplicate all of this stuff with residualvm.py def _parse_list(args): """Parse C{scummvm --list-targets} for a list of available games""" try: rows = subprocess.check_output(['scummvm'] + args) if isinstance(rows, bytes): rows = rows.decode('utf-8') rows = rows.strip().split('\n')[2:] result = {}
def get_games(root_folder='Games'): """Retrieve a list of games from the XDG system menus. Written based on this public-domain code: http://mmoeller.fedorapeople.org/icewm/icewm-xdg-menu/icewm-xdg-menu @bug: On *buntu, this code doesn't find games unless you explicitly pass in the appropriate C{root_folder} value. """ results = [] menu = xdg.Menu.parse() if root_folder: menu = menu.getMenu(root_folder) for dentry in _process_menu(menu): if (dentry.getType() != 'Application' or dentry.getNoDisplay() or dentry.getHidden()): # TODO: allow ignoring Hidden? continue # Remove the placeholder tokens used in the Exec key # TODO: Actually sub in things like %i, %c, %k. # XXX: Should I centralize this substitution to allow argument passing? # (eg. for Emulators?) cmd = re.sub('%[a-zA-Z]', '', dentry.getExec()) # TODO: Find a way to hint that one of the copies of this is generated # TODO: Think of a better way to let the frontend ask for a specific # icon size. name = (dentry.getName() or dentry.DesktopFileID).strip() icon = getIconPath((dentry.getIcon() or '').strip(), 128) path = dentry.getPath() # Replicate the findTryExec() method on pre-0.26 PyXDG versions # TODO: Audit uses elsewhere and then guarantee that # GameLauncher.tryexec will be a path or None tryexec = dentry.getTryExec() tryexec = which(tryexec) if tryexec else None # resolve_cmd needed to work around Desura .desktop quoting bug argv = resolve_exec(cmd) base_path = path or os.path.dirname(tryexec or argv[0]) or None if base_path and base_path in COMMON_DIRS: base_path = None # TODO: Rework results.append(InstalledGameEntry( name=name, icon=icon, base_path=base_path, commands=[GameLauncher( argv=argv, provider=BACKEND_NAME, role=Roles.play, name=name, path=path, icon=icon, description=dentry.getComment(), tryexec=tryexec, categories=dentry.getCategories(), keywords=dentry.getKeywords(), use_terminal=dentry.getTerminal()) ])) return results
def test_find_icon_exists(self): print("Finding an icon that probably exists:") print (getIconPath("firefox"))
def get_games(root_folder='Games'): """Retrieve a list of games from the XDG system menus. Written based on this public-domain code: http://mmoeller.fedorapeople.org/icewm/icewm-xdg-menu/icewm-xdg-menu @bug: On *buntu, this code doesn't find games unless you explicitly pass in the appropriate C{root_folder} value. """ results = [] menu = xdg.Menu.parse() if root_folder: menu = menu.getMenu(root_folder) for dentry in _process_menu(menu): if (dentry.getType() != 'Application' or dentry.getNoDisplay() or dentry.getHidden()): # TODO: allow ignoring Hidden? continue # Remove the placeholder tokens used in the Exec key # TODO: Actually sub in things like %i, %c, %k. # XXX: Should I centralize this substitution to allow argument passing? # (eg. for Emulators?) cmd = re.sub('%[a-zA-Z]', '', dentry.getExec()) # TODO: Find a way to hint that one of the copies of this is generated # TODO: Think of a better way to let the frontend ask for a specific # icon size. name = (dentry.getName() or dentry.DesktopFileID).strip() icon = getIconPath((dentry.getIcon() or '').strip(), 128) path = dentry.getPath() # Replicate the findTryExec() method on pre-0.26 PyXDG versions # TODO: Audit uses elsewhere and then guarantee that # GameLauncher.tryexec will be a path or None tryexec = dentry.getTryExec() tryexec = which(tryexec) if tryexec else None # resolve_cmd needed to work around Desura .desktop quoting bug argv = resolve_exec(cmd) base_path = path or os.path.dirname(tryexec or argv[0]) or None if base_path and base_path in COMMON_DIRS: base_path = None # TODO: Rework results.append( InstalledGameEntry(name=name, icon=icon, base_path=base_path, commands=[ GameLauncher( argv=argv, provider=BACKEND_NAME, role=Roles.play, name=name, path=path, icon=icon, description=dentry.getComment(), tryexec=tryexec, categories=dentry.getCategories(), keywords=dentry.getKeywords(), use_terminal=dentry.getTerminal()) ])) return results
# Create application QT and create WebView app = QApplication([]) web = QWebView() # Get current theme command = "kreadconfig --group 'Icons' --key 'Theme'" theme = subprocess.getoutput(command) # Set Title title = _("Kaiana Control Panel") web.setWindowTitle(title) # Set icon icon = QIcon() icon.addFile(getIconPath('preferences-system', theme=theme, size=16), QSize(16, 16)) icon.addFile(getIconPath('preferences-system', theme=theme, size=32), QSize(32, 32)) icon.addFile(getIconPath('preferences-system', theme=theme, size=64), QSize(64, 64)) icon.addFile(getIconPath('preferences-system', theme=theme, size=256), QSize(256, 256)) web.setWindowIcon(icon) # Get dimensions from config file config = ConfigParser() configFile = None configFilePath = os.getenv("HOME") + "/.kcenter/conf" width, height = 800, 600 x = y = None