Exemplo n.º 1
0
 def on_checkautostart_toggled(self, widget):
     KUPFER_DESKTOP = "kupfer.desktop"
     AUTOSTART_KEY = "X-GNOME-Autostart-enabled"
     autostart_dir = base.save_config_path("autostart")
     autostart_file = os.path.join(autostart_dir, KUPFER_DESKTOP)
     if not os.path.exists(autostart_file):
         desktop_files = list(
             base.load_data_paths("applications", KUPFER_DESKTOP))
         if not desktop_files:
             self.output_error("Installed kupfer desktop file not found!")
             return
         desktop_file_path = desktop_files[0]
         # Read installed file and modify it
         dfile = desktop.DesktopEntry(desktop_file_path)
         executable = dfile.getExec()
         ## append no-splash
         if "--no-splash" not in executable:
             executable += " --no-splash"
         dfile.set("Exec", executable)
     else:
         dfile = desktop.DesktopEntry(autostart_file)
     activestr = str(bool(widget.get_active())).lower()
     self.output_debug("Setting autostart to", activestr)
     dfile.set(AUTOSTART_KEY, activestr)
     ## remove the format specifiers
     executable = dfile.getExec().replace("%F", "")
     dfile.set("Exec", executable)
     dfile.write(filename=autostart_file)
Exemplo n.º 2
0
def parse_menu (menu, fvwm_menu = None):
    ''' parse menu file '''
    prefix = "+"
    if fvwm_menu == None:
        print ''
        print 'DestroyMenu "%s"' % menu
        print 'AddToMenu "%s"' % menu
    else:
        print 'DestroyMenu recreate %s' % fvwm_menu
        prefix = "AddToMenu %s" % fvwm_menu

    for entry in menu.getEntries():
	if isinstance(entry, xdg.Menu.Menu):
            icon = entry.getIcon()
            print u'%s "%s%%menu/folder.png%%" Popup "%s"' % (prefix, entry.getName(), entry)
	elif isinstance(entry, xdg.Menu.MenuEntry):
            desktop = DesktopEntry(entry.DesktopEntry.getFileName())
            icon = desktop.getIcon()
            ind = icon.rfind('.')
            if ind != -1:
                icon = icon[0:ind]
            cmd = desktop.getExec().rstrip('%FUfu')
            cache_icon(icon)
            print u'%s "%s%%menu/%s.png%%" Exec exec %s' % (prefix, desktop.getName(), os.path.basename(icon), cmd)
	else:
	    pass

    for entry in menu.getEntries():
	if isinstance(entry, xdg.Menu.Menu):
	    parse_menu(entry)
Exemplo n.º 3
0
def parse_menu(menu, fvwm_menu=None):
    """ parse menu file """
    prefix = "+"
    if fvwm_menu == None:
        print ""
        print 'DestroyMenu "%s"' % menu
        print 'AddToMenu "%s"' % menu
    else:
        print "DestroyMenu recreate %s" % fvwm_menu
        prefix = "AddToMenu %s" % fvwm_menu

    for entry in menu.getEntries():
        if isinstance(entry, xdg.Menu.Menu):
            icon = entry.getIcon()
            print u'%s "%s%%menu/folder.png%%" Popup "%s"' % (prefix, entry.getName(), entry)
        elif isinstance(entry, xdg.Menu.MenuEntry):
            desktop = DesktopEntry(entry.DesktopEntry.getFileName())
            icon = desktop.getIcon()
            ind = icon.rfind(".")
            if ind != -1:
                icon = icon[0:ind]
            cmd = desktop.getExec().rstrip("%FUfu")
            cache_icon(icon)
            print u'%s "%s%%menu/%s.png%%" Exec exec %s' % (prefix, desktop.getName(), os.path.basename(icon), cmd)
        else:
            pass

    for entry in menu.getEntries():
        if isinstance(entry, xdg.Menu.Menu):
            parse_menu(entry)
    def get_actor_desktop_file(self, actor=None):
        """
        Finds a desktop file for a actor
        """
        
        if actor is None:
            actor = self.event.actor
        
        desktop_file = None
        if actor in common.DESKTOP_FILES:
            return common.DESKTOP_FILES[actor]
        path = None
        for desktop_path in common.DESKTOP_FILE_PATHS:
            if os.path.exists(actor.replace("application://", desktop_path)):
                path = actor.replace("application://", desktop_path)
                break
        if path:
            desktop_file = DesktopEntry.DesktopEntry(path)
        else:
            actor_name = actor.replace("application://", "").replace(".desktop", "")
            for desktop_path in common.DESKTOP_FILE_PATHS:
                for file in glob.glob(desktop_path+'*.desktop'):
                    try:
                        with open(file) as f:
                            contents = f.read()
                        if 'TryExec='+actor_name in contents or 'Exec='+actor_name in contents:
                            desktop_file = DesktopEntry.DesktopEntry(file)
                            common.DESKTOP_FILES[actor] = desktop_file
                            return desktop_file
                    except IOError:
                        pass

        common.DESKTOP_FILES[actor] = desktop_file
        return desktop_file
