Example #1
0
 def get_autostart(self):
     if os.path.exists(self.autostart_desktop):
         desktop_entry = DesktopEntry(self.autostart_desktop)
         return not desktop_entry.getHidden()
     elif os.path.exists(self.sys_autostart_desktop):
         desktop_entry = DesktopEntry(self.sys_autostart_desktop)
         return not desktop_entry.getHidden()
     else:
         return False
Example #2
0
 def get_autostart(self):
     if os.path.exists(self.autostart_desktop):
         desktop_entry = DesktopEntry(self.autostart_desktop)
         return not desktop_entry.getHidden()
     elif os.path.exists(self.sys_autostart_desktop):
         desktop_entry = DesktopEntry(self.sys_autostart_desktop)
         return not desktop_entry.getHidden()
     else:
         return False
Example #3
0
 def _get_app_list(self, directory, user):
     for root, dirs, files in os.walk(directory):
         for name in files:
             if name.endswith(".desktop"):
               
                 app_path = root + "/" + name
                 
                 # setup desktop entry to access its elements                    
                 xgd_de = DesktopEntry(app_path)
                 
                 #                    
                 self.app_entry = Desktop_Entry(
                     name,
                     xgd_de.getName( ),
                     xgd_de.getGenericName( ),
                     xgd_de.getNoDisplay( ),
                     xgd_de.getHidden( ),
                     xgd_de.getOnlyShowIn( ),
                     xgd_de.getNotShowIn( ),
                     xgd_de.getCategories( ),
                     app_path,
                     user,
                     False
                 )   
                  
                 # Just as a note, skip no display or hidden .desktop                    
                 if not (self.app_entry.de_nodisp or self.app_entry.de_hidden):
                     self._add_entry(self.app_entry)                        
Example #4
0
def parse(desktop_file, debug_enabled):
    """
    Returns a dict if the .desktop entry should be included in the dmenu, or
    none if not applicable
    """
    application = DesktopEntry(desktop_file)
    if debug_enabled:
        eprint('PARSED: ' + desktop_file)
    if application.getHidden():
        if debug_enabled:
            eprint('HIDDEN: ' + desktop_file)
        return None
    if application.getNoDisplay():
        if debug_enabled:
            eprint('NODISPLAY: ' + desktop_file)
        return None
    executable = application.getTryExec()
    if not executable:
        executable = application.getExec()
    if not executable:
        if debug_enabled:
            eprint('NO EXECUTABLE: ' + desktop_file)
        return None
    return {
        application.getName():
        [part for part in executable.split(' ') if not part.startswith('%')]
    }
Example #5
0
    def set_autostart(self, enable):
        if not os.path.exists(self.autostart_desktop):
            if os.path.exists(self.sys_autostart_desktop):
                os.system("mkdir -p %s" % os.path.dirname(self.autostart_desktop))
                os.system("cp %s %s" % (self.sys_autostart_desktop, self.autostart_desktop))
            else:
                return False

        desktop_entry = DesktopEntry(self.autostart_desktop)
        if desktop_entry.getHidden() == enable:
            hidden_word = "false" if enable else "true"
            desktop_entry.set("Hidden", hidden_word)
            desktop_entry.write()
Example #6
0
 def test_values(self):
     entry = DesktopEntry(self.test_file)
     self.assertEqual(entry.getName(), 'gedit')
     self.assertEqual(entry.getGenericName(), 'Text Editor')
     self.assertEqual(entry.getNoDisplay(), False)
     self.assertEqual(entry.getComment(), 'Edit text files')
     self.assertEqual(entry.getIcon(), 'accessories-text-editor')
     self.assertEqual(entry.getHidden(), False)
     self.assertEqual(entry.getOnlyShowIn(), [])
     self.assertEqual(entry.getExec(), 'gedit %U')
     self.assertEqual(entry.getTerminal(), False)
     self.assertEqual(entry.getMimeTypes(), ['text/plain'])
     self.assertEqual(entry.getCategories(), ['GNOME', 'GTK', 'Utility', 'TextEditor'])
     self.assertEqual(entry.getTerminal(), False)
Example #7
0
 def test_values(self):
     entry = DesktopEntry(self.test_file)
     self.assertEqual(entry.getName(), 'gedit')
     self.assertEqual(entry.getGenericName(), 'Text Editor')
     self.assertEqual(entry.getNoDisplay(), False)
     self.assertEqual(entry.getComment(), 'Edit text files')
     self.assertEqual(entry.getIcon(), 'accessories-text-editor')
     self.assertEqual(entry.getHidden(), False)
     self.assertEqual(entry.getOnlyShowIn(), [])
     self.assertEqual(entry.getExec(), 'gedit %U')
     self.assertEqual(entry.getTerminal(), False)
     self.assertEqual(entry.getMimeTypes(), ['text/plain'])
     self.assertEqual(entry.getCategories(),
                      ['GNOME', 'GTK', 'Utility', 'TextEditor'])
     self.assertEqual(entry.getTerminal(), False)
