예제 #1
0
파일: FileUtil.py 프로젝트: kahu/sfbm
def entry_visuals(entry):
    name = entry.getName()
    icon = IconTheme.getIconPath(entry.getIcon(), theme=G.icon_theme)
    icon = QtGui.QIcon(icon) if icon else None
    if (not icon) or icon.isNull():
        icon = None
    return name, icon
예제 #2
0
def init():
    try:
        os.remove('index.html')
    except:
        print("Old Menu file could not be removed")
    menu = open('index.html', 'a')
    menu.write(
        "<head><script src='list.min.js'></script><link rel='stylesheet' type='text/css' href='style.css'><script language='javascript' type='text/javascript'>\n function closeWindow() { window.open('','_parent',''); window.close(); }</script><script language='javascript' type='text/javascript'>function startList() {var options = {valueNames: [ 'name']};var userList = new List('users', options);}</script></head><body onload='startList()'><div id='users'><input class='search' placeholder='Search' /><button class='sort' data-sort='name'>Sort by name</button><ul class='list'>"
    )
    os.chdir('/usr/share/applications')
    id = 0
    for file in glob.glob("*.desktop"):
        entry = entryhandler.DesktopEntry(filename=file)
        apps.append({
            'Name': entry.getName(),
            'Icon': 'system' + str(ic.getIconPath(entry.getIcon())),
            'Exec': 'xiwi ' + entry.getExec().split('%', 1)[0],
            'id': id
        })
        id = id + 1
    for app in apps:
        menu.write(
            "<li><a class='name' href='index.html?id=" + str(app['id']) +
            "' onclick='closeWindow()'><img class='icon' height='48' width='48' src='"
            + app['Icon'] + "'>" + app['Name'] + '</a></li>')
    menu.write('</div></body>')
    menu.close()
예제 #3
0
def get_icon(desktop_entry):
    icon_name = desktop_entry.getIcon()
    if not icon_name:
        return
    else:
        icon_path = IconTheme.getIconPath(icon_name)
        return icon_path
예제 #4
0
파일: config.py 프로젝트: mattab/tomate
    def get_icon_path(self, iconname, size=None, theme=None):
        iconpath = IconTheme.getIconPath(iconname, size, theme, extensions=['png', 'svg', 'xpm'])

        if iconpath is not None:
            return iconpath

        raise EnvironmentError('Icon %s not found!' % iconpath)
예제 #5
0
파일: FileUtil.py 프로젝트: kahu/sfbm
 def icon(self, fi):
     if fi.isDir():
         return QtGui.QIcon.fromTheme("inode-directory")
     mime = Mime.get_type(fi.absoluteFilePath())
     mimestr = str(mime).replace("/", "-")
     icon = G.icon_cache.get(mimestr)
     if icon:
         return icon
     ipath = IconTheme.getIconPath(mimestr, theme=G.icon_theme)
     if not ipath:
         ipath = IconTheme.getIconPath(mime.media + "-x-generic", theme=G.icon_theme)
     qi = QtGui.QIcon(ipath)
     if qi.isNull():
         qi = QtGui.QIcon.fromTheme("text-plain")
     G.icon_cache[mimestr] = qi
     return qi
예제 #6
0
def load_icon_from_theme(icon_name, theme=None):
    if not EXPORT_ICONS or not icon_name:
        return None
    from xdg import IconTheme
    filename = IconTheme.getIconPath(icon_name, theme=theme)
    if not filename:
        return None
    return load_icon_from_file(filename)
예제 #7
0
파일: config.py 프로젝트: sebix/tomate
    def get_icon_path(iconname, size=None, theme=None):
        icon_path = IconTheme.getIconPath(
            iconname, size, theme, extensions=["png", "svg", "xpm"]
        )

        if icon_path is not None:
            return icon_path

        raise EnvironmentError("Icon %s not found!" % icon_path)
예제 #8
0
    def _find_icon(self, icon_name):
        for theme in ICON_THEMES:
            icon = IconTheme.getIconPath(icon_name,
                                         theme=theme,
                                         extensions=['png', 'xpm'])
            if icon:
                return icon

        if not icon:
            return ""
예제 #9
0
 def __init__(self, theme, root, data, size):
     name = IconTheme.getIconPath(data.icon, theme=theme)
     self.photo = PhotoImage(
         data=svg2png(url=name, parent_width=size, parent_height=size))
     self.data = data
     self.view = Button(root,
                        image=self.photo,
                        command=self.data.call,
                        text=data.text,
                        compound="left")
