garage44.eu/jeroen/pinnacle

logclone: git clone https://garage44.eu/jeroen/pinnacle.git

.. /view/src/lib.rs

raw

//! Apps built from views. An app describes its interface with Mithril —
//! elements, the component library's classes, signals for what changes —
//! and a [`Screen`] styles it with the library's stylesheet, lays it out for
//! the window's size, draws it into the window's pixels and turns the
//! window's input into the view's events. Only what changed is drawn again,
//! and only that area is sent to the display (`present`).
//!
//! It replaces, app by app, the hand-placed rectangles of `pinnacle_layout`
//! and the immediate drawing of `pinnacle_ui::theme`: an interface that is
//! responsive because the stylesheet is (flex, wrapping, the shell's
//! container widths), and the same library the web and Cartopolis use.

#![no_std]

extern crate alloc;

use alloc::string::String;
use alloc::vec::Vec;

use mithril_native::{Font as Spec, Fonts, Item, Modifiers, Press, Ui};
use mithril_style::cascade::Rgba;
use pinnacle_gfx::font::Face;
use pinnacle_gfx::{Canvas, Color, Font, Rect};
use pinnacle_rt::abi::InputEvent;
use pinnacle_ui::access;
use pinnacle_ui::keyboard::{Key, Keyboard};

pub use mithril_native as native;
pub use mithril_signals::{Computed, Effect, Signal, batch, computed, effect, signal};
pub use mithril_style::{Tokens, css};
/// An app's own rules, written with [`css!`], for [`Screen::with_rules`].
pub type Rules = Vec<mithril_style::Item>;
pub use mithril_view::{Event, IntoView, View, el, fragment};

/// Named controls and their centres, in window pixels.
type Places = Vec<(String, i32, i32)>;

/// Logical pixels to the window's: the library's sheet is drawn for a
/// 15 px body, the system's text is 20 px.
pub const SCALE: f32 = 4.0 / 3.0;

/// The library's tokens in the system's colours (`pinnacle_ui::theme`):
/// one dark look, the same in both of the sheet's themes. The ground is
/// the app icon's (`docs/brand/`), the accent the mark's orange, focus its
/// gold.
pub fn tokens() -> Tokens {
    let mut t = normal_tokens();
    if pinnacle_ui::access::current().high_contrast {
        // High contrast: a black ground, white text, dim text that is
        // still bright, borders that show, the accent lighter.
        let same = mithril_style::Pair::same;
        t.bg = same("#000000");
        t.surface = same("#000000");
        t.surface_raised = same("#0d0d0d");
        t.surface_sunken = same("#000000");
        t.control_bg = same("#000000");
        t.hover = same("#1f1f1f");
        t.pressed = same("#333333");
        t.text = same("#ffffff");
        t.text_strong = same("#ffffff");
        t.text_dim = same("#e0e0e0");
        t.text_faint = same("#c8c8c8");
        t.border = same("#ffffff");
        t.border_strong = same("#ffffff");
        t.accent = same("#ff7a33");
        t.accent_hover = same("#ff9a5c");
        t.accent_text = same("#ffb27f");
        t.accent_soft = same("rgb(255 122 51 / 28%)");
        t.on_accent = same("#000000");
        t.focus = same("#ffd75e");
    }
    t
}

/// The tokens in the system's ordinary colours.
fn normal_tokens() -> Tokens {
    use mithril_style::Pair;
    let mut t = Tokens::garage44();
    let same = Pair::same;
    t.bg = same("#0f1416");
    t.surface = same("#192023");
    t.surface_raised = same("#21292d");
    t.surface_sunken = same("#0a0e10");
    t.control_bg = same("#141a1d");
    t.hover = same("#222b2f");
    t.pressed = same("#2a3439");
    t.text = same("#eceeec");
    t.text_strong = same("#ffffff");
    t.text_dim = same("#8f9a9b");
    t.text_faint = same("#5f6a6c");
    t.border = same("#2a3439");
    t.border_strong = same("#3a464b");
    t.accent = same("#e85a12");
    t.accent_hover = same("#f56f24");
    t.accent_text = same("#ff9a5c");
    t.accent_soft = same("rgb(232 90 18 / 16%)");
    t.on_accent = same("#ffffff");
    t.focus = same("#f0c46a");
    t.success = same("#3fb97a");
    t.danger = same("#e56b6b");
    t
}