Example #8
0
 def __init__(self, stage):
  self._apps = list()
  self._rdsk = re.compile(u".*\.desktop$")
  self._icon_actor_cache = dict()
  HOME = os.getenv("HOME")
  l = list()
  l += self._get_all_desktop_files(u'/usr/share/applications')
  if HOME:
   l += self._get_all_desktop_files(os.path.join(HOME, u'.local/share/applications'))
  for f in l:
   de = DesktopEntry(f)
   if de.getType() == u"Application" and not de.getHidden():
    self._apps.append(apps_entry(stage, de))
  self._apps.sort(key=lambda x: x.name)
  pass
Example #9
0
    def set_autostart(self, enable):
        if not os.path.exists(self.autostart_desktop):
            if os.path.exists(self.sys_autostart_desktop):
                os.system("mkdir -p %s" %
                          os.path.dirname(self.autostart_desktop))
                os.system("cp %s %s" %
                          (self.sys_autostart_desktop, self.autostart_desktop))
            else:
                return False

        desktop_entry = DesktopEntry(self.autostart_desktop)
        if desktop_entry.getHidden() == enable:
            hidden_word = "false" if enable else "true"
            desktop_entry.set("Hidden", hidden_word)
            desktop_entry.write()
Example #10
0
 def __init__(self, stage):
     self._apps = list()
     self._rdsk = re.compile(u".*\.desktop$")
     self._icon_actor_cache = dict()
     HOME = os.getenv("HOME")
     l = list()
     l += self._get_all_desktop_files(u'/usr/share/applications')
     if HOME:
         l += self._get_all_desktop_files(
             os.path.join(HOME, u'.local/share/applications'))
     for f in l:
         de = DesktopEntry(f)
         if de.getType() == u"Application" and not de.getHidden():
             self._apps.append(apps_entry(stage, de))
     self._apps.sort(key=lambda x: x.name)
     pass
Example #11
0
 def add_desktop(self, filename):
     try:
         d = DesktopEntry(filename)
         if d.getHidden() or d.getNoDisplay() or d.getTerminal(
         ) or d.getType() != 'Application':
             return
         app = Application(name=d.getName(),
                           command_line=get_command(d),
                           mtime=datetime.fromtimestamp(
                               os.path.getmtime(filename)),
                           is_desktop=True)
         if d.getPath():
             app.path = d.getPath()
         self.add_app(app)
     except (xdg.Exceptions.ParsingError,
             xdg.Exceptions.DuplicateGroupError,
             xdg.Exceptions.DuplicateKeyError):
         pass
Example #12
0
    def _generate_app_actions(self, path):
        app_actions = []
        filename_pattern = os.path.expanduser(os.path.join(
                path,
                AppsOperator.FILE_TYPE
        ))
        for filename in glob.glob(filename_pattern):
            app = DesktopEntry(filename)

            # TODO: Comply with  full DesktopEntries spec - OnlyShowIn, TryExec
            if app.getType() == "Application" and not app.getNoDisplay() and \
                    not app.getHidden() and not app.getTerminal():
                action = AppAction(
                    name=app.getName(),
                    description="application",
                    run=self._launch_application,
                    data={"desktop_entry": app, "cmd": self.get_cmd(app)},
                    icon=get_icon(app.getIcon()),
                )
                app_actions.append(action)
        return app_actions
Example #13
0
def parse_linux_desktop_entry(fpath):
    """Load data from desktop entry with xdg specification."""
    from xdg.DesktopEntry import DesktopEntry

    try:
        entry = DesktopEntry(fpath)
        entry_data = {}
        entry_data['name'] = entry.getName()
        entry_data['icon_path'] = entry.getIcon()
        entry_data['exec'] = entry.getExec()
        entry_data['type'] = entry.getType()
        entry_data['hidden'] = entry.getHidden()
        entry_data['fpath'] = fpath
    except Exception:
        entry_data = {
            'name': '',
            'icon_path': '',
            'hidden': '',
            'exec': '',
            'type': '',
            'fpath': fpath
        }

    return entry_data
Example #14
0
for dir in SEARCH_DIRS:
    fnames = glob.glob(dir + '/*/*.desktop')

    for fname in fnames:
        de = DesktopEntry(fname)
        cats = de.getCategories() or ["All"]
        for cat in cats:
            if not cat in categories:
                categories[cat] = []

            categories[cat].append(de)

for k, v in sorted(categories.items()):
    catName = k
    for de in v:
        if de.getNoDisplay() or de.getHidden():
            continue

        mainGroup = de.defaultGroup
        printEntry(catName, de, True)

        for group in de.groups():
            if group != mainGroup:
                de.defaultGroup = group
                printEntry(catName, de, False)

for exc in execs.values():
    execFile.write(exc)