예제 #10
0
def get_icon(icon):
    return  IconTheme.getIconPath("preferences-desktop-%s-symbolic" % (altName.get(icon) or icon), theme=get_selected_theme()) or\
            IconTheme.getIconPath("preferences-system-%s-symbolic" % (altName.get(icon) or icon), theme=get_selected_theme()) or\
            IconTheme.getIconPath("preferences-%s-symbolic" % (altName.get(icon) or icon), theme=get_selected_theme()) or\
            IconTheme.getIconPath("system-%s-symbolic" % (altName.get(icon) or icon), theme=get_selected_theme()) or\
            IconTheme.getIconPath("gnome-%s-symbolic" % (altName.get(icon) or icon), theme=get_selected_theme()) or\
            IconTheme.getIconPath("%s-symbolic" % (altName.get(icon) or icon), theme=get_selected_theme()) or\
            IconTheme.getIconPath(altName.get(icon) or icon, theme=get_selected_theme()) or\
            'images/{}.svg'.format(icon)
예제 #11
0
    def icon_path(self, iconname, size=None, theme=None):
        icon_path = IconTheme.getIconPath(iconname,
                                          size,
                                          theme,
                                          extensions=["png", "svg", "xpm"])

        icon_path = 'data/icons/hicolor/256x256/apps/focusyn.png'
        if icon_path is not None:
            return icon_path

        raise EnvironmentError("Icon '%s' not found!" % iconname)
예제 #12
0
 def _getItemInfo(self, desktopEntryPath, compiledRegexp):
     desktopEntry = DesktopEntry.DesktopEntry(desktopEntryPath)
     execCommand = desktopEntry.getExec()
     matchResult = re.match(compiledRegexp, execCommand)
     execCommand = execCommand if matchResult is None else matchResult.groups()[0]
     return {
         'categories': desktopEntry.getCategories(),
         'name': desktopEntry.getName(),
         'exec': execCommand,
         'iconPath': IconTheme.getIconPath(desktopEntry.getIcon(), 32, Config.icon_theme)
     }
예제 #13
0
    def __init__(self, filename, urls):
        self.filename = filename
        self.urls = urls
        self.entry = DesktopEntry.DesktopEntry(filename)
        icon_name = self.entry.getIcon()
        self.icon_path = None
        if not icon_name is None:
            self.icon_path = IconTheme.getIconPath(icon_name)
        self.tooltip = "\n".join([self.entry.getName(),self.entry.getComment()])
        self.short_name = self.entry.getName()

        actions = self.entry.get("Actions",group="Desktop Entry", type="string", list=True)

        self.btn = [self.build_btn(None)] + [self.build_btn(a) for a in actions]
예제 #14
0
	def getIconPath(self, iconName :str):
		if self.isThemeAvailable():
			if (QIcon.hasThemeIcon()):
				return QIcon.fromTheme(iconName)
		if self.isDesktopGnomish():
			from gi.repository.Gtk import IconTheme
			icon_theme = IconTheme.get_default()
			icon_info = icon_theme.lookup_icon(iconName, 48, 0)
			if icon_info is not None:
				return icon_info.get_filename()
		icon = xdg.IconTheme.getIconPath(iconName)
		if icon is not None:
			return icon
		else:
			return xdg.IconTheme.getIconPath("applications-other")
예제 #15
0
 def getIconPath(self, iconName: str):
     if self.isThemeAvailable():
         if (QIcon.hasThemeIcon()):
             return QIcon.fromTheme(iconName)
     if self.isDesktopGnomish():
         from gi.repository.Gtk import IconTheme
         icon_theme = IconTheme.get_default()
         icon_info = icon_theme.lookup_icon(iconName, 48, 0)
         if icon_info is not None:
             return icon_info.get_filename()
     icon = xdg.IconTheme.getIconPath(iconName)
     if icon is not None:
         return icon
     else:
         return xdg.IconTheme.getIconPath("applications-other")