/// The system face at the sizes asked for so far.
struct Faces {
    face: &'static Face<'static>,
    /// The fixed-width face, for `font-family: monospace`.
    mono: &'static Face<'static>,
    /// By size (quarter pixels) and whether fixed-width.
    sizes: Vec<((i32, bool), Font)>,
}

impl Faces {
    fn new() -> Faces {
        Faces {
            face: pinnacle_ui::theme::body().face(),
            mono: pinnacle_ui::theme::mono().face(),
            sizes: Vec::new(),
        }
    }

    /// The face for `family` at `px` window pixels, to the quarter pixel.
    fn at(&mut self, px: f32, family: &str) -> &Font {
        let mono = family.contains("mono");
        let key = ((px * 4.0 + 0.5) as i32, mono);
        let i = match self.sizes.binary_search_by_key(&key, |(k, _)| *k) {
            Ok(i) => i,
            Err(i) => {
                let face = if mono { self.mono } else { self.face };
                self.sizes.insert(i, (key, Font::new(face, key.0 as f32 / 4.0)));
                i
            }
        };
        &self.sizes[i].1
    }
}

/// Text widths for the layout, in logical pixels.
struct Measure<'a> {
    faces: &'a mut Faces,
    scale: f32,
}

impl Fonts for Measure<'_> {
    fn width(&mut self, font: &Spec<'_>, text: &str) -> f32 {
        let f = self.faces.at(font.size * self.scale, font.family);
        let bold = embolden(font.weight, f.size);
        (f.measure(text) + bold) as f32 / self.scale
    }
}

/// An interface in a window, and the on-screen keyboard along its bottom
/// while a text field has the focus: the interface is laid out above it,
/// and scrolled so the field stays in view. A physical keyboard's first key
/// sends it away, as in the apps drawn by hand (`pinnacle_ui::keyboard`).
pub struct Screen {
    ui: Ui,
    /// The app's own rules ([`Screen::with_rules`]), kept for
    /// [`Screen::restyle`].
    rules: Rules,
    faces: Faces,
    keyboard: Keyboard,
    scale: f32,
    width: i32,
    height: i32,
    /// The on-screen keyboard is up.
    typing: bool,
    /// The keyboard came or went: everything is drawn afresh, and the
    /// focused field brought into view.
    relaid: bool,
    /// A key of the on-screen keyboard changed (pressed, shift): it is
    /// drawn again.
    keys_changed: bool,
    /// A clipboard key was typed (ctrl+V, ctrl+C): for the app to act on.
    clipboard: Option<Clipboard>,
    /// What [`Screen::announce`] said last: the prefix, and each named
    /// control's place. Said again where a place moved (a scroll, a list
    /// that grew), once no finger is down.
    announced: Option<(String, Places)>,
    /// A finger or a button is down.
    pressing: bool,
}

/// What a clipboard key asked of the app.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Clipboard {
    /// Ctrl+V: ask the display for what is on the clipboard
    /// (`App::paste`), and give the answer to [`Screen::paste`].
    Paste,
    /// Ctrl+C: put what the app takes to be meant on it (`App::copy`).
    Copy,
}

/// A focused field: one line, several (`<textarea>`), or an element that
/// edits text itself (`role="textbox"`, an editor): keys go to it as the
/// DOM names them, with the keys held, and it does what it likes with them.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Field {
    Line,
    Lines,
    Surface,
}

impl Screen {
    /// An empty interface for a window `width` × `height`, in the dark
    /// theme the system uses.
    pub fn new(width: u32, height: u32) -> Screen {
        // Larger text is the whole interface larger, laid out again for a
        // window that is so many logical pixels smaller: the stylesheet's
        // responsiveness does the rest.
        let scale = SCALE * f32::from(pinnacle_ui::access::current().text_size) / 100.0;
        let mut ui = Ui::new(tokens(), width as f32 / scale, height as f32 / scale);
        let mut env = ui.env().clone();
        env.dark = true;
        env.coarse_pointer = true;
        ui.set_env(env);
        Screen {
            ui,
            rules: Vec::new(),
            faces: Faces::new(),
            keyboard: Keyboard::new(),
            scale,
            width: width as i32,
            height: height as i32,
            typing: false,
            relaid: false,
            keys_changed: false,
            clipboard: None,
            announced: None,
            pressing: false,
        }
    }

