Settings > Apps: choose the default browser, email, files, terminal, editor, viewers and players
CI / test (push) Failing after 45s

- 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 <cmd>, 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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hgywj7RPmFdFhpzGZj
This commit is contained in:
Claude committed 2026-11-25 21:27:30 +00:00
1 parent 442f9477b4
commit bb7c9b947f
26 files changed
+1605 -73

No files matched your search

+36 -54
View File
@@ -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()
+887
View File
@@ -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..<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"])
}
+15
View File
@@ -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 {
+21
View File
@@ -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,
+24 -2
View File
@@ -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
}
+9 -2
View File
@@ -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()