예제 #16
0
    def _add_theme(self, name):
        for theme_path in self.theme_paths:
            theme_file = os.path.join(theme_path, name, "index.theme")
            if os.path.isfile(theme_file):
                theme = IconTheme.IconTheme()
                theme.parse(theme_file)
                theme_dirs = []
                for dir in theme.getDirectories():
                    abs_dir = os.path.join(theme_path, theme.name, dir)
                    if os.path.isdir(abs_dir):
                        theme_dirs.append(
                            (abs_dir, theme.getType(dir) == "Scalable"))
                if theme_dirs:
                    self._theme_dirs.append(theme_dirs)

                for subtheme in theme.getInherits():
                    self._add_theme(subtheme)
예제 #17
0
 def create_menu_item(self, entry):    
     icon = entry.get_icon()
     name = entry.get_name()
     dpath = entry.get_desktop_file_path()
     menu_item = []
     if (icon):
         menu_item.append(name)
         icon_path = xdgicon.getIconPath(icon)
         if icon_path:
         	menu_item.append(icon_path)
         else:
         	menu_item.append(icon)
     else:
     	menu_item.append(name)
     if entry.get_type() ==  gmenu.TYPE_ENTRY:
         menu_item.append(dpath)
     return menu_item
예제 #18
0
def find_theme_icon(*names):
    if not LOAD_FROM_THEME:
        return None
    global IconTheme, Config, themes
    if not (IconTheme and Config and themes):
        return None
    size = Config.icon_size
    #log.info("IconTheme.LookupIcon%s", (icon_name, size, themes.keys(), ("png", "svg", "xpm")))
    for name in names:
        for theme in themes.values():
            fn = IconTheme.LookupIcon(name,
                                      size,
                                      theme=theme,
                                      extensions=EXTENSIONS)
            if fn and os.path.exists(fn):
                return fn
    return None
예제 #19
0
def init():
	try:
		os.remove('index.html')
	except:
		print("Old Menu file could not be removed")
	menu = open('index.html', 'a')
	menu.write("<head><script src='list.min.js'></script><link rel='stylesheet' type='text/css' href='style.css'><script language='javascript' type='text/javascript'>\n function closeWindow() { window.open('','_parent',''); window.close(); }</script><script language='javascript' type='text/javascript'>function startList() {var options = {valueNames: [ 'name']};var userList = new List('users', options);}</script></head><body onload='startList()'><div id='users'><input class='search' placeholder='Search' /><button class='sort' data-sort='name'>Sort by name</button><ul class='list'>")
	os.chdir('/usr/share/applications')
	id=0
	for file in glob.glob("*.desktop"):
		entry=entryhandler.DesktopEntry(filename=file)
		apps.append({'Name': entry.getName(), 'Icon':'system' + str(ic.getIconPath(entry.getIcon())), 'Exec':'xiwi '+entry.getExec().split('%',1)[0], 'id':id})				
		id=id+1
	for app in apps:
		menu.write("<li><a class='name' href='index.html?id=" + str(app['id']) + "' onclick='closeWindow()'><img class='icon' height='48' width='48' src='" + app['Icon'] + "'>" +app['Name'] + '</a></li>')
	menu.write('</div></body>')
	menu.close()
예제 #20
0
#! /usr/bin/env python3
# Configuration happens here
icontheme = 'gnome'
# End of Configuration
import os
import sys
import glob
import http.server
import socketserver
import logging
import cgi
from urllib.parse import urlparse
import xdg.DesktopEntry as entryhandler
import xdg.IconTheme as ic
workingdirectory = os.getcwd()
i = ic.IconTheme()
i.parse('/usr/share/icons/gnome/index.theme')
if not os.path.exists('system'):
    os.symlink("/", "system")
apps = []


def init():
    try:
        os.remove('index.html')
    except:
        print("Old Menu file could not be removed")
    menu = open('index.html', 'a')
    menu.write(
        "<head><script src='list.min.js'></script><link rel='stylesheet' type='text/css' href='style.css'><script language='javascript' type='text/javascript'>\n function closeWindow() { window.open('','_parent',''); window.close(); }</script><script language='javascript' type='text/javascript'>function startList() {var options = {valueNames: [ 'name']};var userList = new List('users', options);}</script></head><body onload='startList()'><div id='users'><input class='search' placeholder='Search' /><button class='sort' data-sort='name'>Sort by name</button><ul class='list'>"
    )