Exemplo n.º 5
0
def parse_qlaunch():
    ''' parse recently opened files '''
    for f in sorted(glob("%s/ydesk/qlaunch/*.desktop" % xdg_data_home)):
        if f.endswith(".desktop"):
            desktop = DesktopEntry(f)
            icon = desktop.getIcon()
            cache_icon(icon)
            cmd = desktop.getExec().rstrip('%FUfu')
            print('+ "%s%%%s.png%%" Exec exec %s' %
                  (desktop.getName(), os.path.basename(icon), cmd))
Exemplo n.º 6
0
def main():
    desktops = []   # init empty list
# List of the categories we are interested in
    categories = ['Network' , 'Office', 'System', 'Development', 'Game',
                  'AudioVideo', 'Graphics', 'Settings']
    categories.sort()
    path = '/usr/share/applications/'
    files = os.listdir(path)
    # Init our config object
    for file in files:
        if fnmatch(file, '*.desktop'):
            entry = DesktopEntry(os.path.join(path, file))
            desktops.append(entry)

    for category in categories:
        print('my' + category + ' = { ')
        for entry in desktops:
            if category in entry.getCategories():
                if getIconPath(entry.getIcon()) and not (fnmatch(getIconPath(entry.getIcon()), '*.ico') or fnmatch(getIconPath(entry.getIcon()), '*.svg')):      # awesome fails with ico/svg
                    print('  { "' + entry.getName() + '", "' + entry.getExec() + '", "' +
                        getIconPath(entry.getIcon()) + '" },')
                else:
                    print('  { "' + entry.getName() + '", "' + entry.getExec() + '" },')
        print('}\n')

    print('myprogmenu {')
    for category in categories:
        print('  { "' + category + '", my' + category + ' },')
    print('}\n')

    return 0
Exemplo n.º 7
0
def info(filter_):
    global APPS
    appList = []
    a = False
    all_apps = glob.glob("/usr/share/applications/*.desktop")
    for a in glob.glob("/usr/share/applications/kde4/*.desktop"):
        all_apps.append(a)
    for a in glob.glob("{}/.local/share/applications/*.desktop".format(
            os.path.expanduser("~"))):
        all_apps.append(a)
    for f in all_apps:
        try:
            if filter_ != "" and filter_.lower() in str(
                    _d.DesktopEntry(unicode(f)).getName()).lower():
                show = True
            elif filter_ == '':
                show = True
            else:
                show = False
            showTerminal = _d.DesktopEntry(unicode(f)).getTerminal()
            dNotShowIn = _d.DesktopEntry(unicode(f)).getNotShowIn()
            dNoDisplay = _d.DesktopEntry(unicode(f)).getNoDisplay()
            dHidden = _d.DesktopEntry(unicode(f)).getHidden()
            dType = _d.DesktopEntry(unicode(f)).getType()
            if dNoDisplay == False and dHidden == False and dType == "Application" and show == True and os.environ.get(
                    "XDG_CURRENT_DESKTOP") not in dNotShowIn:
                app = {}
                OnlyShowIn = _d.DesktopEntry(unicode(f)).getOnlyShowIn()
                current_desk = os.environ.get('XDG_CURRENT_DESKTOP')
                if len(OnlyShowIn) == 0 or current_desk in OnlyShowIn:
                    app["name"] = str(_d.DesktopEntry(unicode(f)).getName())
                    e = str(_d.DesktopEntry(unicode(f)).getExec())

                    #prevent '"' in exec
                    if e[0] == '"' and e[-1] == '"':
                        e = e[:-1][1:]
                    try:
                        pos = e.index("%")
                        e = e[:pos - 1]
                    except ValueError:
                        pass
                    if showTerminal == True:
                        app["exec"] = "xterm -e {}".format(e)
                    else:
                        app["exec"] = e
                    app["icon"] = ico_from_name(
                        str(_d.DesktopEntry(unicode(f)).getIcon()))
                    appList.append(app)
        except:
            pass
    return sorted(appList, key=lambda x: x["name"])
    APPS = sorted(appList, key=lambda x: x["name"])
