///| Installed desktop applications, discovered from freedesktop `.desktop` files /// (XDG data dirs + flatpak exports). Feeds the launcher's search. ///| priv struct DesktopApp { id : String name : String comment : String category : String command : String /// StartupWMClass: the app id its windows carry when that is not the desktop file's name. wm_class : String /// Icon=: an icon theme name ("firefox") or an absolute path. icon : String /// Terminal=true: runs inside a terminal. terminal : Bool /// Categories= has TerminalEmulator. terminal_emulator : Bool } ///| Drop Exec field codes (%f %U ...), keep a literal %%. fn clean_exec(exec : String) -> String { let sb = StringBuilder::new() let chars = exec.to_array() let mut i = 0 while i < chars.length() { if chars[i] == '%' && i + 1 < chars.length() { if chars[i + 1] == '%' { sb.write_char('%') } i = i + 2 } else { sb.write_char(chars[i]) i = i + 1 } } sb.to_string().trim(chars=" ").to_string() } ///| The menu category of a web app a Chromium browser installed (its Exec starts the browser with /// --app-id), named the way the browser names its own menu folder ("Chrome Apps"); None for any /// other command. These files carry no Categories=: the browsers sort them into their folder with /// a desktop menu file instead. fn web_app_category(command : String) -> String? { match command.find("--app-id=") { None => None Some(i) => { // Only the browser's part: an app id may spell anything in a-p. let browser = command[:i].to_string().to_lower() for it in [ ("brave", "Brave Apps"), ("microsoft", "Edge Apps"), ("msedge", "Edge Apps"), ("vivaldi", "Vivaldi Apps"), ("opera", "Opera Apps"), ("chromium", "Chromium Apps"), ("chrome", "Chrome Apps"), ] { if browser.contains(it.0) { return Some(it.1) } } Some("Web Apps") } } } ///| The menu category for a Categories= value: the first of the menu spec's main categories in /// it, by the name menus show, else "Other" (toolkit names such as Qt and GTK are no category). fn menu_category(categories : String) -> String { for c in semi_list(categories) { match c { "AudioVideo" | "Audio" | "Video" => return "Multimedia" "Development" => return "Development" "Education" => return "Education" "Game" => return "Games" "Graphics" => return "Graphics" "Network" => return "Internet" "Office" => return "Office" "Science" => return "Science" "Settings" => return "Settings" "System" => return "System" "Utility" => return "Utilities" _ => () } } "Other" } ///| Parse one .desktop file; None when it should not be listed. A Terminal=true app keeps its /// own command (`terminal`): it is started inside the chosen terminal (`DesktopShell::command_for`). fn parse_desktop(id : String, text : String, have_terminal : Bool) -> DesktopApp? { let k = desktop_entry_keys(text) let get = fn(key : String) { k.get(key).unwrap_or("") } let name = get("Name") let exec = get("Exec") let hidden = get("NoDisplay") == "true" || get("Hidden") == "true" let terminal = get("Terminal") == "true" let kind = k.get("Type").unwrap_or("Application") if hidden || kind != "Application" || name.length() == 0 || exec.length() == 0 { return None } if terminal && !have_terminal { return None } let cats = get("Categories") let category = web_app_category(exec).unwrap_or(menu_category(cats)) let comment = get("Comment") let comment = if comment.length() > 0 { comment } else { get("GenericName") } Some({ id, name, comment, category, command: clean_exec(exec), wm_class: get("StartupWMClass"), icon: get("Icon"), terminal, terminal_emulator: semi_list(cats).contains("TerminalEmulator"), }) } ///| The .desktop file names in the applications dirs, to tell when apps were added or removed. fn desktop_files_in(dirs : Array[String]) -> Array[String] { let out : Array[String] = [] for dir in dirs { out.push(dir) out.append(@sys.list_desktop_files(dir)) } out } ///| Fill the app catalog from the installed .desktop files. fn DesktopShell::load_apps(self : DesktopShell) -> Unit { let dirs = self.xdg_dirs.app_dirs() self.app_files = desktop_files_in(dirs) let old_icons = self.icon_names.copy() self.apps.clear() self.exec.clear() self.wm_classes.clear() self.icon_names.clear() self.terminal_apps.clear() for a in scan_desktop_apps(dirs) { if a.terminal { self.terminal_apps.set(a.id, true) } if a.icon.length() > 0 { self.icon_names.set(a.id, a.icon) } if a.wm_class.length() > 0 { self.wm_classes.set(a.wm_class.to_lower(), a.id) } let glyph = match a.name.to_array().get(0) { Some(c) => c.to_string().to_upper() None => "?" } self.apps.push({ id: a.id, name: a.name, comment: a.comment, category: a.category, glyph }) self.exec.set(a.id, a.command) // A new app (or one with a new icon) may have been looked up before it had one. if old_icons.get(a.id) != self.icon_names.get(a.id) { self.icon_handles.remove(a.id) } } self.order_apps() self.apps_dirty = true } ///| Read the catalog again if apps were installed or removed since (a web app installed from the /// browser, say). Called as the Applications menu opens; only lists the dirs when nothing changed. fn DesktopShell::refresh_apps(self : DesktopShell) -> Unit { if desktop_files_in(self.xdg_dirs.app_dirs()) != self.app_files { self.load_apps() } } ///| Scan every applications dir in `dirs` (highest priority first: a file there overrides one of /// the same name further on), result sorted by name. fn scan_desktop_apps(dirs : Array[String]) -> Array[DesktopApp] { let by_id : Map[String, DesktopApp] = {} let removed : Map[String, Bool] = {} for dir in dirs.rev() { for file in @sys.list_desktop_files(dir) { let bytes = @sys.read_file_bytes(dir + "/" + file) let id = file[:file.length() - 8].to_string() match parse_desktop(id, @utf8.decode_lossy(bytes), true) { Some(app) => { by_id.set(id, app) removed.remove(id) } None => { by_id.remove(id) } } } } // Terminal apps are only listed when there is a terminal to run them in. let mut have_terminal = @sys.has_exe("foot") for _, a in by_id { have_terminal = have_terminal || a.terminal_emulator } let apps : Array[DesktopApp] = [] for _, a in by_id { if have_terminal || !a.terminal { apps.push(a) } } // Strings compare shortest first; menus want A-Z. apps.sort_by(fn(a, b) { a.name.to_lower().lexical_compare(b.name.to_lower()) }) apps } ///| test "parse_desktop reads a normal entry and strips field codes" { let t = "[Desktop Entry]\nType=Application\nName=Firefox\nName[de]=Feuerfuchs\nComment=Browse\nExec=firefox %u\nCategories=Network;WebBrowser;\n[Desktop Action x]\nName=Nope\n" match parse_desktop("firefox", t, true) { Some(a) => { assert_eq(a.name, "Firefox") assert_eq(a.command, "firefox") assert_eq(a.category, "Internet") assert_eq(a.comment, "Browse") } None => fail("expected entry") } } ///| test "parse_desktop keeps StartupWMClass" { let t = "[Desktop Entry]\nType=Application\nName=Code\nExec=code %F\nStartupWMClass=Code\n" match parse_desktop("visual-studio-code", t, true) { Some(a) => assert_eq(a.wm_class, "Code") None => fail("expected entry") } let t2 = "[Desktop Entry]\nType=Application\nName=Files\nExec=nautilus\nIcon=org.gnome.Nautilus\n[Desktop Action w]\nIcon=other\n" match parse_desktop("org.gnome.Nautilus", t2, true) { Some(a) => assert_eq(a.icon, "org.gnome.Nautilus") None => fail("expected entry") } } ///| test "parse_desktop puts a browser's web apps in their own category" { let web = fn(exec : String) { let t = "[Desktop Entry]\nType=Application\nName=YouTube\nExec=" + exec + "\nStartupWMClass=crx_agim\n" + "Actions=Shorts\n[Desktop Action Shorts]\nName=Shorts\nExec=other\n" match parse_desktop("chrome-agim-Default", t, true) { Some(a) => (a.name, a.category, a.command) None => ("", "", "") } } let chrome = "/opt/google/chrome/google-chrome --profile-directory=Default --app-id=edgeop" assert_eq(web(chrome), ("YouTube", "Chrome Apps", chrome)) assert_eq(web("/usr/bin/chromium --app-id=abc").1, "Chromium Apps") assert_eq(web("/usr/bin/flatpak run --command=/app/bin/chrome com.google.Chrome --app-id=abc").1, "Chrome Apps") assert_eq(web("/opt/microsoft/msedge/microsoft-edge --app-id=abc").1, "Edge Apps") assert_eq(web("firefox"), ("YouTube", "Other", "firefox")) } ///| test "menu_category skips toolkit names and names the main category" { assert_eq(menu_category("Qt;KDE;System;TerminalEmulator;"), "System") assert_eq(menu_category("Game;Network;"), "Games") assert_eq(menu_category("GTK;X-Own;"), "Other") assert_eq(menu_category(""), "Other") } ///| test "parse_desktop hides NoDisplay entries" { let t = "[Desktop Entry]\nType=Application\nName=X\nExec=x\nNoDisplay=true\n" assert_true(parse_desktop("x", t, true) is None) } ///| The desktop file id that launches the app whose windows carry `app_id`: the file of that /// name, else one whose StartupWMClass is it, else a case-insensitive match on either, else one /// whose last dotted part matches (a window "nautilus" for org.gnome.Nautilus.desktop). fn resolve_app_id( app_id : String, exec : Map[String, String], wm_classes : Map[String, String], ) -> String? { if app_id.length() == 0 { return None } if exec.contains(app_id) { return Some(app_id) } let low = app_id.to_lower() match wm_classes.get(low) { Some(id) => return Some(id) None => () } for id, _ in exec { if id.to_lower() == low { return Some(id) } } for id, _ in exec { let parts : Array[String] = id.split(".").map(x => x.to_string()).collect() if parts.length() > 1 && parts[parts.length() - 1].to_lower() == low { return Some(id) } } None } ///| test "resolve_app_id finds the desktop file for a window's app id" { let exec : Map[String, String] = { "foot": "foot", "org.gnome.Nautilus": "nautilus --new-window", "visual-studio-code": "code", } let wm : Map[String, String] = { "code": "visual-studio-code" } assert_eq(resolve_app_id("foot", exec, wm), Some("foot")) assert_eq(resolve_app_id("Code", exec, wm), Some("visual-studio-code")) assert_eq(resolve_app_id("org.gnome.nautilus", exec, wm), Some("org.gnome.Nautilus")) assert_eq(resolve_app_id("nautilus", exec, wm), Some("org.gnome.Nautilus")) assert_eq(resolve_app_id("unknown", exec, wm), None) assert_eq(resolve_app_id("", exec, wm), None) } ///| Canonical app id for an external X11 window: resolve WM_CLASS class then instance against /// installed .desktop files (including StartupWMClass, e.g. `astra` -> `gamerig-astra`), /// falling back to the raw class, instance, or title. pub fn DesktopShell::resolve_external_app_id( self : DesktopShell, wm_class : String, wm_instance : String, title : String, ) -> String { match resolve_app_id(wm_class, self.exec, self.wm_classes) { Some(id) => return id None => () } match resolve_app_id(wm_instance, self.exec, self.wm_classes) { Some(id) => return id None => () } if wm_class.length() > 0 { wm_class } else if wm_instance.length() > 0 { wm_instance } else { title } } ///| test "resolve_external_app_id resolves StartupWMClass and falls back cleanly" { let sh = DesktopShell::new(":0") sh.exec.clear() sh.wm_classes.clear() sh.exec.set("com.mitchellh.ghostty", "gamerig-open terminal") sh.exec.set("steam", "gamerig-open steam") sh.exec.set("gamerig-astra", "gamerig-open astra") sh.wm_classes.set("com.mitchellh.ghostty", "com.mitchellh.ghostty") sh.wm_classes.set("steam", "steam") sh.wm_classes.set("astra", "gamerig-astra") assert_eq(sh.resolve_external_app_id("com.mitchellh.ghostty", "ghostty", "Terminal"), "com.mitchellh.ghostty") assert_eq(sh.resolve_external_app_id("steam", "steamwebhelper", "Steam"), "steam") assert_eq(sh.resolve_external_app_id("astra", "astra", "Space Rage: Astra Incognita"), "gamerig-astra") assert_eq(sh.resolve_external_app_id("steam_app_1145360", "steam_app_1145360", "Hades"), "steam_app_1145360") assert_eq(sh.resolve_external_app_id("", "my-inst", "Fallback"), "my-inst") assert_eq(sh.resolve_external_app_id("", "", "Window Title"), "Window Title") }