예제 #21
0
def findIconFromName1(name):
    def err(name):
        print """ICON NOT FOUND {name} PLEASE CHECK. USING DEFAULT ICON """.format(
            **locals())

    #do this here for quick
    #IF NONE GIVEN OR WHATEVER, RETURN DEFAULT ICON
    if name == '' or name == None:
        err(name)
        return Globals.defaultxpm
    basedirs = ['/usr/share/icons/elementary-xfce',
                '/usr/share/icons']  #xpmdir only for system xpms.
    #basedirs=['/usr/share/icons']
    extensions = ['png', 'xpm']

    #IF FULL PATH GIVEN
    if not os.path.basename(name) == name:
        #first check if nonfullpath is in cache
        basenameext = os.path.basename(name)
        basename, file_extension = os.path.splitext(basenameext)
        for e in extensions:
            fullname = os.path.join(Globals.cache, basename + '.' + e)
            if os.path.isfile(fullname):
                #print 'icon with substituted extension found in cache'
                return fullname
        #if not, get the icon
        if os.path.isfile(name):
            #todo
            #print 'full icon path found, using and copy to cache'
            print '1'
            copyToCacheAndGenCdeIcon(name)
            return name
        else:
            #'print full icon path not found, use default'
            err(name)
            return Globals.defaultxpm

    #NO PATH GIVEN...
    #print 'icon no path given'
    basename, file_extension = os.path.splitext(name)
    #if has extension, first only check if exist in cache (mmaybe if has full path always only check if exist)
    if file_extension:
        #print 'icon has extension'
        fullname = os.path.join(Globals.cache, basename)
        if os.path.isfile(fullname):
            #print 'icon with extension found in cache'
            return fullname

    #if no extension first check if exist in cache with .png or .xpmhmm or assume .png?
    #print 'icon has no extension'
    for e in extensions:
        fullname = os.path.join(Globals.cache, basename + '.' + e)
        if os.path.isfile(fullname):
            #print 'icon with substituted extension found in cache'
            return fullname

    print 'LOOKING FOR ICONS (No icon in cache)'

    #search my own icons first,
    print 'trying cdepanel/xpm'
    b = Globals.xpmdir
    for e in extensions:
        #mayb use 'basename' here (de-extensioned version of name)
        #always QUOTE globs in 'find' statements WHY!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        cmd = ("""find {b} -name "{basename}*" -print|grep {e}""".format(
            **locals()))
        out = subprocess.Popen(cmd,
                               shell=True,
                               stdin=subprocess.PIPE,
                               stdout=subprocess.PIPE,
                               stderr=subprocess.PIPE)
        (stdout, stderr) = out.communicate()
        #print stdout
        if stdout:
            l = stdout.splitlines()
            c = Globals.cache
            #todo make a cache dir for this
            copyToCache(l[0])
            #cmd=("""cp {l[0]} {c} """.format(**locals()))
            #out = subprocess.Popen(cmd,shell=True,stdin=subprocess.PIPE, stdout=subprocess.PIPE,stderr=subprocess.PIPE)
            #(stdout, stderr) = out.communicate()
            return l[0]

    #try try
    if QtGui.QIcon.hasThemeIcon(basename):
        icon = QtGui.QIcon.fromTheme(basename)
        pixmap = icon.pixmap(48, 48)
        filename = '/tmp/' + basename + '.png'
        pixmap.save(filename)
        copyToCacheAndGenCdeIcon(filename)
        return filename

    #try this.. Does this work... maybe
    print 'trying xdg icon'
    xdgicon = IconTheme.getIconPath(basename, 48)
    if xdgicon:
        if os.path.isfile(xdgicon):
            print '2'
            copyToCacheAndGenCdeIcon(xdgicon)
            return xdgicon

    #when swithing to some gtk themes, this makes the app crash for some reason
    #try that....any one will do just find it
    #print 'trying gnome icon'
    #icon_theme = gtk.icon_theme_get_default()
    #icon_info = icon_theme.lookup_icon(basename, 48, 0)
    #if icon_info:
    #gtkicon=icon_info.get_filename()
    #if gtkicon:
    #copyToCacheAndGenCdeIcon(gtkicon)
    #if os.path.isfile(gtkicon):return gtkicon

    #more extensive search and copy to cache if found
    #add check exist
    #note if search 'xterm' can come up with 'xterm-color' eg but then in cache end up: 'xterm-color'
    #and is not found in cach next time because look for cache/xterm so yes.. change
    #search for big enough
    print 'more extensive search'
    print name
    for b in basedirs:
        for e in extensions:
            #mayb use 'basename' here (de-extensioned version of name)
            #always QUOTE globs in 'find' statements WHY!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
            cmd = (
                """find {b} -name "{basename}*" -print|grep -E '48x48'|grep {e}"""
                .format(**locals()))
            out = subprocess.Popen(cmd,
                                   shell=True,
                                   stdin=subprocess.PIPE,
                                   stdout=subprocess.PIPE,
                                   stderr=subprocess.PIPE)
            (stdout, stderr) = out.communicate()
            #print stdout
            if stdout:
                l = stdout.splitlines()
                c = Globals.cache
                #todo make a cache dir for this
                print '3'
                copyToCacheAndGenCdeIcon(l[0])
                #copyToCacheAndGenCdeIcon(l[0])
                #cmd=("""cp {l[0]} {c} """.format(**locals()))
                #out = subprocess.Popen(cmd,shell=True,stdin=subprocess.PIPE, stdout=subprocess.PIPE,stderr=subprocess.PIPE)
                #(stdout, stderr) = out.communicate()
                return l[0]

    #search everything. maybe step through result with 'identify' later
    if which('locate'):
        for e in extensions:
            cmd = ("""locate {basename}|grep icon|grep {e}""".format(
                **locals()))
            out = subprocess.Popen(cmd,
                                   shell=True,
                                   stdin=subprocess.PIPE,
                                   stdout=subprocess.PIPE,
                                   stderr=subprocess.PIPE)
            (stdout, stderr) = out.communicate()
            if stdout:
                l = stdout.splitlines()
                c = Globals.cache
                #this search original eg 'xterm' couldnt be found, so maybe chooses 'xterm-color.png'
                #so for quick, make copy of that with name xterm in cache
                #or make cache 'xterm_alt.png' and then check next time also for filname'_alt' or something
                #.... later later leave for now
                print """ICON {name} NOT FOUND SO USING ALTERNATIVE {l[0]} INSTEAD. PLS CHECK """.format(
                    **locals())
                print '4'
                copyToCacheAndGenCdeIcon(l[0])
                #cmd=("""cp {l[0]} {c} """.format(**locals()))
                #out = subprocess.Popen(cmd,shell=True,stdin=subprocess.PIPE, stdout=subprocess.PIPE,stderr=subprocess.PIPE)
                #(stdout, stderr) = out.communicate()
                return l[0]

    err(name)
    return Globals.defaultxpm