Exemplo n.º 8
0
	def checkfiles(self, path):
		if os.path.isdir(path):
			ls = os.listdir(path)
			for file in ls:
				self.checkfiles(os.path.join(path, file))
		else:
			entry = DesktopEntry()
			try:
				entry.parse(path)
			except ParsingError, e:
				print "Parsing error: " + str(e)
				return

			category = entry.getCategories()

			if (len(category) < 2) or (category[0] <> self.category1) or (category[1] <> self.category2):
				return

			entry.name = entry.getName()
			entry.default_status = ""
			entry.after_animate_click = self.after_animate_click

			#debug("xdesktop file found: " + entry.name)
			#debug("category: " + str(entry.getCategories()))

			self.found_files.append(entry)
Exemplo n.º 9
0
    def __getDesktopFile(desktopid: str):
        """Get a .desktop file from the desktop cache for a given desktopid."""
        finalid = None
        if not Application.desktopCache.get(desktopid):
            de = DesktopEntry.DesktopEntry()
            for path in DESKTOPPATHS:
                if not desktopid.endswith(".desktop"):
                    depath = os.path.realpath(path + desktopid + ".desktop")
                else:
                    depath = os.path.realpath(path + desktopid)
                try:
                    de.parse(depath)
                except (DesktopEntry.ParsingError) as e:
                    pass
                else:
                    res = Application.desktopre.match(depath)
                    try:
                        finalid = res.groups()[0].lower()
                    except (ValueError, KeyError) as e:
                        finalid = depath.lower()
                    break

            Application.desktopCache[finalid] = (finalid, de)
            return (finalid, de)

        return Application.desktopCache.get(desktopid)
Exemplo n.º 10
0
def execFromDesktopentrypath (desktopentrypath):
    d=DesktopEntry.DesktopEntry(desktopentrypath)
    getexec=d.getExec()#all kind of junk..?: 'set BLABLA command %f %Bla'
    getexec=os.path.basename(getexec)
    getexec1=re.sub('%.*','',getexec) #remove the %Fs and what not: 
    command=getexec1.split()[-1]#hopefully the actual execultutble 'command' 
    print command
Exemplo n.º 11
0
def set_autostart(auto_start):
    dfile = Desktop.DesktopEntry(auto_start_file)
    dfile.set("X-GNOME-Autostart-enabled", str(auto_start).lower())
    dfile.set("Name", "pocoy")
    dfile.set("Icon", "pocoy")
    dfile.set("Exec", "pocoy")
    dfile.write(filename=auto_start_file)
Exemplo n.º 12
0
    def __init__(self, app_name):
        self.entry = DesktopEntry()

        filename = '%s.desktop' % app_name
        system_entry = os.path.join('/usr/share/applications/', filename)
        self.local_entry = os.path.join(xdg_config_home, 'autostart', filename)
        self.key = 'X-GNOME-Autostart-enabled'

        self.load_file = self.local_entry \
            if os.access(self.local_entry, os.R_OK) else system_entry \
            if os.access(system_entry, os.R_OK) else None

        if self.load_file:
            self.entry.parse(self.load_file)
        else:
            print "Warning: the desktop entry of %s is not found." % app_name
Exemplo n.º 13
0
def parse_settings():
    ''' create settings menu '''
    print('DestroyMenu SettingsMenu\nAddToMenu SettingsMenu')
    for d in xdg_data_dirs:
        for f in glob("%s/settings/*.desktop" % d):
            desktop = DesktopEntry(f)
            print_dentry(desktop, prefix="/usr/lib/ydesk/settings/")
