diff --git a/compositor/host/compositor.mbt b/compositor/host/compositor.mbt index ed30b63..747b2d1 100644 --- a/compositor/host/compositor.mbt +++ b/compositor/host/compositor.mbt @@ -2427,6 +2427,9 @@ fn ChandraCompositor::dispatch_input_inner( } None => () } + if axis == 0U && self.shell.scroll_popup(xi, yi, v, discrete) { + return + } if self.overview is Some(_) { return // nothing scrolls under the overview } diff --git a/compositor/host/dock_test.mbt b/compositor/host/dock_test.mbt index 2c6b6bd..c6d6223 100644 --- a/compositor/host/dock_test.mbt +++ b/compositor/host/dock_test.mbt @@ -80,8 +80,9 @@ test "the dock is the panel's task manager: empty + opens Applications, pin from let launcher = comp.shell.slot_of("launcher") let pr = comp.shell.slot_popup_rect(launcher) assert_true(pr.w > 0) + // (The apps are right of the category column, when the machine has enough of them for one.) // Right-click the first app there: Open, Pin to dock. Pinning keeps the menu open. - click_at(comp, pr.x + 40, pr.y + 60, 20U, btn=273U) + click_at(comp, pr.x + pr.w - 60, pr.y + 60, 20U, btn=273U) assert_true(comp.shell.menu_open) assert_eq(comp.shell.menu_rows.map(r => r.label), ["Open", "Pin to dock"]) let first = comp.shell.menu_title @@ -91,7 +92,7 @@ test "the dock is the panel's task manager: empty + opens Applications, pin from let pinned = comp.shell.module_setting("dock", "pinned").unwrap_or("") assert_true(pinned.length() > 1 && pinned != ";") // The same app's menu now offers Unpin. - click_at(comp, pr.x + 40, pr.y + 60, 30U, btn=273U) + click_at(comp, pr.x + pr.w - 60, pr.y + 60, 30U, btn=273U) assert_eq(comp.shell.menu_title, first) assert_true(comp.shell.menu_rows.map(r => r.label).contains("Unpin from dock")) comp.handle_input(@nested.InputEvent::Key(1U, true), 35U) // Escape closes the menu diff --git a/compositor/host/input_test.mbt b/compositor/host/input_test.mbt index 07aabe3..5335741 100644 --- a/compositor/host/input_test.mbt +++ b/compositor/host/input_test.mbt @@ -1138,7 +1138,8 @@ test "dragging a floating window's corner resizes it" { /// bottom, 8 px margins, 4 px gaps). fn launcher_button(comp : @host.ChandraCompositor, i : Int) -> (Int, Int) { let pr = comp.shell.slot_popup_rect(comp.shell.slot_of("launcher")) - (pr.x + 8 + i * 65 + 30, pr.y + pr.h - 44 + 6 + 15) + let bw = (pr.w - 2 * 8 - 4 * 4) / 5 + (pr.x + 8 + i * (bw + 4) + bw / 2, pr.y + pr.h - 44 + 6 + 15) } ///| diff --git a/compositor/host/launcher_webapps_test.mbt b/compositor/host/launcher_webapps_test.mbt new file mode 100644 index 0000000..ca84a2f --- /dev/null +++ b/compositor/host/launcher_webapps_test.mbt @@ -0,0 +1,59 @@ +///| Web apps (PWAs) Chrome installs, in the Applications menu: they are picked up when the menu +/// next opens, in a "Chrome Apps" category, and the wheel scrolls the list. +/// Needs the modules built: scripts/build-modules.sh. +test "a web app installed while running is in the menu's Chrome Apps" { + let data = "/tmp/chandra-webapps-" + @sys.getpid().to_string() + let dir = data + "/applications" + assert_true(@sys.mkdir_p(dir)) + let app = fn(id : String, name : String, rest : String) { + ignore( + @sys.write_file_bytes( + dir + "/" + id + ".desktop", + @sys.str_to_utf8_bytes("[Desktop Entry]\nType=Application\nName=" + name + "\n" + rest), + ), + ) + } + for i = 0; i < 12; i = i + 1 { + app("chandra-game" + i.to_string(), "Chandra Game " + i.to_string(), "Exec=true\nCategories=Game;\n") + } + let socket_path = "/tmp/wayland-moon-webapps-" + @sys.getpid().to_string() + ".sock" + let comp = @host.ChandraCompositor::new(socket_path, @scene.ThemeTokens::moon_night(), 1280, 720).unwrap() + comp.shell.xdg_dirs = { ..comp.shell.xdg_dirs, data_home: data, data_dirs: [] } + comp.shell.toggle_launcher() + comp.shell.toggle_launcher() + let id = "chrome-chandratestappid-Default" + assert_eq(comp.shell.apps.length(), 12) + assert_false(comp.shell.apps.iter().any(a => a.id == id)) + // Chrome installs it. + app( + id, + "Chandra Web App", + "Exec=/opt/google/chrome/google-chrome --profile-directory=Default --app-id=chandratestappid\n", + ) + comp.shell.toggle_launcher() + for _ in 0..<10 { + @sys.sleep_ms(30) // the popup slides in + ignore(comp.compose_frame()) + } + let a = comp.shell.apps.filter(a => a.id == id) + assert_eq(a.map(a => (a.name, a.category)), [("Chandra Web App", "Chrome Apps")]) + let slot = comp.shell.slot_of("launcher") + let pr = comp.shell.slot_popup_rect(slot) + let texts = fn() { comp.shell.slot_popup_texts(slot).map(t => t.0) } + assert_true(texts().contains("Chrome Apps")) + // The wheel over the list scrolls it (the shell's copy of the menu follows the module's). + let (lx, ly) = (pr.x + pr.w - 60, pr.y + 60) + comp.handle_input(@nested.InputEvent::PointerMove(lx.to_double(), ly.to_double()), 1U) + comp.handle_input(@nested.InputEvent::Scroll(0U, 15.0, 1), 2U) + assert_eq(comp.shell.launcher_state.scroll, 3) + // Its category lists it. + let cats = ["All", "Chrome Apps", "Games"] + let i = cats.search("Chrome Apps").unwrap() + click_at(comp, pr.x + 20, pr.y + 52 + i * 26 + 12, 10U) + ignore(comp.compose_frame()) + assert_eq(comp.shell.launcher_state.category, "Chrome Apps") + assert_true(texts().contains("Chandra Web App")) + assert_false(texts().contains("Chandra Game 0")) + ignore(@sys.write_file_bytes("_build/launcher_webapps.png", @renderer.encode_png(comp.compose_frame()))) + comp.shell.shutdown() +} diff --git a/compositor/shell/apps.mbt b/compositor/shell/apps.mbt index a81c195..c300e23 100644 --- a/compositor/shell/apps.mbt +++ b/compositor/shell/apps.mbt @@ -18,29 +18,6 @@ priv struct DesktopApp { terminal_emulator : Bool } -///| Directories scanned, lowest priority first (later ones override by file name). -fn app_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 : Array[String] = [] - let xdg = @sys.getenv("XDG_DATA_DIRS") - let list = if xdg.length() > 0 { xdg } else { "/usr/local/share:/usr/share" } - let parts : Array[String] = list.split(":").map(x => x.to_string()).collect() - // XDG_DATA_DIRS is highest priority first; we want lowest first. - for i = parts.length() - 1; i >= 0; i = i - 1 { - if parts[i].length() > 0 { - dirs.push(parts[i] + "/applications") - } - } - dirs.push("/var/lib/flatpak/exports/share/applications") - dirs.push(home + "/.local/share/flatpak/exports/share/applications") - dirs.push(data_home + "/applications") - dirs -} - ///| Drop Exec field codes (%f %U ...), keep a literal %%. fn clean_exec(exec : String) -> String { let sb = StringBuilder::new() @@ -60,6 +37,57 @@ fn clean_exec(exec : String) -> String { sb.to_string().trim(chars=" ").to_string() } +///| The menu category of a web app a Chromium browser installed (its Exec starts the browser with +/// --app-id), named the way the browser names its own menu folder ("Chrome Apps"); None for any +/// other command. These files carry no Categories=: the browsers sort them into their folder with +/// a desktop menu file instead. +fn web_app_category(command : String) -> String? { + match command.find("--app-id=") { + None => None + Some(i) => { + // Only the browser's part: an app id may spell anything in a-p. + let browser = command[:i].to_string().to_lower() + for + it in [ + ("brave", "Brave Apps"), + ("microsoft", "Edge Apps"), + ("msedge", "Edge Apps"), + ("vivaldi", "Vivaldi Apps"), + ("opera", "Opera Apps"), + ("chromium", "Chromium Apps"), + ("chrome", "Chrome Apps"), + ] { + if browser.contains(it.0) { + return Some(it.1) + } + } + Some("Web Apps") + } + } +} + +///| The menu category for a Categories= value: the first of the menu spec's main categories in +/// it, by the name menus show, else "Other" (toolkit names such as Qt and GTK are no category). +fn menu_category(categories : String) -> String { + for c in semi_list(categories) { + match c { + "AudioVideo" | "Audio" | "Video" => return "Multimedia" + "Development" => return "Development" + "Education" => return "Education" + "Game" => return "Games" + "Graphics" => return "Graphics" + "Network" => return "Internet" + "Office" => return "Office" + "Science" => return "Science" + "Settings" => return "Settings" + "System" => return "System" + "Utility" => return "Utilities" + _ => () + } + } + "Other" +} + ///| Parse one .desktop file; None when it should not be listed. A Terminal=true app keeps its /// own command (`terminal`): it is started inside the chosen terminal (`DesktopShell::command_for`). fn parse_desktop(id : String, text : String, have_terminal : Bool) -> DesktopApp? { @@ -77,10 +105,7 @@ fn parse_desktop(id : String, text : String, have_terminal : Bool) -> DesktopApp return None } let cats = get("Categories") - let category = match cats.split(";").next() { - Some(c) if c.length() > 0 => c.to_string() - _ => "Other" - } + let category = web_app_category(exec).unwrap_or(menu_category(cats)) let comment = get("Comment") let comment = if comment.length() > 0 { comment } else { get("GenericName") } Some({ @@ -96,11 +121,65 @@ fn parse_desktop(id : String, text : String, have_terminal : Bool) -> DesktopApp }) } -///| Scan every applications dir; later dirs override earlier ones, result sorted by name. -fn scan_desktop_apps() -> Array[DesktopApp] { +///| The .desktop file names in the applications dirs, to tell when apps were added or removed. +fn desktop_files_in(dirs : Array[String]) -> Array[String] { + let out : Array[String] = [] + for dir in dirs { + out.push(dir) + out.append(@sys.list_desktop_files(dir)) + } + out +} + +///| Fill the app catalog from the installed .desktop files. +fn DesktopShell::load_apps(self : DesktopShell) -> Unit { + let dirs = self.xdg_dirs.app_dirs() + self.app_files = desktop_files_in(dirs) + let old_icons = self.icon_names.copy() + self.apps.clear() + self.exec.clear() + self.wm_classes.clear() + self.icon_names.clear() + self.terminal_apps.clear() + for a in scan_desktop_apps(dirs) { + if a.terminal { + self.terminal_apps.set(a.id, true) + } + if a.icon.length() > 0 { + self.icon_names.set(a.id, a.icon) + } + if a.wm_class.length() > 0 { + self.wm_classes.set(a.wm_class.to_lower(), a.id) + } + let glyph = match a.name.to_array().get(0) { + Some(c) => c.to_string().to_upper() + None => "?" + } + self.apps.push({ id: a.id, name: a.name, comment: a.comment, category: a.category, glyph }) + self.exec.set(a.id, a.command) + // A new app (or one with a new icon) may have been looked up before it had one. + if old_icons.get(a.id) != self.icon_names.get(a.id) { + self.icon_handles.remove(a.id) + } + } + self.order_apps() + self.apps_dirty = true +} + +///| Read the catalog again if apps were installed or removed since (a web app installed from the +/// browser, say). Called as the Applications menu opens; only lists the dirs when nothing changed. +fn DesktopShell::refresh_apps(self : DesktopShell) -> Unit { + if desktop_files_in(self.xdg_dirs.app_dirs()) != self.app_files { + self.load_apps() + } +} + +///| Scan every applications dir in `dirs` (highest priority first: a file there overrides one of +/// the same name further on), result sorted by name. +fn scan_desktop_apps(dirs : Array[String]) -> Array[DesktopApp] { let by_id : Map[String, DesktopApp] = {} let removed : Map[String, Bool] = {} - for dir in app_dirs() { + for dir in dirs.rev() { for file in @sys.list_desktop_files(dir) { let bytes = @sys.read_file_bytes(dir + "/" + file) let id = file[:file.length() - 8].to_string() @@ -126,11 +205,8 @@ fn scan_desktop_apps() -> Array[DesktopApp] { apps.push(a) } } - apps.sort_by(fn(a, b) { - let x = a.name.to_lower() - let y = b.name.to_lower() - if x < y { -1 } else if x > y { 1 } else { 0 } - }) + // Strings compare shortest first; menus want A-Z. + apps.sort_by(fn(a, b) { a.name.to_lower().lexical_compare(b.name.to_lower()) }) apps } @@ -141,7 +217,7 @@ test "parse_desktop reads a normal entry and strips field codes" { Some(a) => { assert_eq(a.name, "Firefox") assert_eq(a.command, "firefox") - assert_eq(a.category, "Network") + assert_eq(a.category, "Internet") assert_eq(a.comment, "Browse") } None => fail("expected entry") @@ -162,6 +238,32 @@ test "parse_desktop keeps StartupWMClass" { } } +///| +test "parse_desktop puts a browser's web apps in their own category" { + let web = fn(exec : String) { + let t = "[Desktop Entry]\nType=Application\nName=YouTube\nExec=" + exec + "\nStartupWMClass=crx_agim\n" + + "Actions=Shorts\n[Desktop Action Shorts]\nName=Shorts\nExec=other\n" + match parse_desktop("chrome-agim-Default", t, true) { + Some(a) => (a.name, a.category, a.command) + None => ("", "", "") + } + } + let chrome = "/opt/google/chrome/google-chrome --profile-directory=Default --app-id=edgeop" + assert_eq(web(chrome), ("YouTube", "Chrome Apps", chrome)) + assert_eq(web("/usr/bin/chromium --app-id=abc").1, "Chromium Apps") + assert_eq(web("/usr/bin/flatpak run --command=/app/bin/chrome com.google.Chrome --app-id=abc").1, "Chrome Apps") + assert_eq(web("/opt/microsoft/msedge/microsoft-edge --app-id=abc").1, "Edge Apps") + assert_eq(web("firefox"), ("YouTube", "Other", "firefox")) +} + +///| +test "menu_category skips toolkit names and names the main category" { + assert_eq(menu_category("Qt;KDE;System;TerminalEmulator;"), "System") + assert_eq(menu_category("Game;Network;"), "Games") + assert_eq(menu_category("GTK;X-Own;"), "Other") + assert_eq(menu_category(""), "Other") +} + ///| test "parse_desktop hides NoDisplay entries" { let t = "[Desktop Entry]\nType=Application\nName=X\nExec=x\nNoDisplay=true\n" diff --git a/compositor/shell/default_apps.mbt b/compositor/shell/default_apps.mbt index ecc0b9e..2e2c529 100644 --- a/compositor/shell/default_apps.mbt +++ b/compositor/shell/default_apps.mbt @@ -199,7 +199,7 @@ pub fn XdgDirs::from_env() -> XdgDirs { 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). + // Flatpak's exports (flatpak usually puts them in XDG_DATA_DIRS). let data_dirs = parts(or("XDG_DATA_DIRS", "/usr/local/share:/usr/share")) for d in [home + "/.local/share/flatpak/exports/share", "/var/lib/flatpak/exports/share"] { if !data_dirs.contains(d) { @@ -235,7 +235,7 @@ pub fn XdgDirs::mimeapps_files(self : XdgDirs) -> Array[String] { out } -///| applications dirs, highest priority first (the launcher's `app_dirs` lists them lowest first). +///| applications dirs, highest priority first. fn XdgDirs::app_dirs(self : XdgDirs) -> Array[String] { let out = [self.data_home + "/applications"] for d in self.data_dirs { diff --git a/compositor/shell/dock.mbt b/compositor/shell/dock.mbt index 7afc3f7..7b1d9d8 100644 --- a/compositor/shell/dock.mbt +++ b/compositor/shell/dock.mbt @@ -395,7 +395,7 @@ fn DesktopShell::open_app_menu(self : DesktopShell, app : @types.AppEntry, x : I fn DesktopShell::launcher_app_at(self : DesktopShell, x : Int, y : Int) -> @types.AppEntry? { match self.popup_at(x, y) { Some(w) if w.module_id == launcher_module => { - let shown = @launcher.filter(self.apps, self.launcher_state.query) + let shown = @launcher.listed(self.apps, self.launcher_state) let i = @launcher.row_at(self.apps, self.launcher_state, { x: x - w.popup_rect.x, y: y - w.popup_rect.y }) if i >= 0 && i < shown.length() { Some(shown[i]) diff --git a/compositor/shell/shell.mbt b/compositor/shell/shell.mbt index 48a3772..e40bf1a 100644 --- a/compositor/shell/shell.mbt +++ b/compositor/shell/shell.mbt @@ -419,6 +419,10 @@ pub(all) struct DesktopShell { mut menu_anchor_y : Int /// Extra bottom inset reserved for panel popups (e.g. an open on-screen keyboard). mut popup_bottom_inset : Int + /// The .desktop files there were when the catalog was read (`refresh_apps`). + mut app_files : Array[String] + /// Touchpad scrolling over the launcher's popup not yet worth a row, in pixels. + mut popup_scroll : Double } ///| @@ -428,23 +432,6 @@ pub fn DesktopShell::new(display : String) -> DesktopShell { 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) - } - if a.wm_class.length() > 0 { - wm_classes.set(a.wm_class.to_lower(), a.id) - } - let glyph = match a.name.to_array().get(0) { - Some(c) => c.to_string().to_upper() - None => "?" - } - apps.push({ id: a.id, name: a.name, comment: a.comment, category: a.category, glyph }) - exec.set(a.id, a.command) - } let zero : @scene.Rect = { x: 0, y: 0, w: 0, h: 0 } let sh : DesktopShell = { apps, @@ -559,8 +546,10 @@ pub fn DesktopShell::new(display : String) -> DesktopShell { desk_saved: {}, menu_anchor_y: -1, popup_bottom_inset: 0, + app_files: [], + popup_scroll: 0.0, } - sh.order_apps() + sh.load_apps() sh } @@ -624,7 +613,9 @@ fn DesktopShell::order_apps(self : DesktopShell) -> Unit { for key in g { if !found { for a in self.apps { - if !found && a.id.to_lower().contains(key) { + // A web app's id holds its browser's name (chrome--Default): not the browser. + let web = web_app_category(self.exec.get(a.id).unwrap_or("")) is Some(_) + if !found && !web && a.id.to_lower().contains(key) { take(a, out, seen) found = true } @@ -762,6 +753,9 @@ fn Widget::has_cap(self : Widget, cap : String) -> Bool { ///| Hand an event to a module, then carry out whatever it asked of the host. fn DesktopShell::deliver(self : DesktopShell, w : Widget, popup : Bool, ev : @wasm.PlasmoidEvent) -> Bool { + if w.module_id == launcher_module && !popup && w.popup_rect.w == 0 && ev is PointerDown(_, _) { + self.refresh_apps() // the menu is about to open + } self.publish_host_data() let changed = w.pl.on_event(popup, ev) self.process_requests() @@ -816,6 +810,34 @@ pub fn DesktopShell::launcher_open(self : DesktopShell) -> Bool { self.launcher_rect() is Some(_) } +///| Wheel or touchpad over an open panel popup: `notches` wheel clicks, or (0 of those) `px` +/// pixels; + is down. The launcher's list scrolls by rows. False when (x, y) is on no popup. +pub fn DesktopShell::scroll_popup(self : DesktopShell, x : Int, y : Int, px : Double, notches : Int) -> Bool { + let w = match self.popup_at(x, y) { + Some(w) => w + None => return false + } + if w.module_id != launcher_module || (self.menu_open && inside(self.menu_rect, x, y)) { + return true + } + let mut rows = notches * 3 + if notches == 0 { + self.popup_scroll = self.popup_scroll + px + rows = (self.popup_scroll / 15.0).to_int() + self.popup_scroll = self.popup_scroll - rows.to_double() * 15.0 + } + let key = if rows < 0 { "ScrollUp" } else { "ScrollDown" } + let n = if rows < 0 { -rows } else { rows } + for _ in 0.. 0 { + // The rows moved under a still pointer. + ignore(self.deliver(w, true, PointerMove(x - w.popup_rect.x, y - w.popup_rect.y))) + } + true +} + ///| Close the launcher's popup if it is open. pub fn DesktopShell::close_launcher(self : DesktopShell) -> Unit { for w in self.widgets { diff --git a/compositor/shell/widgets.mbt b/compositor/shell/widgets.mbt index 568ed1f..022c3d1 100644 --- a/compositor/shell/widgets.mbt +++ b/compositor/shell/widgets.mbt @@ -597,6 +597,9 @@ fn DesktopShell::replace_slot_result(self : DesktopShell, slot : String, path : pub fn DesktopShell::reload_modules(self : DesktopShell, name : String) -> (Array[String], Bool) { self.ensure_booted() self.scan_catalog() // a module installed since login shows up in Settings > Panel + if name == "" { + self.load_apps() // and an app's changed .desktop file in the Applications menu + } let targets : Array[(String, String, String)] = [] for w in self.widgets { if name == "" || w.module_id == name || stem(w.path) == name || w.slot == name || w.path == name { diff --git a/host/test/desktop.test.mjs b/host/test/desktop.test.mjs index 503ca0f..963b847 100644 --- a/host/test/desktop.test.mjs +++ b/host/test/desktop.test.mjs @@ -57,9 +57,9 @@ test('launcher: click opens popup, row click launches via host capability, popup assert.ok(texts(f.ops).includes('Terminal')); const pr = desktop.hit.popup.rect; assert.ok(pr.y + pr.h <= 720 - 44, 'popup sits above the panel'); - // second row (52px header + 46px rows) - desktop.pointer('move', pr.x + 20, pr.y + 52 + 46 + 5); - desktop.pointer('down', pr.x + 20, pr.y + 52 + 46 + 5); + // second row (52px header + 46px rows), right of the category column + desktop.pointer('move', pr.x + pr.w - 60, pr.y + 52 + 46 + 5); + desktop.pointer('down', pr.x + pr.w - 60, pr.y + 52 + 46 + 5); assert.deepEqual(platform.launches, ['org.chandra.files']); desktop.frame(); assert.equal(desktop.hit.popup, null, 'popup closed after launch'); diff --git a/lib/launcher/launcher.mbt b/lib/launcher/launcher.mbt index b8562ec..da06680 100644 --- a/lib/launcher/launcher.mbt +++ b/lib/launcher/launcher.mbt @@ -5,6 +5,10 @@ /// The popup ends in a session row: Reload (reload the session's modules from disk), Log out, /// Suspend, Restart and Power off. Log out, Restart and Power off take a second click on the same /// button, like the Settings Power tab; Reload and Suspend act at once. +/// +/// A catalog too long for the popup gets a category column on its left ("All", then the catalog's +/// own categories: "Chrome Apps", "Games", ...) and a scrollbar; the wheel arrives as the keys +/// "ScrollUp" and "ScrollDown", one row each. ///| Which surface an event is addressed to (mirrors the WIT `surface` enum). pub(all) enum Target { @@ -22,11 +26,27 @@ pub struct State { mut hover_action : Int /// Session button waiting for its confirming second click (-1: none). mut armed : Int + /// The category listed while there is no search ("": all apps). + mut category : String + /// How many listed apps are scrolled off above the first row. + mut scroll : Int + /// Category row under the pointer (-1: none). + mut hover_category : Int } ///| pub fn State::new() -> State { - { open: false, query: "", hover: -1, error: "", hover_action: -1, armed: -1 } + { + open: false, + query: "", + hover: -1, + error: "", + hover_action: -1, + armed: -1, + category: "", + scroll: 0, + hover_category: -1, + } } ///| The session row's buttons, in order. `handle_event`'s `session` callback gets the index. @@ -123,16 +143,126 @@ fn visible_rows(n : Int) -> Int { if n > max_rows { max_rows } else { n } } -///| The apps the popup lists now: the filtered catalog, capped at the rows that fit. The shell -/// publishes icons for exactly these while the menu is open. -pub fn shown_rows(apps : Array[@types.AppEntry], st : State) -> Array[@types.AppEntry] { - let shown = filter(apps, st.query) - let n = visible_rows(shown.length()) - if n >= shown.length() { - shown - } else { - shown[:n].to_array() +///| The category column: its width, its rows' height, and the label of its first row. +let sidebar_w : Int = 132 + +///| +let category_h : Int = 26 + +///| +let all_label : String = "All" + +///| The column's rows: "All", the catalog's categories A-Z, "Other" last. Empty (no column) when +/// the whole catalog fits the popup, or has nothing to choose between. +pub fn categories(apps : Array[@types.AppEntry]) -> Array[String] { + if apps.length() <= max_rows { + return [] } + let names : Array[String] = [] + let mut other = false + for a in apps { + let c = category_of(a) + if c == other_label { + other = true + } else if !names.contains(c) { + names.push(c) + } + } + if names.length() + (if other { 1 } else { 0 }) < 2 { + return [] + } + names.sort_by((a, b) => ascii_lower(a).lexical_compare(ascii_lower(b))) + if other { + names.push(other_label) + } + [all_label] + names +} + +///| +let other_label : String = "Other" + +///| +fn category_of(a : @types.AppEntry) -> String { + if a.category == "" { other_label } else { a.category } +} + +///| Width of the category column (0 when there is none). +fn list_x(apps : Array[@types.AppEntry]) -> Int { + if categories(apps).length() > 0 { sidebar_w } else { 0 } +} + +///| Every app the popup lists, scrolled to or not: the search's matches in the whole catalog, or +/// without a search the chosen category. +pub fn listed(apps : Array[@types.AppEntry], st : State) -> Array[@types.AppEntry] { + if st.query.length() > 0 || st.category == "" { + filter(apps, st.query) + } else { + apps.filter(a => category_of(a) == st.category) + } +} + +///| Most rows the list can be scrolled by. +fn max_scroll(n : Int) -> Int { + if n > max_rows { n - max_rows } else { 0 } +} + +///| The first row's index in `listed` (the catalog may have shrunk since it was scrolled). +fn first_row(n : Int, st : State) -> Int { + let m = max_scroll(n) + if st.scroll > m { m } else { st.scroll } +} + +///| Scroll the list by `rows` (+: down). True when it moved. +fn scroll_by(apps : Array[@types.AppEntry], st : State, rows : Int) -> Bool { + let n = listed(apps, st).length() + let from = first_row(n, st) + let to = from + rows + let m = max_scroll(n) + st.scroll = if to < 0 { 0 } else if to > m { m } else { to } + if st.scroll == from { + return false + } + st.hover = -1 + true +} + +///| The app rows the popup draws now, at most `max_rows`. The shell publishes icons for exactly +/// these while the menu is open. +pub fn shown_rows(apps : Array[@types.AppEntry], st : State) -> Array[@types.AppEntry] { + let all = listed(apps, st) + let first = first_row(all.length(), st) + all[first:first + visible_rows(all.length())].to_owned() +} + +///| Category row under a popup-local point, or -1. +fn category_at(apps : Array[@types.AppEntry], p : @types.Point) -> Int { + let n = categories(apps).length() + if n == 0 || p.x < 6 || p.x >= sidebar_w - 2 || p.y < header_h { + return -1 + } + let i = (p.y - header_h) / category_h + if i < n { i } else { -1 } +} + +///| Height of the area between the search field and the status line. +fn body_h(apps : Array[@types.AppEntry], st : State) -> Int { + let rows = visible_rows(listed(apps, st).length()) + let list = (if rows == 0 { 1 } else { rows }) * row_h + let side = categories(apps).length() * category_h + if side > list { side } else { list } +} + +///| The scrollbar's strip on the list's right edge. +let scrollbar_w : Int = 16 + +///| The scrollbar thumb's popup-local top and height for `n` listed apps, when they need one. +fn scroll_thumb(n : Int, st : State) -> (Int, Int)? { + if n <= max_rows { + return None + } + let track = max_rows * row_h - 8 + let th = if track * max_rows / n < 24 { 24 } else { track * max_rows / n } + Some((header_h + 4 + (track - th) * first_row(n, st) / max_scroll(n), th)) } ///| Side of an app's icon in its row. @@ -140,10 +270,8 @@ let icon_px : Int = 32 ///| pub fn popup_size(apps : Array[@types.AppEntry], st : State) -> @types.Size { - let rows = visible_rows(filter(apps, st.query).length()) - let rows = if rows == 0 { 1 } else { rows } let status = if status_text(st) == "" { 0 } else { status_h } - @ui.size(popup_w, header_h + rows * row_h + 8 + status + footer_h) + @ui.size(popup_w + list_x(apps), header_h + body_h(apps, st) + 8 + status + footer_h) } ///| The status line's text: the launch error, else the confirm hint, else "". @@ -157,23 +285,19 @@ fn status_text(st : State) -> String { } } -///| Width of each session button. -fn button_w() -> Int { +///| Popup-local rectangle (x, y, w, h) of session button `i` in a popup of `size`. +fn button_rect(i : Int, size : @types.Size) -> (Int, Int, Int, Int) { + let h = size.h.reinterpret_as_int() let n = session_actions.length() - (popup_w - 2 * footer_margin - (n - 1) * button_gap) / n -} - -///| Popup-local rectangle (x, y, w, h) of session button `i` in a popup of height `h`. -fn button_rect(i : Int, h : Int) -> (Int, Int, Int, Int) { - let bw = button_w() + let bw = (size.w.reinterpret_as_int() - 2 * footer_margin - (n - 1) * button_gap) / n (footer_margin + i * (bw + button_gap), h - footer_h + 6, bw, footer_h - 14) } ///| Session button under a popup-local point, or -1. pub fn action_at(apps : Array[@types.AppEntry], st : State, p : @types.Point) -> Int { - let h = popup_size(apps, st).h.reinterpret_as_int() + let size = popup_size(apps, st) for i = 0; i < session_actions.length(); i = i + 1 { - let (x, y, w, bh) = button_rect(i, h) + let (x, y, w, bh) = button_rect(i, size) if p.x >= x && p.x < x + w && p.y >= y && p.y < y + bh { return i } @@ -188,6 +312,9 @@ pub fn close(st : State) -> Unit { st.hover = -1 st.hover_action = -1 st.armed = -1 + st.category = "" + st.scroll = 0 + st.hover_category = -1 } ///| The panel button: a crescent moon plus a label (shortens to "Apps" or icon-only when tight). @@ -248,22 +375,42 @@ pub fn render_popup( @ui.text(20, 26, st.query + "_", fs, p.foreground) } ops.push(q) - let shown = filter(apps, st.query) + // The category column. A search looks through everything, so it shows as "All". + let cats = categories(apps) + let lx = list_x(apps) + for i = 0; i < cats.length(); i = i + 1 { + let y = header_h + i * category_h + let chosen = if st.query.length() > 0 || st.category == "" { i == 0 } else { cats[i] == st.category } + if chosen || i == st.hover_category { + let bg = if chosen { p.accent } else { p.surface_hover } + ops.push(@ui.fill_rect(@ui.rect(6, y, sidebar_w - 12, category_h - 2), bg, radius=r)) + } + let fg = if chosen { p.accent_foreground } else { p.foreground } + ops.push(@ui.text(14, y + category_h / 2 - 1, cats[i], fs - 2, fg, bold=chosen)) + } + if lx > 0 { + ops.push(@ui.fill_rect(@ui.rect(lx - 2, header_h, 1, body_h(apps, st)), p.border)) + } + let total = listed(apps, st).length() + let first = first_row(total, st) + let shown = shown_rows(apps, st) if shown.length() == 0 { ops.push( - @ui.text(w / 2, header_h + row_h / 2, "No matching applications", fs, p.foreground_muted, align=CENTER), + @ui.text(lx + (w - lx) / 2, header_h + row_h / 2, "No matching applications", fs, p.foreground_muted, align=CENTER), ) } - let n = visible_rows(shown.length()) - for i = 0; i < n; i = i + 1 { + let thumb = scroll_thumb(total, st) + let bar = if thumb is Some(_) { scrollbar_w - 6 } else { 0 } + for i = 0; i < shown.length(); i = i + 1 { let a = shown[i] let y = header_h + i * row_h - if i == st.hover { - ops.push(@ui.fill_rect(@ui.rect(6, y, w - 12, row_h - 2), p.accent, radius=r)) + let hot = first + i == st.hover + if hot { + ops.push(@ui.fill_rect(@ui.rect(lx + 6, y, w - lx - 12 - bar, row_h - 2), p.accent, radius=r)) } - let fg = if i == st.hover { p.accent_foreground } else { p.foreground } - let sub = if i == st.hover { p.accent_foreground } else { p.foreground_muted } - let cx = 30 + let fg = if hot { p.accent_foreground } else { p.foreground } + let sub = if hot { p.accent_foreground } else { p.foreground_muted } + let cx = lx + 30 let cy = y + row_h / 2 - 1 let h = icon(a.id) if h != 0U { @@ -272,8 +419,17 @@ pub fn render_popup( let glyph = if a.glyph.length() > 0 { a.glyph } else { @dock.app_glyph(a.id, a.name) } ops.append(@dock.app_icon(cx, cy, icon_px - 2, a.id, glyph)) } - ops.push(@ui.text(56, y + 14, a.name, fs, fg, bold=true)) - ops.push(@ui.text(56, y + 31, a.comment, fs - 3, sub)) + ops.push(@ui.text(lx + 56, y + 14, a.name, fs, fg, bold=true)) + // An app without a comment (a web app, say) shows its category there. + let about = if a.comment.length() > 0 { a.comment } else { a.category } + ops.push(@ui.text(lx + 56, y + 31, about, fs - 3, sub)) + } + match thumb { + Some((ty, th)) => { + ops.push(@ui.fill_rect(@ui.rect(w - 11, header_h + 4, 5, max_rows * row_h - 8), p.surface, radius=2)) + ops.push(@ui.fill_rect(@ui.rect(w - 11, ty, 5, th), p.foreground_muted, radius=2)) + } + None => () } let status = status_text(st) if status != "" { @@ -283,7 +439,7 @@ pub fn render_popup( // The session row, under a divider. ops.push(@ui.fill_rect(@ui.rect(footer_margin, h - footer_h, w - 2 * footer_margin, 1), p.border)) for i = 0; i < session_actions.length(); i = i + 1 { - let (bx, by, bw, bh) = button_rect(i, h) + let (bx, by, bw, bh) = button_rect(i, size) let armed = st.armed == i let hot = st.hover_action == i if armed { @@ -303,13 +459,32 @@ pub fn render_popup( ops } -///| Row index under a popup-local point, or -1. +///| Index in `listed` of the app row under a popup-local point, or -1. pub fn row_at(apps : Array[@types.AppEntry], st : State, p : @types.Point) -> Int { - if p.x < 6 || p.x >= popup_w - 6 || p.y < header_h { + let n = listed(apps, st).length() + let lx = list_x(apps) + let right = lx + popup_w - (if n > max_rows { scrollbar_w } else { 6 }) + if p.x < lx + 6 || p.x >= right || p.y < header_h { return -1 } let i = (p.y - header_h) / row_h - if i < visible_rows(filter(apps, st.query).length()) { i } else { -1 } + if i < visible_rows(n) { first_row(n, st) + i } else { -1 } +} + +///| A press at a popup-local point on the scrollbar pages the list. False when it isn't on it. +fn scrollbar_press(apps : Array[@types.AppEntry], st : State, p : @types.Point) -> Bool { + let w = list_x(apps) + popup_w + match scroll_thumb(listed(apps, st).length(), st) { + Some((ty, th)) if p.x >= w - scrollbar_w && + p.x < w && + p.y >= header_h && + p.y < header_h + max_rows * row_h => { + let page = max_rows - 1 + ignore(scroll_by(apps, st, if p.y < ty { -page } else if p.y >= ty + th { page } else { 0 })) + true + } + _ => false + } } ///| Handle an event. `launch` is the host capability; `session` carries out a session-row action @@ -335,18 +510,21 @@ pub fn handle_event( (Popup, PointerMove(p)) => { let i = row_at(apps, st, p) let a = action_at(apps, st, p) - if i != st.hover || a != st.hover_action { + let c = category_at(apps, p) + if i != st.hover || a != st.hover_action || c != st.hover_category { st.hover = i st.hover_action = a + st.hover_category = c true } else { false } } (Popup, PointerLeave) => - if st.hover != -1 || st.hover_action != -1 { + if st.hover != -1 || st.hover_action != -1 || st.hover_category != -1 { st.hover = -1 st.hover_action = -1 + st.hover_category = -1 true } else { false @@ -358,6 +536,18 @@ pub fn handle_event( return true } st.armed = -1 + let c = category_at(apps, p) + if c >= 0 { + // Choosing a category ends the search. + st.category = if c == 0 { "" } else { categories(apps)[c] } + st.query = "" + st.scroll = 0 + st.hover = -1 + return true + } + if scrollbar_press(apps, st, p) { + return true + } let i = row_at(apps, st, p) if i >= 0 { activate(apps, st, i, launch) @@ -382,15 +572,21 @@ pub fn handle_event( st.query = st.query[:st.query.length() - 1].to_owned() } st.hover = -1 + st.scroll = 0 true + } else if k == "ScrollUp" { + scroll_by(apps, st, -1) + } else if k == "ScrollDown" { + scroll_by(apps, st, 1) } else if k == "Enter" { - if filter(apps, st.query).length() > 0 { + if listed(apps, st).length() > 0 { activate(apps, st, 0, launch) } true } else if k.length() == 1 { st.query = st.query + k st.hover = -1 + st.scroll = 0 true } else { false @@ -410,14 +606,14 @@ fn session_click(st : State, a : Int, session : (Int) -> Unit) -> Unit { session(a) } -///| Launch the i-th filtered app; a failure is shown in the popup (not hidden). +///| Launch the i-th listed app; a failure is shown in the popup (not hidden). fn activate( apps : Array[@types.AppEntry], st : State, i : Int, launch : (String) -> Result[Unit, String], ) -> Unit { - let a = filter(apps, st.query)[i] + let a = listed(apps, st)[i] match launch(a.id) { Ok(_) => close(st) Err(e) => st.error = "Launch failed: " + e @@ -504,8 +700,7 @@ test "search matches the app id and ranks name matches first" { ///| Popup-local centre of session button `a` for the apps and state given. fn button_centre(apps : Array[@types.AppEntry], st : State, a : Int) -> @types.Point { - let h = popup_size(apps, st).h.reinterpret_as_int() - let (x, y, w, bh) = button_rect(a, h) + let (x, y, w, bh) = button_rect(a, popup_size(apps, st)) { x: x + w / 2, y: y + bh / 2 } } @@ -614,6 +809,89 @@ test "shown_rows is the filtered list, capped at the rows that fit" { assert_eq(shown_rows(apps, st).map(a => a.id), ["app1", "app10", "app11"]) } +///| 20 apps: 12 in "Chrome Apps", 6 in "Games", 2 without a category. +fn long_catalog() -> Array[@types.AppEntry] { + Array::makei(20, i => { + id: "app" + i.to_string(), + name: "App " + i.to_string(), + comment: "", + category: if i < 6 { "Games" } else if i < 18 { "Chrome Apps" } else { "" }, + glyph: "", + }) +} + +///| +test "a catalog too long for the popup gets a category column" { + let apps = long_catalog() + assert_eq(categories(apps), ["All", "Chrome Apps", "Games", "Other"]) + // Short catalogs, and ones with a single category, have none. + assert_eq(categories(sample_apps()), []) + assert_eq(categories(apps.filter(a => a.category == "Chrome Apps")), []) + let st = State::new() + st.open = true + assert_eq(popup_size(apps, st).w.reinterpret_as_int(), popup_w + sidebar_w) + let launched : Array[String] = [] + let send = fn(ev : @types.InputEvent) { + handle_event(apps, st, Popup, ev, id => { + launched.push(id) + Ok(()) + }) + } + // The column's second row lists the Chrome apps only; nothing is launched. + let chrome : @types.Point = { x: 20, y: header_h + category_h + 4 } + assert_true(send(PointerMove(chrome))) + assert_eq((st.hover, st.hover_category), (-1, 1)) + assert_true(send(PointerDown(chrome))) + assert_eq(st.category, "Chrome Apps") + assert_eq(launched, []) + assert_eq(shown_rows(apps, st).map(a => a.id)[0], "app6") + assert_eq(listed(apps, st).length(), 12) + // "Other" holds the apps that name no category. + ignore(send(PointerDown({ x: 20, y: header_h + 3 * category_h + 4 }))) + assert_eq(listed(apps, st).map(a => a.id), ["app18", "app19"]) + // A search looks through everything; choosing a category ends it. + ignore(send(KeyDown("2"))) + assert_eq(listed(apps, st).map(a => a.id), ["app2", "app12"]) + ignore(send(PointerDown(chrome))) + assert_eq((st.query, listed(apps, st).length()), ("", 12)) + // A row launches the app it shows. + ignore(send(PointerDown({ x: sidebar_w + 20, y: header_h + row_h + 4 }))) + assert_eq(launched, ["app7"]) + // Closing forgets the category. + assert_eq((st.open, st.category), (false, "")) +} + +///| +test "the list scrolls with the wheel and the scrollbar" { + let apps = long_catalog() + let st = State::new() + st.open = true + let launched : Array[String] = [] + let send = fn(ev : @types.InputEvent) { + handle_event(apps, st, Popup, ev, id => { + launched.push(id) + Ok(()) + }) + } + assert_false(send(KeyDown("ScrollUp"))) + assert_true(send(KeyDown("ScrollDown"))) + assert_eq(shown_rows(apps, st)[0].id, "app1") + assert_eq(shown_rows(apps, st).length(), max_rows) + // Below the thumb: a page down, then to the end and no further. + let low : @types.Point = { x: sidebar_w + popup_w - 8, y: header_h + max_rows * row_h - 6 } + assert_true(send(PointerDown(low))) + assert_eq(shown_rows(apps, st)[0].id, "app8") + ignore(send(PointerDown(low))) + assert_eq(shown_rows(apps, st).last().unwrap().id, "app19") + assert_false(send(KeyDown("ScrollDown"))) + assert_eq(launched, []) + // Rows are hit where they are drawn. + assert_eq(row_at(apps, st, { x: sidebar_w + 20, y: header_h + 4 }), 12) + // Typing goes back to the top. + ignore(send(KeyDown("a"))) + assert_eq(st.scroll, 0) +} + ///| fn test_tokens() -> @theme.Tokens { {