예제 #22
0
 def ftv(self, event):
     #
     self.fempty_widgets()
     #
     item = self.tv.selection()[0]
     # the tags
     item_tags = self.tv.item(item,"tags")
     # E is for entry - C is for category
     if item_tags[1] == 'E':
         entry = DesktopEntry.DesktopEntry(item_tags[0])
         # name
         self.pname_lbl.configure(text=entry.getName())
         # generic name
         self.generic_name_lbl.configure(text=entry.getGenericName())
         # comment
         self.comment_lbl.configure(text=entry.getComment())
         # image
         img = entry.getIcon()
         # the path of the icona - only png of the hicolor theme
         img_path = IconTheme.getIconPath(img)
         
         try:
             if img_path:
                 self.iimage = tk.PhotoImage(file=img_path)
             else:
                 self.iimage = tk.PhotoImage(file="ag.png")
         except:
             self.iimage = tk.PhotoImage(file="ag.png")
         self.image_lbl.configure(image=self.iimage)
         # command
         self.exec_lbl2.configure(text=entry.getExec())
         # tryexec
         self.tryexec_lbl2.configure(text=entry.getTryExec())
         # categories
         self.categories_cb2.configure(values=entry.getCategories())
         try:
             self.categories_cb2.current(0)
         except:
             pass
         # mimetypes
         self.mime_cb2.configure(values=entry.getMimeTypes())
         try:
             self.mime_cb2.current(0)
         except:
             pass
         # keywords
         self.keywords_cb2.configure(values=self.ffind_action(item_tags[0], "Keywords"))
         try:
             self.keywords_cb2.current(0)
         except:
             pass
         # URL
         self.url_lbl2.configure(text=entry.getURL())
         # Path
         self.path_lbl2.configure(text=entry.getPath())
         ##### options
         # terminal
         self.terminal_lbl2.configure(text=self.fbool(entry.getTerminal()))
         # hidden
         self.hidden_lbl2.configure(text=self.fbool(entry.getHidden()))
         # nodisplay
         self.nodisplay_lbl2.configure(text=self.fbool(entry.getNoDisplay()))