Exemplo n.º 14
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()
Exemplo n.º 15
0
    def run(self):
        with auto_save_dict(self.CACHE_FILE_NAME) as cache:
            if not cache:
                cache.update(self._getNewCache())
            apps = {}
            for f in cache.keys():
                app = DesktopEntry.DesktopEntry(f)
                apps[app.getName()] = app

            def runit(selected):
                if selected:
                    app = re.sub(' \(.+\)$', '', selected)
                    filename = apps[app].getFileName()
                    cache[filename] = 1 + cache.get(filename, 0)
                    if Gio:
                        launcher = Gio.DesktopAppInfo.new_from_filename(
                            filename)
                        launcher.launch([], None)
                    else:
                        cmd = re.sub("( -{1,2}\w+\W?%\w)|( %\w)", "",
                                     apps[app].getExec()).strip()
                        subprocess.Popen(cmd, shell=True)
                self._update_cache(cache)

            names = sorted(
                apps.values(),
                key=lambda x: -cache[x.getFileName()] or ord(x.getName()[0]))
            names = [
                "%s (%s)" % (a.getName(), a.getExec().split()[0])
                for a in names
            ]
            dmenu = Dmenu(names, runit)
            dmenu.set_options(**self.options)
            dmenu.run()
Exemplo n.º 16
0
 def get_category_content_feedline(utility):
     """
     Get the utility feedline to append to one of the cat*_liststore
     """
     # Get the application human-readable name
     desktop_file = d.DesktopEntry(
         filename='/usr/share/applications/' + utility + '.desktop'
         )
     global name_feed
     name_feed = desktop_file.getName().split(',')[0]
     exec_feed = desktop_file.getExec().rstrip("%f")
     term_feed = desktop_file.getTerminal()
     global icon_name
     icon_name = desktop_file.getIcon()
     if icon_name:
         global show_cat
         show_cat = 'yes'
         icon_feed = get_icon(gtk.STOCK_OPEN, icon_name, 48)
         global cat_feedline
         cat_feedline = (
             name_feed,
             icon_feed,
             exec_feed,
             term_feed,
             utility
             )
Exemplo n.º 17
0
def find_desktop_entry(cmd):
    desktop_files = []
    desktop_dirs = list(BaseDirectory.load_data_paths('applications'))
    for d in desktop_dirs:
        desktop_files += [DesktopEntry.DesktopEntry(os.path.join(d, name)) for name in os.listdir(d) if name.endswith(".desktop")]

    matches = [entry for entry in desktop_files if cmd.lower() in entry.getName().lower()]

    return matches[0]
Exemplo n.º 18
0
def checkfiles(path):
    if os.path.isdir(path):
        ls = os.listdir(path)
        for file in ls:
            checkfiles(os.path.join(path, file))
    else:
        try:
            entry = DesktopEntry(path)
        except ParsingError, e:
            print e
            return

        entry.getName()

        try:
            entry.validate()
        except ValidationError, e:
            print e
Exemplo n.º 19
0
    def __init__(self, filename, dir="", prefix=""):
        # Create entry
        self.DesktopEntry = DesktopEntry(os.path.join(dir, filename))
        self.setAttributes(filename, dir, prefix)

        # Can be one of Deleted/Hidden/Empty/NotShowIn/NoExec or True
        self.Show = True

        # Semi-Private
        self.Original = None
        self.Parents = []

        # Private Stuff
        self.Allocated = False
        self.Add = False
        self.MatchedInclude = False

        # Caching
        self.Categories = self.DesktopEntry.getCategories()
Exemplo n.º 20
0
def set_autostart(active):
    AUTOSTART_KEY = "X-GNOME-Autostart-enabled"
    autostart_dir = base.save_config_path("autostart")
    autostart_file = os.path.join(autostart_dir, REDSHIFT_DESKTOP)
    if not os.path.exists(autostart_file):
        desktop_files = list(
            base.load_data_paths("applications", REDSHIFT_DESKTOP))
        if not desktop_files:
            raise IOError("Installed redshift desktop file not found!")
            return
        desktop_file_path = desktop_files[0]
        # Read installed file and modify it
        dfile = desktop.DesktopEntry(desktop_file_path)
    else:
        dfile = desktop.DesktopEntry(autostart_file)
    activestr = str(bool(active)).lower()
    # print "Setting autostart to %s" % activestr
    dfile.set(AUTOSTART_KEY, activestr)
    dfile.write(filename=autostart_file)
Exemplo n.º 21
0
 def _get_should_autostart(self):
     KUPFER_DESKTOP = "kupfer.desktop"
     AUTOSTART_KEY = "X-GNOME-Autostart-enabled"
     autostart_dir = base.save_config_path("autostart")
     autostart_file = os.path.join(autostart_dir, KUPFER_DESKTOP)
     if not os.path.exists(autostart_file):
         return False
     dfile = desktop.DesktopEntry(autostart_file)
     return (dfile.hasKey(AUTOSTART_KEY)
             and dfile.get(AUTOSTART_KEY, type="boolean"))
