#!/usr/bin/env python3 """Generate a JWM menu fragment from freedesktop .desktop files.""" import os, re, shutil from xml.sax.saxutils import escape, quoteattr DIRS = [ "/usr/share/applications", "/usr/local/share/applications", os.path.expanduser("~/.local/share/applications"), ] # (Categories key, menu label, menu icon) — first match wins CATEGORIES = [ ("Network", "Network", "applications-internet"), ("Development", "Development", "applications-development"), ("Education", "Education", "applications-science"), ("Game", "Games", "applications-games"), ("Graphics", "Graphics", "applications-graphics"), ("AudioVideo", "Multimedia", "applications-multimedia"), ("Office", "Office", "applications-office"), ("Science", "Science", "applications-science"), ("Settings", "Settings", "preferences-desktop"), ("System", "System", "applications-system"), ("Utility", "Accessories", "applications-accessories"), ] FALLBACK = ("Other", "applications-other") def read_entry(path): e, section = {}, "" with open(path, encoding="utf-8", errors="replace") as f: for line in f: line = line.strip() if line.startswith("["): section = line elif section == "[Desktop Entry]" and "=" in line and not line.startswith("#"): k, v = line.split("=", 1) e.setdefault(k.strip(), v.strip()) return e def main(): files = {} for d in DIRS: # later dirs override earlier ones if os.path.isdir(d): for fn in sorted(os.listdir(d)): if fn.endswith(".desktop"): files[fn] = os.path.join(d, fn) buckets = {} for fn, path in files.items(): try: e = read_entry(path) except OSError: continue if e.get("Type", "Application") != "Application": continue if e.get("NoDisplay", "").lower() == "true": continue if e.get("Hidden", "").lower() == "true": continue cmd = e.get("Exec", "") if not cmd: continue if e.get("TryExec") and not shutil.which(e["TryExec"]): continue cmd = re.sub(r"%[fFuUdDnNickvm]", "", cmd).strip() # strip field codes if e.get("Terminal", "").lower() == "true": cmd = "xterm -e " + cmd name = e.get("Name") or fn[:-8] icon = e.get("Icon", "") cats = e.get("Categories", "").split(";") label, micon = FALLBACK for key, lab, ic in CATEGORIES: if key in cats: label, micon = lab, ic break buckets.setdefault((label, micon), []).append((name, icon, cmd)) print("") for key in [(lab, ic) for _, lab, ic in CATEGORIES] + [FALLBACK]: items = buckets.get(key) if not items: continue label, micon = key print("" % (quoteattr(label), quoteattr(micon))) for name, icon, cmd in sorted(items, key=lambda t: t[0].lower()): print(" %s" % (quoteattr(name), quoteattr(icon), escape(cmd))) print("") print("") if __name__ == "__main__": main()