예제 #23
0
 def _getQIcon(self, icon_name):
     # Returns a QICon object from the icon name.
     icon_path = IconTheme.getIconPath(icon_name)
     if icon_path is None:
         icon_path = DEFAULT_APP_ICON
     return QIcon(icon_path)
예제 #24
0
def parseMenu(menu, menuJSON):
    for submenu in menu.Entries:
      if isinstance(submenu, Menu):
          newmenu=parseMenu(submenu, []);
          #print ("Submenu icon: "+submenu.getIcon() + " is "+theme.getIconPath(submenu.getIcon()))
          iconpath=theme.getIconPath(submenu.getIcon(), None, 'Numix-Circle')
          #iconpath=theme.getIconPath(submenu.getIcon(), 128, 'future-green')
          #iconpath=theme.getIconPath(submenu.getIcon(), 128, 'Numix-Circle')
          iconpath=give_me_png(iconpath)
          
          if iconpath==None:
              iconpath=''
          print "cat icon: "+submenu.getIcon()+" is "+iconpath
          menuJSON.append({"id": unicode(submenu).replace(" ", "_"), "name":submenu.getName(), "icon":iconpath, "children":newmenu});

      elif isinstance(submenu, MenuEntry):
          # Description at
          # http://pyxdg.readthedocs.org/en/latest/_modules/xdg/DesktopEntry.html
          newitem={}
          
          filename="/usr/share/applications/"+unicode(submenu);
          item=False
          if (os.path.isfile(filename)):
            item=DesktopEntry(filename)
          else:
            # is kde4- prexifed?
            if (unicode(submenu)[0:5]=="kde4-"):
              filename="/usr/share/applications/kde4/"+unicode(submenu)[5:];
              item=DesktopEntry(filename)
            
          #print "!!"+item;
          if item is not False:
         
            newitem["id"]=unicode(submenu).replace(" ", "_")
            newitem["name"]=item.getName()
            #newitem["icon"]=item.getIcon()
            
            newitem["comment"]=item.getComment()
            newitem["tryexec"]=item.getTryExec()
            newitem["exec"]=item.getExec()
            newitem["path"]=item.getPath()
            iconpath=theme.getIconPath(item.getIcon(), 128, 'Numix-Circle')
            #iconpath=theme.getIconPath(item.getIcon(), 128, 'future-green')
            
            #iconname=item.getIcon();    # Convert png if not exists...
            #iconpath=give_me_png(iconname);
            iconpath=give_me_png(iconpath);
            
            
            if iconpath==None:
                iconpath=''
            #print "icon: "+item.getIcon()+" is "+iconpath
            #print ("Icon: "+item.getIcon() + " is "+iconpath)
            newitem["icon"]=iconpath
            #newitem["name"]=a.getName();
            #newitem["id"]=unicode(submenu)
  
            # Only Append if it's executable
  
            #if (item.findTryExec()):
            #     menuJSON.append(newitem);
            #if newitem["name"]!="":
            menuJSON.append(newitem);
          

    return menuJSON
예제 #25
0
#!/usr/bin/env python2
import sys
import Xlib.display
import xdg.IconTheme as ic

winid = sys.argv[1]
dpy = Xlib.display.Display()
win = dpy.create_resource_object('window', int(sys.argv[1], 0))
NET_WM_NAME = dpy.intern_atom('_NET_WM_NAME')
UTF8_STRING = dpy.intern_atom('UTF8_STRING')

iconName = win.get_wm_class()[1].lower()
iconPath = ic.getIconPath(iconName, 16)
title = win.get_full_property(NET_WM_NAME, UTF8_STRING).value

print '{0},{1},{2}'.format(winid, iconPath, title)
예제 #26
0
#!/usr/bin/python
from xdg.IconTheme import *

print getIconPath("opera")