Exemplo n.º 22
0
 def ffill(self):
     try:
         de = DesktopEntry.DesktopEntry(filename=dfilename)
     except Exception as E:
         messagebox.showerror("No", "Error with the file:\n" + str(E))
         return
     # check the consistency of the file
     try:
         de.parse(dfilename)
     except Exception as E:
         messagebox.showerror("No", "Error with the file:\n" + str(E))
         return
     #
     # name
     dname = de.getName()
     self.name_ent_var.set(dname)
     # generic name
     dgenericname = de.getGenericName()
     self.genericname_ent_var.set(dgenericname)
     # executable
     dexec = de.getExec()
     self.exec_ent_var.set(dexec)
     # tryexec
     dtryexec = de.getTryExec()
     self.tryexec_ent_var.set(dtryexec)
     # path
     dpath = de.getPath()
     self.dir_ent_var.set(dpath)
     # category - main only
     dcategories_temp = de.getCategories()
     for ccat in dcategories_temp:
         if ccat in freedesktop_main_categories:
             self.category_var.set(ccat)
             break
     # mimetypes
     dmime = de.getMimeTypes()
     self.mime_var.set(dmime)
     # keywords
     dkeywords = de.getKeywords()
     self.keys_var.set(dkeywords)
     # icon
     dicon = de.getIcon()
     self.icon_var.set(dicon)
     # comment
     dcomment = de.getComment()
     self.comment_var.set(dcomment)
     # run in terminal
     dterminal = de.getTerminal()
     self.terminal_var.set(dterminal)
     # no display
     dnodisplay = de.getNoDisplay()
     self.nodisplay_var.set(dnodisplay)
     # hidden
     dhidden = de.getHidden()
     self.hidden_var.set(dhidden)
Exemplo n.º 23
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)
     }
Exemplo n.º 24
0
def parsemenu(menu, name=""):
    if not name:
        name = menu.getPath()
    # print 'DestroyMenu "%s"' % name
    printtext('AddToMenu "%s"' % name)
    for entry in menu.getEntries():
        if isinstance(entry, xdg.Menu.Menu):
            printmenu(entry.getName(), entry.getIcon(),
                      'Popup "%s"' % entry.getPath())
        elif isinstance(entry, xdg.Menu.MenuEntry):
            desktop = DesktopEntry(entry.DesktopEntry.getFileName())
            printmenu(desktop.getName(), desktop.getIcon(),
                      options.exec_command + " " + desktop.getExec())
        else:
            printtext('# not supported: ' + str(entry))

    print
    for entry in menu.getEntries():
        if isinstance(entry, xdg.Menu.Menu):
            parsemenu(entry)
Exemplo n.º 25
0
def parsemenu(menu, name=""):
    if not name:
      name = menu.getPath()
    # print 'DestroyMenu "%s"' % name
    printtext('AddToMenu "%s"' % name)
    for entry in menu.getEntries():
	if isinstance(entry, xdg.Menu.Menu):
	    printmenu(entry.getName(), entry.getIcon(),
		      'Popup "%s"' % entry.getPath())
	elif isinstance(entry, xdg.Menu.MenuEntry):
	    desktop = DesktopEntry(entry.DesktopEntry.getFileName())
	    printmenu(desktop.getName(), desktop.getIcon(),
		      options.exec_command + " " + desktop.getExec())
	else:
	    printtext('# not supported: ' + str(entry))

    print
    for entry in menu.getEntries():
	if isinstance(entry, xdg.Menu.Menu):
	    parsemenu(entry)
Exemplo n.º 26
0
 def buildFromDir(d):
     with os.scandir(d) as it:
         for entry in it:
             if not entry.name.endswith(".desktop"):
                 continue
             desktopf = DesktopEntry.DesktopEntry(entry.path)
             icon = iconLookup(desktopf.getIcon())
             iconMap[entry.name[:-8].lower(
             )] = icon  # Get rid of .desktop suffix
             wm_class = desktopf.getStartupWMClass()
             if wm_class != "":
                 iconMap[wm_class.lower()] = icon