    /// Where the on-screen keyboard is: empty, at the bottom, while it is
    /// down.
    fn keys_area(&self) -> Rect {
        if self.typing {
            self.keyboard.area(Rect::new(0, 0, self.width, self.height))
        } else {
            Rect::new(0, self.height, self.width, 0)
        }
    }

    /// The text field with the focus, if one has it.
    fn field(&self) -> Option<Field> {
        let tree = self.ui.tree();
        let n = tree.get(self.ui.focused()?)?;
        match n.tag()? {
            "textarea" => Some(Field::Lines),
            "input" => {
                let kind = n.attr("type").unwrap_or("text");
                let text = !matches!(
                    kind,
                    "checkbox" | "radio" | "range" | "button" | "submit" | "hidden"
                );
                text.then_some(Field::Line)
            }
            _ if n.attr("role") == Some("textbox") => Some(Field::Surface),
            _ => None,
        }
    }

    /// The focused field says Enter sends what it holds.
    fn sends(&self) -> bool {
        let tree = self.ui.tree();
        let focused = self.ui.focused().and_then(|f| tree.get(f));
        focused.is_some_and(|n| matches!(n.attr("enterkeyhint"), Some("send" | "go")))
    }

    /// Brings the keyboard up when a text field took the focus, and takes
    /// it away when none has it, or a physical key was typed.
    fn follow_focus(&mut self) {
        let typing = self.field().is_some() && !self.keyboard.physical;
        if typing != self.typing {
            self.typing = typing;
            self.relaid = true;
            let above = self.keys_area().y;
            self.ui
                .resize(self.width as f32 / self.scale, above as f32 / self.scale);
        }
    }

    /// Takes the focus from the field that has it: a press and a release
    /// where there is nothing.
    fn blur(&mut self) {
        self.ui.pointer(Press::Down, -1.0, -1.0);
        self.ui.pointer(Press::Up, -1.0, -1.0);
    }

    /// A key, from either keyboard, to the interface: a character, or a
    /// key as the DOM names it.
    fn type_key(&mut self, key: Key) {
        let mut buf = [0u8; 4];
        let shift = self.keyboard.shift_held();
        self.ui.set_modifiers(Modifiers {
            shift,
            ctrl: self.keyboard.ctrl_held(),
            alt: false,
        });
        let surface = self.field() == Some(Field::Surface);
        let name: &str = match key {
            Key::Char(c) => c.encode_utf8(&mut buf),
            Key::Space => " ",
            Key::Backspace => "Backspace",
            // Enter starts a new line in a field of several; in one of one
            // line it is done, after whoever listens for it heard it.
            Key::Enter if self.field() == Some(Field::Lines) => "\n",
            // One that sends or goes (`enterkeyhint="send"`, a chat's; "go", a
            // password's) keeps the focus and the keyboard, for what is next.
            Key::Enter => {
                self.ui.key("Enter");
                if self.field() == Some(Field::Line) && !self.sends() {
                    self.blur();
                }
                return;
            }
            // The clipboard is the app's to reach (`App::paste`,
            // `App::copy`): asked for here, answered by the app.
            Key::Paste => {
                self.clipboard = Some(Clipboard::Paste);
                return;
            }
            Key::Copy => {
                self.clipboard = Some(Clipboard::Copy);
                return;
            }
            // The caret's keys, with shift selecting as they move.
            Key::Left => "ArrowLeft",
            Key::Right => "ArrowRight",
            Key::Up => "ArrowUp",
            Key::Down => "ArrowDown",
            Key::Home => "Home",
            Key::End => "End",
            Key::Delete => "Delete",
            Key::Tab => "Tab",
            Key::Escape => "Escape",
            Key::PageUp => "PageUp",
            Key::PageDown => "PageDown",
            // Ctrl and a letter is the surface's to read (ctrl held, as the
            // modifiers say); a text field knows only select all.
            Key::Ctrl(c) if surface => c.encode_utf8(&mut buf),
            Key::Ctrl('a') => {
                self.ui.select_all();
                return;
            }
            _ => return,
        };
        self.ui.key_with(name, shift);
    }

