Files
chandra/compositor/shell/default_apps.mbt
T
nandiandClaude Opus 5.5 68baf1a467
CI / test (push) Failing after 49s
Launcher: pick up web apps as they are installed, categories, scrolling
- Read the app catalog again when the Applications menu opens if .desktop files were added or removed (and on Reload); it was only read at login, so a PWA installed during the session was missing from the menu and its search
- List a Chromium browser's web apps in their own category ("Chrome Apps", "Chromium Apps", ...), as Plasma does; don't take one for the default browser
- Category column and a scrollable list (wheel, scrollbar) when the catalog doesn't fit the menu
- Show menu-spec main category names instead of the first Categories= entry; sort apps A-Z (they were sorted shortest name first)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 23:42:10 -08:00

888 lines
31 KiB
MoonBit

///| Default applications (the settings module's Apps tab, capability `default-apps`): which
/// installed app opens web links, mail, folders, text, images, video, music, documents and
/// archives, and which terminal runs terminal apps.
///
/// Everything but the terminal lives where other programs look for it, the freedesktop MIME
/// application associations (mimeapps.list):
///
/// - reading follows the spec's lookup order: `$XDG_CONFIG_HOME/$desktop-mimeapps.list`, then
/// `$XDG_CONFIG_HOME/mimeapps.list`, the same two in each `$XDG_CONFIG_DIRS` dir (/etc/xdg),
/// then `applications/[$desktop-]mimeapps.list` in `$XDG_DATA_HOME` and each `$XDG_DATA_DIRS`
/// dir. The first `[Default Applications]` entry for the category's main MIME type whose app is
/// installed wins. With none, the system's associations decide (`[Added Associations]`, then
/// each applications dir's mimeinfo.cache, minus `[Removed Associations]`), else the first
/// installed app that handles the type. An app chosen before that is no longer installed is
/// reported as missing (and skipped, as xdg-open does).
/// - setting writes `[Default Applications]` in `$XDG_CONFIG_HOME/mimeapps.list` for every MIME
/// type of the category that the app handles (and always the main one), like `xdg-mime
/// default` / `xdg-settings set default-web-browser`. Every other section, entry, comment and
/// blank line is kept as it was; the app is taken out of `[Removed Associations]` for those
/// types. A desktop-specific file (`$XDG_CONFIG_HOME/chandra-mimeapps.list`) that already names a
/// default for one of them is updated too, since it would otherwise win.
///
/// The terminal has no MIME type: the choice is kept in state.edn (`:terminal "foot"`), used for
/// apps with Terminal=true, and exported as the first line of `$XDG_CONFIG_HOME/xdg-terminals.list`
/// (the xdg-terminal-exec convention) so tools that open "a terminal" follow it.
///| A category of default app.
pub(all) struct AppCategory {
/// Short id ("browser").
id : String
/// Shown in the settings module.
label : String
/// The MIME types it covers, the main one first (read to find the current default). Empty for
/// the terminal.
mimes : Array[String]
}
///| The categories, in the order the Apps tab shows them.
pub let app_categories : Array[AppCategory] = [
{
id: "browser",
label: "Web browser",
mimes: [
"x-scheme-handler/http", "x-scheme-handler/https", "text/html", "application/xhtml+xml",
],
},
{ id: "email", label: "Email", mimes: ["x-scheme-handler/mailto", "message/rfc822"] },
{ id: "files", label: "File manager", mimes: ["inode/directory"] },
{ id: "terminal", label: "Terminal", mimes: [] },
{
id: "editor",
label: "Text editor",
mimes: [
"text/plain", "text/markdown", "text/x-csrc", "text/x-chdr", "text/x-c++src", "text/x-python",
"text/x-log", "application/x-shellscript", "application/json", "application/xml",
],
},
{
id: "images",
label: "Image viewer",
mimes: [
"image/png", "image/jpeg", "image/gif", "image/webp", "image/bmp", "image/svg+xml", "image/tiff",
"image/avif", "image/heif",
],
},
{
id: "video",
label: "Video player",
mimes: [
"video/mp4", "video/x-matroska", "video/webm", "video/mpeg", "video/quicktime", "video/x-msvideo",
"video/ogg", "video/x-flv",
],
},
{
id: "music",
label: "Music player",
mimes: [
"audio/mpeg", "audio/flac", "audio/ogg", "audio/x-vorbis+ogg", "audio/opus", "audio/x-wav",
"audio/mp4", "audio/aac", "audio/x-m4a",
],
},
{
id: "documents",
label: "PDF and documents",
mimes: ["application/pdf", "application/epub+zip", "application/postscript", "image/vnd.djvu"],
},
{
id: "archives",
label: "Archive manager",
mimes: [
"application/zip", "application/x-tar", "application/x-compressed-tar", "application/x-7z-compressed",
"application/vnd.rar", "application/x-rar", "application/gzip", "application/x-xz-compressed-tar",
"application/x-bzip2-compressed-tar", "application/zstd",
],
},
]
///| Index of the terminal category.
let terminal_category : Int = 3
///| An installed application as far as default apps care: from its .desktop file.
pub(all) struct HandlerApp {
/// Desktop file id without ".desktop".
id : String
name : String
/// Icon= value.
icon : String
/// Exec= with field codes dropped.
command : String
/// MimeType= and Categories= entries.
mimes : Array[String]
categories : Array[String]
/// Listed in menus (not NoDisplay): only these are offered, but a hidden one that is already
/// the default still counts as installed.
shown : Bool
} derive(Debug)
///| The [Desktop Entry] group of a .desktop file as key -> value (later keys win; other groups
/// and comments are skipped). Shared with the launcher's `parse_desktop`.
fn desktop_entry_keys(text : String) -> Map[String, String] {
let out : Map[String, String] = {}
let mut in_entry = false
for raw in text.split("\n") {
let line = raw.trim(chars=" \r\t").to_string()
if line.length() == 0 || line.has_prefix("#") {
continue
}
if line.has_prefix("[") {
in_entry = line == "[Desktop Entry]"
continue
}
if !in_entry {
continue
}
match line.find("=") {
None => ()
Some(eq) =>
out.set(line[:eq].trim(chars=" ").to_string(), line[eq + 1:].trim(chars=" ").to_string())
}
}
out
}
///| A ;-separated list ("a;b;") as its non-empty parts.
fn semi_list(s : String) -> Array[String] {
let out : Array[String] = []
for p in s.split(";") {
let t = p.trim(chars=" ").to_string()
if t.length() > 0 {
out.push(t)
}
}
out
}
///| Parse a .desktop file for default apps; None when it is not an installed application
/// (Hidden=true, not Type=Application, or no Name/Exec).
pub fn parse_handler_app(id : String, text : String) -> HandlerApp? {
let k = desktop_entry_keys(text)
let get = fn(key : String) { k.get(key).unwrap_or("") }
if get("Hidden") == "true" || k.get("Type").unwrap_or("Application") != "Application" {
return None
}
let name = get("Name")
let exec = get("Exec")
if name.length() == 0 || exec.length() == 0 {
return None
}
Some({
id,
name,
icon: get("Icon"),
command: clean_exec(exec),
mimes: semi_list(get("MimeType")),
categories: semi_list(get("Categories")),
shown: get("NoDisplay") != "true",
})
}
///| The directories the default-apps lookup reads, so tests can point it at a temporary tree.
pub(all) struct XdgDirs {
config_home : String
/// $XDG_CONFIG_DIRS, highest priority first.
config_dirs : Array[String]
data_home : String
/// $XDG_DATA_DIRS, highest priority first.
data_dirs : Array[String]
/// $XDG_CURRENT_DESKTOP, lower-cased, in order.
desktops : Array[String]
}
///| The directories from the environment (with the spec's defaults).
pub fn XdgDirs::from_env() -> XdgDirs {
let home = @sys.getenv("HOME")
let or = fn(name : String, dflt : String) {
let v = @sys.getenv(name)
if v.length() > 0 { v } else { dflt }
}
let parts = fn(s : String) -> Array[String] {
s.split(":").filter(p => p.length() > 0).map(p => p.to_string()).collect()
}
// Flatpak's exports (flatpak usually puts them in XDG_DATA_DIRS).
let data_dirs = parts(or("XDG_DATA_DIRS", "/usr/local/share:/usr/share"))
for d in [home + "/.local/share/flatpak/exports/share", "/var/lib/flatpak/exports/share"] {
if !data_dirs.contains(d) {
data_dirs.push(d)
}
}
{
config_home: or("XDG_CONFIG_HOME", home + "/.config"),
config_dirs: parts(or("XDG_CONFIG_DIRS", "/etc/xdg")),
data_home: or("XDG_DATA_HOME", home + "/.local/share"),
data_dirs,
desktops: parts(@sys.getenv("XDG_CURRENT_DESKTOP").to_lower()),
}
}
///| mimeapps.list files in lookup order (highest priority first).
pub fn XdgDirs::mimeapps_files(self : XdgDirs) -> Array[String] {
let out : Array[String] = []
let add = fn(dir : String) {
for d in self.desktops {
out.push(dir + "/" + d + "-mimeapps.list")
}
out.push(dir + "/mimeapps.list")
}
add(self.config_home)
for d in self.config_dirs {
add(d)
}
add(self.data_home + "/applications")
for d in self.data_dirs {
add(d + "/applications")
}
out
}
///| applications dirs, highest priority first.
fn XdgDirs::app_dirs(self : XdgDirs) -> Array[String] {
let out = [self.data_home + "/applications"]
for d in self.data_dirs {
out.push(d + "/applications")
}
out
}
///| Every installed application, by desktop id; a file in a higher-priority dir hides one of the
/// same name below it (also when it is Hidden).
pub fn scan_handler_apps(dirs : XdgDirs) -> Map[String, HandlerApp] {
let out : Map[String, HandlerApp] = {}
let seen : Map[String, Bool] = {}
for dir in dirs.app_dirs() {
for file in @sys.list_desktop_files(dir) {
let id = file[:file.length() - 8].to_string()
if seen.contains(id) {
continue
}
seen.set(id, true)
match parse_handler_app(id, @utf8.decode_lossy(@sys.read_file_bytes(dir + "/" + file))) {
Some(a) => out.set(id, a)
None => ()
}
}
}
out
}
///| The entries of section `group` ("Default Applications") of a mimeapps.list or
/// mimeinfo.cache: MIME type -> desktop ids (".desktop" dropped), in file order.
pub fn mimeapps_section(text : String, group : String) -> Map[String, Array[String]] {
let out : Map[String, Array[String]] = {}
let mut inside = false
for raw in text.split("\n") {
let line = raw.trim(chars=" \r\t").to_string()
if line.has_prefix("[") {
inside = line == "[" + group + "]"
continue
}
if !inside || line.has_prefix("#") {
continue
}
match line.find("=") {
None => ()
Some(eq) => {
let key = line[:eq].trim(chars=" ").to_string()
let ids = semi_list(line[eq + 1:].to_string()).map(desktop_id)
match out.get(key) {
Some(prev) => for i in ids { prev.push(i) }
None => out.set(key, ids)
}
}
}
}
out
}
///| "firefox.desktop" -> "firefox".
fn desktop_id(s : String) -> String {
if s.has_suffix(".desktop") {
s[:s.length() - 8].to_string()
} else {
s
}
}
///| `text` (a mimeapps.list) with `[Default Applications]` set to `app` for each MIME type in
/// `mimes`. Other lines are kept as they are: existing entries for those types are replaced in
/// place, new ones go at the end of the section (which is added when missing), and `app` is
/// taken out of those types' `[Removed Associations]`.
pub fn set_mimeapps_defaults(text : String, mimes : Array[String], app : String) -> String {
let value = app + ".desktop;"
let lines : Array[String] = text.split("\n").map(l => l.to_string()).collect()
if lines.length() > 0 && lines[lines.length() - 1] == "" {
ignore(lines.pop())
}
let out : Array[String] = []
let done : Map[String, Bool] = {}
let mut section = ""
let mut had_defaults = false
let flush = fn(out : Array[String]) {
// Entries the section didn't have yet, before any blank lines that end it.
let mut blanks = 0
while out.length() > blanks && out[out.length() - 1 - blanks].trim(chars=" \t\r") == "" {
blanks = blanks + 1
}
let tail : Array[String] = []
for _ in 0..<blanks {
tail.push(out.pop().unwrap())
}
for m in mimes {
if !done.contains(m) {
out.push(m + "=" + value)
done.set(m, true)
}
}
for i = tail.length() - 1; i >= 0; i = i - 1 {
out.push(tail[i])
}
}
for line in lines {
let t = line.trim(chars=" \t\r").to_string()
if t.has_prefix("[") {
if section == "Default Applications" {
flush(out)
}
section = t[1:t.length() - (if t.has_suffix("]") { 1 } else { 0 })].to_string()
if section == "Default Applications" {
had_defaults = true
}
out.push(line)
continue
}
let eq = t.find("=")
match (section, eq) {
("Default Applications", Some(i)) if !t.has_prefix("#") => {
let key = t[:i].trim(chars=" ").to_string()
if mimes.contains(key) {
if !done.contains(key) {
out.push(key + "=" + value)
done.set(key, true)
}
continue
}
out.push(line)
}
("Removed Associations", Some(i)) if !t.has_prefix("#") => {
let key = t[:i].trim(chars=" ").to_string()
if mimes.contains(key) {
let rest = semi_list(t[i + 1:].to_string()).filter(x => desktop_id(x) != app)
if rest.length() > 0 {
out.push(key + "=" + rest.join(";") + ";")
}
continue
}
out.push(line)
}
_ => out.push(line)
}
}
if section == "Default Applications" {
flush(out)
}
if !had_defaults {
if out.length() > 0 && out[out.length() - 1].trim(chars=" \t\r") != "" {
out.push("")
}
out.push("[Default Applications]")
flush(out)
}
out.join("\n") + "\n"
}
///| Whether `app` can be offered for category `c`: the terminal wants TerminalEmulator; the others
/// an app that handles one of their MIME types. Web browsers handle images, PDFs and text too, but
/// are only offered as browsers.
pub fn handles_category(app : HandlerApp, c : Int) -> Bool {
if c == terminal_category {
return app.categories.contains("TerminalEmulator")
}
let cat = app_categories[c]
if cat.id != "browser" && app.categories.contains("WebBrowser") {
return false
}
cat.mimes.iter().any(m => app.mimes.contains(m))
}
///| One category as the Apps tab shows it.
pub(all) struct CategoryChoices {
/// The apps it can be set to (shown ones, by name).
apps : Array[HandlerApp]
/// Index of the current default in `apps`, or -1 (none, or a hidden app).
current : Int
/// Desktop id of the current default ("" when there is none).
current_id : String
/// The chosen app that is not installed any more ("" when none).
missing : String
} derive(Debug)
///| The current default for MIME type `mime`: (installed app id or "", the first configured
/// default that is not installed or "").
pub fn default_for_mime(
dirs : XdgDirs,
installed : Map[String, HandlerApp],
mime : String,
) -> (String, String) {
let mut missing = ""
let removed : Array[String] = []
let added : Array[String] = []
for path in dirs.mimeapps_files() {
let text = @utf8.decode_lossy(@sys.read_file_bytes(path))
if text.length() == 0 {
continue
}
match mimeapps_section(text, "Default Applications").get(mime) {
Some(ids) =>
for id in ids {
if installed.contains(id) && !removed.contains(id) {
return (id, missing)
} else if missing == "" && !installed.contains(id) {
missing = id
}
}
None => ()
}
match mimeapps_section(text, "Added Associations").get(mime) {
Some(ids) => for id in ids { if !removed.contains(id) { added.push(id) } }
None => ()
}
match mimeapps_section(text, "Removed Associations").get(mime) {
Some(ids) => for id in ids { removed.push(id) }
None => ()
}
}
for id in added {
if installed.contains(id) && !removed.contains(id) {
return (id, missing)
}
}
for dir in dirs.app_dirs() {
let text = @utf8.decode_lossy(@sys.read_file_bytes(dir + "/mimeinfo.cache"))
match mimeapps_section(text, "MIME Cache").get(mime) {
Some(ids) =>
for id in ids {
if installed.contains(id) && !removed.contains(id) {
return (id, missing)
}
}
None => ()
}
}
// No cache: the first installed app (by name) that says it handles the type.
let ids : Array[String] = []
for id, a in installed {
if a.mimes.contains(mime) && !removed.contains(id) {
ids.push(id)
}
}
ids.sort_by(fn(a, b) { compare_names(installed, a, b) })
(ids.get(0).unwrap_or(""), missing)
}
///|
fn compare_names(installed : Map[String, HandlerApp], a : String, b : String) -> Int {
let x = installed.get(a).map(h => h.name.to_lower()).unwrap_or(a)
let y = installed.get(b).map(h => h.name.to_lower()).unwrap_or(b)
match alphabetical(x, y) {
0 => alphabetical(a, b)
c => c
}
}
///| Dictionary order (String's own compare puts shorter strings first).
fn alphabetical(x : String, y : String) -> Int {
let n = if x.length() < y.length() { x.length() } else { y.length() }
for i = 0; i < n; i = i + 1 {
if x[i] != y[i] {
return if x[i] < y[i] { -1 } else { 1 }
}
}
x.length() - y.length()
}
///| The xdg-terminals.list files (xdg-terminal-exec), highest priority first.
fn XdgDirs::terminal_lists(self : XdgDirs) -> Array[String] {
let out : Array[String] = []
for dir in [self.config_home] + self.config_dirs {
for d in self.desktops {
out.push(dir + "/" + d + "-xdg-terminals.list")
}
out.push(dir + "/xdg-terminals.list")
}
out
}
///| Desktop ids listed in an xdg-terminals.list (comments, blank lines and `+`/`-` action
/// suffixes dropped).
fn terminal_list_ids(text : String) -> Array[String] {
let out : Array[String] = []
for raw in text.split("\n") {
let mut t = raw.trim(chars=" \t\r").to_string()
if t.length() == 0 || t.has_prefix("#") || t.has_prefix("/") {
continue
}
match t.find(":") {
Some(i) => t = t[:i].to_string()
None => ()
}
out.push(desktop_id(t))
}
out
}
///| Terminals tried, in order, when nothing chose one: foot is what Chandra always ran.
let preferred_terminals : Array[String] = [
"foot", "org.codeberg.dnkl.foot", "org.kde.konsole", "konsole", "org.gnome.Ptyxis", "org.gnome.Console",
"org.gnome.Terminal", "kitty", "Alacritty", "org.wezfurlong.wezterm", "xterm",
]
///| The current terminal: `chosen` (state.edn) when installed, else the first installed one in
/// xdg-terminals.list, else the first installed preferred one, else any. Returns (id or "", the
/// chosen one when it is no longer installed or "").
pub fn current_terminal(
dirs : XdgDirs,
installed : Map[String, HandlerApp],
chosen : String,
) -> (String, String) {
let ok = fn(id : String) {
match installed.get(id) {
Some(a) => handles_category(a, terminal_category)
None => false
}
}
let missing = if chosen != "" && !installed.contains(chosen) { chosen } else { "" }
if chosen != "" && ok(chosen) {
return (chosen, "")
}
for path in dirs.terminal_lists() {
for id in terminal_list_ids(@utf8.decode_lossy(@sys.read_file_bytes(path))) {
if ok(id) {
return (id, missing)
}
}
}
for id in preferred_terminals {
if ok(id) {
return (id, missing)
}
}
let ids : Array[String] = []
for id, _ in installed {
if ok(id) {
ids.push(id)
}
}
ids.sort_by(fn(a, b) { compare_names(installed, a, b) })
(ids.get(0).unwrap_or(""), missing)
}
///| Every category's choices and current default.
pub fn default_app_choices(
dirs : XdgDirs,
installed : Map[String, HandlerApp],
terminal : String,
) -> Array[CategoryChoices] {
let shown : Array[HandlerApp] = []
for _, a in installed {
if a.shown {
shown.push(a)
}
}
shown.sort_by(fn(a, b) { compare_names(installed, a.id, b.id) })
let out : Array[CategoryChoices] = []
for c = 0; c < app_categories.length(); c = c + 1 {
let apps = shown.filter(a => handles_category(a, c))
let (cur, missing) = if c == terminal_category {
current_terminal(dirs, installed, terminal)
} else {
default_for_mime(dirs, installed, app_categories[c].mimes[0])
}
let mut idx = -1
for i, a in apps {
if a.id == cur {
idx = i
}
}
let missing = if missing == "" {
""
} else {
installed.get(missing).map(a => a.name).unwrap_or(missing)
}
out.push({ apps, current: idx, current_id: cur, missing })
}
out
}
///| The MIME types of category `c` to set `app` as the default for: the main one always, the
/// others where the app says it handles them.
pub fn category_mimes_for(app : HandlerApp, c : Int) -> Array[String] {
let mimes = app_categories[c].mimes
let out : Array[String] = []
for i, m in mimes {
if i == 0 || app.mimes.contains(m) {
out.push(m)
}
}
out
}
///| Write `app` as the default for `mimes` into the user's mimeapps.list (and into a
/// desktop-specific one in the same dir that already names a default for one of them).
pub fn write_mimeapps_default(dirs : XdgDirs, mimes : Array[String], app : String) -> Bool {
if !@sys.mkdir_p(dirs.config_home) {
return false
}
let write = fn(path : String) {
let text = @utf8.decode_lossy(@sys.read_file_bytes(path))
@sys.write_file_bytes(path, @utf8.encode(set_mimeapps_defaults(text, mimes, app))) >= 0
}
for d in dirs.desktops {
let path = dirs.config_home + "/" + d + "-mimeapps.list"
let text = @utf8.decode_lossy(@sys.read_file_bytes(path))
let defs = mimeapps_section(text, "Default Applications")
if mimes.iter().any(m => defs.contains(m)) {
ignore(write(path))
}
}
write(dirs.config_home + "/mimeapps.list")
}
///| Put `app` first in the user's xdg-terminals.list, keeping the other lines.
pub fn write_terminal_list(dirs : XdgDirs, app : String) -> Bool {
if !@sys.mkdir_p(dirs.config_home) {
return false
}
let path = dirs.config_home + "/xdg-terminals.list"
let text = @utf8.decode_lossy(@sys.read_file_bytes(path))
let out = [app + ".desktop"]
for raw in text.split("\n") {
let line = raw.to_string()
let t = line.trim(chars=" \t\r").to_string()
if t.length() == 0 {
continue
}
if !t.has_prefix("#") && terminal_list_ids(t) == [app] {
continue
}
out.push(line)
}
@sys.write_file_bytes(path, @utf8.encode(out.join("\n") + "\n")) >= 0
}
///| `command` run inside terminal `term` (its desktop id and Exec command): most terminals take
/// `-e`; GNOME's take `--`, kitty the command itself, wezterm `start --`.
pub fn terminal_wrap(term_id : String, term_cmd : String, command : String) -> String {
let low = term_id.to_lower() + " " + term_cmd.to_lower()
if low.contains("wezterm") {
let base = if term_cmd.contains(" start") { term_cmd[:term_cmd.find(" start").unwrap()].to_string() } else { term_cmd }
base + " start -- " + command
} else if low.contains("gnome-terminal") || low.contains("kgx") || low.contains("ptyxis") {
term_cmd + " -- " + command
} else if low.contains("kitty") {
term_cmd + " " + command
} else {
term_cmd + " -e " + command
}
}
///| Scan the installed apps and the defaults again, and publish them.
pub fn DesktopShell::refresh_default_apps(self : DesktopShell) -> Unit {
let dirs = self.xdg_dirs
let installed = scan_handler_apps(dirs)
self.handler_apps = Some(installed)
self.default_apps = default_app_choices(dirs, installed, self.terminal)
self.default_apps_dirty = true
}
///| The categories' choices and current defaults (scanned on first use).
pub fn DesktopShell::default_app_choices(self : DesktopShell) -> Array[CategoryChoices] {
if self.handler_apps is None {
self.refresh_default_apps()
}
self.default_apps
}
///| Make the `app`-th choice of category `c` its default. False when there is no such choice or
/// the file could not be written.
pub fn DesktopShell::set_default_app(self : DesktopShell, c : Int, app : Int) -> Bool {
let choices = self.default_app_choices()
if c < 0 || c >= choices.length() || app < 0 || app >= choices[c].apps.length() {
return false
}
let a = choices[c].apps[app]
let ok = if c == terminal_category {
self.terminal = a.id
self.save_state()
ignore(write_terminal_list(self.xdg_dirs, a.id))
true
} else {
write_mimeapps_default(self.xdg_dirs, category_mimes_for(a, c), a.id)
}
self.refresh_default_apps()
if !ok {
self.say("Could not write mimeapps.list")
}
ok
}
///| The command that runs terminal app `command` in the chosen terminal (foot when nothing is
/// known).
pub fn DesktopShell::in_terminal(self : DesktopShell, command : String) -> String {
let installed = match self.handler_apps {
Some(m) => m
None => {
self.refresh_default_apps()
self.handler_apps.unwrap()
}
}
let (id, _) = current_terminal(self.xdg_dirs, installed, self.terminal)
match installed.get(id) {
Some(t) => terminal_wrap(id, t.command, command)
None => "foot -e " + command
}
}
///| The command that starts desktop app `id` (terminal apps inside the chosen terminal).
pub fn DesktopShell::command_for(self : DesktopShell, id : String) -> String? {
match self.exec.get(id) {
Some(cmd) => Some(if self.terminal_apps.contains(id) { self.in_terminal(cmd) } else { cmd })
None => None
}
}
///| Publish the categories (table 11: name, current default's name, missing) and their choices (table 12) when they changed.
/// Nothing is scanned until a module asks (`refresh`, when the Apps tab opens).
fn DesktopShell::publish_default_apps(self : DesktopShell) -> Unit {
if self.handler_apps is None || !self.default_apps_dirty {
return
}
let choices = self.default_apps
self.default_apps_dirty = false
let cats = @wasm.Table::new()
let apps = @wasm.Table::new()
for c, ch in choices {
cats.str(app_categories[c].label)
cats.str(
match self.handler_apps {
Some(m) => m.get(ch.current_id).map(a => a.name).unwrap_or("")
None => ""
},
)
cats.str(ch.missing)
cats.end_row()
for i, a in ch.apps {
apps.int(c)
apps.str(a.id)
apps.str(a.name)
apps.int(self.desktop_icon(a.id, a.icon).reinterpret_as_int())
apps.int(if i == ch.current { 1 } else { 0 })
apps.end_row()
}
}
@wasm.publish(AppCategories, cats)
@wasm.publish(AppChoices, apps)
}
///| A default-apps request: category * 1000 + app sets a default, -1 scans again.
pub fn DesktopShell::default_app_request(self : DesktopShell, code : Int) -> Unit {
if code < 0 {
self.refresh_default_apps()
} else {
ignore(self.set_default_app(code / 1000, code % 1000))
}
}
///|
test "desktop entries: MimeType, Categories, NoDisplay and Hidden" {
let t = "[Desktop Entry]\nType=Application\nName=Firefox\nExec=firefox %u\nIcon=firefox\nMimeType=text/html;x-scheme-handler/http;\nCategories=Network;WebBrowser;\n[Desktop Action new]\nName=New\nExec=firefox --new\n"
let a = parse_handler_app("firefox", t).unwrap()
assert_eq(a.name, "Firefox")
assert_eq(a.command, "firefox")
assert_eq(a.mimes, ["text/html", "x-scheme-handler/http"])
assert_eq(a.categories, ["Network", "WebBrowser"])
assert_true(a.shown)
let hidden = parse_handler_app("h", "[Desktop Entry]\nName=H\nExec=h\nNoDisplay=true\n").unwrap()
assert_false(hidden.shown)
assert_true(parse_handler_app("x", "[Desktop Entry]\nName=X\nExec=x\nHidden=true\n") is None)
assert_true(parse_handler_app("l", "[Desktop Entry]\nType=Link\nName=L\nURL=x\n") is None)
}
///|
test "mimeapps.list sections parse into MIME type -> desktop ids" {
let t = "# mine\n[Added Associations]\ntext/plain=gedit.desktop;\n\n[Default Applications]\ntext/html=firefox.desktop;chromium.desktop;\ninode/directory = org.gnome.Nautilus.desktop\n# x=y\n[Removed Associations]\ntext/plain=kate.desktop;\n"
let d = mimeapps_section(t, "Default Applications")
assert_eq(d.get("text/html"), Some(["firefox", "chromium"]))
assert_eq(d.get("inode/directory"), Some(["org.gnome.Nautilus"]))
assert_eq(d.get("text/plain"), None)
assert_eq(d.get("# x"), None)
assert_eq(mimeapps_section(t, "Removed Associations").get("text/plain"), Some(["kate"]))
}
///|
test "setting a default keeps every other section, entry and comment" {
let t = "# my associations\n[Added Associations]\ntext/plain=gedit.desktop;\n\n[Default Applications]\ntext/html=chromium.desktop;\nimage/png=eog.desktop;\n\n[Removed Associations]\nx-scheme-handler/http=firefox.desktop;chromium.desktop;\nx-scheme-handler/https=firefox.desktop;\n"
let out = set_mimeapps_defaults(
t,
["x-scheme-handler/http", "x-scheme-handler/https", "text/html"],
"firefox",
)
assert_eq(
out,
"# my associations\n[Added Associations]\ntext/plain=gedit.desktop;\n\n[Default Applications]\ntext/html=firefox.desktop;\nimage/png=eog.desktop;\nx-scheme-handler/http=firefox.desktop;\nx-scheme-handler/https=firefox.desktop;\n\n[Removed Associations]\nx-scheme-handler/http=chromium.desktop;\n",
)
// Setting it again changes nothing.
assert_eq(
set_mimeapps_defaults(out, ["x-scheme-handler/http", "x-scheme-handler/https", "text/html"], "firefox"),
out,
)
// No file yet, or no [Default Applications] section: one is added.
assert_eq(set_mimeapps_defaults("", ["inode/directory"], "thunar"), "[Default Applications]\ninode/directory=thunar.desktop;\n")
assert_eq(
set_mimeapps_defaults("[Added Associations]\na/b=x.desktop;", ["text/plain"], "kate"),
"[Added Associations]\na/b=x.desktop;\n\n[Default Applications]\ntext/plain=kate.desktop;\n",
)
}
///|
test "categories offer the apps that handle their MIME types; browsers only as browsers" {
let app = fn(id : String, mimes : Array[String], cats : Array[String]) -> HandlerApp {
{ id, name: id, icon: "", command: id, mimes, categories: cats, shown: true }
}
let firefox = app("firefox", ["text/html", "x-scheme-handler/http", "image/png", "application/pdf"], ["WebBrowser"])
let eog = app("eog", ["image/png", "image/jpeg"], ["Graphics", "Viewer"])
let vlc = app("vlc", ["video/mp4", "audio/mpeg"], ["AudioVideo"])
let foot = app("foot", [], ["System", "TerminalEmulator"])
let idx = fn(id : String) {
let mut n = -1
for i, c in app_categories {
if c.id == id {
n = i
}
}
n
}
assert_true(handles_category(firefox, idx("browser")))
assert_false(handles_category(firefox, idx("images")))
assert_false(handles_category(firefox, idx("documents")))
assert_true(handles_category(eog, idx("images")))
assert_false(handles_category(eog, idx("video")))
assert_true(handles_category(vlc, idx("video")))
assert_true(handles_category(vlc, idx("music")))
assert_true(handles_category(foot, idx("terminal")))
assert_false(handles_category(eog, idx("terminal")))
assert_eq(idx("terminal"), terminal_category)
// What gets written: the main type always, the others the app handles.
assert_eq(category_mimes_for(eog, idx("images")), ["image/png", "image/jpeg"])
assert_eq(category_mimes_for(vlc, idx("music")), ["audio/mpeg"])
assert_eq(category_mimes_for(firefox, idx("browser")), ["x-scheme-handler/http", "text/html"])
}
///|
test "terminal commands follow each terminal's convention" {
assert_eq(terminal_wrap("foot", "foot", "htop"), "foot -e htop")
assert_eq(terminal_wrap("org.gnome.Console", "kgx", "htop"), "kgx -- htop")
assert_eq(terminal_wrap("kitty", "kitty", "htop"), "kitty htop")
assert_eq(terminal_wrap("org.wezfurlong.wezterm", "wezterm start --cwd .", "htop"), "wezterm start -- htop")
assert_eq(terminal_list_ids("# mine\nkitty.desktop\n\nfoot.desktop:new-window\n/usr/bin/xterm\n"), ["kitty", "foot"])
}