Exemplo n.º 27
0
 def _get_should_autostart(self):
     KUPFER_DESKTOP = "kupfer.desktop"
     AUTOSTART_KEY = "X-GNOME-Autostart-enabled"
     autostart_dir = base.save_config_path("autostart")
     autostart_file = os.path.join(autostart_dir, KUPFER_DESKTOP)
     if not os.path.exists(autostart_file):
         return False
     try:
         dfile = desktop.DesktopEntry(autostart_file)
     except xdg_e.ParsingError, exception:
         pretty.print_error(__name__, exception)
         return False
Exemplo n.º 28
0
def get_autostart():
    AUTOSTART_KEY = "X-GNOME-Autostart-enabled"
    autostart_dir = base.save_config_path("autostart")
    autostart_file = os.path.join(autostart_dir, REDSHIFT_DESKTOP)
    if not os.path.exists(autostart_file):
        desktop_files = list(
            base.load_data_paths("applications", REDSHIFT_DESKTOP))
        if not desktop_files:
            raise IOError("Installed redshift desktop file not found!")
        desktop_file_path = desktop_files[0]
        # Read installed file and modify it
        dfile = desktop.DesktopEntry(desktop_file_path)
        dfile.set(AUTOSTART_KEY, "false")
        dfile.write(filename=autostart_file)
        return False
    else:
        dfile = desktop.DesktopEntry(autostart_file)
        if dfile.get(AUTOSTART_KEY) == 'false':
            return False
        else:
            return True
Exemplo n.º 29
0
def scan_for_browsers():
    ret = []
    for d in SCAN_DIR:
        print("Scanning %s" % d)
        files = glob.glob(os.path.join(d, "*.desktop"))
        for f in files:
            de = DesktopEntry.DesktopEntry(f)
            if "WebBrowser" in de.getCategories():
                print("Found %s" % f)
                ret.append(f)

    save_conf(CONF_FILE, ret)
Exemplo n.º 30
0
 def __init__(self, filebgtag, filebgpressedtag, desktopentrypath, htop,
              parent):
     self.desktopentrypath = desktopentrypath
     d = DesktopEntry.DesktopEntry(desktopentrypath)
     iconnamenoext = d.getIcon()
     fileicon = findIconFromName1(iconnamenoext)
     command = d.getExec()
     super(PicButtonCommandLauncher1,
           self).__init__(filebgtag, filebgpressedtag, fileicon, command,
                          htop, parent)
     self.setAcceptDrops(True)
     self.mousePressPos = None
     self.dragThreshold = 30
Exemplo n.º 31
0
def open_autostart_file():
    autostart_dir = base.save_config_path("autostart")
    autostart_file = os.path.join(autostart_dir, REDSHIFT_DESKTOP)

    if not os.path.exists(autostart_file):
        desktop_files = list(
            base.load_data_paths("applications", REDSHIFT_DESKTOP))

        if not desktop_files:
            raise IOError("Installed redshift desktop file not found!")

        desktop_file_path = desktop_files[0]

        # Read installed file
        dfile = desktop.DesktopEntry(desktop_file_path)
        for key, values in AUTOSTART_KEYS:
            dfile.set(key, values[False])
        dfile.write(filename=autostart_file)
    else:
        dfile = desktop.DesktopEntry(autostart_file)

    return dfile, autostart_file
Exemplo n.º 32
0
def parse_toplevel(menu):
    ''' parse menu file for embedding '''
    for entry in menu.getEntries():
        if isinstance(entry, xdg.Menu.Menu):
            icon = entry.getIcon()
            cache_icon(icon)
            print('+ "%s%%%s.png%%" Popup "%s"' %
                  (entry.getName(), os.path.basename(icon), entry))
        elif isinstance(entry, xdg.Menu.MenuEntry):
            desktop = DesktopEntry(entry.DesktopEntry.getFileName())
            print_dentry(desktop)
        else:
            pass
Exemplo n.º 33
0
 def get_applications(self):
     """Returns a dictionary object for each application"""
     result = {}
     datadirs = list(BaseDirectory.load_data_paths('applications'))
     for application in self.apps:
         for datadir in datadirs:
             filename = os.path.join(datadir, application)
             if os.path.exists(filename):
                 desktop_entry = DesktopEntry.DesktopEntry(filename)
                 break
         else:
             desktop_entry = None
         result[application] = desktop_entry
     return result