    /// The part of a text field's value that is selected, if a part is:
    /// in the focused field, or in the one a tap on a button (Copy) just
    /// took the focus from.
    pub fn selected_text(&self) -> Option<String> {
        self.ui.selected_text()
    }

    /// Scrolls the focused field into the room above the keyboard.
    fn reveal(&mut self) {
        let Some(focus) = self.ui.focused() else {
            return;
        };
        let Some(r) = self.ui.tree().get(focus).map(|n| n.placed.rect) else {
            return;
        };
        let room = self.keys_area().y as f32 / self.scale;
        let margin = 16.0;
        let below = r.bottom() + margin - room;
        let above = margin - r.y;
        // Up until its bottom shows, but never past its top, for a field
        // taller than the room.
        let by = if below > 0.0 && above < 0.0 {
            below.min(-above)
        } else if above > 0.0 {
            -above
        } else {
            return;
        };
        self.ui.scroll(r.x + 1.0, r.y + 1.0, 0.0, by);
    }

    /// Whether the on-screen keyboard is up, as the last draw left it: an
    /// app with keys of its own to add above it (the terminal's) shows them.
    pub fn keyboard_shown(&self) -> bool {
        self.typing
    }

    /// The clipboard key typed since the last call, if one was.
    pub fn clipboard(&mut self) -> Option<Clipboard> {
        self.clipboard.take()
    }

    /// The clipboard's text, as `Event::Clipboard` brings it: into the
    /// focused text field. Returns whether one took it.
    pub fn paste(&mut self, text: &str) -> bool {
        self.ui.paste(text)
    }

    /// The library's sheet with the app's own rules after it: a state the
    /// library has no class for (a tile's press), styled as CSS is rather
    /// than by an inline style rewritten per state.
    pub fn with_rules(mut self, own: &[mithril_style::Item]) -> Screen {
        let stylist = mithril_style::Stylist::library_and(tokens(), own);
        let ui = core::mem::replace(&mut self.ui, Ui::new(tokens(), 1.0, 1.0));
        self.ui = ui.with_stylist(stylist);
        self.rules = own.to_vec();
        self
    }

    /// Takes the person's preferences as they are now (`Event::Preferences`):
    /// the text size and the contrast. The interface is emptied: the app
    /// mounts its view again, in the new language too.
    pub fn restyle(&mut self) {
        let mut fresh = Screen::new(self.width as u32, self.height as u32);
        if !self.rules.is_empty() {
            fresh = fresh.with_rules(&self.rules.clone());
        }
        fresh.announced = self.announced.take();
        *self = fresh;
        self.relaid = true;
    }

    pub fn mount(&mut self, view: View) {
        self.ui.mount(view);
    }

    pub fn clear(&mut self) {
        self.ui.clear();
    }

    /// The window changed size: everything is laid out and drawn afresh.
    pub fn resize(&mut self, width: u32, height: u32) {
        self.width = width as i32;
        self.height = height as i32;
        let above = self.keys_area().y;
        self.ui
            .resize(width as f32 / self.scale, above as f32 / self.scale);
        self.relaid = self.typing;
    }

    pub fn ui(&mut self) -> &mut Ui {
        &mut self.ui
    }

    /// Brings the interface up to date and draws what changed. Returns
    /// the area drawn, to present; `None` when nothing changed. `all`
    /// draws the whole window (after a resize, or when it was shown).
    pub fn draw(&mut self, canvas: &mut Canvas, all: bool) -> Option<Rect> {
        self.draw_with(canvas, all, &mut |_, _, _| {})
    }