theme = IconTheme()
theme.parse("/usr/kde/3.4/share/icons/hicolor/index.desktop")
theme.validate()
예제 #27
0
	def __init__(self):
		self.action = {}
		apps_dir = '/usr/share/applications/'

		if not os.path.exists('system'):
			os.symlink("/", "system")

		iconthemes = ['Humanity', 'breeze', 'gnome']
		for icontheme in iconthemes:
			icontheme_path = '/usr/share/icons/{}/index.theme'.format(icontheme)
			if os.path.isfile(icontheme_path):
				break
		self.icons = ic.IconTheme()
		self.icons.parse(icontheme_path)


		#Read deskto files
		files =  glob.glob(apps_dir+"*.desktop")
		entrys = [entryhandler.DesktopEntry(filename=file) for file in files]
		entrys = sorted(entrys, key = lambda e: e.getName().lower())
		id=0
		executables = ["/bin/htop",'"/usr/NX/bin/nxplayer" --recording','"/usr/NX/bin/nxplayer" --session']
		names = ['NoMachine Service']
		for entry in entrys:
			name =  entry.getName()
			#print(name)
			iconPath = str(ic.getIconPath(entry.getIcon()))
			executable = entry.getExec().split('%',1)[0]
			added = executable in executables or name in names
			try:
				isTerminal = entry.content['Desktop Entry']['Terminal'] == 'true'
			except:
				isTerminal = False
			try:
				nodisplay = entry.content['Desktop Entry']['NoDisplay'] == 'true'
			except:
				nodisplay = False
			try:
				categories = entry.content['Desktop Entry']['Categories']
				fobiden_cat = bool(re.search('Settings|System',categories))
			except:
				fobiden_cat = False
			if None != iconPath and bool(re.search("png$|svg$",iconPath)) and \
					not bool(re.search("sbin|pkexec|^none", entry.getExec())) and \
					not isTerminal and \
					not nodisplay and not added and not fobiden_cat:
				self.action[str(id)] = {'Name':name,
									  'Icon':'system' + iconPath,
									  'Exec': executable,
									  'id':str(id),
									  'type': 'app'}
				executables = executables + [executable]
				names = names + [name]
				id = id + 1

		html_items = ""
		#Create HTML
		for app in range(id):
			app = self.action[str(app)]
			html_items = html_items + \
				"<li class ='list-group-item' > " \
				"<a class ='name' href='index.html?id={id}' onclick='closeWindow()' run='{Exec}'> " \
				"<img class ='icon' height='32' width='32' src='{Icon}' >" \
				"{Name}" \
				"</a></li> \n".format_map(app)

		html_items = html_items + '<li class="list-group-item">' \
								  "<a class ='name' href='index.html?id=startx' onclick='closeWindow()'> " \
								  "<img class ='icon' height='32' width='32' src='desktop.png' >" \
								  "Launch Desktop " \
								  "</a></li>\n"
		html_items = html_items + '<li class="list-group-item" data-toggle="modal" data-target="#optionModal">Options</li>\n'

		self.action['tabMode'] = {'type': 'param',
								  'attr': 'newAppMode',
								  'val':'tabMode'}
		self.action['winMode'] = {'type': 'param',
								  'attr': 'newAppMode',
								  'val':'winMode'}
		self.action['kde'] = {'type': 'param',
								  'attr': 'desktop',
								  'val':'startkde -X xiwi'}
		self.action['xfce4'] = {'type': 'param',
								  'attr': 'desktop',
								  'val':'startxfce4 -X xiwi'}
		self.action['gnome'] = {'type': 'param',
								  'attr': 'desktop',
								  'val':'startgnome -X xiwi'}
		self.action['startx'] = {'type': 'startx'}

		with open('index_template.html','r') as t:
			template = t.readlines()

		for n in range(len(template)):
			if(template[n] == '@apps@\n'):
				template[n] = html_items

		try:
			os.remove('index.html')
		except:
			print("Old Menu file could not be removed")

		with open('index.html','w+') as i:
			for t in template:
				i.write(t)
예제 #28
0
				_exec_args = shlex.split(entry.getExec())
				for arg in _exec_args:
					if arg != "%u": execlist.append(arg)
			except:
				pass
			finally:
				break
except:
	pass

for i in desktop_list:
	x = os.path.join(dirpath,tree[2],i)
	if os.access(x,os.R_OK):
		try:
			entry.parse(x)
			icon_name = IconTheme.getIconPath(entry.getIcon())
			print icon_name
			if os.access(icon_name,os.R_OK):
				print "Readable."
				icon = open(icon_name,'r')
				print icon
			elif os.access(os.path.join(dirpath,tree[2],icon_name)):
				icon = open(os.path.join(dirpath,tree[2],icon_name))
		except:
			pass
		finally:
			break

# CREATE RUNSCRIPT
try:
	handle = open(os.path.join(os.path.join(dirpath,tree[0]),"Run"),'w')