Exemplo n.º 34
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]
Exemplo n.º 35
0
def get_info_desktop(desktopfile):
    """return infos from a .desktop file"""
    name, cmd, icon, generic = "", "", "", ""
    lang = locale.setlocale(locale.LC_ALL, "")[0:2]
    d = DesktopEntry.DesktopEntry(desktopfile)
    name = d.getName()
    icon = d.getIcon()
    generic = d.getGenericName()
    cmd = d.getExec()

    cmd = cmd.split('%')[0].strip()
    # handle wine shortcuts
    if cmd.startswith('env WINEPREFIX'):
        cmd = cmd.replace('\\\\', '\\')
    return (name, cmd, icon, generic)
Exemplo n.º 36
0
Arquivo: Menu.py Projeto: zevipa/umte
    def __init__(self, filename, dir="", prefix=""):
        # Create entry
        self.DesktopEntry = DesktopEntry(os.path.join(dir,filename))
        self.setAttributes(filename, dir, prefix)

        # Can be one of Deleted/Hidden/Empty/NotShowIn/NoExec or True
        self.Show = True

        # Semi-Private
        self.Original = None
        self.Parents = []

        # Private Stuff
        self.Allocated = False
        self.Add = False
        self.MatchedInclude = False

        # Caching
        self.Categories = self.DesktopEntry.getCategories()
Exemplo n.º 37
0
class AutoStart(object):
    """Read and Write Desktop Entry for Autostart

    Desktop Application Autostart Specification
    http://standards.freedesktop.org/autostart-spec/latest/
    """

    def __init__(self, app_name):
        self.entry = DesktopEntry()

        filename = '%s.desktop' % app_name
        system_entry = os.path.join('/usr/share/applications/', filename)
        self.local_entry = os.path.join(xdg_config_home, 'autostart', filename)
        self.key = 'X-GNOME-Autostart-enabled'

        self.load_file = self.local_entry \
            if os.access(self.local_entry, os.R_OK) else system_entry \
            if os.access(system_entry, os.R_OK) else None

        if self.load_file:
            self.entry.parse(self.load_file)
        else:
            print "Warning: the desktop entry of %s is not found." % app_name

    def check_enable(self):
        state = bool(self.load_file)
        return state

    def get(self):
        state = bool(self.entry.get(self.key) == 'true')
        return state

    def set(self, state):
        if self.check_enable():
            state_str = 'true' if state else 'false'
            self.entry.set(self.key, state_str, 'Desktop Entry')
            self.entry.write(self.local_entry)
Exemplo n.º 38
0
#!/usr/bin/python
from xdg.DesktopEntry import *

import os, sys

test = DesktopEntry()
test.parse("/usr/share/applications/gedit.desktop")
test.removeKey("Name")
test.addGroup("Hallo")
test.set("key", "value", "Hallo")
test.write("test.desktop")
Exemplo n.º 39
0
Arquivo: Menu.py Projeto: zevipa/umte
class MenuEntry:
    "Wrapper for 'Menu Style' Desktop Entries"
    def __init__(self, filename, dir="", prefix=""):
        # Create entry
        self.DesktopEntry = DesktopEntry(os.path.join(dir,filename))
        self.setAttributes(filename, dir, prefix)

        # Can be one of Deleted/Hidden/Empty/NotShowIn/NoExec or True
        self.Show = True

        # Semi-Private
        self.Original = None
        self.Parents = []

        # Private Stuff
        self.Allocated = False
        self.Add = False
        self.MatchedInclude = False

        # Caching
        self.Categories = self.DesktopEntry.getCategories()

    def save(self):
        if self.DesktopEntry.tainted == True:
            self.DesktopEntry.write()

    def getDir(self):
        return self.DesktopEntry.filename.replace(self.Filename, '')

    def getType(self):
        """Return the type of MenuEntry, System/User/Both"""
        if xdg.Config.root_mode == False:
            if self.Original:
                return "Both"
            elif xdg_data_dirs[0] in self.DesktopEntry.filename:
                return "User"
            else:
                return "System"
        else:
            return "User"

    def setAttributes(self, filename, dir="", prefix=""):
        self.Filename = filename
        self.Prefix = prefix
        self.DesktopFileID = os.path.join(prefix,filename).replace("/", "-")

        if not os.path.isabs(self.DesktopEntry.filename):
            self.__setFilename()

    def updateAttributes(self):
        if self.getType() == "System":
            self.Original = MenuEntry(self.Filename, self.getDir(), self.Prefix)
            self.__setFilename()

    def __setFilename(self):
        if xdg.Config.root_mode == False:
            path = xdg_data_dirs[0]
        else:
            path= xdg_data_dirs[1]

        if self.DesktopEntry.getType() == "Application":
            dir = os.path.join(path, "applications")
        else:
            dir = os.path.join(path, "desktop-directories")

        self.DesktopEntry.filename = os.path.join(dir, self.Filename)

    def __cmp__(self, other):
        return locale.strcoll(self.DesktopEntry.getName(), other.DesktopEntry.getName())
    
    def _key(self):
        """Key function for locale-aware sorting."""
        return _strxfrm(self.DesktopEntry.getName())
    
    def __lt__(self, other):
        try:
            other = other._key()
        except AttributeError:
            pass
        return self._key() < other
            

    def __eq__(self, other):
        if self.DesktopFileID == str(other):
            return True
        else:
            return False

    def __repr__(self):
        return self.DesktopFileID