    /// [`Screen::draw`], with the app drawing its `<canvas>` elements:
    /// `surfaces(name, canvas, rect)` for each in the area drawn, `name` its
    /// `data-name`, `rect` where it is in the window (the canvas's clip is
    /// the part being drawn). Move a canvas's `data-revision` on to have it
    /// drawn again.
    pub fn draw_with(
        &mut self,
        canvas: &mut Canvas,
        all: bool,
        surfaces: &mut dyn FnMut(&str, &mut Canvas, Rect),
    ) -> Option<Rect> {
        self.follow_focus();
        let relaid = core::mem::take(&mut self.relaid);
        let all = all || relaid;
        let mut measure = Measure {
            faces: &mut self.faces,
            scale: self.scale,
        };
        let mut damage = self.ui.frame(&mut measure);
        if relaid && self.typing {
            self.reveal();
            let mut measure = Measure {
                faces: &mut self.faces,
                scale: self.scale,
            };
            damage = self.ui.frame(&mut measure);
        }
        let keys = self.keys_area();
        let drawn_keys = (all || core::mem::take(&mut self.keys_changed)) && self.typing;
        if drawn_keys {
            canvas.set_clip(keys);
            self.keyboard.draw(canvas, keys);
        }
        let full = Rect::new(0, 0, self.width, keys.y);
        let area = if all {
            full
        } else {
            damage
                .map(|d| px_rect(&d.round_out(), self.scale).intersect(&full))
                .unwrap_or_default()
        };
        let drawn = match (area.is_empty(), drawn_keys) {
            (true, false) => None,
            (true, true) => Some(keys),
            (false, _) => {
                self.paint(canvas, area, surfaces);
                Some(if drawn_keys { area.union(&keys) } else { area })
            }
        };
        canvas.set_clip(Rect::new(0, 0, self.width, self.height));
        self.announce_moved();
        if pinnacle_ui::access::tree_wanted() && (drawn.is_some() || all) {
            pinnacle_ui::access::offer_tree(&self.access_tree());
        }
        drawn
    }

    /// The interface as the screen reader reads it: its headings, texts
    /// and controls in reading order, each with its role, name and state,
    /// those in the window only.
    pub fn access_tree(&self) -> Vec<access::Node> {
        let tree = self.ui.tree();
        let mut out = Vec::new();
        let window = Rect::new(0, 0, self.width, self.keys_area().y);
        walk(&tree, mithril_native::ROOT, self.scale, window, &mut out);
        out
    }

    /// Paints the interface's items in `area`.
    fn paint(&mut self, canvas: &mut Canvas, area: Rect, surfaces: &mut dyn FnMut(&str, &mut Canvas, Rect)) {
        let background = self.background();
        canvas.set_clip(area);
        canvas.fill_rect(area, background);
        let mut clips = alloc::vec![area];
        let scale = self.scale;
        for item in self.ui.items() {
            match item {
                Item::Fill { rect, color, radius } => {
                    let (c, a) = color_of(color);
                    canvas.fill_round_rect(px_rect(rect, scale), radii(radius, scale), c, a);
                }
                Item::Border {
                    rect,
                    widths,
                    color,
                    radius,
                } => {
                    let (c, a) = color_of(color);
                    let w = widths.map(|w| px_len(w, scale).max(if w > 0.0 { 1 } else { 0 }));
                    canvas.stroke_round_rect(px_rect(rect, scale), radii(radius, scale), w, c, a);
                }
                Item::Shadow {
                    rect,
                    color,
                    radius,
                    blur,
                } => {
                    // A blur as a few widening rings, each fainter.
                    let (c, a) = color_of(color);
                    let steps = (px_len(*blur, scale) / 2).clamp(1, 6);
                    let base = px_rect(rect, scale);
                    let r = radii(radius, scale);
                    for i in (0..steps).rev() {
                        let grow = (i + 1) * px_len(*blur, scale).max(1) / (2 * steps);
                        let ring = Rect::new(
                            base.x - grow,
                            base.y - grow,
                            base.width + 2 * grow,
                            base.height + 2 * grow,
                        );
                        let alpha = (u32::from(a) / (steps as u32 + 1)).max(1) as u8;
                        canvas.fill_round_rect(ring, r.map(|v| v + grow), c, alpha);
                    }
                }
                Item::Text {
                    x,
                    y,
                    height,
                    text,
                    size,
                    color,
                    family,
                    weight,
                } => {
                    let font = self.faces.at(size * scale, family);
                    let (c, _) = color_of(color);
                    let top = (y * scale) as i32;
                    let line = (height * scale) as i32;
                    let baseline = top + (line + font.ascent - font.descent) / 2;
                    let x = (x * scale) as i32;
                    canvas.text(font, x, baseline, text, c);
                    // The system has one weight: bold is the same glyphs
                    // again, a little to the right.
                    let bold = embolden(*weight, font.size);
                    if bold > 0 {
                        canvas.text(font, x + bold, baseline, text, c);
                    }
                }
                Item::Polyline { points, width, color } => {
                    let (c, a) = color_of(color);
                    let points: Vec<(f32, f32)> =
                        points.iter().map(|&(x, y)| (x * scale, y * scale)).collect();
                    canvas.stroke_polyline(&points, width * scale, c, a);
                }
                Item::Surface { rect, name, .. } => {
                    surfaces(name, canvas, px_rect(rect, scale));
                }
                Item::Clip { rect } => {
                    let top = *clips.last().expect("the damage is the outermost clip");
                    let clip = px_rect(rect, scale).intersect(&top);
                    clips.push(clip);
                    canvas.set_clip(clip);
                }
                Item::Unclip => {
                    if clips.len() > 1 {
                        clips.pop();
                    }
                    canvas.set_clip(*clips.last().expect("the damage stays"));
                }
            }
        }
    }

