From bb7c9b947fb61402aaef400be5d9a891f487f698 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 21:27:30 +0000 Subject: [PATCH] Settings > Apps: choose the default browser, email, files, terminal, editor, viewers and players - A sixth Settings tab, Apps (key 6, SettingsTab::Apps; the popup is 390 px wide for it): Web browser, Email, File manager, Terminal, Text editor, Image viewer, Video player, Music player, PDF and documents, Archive manager. Each row shows the current default with its real icon (the icon-theme lookup the task manager uses; a letter tile when there is none). Click a row to list the installed apps that can take it, click one to make it the default. A chosen app that has been uninstalled since is named in red under its row ("gthumb is not installed any more"). - Installed apps come from the .desktop files in the XDG data dirs (and flatpak's exports), with MimeType= and Categories= (desktop_entry_keys, now shared with the launcher's parse_desktop). A kind lists the shown apps that handle one of its MIME types; the terminal lists TerminalEmulator apps; browsers are only offered as browsers. - Reading follows the mimeapps.list spec: $XDG_CONFIG_HOME/[chandra-]mimeapps.list, then $XDG_CONFIG_DIRS (/etc/xdg), then $XDG_DATA_HOME and $XDG_DATA_DIRS applications/; the first installed [Default Applications] entry wins, else [Added Associations], else mimeinfo.cache (minus [Removed Associations]), else the first installed app that handles the type. A hidden (NoDisplay) default still counts and its name is shown. - Setting writes [Default Applications] in ~/.config/mimeapps.list for each of the kind's MIME types the app handles (always the main one: http/https/text/html for browsers, mailto, inode/directory, text/plain, image/png..., video/mp4..., audio/mpeg..., application/pdf..., application/zip...), as xdg-mime default / xdg-settings do, without running them. Every other section, entry, comment and blank line is kept; the app leaves those types' [Removed Associations]; a chandra-mimeapps.list that already names one of those types is updated too. - The terminal has no MIME type: state.edn :terminal "kitty" (desktop id), also written first in ~/.config/xdg-terminals.list (xdg-terminal-exec). Terminal=true apps from the launcher (and session restore) now start in it (foot -e, kgx/gnome-terminal/ptyxis --, kitty , wezterm start --) instead of always foot; with no choice: xdg-terminals.list, then foot, then any installed terminal. Terminal apps are listed when any terminal emulator is installed, not only foot. - New `default-apps` capability (categories, apps, set-default, refresh): host tables 11 (sss: name current missing) and 12 (issii: category id name icon current), request 19 (category * 1000 + app, -1 rescans) in the wasmer/wasmtime stub, host-wasm and the MoonBit wasmhost (chandra:host/plasmoids default-app(s32)). Nothing is scanned until the tab opens (refresh). - Tests with a temporary XDG tree: categories and current defaults (user file, system file, Added Associations, mimeinfo.cache, missing apps, hidden defaults), writing that keeps other entries, desktop-specific files, the terminal list and commands, the Apps tab end to end, and the :terminal round trip through state.edn. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DPL5hgywj7RPmFdFhpzGZj --- README.md | 10 +- .../chandra/desktop/plasmoid/moon.pkg | 1 + .../chandra/desktop/plasmoid/stub.mbt | 119 ++- compositor/host/default_apps_test.mbt | 237 +++++ compositor/shell/apps.mbt | 90 +- compositor/shell/default_apps.mbt | 887 ++++++++++++++++++ compositor/shell/icons.mbt | 15 + compositor/shell/shell.mbt | 21 + compositor/shell/state.mbt | 26 +- compositor/shell/widgets.mbt | 11 +- compositor/wasm/wasm_host.mbt | 10 + compositor/wasm/wasm_native.mbt | 10 + compositor/wasm/wasm_stub.c | 15 +- host-wasm/src/main.rs | 1 + host-wasm/src/plasmoid.rs | 44 +- .../chandra/desktop/default-apps/README.md | 5 + .../chandra/desktop/default-apps/ffi.mbt | 40 + .../chandra/desktop/default-apps/moon.pkg | 1 + .../chandra/desktop/default-apps/top.mbt | 73 ++ .../chandra/host/plasmoids/pkg.generated.mbti | 1 + interface/chandra/host/plasmoids/top.mbt | 8 +- wasmhost/bin/plasmoids.mbt | 1 + wit/capabilities.wit | 38 + wit/host/plasmoids.wit | 6 +- wit/worlds.wit | 5 +- world/session-settings-widget/README.md | 3 +- 26 files changed, 1605 insertions(+), 73 deletions(-) create mode 100644 compositor/host/default_apps_test.mbt create mode 100644 compositor/shell/default_apps.mbt create mode 100644 interface/chandra/desktop/default-apps/README.md create mode 100644 interface/chandra/desktop/default-apps/ffi.mbt create mode 100644 interface/chandra/desktop/default-apps/moon.pkg create mode 100644 interface/chandra/desktop/default-apps/top.mbt diff --git a/README.md b/README.md index 6f17fe7..5641c05 100644 --- a/README.md +++ b/README.md @@ -145,8 +145,11 @@ a recording shortcut again to stop. and a binary clock. * **Screenshot**, **Layout** (Tile | Float), **Inspector** (interface explorer). * **Settings**: tabs for Session (reopen windows at login, remember window positions, dark - mode), Desktop (wallpapers), Panel (add, remove and replace modules) and Power (screen off and - suspend when idle, battery, suspend / restart / power off). Dark mode also sets the system + mode), Desktop (wallpapers), Panel (add, remove and replace modules), Power (screen off and + suspend when idle, battery, suspend / restart / power off), Shortcuts and Apps (the default web + browser, email, file manager, terminal, text editor, image viewer, video and music player, PDF + viewer and archive manager, chosen from the installed apps; written to + `~/.config/mimeapps.list`, so xdg-open and other apps follow it). Dark mode also sets the system preference for apps: GTK, Qt and KDE settings, and in the login session Chandra serves xdg-desktop-portal's Settings color-scheme itself, so Chrome, Firefox and Electron apps follow the switch live (see [docs/dark-mode.md](docs/dark-mode.md)). @@ -163,7 +166,8 @@ keep pixels on the host rather than copying them through the component. * `~/.config/chandra/panel.edn`: the panel's modules, in order. * `~/.config/chandra/state.edn`: layout mode, recent apps, window positions, the windows to - reopen, wallpaper, theme, power timeouts, per-module settings (`:module-config`), and the + reopen, wallpaper, theme, power timeouts, the terminal terminal apps run in (`:terminal`, also + put first in `~/.config/xdg-terminals.list`), per-module settings (`:module-config`), and the Settings switches (`:restore-session false`, `:remember-windows false`, `:theme :light`). * Themes: `config/themes/moon-night.json` (default) and `moon-day.json`. diff --git a/components/session-settings/gen/interface/chandra/desktop/plasmoid/moon.pkg b/components/session-settings/gen/interface/chandra/desktop/plasmoid/moon.pkg index e6fbe34..e5aabf5 100644 --- a/components/session-settings/gen/interface/chandra/desktop/plasmoid/moon.pkg +++ b/components/session-settings/gen/interface/chandra/desktop/plasmoid/moon.pkg @@ -7,6 +7,7 @@ import { "chandra/desktop/interface/chandra/desktop/power" @power, "chandra/desktop/interface/chandra/desktop/system" @system, "chandra/desktop/interface/chandra/desktop/shortcuts" @shortcuts, + "chandra/desktop/interface/chandra/desktop/default-apps" @default_apps, "chandra/desktop/lib/ui" @ui, } diff --git a/components/session-settings/gen/interface/chandra/desktop/plasmoid/stub.mbt b/components/session-settings/gen/interface/chandra/desktop/plasmoid/stub.mbt index 20030ee..5a945e0 100644 --- a/components/session-settings/gen/interface/chandra/desktop/plasmoid/stub.mbt +++ b/components/session-settings/gen/interface/chandra/desktop/plasmoid/stub.mbt @@ -18,17 +18,22 @@ /// Enter) and press the new keys: the compositor takes that combo for it (Escape cancels, /// Backspace unbinds; clicking the row again also cancels). "Reset" at the end of a changed /// row, or Backspace on the highlighted row, puts it back; "Reset all to defaults" does every -/// one. Combos two shortcuts share are shown in red and listed under the shortcuts. +/// one. Combos two shortcuts share are shown in red and listed under the shortcuts; +/// - Apps: the default app for each kind of thing (`default-apps`): web browser, email, file +/// manager, terminal, text editor, image viewer, video and music player, PDF and documents, +/// archives. Each row shows the current one with its icon; click it to list the installed apps +/// that can take its place, click one of those to make it the default (the list folds up +/// again). A chosen app that has since been uninstalled is named in red under its row. /// /// Clicking a row acts at once and the popup stays open; a row in the panel list only acts through /// its buttons, so a stray click doesn't remove anything. Up/Down move the highlight, Left/Right -/// (or 1-5) switch tabs, Enter or Space acts on the highlighted row, Backspace or Delete removes +/// (or 1-6) switch tabs, Enter or Space acts on the highlighted row, Backspace or Delete removes /// the highlighted panel module (or resets the highlighted shortcut) and PageUp/PageDown move it, /// Escape or a click elsewhere closes. The shell remembers settings, wallpaper and shortcuts in /// state.edn, the panel in panel.edn. ///| Popup geometry: the tab bar, then a column of rows, with a margin around them. -let popup_w : Int = 360 +let popup_w : Int = 390 ///| let margin : Int = 6 @@ -50,7 +55,13 @@ let switch_w : Int = 34 let switch_h : Int = 18 ///| -let tab_names : Array[String] = ["Session", "Desktop", "Panel", "Power", "Shortcuts"] +let tab_names : Array[String] = ["Session", "Desktop", "Panel", "Power", "Shortcuts", "Apps"] + +///| The Apps tab's category whose choices are listed (-1: none). +let expanded : Ref[Int] = { val: -1 } + +///| Size of the app icons on the Apps tab. +let icon_size : Int = 18 ///| A popup row. enum Row { @@ -76,6 +87,11 @@ enum Row { Shortcut(Int, @shortcuts.Shortcut) /// "Reset all to defaults" (the shortcuts). ResetShortcuts + /// A kind of default app: its index, name, the current default among its choices (None: not + /// one of them), the current default's name ("" for none) and how many apps can take it. + AppKind(Int, String, @default_apps.AppChoice?, String, Int) + /// One of a kind's apps, listed under it while it is expanded: the kind, its index there, the app. + AppOption(Int, Int, @default_apps.AppChoice) } ///| Width of the "Reset" button at the end of a changed shortcut's row. @@ -196,6 +212,23 @@ fn rows() -> Array[Row] { rs.push(PowerNow(2, "Restart")) rs.push(PowerNow(1, "Power off")) } + 5 => { + let cats = @default_apps.categories() + let apps = @default_apps.apps() + for c = 0; c < cats.length(); c = c + 1 { + let mine = apps.filter(a => a.category.reinterpret_as_int() == c) + let cur = mine.iter().find_first(a => a.current) + rs.push(AppKind(c, cats[c].name, cur, cats[c].current, mine.length())) + if cats[c].missing != "" { + rs.push(Info("! " + cats[c].missing + " is not installed any more")) + } + if expanded.val == c { + for k, a in mine { + rs.push(AppOption(c, k, a)) + } + } + } + } 4 => { rs.push(Heading("Click one, then press its new keys")) let list = @shortcuts.shortcuts() @@ -363,6 +396,11 @@ let hover_btn : Ref[Int] = { val: -1 } ///| fn set_tab(i : Int) -> Unit { cancel_capture() + expanded.val = -1 + if i == 5 && tab.val != 5 { + // Another program may have changed a default since the tab was last open. + @default_apps.refresh() + } tab.val = i armed.val = -1 hover.val = first_active(rows()) @@ -422,6 +460,11 @@ fn act(rs : Array[Row], i : Int, btn~ : Int = -1, x~ : Int = 0) -> Unit { @shortcuts.capture(k.reinterpret_as_uint()) } ResetShortcuts => @shortcuts.reset_all() + AppKind(c, _, _, _, n) => expanded.val = if expanded.val == c || n == 0 { -1 } else { c } + AppOption(c, k, _) => { + @default_apps.set_default(c.reinterpret_as_uint(), k.reinterpret_as_uint()) + expanded.val = -1 + } Setting(k, _) => { let idx = k.reinterpret_as_uint() @settings.set_setting(idx, !@settings.is_on(idx)) @@ -440,6 +483,28 @@ fn act(rs : Array[Row], i : Int, btn~ : Int = -1, x~ : Int = 0) -> Unit { } } +///| An app's icon with its left edge at `x`, centred on `mid`: the host's image, or a rounded +/// square with the name's first letter. +fn app_icon_ops( + x : Int, + mid : Int, + a : @default_apps.AppChoice, + fg : @types.Color, +) -> Array[@types.DrawOp] { + let r = @ui.rect(x, mid - icon_size / 2, icon_size, icon_size) + if a.icon != 0U { + return [Image({ rect: r, image: a.icon })] + } + let glyph = match a.name.to_array().get(0) { + Some(ch) => ch.to_string().to_upper() + None => "?" + } + [ + @ui.stroke_rect(r, @ui.with_alpha(fg, 120), width=1, radius=4), + @ui.text(x + icon_size / 2, mid, glyph, 10, fg, align=CENTER, bold=true), + ] +} + ///| Move the highlight by `step` rows, skipping headings; stays put at either end. fn move_hover(step : Int) -> Unit { let rs = rows() @@ -678,6 +743,50 @@ pub fn popup() -> PopupSurface? { } } ResetShortcuts => ops.push(@ui.text(margin + 10, mid, "Reset all to defaults", fs - 1, list_fg, bold=true)) + AppKind(c, name, cur, cur_name, n) => { + let open = expanded.val == c + ops.push(@ui.text(margin + 10, mid, name, fs - 1, list_fg, bold=open)) + // The current app at the right, then a chevron (down while its list is open). + let cx = w - margin - 14 + let cfg = if hot { list_fg } else { p.foreground_muted } + if n > 0 { + if open { + ops.push(@ui.line(cx - 4, mid - 2, cx, mid + 2, cfg, width=2)) + ops.push(@ui.line(cx, mid + 2, cx + 4, mid - 2, cfg, width=2)) + } else { + ops.push(@ui.line(cx - 2, mid - 4, cx + 2, mid, cfg, width=2)) + ops.push(@ui.line(cx + 2, mid, cx - 2, mid + 4, cfg, width=2)) + } + } + let right = cx - 12 + match cur { + Some(a) => { + let label = a.name + ops.push(@ui.text(right, mid, label, fs - 2, list_fg, align=RIGHT)) + let tw = @ui.text_width(label, fs - 2) + ops.append(app_icon_ops(right - tw - 6 - icon_size, mid, a, list_fg)) + } + None => { + let label = if cur_name != "" { + cur_name + } else if n == 0 { + "None installed" + } else { + "Not set" + } + ops.push(@ui.text(right, mid, label, fs - 2, if hot { list_fg } else { p.foreground_muted }, align=RIGHT)) + } + } + } + AppOption(_, _, a) => { + let x = margin + 26 + if a.current { + ops.push(@ui.line(margin + 10, mid, margin + 13, mid + 4, list_fg, width=2)) + ops.push(@ui.line(margin + 13, mid + 4, margin + 20, mid - 4, list_fg, width=2)) + } + ops.append(app_icon_ops(x, mid, a, list_fg)) + ops.push(@ui.text(x + icon_size + 8, mid, a.name, fs - 1, list_fg, bold=a.current)) + } } } Some({ size: { w: w.reinterpret_as_uint(), h: h.reinterpret_as_uint() }, ops }) @@ -802,7 +911,7 @@ pub fn on_event(target : Surface, event : @types.InputEvent) -> Bool { } else if k == "ArrowLeft" || k == "Left" { set_tab((tab.val + tab_names.length() - 1) % tab_names.length()) true - } else if k == "1" || k == "2" || k == "3" || k == "4" || k == "5" { + } else if k == "1" || k == "2" || k == "3" || k == "4" || k == "5" || k == "6" { set_tab(k[0].to_int() - '1'.to_int()) true } else { diff --git a/compositor/host/default_apps_test.mbt b/compositor/host/default_apps_test.mbt new file mode 100644 index 0000000..020a89a --- /dev/null +++ b/compositor/host/default_apps_test.mbt @@ -0,0 +1,237 @@ +///| Default apps: a temporary XDG tree (applications, mimeinfo.cache, mimeapps.list, +/// xdg-terminals.list), the categories' choices and current defaults, setting them (other entries +/// kept), the terminal choice, and the settings module's Apps tab. + +///| +fn da_write(path : String, text : String) -> Unit { + let slash = path.rev_find("/").unwrap() + ignore(@sys.mkdir_p(path[:slash].to_string())) + ignore(@sys.write_file_bytes(path, @sys.str_to_utf8_bytes(text))) +} + +///| +fn da_read(path : String) -> String { + let raw = @sys.read_file_bytes(path) + let sb = StringBuilder::new() + for i = 0; i < raw.length(); i = i + 1 { + sb.write_char(Int::unsafe_to_char(raw[i].to_int())) // the files are ASCII + } + sb.to_string() +} + +///| A desktop entry. +fn da_app(name : String, exec : String, mimes : String, cats : String, extra? : String = "") -> String { + "[Desktop Entry]\nType=Application\nName=" + + name + + "\nExec=" + + exec + + "\nMimeType=" + + mimes + + "\nCategories=" + + cats + + "\n" + + extra +} + +///| A fresh XDG tree under /tmp: user config + data, one system config dir, one system data dir. +fn da_tree(tag : String) -> (String, @shell.XdgDirs) { + let root = "/tmp/chandra-default-apps-" + tag + "-" + @sys.getpid().to_string() + let sys = root + "/usr/share/applications" + da_write(sys + "/firefox.desktop", da_app("Firefox", "firefox %u", "text/html;x-scheme-handler/http;x-scheme-handler/https;image/png;application/pdf;", "Network;WebBrowser;")) + da_write(sys + "/chromium.desktop", da_app("Chromium", "chromium %U", "text/html;x-scheme-handler/http;x-scheme-handler/https;", "Network;WebBrowser;")) + da_write(sys + "/thunderbird.desktop", da_app("Thunderbird", "thunderbird %u", "x-scheme-handler/mailto;message/rfc822;", "Network;Email;")) + da_write(sys + "/org.gnome.Nautilus.desktop", da_app("Files", "nautilus --new-window %U", "inode/directory;", "GNOME;Utility;FileManager;")) + da_write(sys + "/foot.desktop", da_app("Foot", "foot", "", "System;TerminalEmulator;")) + da_write(sys + "/kitty.desktop", da_app("kitty", "kitty", "", "System;TerminalEmulator;")) + da_write(sys + "/org.gnome.gedit.desktop", da_app("Text Editor", "gedit %U", "text/plain;text/markdown;", "Utility;TextEditor;")) + da_write(sys + "/eog.desktop", da_app("Image Viewer", "eog %U", "image/png;image/jpeg;", "Graphics;Viewer;")) + da_write(sys + "/vlc.desktop", da_app("VLC", "vlc %U", "video/mp4;audio/mpeg;", "AudioVideo;")) + da_write(sys + "/evince.desktop", da_app("Document Viewer", "evince %U", "application/pdf;", "Office;Viewer;")) + da_write(sys + "/evince-previewer.desktop", da_app("Print Preview", "evince-previewer %U", "application/pdf;", "Office;", extra="NoDisplay=true\n")) + da_write(sys + "/htop.desktop", "[Desktop Entry]\nType=Application\nName=htop\nExec=htop\nTerminal=true\nCategories=System;Monitor;\n") + // The system's cache says Chromium for mail links (it doesn't handle them: not installed for + // that), Files for folders. + da_write(sys + "/mimeinfo.cache", "[MIME Cache]\ninode/directory=org.gnome.Nautilus.desktop;\napplication/pdf=evince-previewer.desktop;evince.desktop;\n") + // A system-wide default: VLC for video. + da_write(root + "/etc/xdg/mimeapps.list", "[Default Applications]\nvideo/mp4=vlc.desktop\n") + // The user's own file: Chromium for web pages, a removed viewer for PNGs, notes to keep. + da_write( + root + "/config/mimeapps.list", + "# mine\n[Added Associations]\ntext/plain=org.gnome.gedit.desktop;\n\n[Default Applications]\ntext/html=chromium.desktop;\nx-scheme-handler/http=chromium.desktop;\nimage/png=gthumb.desktop;eog.desktop;\n\n[Removed Associations]\nx-scheme-handler/https=firefox.desktop;\n", + ) + da_write(root + "/config/xdg-terminals.list", "# preferred\nfoot.desktop\n") + let dirs : @shell.XdgDirs = { + config_home: root + "/config", + config_dirs: [root + "/etc/xdg"], + data_home: root + "/home-data", + data_dirs: [root + "/usr/share"], + desktops: ["chandra"], + } + (root, dirs) +} + +///| +fn da_cat(id : String) -> Int { + let mut n = -1 + for i, c in @shell.app_categories { + if c.id == id { + n = i + } + } + n +} + +///| +fn da_names(ch : @shell.CategoryChoices) -> Array[String] { + ch.apps.map(a => a.name) +} + +///| +test "each category lists its installed apps and reads the current default" { + let (_, dirs) = da_tree("read") + let installed = @shell.scan_handler_apps(dirs) + let ch = @shell.default_app_choices(dirs, installed, "") + assert_eq(ch.length(), @shell.app_categories.length()) + // Browsers: both, by name; the user's file says Chromium. + let b = ch[da_cat("browser")] + assert_eq(da_names(b), ["Chromium", "Firefox"]) + assert_eq(b.current_id, "chromium") + assert_eq(b.current, 0) + assert_eq(b.missing, "") + // Firefox handles PNGs and PDFs but is only a browser. + assert_eq(da_names(ch[da_cat("images")]), ["Image Viewer"]) + // PNGs: gThumb was chosen but is gone; the next entry, Image Viewer, is used. + assert_eq(ch[da_cat("images")].current_id, "eog") + assert_eq(ch[da_cat("images")].missing, "gthumb") + // Mail: no default anywhere, the only app that handles it. + assert_eq(ch[da_cat("email")].current_id, "thunderbird") + // Folders: from mimeinfo.cache. + assert_eq(ch[da_cat("files")].current_id, "org.gnome.Nautilus") + // Video: the system-wide mimeapps.list in XDG_CONFIG_DIRS. + assert_eq(ch[da_cat("video")].current_id, "vlc") + assert_eq(da_names(ch[da_cat("music")]), ["VLC"]) + // PDFs: the cache's first entry is hidden from menus but installed, so it is the default; + // only the shown viewer is offered. + assert_eq(ch[da_cat("documents")].current_id, "evince-previewer") + assert_eq(ch[da_cat("documents")].current, -1) + assert_eq(da_names(ch[da_cat("documents")]), ["Document Viewer"]) + // Text: Added Associations. + assert_eq(ch[da_cat("editor")].current_id, "org.gnome.gedit") + // Terminal: xdg-terminals.list says foot. + let t = ch[da_cat("terminal")] + assert_eq(da_names(t), ["Foot", "kitty"]) + assert_eq(t.current_id, "foot") + // Nothing handles archives. + assert_eq(ch[da_cat("archives")].apps.length(), 0) + assert_eq(ch[da_cat("archives")].current_id, "") + // The terminal chosen in state.edn wins; a chosen one that is gone is reported. + assert_eq(@shell.current_terminal(dirs, installed, "kitty"), ("kitty", "")) + assert_eq(@shell.current_terminal(dirs, installed, "alacritty"), ("foot", "alacritty")) +} + +///| +test "setting a default writes mimeapps.list and keeps everything else" { + let (root, dirs) = da_tree("write") + // A desktop-specific file that names a browser would win over mimeapps.list: it is updated too. + da_write(root + "/config/chandra-mimeapps.list", "[Default Applications]\ntext/html=chromium.desktop;\napplication/pdf=evince.desktop;\n") + let comp = new_comp("da-write") + comp.shell.xdg_dirs = dirs + comp.shell.refresh_default_apps() + let b = da_cat("browser") + assert_eq(comp.shell.default_app_choices()[b].current_id, "chromium") + assert_true(comp.shell.set_default_app(b, 1)) // Firefox + assert_eq(comp.shell.default_app_choices()[b].current_id, "firefox") + assert_eq( + da_read(root + "/config/mimeapps.list"), + "# mine\n[Added Associations]\ntext/plain=org.gnome.gedit.desktop;\n\n[Default Applications]\ntext/html=firefox.desktop;\nx-scheme-handler/http=firefox.desktop;\nimage/png=gthumb.desktop;eog.desktop;\nx-scheme-handler/https=firefox.desktop;\n\n[Removed Associations]\n", + ) + assert_eq( + da_read(root + "/config/chandra-mimeapps.list"), + "[Default Applications]\ntext/html=firefox.desktop;\napplication/pdf=evince.desktop;\nx-scheme-handler/http=firefox.desktop;\nx-scheme-handler/https=firefox.desktop;\n", + ) + // Picking the image viewer again clears the missing gThumb. + let im = da_cat("images") + assert_true(comp.shell.set_default_app(im, 0)) + assert_eq(comp.shell.default_app_choices()[im].missing, "") + assert_true(da_read(root + "/config/mimeapps.list").contains("image/png=eog.desktop;\nx-scheme-handler/https=firefox.desktop;\nimage/jpeg=eog.desktop;\n")) + // Out of range: nothing happens. + assert_false(comp.shell.set_default_app(im, 5)) + assert_false(comp.shell.set_default_app(99, 0)) +} + +///| +test "the terminal choice runs terminal apps and goes first in xdg-terminals.list" { + let (root, dirs) = da_tree("term") + let comp = new_comp("da-term") + comp.shell.xdg_dirs = dirs + comp.shell.refresh_default_apps() + assert_eq(comp.shell.in_terminal("htop"), "foot -e htop") + let t = da_cat("terminal") + assert_true(comp.shell.set_default_app(t, 1)) // kitty + assert_eq(comp.shell.terminal, "kitty") + assert_eq(comp.shell.in_terminal("htop"), "kitty htop") + assert_eq(da_read(root + "/config/xdg-terminals.list"), "kitty.desktop\n# preferred\nfoot.desktop\n") + assert_true(comp.shell.set_default_app(t, 0)) // foot + assert_eq(da_read(root + "/config/xdg-terminals.list"), "foot.desktop\nkitty.desktop\n# preferred\n") +} + +///| +test "the settings module's Apps tab shows each kind's default and sets it" { + let (root, dirs) = da_tree("tab") + let comp = new_comp("da-tab") + comp.shell.xdg_dirs = dirs + let slot = comp.shell.slot_of("session-settings") + assert_true(comp.shell.open_settings(Apps)) + ignore(comp.compose_frame()) + // Ten kinds, plus the line saying gThumb is gone. + let kinds = @shell.app_categories.length() + let pr = comp.shell.slot_popup_rect(slot) + assert_eq(pr.h, 40 + (kinds + 1) * 28 + 6) + let texts = comp.shell.slot_popup_texts(slot).map(t => t.0) + assert_true(texts.contains("Web browser")) + assert_true(texts.contains("Chromium")) + assert_true(texts.contains("! gthumb is not installed any more")) + assert_true(texts.contains("None installed")) + // Row i's middle (the popup grows upwards from the panel, so read where it is now). + let row_y = fn(i : Int) { comp.shell.slot_popup_rect(slot).y + 40 + i * 28 + 13 } + // Click "Web browser": its two apps are listed under it. + ignore(@sys.write_file_bytes("_build/default_apps_tab.png", @renderer.encode_png(comp.compose_frame()))) + click_at(comp, pr.x + 40, row_y(0), 5U) + assert_eq(comp.shell.slot_popup_rect(slot).h, pr.h + 2 * 28) + ignore(@sys.write_file_bytes("_build/default_apps_open.png", @renderer.encode_png(comp.compose_frame()))) + assert_true(comp.shell.slot_popup_texts(slot).map(t => t.0).contains("Firefox")) + // Click Firefox: it is the browser now, and the list folds up. + click_at(comp, pr.x + 60, row_y(2), 10U) + ignore(comp.compose_frame()) + assert_eq(comp.shell.default_app_choices()[da_cat("browser")].current_id, "firefox") + assert_true(da_read(root + "/config/mimeapps.list").contains("text/html=firefox.desktop;")) + assert_eq(comp.shell.slot_popup_rect(slot).h, pr.h) + assert_true(comp.shell.slot_popup_texts(slot).map(t => t.0).contains("Firefox")) + // A kind with nothing installed doesn't open. + let arch = da_cat("archives") + 1 // under the gThumb line + click_at(comp, pr.x + 40, row_y(arch), 20U) + assert_eq(comp.shell.slot_popup_rect(slot).h, pr.h) +} + +///| +test "the chosen terminal is saved to state.edn and restored" { + if @sys.getenv("CHANDRA_TEST_CONFIG") == "1" { + write_state_edn("{:note \"keep\"}\n") + let (_, dirs) = da_tree("save") + let a = new_comp("da-save-a") + a.shell.persist = true + a.restore_state() + a.shell.xdg_dirs = dirs + a.shell.refresh_default_apps() + assert_true(a.shell.set_default_app(da_cat("terminal"), 1)) + let text = read_state_edn() + assert_true(text.contains(":terminal \"kitty\"")) + assert_true(text.contains(":note \"keep\"")) + let b = new_comp("da-save-b") + b.shell.persist = true + b.shell.xdg_dirs = dirs + b.restore_state() + assert_eq(b.shell.terminal, "kitty") + assert_eq(b.shell.default_app_choices()[da_cat("terminal")].current_id, "kitty") + } +} diff --git a/compositor/shell/apps.mbt b/compositor/shell/apps.mbt index 8bf4da7..31adba8 100644 --- a/compositor/shell/apps.mbt +++ b/compositor/shell/apps.mbt @@ -12,6 +12,10 @@ priv struct DesktopApp { 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 } ///| Directories scanned, lowest priority first (later ones override by file name). @@ -56,80 +60,51 @@ fn clean_exec(exec : String) -> String { sb.to_string().trim(chars=" ").to_string() } -///| Parse one .desktop file; None when it should not be listed. +///| 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 mut in_entry = false - let mut name = "" - let mut generic = "" - let mut comment = "" - let mut exec = "" - let mut cats = "" - let mut hidden = false - let mut terminal = false - let mut kind = "Application" - let mut wm_class = "" - let mut icon = "" - 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) => { - let key = line[:eq].trim(chars=" ").to_string() - let val = line[eq + 1:].trim(chars=" ").to_string() - match key { - "Name" => name = val - "GenericName" => generic = val - "Comment" => comment = val - "Exec" => exec = val - "Categories" => cats = val - "Type" => kind = val - "NoDisplay" | "Hidden" => if val == "true" { hidden = true } - "Terminal" => terminal = val == "true" - "StartupWMClass" => wm_class = val - "Icon" => icon = val - _ => () - } - } - } - } + 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 mut command = clean_exec(exec) - if terminal { - command = "foot -e " + command - } + let cats = get("Categories") let category = match cats.split(";").next() { Some(c) if c.length() > 0 => c.to_string() _ => "Other" } - let comment = if comment.length() > 0 { comment } else { generic } - Some({ id, name, comment, category, command, wm_class, icon }) + 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"), + }) } ///| Scan every applications dir; later dirs override earlier ones, result sorted by name. fn scan_desktop_apps() -> Array[DesktopApp] { - let have_terminal = @sys.has_exe("foot") let by_id : Map[String, DesktopApp] = {} let removed : Map[String, Bool] = {} for dir in app_dirs() { 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), have_terminal) { + match parse_desktop(id, @utf8.decode_lossy(bytes), true) { Some(app) => { by_id.set(id, app) removed.remove(id) @@ -140,9 +115,16 @@ fn scan_desktop_apps() -> Array[DesktopApp] { } } } + // 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 { - apps.push(a) + if have_terminal || !a.terminal { + apps.push(a) + } } apps.sort_by(fn(a, b) { let x = a.name.to_lower() diff --git a/compositor/shell/default_apps.mbt b/compositor/shell/default_apps.mbt new file mode 100644 index 0000000..ecc0b9e --- /dev/null +++ b/compositor/shell/default_apps.mbt @@ -0,0 +1,887 @@ +///| 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, as the launcher scans them (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 (the launcher's `app_dirs` lists them lowest 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.. { + 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"]) +} diff --git a/compositor/shell/icons.mbt b/compositor/shell/icons.mbt index 6c2b437..89df731 100644 --- a/compositor/shell/icons.mbt +++ b/compositor/shell/icons.mbt @@ -110,6 +110,21 @@ fn DesktopShell::app_icon(self : DesktopShell, app_id : String) -> UInt { h } +///| The image handle of desktop app `id`'s icon (Icon= value `icon`), sharing `app_icon`'s cache. +fn DesktopShell::desktop_icon(self : DesktopShell, id : String, icon : String) -> UInt { + match self.icon_handles.get(id) { + Some(h) => return h + None => () + } + let name = if icon.length() > 0 { icon } else { id } + let h = match find_icon_file(name, @sys.host_raster()) { + Some(path) => @raster.load_image(path) + None => 0U + } + self.icon_handles.set(id, h) + h +} + ///| The image handle of the app icon for a window with `app_id` (0: none), for the compositor's /// own UI (the Alt+Tab switcher). pub fn DesktopShell::window_icon(self : DesktopShell, app_id : String) -> UInt { diff --git a/compositor/shell/shell.mbt b/compositor/shell/shell.mbt index 600ec81..00bac63 100644 --- a/compositor/shell/shell.mbt +++ b/compositor/shell/shell.mbt @@ -280,6 +280,17 @@ pub(all) struct DesktopShell { shortcuts : Shortcuts /// The shortcut waiting for its new combo from the Shortcuts tab (-1: none). mut shortcut_capture : Int + /// Default apps (default_apps.mbt): where mimeapps.list and the .desktop files are, the + /// installed apps (scanned on first use and on the Apps tab's refresh) and each category's + /// choices, and whether they still need publishing. + mut xdg_dirs : XdgDirs + mut handler_apps : Map[String, HandlerApp]? + mut default_apps : Array[CategoryChoices] + mut default_apps_dirty : Bool + /// The terminal chosen in the Apps tab (desktop id; "" for none), saved as state.edn :terminal. + mut terminal : String + /// Desktop ids of Terminal=true apps, started inside the terminal. + terminal_apps : Map[String, Bool] mut desk_set : Bool mut desk_x : Int mut desk_y : Int @@ -343,7 +354,11 @@ pub fn DesktopShell::new(display : String) -> DesktopShell { let exec : Map[String, String] = {} let wm_classes : Map[String, String] = {} let icon_names : Map[String, String] = {} + let terminal_apps : Map[String, Bool] = {} for a in scan_desktop_apps() { + if a.terminal { + terminal_apps.set(a.id, true) + } if a.icon.length() > 0 { icon_names.set(a.id, a.icon) } @@ -387,6 +402,12 @@ pub fn DesktopShell::new(display : String) -> DesktopShell { suspend_min: default_suspend_min, shortcuts: Shortcuts::defaults(), shortcut_capture: -1, + xdg_dirs: XdgDirs::from_env(), + handler_apps: None, + default_apps: [], + default_apps_dirty: true, + terminal: "", + terminal_apps, desk_set: false, desk_x: 0, desk_y: 0, diff --git a/compositor/shell/state.mbt b/compositor/shell/state.mbt index f4f4f43..678cf8b 100644 --- a/compositor/shell/state.mbt +++ b/compositor/shell/state.mbt @@ -12,6 +12,8 @@ /// :shortcuts {:show-desktop "Super+Ctrl+D" :screenshot-full ""} /// ; keyboard shortcuts changed from their defaults ("" unbinds; /// ; ids and combo syntax in shortcuts.mbt) +/// :terminal "kitty" ; the Apps tab's terminal (desktop file id) for terminal apps +/// ; (absent: xdg-terminals.list, else foot; see default_apps.mbt) /// :session [{:app "foot"} {:app "org.gnome.Nautilus" :minimized true}] /// ; the windows open when the last session ended, reopened at /// ; the next start (see session.mbt in compositor/host) @@ -43,6 +45,8 @@ pub(all) struct SavedState { power : (Int?, Int?) /// From `:shortcuts`: (id, combo text) pairs; empty when the file doesn't say. shortcuts : Array[(String, String)] + /// From `:terminal`: the chosen terminal's desktop id. + terminal : String? } ///| @@ -56,7 +60,7 @@ let layout_names : Array[String] = ["tiling", "monocle", "floating"] ///| The keys this build owns; everything else in the file is kept as it is. let owned_keys : Array[String] = [ "layout", "recent", "desktop-card", "windows", "wallpaper", "restore-session", "remember-windows", - "theme", "power", "shortcuts", + "theme", "power", "shortcuts", "terminal", ] ///| How state.edn names each wallpaper, in `@libshell.wallpaper_names` order. @@ -103,6 +107,7 @@ pub fn DesktopShell::load_state(self : DesktopShell) -> SavedState { dark_mode: None, power: (None, None), shortcuts: [], + terminal: None, } } let entries = read_state_file() @@ -214,6 +219,10 @@ pub fn DesktopShell::load_state(self : DesktopShell) -> SavedState { } _ => (None, None) }, + terminal: match lookup_key(entries, "terminal") { + Some(Text(t)) if t.length() > 0 => Some(t) + _ => None + }, shortcuts: match lookup_key(entries, "shortcuts") { Some(Mapping(m)) => { let out : Array[(String, String)] = [] @@ -265,6 +274,16 @@ pub fn DesktopShell::apply_state(self : DesktopShell, st : SavedState) -> Unit { _ => () } self.shortcuts.apply_saved(st.shortcuts) + match st.terminal { + Some(t) => { + self.terminal = t + self.default_apps_dirty = true + if self.handler_apps is Some(_) { + self.refresh_default_apps() + } + } + None => () + } match st.desk { Some((x, y)) => { self.desk_set = true @@ -343,6 +362,9 @@ pub fn DesktopShell::save_state(self : DesktopShell) -> Unit { (@edn.Value::Keyword("suspend"), @edn.Value::Integer(self.suspend_min.to_string())), ]))) } + if self.terminal.length() > 0 { + entries.insert(2, (@edn.Value::Keyword("terminal"), @edn.Value::Text(self.terminal))) + } let changed = self.shortcuts.changed() if changed.length() > 0 { entries.insert(2, (@edn.Value::Keyword("shortcuts"), @edn.Value::Mapping( @@ -498,7 +520,7 @@ pub fn DesktopShell::save_session(self : DesktopShell, session : Array[SessionEn pub fn DesktopShell::launch_app_id(self : DesktopShell, app_id : String) -> Bool { match resolve_app_id(app_id, self.exec, self.wm_classes) { Some(id) => - match self.exec.get(id) { + match self.command_for(id) { Some(cmd) => @sys.spawn(cmd, self.display) None => false } diff --git a/compositor/shell/widgets.mbt b/compositor/shell/widgets.mbt index 9ac380e..cca6766 100644 --- a/compositor/shell/widgets.mbt +++ b/compositor/shell/widgets.mbt @@ -654,6 +654,9 @@ fn DesktopShell::publish_host_data(self : DesktopShell) -> Unit { if self.widgets.iter().any(w => w.has_cap("shortcuts")) { self.publish_shortcuts() } + if self.widgets.iter().any(w => w.has_cap("default-apps")) { + self.publish_default_apps() + } if self.widgets.iter().any(w => w.has_cap("screenshot")) { @wasm.publish_screenshot(self.screenshot_state) } @@ -756,7 +759,7 @@ fn DesktopShell::process_requests(self : DesktopShell) -> Unit { match @wasm.next_request() { None => break Some(Launch(id)) => { - match self.exec.get(id) { + match self.command_for(id) { Some(bin) => if @sys.spawn(bin, self.display) { self.note_recent(id) @@ -781,6 +784,7 @@ fn DesktopShell::process_requests(self : DesktopShell) -> Unit { Some(SetScreenOff(m)) => self.set_power_timeouts(m, self.suspend_min) Some(SetSuspendAfter(m)) => self.set_power_timeouts(self.screen_off_min, m) Some(Shortcut(code)) => self.shortcut_request(code) + Some(DefaultApp(code)) => self.default_app_request(code) Some(PowerAction(a)) => if a >= 0 && a <= 2 { self.actions.push(SystemPower(a)) } Some(Network(code, ssid, password)) => self.network_request(code, ssid, password) Some(SetInspector(on)) => self.set_inspecting(on) @@ -873,6 +877,8 @@ pub(all) enum SettingsTab { Power /// The keyboard shortcuts: rebind, reset. Shortcuts + /// Default apps: browser, email, file manager, terminal, editor, viewers and players. + Apps } derive(Eq, Debug) ///| Open the settings module ("System settings") on `tab`, loading it into the panel first if it @@ -901,13 +907,14 @@ pub fn DesktopShell::open_settings(self : DesktopShell, tab : SettingsTab) -> Bo if w.popup_rect.w == 0 { ignore(self.deliver(w, false, PointerDown(0, 0))) } - // The module's keys 1-5 pick its tabs. + // The module's keys 1-6 pick its tabs. let key = match tab { Session => "1" Desktop => "2" Panel => "3" Power => "4" Shortcuts => "5" + Apps => "6" } ignore(self.deliver(w, true, KeyDown(key))) self.save_panel_config() diff --git a/compositor/wasm/wasm_host.mbt b/compositor/wasm/wasm_host.mbt index 187a351..915e0b1 100644 --- a/compositor/wasm/wasm_host.mbt +++ b/compositor/wasm/wasm_host.mbt @@ -305,6 +305,10 @@ pub(all) enum HostTable { NetNetworks /// Keyboard shortcuts (ssssi: name binding default-binding conflict capturing). Shortcuts + /// Default-app categories (sss: name current missing). + AppCategories + /// Default-app choices (issii: category id name icon current). + AppChoices } ///| @@ -330,6 +334,8 @@ pub fn publish(which : HostTable, t : Table) -> Unit { NetStatus => 8U NetNetworks => 9U Shortcuts => 10U + AppCategories => 11U + AppChoices => 12U } // Most tables are republished every frame unchanged: skip the copy into the host then. let slot = id.reinterpret_as_int() @@ -405,6 +411,9 @@ pub(all) enum HostRequest { /// The shortcuts capability: action * 1000 + index (0 capture, 1 reset, 2 reset all, 3 cancel /// the capture). Shortcut(Int) + /// The default-apps capability: category * 1000 + app sets that category's default, -1 scans + /// the apps and defaults again. + DefaultApp(Int) /// The session capability's `reload`: reload every loaded panel module from disk. ReloadSession } derive(Eq, Debug) @@ -430,6 +439,7 @@ pub fn next_request() -> HostRequest? { Some(PowerAction(a)) => Some(PowerAction(a)) Some(Network(r)) => Some(Network(r.action, r.ssid, r.password)) Some(Shortcut(code)) => Some(Shortcut(code)) + Some(DefaultApp(code)) => Some(DefaultApp(code)) Some(ReloadSession) => Some(ReloadSession) } } diff --git a/compositor/wasm/wasm_native.mbt b/compositor/wasm/wasm_native.mbt index adfc6df..21560bd 100644 --- a/compositor/wasm/wasm_native.mbt +++ b/compositor/wasm/wasm_native.mbt @@ -697,6 +697,10 @@ pub(all) enum HostTable { NetNetworks /// Keyboard shortcuts (ssssi: name binding default-binding conflict capturing). Shortcuts + /// Default-app categories (sss: name current missing). + AppCategories + /// Default-app choices (issii: category id name icon current). + AppChoices } ///| Publish `t` as the data behind `which` for every module's next call. @@ -713,6 +717,8 @@ pub fn publish(which : HostTable, t : Table) -> Unit { NetStatus => 8 NetNetworks => 9 Shortcuts => 10 + AppCategories => 11 + AppChoices => 12 } let out : Array[Byte] = [] for k = 0; k < 4; k = k + 1 { @@ -787,6 +793,9 @@ pub(all) enum HostRequest { /// The shortcuts capability: action * 1000 + index (0 capture, 1 reset, 2 reset all, 3 cancel /// the capture). Shortcut(Int) + /// The default-apps capability: category * 1000 + app sets that category's default, -1 scans + /// the apps and defaults again. + DefaultApp(Int) /// The session capability's `reload`: reload every loaded panel module from disk. ReloadSession } derive(Eq, Debug) @@ -829,6 +838,7 @@ pub fn next_request() -> HostRequest? { } } 18 => Some(Shortcut(c_host_req_int())) + 19 => Some(DefaultApp(c_host_req_int())) _ => None } } diff --git a/compositor/wasm/wasm_stub.c b/compositor/wasm/wasm_stub.c index aaa4718..21845ed 100644 --- a/compositor/wasm/wasm_stub.c +++ b/compositor/wasm/wasm_stub.c @@ -60,14 +60,15 @@ enum { K_BAT_READ, K_NET_STATUS, K_NET_LIST, K_NET_SCAN, K_NET_CONNECT, K_NET_DISCONNECT, K_NET_FORGET, K_NET_SET_WIFI, K_NET_SET_AIRPLANE, - K_SC_LIST, K_SC_CAPTURE, K_SC_CANCEL, K_SC_RESET, K_SC_RESET_ALL + K_SC_LIST, K_SC_CAPTURE, K_SC_CANCEL, K_SC_RESET, K_SC_RESET_ALL, + K_DA_CATS, K_DA_APPS, K_DA_SET, K_DA_REFRESH }; typedef struct Env { Inst *inst; int kind; } Env; /* ---- host data the shell publishes before calling a guest ---- * A table is [u32 rows] then rows of fields, each field a LE i32 ('i') or a u32 byte length + UTF-8 ('s'). */ enum { T_APPS, T_WINDOWS, T_LAYOUTS, T_MODULES, T_INSTANCES, T_WALLPAPERS, T_SESSION_SETTINGS, T_ICONS, - T_NET_STATUS, T_NET_NETWORKS, T_SHORTCUTS, T_N }; + T_NET_STATUS, T_NET_NETWORKS, T_SHORTCUTS, T_APP_CATS, T_APP_CHOICES, T_N }; typedef struct { uint8_t *data; size_t len; } Blob; static Blob tables[T_N]; static int32_t host_ints[12] = {[7] = -1}; /* 0 layout mode, 1 inspector on, 2 current wallpaper, 3 session settings on (bit i: row i), @@ -402,6 +403,12 @@ static wasm_trap_t *host_import(void *env, const wasm_val_vec_t *args, wasm_val_ case K_SC_RESET: if (a0 >= 0 && a0 < 1000) push_req(18, 1000 + a0, NULL); break; case K_SC_RESET_ALL: push_req(18, 2000, NULL); break; case K_SC_CANCEL: push_req(18, 3000, NULL); break; + /* Default apps: categories from table 11 (name current missing), choices from table 12 (category id name + * icon current); request 19 is category * 1000 + app, or -1 to scan again. */ + case K_DA_CATS: build_list(in, T_APP_CATS, "sss", a0); break; + case K_DA_APPS: build_list(in, T_APP_CHOICES, "issib", a0); break; + case K_DA_SET: if (a0 >= 0 && a0 < 1000 && a1 >= 0 && a1 < 1000) push_req(19, a0 * 1000 + a1, NULL); break; + case K_DA_REFRESH: push_req(19, -1, NULL); break; case K_NET_SCAN: push_req(16, 0, NULL); break; case K_NET_DISCONNECT: push_req(16, 1, NULL); break; case K_NET_SET_WIFI: push_req(16, a0 ? 3 : 2, NULL); break; @@ -603,6 +610,10 @@ static int classify_import(const wasm_name_t *m, const wasm_name_t *f) { if (!strcmp(iface, "shortcuts") && !strcmp(fn, "cancel-capture")) return K_SC_CANCEL; if (!strcmp(iface, "shortcuts") && !strcmp(fn, "reset")) return K_SC_RESET; if (!strcmp(iface, "shortcuts") && !strcmp(fn, "reset-all")) return K_SC_RESET_ALL; + if (!strcmp(iface, "default-apps") && !strcmp(fn, "categories")) return K_DA_CATS; + if (!strcmp(iface, "default-apps") && !strcmp(fn, "apps")) return K_DA_APPS; + if (!strcmp(iface, "default-apps") && !strcmp(fn, "set-default")) return K_DA_SET; + if (!strcmp(iface, "default-apps") && !strcmp(fn, "refresh")) return K_DA_REFRESH; if (!strcmp(iface, "network") && !strcmp(fn, "status")) return K_NET_STATUS; if (!strcmp(iface, "network") && !strcmp(fn, "wifi-networks")) return K_NET_LIST; if (!strcmp(iface, "network") && !strcmp(fn, "scan")) return K_NET_SCAN; diff --git a/host-wasm/src/main.rs b/host-wasm/src/main.rs index 3a4e161..ebce073 100644 --- a/host-wasm/src/main.rs +++ b/host-wasm/src/main.rs @@ -277,6 +277,7 @@ impl chandra::host::plasmoids::Host for State { R::Network(chandra::host::plasmoids::NetworkRequest { action, ssid, password }) } Req::Shortcut(code) => R::Shortcut(code), + Req::DefaultApp(code) => R::DefaultApp(code), }) } diff --git a/host-wasm/src/plasmoid.rs b/host-wasm/src/plasmoid.rs index 67a2616..a3bfe48 100644 --- a/host-wasm/src/plasmoid.rs +++ b/host-wasm/src/plasmoid.rs @@ -61,6 +61,8 @@ pub enum Req { Network(i32, String, String), /// A shortcuts request: action * 1000 + index (0 capture, 1 reset, 2 reset all, 3 cancel). Shortcut(i32), + /// A default-apps request: category * 1000 + app sets a default, -1 scans again. + DefaultApp(i32), } pub const T_APPS: usize = 0; @@ -78,11 +80,15 @@ pub const T_NET_STATUS: usize = 8; pub const T_NET_NETWORKS: usize = 9; /// Keyboard shortcuts (ssssi): name binding default-binding conflict capturing. pub const T_SHORTCUTS: usize = 10; +/// Default-app categories (sss): name current missing. +pub const T_APP_CATS: usize = 11; +/// Default-app choices (issii): category id name icon current. +pub const T_APP_CHOICES: usize = 12; /// Host data every module reads from, shared by all loaded modules. #[derive(Default)] pub struct Shared { - pub tables: [Vec; 11], + pub tables: [Vec; 13], pub layout_mode: i32, pub wallpaper: i32, /// Which session settings are on: bit i for row i of the session settings table. @@ -393,6 +399,42 @@ impl d::shortcuts::Host for PState { } } +impl d::default_apps::Host for PState { + fn categories(&mut self) -> Vec { + self.rows(T_APP_CATS, "sss") + .iter() + .filter(|r| r.len() == 3) + .map(|r| d::default_apps::AppCategory { + name: s(&r[0]), + current: s(&r[1]), + missing: s(&r[2]), + }) + .collect() + } + fn apps(&mut self) -> Vec { + self.rows(T_APP_CHOICES, "issii") + .iter() + .filter(|r| r.len() == 5) + .map(|r| d::default_apps::AppChoice { + category: i(&r[0]) as u32, + id: s(&r[1]), + name: s(&r[2]), + icon: i(&r[3]) as u32, + current: i(&r[4]) != 0, + }) + .collect() + } + fn set_default(&mut self, category: u32, app: u32) { + if category < 1000 && app < 1000 { + let code = (category * 1000 + app) as i32; + self.shared.borrow_mut().requests.push_back(Req::DefaultApp(code)); + } + } + fn refresh(&mut self) { + self.shared.borrow_mut().requests.push_back(Req::DefaultApp(-1)); + } +} + impl d::screenshot::Host for PState { fn take(&mut self, mode: u32) { if mode <= 3 { diff --git a/interface/chandra/desktop/default-apps/README.md b/interface/chandra/desktop/default-apps/README.md new file mode 100644 index 0000000..2a8e99e --- /dev/null +++ b/interface/chandra/desktop/default-apps/README.md @@ -0,0 +1,5 @@ +Default applications: which installed app opens web links, mail, folders, text, images, video, +music, documents and archives, kept in the freedesktop mimeapps.list that other apps and +xdg-open follow, and which terminal Chandra runs terminal apps in (state.edn, exported as +xdg-terminals.list). A module with this capability (the settings module's Apps tab) lists the +choices and sets them. \ No newline at end of file diff --git a/interface/chandra/desktop/default-apps/ffi.mbt b/interface/chandra/desktop/default-apps/ffi.mbt new file mode 100644 index 0000000..782bb65 --- /dev/null +++ b/interface/chandra/desktop/default-apps/ffi.mbt @@ -0,0 +1,40 @@ +// Generated by `wit-bindgen` 0.63.0. DO NOT EDIT! + +///| +fn wasmImportCategories(p0 : Int) = "chandra:desktop/default-apps@0.1.0" "categories" + +///| +fn wasmImportApps(p0 : Int) = "chandra:desktop/default-apps@0.1.0" "apps" + +///| +fn wasmImportSetDefault(p0 : Int, p1 : Int) = "chandra:desktop/default-apps@0.1.0" "set-default" + +///| +fn wasmImportRefresh() = "chandra:desktop/default-apps@0.1.0" "refresh" + +///| +extern "wasm" fn mbt_ffi_load32(offset : Int) -> Int = +#|(func (param i32) (result i32) local.get 0 i32.load) + +///| +extern "wasm" fn mbt_ffi_free(position : Int) = +#|(func (param i32) local.get 0 call $moonbit.decref) + +///| +extern "wasm" fn mbt_ffi_load8_u(offset : Int) -> Int = +#|(func (param i32) (result i32) local.get 0 i32.load8_u) + +///| +extern "wasm" fn mbt_ffi_malloc(size : Int) -> Int = +#|(func (param i32) (result i32) (local i32) +#| local.get 0 i32.const 4 i32.add call $moonbit.gc.malloc +#| local.tee 1 i32.const 0 call $moonbit.init_array8 +#| local.get 1) + +///| +extern "wasm" fn mbt_ffi_ptr2str(ptr : Int, len : Int) -> String = +#|(func (param i32) (param i32) (result i32) +#| local.get 0 +#| local.get 1 call $moonbit.init_array16 +#| local.get 0) + diff --git a/interface/chandra/desktop/default-apps/moon.pkg b/interface/chandra/desktop/default-apps/moon.pkg new file mode 100644 index 0000000..e2a6033 --- /dev/null +++ b/interface/chandra/desktop/default-apps/moon.pkg @@ -0,0 +1 @@ +warnings = "-44" diff --git a/interface/chandra/desktop/default-apps/top.mbt b/interface/chandra/desktop/default-apps/top.mbt new file mode 100644 index 0000000..67281a7 --- /dev/null +++ b/interface/chandra/desktop/default-apps/top.mbt @@ -0,0 +1,73 @@ +// Generated by `wit-bindgen` 0.63.0. DO NOT EDIT! +///| +pub(all) struct AppCategory { + name : String; current : String; missing : String +} +///| +pub(all) struct AppChoice { + category : UInt; id : String; name : String; icon : UInt; current : Bool +} +///| +/// The categories, in the order they are shown. +pub fn categories() -> Array[AppCategory] { + + let return_area = mbt_ffi_malloc(8) + wasmImportCategories(return_area); + + let array : Array[AppCategory] = []; + for index = 0; index < (mbt_ffi_load32((return_area) + 4)); index = index + 1 { + let iter_base = (mbt_ffi_load32((return_area) + 0)) + (index * 24) + + let result = mbt_ffi_ptr2str(mbt_ffi_load32((iter_base) + 0), mbt_ffi_load32((iter_base) + 4)) + + let result0 = mbt_ffi_ptr2str(mbt_ffi_load32((iter_base) + 8), mbt_ffi_load32((iter_base) + 12)) + + let result1 = mbt_ffi_ptr2str(mbt_ffi_load32((iter_base) + 16), mbt_ffi_load32((iter_base) + 20)) + + array.push(AppCategory::{name : result, current : result0, missing : result1}) + } + mbt_ffi_free(mbt_ffi_load32((return_area) + 0)) + let ret = array + mbt_ffi_free(return_area) + return ret + +} +///| +/// The installed apps that can be each category's default, grouped by category in category +/// order, each group in name order. +pub fn apps() -> Array[AppChoice] { + + let return_area = mbt_ffi_malloc(8) + wasmImportApps(return_area); + + let array : Array[AppChoice] = []; + for index = 0; index < (mbt_ffi_load32((return_area) + 4)); index = index + 1 { + let iter_base = (mbt_ffi_load32((return_area) + 0)) + (index * 28) + + let result = mbt_ffi_ptr2str(mbt_ffi_load32((iter_base) + 4), mbt_ffi_load32((iter_base) + 8)) + + let result0 = mbt_ffi_ptr2str(mbt_ffi_load32((iter_base) + 12), mbt_ffi_load32((iter_base) + 16)) + + array.push(AppChoice::{category : (mbt_ffi_load32((iter_base) + 0)).reinterpret_as_uint(), id : result, name : result0, icon : (mbt_ffi_load32((iter_base) + 20)).reinterpret_as_uint(), current : (mbt_ffi_load8_u((iter_base) + 24) != 0)}) + } + mbt_ffi_free(mbt_ffi_load32((return_area) + 0)) + let ret = array + mbt_ffi_free(return_area) + return ret + +} +///| +/// Make the category's `app`-th app (counting within the category, from 0) its default. +pub fn set_default(category : UInt, app : UInt) -> Unit { + + wasmImportSetDefault((category).reinterpret_as_int(), (app).reinterpret_as_int()); + +} +///| +/// Scan the installed apps and the defaults again (another program may have changed them). +pub fn refresh() -> Unit { + + wasmImportRefresh(); + +} + diff --git a/interface/chandra/host/plasmoids/pkg.generated.mbti b/interface/chandra/host/plasmoids/pkg.generated.mbti index a2ef473..f417a23 100644 --- a/interface/chandra/host/plasmoids/pkg.generated.mbti +++ b/interface/chandra/host/plasmoids/pkg.generated.mbti @@ -112,6 +112,7 @@ pub(all) enum Request { MoveInstance(InstanceMove) Shortcut(Int32) ReloadSession + DefaultApp(Int32) } pub(all) struct SettingChange { diff --git a/interface/chandra/host/plasmoids/top.mbt b/interface/chandra/host/plasmoids/top.mbt index a65072d..5285fd7 100644 --- a/interface/chandra/host/plasmoids/top.mbt +++ b/interface/chandra/host/plasmoids/top.mbt @@ -60,6 +60,7 @@ pub(all) enum Request { MoveInstance(InstanceMove) Shortcut(Int) ReloadSession + DefaultApp(Int) } ///| /// A native file-chooser dialog (zenity on the host session) for "Add widget". @@ -393,7 +394,8 @@ pub fn set_config(handle : UInt, key : String, value : String) -> Bool { /// settings (s), 7 icons (si: app id, raster image handle from `raster.load-image`) served by `icons.app-icon`, /// 8 network status (one row, iissiiii: state signal name message wifi-enabled airplane /// can-manage has-wifi), 9 Wi-Fi networks (siiii: ssid signal secured active saved), 10 keyboard -/// shortcuts (ssssi: name binding default-binding conflict capturing). +/// shortcuts (ssssi: name binding default-binding conflict capturing), 11 default-app +/// categories (sss: name current missing), 12 default-app choices (issii: category id name icon current). pub fn publish_table(which : UInt, rows : FixedArray[Byte]) -> Unit { let ptr = mbt_ffi_bytes2ptr(rows) @@ -575,6 +577,10 @@ pub fn next_request() -> Request? { Request::ReloadSession } + 18 => { + + Request::DefaultApp(mbt_ffi_load32((return_area) + 8)) + } _ => panic() } diff --git a/wasmhost/bin/plasmoids.mbt b/wasmhost/bin/plasmoids.mbt index d875e33..5e2a7a0 100644 --- a/wasmhost/bin/plasmoids.mbt +++ b/wasmhost/bin/plasmoids.mbt @@ -261,6 +261,7 @@ fn request_val(r : @wasm.HostRequest) -> @wt.Val { ) Shortcut(n) => Variant("shortcut", Some(S32(n))) ReloadSession => Variant("reload-session", None) + DefaultApp(n) => Variant("default-app", Some(S32(n))) } } diff --git a/wit/capabilities.wit b/wit/capabilities.wit index 34a39a5..67ea6c5 100644 --- a/wit/capabilities.wit +++ b/wit/capabilities.wit @@ -185,6 +185,44 @@ interface shortcuts { reset-all: func(); } +/// Default applications: which installed app opens web links, mail, folders, text, images, video, +/// music, documents and archives, kept in the freedesktop mimeapps.list that other apps and +/// xdg-open follow, and which terminal Chandra runs terminal apps in (state.edn, exported as +/// xdg-terminals.list). A module with this capability (the settings module's Apps tab) lists the +/// choices and sets them. +interface default-apps { + record app-category { + /// What it is for ("Web browser"). + name: string, + /// The name of its current default, also when that app is not one of the choices (hidden + /// from menus); empty when there is none. + current: string, + /// The app chosen for it that is no longer installed (its name, or its desktop file id when + /// that is all that is known), or empty. + missing: string, + } + record app-choice { + /// Index into `categories`. + category: u32, + /// Desktop file id without ".desktop" ("firefox"). + id: string, + name: string, + /// Image handle of its icon (0: none; draw your own stand-in then). + icon: u32, + /// Whether it is the category's default now. + current: bool, + } + /// The categories, in the order they are shown. + categories: func() -> list; + /// The installed apps that can be each category's default, grouped by category in category + /// order, each group in name order. + apps: func() -> list; + /// Make the category's `app`-th app (counting within the category, from 0) its default. + set-default: func(category: u32, app: u32); + /// Scan the installed apps and the defaults again (another program may have changed them). + refresh: func(); +} + /// Screenshots and screen recordings, after KDE Spectacle. The compositor captures (it alone sees /// the screen); a module with this capability offers the modes and starts them. interface screenshot { diff --git a/wit/host/plasmoids.wit b/wit/host/plasmoids.wit index 49c1adf..f3fc08b 100644 --- a/wit/host/plasmoids.wit +++ b/wit/host/plasmoids.wit @@ -57,7 +57,8 @@ interface plasmoids { /// settings (s), 7 icons (si: app id, raster image handle from `raster.load-image`) served by `icons.app-icon`, /// 8 network status (one row, iissiiii: state signal name message wifi-enabled airplane /// can-manage has-wifi), 9 Wi-Fi networks (siiii: ssid signal secured active saved), 10 keyboard - /// shortcuts (ssssi: name binding default-binding conflict capturing). + /// shortcuts (ssssi: name binding default-binding conflict capturing), 11 default-app + /// categories (sss: name current missing), 12 default-app choices (issii: category id name icon current). publish-table: func(which: u32, rows: list); /// Layout mode (0 tiling, 1 monocle, 2 floating) and whether the Interface Explorer is on. publish-state: func(layout-mode: s32, inspector-on: bool); @@ -142,6 +143,9 @@ interface plasmoids { shortcut(s32), /// The session capability's `reload`: reload every loaded panel module from disk. reload-session, + /// The default-apps capability: category * 1000 + app (set that category's default to its + /// app-th app), or -1 to scan the apps and defaults again. + default-app(s32), } /// The next pending request, oldest first. next-request: func() -> option; diff --git a/wit/worlds.wit b/wit/worlds.wit index d71ed0f..e01abf4 100644 --- a/wit/worlds.wit +++ b/wit/worlds.wit @@ -88,12 +88,14 @@ world plasmoid-host { import battery; import network; import shortcuts; + import default-apps; export plasmoid; } /// The settings module: session switches (restore, window places, dark mode), the wallpaper, the /// panel's modules (load, unload, browse; the panel menu's "Modules..." opens that tab), and power -/// (idle timeouts, battery, suspend / restart / power off) and keyboard shortcuts (rebind, reset). +/// (idle timeouts, battery, suspend / restart / power off), keyboard shortcuts (rebind, reset) and +/// default apps (browser, email, files, terminal, editor, viewers and players). world session-settings-widget { include widget; import session-settings; @@ -102,6 +104,7 @@ world session-settings-widget { import power; import system; import shortcuts; + import default-apps; } /// Screenshot and screen recording launcher. diff --git a/world/session-settings-widget/README.md b/world/session-settings-widget/README.md index 992caab..51b8d86 100644 --- a/world/session-settings-widget/README.md +++ b/world/session-settings-widget/README.md @@ -1,3 +1,4 @@ The settings module: session switches (restore, window places, dark mode), the wallpaper, the panel's modules (load, unload, browse; the panel menu's "Modules..." opens that tab), and power -(idle timeouts, battery, suspend / restart / power off) and keyboard shortcuts (rebind, reset). \ No newline at end of file +(idle timeouts, battery, suspend / restart / power off), keyboard shortcuts (rebind, reset) and +default apps (browser, email, files, terminal, editor, viewers and players). \ No newline at end of file