Exemplo n.º 40
0
def getservices():

    # get list of desktop files from kde
    command = "grep -l kcmshell4 /usr/share/kde4/services/*.desktop"
    files = subprocess.getoutput(command).splitlines()

    # get list of desktop files from big
    command = "ls -d -1 " + os.getcwd() + "/includes/*.desktop"
    files += subprocess.getoutput(command).splitlines()

    # get current theme
    command = "kreadconfig --group 'Icons' --key 'Theme'"
    theme = subprocess.getoutput(command)

    # output
    output = {}

    # Map categories
    category_types = {
        "X-KDE-settings-accessibility": _("DESKTOP"),
        "X-KDE-settings-components": _("DESKTOP"),
        "X-KDE-settings-desktop": _("DESKTOP"),
        "X-KDE-settings-looknfeel": _("LOOK AND FEEL"),
        "X-KDE-settings-network": _("NETWORK AND CONNECTIVITY"),
        "X-KDE-settings-webbrowsing": _("NETWORK AND CONNECTIVITY"),
        "X-KDE-settings-peripherals": _("HARDWARE"),
        "X-KDE-settings-hardware": _("HARDWARE"),
        "X-KDE-settings-power": _("SYSTEM"),
        "X-KDE-settings-security": _("SECURITY"),
        "X-KDE-settings-sound": _("HARDWARE"),
        "X-KDE-settings-system": _("SYSTEM"),
        "X-KDE-settings-bluetooth": _("NETWORK AND CONNECTIVITY"),
        "X-KDE-settings-system-administration": _("SYSTEM"),
        "X-KDE-settings-user_manager": _("SYSTEM"),
        "X-KDE-information": _("INFORMATIONS OF SYSTEM")
    }


    # extra configurations
    apps_remove = open(os.getcwd() + "/conf/remove.conf").read().splitlines()
    apps_category = open(os.getcwd() + "/conf/category.conf").read().splitlines()

    # get informations from files
    for file in files:

        entry = DesktopEntry()

        # parse file
        try:
            entry.parse(file)
        except:
            continue

        # data from file
        name = entry.getName()
        comment = entry.getComment()
        icon = str(getIconPath(entry.getIcon(), theme=theme, size=32))
        filename = os.path.splitext(os.path.basename(file))[0]
        category = None

        # fix error on get icon path
        if icon == "None":
            icon = str(getIconPath("preferences-system", theme=theme, size=32))

        # get all categories from file
        file_categories = entry.getCategories()

        # use last category
        for elem in file_categories:
            category = elem

        # big applications
        if "/usr/share/kde4" not in file:
            execute = entry.getExec()
            category = _(category.upper())

        # kde applications
        else:
            # remove applications
            if filename in apps_remove:
                continue

            execute = "kcmshell4 " + str(filename)

            # get category from file
            try:
                if category is None:
                    raise Exception()
                category = category_types[category]
            except:
                category = _("OTHERS CONFIGURATIONS")

            # check recategorize
            regex=re.compile(filename + "=*")
            for line in apps_category:
                if regex.search(line):
                    category = _(line.split("=")[1].upper())


        # convert to upper
        category = category.upper()

        # fill array service
        if category not in output:
            output[category] = []

        output[category].append({
            "execute": execute,
            "comment": comment,
            "icon": icon,
            "name": name
        })

    output = OrderedDict(sorted(output.items()))
    return output