    /// Prints where every element named `data-name="…"` is, as
    /// `<prefix><name> at <x> <y>` (its centre, window pixels), one line
    /// each: how `cargo xtask` finds a control the stylesheet placed, where it
    /// used to compute the place from `pinnacle_layout`.
    ///
    /// Said once, it is said again by [`Screen::draw`] for the controls that
    /// moved since (a page scrolled by a finger), once the finger is up.
    pub fn announce(&mut self, prefix: &str) {
        let places = self.places();
        for (name, x, y) in &places {
            pinnacle_rt::println!("{prefix}{name} at {x} {y}");
        }
        self.announced = Some((String::from(prefix), places));
    }

    /// Says again where the named controls that moved are.
    fn announce_moved(&mut self) {
        if self.pressing || self.announced.is_none() {
            return;
        }
        let places = self.places();
        let Some((prefix, said)) = &mut self.announced else {
            return;
        };
        if *said == places {
            return;
        }
        for p in places.iter().filter(|p| !said.contains(p)) {
            pinnacle_rt::println!("{prefix}{} at {} {}", p.0, p.1, p.2);
        }
        *said = places;
    }

    /// Every named control's centre, in window pixels.
    fn places(&self) -> Places {
        let tree = self.ui.tree();
        tree.iter()
            .filter_map(|(_, n)| {
                // An option is tapped as its row in the select's open menu,
                // which carries its name; the option itself, in the closed
                // select, is shown or not at all.
                if n.tag() == Some("option") {
                    return None;
                }
                let name = n.attr("data-name")?;
                let r = &n.placed.rect;
                let (x, y) = ((r.x + r.w / 2.0) * self.scale, (r.y + r.h / 2.0) * self.scale);
                Some((String::from(name), x as i32, y as i32))
            })
            .collect()
    }

    /// The page's background: the tokens' `--m-bg` for the theme.
    fn background(&self) -> Color {
        let tree = self.ui.tree();
        let bg = tree
            .get(mithril_native::ROOT)
            .and_then(|n| n.style.as_ref())
            .and_then(|s| s.custom.get("--m-bg").and_then(|v| Rgba::parse(v)));
        bg.map_or(pinnacle_ui::theme::BACKGROUND, |c| color_of(&c).0)
    }

