///| App icons for panel modules (the `icons` capability): a window's app id is matched to its /// .desktop file (`resolve_app_id`), whose Icon= key is looked up in the freedesktop icon themes /// (a simplified icon theme spec lookup), and the file is loaded for `Image` draw ops. ///| Base directories icon themes live in, highest priority first. fn icon_base_dirs() -> Array[String] { let home = @sys.getenv("HOME") let data_home = { let x = @sys.getenv("XDG_DATA_HOME") if x.length() > 0 { x } else { home + "/.local/share" } } let dirs = [data_home + "/icons", home + "/.icons"] let xdg = @sys.getenv("XDG_DATA_DIRS") let list = if xdg.length() > 0 { xdg } else { "/usr/local/share:/usr/share" } for p in list.split(":") { if p.length() > 0 { dirs.push(p.to_string() + "/icons") } } dirs.push(home + "/.local/share/flatpak/exports/share/icons") dirs.push("/var/lib/flatpak/exports/share/icons") dirs } ///| Themes searched: hicolor is where apps install their icons; the others cover apps whose icon ///| Themes tried after the user's own (and hicolor) for an icon the user's theme lacks, in this /// order. KDE apps such as Konsole and Dolphin ship no icon of their own: they name a theme icon /// (Icon=utilities-terminal, Icon=system-file-manager) that only desktop themes have. let fallback_icon_themes : Array[String] = ["breeze", "Adwaita"] ///| Fixed-size directories, best first for a ~22-48 px icon (scaled down well); the scalable SVG /// goes after the first three when the host can draw SVG. Only for themes without an index.theme. let icon_sizes : Array[String] = [ "48x48", "64x64", "32x32", "96x96", "128x128", "256x256", "24x24", "22x22", "16x16", "512x512", ] ///| The size icons are looked up at: the dock's largest icons are 28 px, so 48 leaves room for /// magnification and scales down cleanly. let icon_lookup_size : Int = 48 ///| The freedesktop name of the generic application icon, drawn for an app whose own icon no /// theme has. let generic_app_icon : String = "application-x-executable" ///| How a theme directory's icons may be scaled (index.theme `Type=`). priv enum IconDirKind { Fixed Scalable Threshold } derive(Eq, Debug) ///| One directory of an icon theme, from its index.theme group. priv struct IconDir { /// Relative to the theme's directory: "apps/48" (breeze), "48x48/apps" (hicolor, Adwaita). path : String size : Int scale : Int min : Int max : Int threshold : Int kind : IconDirKind } derive(Debug) ///| An icon theme as its index.theme describes it. priv struct IconTheme { /// Its directory name under an icons base dir ("breeze-dark"). name : String /// Inherits=, in order. inherits : Array[String] /// Directories= then ScaledDirectories=. dirs : Array[IconDir] } derive(Debug) ///| A comma-separated list as its non-empty parts. fn comma_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 } ///| An int value, or `dflt` when missing or not a number. fn ini_int(keys : Map[String, String], key : String, dflt : Int) -> Int { match keys.get(key) { Some(v) => parse_int_str(v).unwrap_or(dflt) None => dflt } } ///| The groups of an ini-style file (index.theme, kdeglobals, settings.ini) as group -> key -> /// value. fn ini_groups(text : String) -> Map[String, Map[String, String]] { let out : Map[String, Map[String, String]] = {} let mut cur : Map[String, String] = {} for raw in text.split("\n") { let line = raw.trim(chars=" \r\t").to_string() if line.length() == 0 || line.has_prefix("#") || line.has_prefix(";") { continue } if line.has_prefix("[") && line.has_suffix("]") { let name = line[1:line.length() - 1].to_string() cur = match out.get(name) { Some(m) => m None => { let m : Map[String, String] = {} out.set(name, m) m } } continue } match line.find("=") { None => () Some(eq) => cur.set(line[:eq].trim(chars=" ").to_string(), line[eq + 1:].trim(chars=" ").to_string()) } } out } ///| Parse theme `name`'s index.theme. fn parse_index_theme(name : String, text : String) -> IconTheme { let groups = ini_groups(text) let head = groups.get("Icon Theme").unwrap_or({}) let dirs : Array[IconDir] = [] let listed = comma_list(head.get("Directories").unwrap_or("")) listed.append(comma_list(head.get("ScaledDirectories").unwrap_or(""))) for path in listed { match groups.get(path) { None => () Some(g) => { let size = ini_int(g, "Size", 0) if size <= 0 { continue } let kind = match g.get("Type").unwrap_or("Threshold") { "Fixed" => Fixed "Scalable" => Scalable _ => Threshold } dirs.push({ path, size, scale: ini_int(g, "Scale", 1), min: ini_int(g, "MinSize", size), max: ini_int(g, "MaxSize", size), threshold: ini_int(g, "Threshold", 2), kind, }) } } } { name, inherits: comma_list(head.get("Inherits").unwrap_or("")), dirs } } ///| Whether the directory holds icons for `size` at scale 1 (the spec's DirectoryMatchesSize). fn IconDir::matches(self : IconDir, size : Int) -> Bool { if self.scale != 1 { return false } match self.kind { Fixed => self.size == size Scalable => self.min <= size && size <= self.max Threshold => self.size - self.threshold <= size && size <= self.size + self.threshold } } ///| How far the directory's icons are from `size` (the spec's DirectorySizeDistance). fn IconDir::distance(self : IconDir, size : Int) -> Int { let s = self.scale match self.kind { Fixed => (self.size * s - size).abs() Scalable => if size < self.min * s { self.min * s - size } else if size > self.max * s { size - self.max * s } else { 0 } Threshold => if size < (self.size - self.threshold) * s { self.min * s - size } else if size > (self.size + self.threshold) * s { size - self.max * s } else { 0 } } } ///| Candidate files for icon `name` in `theme`, best first: the directories matching `size`, /// then the others by size distance, bigger first at a tie (they scale down better). fn theme_candidates( theme : IconTheme, name : String, size : Int, svg_ok : Bool, bases : Array[String], ) -> Array[String] { let exts = if svg_ok { [".png", ".svg"] } else { [".png"] } let order : Array[(Int, Int)] = [] // (distance, index); exact matches 0 for i, d in theme.dirs { order.push((if d.matches(size) { 0 } else { d.distance(size) + 1 }, i)) } order.sort_by((a, b) => { if a.0 != b.0 { return a.0.compare(b.0) } let sa = theme.dirs[a.1].size * theme.dirs[a.1].scale let sb = theme.dirs[b.1].size * theme.dirs[b.1].scale if sa != sb { sb.compare(sa) } else { a.1.compare(b.1) } }) let out : Array[String] = [] for o in order { let d = theme.dirs[o.1] for base in bases { for ext in exts { out.push(base + "/" + theme.name + "/" + d.path + "/" + name + ext) } } } out } ///| Candidates in a theme without an index.theme: the usual `/apps` layout. fn plain_theme_candidates( theme : String, name : String, svg_ok : Bool, bases : Array[String], ) -> Array[String] { let out : Array[String] = [] for base in bases { let dir = base + "/" + theme for i = 0; i < icon_sizes.length(); i = i + 1 { if i == 3 && svg_ok { out.push(dir + "/scalable/apps/" + name + ".svg") } out.push(dir + "/" + icon_sizes[i] + "/apps/" + name + ".png") } } out } ///| Candidate files for icon `name` (an Icon= value), in lookup order: through `themes` (as /// `icon_theme_chain` orders them; None: a theme without an index.theme), then the pixmaps dirs. /// `svg_ok`: whether the image loader can read SVG (the host does; the native software renderer /// only reads PNG). fn icon_candidates( name : String, svg_ok : Bool, themes : Array[(String, IconTheme?)], bases : Array[String], pixmaps : Array[String], ) -> Array[String] { if name.length() == 0 { return [] } if name.has_prefix("/") { // Any file name: AppImage managers write icons without an extension, and the loader tells // the type from the contents. return if !svg_ok && name.has_suffix(".svg") { [] } else { [name] } } // Icon=foo.png is not allowed by the spec but common: look it up as "foo". let stem = if name.has_suffix(".png") || name.has_suffix(".svg") || name.has_suffix(".xpm") { name[:name.length() - 4].to_string() } else { name } let out : Array[String] = [] for t in themes { match t.1 { Some(theme) => out.append(theme_candidates(theme, stem, icon_lookup_size, svg_ok, bases)) None => out.append(plain_theme_candidates(t.0, stem, svg_ok, bases)) } } for p in pixmaps { out.push(p + "/" + stem + ".png") if svg_ok { out.push(p + "/" + stem + ".svg") } } out } ///| The user's icon theme, or "" when nothing names one. `$CHANDRA_ICON_THEME` (`env`) wins, then /// kdeglobals `[Icons] Theme=`, then GTK's settings.ini `gtk-icon-theme-name`; a kdeglobals /// without one means KDE's default, breeze. `config` reads a file under the config dir. fn user_icon_theme(env : String, config : (String) -> String) -> String { if env.length() > 0 { return env } let kde = config("kdeglobals") match ini_groups(kde).get("Icons") { Some(g) => match g.get("Theme") { Some(t) if t.length() > 0 => return t _ => () } None => () } for f in ["gtk-4.0/settings.ini", "gtk-3.0/settings.ini"] { match ini_groups(config(f)).get("Settings") { Some(g) => match g.get("gtk-icon-theme-name") { Some(t) => { let t = t.trim(chars="\"' ").to_string() if t.length() > 0 { return t } } None => () } None => () } } if kde.length() > 0 { "breeze" } else { "" } } ///| The themes to search, in order: `user` and what it inherits (depth first), hicolor (where /// apps install their own icons), then the fallback themes and theirs. `load` reads a theme's /// index.theme (None: not installed); themes that aren't installed are left out, hicolor stays /// (some installs have hicolor dirs without its index.theme). fn icon_theme_chain(user : String, load : (String) -> IconTheme?) -> Array[(String, IconTheme?)] { let out : Array[(String, IconTheme?)] = [] let seen : Map[String, Bool] = {} fn visit(name : String, depth : Int) -> Unit { if name.length() == 0 || name == "hicolor" || seen.contains(name) || depth > 8 { return } seen.set(name, true) match load(name) { None => () Some(t) => { out.push((name, Some(t))) for p in t.inherits { visit(p, depth + 1) } } } } visit(user, 0) out.push(("hicolor", load("hicolor"))) for f in fallback_icon_themes { visit(f, 0) } out } ///| The first base dir's index.theme for theme `name`, parsed. fn load_icon_theme(name : String, bases : Array[String]) -> IconTheme? { for base in bases { let b = @sys.read_file_bytes(base + "/" + name + "/index.theme") if b.length() > 0 { return Some(parse_index_theme(name, @utf8.decode_lossy(b))) } } None } ///| A file under $XDG_CONFIG_HOME (or ~/.config) as text ("" when missing). fn read_config_text(rel : String) -> String { let x = @sys.getenv("XDG_CONFIG_HOME") let dir = if x.length() > 0 { x } else { @sys.getenv("HOME") + "/.config" } @utf8.decode_lossy(@sys.read_file_bytes(dir + "/" + rel)) } ///| Where icons are looked up: the base dirs and the theme chain, read once per shell. struct IconSearch { bases : Array[String] themes : Array[(String, IconTheme?)] } ///| fn IconSearch::from_env() -> IconSearch { let bases = icon_base_dirs() let user = user_icon_theme(@sys.getenv("CHANDRA_ICON_THEME"), read_config_text) let themes = icon_theme_chain(user, n => load_icon_theme(n, bases)) @sys.log("chandra: icon themes: " + themes.map(t => t.0).join(", ")) { bases, themes } } ///| The icon file for Icon= value `name`, or None when no theme has it. fn IconSearch::find(self : IconSearch, name : String, svg_ok : Bool) -> String? { for path in icon_candidates(name, svg_ok, self.themes, self.bases, ["/usr/share/pixmaps"]) { if @sys.read_file_bytes(path).length() > 0 { return Some(path) } } None } ///| The icon names tried for an app, best first: its Icon= value, its desktop id or window app /// id (many apps' icons are named after it), that id's last dotted part lower-cased /// (`org.kde.kwrite` -> `kwrite`), and last the generic application icon, so an app whose own /// icon is nowhere still looks like an app (the letter tile is drawn only when even that is /// missing). fn icon_names_for(icon : String, id : String) -> Array[String] { let out : Array[String] = [] let add = fn(n : String) { if n.length() > 0 && !out.contains(n) { out.push(n) } } add(icon) add(id) let parts = id.split(".").to_array() if parts.length() > 1 { add(parts[parts.length() - 1].to_string().to_lower()) } add(generic_app_icon) out } ///| The icon search, read on first use. fn DesktopShell::icon_search(self : DesktopShell) -> IconSearch { match self.icon_search { Some(s) => s None => { let s = IconSearch::from_env() self.icon_search = Some(s) s } } } ///| The image handle for app `id` with Icon= value `icon` (0: none), cached per id so each app's /// themes are searched once. fn DesktopShell::lookup_icon(self : DesktopShell, id : String, icon : String) -> UInt { match self.icon_handles.get(id) { Some(h) => return h None => () } let search = self.icon_search() let svg_ok = @sys.host_raster() let mut h = 0U for name in icon_names_for(icon, id) { match search.find(name, svg_ok) { Some(path) => { h = @raster.load_image(path) if h != 0U { if name == generic_app_icon && icon != generic_app_icon { @sys.log("chandra: no icon for " + id + " (Icon=" + icon + "), using " + path) } break } } None => () } } if h == 0U { @sys.log("chandra: no icon for " + id + " (Icon=" + icon + ")") } self.icon_handles.set(id, h) h } ///| The image handle of the icon for windows carrying `app_id` (0: none). fn DesktopShell::app_icon(self : DesktopShell, app_id : String) -> UInt { match self.icon_handles.get(app_id) { Some(h) => return h None => () } let icon = match resolve_app_id(app_id, self.exec, self.wm_classes) { Some(id) => self.icon_names.get(id).unwrap_or("") None => "" } self.lookup_icon(app_id, icon) } ///| 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 { self.lookup_icon(id, icon) } ///| 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 { if app_id.length() == 0 { 0U } else { self.app_icon(app_id) } } ///| The app ids whose icons the modules need now: the windows' apps, the dock's apps (running or /// not), the rows the Applications menu shows while it is open (only those, so opening it looks /// up a handful of icons, not the whole catalog), and every app the desktop module can show when /// it imports `icons` (Icon Desktop). Each id once, in that order. pub fn DesktopShell::icon_app_ids(self : DesktopShell) -> Array[String] { let out : Array[String] = [] let seen : Map[String, Bool] = {} let add = fn(id : String) { if id.length() > 0 && !seen.contains(id) { seen.set(id, true) out.push(id) } } for w in self.win_list { add(w.app_id) } for id in self.dock_app_ids() { add(id) } for id in self.launcher_icon_ids() { add(id) } match self.desk_mod { Some(d) if d.has_cap("icons") => for a in self.apps { add(a.id) } _ => () } out } ///| The apps the open Applications menu lists (as the shell follows its search), else none. fn DesktopShell::launcher_icon_ids(self : DesktopShell) -> Array[String] { let st = self.launcher_state if !st.open { return [] } @launcher.shown_rows(self.apps, st).map(a => a.id) } ///| Publish the icons table (app id -> image handle) for `icon_app_ids`. Lookups are cached per id /// (`lookup_icon`), and an unchanged table is not sent again. fn DesktopShell::publish_icons(self : DesktopShell) -> Unit { let rows : Array[(String, UInt)] = [] for id in self.icon_app_ids() { let h = self.app_icon(id) if h != 0U { rows.push((id, h)) } } if rows == self.icons_published { return } self.icons_published = rows let t = @wasm.Table::new() for r in rows { t.str(r.0) t.int(r.1.reinterpret_as_int()) t.end_row() } @wasm.publish(Icons, t) } ///| The image handle of theme icon `name` (say "drive-harddisk"; 0: none), cached. pub fn DesktopShell::theme_icon(self : DesktopShell, name : String) -> UInt { if name == "" { return 0U } let key = "icon:" + name match self.icon_handles.get(key) { Some(h) => return h None => () } let h = match self.icon_search().find(name, @sys.host_raster()) { Some(path) => @raster.load_image(path) None => 0U } self.icon_handles.set(key, h) h }