Files
chandra/lib/launcher/launcher.mbt
T
nandiandClaude Opus 5.5 2f404ced5c
CI / test (push) Canceled after 0s
Launcher: draw the search field focused, with a caret
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 00:28:57 -08:00

949 lines
30 KiB
MoonBit

///| Kickoff-style application launcher: state machine + render logic. Pure;
/// host capabilities (app list, launch, session and power actions) are passed in by the
/// component stub.
///
/// 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 {
Widget
Popup
}
///|
pub struct State {
mut open : Bool
mut query : String
mut hover : Int
mut error : String
/// Session button under the pointer (-1: none).
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,
category: "",
scroll: 0,
hover_category: -1,
}
}
///| The session row's buttons, in order. `handle_event`'s `session` callback gets the index.
pub let session_actions : Array[String] = [
"Reload", "Log out", "Suspend", "Restart", "Power off",
]
///| Index of each session action.
pub let action_reload : Int = 0
///|
pub let action_logout : Int = 1
///|
pub let action_suspend : Int = 2
///|
pub let action_restart : Int = 3
///|
pub let action_power_off : Int = 4
///| Whether an action ends or interrupts the session and so takes a second click.
pub fn needs_confirm(action : Int) -> Bool {
action == action_logout || action == action_restart || action == action_power_off
}
///| What the status line says while `action` is armed.
fn confirm_hint(action : Int) -> String {
"Click " + session_actions[action] + " again to confirm"
}
///|
pub let popup_w : Int = 340
///|
let header_h : Int = 52
///|
let row_h : Int = 46
///|
let max_rows : Int = 8
///| The session row at the bottom of the popup, and the status line above it (shown only when
/// there is something to say: a launch error, or which button is waiting to be confirmed).
let footer_h : Int = 44
///|
let status_h : Int = 22
///|
let footer_margin : Int = 8
///|
let button_gap : Int = 4
///|
fn ascii_lower(s : String) -> String {
let sb = StringBuilder()
for c in s {
if c >= 'A' && c <= 'Z' {
sb.write_char(Int::unsafe_to_char(c.to_int() + 32))
} else {
sb.write_char(c)
}
}
sb.to_string()
}
///|
fn contains_ci(hay : String, needle : String) -> Bool {
if needle.length() == 0 {
return true
}
ascii_lower(hay).contains(ascii_lower(needle))
}
///| KRunner-ish filter: case-insensitive substring over name, id, comment and
/// category. Name matches come first, then the rest; each group keeps its order.
pub fn filter(apps : Array[@types.AppEntry], query : String) -> Array[@types.AppEntry] {
let by_name = apps.filter(a => contains_ci(a.name, query))
let others = apps.filter(a => {
!contains_ci(a.name, query) &&
(contains_ci(a.id, query) ||
contains_ci(a.comment, query) ||
contains_ci(a.category, query))
})
by_name + others
}
///|
fn visible_rows(n : Int) -> Int {
if n > max_rows { max_rows } else { n }
}
///| 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.
let icon_px : Int = 32
///|
pub fn popup_size(apps : Array[@types.AppEntry], st : State) -> @types.Size {
let status = if status_text(st) == "" { 0 } else { status_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 "".
fn status_text(st : State) -> String {
if st.error.length() > 0 {
st.error
} else if st.armed >= 0 {
confirm_hint(st.armed)
} else {
""
}
}
///| 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()
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 size = popup_size(apps, st)
for i = 0; i < session_actions.length(); i = i + 1 {
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
}
}
-1
}
///|
pub fn close(st : State) -> Unit {
st.open = false
st.query = ""
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).
pub fn render_button(
size : @types.Size,
t : @theme.Tokens,
st : State,
) -> Array[@types.DrawOp] {
let w = size.w.reinterpret_as_int()
let h = size.h.reinterpret_as_int()
let bg = if st.open { t.palette.accent } else { t.palette.surface_hover }
let fg = if st.open { t.palette.accent_foreground } else { t.palette.foreground }
let r = t.radius.reinterpret_as_int()
let fs = t.font_size.reinterpret_as_int()
let cy = h / 2
let ops = [@ui.fill_rect(@ui.rect(0, 0, w, h), bg, radius=r)]
if 36 + @ui.text_width("Applications", fs) + 12 <= w {
// Crescent: light disc with a button-coloured disc biting into it.
ops.push(@ui.circle(18, cy, 9, fg))
ops.push(@ui.circle(22, cy - 3, 8, bg))
ops.push(@ui.text(36, cy, "Applications", fs, fg, bold=true))
} else if 34 + @ui.text_width("Apps", fs) + 10 <= w {
ops.push(@ui.circle(17, cy, 9, fg))
ops.push(@ui.circle(21, cy - 3, 8, bg))
ops.push(@ui.text(34, cy, "Apps", fs, fg, bold=true))
} else {
let cx = w / 2
ops.push(@ui.circle(cx, cy, 9, fg))
ops.push(@ui.circle(cx + 4, cy - 3, 8, bg))
}
ops
}
///|
///| Draw the open popup. `icon` gives an app id's .desktop icon as an image handle (0: none, the
/// app's letter tile is drawn instead, the same one the dock uses).
pub fn render_popup(
apps : Array[@types.AppEntry],
t : @theme.Tokens,
st : State,
icon~ : (String) -> UInt = _ => 0U,
) -> Array[@types.DrawOp] {
let size = popup_size(apps, st)
let w = size.w.reinterpret_as_int()
let h = size.h.reinterpret_as_int()
let fs = t.font_size.reinterpret_as_int()
let r = t.radius.reinterpret_as_int()
let p = t.palette
let ops = [
@ui.fill_rect(@ui.rect(0, 0, w, h), p.surface_popup, radius=r + 4),
@ui.stroke_rect(@ui.rect(0, 0, w, h), p.border, radius=r + 4),
// The search field. It has the keyboard as long as the menu is open, so it is always drawn
// focused: an accent outline and a caret.
@ui.fill_rect(@ui.rect(10, 10, w - 20, 32), p.surface, radius=r),
@ui.stroke_rect(@ui.rect(10, 10, w - 20, 32), p.accent, width=2, radius=r),
]
if st.query.length() == 0 {
ops.push(@ui.fill_rect(@ui.rect(20, 18, 2, 16), p.accent))
ops.push(@ui.text(26, 26, "Type to search applications...", fs - 1, p.foreground_muted))
} else {
// The caret is a glyph: it has to follow text whose width only the renderer knows.
ops.push(@ui.text(20, 26, st.query + "|", fs, p.foreground))
}
// 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(lx + (w - lx) / 2, header_h + row_h / 2, "No matching applications", fs, p.foreground_muted, align=CENTER),
)
}
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
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 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 {
ops.push(@types.DrawOp::Image({ rect: @ui.rect(cx - icon_px / 2, cy - icon_px / 2, icon_px, icon_px), image: h }))
} else {
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(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 != "" {
let color = if st.error.length() > 0 { @ui.color(240, 90, 90, 255) } else { p.accent }
ops.push(@ui.text(14, h - footer_h - status_h / 2, status, fs - 3, color, bold=st.error == ""))
}
// 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, size)
let armed = st.armed == i
let hot = st.hover_action == i
if armed {
ops.push(@ui.fill_rect(@ui.rect(bx, by, bw, bh), p.accent, radius=r))
} else if hot {
ops.push(@ui.fill_rect(@ui.rect(bx, by, bw, bh), p.surface_hover, radius=r))
}
let fg = if armed {
p.accent_foreground
} else if hot {
p.foreground
} else {
p.foreground_muted
}
ops.push(@ui.text(bx + bw / 2, by + bh / 2, session_actions[i], fs - 3, fg, align=CENTER, bold=armed))
}
ops
}
///| 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 {
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(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
/// (an index into `session_actions`) once it is confirmed. Returns true on redraw.
pub fn handle_event(
apps : Array[@types.AppEntry],
st : State,
target : Target,
ev : @types.InputEvent,
launch : (String) -> Result[Unit, String],
session~ : (Int) -> Unit = _ => (),
) -> Bool {
match (target, ev) {
(Widget, PointerDown(_)) => {
if st.open {
close(st)
} else {
st.open = true
st.error = ""
}
true
}
(Popup, PointerMove(p)) => {
let i = row_at(apps, st, p)
let a = action_at(apps, st, p)
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 || st.hover_category != -1 {
st.hover = -1
st.hover_action = -1
st.hover_category = -1
true
} else {
false
}
(Popup, PointerDown(p)) => {
let a = action_at(apps, st, p)
if a >= 0 {
session_click(st, a, session)
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)
}
true
}
(_, FocusLost) =>
if st.open {
close(st)
true
} else {
false
}
(_, KeyDown(k)) =>
if !st.open {
false
} else if k == "Escape" {
close(st)
true
} else if k == "Backspace" {
if st.query.length() > 0 {
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 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
}
_ => false
}
}
///| A click on session button `a`: act now, or arm it and act on a second click.
fn session_click(st : State, a : Int, session : (Int) -> Unit) -> Unit {
if needs_confirm(a) && st.armed != a {
st.armed = a
st.error = ""
return
}
close(st)
session(a)
}
///| 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 = listed(apps, st)[i]
match launch(a.id) {
Ok(_) => close(st)
Err(e) => st.error = "Launch failed: " + e
}
}
///|
fn sample_apps() -> Array[@types.AppEntry] {
[
{ id: "a", name: "Terminal", comment: "Command line", category: "System", glyph: ">_" },
{ id: "b", name: "Files", comment: "Browse folders", category: "Utilities", glyph: "F" },
{ id: "c", name: "Web Browser", comment: "Browse the web", category: "Internet", glyph: "W" },
]
}
///|
test "filter is case-insensitive over name/comment/category" {
let apps = sample_apps()
assert_eq(filter(apps, "").length(), 3)
assert_eq(filter(apps, "TERM").length(), 1)
assert_eq(filter(apps, "folders")[0].id, "b")
assert_eq(filter(apps, "internet")[0].id, "c")
assert_eq(filter(apps, "zzz").length(), 0)
}
///|
test "open, type, launch via keyboard" {
let apps = sample_apps()
let st = State::new()
let launched : Array[String] = []
let launch = id => {
launched.push(id)
Ok(())
}
assert_true(handle_event(apps, st, Widget, PointerDown({ x: 1, y: 1 }), launch))
assert_true(st.open)
assert_true(handle_event(apps, st, Popup, KeyDown("f"), launch))
assert_true(handle_event(apps, st, Popup, KeyDown("i"), launch))
assert_eq(st.query, "fi")
assert_true(handle_event(apps, st, Popup, KeyDown("Enter"), launch))
assert_eq(launched, ["b"])
assert_false(st.open)
}
///|
test "click on a row launches; failure is surfaced and keeps the menu open" {
let apps = sample_apps()
let st = State::new()
st.open = true
let i = row_at(apps, st, { x: 20, y: 52 + 46 + 5 })
assert_eq(i, 1)
let _ = handle_event(
apps,
st,
Popup,
PointerDown({ x: 20, y: 52 + 46 + 5 }),
_ => Err("boom"),
)
assert_true(st.open)
assert_eq(st.error, "Launch failed: boom")
}
///|
test "focus loss closes and hover tracks the pointer" {
let apps = sample_apps()
let st = State::new()
st.open = true
assert_true(handle_event(apps, st, Popup, PointerMove({ x: 20, y: 60 }), _ => Ok(())))
assert_eq(st.hover, 0)
assert_false(handle_event(apps, st, Popup, PointerMove({ x: 21, y: 61 }), _ => Ok(())))
assert_true(handle_event(apps, st, Widget, FocusLost, _ => Ok(())))
assert_false(st.open)
}
///|
test "search matches the app id and ranks name matches first" {
let apps : Array[@types.AppEntry] = [
{ id: "org.kde.kate", name: "Text Editor", comment: "", category: "Utility", glyph: "T" },
{ id: "x.pad", name: "Kate Pad", comment: "", category: "Utility", glyph: "K" },
]
let r = filter(apps, "kate")
assert_eq(r.map(a => a.id), ["x.pad", "org.kde.kate"])
}
///| 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 (x, y, w, bh) = button_rect(a, popup_size(apps, st))
{ x: x + w / 2, y: y + bh / 2 }
}
///|
test "session row: Reload and Suspend act at once, closing the menu" {
let apps = sample_apps()
let st = State::new()
st.open = true
let done : Array[Int] = []
let p = button_centre(apps, st, action_reload)
assert_eq(action_at(apps, st, p), action_reload)
assert_true(handle_event(apps, st, Popup, PointerDown(p), _ => Ok(()), session=a => done.push(a)))
assert_eq(done, [action_reload])
assert_false(st.open)
st.open = true
let p = button_centre(apps, st, action_suspend)
let _ = handle_event(apps, st, Popup, PointerDown(p), _ => Ok(()), session=a => done.push(a))
assert_eq(done, [action_reload, action_suspend])
}
///|
test "session row: Log out, Restart and Power off take a second click" {
let apps = sample_apps()
let st = State::new()
st.open = true
let done : Array[Int] = []
let session = a => done.push(a)
let click = a => {
let p = button_centre(apps, st, a)
ignore(handle_event(apps, st, Popup, PointerDown(p), _ => Ok(()), session~))
}
click(action_logout)
assert_eq(done, [])
assert_eq(st.armed, action_logout)
assert_true(st.open)
// The popup grew a status line; the hint names the button.
assert_eq(status_text(st), "Click Log out again to confirm")
// Another armed button takes over; nothing runs.
click(action_power_off)
assert_eq(st.armed, action_power_off)
assert_eq(done, [])
click(action_power_off)
assert_eq(done, [action_power_off])
assert_false(st.open)
assert_eq(st.armed, -1)
// Closing the menu disarms: reopening and clicking once does nothing yet.
st.open = true
click(action_restart)
ignore(handle_event(apps, st, Widget, FocusLost, _ => Ok(()), session~))
st.open = true
click(action_restart)
assert_eq(done, [action_power_off])
click(action_restart)
assert_eq(done, [action_power_off, action_restart])
}
///|
test "session row: a click on an app disarms, and app rows don't reach the row" {
let apps = sample_apps()
let st = State::new()
st.open = true
let p = button_centre(apps, st, action_logout)
assert_eq(row_at(apps, st, p), -1)
ignore(handle_event(apps, st, Popup, PointerDown(p), _ => Ok(())))
assert_eq(st.armed, action_logout)
ignore(handle_event(apps, st, Popup, PointerDown({ x: 20, y: 60 }), _ => Ok(())))
assert_eq(st.armed, -1)
}
///| The image ops of a drawing, with the handles they draw.
fn images(ops : Array[@types.DrawOp]) -> Array[UInt] {
ops.filter_map(op => match op { Image(img) => Some(img.image); _ => None })
}
///|
test "rows draw the app's .desktop icon, or the letter tile when it has none" {
let apps = sample_apps()
let st = State::new()
st.open = true
let asked : Array[String] = []
let icon = fn(id : String) {
asked.push(id)
if id == "b" { 0U } else if id == "a" { 7U } else { 9U }
}
let ops = render_popup(apps, test_tokens(), st, icon~)
assert_eq(asked, ["a", "b", "c"])
assert_eq(images(ops), [7U, 9U])
// Files has no icon: its tile shows its glyph.
assert_true(ops.iter().any(op => match op { Text(t) => t.text == "F"; _ => false }))
// With a search only the matching rows ask for icons.
st.query = "term"
asked.clear()
assert_eq(images(render_popup(apps, test_tokens(), st, icon~)), [7U])
assert_eq(asked, ["a"])
}
///|
test "shown_rows is the filtered list, capped at the rows that fit" {
let apps : Array[@types.AppEntry] = []
for i = 0; i < 12; i = i + 1 {
apps.push({ id: "app" + i.to_string(), name: "App " + i.to_string(), comment: "", category: "", glyph: "" })
}
let st = State::new()
assert_eq(shown_rows(apps, st).length(), max_rows)
st.query = "App 1"
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 open menu's search field looks focused, empty or not" {
let st = State::new()
st.open = true
let t = test_tokens()
let outlined = fn() {
render_popup(sample_apps(), t, st).iter().any(op => match op {
StrokeRect(s) => s.rect.y == 10 && s.color.b == t.palette.accent.b
_ => false
})
}
assert_true(outlined())
// Empty: the caret before the hint.
assert_true(
render_popup(sample_apps(), t, st).iter().any(op => match op {
FillRect(f) => f.rect.x == 20 && f.rect.w == 2U && f.color.b == t.palette.accent.b
_ => false
}),
)
st.query = "ma"
assert_true(outlined())
assert_true(
render_popup(sample_apps(), t, st).iter().any(op => match op {
Text(x) => x.text == "ma|"
_ => 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 {
{
name: "t",
palette: {
desktop_top: @ui.color(0, 0, 0, 255),
desktop_bottom: @ui.color(0, 0, 0, 255),
surface: @ui.color(30, 30, 30, 255),
surface_hover: @ui.color(40, 40, 40, 255),
surface_popup: @ui.color(30, 30, 30, 255),
foreground: @ui.color(255, 255, 255, 255),
foreground_muted: @ui.color(150, 150, 150, 255),
accent: @ui.color(60, 120, 220, 255),
accent_foreground: @ui.color(255, 255, 255, 255),
border: @ui.color(60, 60, 60, 255),
},
font_size: 14U,
radius: 6U,
spacing: 6U,
panel_height: 44U,
}
}