    /// Input from the window: pointer presses and moves, the on-screen
    /// keyboard's taps, physical keys.
    pub fn input(&mut self, e: &InputEvent) {
        let (x, y) = (e.x as f32 / self.scale, e.y as f32 / self.scale);
        let keys = self.keys_area();
        match e.kind {
            InputEvent::PRESS if self.typing && keys.contains(e.x, e.y) => {
                let (changed, key) = self.keyboard.touch(e.x, e.y, keys, e.value != 0);
                self.keys_changed |= changed;
                if let Some(key) = key {
                    self.type_key(key);
                }
            }
            InputEvent::PRESS => {
                let press = if e.value != 0 { Press::Down } else { Press::Up };
                self.pressing = press == Press::Down;
                self.ui.pointer(press, x, y);
                // Tapping a field calls the keyboard back after a physical
                // one sent it away; a press elsewhere (a button beside the
                // field) leaves it as it is, so what is pressed stays put.
                if press == Press::Down
                    && let (Some(field), Some(hit)) = (self.ui.focused(), self.ui.hit(x, y))
                    && self.ui.tree().contains(field, hit)
                {
                    self.keyboard.physical = false;
                }
            }
            InputEvent::MOVE => self.ui.pointer(Press::Move, x, y),
            InputEvent::KEY => {
                if let Some(key) = self.keyboard.key_event(e.code, e.value) {
                    self.type_key(key);
                    // An accent that went on nothing, then the key after it.
                    if let Some(key) = self.keyboard.queued() {
                        self.type_key(key);
                    }
                }
            }
            _ => {}
        }
    }
}

/// Whether a node is drawn at all: not `display: none`, not hidden.
fn shown(n: &mithril_native::tree::Node) -> bool {
    n.style
        .as_ref()
        .is_none_or(|s| s.visible && s.display != mithril_style::cascade::Display::None)
        && n.attr("aria-hidden") != Some("true")
}

/// The text under a node, its pieces joined by a comma, where a reader
/// pauses.
fn text_of(tree: &mithril_native::Tree, id: mithril_native::NodeId, out: &mut String) {
    use mithril_native::tree::NodeKind;
    let Some(n) = tree.get(id) else {
        return;
    };
    if !shown(n) {
        return;
    }
    match &n.kind {
        NodeKind::Text(t) => {
            let t = t.trim();
            if !t.is_empty() {
                if !out.is_empty() {
                    out.push_str(", ");
                }
                out.push_str(t);
            }
        }
        NodeKind::Element { .. } if control_role(n).is_some() => {}
        _ => {
            for &c in &n.children {
                text_of(tree, c, out);
            }
        }
    }
}

/// The role of an element a person acts on, if it is one.
fn control_role(n: &mithril_native::tree::Node) -> Option<access::Role> {
    use access::Role;
    let tag = n.tag()?;
    let role = n.attr("role");
    Some(match (tag, role) {
        (_, Some("switch")) => Role::Switch,
        (_, Some("checkbox")) => Role::Checkbox,
        (_, Some("button")) | ("button", _) => Role::Button,
        (_, Some("link")) => Role::Link,
        (_, Some("textbox")) | ("textarea", _) => Role::TextField,
        (_, Some("slider")) => Role::Slider,
        ("a", _) if n.attr("href").is_some() => Role::Link,
        ("input", _) => match n.attr("type").unwrap_or("text") {
            "checkbox" => Role::Checkbox,
            "radio" => Role::Checkbox,
            "range" => Role::Slider,
            "button" | "submit" => Role::Button,
            "hidden" => return None,
            _ => Role::TextField,
        },
        _ if n.handlers.iter().any(|(e, _)| e == "click") => Role::Control,
        _ => return None,
    })
}