menuFile.close()
execFile.close()
        glob(os.path.join(path, '*.desktop'))
        for path in BaseDirectory.load_data_paths('applications')
):
    desktop = DesktopEntry(dfile)
    fname = os.path.splitext(os.path.basename(dfile))[0]

    try:
        cmd = FILTER.sub('', desktop.getExec()).split(' ', 1)
        cmd[0] = which(cmd[0])
    except ProgramNotFound:
        continue

    if desktop.getTerminal():
        cmd.insert(0, withpty)

    #service_path = os.path.join(generator_dir, fname)
    service_path = os.path.join(generator_dir, fname + "@.service")
    service = IniFile()
    service.addGroup('Unit')
    service.set('SourcePath', dfile, 'Unit')
    if not desktop.getHidden():
        service.set('X-ShowInMenu', "True", 'Unit')
    service.set('Description', desktop.getName(), 'Unit')
    service.addGroup('Service')
    service.set('EnvironmentFile', "%t/sessions/%i/environ", 'Service')
    service.set('ExecStart', " ".join(cmd), 'Service')

    service.defaultGroup = 'Unit'

    service.write(service_path)
#!/usr/bin/env python3
# Author: Juho Teperi

from xdg.BaseDirectory import load_data_paths
from xdg.DesktopEntry import DesktopEntry
from glob import glob
from re import sub
from os.path import basename

# To remove duplicates
data = {}

for d in load_data_paths("applications"):
    for app in glob(d + "/*.desktop"):
        desktop = DesktopEntry(app)
        name = desktop.getName()

        if (not desktop.getHidden() and not desktop.getNoDisplay()) and name not in data:
            data[name] = basename(app)

for name, cmd in data.items():
    print('{}\t{}'.format(name, cmd))
Example #17
0
class AutostartFile:
    def __init__(self, path):
        self.path = path
        self.filename = os.path.basename(path)
        self.dirname = os.path.dirname(path)
        self.de = DesktopEntry(path)

    def __eq__(self, other):
        return self.filename == other.filename

    def __str__(self):
        return self.path + " : " + self.de.getName()

    def _isexecfile(self, path):
        return os.access(path, os.X_OK)

    def _findFile(self, path, search, match_func):
        # check empty path
        if not path:
            return None
        # check absolute path
        if path[0] == "/":
            if match_func(path):
                return path
            else:
                return None
        else:
            # check relative path
            for dirname in search.split(os.pathsep):
                if dirname != "":
                    candidate = os.path.join(dirname, path)
                    if match_func(candidate):
                        return candidate

    def _alert(self, mstr, info=False):
        if info:
            print("\t " + mstr)
        else:
            print("\t*" + mstr)

    def _showInEnvironment(self, envs, verbose=False):
        default = not self.de.getOnlyShowIn()
        noshow = False
        force = False
        for i in self.de.getOnlyShowIn():
            if i in envs:
                force = True
        for i in self.de.getNotShowIn():
            if i in envs:
                noshow = True

        if verbose:
            if not default and not force:
                s = ""
                for i in self.de.getOnlyShowIn():
                    if s:
                        s += ", "
                    s += i
                self._alert("Excluded by: OnlyShowIn (" + s + ")")
            if default and noshow and not force:
                s = ""
                for i in self.de.getNotShowIn():
                    if s:
                        s += ", "
                    s += i
                self._alert("Excluded by: NotShowIn (" + s + ")")
        return (default and not noshow) or force

    def _shouldRun(self, envs, verbose=False):
        if not self.de.getExec():
            if verbose:
                self._alert("Excluded by: Missing Exec field")
            return False
        if self.de.getHidden():
            if verbose:
                self._alert("Excluded by: Hidden")
            return False
        if self.de.getTryExec():
            if not self._findFile(self.de.getTryExec(), os.getenv("PATH"), self._isexecfile):
                if verbose:
                    self._alert("Excluded by: TryExec (" + self.de.getTryExec() + ")")
                return False
        if not self._showInEnvironment(envs, verbose):
            return False
        return True

    def display(self, envs):
        if self._shouldRun(envs):
            print("[*] " + self.de.getName())
        else:
            print("[ ] " + self.de.getName())
        self._alert("File: " + self.path, info=True)
        if self.de.getExec():
            self._alert("Executes: " + self.de.getExec(), info=True)
        self._shouldRun(envs, True)
        print

    def run(self, envs):
        here = os.getcwd()
        if self.de.getPath():
            os.chdir(self.de.getPath())
        if self._shouldRun(envs):
            args = ["/bin/sh", "-c", "exec " + self.de.getExec()]
            os.spawnv(os.P_NOWAIT, args[0], args)
        os.chdir(here)
Example #18
0
for dir in SEARCH_DIRS:
    fnames = glob.glob(dir+'/*/*.desktop')

    for fname in fnames:
        de = DesktopEntry(fname)
        cats = de.getCategories() or ["All"]
        for cat in cats:
            if not cat in categories:
                categories[cat] = []
            
            categories[cat].append(de)

for k, v in sorted(categories.items()):
    catName = k
    for de in v:
        if de.getNoDisplay() or de.getHidden():
            continue

        mainGroup = de.defaultGroup
        printEntry(catName, de, True)

        for group in de.groups():
            if group != mainGroup:
                de.defaultGroup = group
                printEntry(catName, de, False)

for exc in execs.values():
    execFile.write(exc)

menuFile.close()
execFile.close()