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)
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
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"])
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 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/")
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)
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()
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
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)
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 )
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()
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]
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"))
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))
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)
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)
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) }
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
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
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
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)
def parse_autostart(): ''' parse autostart items ''' cmds = [] for d in xdg_config_dirs: for f in glob("%s/autostart/*.desktop" % d): desktop = DesktopEntry(f) if not desktop.getHidden(): cmds.append(desktop.getExec().rstrip('%FUfu')) for f in glob("%s/autostart/*.desktop" % xdg_config_home): desktop = DesktopEntry(f) cmd = desktop.getExec().rstrip('%FUfu') if not desktop.getHidden(): cmds.append(cmd) else: try: cmds.remove(cmd) except ValueError: pass # output for c in set(cmds): print('+ I Exec exec %s' % c)
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
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
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
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
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]
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)
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 fpop(self, ap_dir): for ddir in ap_dir: if os.path.exists(ddir): for ffile in os.listdir(ddir): if not ffile.lower().endswith(".desktop"): continue # fpath = os.path.join(ddir, ffile) try: entry = DesktopEntry.DesktopEntry(fpath) ftype = entry.getType() if ftype != "Application": continue hidden = entry.getHidden() nodisplay = entry.getNoDisplay() # do not show those marked as hidden or not to display if hidden or nodisplay: continue # item.name fname = entry.getName() # item.path # fpath # category ccat = entry.getCategories() fcategory = self.get_category(ccat) ## item.name.lower() # fname_lower = fname.lower() # pexec (executable) fexec = entry.getExec() if fexec[0:5] == "$HOME": fexec = "~" + fexec[5:] # check for arguments and remove them # if fexec[-3:] in self.execArgs: # fexec = fexec[:-3] for aargs in self.execArgs: if aargs in fexec: fexec = fexec.strip(aargs) # icon ficon = entry.getIcon() # comment fcomment = entry.getComment() ### self.lists.append([ fname, fpath, fcategory or "Missed", fexec, ficon ]) except: pass