/// Adds the nodes the screen reader reads under `id`, in document order.
fn walk(
    tree: &mithril_native::Tree,
    id: mithril_native::NodeId,
    scale: f32,
    window: Rect,
    out: &mut Vec<access::Node>,
) {
    use access::Role;
    use mithril_native::tree::NodeKind;
    let Some(n) = tree.get(id) else {
        return;
    };
    if !shown(n) {
        return;
    }
    let rect = px_rect(&n.placed.rect, scale);
    let (cx, cy) = (rect.x + rect.width / 2, rect.y + rect.height / 2);
    let visible = window.contains(cx, cy) && !rect.is_empty();
    let mut push = |role: Role, name: String, value: String, checked: Option<bool>| {
        if visible && !(name.is_empty() && value.is_empty() && role == Role::Text) {
            out.push(access::Node {
                role,
                name,
                value,
                checked,
                disabled: n.states().disabled,
                rect,
            });
        }
    };
    match &n.kind {
        NodeKind::Text(t) => {
            let t = t.trim();
            if !t.is_empty() {
                push(Role::Text, String::from(t), String::new(), None);
            }
            return;
        }
        NodeKind::Anchor => return,
        NodeKind::Element { .. } => {}
    }
    let label = n.attr("aria-label").map(String::from);
    if let Some(role) = control_role(n) {
        let mut name = label.unwrap_or_default();
        let mut value = String::new();
        let mut checked = None;
        match role {
            Role::Switch | Role::Checkbox => {
                checked = Some(n.prop("checked").is_some_and(|v| v != "false") || n.states().checked);
                if name.is_empty() {
                    // A switch in a row is named by the row's title: its
                    // first text.
                    let mut t = String::new();
                    if let Some(p) = n.parent {
                        text_of(tree, p, &mut t);
                    }
                    name = String::from(t.split(", ").next().unwrap_or(""));
                }
            }
            Role::TextField => {
                if name.is_empty() {
                    name = n.attr("placeholder").map(String::from).unwrap_or_default();
                }
                let v = n.value("value").unwrap_or("");
                value = if n.attr("type") == Some("password") {
                    v.chars().map(|_| '•').collect()
                } else {
                    String::from(v)
                };
            }
            Role::Slider => value = String::from(n.value("value").unwrap_or("")),
            _ => {
                if name.is_empty() {
                    text_of(tree, id, &mut name);
                    // The text of a control is read with it; its children
                    // are not read again.
                    let mut inner = String::new();
                    for &c in &n.children {
                        text_of(tree, c, &mut inner);
                    }
                    if name.is_empty() {
                        name = inner;
                    }
                }
            }
        }
        push(role, name, value, checked);
        return;
    }
    let tag = n.tag().unwrap_or("");
    let heading = matches!(tag, "h1" | "h2" | "h3" | "h4" | "h5" | "h6") || n.attr("role") == Some("heading");
    if heading || matches!(tag, "img") || n.attr("role") == Some("img") {
        let mut name = label.unwrap_or_default();
        if name.is_empty() {
            match n.attr("alt") {
                Some(alt) => name = String::from(alt),
                None => text_of(tree, id, &mut name),
            }
        }
        push(
            if heading { Role::Heading } else { Role::Image },
            name,
            String::new(),
            None,
        );
        return;
    }
    if n.attr("role") == Some("listitem") || tag == "li" {
        // A row: its words read together, then its controls one by one.
        let mut name = label.unwrap_or_default();
        if name.is_empty() {
            text_of(tree, id, &mut name);
        }
        push(Role::ListItem, name, String::new(), None);
        drop(push);
        for &c in &n.children {
            controls(tree, c, scale, window, out);
        }
        return;
    }
    if let Some(label) = label {
        push(Role::Text, label, String::new(), None);
        return;
    }
    drop(push);
    for &c in &n.children {
        walk(tree, c, scale, window, out);
    }
}

/// Only the controls under `id`, for a row whose words were read whole.
fn controls(
    tree: &mithril_native::Tree,
    id: mithril_native::NodeId,
    scale: f32,
    window: Rect,
    out: &mut Vec<access::Node>,
) {
    let Some(n) = tree.get(id) else {
        return;
    };
    if !shown(n) {
        return;
    }
    if control_role(n).is_some() {
        walk(tree, id, scale, window, out);
        return;
    }
    for &c in &n.children {
        controls(tree, c, scale, window, out);
    }
}

/// How far to the right bold text is drawn a second time, in window
/// pixels, for a face `size` pixels: 0 below `font-weight: 600`.
fn embolden(weight: u16, size: i32) -> i32 {
    if weight >= 600 { (size / 20).max(1) } else { 0 }
}

fn px_len(v: f32, scale: f32) -> i32 {
    (v * scale + 0.5) as i32
}

/// A logical rectangle in window pixels, its edges rounded to the nearest.
fn px_rect(r: &mithril_native::Rect, scale: f32) -> Rect {
    let x = px_len(r.x, scale);
    let y = px_len(r.y, scale);
    Rect::new(x, y, px_len(r.right(), scale) - x, px_len(r.bottom(), scale) - y)
}

fn radii(r: &[f32; 4], scale: f32) -> [i32; 4] {
    r.map(|v| px_len(v, scale))
}

fn color_of(c: &Rgba) -> (Color, u8) {
    let ch = |v: f32| (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8;
    (Color::rgb(ch(c.r), ch(c.g), ch(c.b)), ch(c.a))
}