Skip to main content

day_spec/
lib.rs

1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3
4//! day-spec: the toolkit specification (DESIGN.md §8).
5//!
6//! Backends depend only on this crate (never on day-core). One backend is linked per binary;
7//! `day-core` is monomorphized over the concrete [`Toolkit`].
8
9use std::any::Any;
10use std::collections::HashMap;
11
12pub use day_geometry::*;
13// `Support` is in `Toolkit`'s signatures and every backend trampoline runs through the guard, so
14// a backend reaches both from the contract crate it already depends on. day-process owns them.
15pub use day_process::{Support, ffi_guard};
16// The link-time registry crate `renderer!` expands to, so a renderer needs no dependency on it.
17pub use day_process::linkme;
18
19pub mod controls;
20pub use controls::datetime::{DayDate, DayTime, now_epoch_millis, now_epoch_secs};
21
22pub mod applications;
23pub mod capture;
24/// Inline markdown → styled runs (docs/markdown.md). Lives here rather than in day-pieces
25/// because it produces `TextRun`s, and every format codec beside it reads the same model.
26pub mod markdown;
27pub mod render;
28pub use render::fill_measure;
29/// Bundled-resource random-access API + the per-backend `ResourceOpener` hook (§18.3).
30pub mod resource;
31/// Styled text: the document model `label().runs(…)` renders and `day-piece-text-editor` edits,
32/// with the Markdown / HTML / RTF codecs over it (docs/texteditor.md).
33pub mod styled;
34/// Import and export for [`StyledText`]: Markdown, HTML and RTF (docs/texteditor.md).
35pub mod styled_codec;
36pub mod transfer;
37
38pub use resource::{
39    AssetDir, AssetName, FontFamily, ImageName, Resource, ResourceOpener, VectorName,
40    resolve_asset_dir, resolve_image_file, resource, set_resource_opener,
41};
42pub use styled::{
43    ListStyle, ParagraphAlign, ParagraphRun, ParagraphStyle, RunStyle, StyledText, Underline,
44    coalesce_runs, paragraph_bounds, paragraphs_are_valid,
45};
46pub use styled_codec::{
47    DocStyle, html_to_styled, markdown_to_styled, rtf_to_styled, styled_to_html,
48    styled_to_markdown, styled_to_rtf,
49};
50
51/// Bundled custom fonts: name-table parsing, runtime font directory, family → file resolution
52/// (§18.4). Shared by the CLI stagers and the backends' startup registration. Lives in the leaf
53/// `day-fonts` crate (pure std, no `day-geometry`), re-exported here so `day_spec::fonts::…` is
54/// unchanged for the backends while the CLI can depend on `day-fonts` alone.
55pub use day_fonts as fonts;
56
57/// The route inside a deep-link URL (docs/deep-links.md): everything after `scheme://`,
58/// query included (`notes://mail/inbox?hint=x` ⇒ `mail/inbox?hint=x`). A string with no
59/// scheme passes through unchanged (it is already a route). One definition, shared by every
60/// platform's intake and the dayscript `deep_link` step, so a URL maps to the same route
61/// bytes everywhere; percent-decoding stays with the route parser (docs/navigation.md).
62#[must_use]
63pub fn route_of_url(url: &str) -> String {
64    match url.split_once("://") {
65        Some((_, rest)) => rest.to_string(),
66        None => url.to_string(),
67    }
68}
69
70// ---------------------------------------------------------------------------
71// Identity
72// ---------------------------------------------------------------------------
73
74/// Interned piece-kind key, e.g. `"day.label"` or `"acme.combobox"`.
75pub type PieceKind = &'static str;
76
77/// Declare the built-in piece vocabulary once: the [`Builtin`] enum, its string keys, and the
78/// `kinds::*` constants are all generated from this list, so they can never drift apart.
79///
80/// Adding a variant here is a breaking change for backends: every `Toolkit` must decide how
81/// to realize the new kind, and the exhaustive `match Builtin` in each backend's `realize`
82/// turns that decision into a compile error rather than a runtime placeholder.
83macro_rules! builtin_kinds {
84    ($( $(#[$meta:meta])* $variant:ident = $konst:ident => $key:literal ),+ $(,)?) => {
85        /// Every piece kind Day itself defines (§5.3). Backends match on this exhaustively in
86        /// `realize`; anything outside it is an extension piece resolved through the
87        /// [`Registry`] by its string [`PieceKind`].
88        #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
89        pub enum Builtin {
90            $( $(#[$meta])* $variant, )+
91        }
92
93        impl Builtin {
94            /// This kind's wire key: the same string as the matching `kinds::*` constant.
95            pub const fn key(self) -> PieceKind {
96                match self { $( Builtin::$variant => $key, )+ }
97            }
98
99            /// The built-in this key names, or `None` for an extension piece's kind.
100            pub fn from_key(kind: PieceKind) -> Option<Builtin> {
101                match kind {
102                    $( $key => Some(Builtin::$variant), )+
103                    _ => None,
104                }
105            }
106
107            /// Every built-in, in declaration order (conformance tests iterate it).
108            pub const ALL: &'static [Builtin] = &[ $( Builtin::$variant, )+ ];
109        }
110
111        /// The built-in piece keys as plain strings, for the registry and the `PieceKind` API.
112        pub mod kinds {
113            $( $(#[$meta])* pub const $konst: super::PieceKind = super::Builtin::$variant.key(); )+
114        }
115    };
116}
117
118builtin_kinds! {
119    /// A dumb native panel (the column/row/stack backing).
120    Container = CONTAINER => "day.container",
121    Label = LABEL => "day.label",
122    Button = BUTTON => "day.button",
123    Toggle = TOGGLE => "day.toggle",
124    Slider = SLIDER => "day.slider",
125    TextField = TEXT_FIELD => "day.text_field",
126    /// A native multi-line text editor (docs/textarea.md). Built-in since 2026-07 (previously
127    /// the satellite `day-piece-textarea`).
128    TextArea = TEXT_AREA => "day.text_area",
129    /// A native option picker with menu/segmented/inline stylings (docs/picker.md). Built-in
130    /// since 2026-07 (previously the satellite `day-piece-picker`).
131    Picker = PICKER => "day.picker",
132    Divider = DIVIDER => "day.divider",
133    Scroll = SCROLL => "day.scroll",
134    Image = IMAGE => "day.image",
135    /// Progress indicator: determinate bar (fraction) or indeterminate spinner.
136    Progress = PROGRESS => "day.progress",
137    Canvas = CANVAS => "day.canvas",
138    /// Navigation host (docs/navigation.md): stack on mobile, split panes on desktop.
139    Nav = NAV => "day.nav",
140    /// One destination's native container inside a NAV host.
141    NavPage = NAV_PAGE => "day.nav_page",
142    /// Native navigation item list (docs/navigation.md): `NSOutlineView` source list /
143    /// `GtkListBox` navigation-sidebar / `QListWidget` / `UITableView` rows with chevrons.
144    NavMenu = NAV_MENU => "day.nav_menu",
145    /// Native recycling list (docs/list.md): `NSTableView` / `UITableView` / `RecyclerView` /
146    /// `GtkListView` / `QListView`. Owns scrolling + cell reuse; Day binds row content on demand.
147    List = LIST => "day.list",
148    /// A recycled row's content anchor inside a `LIST`; Day adopts the native cell as its handle.
149    /// Adopted, never realized: `Toolkit::adopt` wraps the native cell, so backends' `realize`
150    /// never sees this kind.
151    ListCell = LIST_CELL => "day.list_cell",
152    /// Native hierarchical tree (docs/tree.md): `NSOutlineView` / sidebar collection list /
153    /// `GtkListView`+`TreeListModel` / WinUI `TreeView` / ArkTS `TreeView`. Rows nest, disclose, and
154    /// drag-to-reparent; Day binds row content on demand through `Toolkit::attach_tree`.
155    /// Row cells are adopted (the same `LIST_CELL` anchor path as `List`).
156    Tree = TREE => "day.tree",
157    /// A fullscreen cover (docs/cover.md): a modal surface presented over the whole window,
158    /// edge-to-edge, driven by `CoverPatch::{Present,Dismiss}`. The handle is the cover's
159    /// content container; its frame is native-owned while presented (the backend sizes it to
160    /// the safe area and reports it via `Event::FrameChanged`).
161    Cover = COVER => "day.cover",
162    /// Content beside a trailing inspector pane (docs/inspector.md): the native split whose
163    /// second pane is a show/hidable properties panel. Exactly two `INSPECTOR_PANE` children:
164    /// the content, then the panel (`InspectorPaneProps::panel`). Only realized where
165    /// `Cap::Inspector` answers `Native`; everywhere else the `inspector` piece composes the
166    /// pane from plain containers and this kind never reaches the backend.
167    Inspector = INSPECTOR => "day.inspector",
168    /// One pane's container inside an `INSPECTOR` host: the `NAV_PAGE` of the inspector split.
169    /// Its frame is native-owned (the splitter/dock sizes it), reported via
170    /// `Event::FrameChanged` on this node; Day lays the pane's content out inside it.
171    InspectorPane = INSPECTOR_PANE => "day.inspector_pane",
172    /// Two panes with a divider the user drags (docs/split.md): the toolkit's own splitter,
173    /// side by side or stacked (`SplitProps::axis`), the first pane's share bound to the app
174    /// (`SplitProps::fraction`, reported back as `Event::ValueChanged`). Exactly two
175    /// `SPLIT_PANE` children, first then second. Only realized where `Cap::Split` answers
176    /// `Native`; everywhere else the `split` piece composes the panes and draws the divider
177    /// itself, and this kind never reaches the backend.
178    Split = SPLIT => "day.split",
179    /// One pane's container inside a `SPLIT` host: native-owned frame (the splitter sizes it),
180    /// reported via `Event::FrameChanged` on this node, like an `INSPECTOR_PANE`.
181    SplitPane = SPLIT_PANE => "day.split_pane",
182    /// A list row's standard content (docs/list.md "List items"): a leading icon, a title, an
183    /// optional subtitle and trailing detail, and a check mark, drawn the way the platform
184    /// draws its own list rows: a `UIListContentView` with the cell's default content
185    /// configuration, a Material list item, an `NSTableCellView`'s image and text, a GTK row
186    /// box. Only realized where `Cap::ListItem` answers `Native`; everywhere else the
187    /// `list_item` piece composes the same content and this kind never reaches the backend.
188    ListItem = LIST_ITEM => "day.list_item",
189}
190
191/// Whether a kind is worth asking [`Toolkit::first_baseline`] about (docs/baseline.md).
192///
193/// A blocklist, not an allowlist: the structural and graphic kinds below have no text of their
194/// own, and everything else (including extension pieces like the date/time pickers, whose kinds
195/// day-spec has never heard of) is assumed to be worth asking. An extension piece that turns
196/// out to have no baseline answers `None`, which costs one query; an allowlist would instead
197/// silently leave every extension piece centered, which is the bug this shape avoids.
198#[must_use]
199pub fn kind_has_baseline(kind: PieceKind) -> bool {
200    !matches!(
201        Builtin::from_key(kind),
202        Some(
203            Builtin::Container
204                | Builtin::Scroll
205                | Builtin::Divider
206                | Builtin::Image
207                | Builtin::Canvas
208                | Builtin::Slider
209                | Builtin::Toggle
210                | Builtin::Progress
211                | Builtin::Nav
212                | Builtin::NavPage
213                | Builtin::NavMenu
214                | Builtin::Split
215                | Builtin::SplitPane
216                | Builtin::List
217                | Builtin::ListCell
218                | Builtin::Cover
219                | Builtin::Inspector
220                | Builtin::InspectorPane
221        )
222    )
223}
224
225/// Placeholder leaves: the one hole in Day's rendering that is invisible to a screenshot.
226///
227/// When a backend has no renderer for a kind it realizes a visible `⟨kind⟩` label rather than
228/// failing. That is the right runtime behavior, but it means a missing renderer looks like a
229/// rendered app: the walkthrough passes, and the gallery's validator (which counts distinct
230/// colors) sees nothing wrong. That is how a stale `skip_on:` survived in the showcase
231/// walkthrough after the renderer it skipped had landed.
232///
233/// So every backend reports here instead of keeping its own warn-once set. The table is process-
234/// wide and append-only, which gives dayscript's `assert_no_placeholders` something to assert on
235/// (`crates/day-script`): a placeholder becomes a test failure instead of a silent gap.
236pub mod placeholder {
237    use super::PieceKind;
238    use std::collections::BTreeSet;
239    use std::sync::{Mutex, OnceLock};
240
241    fn table() -> &'static Mutex<BTreeSet<PieceKind>> {
242        static TABLE: OnceLock<Mutex<BTreeSet<PieceKind>>> = OnceLock::new();
243        TABLE.get_or_init(|| Mutex::new(BTreeSet::new()))
244    }
245
246    /// Record that `toolkit` had no renderer for `kind` and warn, once per kind, however many
247    /// nodes of it are realized. Call from a backend's `realize` fallback arm.
248    pub fn report(kind: PieceKind, toolkit: &str) {
249        let Ok(mut seen) = table().lock() else { return };
250        if seen.insert(kind) {
251            log::warn!(
252                "no renderer for piece kind \"{kind}\" on {toolkit} — is the piece's \
253                 {toolkit} feature enabled? (rendering a placeholder)"
254            );
255        }
256    }
257
258    /// Every kind that has rendered a placeholder in this process, sorted. Empty is the goal.
259    #[must_use]
260    pub fn seen() -> Vec<PieceKind> {
261        table()
262            .lock()
263            .map_or_default(|s| s.iter().copied().collect())
264    }
265}
266
267/// Downcast a realize/update payload to the props/patch type a backend arm expects,
268/// warning (once per kind, via [`placeholder::report`]) instead of panicking on a
269/// mismatch. A mismatch means a piece registered under a builtin key or a day-core
270/// regression; degrade to the placeholder path, never abort: most backend arms run
271/// inside native up-calls, where a panic is a process kill.
272pub fn props_of<'a, T: 'static>(
273    kind: PieceKind,
274    toolkit: &str,
275    any: &'a dyn std::any::Any,
276) -> Option<&'a T> {
277    let p = any.downcast_ref::<T>();
278    if p.is_none() {
279        placeholder::report(kind, toolkit);
280    }
281    p
282}
283
284/// Pointer-keyed per-view side tables with an automatic release sweep.
285///
286/// Backends keep auxiliary per-view state in thread-local maps keyed by the native
287/// handle's address. Historically each map needed its own line in `release()`, a
288/// checklist that drifted repeatedly (missed entries have produced both leaks and
289/// stale-pointer CI segfaults, since a freed address gets recycled). A [`crate::sidetable::SideTable`]
290/// registers itself with a per-thread sweeper list at construction, so a backend's
291/// `release()` calls [`crate::sidetable::sweep`] once and every table, present and future, drops its
292/// entry for that handle, running its teardown hook if one was given.
293pub mod sidetable {
294    use std::cell::RefCell;
295    use std::collections::HashMap;
296    use std::rc::Rc;
297
298    /// One table's "remove this key" hook, registered at construction.
299    type Sweeper = Rc<dyn Fn(usize)>;
300
301    thread_local! {
302        static SWEEPERS: RefCell<Vec<Sweeper>> = const { RefCell::new(Vec::new()) };
303    }
304
305    /// A pointer-keyed map swept automatically by [`crate::sidetable::sweep`]. Construct inside a
306    /// `thread_local!` initializer; the optional teardown hook runs for each removed
307    /// value (release a retained native object, dispose an owned child, …), both on sweep
308    /// and on plain [`SideTable::remove`], so teardown cannot be bypassed by accident.
309    pub struct SideTable<V: 'static> {
310        map: Rc<RefCell<HashMap<usize, V>>>,
311        teardown: Option<Rc<dyn Fn(V)>>,
312    }
313
314    impl<V> Default for SideTable<V> {
315        fn default() -> Self {
316            Self::new()
317        }
318    }
319
320    impl<V> SideTable<V> {
321        #[must_use]
322        pub fn new() -> Self {
323            Self::build(None)
324        }
325
326        /// A table whose values need active teardown when their view goes away.
327        pub fn with_teardown(teardown: impl Fn(V) + 'static) -> Self {
328            Self::build(Some(Rc::new(teardown)))
329        }
330
331        fn build(teardown: Option<Rc<dyn Fn(V)>>) -> Self {
332            let map: Rc<RefCell<HashMap<usize, V>>> = Rc::default();
333            let (m, t) = (map.clone(), teardown.clone());
334            SWEEPERS.with(|s| {
335                s.borrow_mut().push(Rc::new(move |key| {
336                    // Remove under the borrow, tear down outside it: hooks may re-enter
337                    // toolkit code that reads other tables.
338                    let v = m.borrow_mut().remove(&key);
339                    if let (Some(v), Some(t)) = (v, &t) {
340                        t(v);
341                    }
342                }));
343            });
344            SideTable { map, teardown }
345        }
346
347        pub fn insert(&self, key: usize, value: V) -> Option<V> {
348            self.map.borrow_mut().insert(key, value)
349        }
350
351        /// Remove and tear down the entry (returns `None` always when a teardown hook
352        /// exists, because the value is consumed by it; use [`SideTable::take`] to skip it).
353        #[must_use]
354        pub fn remove(&self, key: usize) -> Option<V> {
355            let v = self.map.borrow_mut().remove(&key)?;
356            match &self.teardown {
357                Some(t) => {
358                    t(v);
359                    None
360                }
361                None => Some(v),
362            }
363        }
364
365        /// Remove without running the teardown hook (the caller takes ownership).
366        #[must_use]
367        pub fn take(&self, key: usize) -> Option<V> {
368            self.map.borrow_mut().remove(&key)
369        }
370
371        #[must_use]
372        pub fn contains(&self, key: usize) -> bool {
373            self.map.borrow().contains_key(&key)
374        }
375
376        #[must_use]
377        pub fn get(&self, key: usize) -> Option<V>
378        where
379            V: Clone,
380        {
381            self.map.borrow().get(&key).cloned()
382        }
383
384        /// Run `f` on the value in place (returns `None` if absent).
385        pub fn with<R>(&self, key: usize, f: impl FnOnce(&mut V) -> R) -> Option<R> {
386            self.map.borrow_mut().get_mut(&key).map(f)
387        }
388
389        /// Run `f` over every `(key, value)` (immutable; do not re-enter this table).
390        pub fn for_each(&self, mut f: impl FnMut(usize, &V)) {
391            for (k, v) in self.map.borrow().iter() {
392                f(*k, v);
393            }
394        }
395    }
396
397    /// Remove `key` from every table registered on this thread, running teardowns.
398    /// Call once from a backend's `release()` (and once per auxiliary native object a
399    /// release frees, e.g. an owned content container).
400    pub fn sweep(key: usize) {
401        // Clone the sweeper list first: a teardown may construct a new SideTable
402        // (registering a sweeper) without deadlocking on the borrow.
403        let sweepers: Vec<Sweeper> = SWEEPERS.with(|s| s.borrow().clone());
404        for f in sweepers {
405            f(key);
406        }
407    }
408}
409
410/// The painting threads behind the offscreen exports (docs/canvas.md "Exporting").
411///
412/// `Toolkit::render_bitmap` answers with an event, so a toolkit whose 2-D API can draw into a
413/// memory surface from any thread paints there and posts the answer back to the UI thread. The
414/// pool is shared by every toolkit in the process: a few threads, one short of the cores and
415/// never more than four, so a screenful of requests cannot starve the UI thread or the app's
416/// own work. Jobs run in the order they were queued.
417///
418/// Not built for the web: a browser's `createImageBitmap` is already asynchronous, and
419/// `wasm32-unknown-unknown` has no threads to spawn.
420#[cfg(not(target_arch = "wasm32"))]
421pub mod offscreen {
422    use std::sync::atomic::{AtomicUsize, Ordering};
423    use std::sync::{Arc, Mutex, OnceLock, mpsc};
424
425    type Job = Box<dyn FnOnce() + Send + 'static>;
426
427    static QUEUE: OnceLock<Mutex<mpsc::Sender<Job>>> = OnceLock::new();
428    /// How many painting threads started; zero means every job runs where it was queued.
429    static WORKERS: AtomicUsize = AtomicUsize::new(0);
430
431    /// Run `job` on a painting thread, or inline when none could be started. A panic inside
432    /// `job` is contained ([`crate::ffi_guard::contain`]) so one bad replay cannot take the
433    /// thread, and with it every later export, down; the job itself should answer its request
434    /// in that case, which is why toolkits wrap the paint and not the post.
435    pub fn spawn(job: impl FnOnce() + Send + 'static) {
436        let queue = QUEUE.get_or_init(start);
437        if WORKERS.load(Ordering::Acquire) == 0 {
438            crate::ffi_guard::contain((), job);
439            return;
440        }
441        let job: Job = Box::new(job);
442        // The receivers live as long as the process, so a refused send means every worker left
443        // its loop; the job still runs, inline, rather than a request going unanswered.
444        let refused = match queue.lock() {
445            Ok(sender) => sender.send(job).err().map(|e| e.0),
446            Err(_) => Some(job),
447        };
448        if let Some(job) = refused {
449            crate::ffi_guard::contain((), job);
450        }
451    }
452
453    fn start() -> Mutex<mpsc::Sender<Job>> {
454        let (tx, rx) = mpsc::channel::<Job>();
455        let rx = Arc::new(Mutex::new(rx));
456        let want = std::thread::available_parallelism()
457            .map_or(2, std::num::NonZero::get)
458            .saturating_sub(1)
459            .clamp(1, 4);
460        let mut started = 0;
461        for i in 0..want {
462            let rx = Arc::clone(&rx);
463            let spawned = std::thread::Builder::new()
464                .name(format!("day-paint-{i}"))
465                .spawn(move || {
466                    loop {
467                        // The lock is held only while waiting for the next job, never while
468                        // running one, so the other workers queue behind it fairly.
469                        let next = match rx.lock() {
470                            Ok(guard) => guard.recv(),
471                            Err(_) => return,
472                        };
473                        match next {
474                            Ok(job) => crate::ffi_guard::contain((), job),
475                            Err(_) => return,
476                        }
477                    }
478                });
479            match spawned {
480                Ok(_) => started += 1,
481                Err(e) => log::error!("day-spec: could not start a painting thread: {e}"),
482            }
483        }
484        WORKERS.store(started, Ordering::Release);
485        Mutex::new(tx)
486    }
487}
488
489/// Realized-node identity as seen by backends (day-core's slotmap key, FFI-encoded).
490#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
491pub struct NodeId(pub u64);
492
493/// Default navigation sidebar width (split presentation) until the pane reports its size.
494/// Semantic container surfaces (see `ContainerProps::role`): each backend maps a role to its
495/// own theme-adaptive material so the fill tracks light/dark mode without app code.
496#[derive(Clone, Copy, Debug, PartialEq, Eq)]
497pub enum SurfaceRole {
498    /// A form `section` card, the platform's grouped-content background: AppKit quaternary
499    /// system fill, libadwaita `.card`, Qt `palette(alternate-base)`, UIKit tertiary system
500    /// fill, Material surface-container, XAML card background brush.
501    SectionCard,
502    /// The window's own background, the surface a page sits on: what an opaque cover paints
503    /// by default, and the card of a composed modal sheet (docs/cover.md "Modal sheet").
504    Window,
505    /// The layer between a composed modal sheet and the page under it, which says the page is
506    /// out of reach until the sheet goes. The container's `background` is the plain dimming a
507    /// backend draws when it has no material of its own; the web frosts the page instead.
508    Scrim,
509}
510
511pub const NAV_SIDEBAR_WIDTH: f64 = 240.0;
512
513/// Drag limits for a navigation host's sidebar pane, around [`NAV_SIDEBAR_WIDTH`]. Shared by the
514/// desktops whose divider the user can drag (docs/navigation.md): AppKit enforces both through
515/// its `NSSplitViewItem`; Qt honors the minimum through the pane's own minimum size and leaves
516/// the maximum to the user.
517pub const NAV_SIDEBAR_MIN_W: f64 = 160.0;
518pub const NAV_SIDEBAR_MAX_W: f64 = 400.0;
519
520/// Default preferred width of a navigation host's content-list pane
521/// (`props::NavProps::list_width`, docs/navigation.md), Mail's message-list proportion.
522pub const NAV_LIST_WIDTH: f64 = 300.0;
523
524/// Drag limits for the content-list pane, around the app's preferred width; the same split of
525/// duties as the sidebar's.
526pub const NAV_LIST_MIN_W: f64 = 220.0;
527pub const NAV_LIST_MAX_W: f64 = 560.0;
528
529/// Reserved id for window-level events (resize, lifecycle): day-core routes it to the root.
530pub const WINDOW_NODE: NodeId = NodeId(u64::MAX);
531
532/// Which nodes handle the non-text keys (docs/menus.md). Keys follow focus (the focused piece
533/// hears them and nobody else), so a backend whose focused view would have to claim a key from
534/// the platform's own dispatch (AppKit's responder chain, the DOM's default action) has to know
535/// whether the app wants it before swallowing it. An unclaimed arrow has to keep traveling, or
536/// a canvas inside a scroll view would silently eat the keys that scroll it.
537///
538/// It lives here, in day-spec, rather than in day-core: `day-toolkit-dom` depends on day-spec alone,
539/// and this is a fact about a node that both sides need.
540pub mod keys {
541    use super::NodeId;
542    use std::cell::RefCell;
543    use std::collections::HashSet;
544
545    thread_local! {
546        static HANDLED: RefCell<HashSet<NodeId>> = RefCell::new(HashSet::new());
547    }
548
549    /// Declare that `node` has a key handler (what `Decorate::on_key` records at build).
550    pub fn mark(node: NodeId) {
551        HANDLED.with(|h| h.borrow_mut().insert(node));
552    }
553
554    /// Whether `node` has one.
555    #[must_use]
556    pub fn handled(node: NodeId) -> bool {
557        HANDLED.with(|h| h.borrow().contains(&node))
558    }
559
560    thread_local! {
561        static TEXT: RefCell<HashSet<NodeId>> = RefCell::new(HashSet::new());
562    }
563
564    /// Declare that `node` takes the whole keyboard while focused (what `Decorate::keyboard`
565    /// records at build): every key the platform delivers reaches its handler, named the way
566    /// [`super::KeyEvent`] describes for the full route, and a touch platform raises its soft
567    /// keyboard for it.
568    pub fn mark_text(node: NodeId) {
569        TEXT.with(|h| h.borrow_mut().insert(node));
570    }
571
572    /// Whether `node` takes the whole keyboard: it declared so AND it [`handled`]s keys. A
573    /// declaration with no `.on_key` behind it claims nothing, so every backend asks this one
574    /// question before it raises a soft keyboard, names a letter or claims a Tab.
575    #[must_use]
576    pub fn text(node: NodeId) -> bool {
577        TEXT.with(|h| h.borrow().contains(&node)) && handled(node)
578    }
579
580    /// The keys a focused single-line text field hands to its key handler instead of acting
581    /// on them itself (docs/textfield.md "Keys"): what an address bar needs to walk a
582    /// suggestion list and to cancel an edit. Return stays the field's submit, Tab its focus
583    /// walk, and every other key its editing.
584    pub const FIELD_KEYS: [&str; 3] = ["ArrowUp", "ArrowDown", "Escape"];
585
586    /// Whether a focused text field at `node` claims the key named `key` (web name, see
587    /// [`super::KeyEvent::key`]) pressed with `modifiers`: one of [`FIELD_KEYS`], no modifier
588    /// held, and a handler declared for the field. A backend that answers yes reports
589    /// `Event::Key` for `node` and keeps the key from the native field.
590    #[must_use]
591    pub fn field_claims(node: NodeId, key: &str, modifiers: u8) -> bool {
592        modifiers == 0 && FIELD_KEYS.contains(&key) && handled(node)
593    }
594
595    /// Drop both marks for a node that left the tree (day-core calls it from its removal
596    /// path). Node ids are generational, so a stale id would never match a new node; this
597    /// keeps the registries from growing with every rebuilt canvas.
598    pub fn forget(node: NodeId) {
599        HANDLED.with(|h| h.borrow_mut().remove(&node));
600        TEXT.with(|h| h.borrow_mut().remove(&node));
601    }
602}
603
604/// Raw foreign native handle for polyglot adoption (§15.3).
605pub type RawHandle = *mut std::ffi::c_void;
606
607// ---------------------------------------------------------------------------
608// Events (§8.3)
609// ---------------------------------------------------------------------------
610
611/// The wire table for backends whose native side reaches Rust through one numeric-kind
612/// trampoline (Android's JNI `nativeOnEvent`, ArkUI's `day_arkui_on_event`). This enum
613/// defines those kind numbers; the Java and C++ sides carry mirrored constants that parity
614/// tests check against these discriminants (so a collision or drift fails `cargo test` on the
615/// host instead of silently mis-decoding events on a device). AppKit/UIKit/GTK/Qt emit `Event`
616/// values directly and never use these numbers; XAML uses per-event callbacks with its own
617/// small local codes.
618///
619/// Payload conventions ride `(num: f64, text: String)` per kind, documented on each variant.
620pub mod bridge {
621    /// One numeric event kind. `as i32` is the wire value.
622    #[repr(i32)]
623    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
624    pub enum BridgeKind {
625        /// Click/press. No payload.
626        Pressed = 0,
627        /// `text` = the field's full new text.
628        TextChanged = 1,
629        /// `num` != 0 ⇒ on.
630        ToggleChanged = 2,
631        /// `num` = the new value.
632        ValueChanged = 3,
633        /// `num` = the selected index.
634        SelectionChanged = 4,
635        /// `num` == 1 ⇒ the native side already popped (predictive back / up arrow).
636        NavBack = 5,
637        /// Nav/tab page size report; `text` = `"w,h"` in px (Rust divides by density).
638        FrameChanged = 6,
639        /// Warm deep link; `text` = the route.
640        Deeplink = 7,
641        /// Modal answered with a button; `num` = the button index.
642        PresentButton = 8,
643        /// Modal answered with text; `text` = the entry.
644        PresentText = 9,
645        /// Modal dismissed.
646        PresentDismissed = 10,
647        /// Gesture; `num` = phase (0 tap, 1 began, 2 changed, 3 ended), `text` = `"x,y,tx,ty"` px.
648        Gesture = 11,
649        /// Piece-defined open channel (`Event::Custom` with an empty tag): the piece reads the
650        /// raw `num`/`text` payload.
651        Custom = 12,
652        /// Menu selection; the event's node id is the chosen action's dispatch id.
653        MenuAction = 13,
654        /// App lifecycle; `num` = the phase code (`day_spec::Lifecycle` order).
655        Lifecycle = 14,
656        /// File-picker answer; `text` = chosen locators joined by the unit separator.
657        PresentFile = 15,
658        /// `num` != 0 ⇒ gained keyboard focus.
659        FocusChanged = 16,
660        /// IME action / Return.
661        Submitted = 17,
662        /// Root size change; `text` = `"w,h"` in px. Routed to `WINDOW_NODE` as a window
663        /// resize (the rail rotation, late inset passes, and the soft keyboard ride).
664        WindowResized = 18,
665        /// Safe-area report from an edge-to-edge backend; `text` =
666        /// `"top,bottom,leading,trailing"` in px (Rust divides by density and feeds
667        /// `day_core::set_safe_area`). Node id ignored; no `Event` is emitted.
668        SafeArea = 19,
669        /// A secondary window closed (docs/windows.md); the node id is the window's root.
670        WindowClosed = 20,
671        /// A secondary window's key/active state changed; `num` != 0 ⇒ focused.
672        WindowFocused = 21,
673        /// `num` = the settled value: the drag ended (see `Event::ValueCommitted`). A backend
674        /// that cannot tell a settled value from a moving one sends only `ValueChanged`.
675        ValueCommitted = 22,
676        /// Inline search on a `.searchable()` navigation surface (docs/search.md): the field's
677        /// new text, against the nav host's node. `num` = 1 ⇒ the text was submitted (Return or
678        /// the keyboard's Search key), decoding to [`crate::Event::SearchSubmitted`].
679        SearchChanged = 23,
680        /// The toolkit's own adaptive nav container changed presentation and is reporting it
681        /// (docs/size-classes.md). `num` = 1.0 for split, 0.0 for stacked.
682        NavPresentation = 24,
683        /// The system switched between light and dark appearance. No payload; node id ignored
684        /// and no `Event` is emitted; Rust calls `day_core::note_appearance_changed`, the same
685        /// thing AppKit's and GTK's own scheme observers do.
686        AppearanceChanged = 25,
687        /// A fullscreen cover's hide transition finished (docs/cover.md); no payload, and the
688        /// node id is the cover's. Decodes to [`crate::Event::CoverHidden`].
689        CoverHidden = 26,
690        /// A styled text run's link was tapped (docs/text-runs.md); `text` = the run's target.
691        /// Decodes to [`crate::Event::LinkActivated`].
692        LinkActivated = 27,
693        /// The platform's own undo affordance fired (⌘Z, a three-finger swipe, the Edit menu
694        /// through a native front); `num` != 0 ⇒ redo.
695        UndoInvoked = 28,
696        /// A toolbar item produced a value (docs/toolbars.md): the node id is the item's
697        /// dispatch action; `text` = `"on"` with `num` != 0 ⇒ a toggle turned on, `"on"` with
698        /// 0 ⇒ off, `"sel"` with `num` = the chosen segment, `"text:<query>"` ⇒ a search
699        /// item's new text, `"submit:<query>"` ⇒ that text submitted. Decodes to
700        /// [`crate::Event::ToolbarChanged`]. A plain toolbar button sends `MenuAction`.
701        ToolbarChanged = 30,
702        /// An activated list row; `num` is its current index.
703        ListActivated = 31,
704        /// External document copied into app storage; `text` = its local locator.
705        DocumentOpened = 32,
706        /// The user's reduce-motion setting flipped (docs/accessibility.md). No payload; node
707        /// id ignored and no `Event` is emitted; Rust calls `day_core::note_motion_changed`, as
708        /// the desktop backends' own observers do.
709        ReduceMotionChanged = 33,
710        /// Text committed on the full key route (docs/menus.md "The full route"): `text` =
711        /// what the input method or the key typed, `num` = the modifier mask. Decodes to an
712        /// [`crate::Event::Key`] whose `text` is set; a key that typed nothing rides `Key`.
713        Text = 36,
714        /// A non-text key reached the focused node (docs/menus.md); `text` = the day key name
715        /// (`"ArrowLeft"`, `"5"`, …), `num` = the [`crate::KeyEvent`] modifier mask. Decodes to
716        /// [`crate::Event::Key`].
717        Key = 29,
718        /// A window's display state changed (docs/windows.md): `num` = the
719        /// [`crate::WindowState`] code (0 normal, 1 minimized, 2 maximized, 3 fullscreen), against
720        /// the window's root node, or [`crate::WINDOW_NODE`] for the primary. Decodes to
721        /// [`crate::Event::WindowStateChanged`] through [`crate::WindowState::from_code`].
722        WindowStateChanged = 34,
723        /// Native pull-to-refresh request; no payload.
724        RefreshRequested = 35,
725        /// Text shared to the app from the system share sheet (Day.toml `share_target`,
726        /// docs/deep-links.md): `text` = the shared text, then the unit separator and the
727        /// subject when one came with it. Node id ignored and no `Event` is emitted; Rust calls
728        /// `day_core::request_shared_text`, which sends a web link in it to `on_open_url`.
729        SharedText = 37,
730    }
731
732    impl BridgeKind {
733        /// Every variant, for uniqueness/parity tests and exhaustive dispatch.
734        pub const ALL: [BridgeKind; 38] = [
735            BridgeKind::Pressed,
736            BridgeKind::TextChanged,
737            BridgeKind::ToggleChanged,
738            BridgeKind::ValueChanged,
739            BridgeKind::SelectionChanged,
740            BridgeKind::NavBack,
741            BridgeKind::FrameChanged,
742            BridgeKind::Deeplink,
743            BridgeKind::PresentButton,
744            BridgeKind::PresentText,
745            BridgeKind::PresentDismissed,
746            BridgeKind::Gesture,
747            BridgeKind::Custom,
748            BridgeKind::MenuAction,
749            BridgeKind::Lifecycle,
750            BridgeKind::PresentFile,
751            BridgeKind::FocusChanged,
752            BridgeKind::Submitted,
753            BridgeKind::WindowResized,
754            BridgeKind::SafeArea,
755            BridgeKind::WindowClosed,
756            BridgeKind::WindowFocused,
757            BridgeKind::ValueCommitted,
758            BridgeKind::SearchChanged,
759            BridgeKind::NavPresentation,
760            BridgeKind::AppearanceChanged,
761            BridgeKind::CoverHidden,
762            BridgeKind::LinkActivated,
763            BridgeKind::UndoInvoked,
764            BridgeKind::Key,
765            BridgeKind::ToolbarChanged,
766            BridgeKind::ListActivated,
767            BridgeKind::DocumentOpened,
768            BridgeKind::ReduceMotionChanged,
769            BridgeKind::WindowStateChanged,
770            BridgeKind::RefreshRequested,
771            BridgeKind::Text,
772            BridgeKind::SharedText,
773        ];
774    }
775
776    #[cfg(test)]
777    mod tests {
778        use super::BridgeKind;
779
780        /// The kind-15 lesson: two meanings on one number decode silently as the first. Every
781        /// discriminant must be unique, and the table must stay dense enough to spot gaps.
782        #[test]
783        fn discriminants_are_unique() {
784            let mut seen = std::collections::BTreeSet::new();
785            for k in BridgeKind::ALL {
786                assert!(
787                    seen.insert(k as i32),
788                    "duplicate bridge kind number {} ({k:?})",
789                    k as i32
790                );
791            }
792            assert_eq!(seen.len(), BridgeKind::ALL.len());
793        }
794
795        /// `ALL` is what the uniqueness check above sees, so a variant left out of it is a variant
796        /// nothing checks, which is how `SearchChanged` and `NavPresentation` sat outside the
797        /// table. The wire numbers are assigned densely from 0, so demanding the set be exactly
798        /// `0..len` catches both a gap and an omission.
799        #[test]
800        fn table_covers_every_wire_number() {
801            let mut nums: Vec<i32> = BridgeKind::ALL.iter().map(|k| *k as i32).collect();
802            nums.sort_unstable();
803            let dense: Vec<i32> = (0..BridgeKind::ALL.len() as i32).collect();
804            assert_eq!(
805                nums, dense,
806                "bridge kinds must be dense from 0 — a missing entry means a variant no test sees"
807            );
808        }
809    }
810}
811
812#[derive(Clone, Debug, PartialEq)]
813pub enum Event {
814    Pressed,
815    TextChanged(String),
816    Submitted,
817    ToggleChanged(bool),
818    ValueChanged(f64),
819    /// A continuous control's value settled: the drag ended (mouse/touch up), or the value moved
820    /// by a discrete action (a keyboard arrow, a click on the track). Always preceded by the
821    /// `ValueChanged` carrying the same value.
822    ///
823    /// The pair exists because one gesture produces two different facts. `ValueChanged` is the
824    /// live one (bindings follow it so the UI tracks the thumb) and it fires continuously, which
825    /// is why nothing durable should key off it: a drag from 1 to 100 and back to 50 emits every
826    /// value in between. `ValueCommitted` fires once, with the value the user chose, and is what
827    /// a recording, a log, or a refetch should use.
828    ///
829    /// A backend that cannot tell the two apart emits only `ValueChanged`; its sliders then do not
830    /// record (docs/coverage-matrix.md).
831    ValueCommitted(f64),
832    SelectionChanged(i64),
833    /// A list row was activated: desktop double-click/Enter, or a touch tap.
834    /// Separate from selection so keyboard browsing need not open or play the row.
835    ListActivated(usize),
836    /// The platform's own undo affordance fired through a native front (⌘Z on the Edit menu,
837    /// a three-finger swipe, shake-to-undo); `redo` distinguishes the pair. Only backends
838    /// with a native undo system emit it; everywhere else the app's own controls call the
839    /// stack directly and this event never exists (docs/model.md).
840    Undo {
841        redo: bool,
842    },
843    /// The platform's own standard edit command fired through its native route (Edit ▸
844    /// Cut/Copy/Paste, ⌘X/⌘C/⌘V, the browser's `copy`/`paste` DOM events) with no text
845    /// widget claiming it first; the app's edit bridge answers (docs/menus.md). Transport
846    /// is the system clipboard (day-part-clipboard), not the event.
847    Edit(EditOp),
848    /// A multi-select list's selection changed: the full set of selected row indices,
849    /// ascending (empty = nothing selected). Emitted instead of `SelectionChanged` where
850    /// `ListProps::multi_select` is honored (docs/list.md).
851    SelectionSet(Vec<i64>),
852    FocusChanged(bool),
853    Tap(Point),
854    /// A link run inside a label was activated; the payload is [`TextRun::link`] verbatim.
855    LinkActivated(String),
856    LongPress(Point),
857    /// A context-menu summon reported by a toolkit that presents no native menu of its own
858    /// (web-dom): the pieces layer shows the composed menu (docs/menus.md). `local` is the
859    /// point in the node's own coordinates (what the app's provider receives); `window` the
860    /// same point in window coordinates (where the composed panel goes). Toolkits that serve
861    /// context menus natively never emit this.
862    ContextMenu {
863        local: Point,
864        window: Point,
865    },
866    /// A drag/pan gesture (docs/shapes.md). `location` is in the node's local coordinates;
867    /// `translation` is the cumulative movement since `Began`.
868    Drag {
869        phase: DragPhase,
870        location: Point,
871        translation: Point,
872    },
873    /// A pinch/magnify gesture over the node (docs/shapes.md): `scale` is cumulative since
874    /// `Began` (1.0 = unchanged), `location` the gesture's centroid in local coordinates,
875    /// the anchor a zoom keeps stationary. Only nodes that enabled
876    /// [`GestureKind::Pinch`] receive it; a backend with no recognizer emits nothing.
877    Pinch {
878        phase: DragPhase,
879        scale: f64,
880        location: Point,
881    },
882    /// A two-finger rotation over the node (docs/canvas.md "Zoom and pan"): `rotation` is in
883    /// radians, cumulative since `Began`, positive clockwise on screen; `location` the
884    /// gesture's centroid in local coordinates ([`Point::ZERO`] where the platform gives
885    /// none). A trackpad's rotate tick has no gesture session and arrives as a lone `Changed`
886    /// carrying that tick's own angle. Only nodes that enabled [`GestureKind::Rotate`]
887    /// receive it; a backend with no recognizer emits nothing.
888    Rotate {
889        phase: DragPhase,
890        rotation: f64,
891        location: Point,
892    },
893    /// A viewport pan over the node (docs/shapes.md): `delta` is the movement since the
894    /// previous event; incremental, not cumulative, because desktop wheels have no gesture
895    /// session to accumulate over (a discrete wheel tick arrives as a lone `Changed`).
896    /// Two-finger touch pans bracket theirs with `Began`/`Ended`. Distinct from
897    /// [`Event::Drag`], the primary pointer's press-drag.
898    Pan {
899        phase: DragPhase,
900        delta: Point,
901        location: Point,
902    },
903    /// The pointer moved over the node, or left it (docs/canvas.md "Interaction"). `location` is
904    /// in the node's local coordinates. Phases follow the drag vocabulary: `Began` on entry,
905    /// `Changed` for each move, `Ended` on exit, where `location` is the last point seen inside,
906    /// so a handler always knows where the pointer went out.
907    ///
908    /// Only nodes that enabled [`GestureKind::Hover`] receive it, and only on a device with a
909    /// pointer at all.
910    Hover {
911        phase: DragPhase,
912        location: Point,
913    },
914    ScrollChanged(Point),
915    /// A canvas node was re-framed by layout; re-record (§11). Nav pane/page containers
916    /// also report their allocated size with this (docs/navigation.md).
917    FrameChanged(Size),
918    /// Native back navigation (iOS back button/swipe, Android system back or toolbar up).
919    /// `already_popped` = the toolkit already performed the pop natively (iOS); the nav
920    /// host then syncs its stack without re-issuing `NavPatch::Popped`.
921    NavBack {
922        already_popped: bool,
923    },
924    /// A nav host's own adaptive container changed presentation, and Day is being told about it
925    /// after the fact (docs/size-classes.md).
926    ///
927    /// The counterpart to [`props::NavPatch::Presentation`], for the toolkits that answer
928    /// `Cap::NavRepresent = Emulated`: `UISplitViewController` collapsing as a Pro Max iPhone
929    /// rotates into portrait, `SlidingPaneLayout` deciding at measure time that two panes no
930    /// longer fit. Day did not ask for it and must not fight it; the pieces layer only
931    /// reconciles what follows, which is the selection rule (a split presentation cannot draw an
932    /// empty detail pane, so expanding with nothing selected picks the first item).
933    ///
934    /// Emitted on the NAV host node, and only when the presentation actually changed.
935    NavPresentationChanged(props::NavPresentation),
936    Key(KeyEvent),
937    Pointer(PointerEvent),
938    WindowResized(Size),
939    /// The platform asks the app to show a route (docs/navigation.md), a runtime deep link:
940    /// on web-dom, the URL hash changing under the app (hand-edited, or browser back/forward);
941    /// on mobile, a warm scheme link (iOS `application:openURL:`, Android `onNewIntent` via
942    /// `BridgeKind::Deeplink`). Emitted on [`WINDOW_NODE`] (day-core answers with `navigate()`
943    /// when the route differs from the current one) or on the active nav host's node (the nav
944    /// piece answers with `navigate()` itself, docs/deep-links.md). Launch-time deep links use
945    /// `DAY_DEEPLINK`/`set_launch_deeplink` instead; this variant is for changes while the
946    /// app runs.
947    RouteRequested(String),
948    /// A native modal answered request `req` (docs/dialogs.md).
949    PresentResult {
950        req: u64,
951        result: present::PresentResult,
952    },
953    /// A decode started by [`Toolkit::decode_image`] finished (docs/images.md).
954    ///
955    /// Keyed by request id like [`Event::PresentResult`], and for the same reason: the answer
956    /// belongs to a waiting caller, not to a tree node. It never crosses a native boundary
957    /// (every backend raises it from its own Rust arm once the platform decoder answers), so it
958    /// has no [`bridge::BridgeKind`], exactly like the completion events dialogs use in-process.
959    ///
960    /// No bitmap id rides here: day-core minted it and handed it to the backend with the bytes,
961    /// so it already knows which image a request answers for. A backend that stored the image
962    /// under that id has nothing more to say than the facts it read.
963    ImageDecoded {
964        req: u64,
965        result: Result<BitmapInfo, ImageError>,
966    },
967    /// An encode started by [`Toolkit::encode_image`] finished (docs/images.md): the encoded
968    /// bytes, or why they could not be produced.
969    ImageEncoded {
970        req: u64,
971        result: Result<Vec<u8>, ImageError>,
972    },
973    /// A canvas drawing started by [`Toolkit::render_bitmap`] finished rendering
974    /// (docs/canvas.md "Exporting"). Keyed by request id like [`Event::ImageDecoded`], and like
975    /// it carries no bitmap id: day-core minted the id and handed it over with the ops, so the
976    /// answer is only the facts of the image the backend stored under it.
977    BitmapRendered {
978        req: u64,
979        result: Result<BitmapInfo, ExportError>,
980    },
981    /// A PDF started by [`Toolkit::render_pdf`] finished (docs/canvas.md "Exporting"): the
982    /// document's bytes, or why they could not be produced.
983    PdfRendered {
984        req: u64,
985        result: Result<Vec<u8>, ExportError>,
986    },
987    /// An open, piece-defined event (§8.2). `tag` names the event for in-process emitters (a static
988    /// literal); it is empty for events that cross a native boundary (JNI/C-ABI), which carry only the
989    /// primitive `num`/`text` payload. A piece's `cx.on` reads whichever fields it needs. This is the
990    /// escape hatch for events the fixed variants above don't cover (a web view's URL, a picked date, …).
991    Custom {
992        tag: &'static str,
993        num: f64,
994        text: String,
995    },
996    /// A menu item (app menu or context menu) with this action id was activated (§ menus). day-core
997    /// routes it to the app closure registered for the id. Standard-role items don't carry an id
998    /// (`role` items are handled natively) so they never emit this.
999    MenuAction(u64),
1000    /// A toolbar item produced a value: a search field's text, a toggle's new state
1001    /// (docs/toolbars.md). `action` is the item's dispatch id, from the same registry
1002    /// [`Event::MenuAction`] uses, and day-core routes it to the closure registered for it.
1003    /// A plain toolbar button has no value and emits `MenuAction` instead.
1004    ToolbarChanged {
1005        action: u64,
1006        value: ToolbarValue,
1007    },
1008    /// A searchable navigation surface's field changed (docs/search.md). Emitted against the nav
1009    /// host's node, not through the toolbar's dispatch registry: search belongs to the surface,
1010    /// so the field can move between the toolbar and the navigation list without the app
1011    /// re-registering anything.
1012    SearchChanged(String),
1013    /// The user picked a different scope. Carries the index into `SearchProps::scopes`.
1014    SearchScopeChanged(usize),
1015    /// The user chose one of `SearchProps::suggestions`, by index. The toolkit has already put
1016    /// that completion in the field and emitted [`Event::SearchChanged`] for it; this says which
1017    /// one, for an app that wants to act on the choice itself.
1018    SearchSuggestionChosen(usize),
1019    /// The user submitted the inline field's text with its Return or Search key. Emitted
1020    /// after the last [`Event::SearchChanged`], with the text as submitted, for a search that
1021    /// runs on demand (a server query) rather than narrowing as the text changes.
1022    SearchSubmitted(String),
1023    /// The app moved through a lifecycle phase (docs/lifecycle.md). Backends emit this from the
1024    /// native app/activity delegate; day-core routes it to the app's `on_lifecycle` handlers.
1025    Lifecycle(Lifecycle),
1026    /// A secondary native window closed (the title-bar close, a platform gesture such as an
1027    /// app-switcher swipe or an activity finish, or `Toolkit::close_window`); emitted on the
1028    /// window's root node after the platform committed the close. day-core disposes the
1029    /// window's subtree on receipt, so native and programmatic closes share one teardown
1030    /// path (docs/windows.md). Never emitted for the primary window (its close terminates
1031    /// the app).
1032    WindowClosed,
1033    /// A secondary window's key/active state changed; emitted on the window's root node.
1034    /// day-core tracks the focused window with it (dialog parenting, dayscript targeting).
1035    WindowFocused(bool),
1036    /// A window's display state changed (docs/windows.md): the user minimized, zoomed or took it
1037    /// fullscreen, or a [`WindowChange::State`] request landed. Emitted on the window's root node
1038    /// (the primary's may arrive on [`WINDOW_NODE`]); day-core feeds the window's `state()`
1039    /// signal with it, so the app reads what the platform did rather than what it asked for.
1040    WindowStateChanged(WindowState),
1041    /// A native list committed a drag-reorder (docs/list.md): row `from` landed at row `to`.
1042    /// Emitted on the `LIST` node by the list piece's commit hook: the reorder driver
1043    /// rotates its snapshot synchronously inside the platform's drop callback, then reports
1044    /// through the event queue so the app's `on_reorder` never runs inside a native animation
1045    /// callstack.
1046    ListReorder {
1047        from: usize,
1048        to: usize,
1049    },
1050    /// A regrouping sidebar committed a drop (`props::NavMenuProps::regroup`, docs/navigation.md
1051    /// "Moving rows between sections"), in item indices into the rows as they were before the
1052    /// move: row `from` now sits in the section whose first row is item `section` (item 0 for
1053    /// rows above the first header), before item `before`, or at that section's end for
1054    /// `None`. `before` is never `from`. Emitted on the `NAV_MENU` node by a toolkit whose
1055    /// `Cap::NavReorder` is `Native`, deferred through the event queue exactly as
1056    /// [`Event::ListReorder`] is; the nav validates it against the app's rules before reporting.
1057    NavRegroup {
1058        from: usize,
1059        section: usize,
1060        before: Option<usize>,
1061    },
1062    /// A native list committed a swipe-delete (docs/list.md): the row at this index is gone.
1063    /// Deferred through the event queue exactly as [`Event::ListReorder`] is.
1064    ListDelete(usize),
1065    /// The native pull-to-refresh control requested an update. The app owns its busy state.
1066    RefreshRequested,
1067    /// A native list activated a swipe action (docs/list.md): the user pressed button `action`
1068    /// (an index into the row's [`ListSwipe::actions_at`] offer for `edge`) on row `index`, or
1069    /// swiped clear across for the edge's first action. Emitted on the `LIST` node by the list
1070    /// piece's commit hook and deferred through the event queue exactly as
1071    /// [`Event::ListReorder`] is, so the app's handler never runs inside a native animation
1072    /// callstack.
1073    ListSwipe {
1074        index: usize,
1075        edge: SwipeEdge,
1076        action: usize,
1077    },
1078    /// A fullscreen cover's hide transition finished (docs/cover.md): the content can now be
1079    /// disposed. Answers [`props::CoverPatch::Dismiss`]; delivery is a hard guarantee, and
1080    /// backends over-report rather than under-report; consumers gate on their own closing
1081    /// flag, so duplicates and belated reports are no-ops.
1082    CoverHidden,
1083    /// The user showed or hid an inspector pane through a native affordance (a dock widget's
1084    /// close button, a divider dragged shut) rather than through Day (docs/inspector.md).
1085    /// Emitted on the `kinds::INSPECTOR` node, and only when the visibility actually changed;
1086    /// the piece writes it back to the bound signal. Applying
1087    /// [`props::InspectorPatch::Visible`] must never re-emit it (the from-native echo rule).
1088    InspectorChanged(bool),
1089    /// The user disclosed or collapsed a tree row through the native affordance (docs/tree.md).
1090    /// Emitted on the `kinds::TREE` node; the piece writes it back to the app's expansion
1091    /// signal. Applying [`props::TreePatch::Expand`] must never re-emit it (the from-native
1092    /// echo rule).
1093    TreeExpanded {
1094        token: u64,
1095        expanded: bool,
1096    },
1097    /// A native tree committed a drag move (docs/tree.md): `token` now sits under `parent`
1098    /// (`None` = the root) at `index` (`None` = dropped onto the parent, an append). Deferred
1099    /// through the event queue exactly as [`Event::ListReorder`] is; the app's `on_move`
1100    /// writes its own data, whose refresh reloads the tree.
1101    TreeMove {
1102        token: u64,
1103        parent: Option<u64>,
1104        index: Option<usize>,
1105    },
1106    /// A tree's selection changed: the full set of selected row tokens (empty = cleared).
1107    /// Token-addressed, since a tree cannot speak row indices: expanding a row renumbers
1108    /// everything below it (docs/tree.md).
1109    TreeSelection(Vec<u64>),
1110}
1111
1112impl Event {
1113    /// Build a text-carrying [`Event::Custom`] (with `num` defaulted to 0), the common case for an
1114    /// in-process piece reporting a value back: `emit(node, Event::custom("webview:url", url))`.
1115    pub fn custom(tag: &'static str, text: impl Into<String>) -> Event {
1116        Event::Custom {
1117            tag,
1118            num: 0.0,
1119            text: text.into(),
1120        }
1121    }
1122}
1123
1124/// An app-lifecycle phase (docs/lifecycle.md). Each backend maps these onto its OS's native app /
1125/// activity delegate. Some phases only exist on some platforms (a mobile app enters the
1126/// background and can be low on memory, a desktop app cannot), so [`Lifecycle::is_universal`]
1127/// marks the ones every backend delivers, and [`Toolkit::supports_lifecycle`] reports per-backend
1128/// truth.
1129///
1130/// Rough native mapping:
1131///
1132/// | phase | AppKit | UIKit | GTK | Qt | Android | XAML |
1133/// |---|---|---|---|---|---|---|
1134/// | `WillLaunch` / `DidLaunch` | `applicationWill/DidFinishLaunching` | same | `startup`/mount | mount | `onCreate` | window create |
1135/// | `DidBecomeActive` | `didBecomeActive` | `didBecomeActive` | `notify::is-active` | `ApplicationActive` | `onResume` | `Activated` |
1136/// | `WillResignActive` | `willResignActive` | `willResignActive` | `notify::is-active` | `ApplicationInactive` | `onPause` | `Deactivated` |
1137/// | `WillEnterForeground` | — | `willEnterForeground` | — | — | `onStart` | — |
1138/// | `DidEnterBackground` | — | `didEnterBackground` | — | — | `onStop` | — |
1139/// | `DidReceiveMemoryWarning` | — | `didReceiveMemoryWarning` | — | — | `onTrimMemory` | — |
1140/// | `WillTerminate` | `willTerminate` | `willTerminate` | `shutdown` | `aboutToQuit` | `onDestroy` | window close |
1141/// | `DidExit` | after `willTerminate` | after `willTerminate` | `run` returned | `exec` returned | after `onDestroy` | loop returned |
1142#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1143pub enum Lifecycle {
1144    /// Before the window and UI are built: the first thing to run. Set up global state here.
1145    WillLaunch,
1146    /// The UI is mounted and the app is about to start running. Kick off startup work here.
1147    DidLaunch,
1148    /// The app came to the foreground and is the active, focused app receiving input.
1149    DidBecomeActive,
1150    /// The app is about to stop being active (an interruption, app switch, or losing focus).
1151    WillResignActive,
1152    /// The app is about to return to the foreground (mobile). Refresh what background invalidated.
1153    WillEnterForeground,
1154    /// The app left the foreground and is no longer visible (mobile). Persist state, release UI work.
1155    DidEnterBackground,
1156    /// The system is low on memory (mobile). Drop caches and non-essential memory now.
1157    DidReceiveMemoryWarning,
1158    /// The app is about to terminate: the last chance to save. Triggered by the Quit command,
1159    /// the platform's quit shortcut, or the OS reclaiming the app.
1160    WillTerminate,
1161    /// The run loop is over and nothing of the app will run after this: the last phase, after
1162    /// every `WillTerminate` handler. Day logs its exit line ("Clean exit for …") once the
1163    /// handlers have run, so a handler here is the app's last word before it.
1164    DidExit,
1165}
1166
1167impl Lifecycle {
1168    /// Every phase, in delivery order (launch → run → quit). Handy for logging/registration sweeps.
1169    pub const ALL: [Lifecycle; 9] = [
1170        Lifecycle::WillLaunch,
1171        Lifecycle::DidLaunch,
1172        Lifecycle::DidBecomeActive,
1173        Lifecycle::WillResignActive,
1174        Lifecycle::WillEnterForeground,
1175        Lifecycle::DidEnterBackground,
1176        Lifecycle::DidReceiveMemoryWarning,
1177        Lifecycle::WillTerminate,
1178        Lifecycle::DidExit,
1179    ];
1180
1181    /// True for phases every backend delivers (launch, activation, termination). The remaining
1182    /// phases (`WillEnterForeground`, `DidEnterBackground`, `DidReceiveMemoryWarning`) are mobile
1183    /// concepts and are only delivered by the mobile backends. `const` so it composes into a
1184    /// backend's `const fn lifecycle_supported` and thus into compile-time guards.
1185    #[must_use]
1186    pub const fn is_universal(self) -> bool {
1187        matches!(
1188            self,
1189            Lifecycle::WillLaunch
1190                | Lifecycle::DidLaunch
1191                | Lifecycle::DidBecomeActive
1192                | Lifecycle::WillResignActive
1193                | Lifecycle::WillTerminate
1194                | Lifecycle::DidExit
1195        )
1196    }
1197
1198    /// A stable, human-readable name (for logs/warnings).
1199    #[must_use]
1200    pub const fn name(self) -> &'static str {
1201        match self {
1202            Lifecycle::WillLaunch => "WillLaunch",
1203            Lifecycle::DidLaunch => "DidLaunch",
1204            Lifecycle::DidBecomeActive => "DidBecomeActive",
1205            Lifecycle::WillResignActive => "WillResignActive",
1206            Lifecycle::WillEnterForeground => "WillEnterForeground",
1207            Lifecycle::DidEnterBackground => "DidEnterBackground",
1208            Lifecycle::DidReceiveMemoryWarning => "DidReceiveMemoryWarning",
1209            Lifecycle::WillTerminate => "WillTerminate",
1210            Lifecycle::DidExit => "DidExit",
1211        }
1212    }
1213}
1214
1215/// The phase of a drag gesture (docs/shapes.md).
1216#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1217pub enum DragPhase {
1218    Began,
1219    Changed,
1220    Ended,
1221}
1222
1223/// A gesture a node wants delivered. Backends attach the matching native recognizer when day-core
1224/// calls [`Toolkit::enable_gesture`]; the default is no gesture (recognizers cost, so opt-in).
1225#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1226pub enum GestureKind {
1227    Tap,
1228    LongPress,
1229    Drag,
1230    /// The pointer moving over the node without pressing (docs/canvas.md "Interaction"), and
1231    /// leaving it. Delivered only where a pointer exists: every desktop, an iPad with a trackpad
1232    /// or pencil, an Android device with a mouse or stylus. A touch-only device reports none,
1233    /// which is the right answer, not a gap, so anything reachable by hover must also be
1234    /// reachable by a tap.
1235    Hover,
1236    /// Pinch/magnify (docs/shapes.md): trackpad magnification, two-finger touch pinch.
1237    Pinch,
1238    /// Rotation (docs/canvas.md "Zoom and pan"): trackpad rotate, two-finger touch twist.
1239    Rotate,
1240    /// Viewport pan (docs/shapes.md): trackpad two-finger scroll, two-finger touch pan.
1241    /// Distinct from [`GestureKind::Drag`], the primary pointer's press-drag.
1242    Pan,
1243}
1244
1245// ---------------------------------------------------------------------------
1246// Menus (app menu bar + context menus). The model is a toolkit-neutral tree; each backend renders
1247// it with its native affordance (NSMenu / GMenu+GtkPopoverMenu / QMenu / UIMenu / Android
1248// PopupMenu / XAML MenuFlyout) and its own conventions, so day imposes no menu manager of its own.
1249// ---------------------------------------------------------------------------
1250
1251/// A keyboard shortcut for a menu item. `primary` is the platform's command modifier (⌘ on Apple,
1252/// Ctrl on GTK/Qt/XAML) so one declaration reads correctly everywhere. `key` is a single character
1253/// (`"s"`, `"."`) or a named key (`"Return"`, `"Delete"`, `"Left"`, `"F1"`).
1254#[derive(Clone, Debug, PartialEq, Eq, Default)]
1255pub struct Shortcut {
1256    pub key: String,
1257    /// ⌘ (Apple) / Ctrl (elsewhere). The conventional command modifier.
1258    pub primary: bool,
1259    pub shift: bool,
1260    /// ⌥ / Alt.
1261    pub alt: bool,
1262    /// Literal Control (⌃ on Apple). Rare; prefer `primary` for the command modifier.
1263    pub control: bool,
1264}
1265
1266impl Shortcut {
1267    /// `primary`+`key` (⌘S / Ctrl+S), the common case: `Shortcut::primary("s").shift()`.
1268    pub fn primary(key: impl Into<String>) -> Shortcut {
1269        Shortcut {
1270            key: key.into(),
1271            primary: true,
1272            ..Default::default()
1273        }
1274    }
1275    /// `key` with no modifiers (e.g. `F1`, plain `Delete`).
1276    pub fn plain(key: impl Into<String>) -> Shortcut {
1277        Shortcut {
1278            key: key.into(),
1279            ..Default::default()
1280        }
1281    }
1282    #[must_use]
1283    pub fn shift(mut self) -> Shortcut {
1284        self.shift = true;
1285        self
1286    }
1287    #[must_use]
1288    pub fn alt(mut self) -> Shortcut {
1289        self.alt = true;
1290        self
1291    }
1292    #[must_use]
1293    pub fn control(mut self) -> Shortcut {
1294        self.control = true;
1295        self
1296    }
1297}
1298
1299/// A standard/system command. The backend supplies the native item, a selector on AppKit/UIKit
1300/// (`cut:`/`copy:`/`paste:`…) or a stock action on GTK/Qt/XAML, so it targets the focused
1301/// control, gets the platform's default label + shortcut, and enables/disables itself
1302/// automatically. This is how default items (Edit ▸ Cut/Copy/Paste, the app's Quit/About) are
1303/// accommodated without the app re-implementing them.
1304#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1305pub enum MenuRole {
1306    Cut,
1307    Copy,
1308    Paste,
1309    SelectAll,
1310    Undo,
1311    Redo,
1312    Delete,
1313    /// The app's About command (docs/settings.md). With an About registered through
1314    /// `day::register_about` the item lowers to that dispatch action (a Day-rendered About
1315    /// window, or the toolkit's own About dialog where one exists); without one AppKit shows
1316    /// its stock Info.plist panel and the other desktops show the label alone.
1317    About,
1318    Quit,
1319    Preferences,
1320    Minimize,
1321    CloseWindow,
1322    Fullscreen,
1323    /// File ▸ New Window (docs/windows.md): opens another window through the builder the
1324    /// app registered with `day::register_new_window`. No platform has a native selector
1325    /// for it, so the item lowers to the registered dispatch action (disabled when none).
1326    NewWindow,
1327    /// Check for Updates… (docs/settings.md): placed directly under About in the macOS App
1328    /// menu (the Sparkle convention) and in Help elsewhere. Lowers to the action an updater
1329    /// registered with `day::register_check_for_updates`; absent from the bar when none did.
1330    CheckForUpdates,
1331}
1332
1333/// The keyboard modifiers held at an interaction, queryable ambiently
1334/// ([`Toolkit::modifiers`]): `primary` is the platform's command key (⌘ on Apple platforms,
1335/// Ctrl elsewhere, the same convention [`Shortcut::primary`] uses). Touch-only backends
1336/// answer all-false.
1337#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1338pub struct Modifiers {
1339    pub shift: bool,
1340    pub primary: bool,
1341    pub alt: bool,
1342}
1343
1344/// A standard edit command a platform route delivered ([`Event::Edit`]).
1345#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1346pub enum EditOp {
1347    Cut,
1348    Copy,
1349    Paste,
1350    SelectAll,
1351}
1352
1353/// What the app's edit bridge can currently do, mirrored into the toolkit
1354/// ([`Toolkit::set_edit_state`]) so native menu validation enables the stock items.
1355/// `can_paste` is the app's half ("a paste handler is installed"); the toolkit combines it
1356/// with its own clipboard-has-text check where one exists.
1357#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1358pub struct EditState {
1359    pub can_cut: bool,
1360    pub can_copy: bool,
1361    pub can_paste: bool,
1362    pub can_select_all: bool,
1363}
1364
1365/// The undo stack's face, as a native front mirrors it ([`Toolkit::set_undo_state`]): what is
1366/// possible and what the menu titles should say. Labels arrive already localized: a toolkit
1367/// cannot invent translated text, the same rule as every other label in this file.
1368#[derive(Clone, Debug, PartialEq, Default)]
1369pub struct UndoState {
1370    pub can_undo: bool,
1371    pub can_redo: bool,
1372    /// The next undo unit's display label ("Rename"), empty when nothing is undoable. Fronts
1373    /// interpolate it into the platform's own title form ("Undo Rename").
1374    pub undo_label: String,
1375    pub redo_label: String,
1376}
1377
1378/// One entry in a menu (recursive: a `Submenu` nests).
1379#[derive(Clone, Debug, PartialEq)]
1380pub enum MenuItem {
1381    /// A command. `action` (nonzero) dispatches [`Event::MenuAction`] to the app; a `role`-only item
1382    /// uses the native standard command instead (action 0). `label`/`shortcut` override the role's
1383    /// defaults. `icon` is the platform's own glyph beside the title where menus carry one (macOS,
1384    /// Windows, GNOME, KDE, Android); a backend whose menus are text-only ignores it.
1385    ///
1386    /// The `id`/`action` split is [`ToolbarItem`]'s: `id` names the item and `action` is what it
1387    /// runs. They are separate because a label cannot serve as a name (it is localized, and an
1388    /// item that shows its own state changes it), so anything addressing an item from outside
1389    /// (dayscript's `menu: { id: … }`) needs something that does not move.
1390    Action {
1391        /// The app's own name for this item, where it gave one. Stable across locales and across
1392        /// a change of `checked`, and unique within the menu it is installed in.
1393        id: Option<String>,
1394        /// The item's command, as a dispatch id from the same registry [`Event::MenuAction`] uses
1395        /// (0 = no command), so a toolbar button and its menu twin can share one closure.
1396        action: u64,
1397        label: String,
1398        shortcut: Option<Shortcut>,
1399        enabled: bool,
1400        /// On/off state where the item stands for a setting or one of several choices, drawn with
1401        /// the platform's own check mark. `None` is a plain command and reserves no mark; `Some`
1402        /// makes the item checkable and says which way it currently sits.
1403        ///
1404        /// The item still runs its `action` when chosen; a backend never flips this on its own.
1405        /// The app owns the state, and re-installing the menu (`app_menu`, which re-lowers on change) is what moves
1406        /// the mark, so what the menu shows can never disagree with what the app thinks.
1407        checked: Option<bool>,
1408        role: Option<MenuRole>,
1409        icon: Option<Icon>,
1410    },
1411    /// A nested submenu. At the top level of an app menu a `role` claims one of the platform's
1412    /// standard menu-bar slots: the backend then uses this menu instead of its stock one, and
1413    /// places it where the platform expects that menu to sit.
1414    Submenu {
1415        label: String,
1416        items: Vec<MenuItem>,
1417        role: Option<MenuBarRole>,
1418    },
1419    /// A visual separator.
1420    Separator,
1421}
1422
1423/// A standard menu-bar slot (macOS's File/Edit/View/Window/Help, and their counterparts
1424/// elsewhere). A backend that has a house style for the menu bar fills every slot an app did
1425/// not claim with its own stock menu, so an app never has to restate the platform's furniture,
1426/// and can still replace any of it by tagging its own submenu with the matching role.
1427#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1428#[non_exhaustive]
1429pub enum MenuBarRole {
1430    File,
1431    Edit,
1432    View,
1433    /// KDE/Plasma's Settings menu (`Configure <App>`, Configure Shortcuts). No counterpart on
1434    /// macOS, where preferences live in the app menu, or on GNOME/Windows.
1435    Settings,
1436    /// macOS's Window menu. Windows and Linux desktops do not have one.
1437    Window,
1438    Help,
1439}
1440
1441// ---------------------------------------------------------------------------
1442// Window toolbars (docs/toolbars.md)
1443// ---------------------------------------------------------------------------
1444
1445/// A standard icon, named by what it means rather than by how it looks, so each backend can
1446/// draw the platform's own glyph for it: an SF Symbol on macOS, a freedesktop icon name on
1447/// GTK and Qt, a Fluent glyph on Windows. This is the only way an icon looks native on every
1448/// desktop at once; a bundled PNG cannot, because it is one artist's take on all four.
1449///
1450/// The set is kept small: the commands that recur across toolbars. Anything
1451/// app-specific is an [`Icon::Image`].
1452#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1453#[non_exhaustive]
1454pub enum Symbol {
1455    Add,
1456    Remove,
1457    Delete,
1458    Edit,
1459    New,
1460    Open,
1461    Save,
1462    Print,
1463    Refresh,
1464    Search,
1465    Share,
1466    Settings,
1467    Info,
1468    Star,
1469    Bookmark,
1470    Back,
1471    Forward,
1472    Up,
1473    Down,
1474    Home,
1475    /// Show/hide the sidebar, the leading item of most desktop toolbars.
1476    Sidebar,
1477    Filter,
1478    Sort,
1479    /// An overflow affordance (macOS `ellipsis`, Android's vertical `more_vert`, GNOME's hamburger,
1480    /// Fluent `More`).
1481    More,
1482    Play,
1483    Pause,
1484    Stop,
1485    /// A photo capture: a screenshot command, a camera control.
1486    Camera,
1487    /// Source code.
1488    Code,
1489    /// Light appearance (a sun). The three below are the vocabulary of a theme chooser, which
1490    /// every platform draws with the same three ideas.
1491    Light,
1492    /// Dark appearance (a moon).
1493    Dark,
1494    /// Follow the system: the half-filled circle every platform uses for "automatic".
1495    Auto,
1496    ZoomIn,
1497    ZoomOut,
1498    /// Back to actual size: the 100% zoom command between [`Symbol::ZoomIn`] and
1499    /// [`Symbol::ZoomOut`].
1500    ZoomReset,
1501    Undo,
1502    Redo,
1503    Copy,
1504    Cut,
1505    Paste,
1506    Mail,
1507    Folder,
1508    Document,
1509    Check,
1510    Close,
1511    Warning,
1512    /// A rectangle: the shape vocabulary a drawing surface needs (docs/shapes.md), and the
1513    /// glyphs every drawing, diagram and annotation tool puts in the same place.
1514    Rectangle,
1515    /// An ellipse.
1516    Oval,
1517    /// An outlined circle: the read/unread vocabulary (a read row, its dot removed), and the
1518    /// generic ring glyph.
1519    Circle,
1520    /// A filled circle: the unread dot itself.
1521    CircleFilled,
1522    /// A straight line segment.
1523    Line,
1524    /// Combine the selection into a group: the drawing-tool command (two stacked squares).
1525    Group,
1526    /// Dissolve a group back into its members (two separated squares).
1527    Ungroup,
1528    /// Text: a line of type as a drawing element (the drawing-tool "T").
1529    Text,
1530    /// The device's own position: a map's "show my location" button (Apple's arrow, the
1531    /// crosshair elsewhere).
1532    Location,
1533    /// The open tabs or windows: a browser's tab switcher (two overlapping squares).
1534    Tabs,
1535    /// A book: a library of bookmarks or saved reading (Safari's bookmarks button).
1536    Book,
1537    /// Past activity: a history list (a clock with a turning arrow).
1538    History,
1539}
1540
1541/// The SF Symbol each standard symbol draws as. The system's own glyphs match the user's
1542/// device: weight, optical size, accent color and all. Shared by both Apple backends
1543/// (toolbars on macOS, menus on both).
1544///
1545/// The match is exhaustive so that a new [`Symbol`] must name its glyph here rather than
1546/// silently drawing nothing on Apple. A name this OS release does not know still resolves to
1547/// no image, and the item falls back to its label.
1548#[must_use]
1549pub fn sf_symbol_name(s: Symbol) -> &'static str {
1550    match s {
1551        Symbol::Add => "plus",
1552        Symbol::Remove => "minus",
1553        Symbol::Delete => "trash",
1554        Symbol::Edit => "pencil",
1555        Symbol::New => "square.and.pencil",
1556        Symbol::Open | Symbol::Folder => "folder",
1557        Symbol::Save => "square.and.arrow.down",
1558        Symbol::Print => "printer",
1559        Symbol::Refresh => "arrow.clockwise",
1560        Symbol::Search => "magnifyingglass",
1561        Symbol::Share => "square.and.arrow.up",
1562        Symbol::Settings => "gearshape",
1563        Symbol::Info => "info.circle",
1564        Symbol::Star => "star",
1565        Symbol::Bookmark => "bookmark",
1566        Symbol::Back => "chevron.backward",
1567        Symbol::Forward => "chevron.forward",
1568        Symbol::Up => "chevron.up",
1569        Symbol::Down => "chevron.down",
1570        Symbol::Home => "house",
1571        Symbol::Sidebar => "sidebar.leading",
1572        Symbol::Filter => "line.3.horizontal.decrease",
1573        Symbol::Sort => "arrow.up.arrow.down",
1574        Symbol::More => "ellipsis",
1575        Symbol::Play => "play.fill",
1576        Symbol::Pause => "pause.fill",
1577        Symbol::Stop => "stop.fill",
1578        Symbol::Camera => "camera",
1579        Symbol::Code => "chevron.left.forwardslash.chevron.right",
1580        Symbol::Light => "sun.max",
1581        Symbol::Dark => "moon",
1582        Symbol::Auto => "circle.lefthalf.filled",
1583        Symbol::ZoomIn => "plus.magnifyingglass",
1584        Symbol::ZoomReset => "1.magnifyingglass",
1585        Symbol::ZoomOut => "minus.magnifyingglass",
1586        Symbol::Undo => "arrow.uturn.backward",
1587        Symbol::Redo => "arrow.uturn.forward",
1588        Symbol::Copy => "doc.on.doc",
1589        Symbol::Cut => "scissors",
1590        Symbol::Paste => "doc.on.clipboard",
1591        Symbol::Mail => "envelope",
1592        Symbol::Document => "doc",
1593        Symbol::Check => "checkmark",
1594        Symbol::Close => "xmark",
1595        Symbol::Warning => "exclamationmark.triangle",
1596        Symbol::Rectangle => "rectangle",
1597        Symbol::Oval => "oval",
1598        Symbol::Circle => "circle",
1599        Symbol::CircleFilled => "circle.fill",
1600        Symbol::Line => "line.diagonal",
1601        Symbol::Group | Symbol::Tabs => "square.on.square",
1602        Symbol::Ungroup => "square.on.square.dashed",
1603        Symbol::Text => "textformat",
1604        Symbol::Location => "location",
1605        Symbol::Book => "book",
1606        Symbol::History => "clock.arrow.circlepath",
1607    }
1608}
1609
1610/// A button or toolbar item's picture: a standard [`Symbol`] (drawn with the platform's own icon set) or
1611/// a bundled image from `resource/images` for something only this app has.
1612#[derive(Clone, Debug, PartialEq)]
1613pub enum Icon {
1614    Symbol(Symbol),
1615    /// A bundled image name, resolved the same way [`ImageName`] is elsewhere.
1616    Image(String),
1617}
1618
1619/// What a toolbar item is. The variants are the vocabulary every desktop toolbar shares; each
1620/// backend realizes one with its native control, never with a drawn imitation.
1621#[derive(Clone, Debug, PartialEq)]
1622pub enum ToolbarItemKind {
1623    /// A push button running the item's `action`.
1624    Button,
1625    /// A two-state button. `on` seeds it; the user flipping it emits
1626    /// [`ToolbarValue::On`], and the app's own writes arrive as [`ToolbarPatch::On`].
1627    Toggle { on: bool },
1628    /// A button that drops a menu: the same [`MenuItem`] model the menu bar uses, so a
1629    /// toolbar menu and its menu-bar twin are one list of commands.
1630    Menu { items: Vec<MenuItem> },
1631    /// A search field. Edits emit [`ToolbarValue::Text`]; the app's own writes arrive as
1632    /// [`ToolbarPatch::Text`].
1633    ///
1634    /// Day creates this item itself, from a `.searchable()` surface whose placement resolved to
1635    /// the toolbar (docs/search.md); apps declare search on the surface, never here.
1636    Search {
1637        text: String,
1638        placeholder: String,
1639        /// Completions for the current text, drawn by the field's own completion affordance
1640        /// where it has one (`AutoSuggestBox`, `QCompleter`, `<datalist>`). Empty = none.
1641        suggestions: Vec<String>,
1642    },
1643    /// A row of mutually exclusive choices drawn as one control: the native segmented control
1644    /// (`NSSegmentedControl`, a linked GTK/Qt button box, a XAML toggle strip, `.day-segmented`
1645    /// on the web).
1646    ///
1647    /// This is what a set of related toolbar toggles should be when exactly one of them is on at
1648    /// a time: three separate toggles say "three independent switches" to the eye and to a screen
1649    /// reader, and leave the app to keep them exclusive. Choosing a segment emits
1650    /// [`ToolbarValue::Selected`]; the app's own writes arrive as [`ToolbarPatch::Selected`].
1651    Segmented {
1652        /// One entry per segment. A segment with an icon draws it in place of its title where
1653        /// the platform does that, and keeps the title as its accessible name.
1654        segments: Vec<ToolbarSegment>,
1655        selected: usize,
1656    },
1657    /// Static text, for a status or a caption.
1658    Label,
1659    /// A divider between neighbors in the same placement bucket, where the platform draws one
1660    /// (macOS toolbars have no separator, so AppKit renders it as a fixed space,
1661    /// docs/toolbars.md). Grouping is all it does: alignment is [`ToolbarPlacement`]'s job.
1662    Separator,
1663}
1664
1665/// One choice inside a [`ToolbarItemKind::Segmented`] control.
1666#[derive(Clone, Debug, PartialEq)]
1667pub struct ToolbarSegment {
1668    /// The segment's name: its label where the platform shows text, its accessible name always.
1669    pub title: String,
1670    pub icon: Option<Icon>,
1671}
1672
1673/// The reserved id of the sidebar affordance a `nav(Sidebar)` supplies for itself
1674/// (docs/toolbars.md). Backends with a system item for the job (AppKit's
1675/// `NSToolbarToggleSidebarItem`) recognize it by this id and draw theirs instead; dayscript
1676/// recognizes it to drive the toolkit's own duty rather than an app closure.
1677pub const SIDEBAR_TOGGLE_ID: &str = "day::sidebar_toggle";
1678
1679/// The reserved id of a `.searchable()` surface's field (docs/search.md): the `ToolbarItem` a
1680/// desktop bar draws for it, and the name dayscript's `toolbar:` step drives it by wherever the
1681/// platform put it — on the bar, or inline on the navigation surface where the bar holds no
1682/// field, in which case day-core resolves the id to that host instead.
1683pub const SEARCH_ITEM_ID: &str = "day::search";
1684
1685/// One item in a window's toolbar (docs/toolbars.md).
1686#[derive(Clone, Debug, PartialEq)]
1687pub struct ToolbarItem {
1688    /// Stable identity: the native item identifier, the dayscript target, and the key a
1689    /// [`ToolbarPatch`] addresses. Unique within a toolbar.
1690    pub id: String,
1691    pub kind: ToolbarItemKind,
1692    /// The item's name. Shown beside or below the icon where the platform does that, and used
1693    /// verbatim in the overflow and customization menus, so it is never optional, even on a
1694    /// toolbar that only shows icons. It is also the item's accessible name.
1695    pub label: String,
1696    /// Hover help. Defaults to `label` where the platform expects a tooltip and none is given.
1697    pub tooltip: Option<String>,
1698    pub icon: Option<Icon>,
1699    pub enabled: bool,
1700    /// The item's command, as a dispatch id from the same registry [`Event::MenuAction`] uses
1701    /// (0 = no command), so a toolbar button and its menu twin can share one closure.
1702    pub action: u64,
1703    /// This item's role on the chrome carrying it (docs/toolbars.md). It never names a surface:
1704    /// Which chrome an item rides is decided by where the app declared it, so this says only
1705    /// where on that chrome it belongs.
1706    pub placement: ToolbarPlacement,
1707    /// Whether the item draws its title, its icon, or both, where the platform can do more than
1708    /// one. An item folded into an overflow menu shows its title whatever this asks for; a menu
1709    /// row with no words is not a menu row.
1710    pub label_style: LabelStyle,
1711    /// Draw this item in the platform's emphasized style (a tinted/filled bar button, a
1712    /// prominent `NSToolbarItem`). For the one action a chrome is really offering.
1713    pub prominent: bool,
1714    /// Which column of a multi-pane window this item came from (docs/toolbars.md), set by Day
1715    /// from the piece that declared it, never by an app.
1716    ///
1717    /// A desktop toolbar spans every column at once, and a three-pane app expects each column's
1718    /// commands to sit over that column: the sidebar's against the first divider, the list's over
1719    /// the list, the rest over the detail. That is what Mail, Notes and Finder do, and it is only
1720    /// expressible because the declaration site already said which pane the command belongs to.
1721    /// Backends that draw one undivided bar ignore it.
1722    pub column: ToolbarColumn,
1723}
1724
1725/// Which pane of a window's navigation a toolbar item was declared in (docs/toolbars.md).
1726#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1727pub enum ToolbarColumn {
1728    /// The window itself, over no particular column. Draws with the detail's items, which is
1729    /// where a command that acts on the whole window belongs when the panes are side by side.
1730    #[default]
1731    Window,
1732    /// The sidebar / master column.
1733    Sidebar,
1734    /// The content-list column between the sidebar and the detail.
1735    List,
1736    /// The detail column.
1737    Detail,
1738}
1739
1740/// Where an item sits on the chrome that carries it (docs/toolbars.md).
1741///
1742/// A placement is a role, never a surface. Which toolbar, navigation bar or column an item
1743/// rides follows from the piece that declared it, so an app never spells that out twice.
1744#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1745pub enum ToolbarPlacement {
1746    /// The natural spot on this chrome: after the leading group on a desktop toolbar, the
1747    /// trailing item group on a navigation bar, an `IF_ROOM` menu action on Android.
1748    #[default]
1749    Automatic,
1750    /// The leading edge: a pane toggle, a control that reveals what is to its left.
1751    Navigation,
1752    /// Centered: a title accessory, a transport, a status readout.
1753    Principal,
1754    /// Trailing, and the last thing a crowded chrome gives up.
1755    Primary,
1756    /// Trailing, and the first thing a crowded chrome folds into its overflow.
1757    Secondary,
1758    /// A bottom bar where the platform has one (iOS `toolbarItems`, an Android bottom app bar);
1759    /// [`ToolbarPlacement::Secondary`] everywhere else.
1760    Bottom,
1761}
1762
1763/// Which halves of an item's label a platform draws, where it can draw more than one.
1764#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1765pub enum LabelStyle {
1766    /// The platform's own convention for this chrome.
1767    #[default]
1768    Automatic,
1769    /// The icon alone (the title stays as the accessible name and the tooltip).
1770    IconOnly,
1771    /// The title alone, even where an icon was given.
1772    TitleOnly,
1773    /// Both, where the chrome has room for both.
1774    TitleAndIcon,
1775}
1776
1777/// A value a toolbar item produced.
1778#[derive(Clone, Debug, PartialEq)]
1779pub enum ToolbarValue {
1780    /// A search item's full new text.
1781    Text(String),
1782    /// A search item's text, submitted with the field's Return or Search key. Sent after the
1783    /// last [`ToolbarValue::Text`]; it changes no state of its own.
1784    Submit(String),
1785    /// A toggle item's new state.
1786    On(bool),
1787    /// A segmented item's newly chosen index.
1788    Selected(usize),
1789}
1790
1791/// A targeted update to one live toolbar item: the path that keeps a bound signal in sync
1792/// without rebuilding the bar (which would drop the search field's focus mid-keystroke).
1793#[derive(Clone, Debug, PartialEq)]
1794pub enum ToolbarPatch {
1795    /// Focus a search control and select its text without changing its value.
1796    Focus { item: String },
1797    /// Replace a search item's text.
1798    Text { item: String, text: String },
1799    /// Set a toggle item's state.
1800    On { item: String, on: bool },
1801    /// Select a segmented item's index.
1802    Selected { item: String, index: usize },
1803    /// Enable or disable any item.
1804    Enabled { item: String, on: bool },
1805    /// Replace a search item's completions (docs/search.md). Targeted rather than a rebuild,
1806    /// because these change on every keystroke and rebuilding the bar would take the field's
1807    /// focus with it.
1808    Suggestions { item: String, list: Vec<String> },
1809    /// Replace an item's words (a language change): its label, which an icon-only item still
1810    /// carries for the overflow menu and assistive technology, and its tooltip. The item keeps
1811    /// its native widget, its action and its place.
1812    Label {
1813        item: String,
1814        label: String,
1815        tooltip: Option<String>,
1816    },
1817    /// Replace a search item's empty-state prompt (docs/search.md), in the live field.
1818    Placeholder { item: String, text: String },
1819}
1820
1821impl ToolbarPatch {
1822    /// The id of the item this patch addresses.
1823    #[must_use]
1824    pub fn item(&self) -> &str {
1825        match self {
1826            ToolbarPatch::Focus { item }
1827            | ToolbarPatch::Text { item, .. }
1828            | ToolbarPatch::On { item, .. }
1829            | ToolbarPatch::Selected { item, .. }
1830            | ToolbarPatch::Enabled { item, .. }
1831            | ToolbarPatch::Suggestions { item, .. }
1832            | ToolbarPatch::Label { item, .. }
1833            | ToolbarPatch::Placeholder { item, .. } => item,
1834        }
1835    }
1836
1837    /// Write this patch's value into `items`, the model of a bar. `false` when no item there
1838    /// takes it (an unknown id, or a kind the value does not apply to).
1839    pub fn apply_to(&self, items: &mut [ToolbarItem]) -> bool {
1840        let Some(it) = items.iter_mut().find(|i| i.id == self.item()) else {
1841            return false;
1842        };
1843        match (self, &mut it.kind) {
1844            (ToolbarPatch::Focus { .. }, ToolbarItemKind::Search { .. }) => (),
1845            (ToolbarPatch::Text { text, .. }, ToolbarItemKind::Search { text: t, .. }) => {
1846                t.clone_from(text);
1847            }
1848            (
1849                ToolbarPatch::Suggestions { list, .. },
1850                ToolbarItemKind::Search { suggestions, .. },
1851            ) => suggestions.clone_from(list),
1852            (ToolbarPatch::On { on, .. }, ToolbarItemKind::Toggle { on: o }) => *o = *on,
1853            (
1854                ToolbarPatch::Selected { index, .. },
1855                ToolbarItemKind::Segmented { segments, selected },
1856            ) if *index < segments.len() => *selected = *index,
1857            (ToolbarPatch::Enabled { on, .. }, _) => it.enabled = *on,
1858            (ToolbarPatch::Label { label, tooltip, .. }, _) => {
1859                it.label = label.clone();
1860                it.tooltip = tooltip.clone();
1861            }
1862            (
1863                ToolbarPatch::Placeholder { text, .. },
1864                ToolbarItemKind::Search { placeholder, .. },
1865            ) => placeholder.clone_from(text),
1866            _ => return false,
1867        }
1868        true
1869    }
1870}
1871
1872/// One step of an edit to a window's toolbar (docs/toolbars.md).
1873///
1874/// Day hands a backend its bar as edits, never as a whole new model to rebuild, for the same
1875/// reason the view tree arrives as `insert`/`remove` rather than as a fresh tree: an item the
1876/// edit does not name keeps its native widget, and with it the keyboard focus, the caret, a
1877/// menu that is open. A value (search text, a toggle) never travels as an edit; it is a
1878/// [`ToolbarPatch`] on the live item.
1879///
1880/// An edit lists every [`ToolbarOp::Remove`] first, then every [`ToolbarOp::Insert`] in
1881/// ascending `index`, so applying them in order to the bar's current items (a
1882/// [`ToolbarMirror`] does exactly that) produces the new bar. Items keep their relative order
1883/// across an edit: an item that moves arrives as a remove and an insert, like one whose
1884/// presentation changed.
1885#[derive(Clone, Debug, PartialEq)]
1886pub enum ToolbarOp {
1887    /// The item with this id leaves the bar.
1888    Remove { id: String },
1889    /// `item` joins the bar at `index`, its position once this edit is complete.
1890    Insert { index: usize, item: ToolbarItem },
1891}
1892
1893impl ToolbarOp {
1894    /// Apply this op to `items`, a bar's model in order.
1895    pub fn apply_to(&self, items: &mut Vec<ToolbarItem>) {
1896        match self {
1897            ToolbarOp::Remove { id } => items.retain(|i| i.id != *id),
1898            ToolbarOp::Insert { index, item } => {
1899                items.insert((*index).min(items.len()), item.clone());
1900            }
1901        }
1902    }
1903}
1904
1905/// A backend's copy of one window's toolbar, kept in step with the [`ToolbarOp`]s and
1906/// [`ToolbarPatch`]es that reach it, and the one place a backend works out where a new item
1907/// goes (docs/toolbars.md).
1908///
1909/// Every backend lays its bar out as a few groups (the leading and trailing ends of a header
1910/// bar, the columns of a split window, the primary and overflow commands of a command bar) and
1911/// keeps model order within each. So an inserted item always goes right after
1912/// [`ToolbarMirror::prev_where`] its own group, or first in the group when that is `None`, and
1913/// nothing already on the bar moves.
1914#[derive(Clone, Debug, Default)]
1915pub struct ToolbarMirror {
1916    items: Vec<ToolbarItem>,
1917}
1918
1919impl ToolbarMirror {
1920    /// The bar's items, in model order.
1921    #[must_use]
1922    pub fn items(&self) -> &[ToolbarItem] {
1923        &self.items
1924    }
1925
1926    #[must_use]
1927    pub fn is_empty(&self) -> bool {
1928        self.items.is_empty()
1929    }
1930
1931    /// The item with this id.
1932    #[must_use]
1933    pub fn get(&self, id: &str) -> Option<&ToolbarItem> {
1934        self.items.iter().find(|i| i.id == id)
1935    }
1936
1937    /// The item dispatching `action`: how a backend whose native bar reports only an action
1938    /// id (a menu tap) finds what was tapped.
1939    #[must_use]
1940    pub fn by_action(&self, action: u64) -> Option<&ToolbarItem> {
1941        self.items
1942            .iter()
1943            .find(|i| i.action == action && action != 0)
1944    }
1945
1946    /// Take the item with `id` out, returning it.
1947    pub fn remove(&mut self, id: &str) -> Option<ToolbarItem> {
1948        let at = self.items.iter().position(|i| i.id == id)?;
1949        Some(self.items.remove(at))
1950    }
1951
1952    /// Put `item` at `index` (clamped to the end).
1953    pub fn insert(&mut self, index: usize, item: ToolbarItem) {
1954        let at = index.min(self.items.len());
1955        self.items.insert(at, item);
1956    }
1957
1958    /// Apply one op to the model: what a backend that repaints its whole native bar from the
1959    /// model (a menu of actions) does with each.
1960    pub fn apply(&mut self, op: &ToolbarOp) {
1961        op.apply_to(&mut self.items);
1962    }
1963
1964    /// Write a value patch into the model. `false` when no item takes it.
1965    pub fn patch(&mut self, patch: &ToolbarPatch) -> bool {
1966        patch.apply_to(&mut self.items)
1967    }
1968
1969    /// The nearest item before `index` that `same_group` accepts: the native item a new one at
1970    /// `index` goes right after, in that group. `None` = it goes first in the group.
1971    pub fn prev_where(
1972        &self,
1973        index: usize,
1974        same_group: impl Fn(&ToolbarItem) -> bool,
1975    ) -> Option<&ToolbarItem> {
1976        self.items[..index.min(self.items.len())]
1977            .iter()
1978            .rev()
1979            .find(|i| same_group(i))
1980    }
1981}
1982
1983#[derive(Clone, Debug, PartialEq)]
1984pub struct KeyEvent {
1985    /// The key's name, in the web `KeyboardEvent.key` vocabulary every platform can map onto:
1986    /// the four arrows ("`ArrowLeft`", "`ArrowRight`", "`ArrowUp`", "`ArrowDown`") and the ten digits
1987    /// ("0" through "9", from the main row or the numeric keypad) everywhere, plus
1988    /// "Delete" and "Backspace" on backends with no menu bar ([`Cap::AppMenu`] unsupported),
1989    /// where no accelerator can own those keys. A focused piece claims every key the route
1990    /// carries, so offering them on a menu-bar platform would let a canvas swallow the Delete
1991    /// its own Edit menu was about to act on (docs/menus.md). The two delete keys keep the
1992    /// names the platform gives the physical keys (a Mac's ⌫ is "Backspace" and its ⌦ is
1993    /// "Delete"), so a handler that means "remove this" takes both. A digit arrives only while
1994    /// neither [`KeyEvent::PRIMARY`] nor [`KeyEvent::ALT`] (nor a Mac's Control) is held: ⌘1
1995    /// and Ctrl+1 are accelerators, and a canvas claiming them would starve the menu. Most
1996    /// backends name the digit the keypress types, so a layout whose number row needs Shift for
1997    /// digits reports "1" with [`KeyEvent::SHIFT`] set; XAML and ArkUI read the physical key.
1998    /// Backends emit `Event::Key` only while no text widget has focus; a field's own editing
1999    /// keys never surface here. The one exception is a single-line text field with a key
2000    /// handler ([`keys::handled`] for its node): it hands "`ArrowUp`", "`ArrowDown`" and "Escape",
2001    /// pressed with no modifier, to that handler instead of acting on them itself, so an
2002    /// address bar can walk a suggestion list (docs/textfield.md "Keys").
2003    ///
2004    /// A piece that declared `Decorate::keyboard()` takes the full route instead: every key
2005    /// the platform delivers while it is focused. A key that types nothing is named by its
2006    /// web name ([`KeyEvent::NAMED`]: "Enter", "Tab", "Escape", "Backspace", "Delete", "Home",
2007    /// "End", "`PageUp`", "`PageDown`", "Insert", the arrows and "F1" through "F12"); a key that
2008    /// types is named by its unmodified character ("a", "A" under Shift, "8", "ü" on a layout
2009    /// that has one), and what it typed rides in [`KeyEvent::text`]. Under Control or Alt the
2010    /// name stays that character ("c" with [`KeyEvent::CONTROL`] set, never the control code
2011    /// it would type). Text an input method commits (a dead-key accent, a Japanese phrase,
2012    /// the soft keyboard's word) arrives with the text alone and an empty name: no single
2013    /// key is behind it. Only the platform's command chords stay out: ⌘ on Apple platforms
2014    /// and the browser's own shortcuts belong to the menu and the browser, so a terminal's
2015    /// ⌘C still copies. [`KeyEvent::typed`] is the question a text consumer asks.
2016    pub key: String,
2017    /// A [`KeyEvent::SHIFT`]/[`KeyEvent::PRIMARY`]/[`KeyEvent::ALT`]/[`KeyEvent::CONTROL`]
2018    /// mask.
2019    pub modifiers: u8,
2020    /// The text this press committed, on the full route: what the key typed ("a", "A", "é"
2021    /// after a dead key, the whole string an input method committed at once), or `None` for
2022    /// a key that typed nothing (a named key, a Control or Alt chord, a composition still in
2023    /// progress). Separate from [`KeyEvent::key`] so that a committed "Enter" is text and the
2024    /// Enter key is a key, whatever the input method sends. Always `None` on the short route.
2025    pub text: Option<String>,
2026}
2027
2028impl KeyEvent {
2029    pub const SHIFT: u8 = 1;
2030    /// The platform's command key: ⌘ on Apple platforms, Ctrl elsewhere (the
2031    /// [`Shortcut::primary`] convention).
2032    pub const PRIMARY: u8 = 2;
2033    pub const ALT: u8 = 4;
2034    /// The Control key itself, wherever it sits: on Apple platforms it is a different key from
2035    /// [`KeyEvent::PRIMARY`] (⌘), elsewhere the same one, so a Ctrl+C on Linux sets both.
2036    /// Carried on the full route only (`Decorate::keyboard`).
2037    pub const CONTROL: u8 = 8;
2038
2039    /// The ten digit key names, indexed by value.
2040    pub const DIGITS: [&'static str; 10] = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"];
2041
2042    /// Every name the full route gives a key that types nothing (the web `KeyboardEvent.key`
2043    /// vocabulary). A key outside this list is named by the text it types.
2044    pub const NAMED: [&'static str; 26] = [
2045        "ArrowLeft",
2046        "ArrowRight",
2047        "ArrowUp",
2048        "ArrowDown",
2049        "Enter",
2050        "Tab",
2051        "Escape",
2052        "Backspace",
2053        "Delete",
2054        "Home",
2055        "End",
2056        "PageUp",
2057        "PageDown",
2058        "Insert",
2059        "F1",
2060        "F2",
2061        "F3",
2062        "F4",
2063        "F5",
2064        "F6",
2065        "F7",
2066        "F8",
2067        "F9",
2068        "F10",
2069        "F11",
2070        "F12",
2071    ];
2072
2073    /// The text this press typed ([`KeyEvent::text`]), or `None` for a key that typed nothing.
2074    #[must_use]
2075    pub fn typed(&self) -> Option<&str> {
2076        self.text.as_deref()
2077    }
2078
2079    /// A key that types nothing (one of [`KeyEvent::NAMED`], or a chord's character under
2080    /// Control or Alt), on either route.
2081    pub fn named(key: impl Into<String>, modifiers: u8) -> KeyEvent {
2082        KeyEvent {
2083            key: key.into(),
2084            modifiers,
2085            text: None,
2086        }
2087    }
2088
2089    /// Text a press committed on the full route. The key is named by the text when the text
2090    /// is one character (the press typed it), and left empty for a longer commit, which no
2091    /// single key is behind.
2092    pub fn typed_text(text: impl Into<String>, modifiers: u8) -> KeyEvent {
2093        let text = text.into();
2094        let mut chars = text.chars();
2095        let key = match (chars.next(), chars.next()) {
2096            (Some(_), None) => text.clone(),
2097            _ => String::new(),
2098        };
2099        KeyEvent {
2100            key,
2101            modifiers,
2102            text: Some(text),
2103        }
2104    }
2105
2106    /// Text a press committed on the full route, named by the key that produced it
2107    /// (`key`, in the vocabulary above) when the backend knows it.
2108    pub fn typed_by(key: impl Into<String>, text: impl Into<String>, modifiers: u8) -> KeyEvent {
2109        KeyEvent {
2110            key: key.into(),
2111            modifiers,
2112            text: Some(text.into()),
2113        }
2114    }
2115
2116    /// The web name for the function key `F<n>`, `1..=12`.
2117    #[must_use]
2118    pub fn function_name(n: u8) -> Option<&'static str> {
2119        match n {
2120            1..=12 => Some(Self::NAMED[13 + n as usize]),
2121            _ => None,
2122        }
2123    }
2124
2125    /// The key name for a typed character when it is one of the ten digits: what a backend
2126    /// reports for a keypress that types `0`–`9`.
2127    #[must_use]
2128    pub fn digit_name(c: char) -> Option<&'static str> {
2129        c.to_digit(10).map(|d| Self::DIGITS[d as usize])
2130    }
2131
2132    /// The value of a digit key, or `None` for every other key.
2133    #[must_use]
2134    pub fn digit(&self) -> Option<u8> {
2135        match self.key.as_bytes() {
2136            [d @ b'0'..=b'9'] => Some(d - b'0'),
2137            _ => None,
2138        }
2139    }
2140
2141    #[must_use]
2142    pub fn shift(&self) -> bool {
2143        self.modifiers & Self::SHIFT != 0
2144    }
2145    #[must_use]
2146    pub fn primary(&self) -> bool {
2147        self.modifiers & Self::PRIMARY != 0
2148    }
2149    #[must_use]
2150    pub fn alt(&self) -> bool {
2151        self.modifiers & Self::ALT != 0
2152    }
2153    #[must_use]
2154    pub fn control(&self) -> bool {
2155        self.modifiers & Self::CONTROL != 0
2156    }
2157}
2158
2159#[cfg(test)]
2160mod key_event_tests {
2161    use super::KeyEvent;
2162
2163    #[test]
2164    fn digit_names_read_back_as_values() {
2165        for (value, c) in ('0'..='9').enumerate() {
2166            let name = KeyEvent::digit_name(c).expect("an ASCII digit names itself");
2167            let key = KeyEvent::named(name, 0);
2168            assert_eq!(key.digit(), Some(value as u8));
2169        }
2170        // Only the ASCII digits: a letter, an Arabic-Indic three, and a named key are not.
2171        assert_eq!(KeyEvent::digit_name('a'), None);
2172        assert_eq!(KeyEvent::digit_name('٣'), None);
2173        let arrow = KeyEvent::named("ArrowUp", 0);
2174        assert_eq!(arrow.digit(), None);
2175    }
2176
2177    #[test]
2178    fn typed_text_is_told_from_named_keys() {
2179        let a = KeyEvent::typed_text("a", 0);
2180        assert_eq!((a.key.as_str(), a.typed()), ("a", Some("a")));
2181        let space = KeyEvent::typed_text(" ", 0);
2182        assert_eq!((space.key.as_str(), space.typed()), (" ", Some(" ")));
2183        assert_eq!(KeyEvent::typed_text("7", 0).digit(), Some(7));
2184        // A longer commit has no key behind it.
2185        let phrase = KeyEvent::typed_text("こんにちは", 0);
2186        assert_eq!(
2187            (phrase.key.as_str(), phrase.typed()),
2188            ("", Some("こんにちは"))
2189        );
2190        // Text that spells a key name is still text, and the key is still a key.
2191        for name in KeyEvent::NAMED {
2192            assert_eq!(
2193                KeyEvent::named(name, 0).typed(),
2194                None,
2195                "{name} types nothing"
2196            );
2197            assert_eq!(KeyEvent::typed_text(name, 0).typed(), Some(name));
2198        }
2199        let accent = KeyEvent::typed_by("e", "é", 0);
2200        assert_eq!((accent.key.as_str(), accent.typed()), ("e", Some("é")));
2201        assert_eq!(KeyEvent::function_name(1), Some("F1"));
2202        assert_eq!(KeyEvent::function_name(12), Some("F12"));
2203        assert_eq!(KeyEvent::function_name(13), None);
2204        let chord = KeyEvent::named("c", KeyEvent::CONTROL | KeyEvent::SHIFT);
2205        assert!(chord.control() && chord.shift() && !chord.primary());
2206        assert_eq!(chord.typed(), None);
2207    }
2208
2209    #[test]
2210    fn a_declaration_claims_nothing_without_a_handler() {
2211        let node = super::NodeId(0xdead_0001);
2212        super::keys::mark_text(node);
2213        assert!(!super::keys::text(node), "no handler, no claim");
2214        super::keys::mark(node);
2215        assert!(super::keys::text(node) && super::keys::handled(node));
2216        super::keys::forget(node);
2217        assert!(!super::keys::text(node) && !super::keys::handled(node));
2218    }
2219}
2220
2221#[derive(Clone, Copy, Debug, PartialEq)]
2222pub struct PointerEvent {
2223    pub position: Point,
2224    pub down: bool,
2225}
2226
2227/// The event sink: enqueue-only. It may be invoked re-entrantly from inside any Toolkit method;
2228/// day-core drains queued events at safe points, each as a fresh batch (§3.3).
2229pub type EventSink = Box<dyn Fn(NodeId, Event)>;
2230
2231/// The synchronous row-pull closures for recycling lists (docs/list.md, §10). day-core injects one
2232/// per `LIST` host via [`Toolkit::attach_list`]; a recycling backend stores it and calls it from
2233/// its native data-source (on the UI thread, outside any day-core borrow). Each closure re-enters
2234/// day-core, so, unlike [`EventSink`], these run to completion synchronously (`bind_row` even
2235/// flushes + lays out the row before returning, so the host can measure the cell immediately).
2236#[derive(Clone)]
2237pub struct ListSource {
2238    /// Report the first actually visible row (exclude overscan). Enqueue-only; optional,
2239    /// so hosts without a viewport binding incur no app event work.
2240    pub first_visible: Option<std::rc::Rc<dyn Fn(usize)>>,
2241    /// Current row count.
2242    pub len: std::rc::Rc<dyn Fn() -> usize>,
2243    /// Present on a sectioned list (`ListProps::sections`, docs/list.md "Sections"): whether
2244    /// row `index` is a section header. Every row index the host sees counts headers, and
2245    /// day-core translates to the app's items. A header row is not selectable, activatable or
2246    /// swipeable; the host draws it in its platform's group-header style, sized to its content
2247    /// even in a `Uniform` list, and floats it where the platform does (macOS group rows,
2248    /// UIKit plain-table section headers).
2249    pub is_header: Option<std::rc::Rc<dyn Fn(usize) -> bool>>,
2250    /// Stable identity token for the row at `index` (for native diffing / animation).
2251    pub token_at: std::rc::Rc<dyn Fn(usize) -> u64>,
2252    /// Build (first use of this cell) or rebind (recycled cell) row `index` into the native cell.
2253    pub bind_row: std::rc::Rc<dyn Fn(usize, RawHandle)>,
2254    /// A host that emulates `Cap::ListSections` binds the header it pins over the top of the
2255    /// list with this instead of `bind_row` (docs/list.md "Sections"): the same build or
2256    /// rebind, but the copy carries no element ids, so a dayscript or accessibility lookup of a
2257    /// header finds the header row in the list, never its pinned copy.
2258    pub bind_pinned: std::rc::Rc<dyn Fn(usize, RawHandle)>,
2259    /// The native cell left the viewport; Day may drop per-cell bookkeeping (optional).
2260    pub recycle: std::rc::Rc<dyn Fn(RawHandle)>,
2261    /// The native host is done with this cell for good (a `GtkListItemFactory::teardown`, a
2262    /// `UITableViewCell` deallocating): Day disposes the row it built there, its scope, nodes
2263    /// and element ids. Without this a host that discards cells, as every pool does on a far
2264    /// jump, leaves one dead row behind in day-core per discarded cell. Safe inside a day-core
2265    /// borrow (the work is held for the borrow's end) and for a cell Day never saw.
2266    pub release: std::rc::Rc<dyn Fn(RawHandle)>,
2267    /// Re-lay the row bound to this cell at `width`, called from the cell's own native layout
2268    /// pass, the hook [`TreeSource::layout_cell`] already gives trees. day-core lays a row at the
2269    /// `LIST`'s width first, which is right wherever the cell is the row itself; a backend
2270    /// whose native row wraps the cell in chrome (`GtkListView`'s themed `row` node pads it)
2271    /// corrects it here, so the row fits the cell the platform gave it instead of holding the
2272    /// whole list wider than its frame. Skips quietly when called inside a day-core borrow (a
2273    /// snapshot pass).
2274    pub layout_cell: std::rc::Rc<dyn Fn(RawHandle, f64)>,
2275    /// The height day-core last laid the row bound to this cell at: the row's own height,
2276    /// padding included, as `RowHeight` resolves it. A backend whose cell measures itself
2277    /// (`GtkListView`'s `DayCell`) reports it as the cell's height, so a padded row keeps its
2278    /// bottom padding rather than the height of its last child's frame. `0.0` before the row's
2279    /// first layout, or inside a day-core borrow.
2280    pub cell_height: std::rc::Rc<dyn Fn(RawHandle) -> f64>,
2281    /// Drag-to-reorder closures, present when `ListProps::reorderable` (docs/list.md). `None` on
2282    /// non-reorderable lists; backends must not enable their drag machinery without it.
2283    pub reorder: Option<ListReorder>,
2284    /// Swipe-to-delete closures, present when `ListProps::deletable` (docs/list.md). `None` on
2285    /// non-deletable lists; backends must not offer their delete affordance without it.
2286    pub delete: Option<ListDelete>,
2287    /// Swipe-actions closures, present when `ListProps::swipe_actions` (docs/list.md). `None` on
2288    /// lists that declared none; backends must not install their row-action machinery
2289    /// without it.
2290    pub swipe: Option<ListSwipe>,
2291}
2292
2293/// The synchronous drag-to-reorder half of [`ListSource`] (docs/list.md). Both closures follow
2294/// `bind_row`'s discipline: called on the UI thread from inside native drag callbacks, outside
2295/// any day-core borrow, and they run to completion synchronously.
2296#[derive(Clone)]
2297pub struct ListReorder {
2298    /// May row `from` drop at row `to`? Called from the native validate/hover hook so the
2299    /// affordance (gap, insertion mark, forbidden cursor) reflects the app's answer live.
2300    /// Returns the accepted target index: `to` itself to allow, another index to retarget the
2301    /// drop, or `-1` to deny.
2302    pub can_move: std::rc::Rc<dyn Fn(usize, usize) -> i64>,
2303    /// Commit: row `from` dropped at row `to` (an index `can_move` accepted). Rotates Day's row
2304    /// snapshot before returning (so `len`/`token_at`/`bind_row` reflect the new order while the
2305    /// native move animates) and defers the app's own callback to the next event drain.
2306    pub move_row: std::rc::Rc<dyn Fn(usize, usize)>,
2307}
2308
2309/// The synchronous swipe-to-delete half of [`ListSource`] (docs/list.md), shaped exactly like
2310/// [`ListReorder`]: both closures are called on the UI thread from inside native swipe callbacks,
2311/// outside any day-core borrow, and run to completion synchronously.
2312///
2313/// Each platform spells the gesture its own way (a trailing swipe action on iOS, an
2314/// `ItemTouchHelper` swipe on Android, a `ListItem` swipe action on ArkUI), but all three ask the
2315/// same two questions, so this struct is one pair of closures rather than three shapes.
2316#[derive(Clone)]
2317pub struct ListDelete {
2318    /// May row `index` be deleted? Called before the affordance is offered, so a row the app
2319    /// protects shows no delete action at all rather than one that fails on use.
2320    pub can_delete: std::rc::Rc<dyn Fn(usize) -> bool>,
2321    /// Commit: delete row `index`. Removes it from Day's row snapshot before returning (so
2322    /// `len`/`token_at`/`bind_row` already reflect the shorter list while the native row-removal
2323    /// animates) and defers the app's own callback to the next event drain.
2324    pub delete_row: std::rc::Rc<dyn Fn(usize)>,
2325}
2326
2327/// Which edge of a row a swipe action rides (docs/list.md). Semantic, not geometric:
2328/// `Leading` follows the reading direction (the left edge in LTR, the right in RTL), the
2329/// mapping every platform's swipe API already makes.
2330#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2331pub enum SwipeEdge {
2332    Leading,
2333    Trailing,
2334}
2335
2336/// One offered swipe action (docs/list.md): pure data. The pieces layer keeps the handlers;
2337/// the backend answers a tap through [`ListSwipe::perform`] by index into the offer.
2338#[derive(Clone, Debug, PartialEq)]
2339pub struct ListSwipeAction {
2340    /// The word on the button, already localized (a toolkit cannot translate).
2341    pub label: String,
2342    /// Destructive styling: the platform's red.
2343    pub destructive: bool,
2344    /// Explicit button color; `None` = the platform's default for the style.
2345    pub tint: Option<Color>,
2346    /// A glyph for the button where the platform draws one: above the label on macOS, in
2347    /// place of it on iOS (docs/list.md).
2348    pub symbol: Option<Symbol>,
2349}
2350
2351/// The synchronous swipe-actions half of [`ListSource`] (docs/list.md), the generalized
2352/// sibling of [`ListDelete`]: reveal-as-you-swipe buttons on either row edge. The offer is
2353/// pulled per row at gesture time, so labels follow row state ("Mark Read" on an unread row,
2354/// "Mark Unread" on a read one); the commit defers to the event drain like every closure here.
2355#[derive(Clone)]
2356pub struct ListSwipe {
2357    /// The offer: the actions for row `index` on `edge`, called inside the platform's swipe
2358    /// callback, so keep it pure. Empty = no affordance for that row and edge. The first action
2359    /// is the full-swipe action where the platform activates one at the far edge.
2360    pub actions_at: std::rc::Rc<dyn Fn(usize, SwipeEdge) -> Vec<ListSwipeAction>>,
2361    /// The commit: the user activated action `action` (an index into the offer) on row
2362    /// `index`, `edge`. Unlike a delete this never reshapes the row snapshot; the app's
2363    /// handler is deferred to the next event drain, never run inside the native callback.
2364    pub perform: std::rc::Rc<dyn Fn(usize, SwipeEdge, usize)>,
2365}
2366
2367/// The synchronous row-pull closures for hierarchical trees (docs/tree.md): [`ListSource`]'s
2368/// shape, addressed by token instead of row index, because expanding a row renumbers every
2369/// index below it while tokens hold still. day-core injects one per `TREE` host via
2370/// [`Toolkit::attach_tree`]; the backend answers its native data-source from it. The same
2371/// synchronous discipline as [`ListSource`]: UI thread, outside any day-core borrow;
2372/// `bind_row` flushes and lays the row out before returning.
2373#[derive(Clone)]
2374pub struct TreeSource {
2375    /// How many children `parent` has (`None` = the root level).
2376    pub children_len: std::rc::Rc<dyn Fn(Option<u64>) -> usize>,
2377    /// The i-th child of `parent`: the stable token every backend keys its rows by.
2378    pub child_token: std::rc::Rc<dyn Fn(Option<u64>, usize) -> u64>,
2379    /// Whether this token can hold children at all: what draws (or omits) the disclosure.
2380    pub expandable: std::rc::Rc<dyn Fn(u64) -> bool>,
2381    /// Non-selectable section heading, separate from a navigation destination.
2382    pub section_header: std::rc::Rc<dyn Fn(u64) -> bool>,
2383    /// Current desired expansion, including restoration before the first native reload.
2384    pub expanded: std::rc::Rc<dyn Fn(u64) -> bool>,
2385    /// Build (first use of this cell) or rebind (recycled cell) the row for `token` into the
2386    /// native cell.
2387    pub bind_row: std::rc::Rc<dyn Fn(u64, RawHandle)>,
2388    /// The native cell left the viewport; Day may drop per-cell bookkeeping (optional).
2389    pub recycle: std::rc::Rc<dyn Fn(RawHandle)>,
2390    /// Re-lay the row bound to this cell at `width`, called from the cell's own native
2391    /// layout pass. Trees need this where lists don't: indentation makes every cell's
2392    /// content width per-row, so the host-width layout `bind_row` did is only a first
2393    /// approximation. Skips quietly when called inside a day-core borrow (a snapshot pass).
2394    pub layout_cell: std::rc::Rc<dyn Fn(RawHandle, f64)>,
2395    /// Native bounds for controls whose group headers have a different height from leaves.
2396    /// Overrides the initial row-height estimate and preserves the native height on rebind.
2397    pub layout_cell_size: std::rc::Rc<dyn Fn(RawHandle, Size)>,
2398    /// The height day-core last laid this cell's row at (see [`ListSource::cell_height`]).
2399    pub cell_height: std::rc::Rc<dyn Fn(RawHandle) -> f64>,
2400    /// The row's type-ahead string (docs/tree.md): what native type-select matches against.
2401    pub type_select_text: std::rc::Rc<dyn Fn(u64) -> String>,
2402    /// The row's context menu, built when the menu is summoned (docs/menus.md "Dynamic context
2403    /// menus"), called on the UI thread from the platform's own menu callback, outside any
2404    /// day-core borrow, like every closure here. `None` = rows carry no menu; an empty
2405    /// result suppresses the menu for that row.
2406    pub row_menu: Option<std::rc::Rc<dyn Fn(u64) -> Vec<MenuItem>>>,
2407    /// Drag-to-move closures, present when `TreeProps::movable` (docs/tree.md). `None` on
2408    /// immovable trees; backends must not enable their drag machinery without it.
2409    pub moves: Option<TreeMoves>,
2410}
2411
2412/// The synchronous drag half of [`TreeSource`] (docs/tree.md). Both closures follow
2413/// `bind_row`'s discipline: called on the UI thread from inside native drag callbacks.
2414#[derive(Clone)]
2415pub struct TreeMoves {
2416    /// The live verdict, consulted while the drag is over a target: may `token` land under
2417    /// `parent` at `index`? `index: None` means "dropped onto the parent" (append). Pure, since
2418    /// it runs inside the platform's drag-validate callback.
2419    #[allow(clippy::type_complexity)]
2420    pub can_move: std::rc::Rc<dyn Fn(u64, Option<u64>, Option<usize>) -> MoveVerdict>,
2421    /// Commit an accepted drop. Defers the app's `on_move` through the event queue
2422    /// ([`Event::TreeMove`]); the app's own data write drives the reload.
2423    #[allow(clippy::type_complexity)]
2424    pub move_node: std::rc::Rc<dyn Fn(u64, Option<u64>, Option<usize>)>,
2425}
2426
2427/// A summon-time context-menu provider (docs/menus.md): local-point in, menu out.
2428pub type ContextMenuFn = std::rc::Rc<dyn Fn(Point) -> Vec<MenuItem>>;
2429
2430/// Ask a menu button's provider for its menu at press time ([`Toolkit::set_button_menu`]), and
2431/// answer the items to show, or `None` to show nothing: an empty menu, or a provider that
2432/// removed its own button. The provider is app code; a signal it writes can rebuild the tree
2433/// synchronously and release the very button being pressed. `still_registered` asks the
2434/// toolkit's own registry, AFTER the provider has returned, whether the button is still the one
2435/// registered for this press; a toolkit holding a raw native handle must not touch it otherwise.
2436pub fn resolve_button_menu(
2437    provider: &ContextMenuFn,
2438    still_registered: impl FnOnce() -> bool,
2439) -> Option<Vec<MenuItem>> {
2440    let items = provider(Point::ZERO);
2441    if items.is_empty() || !still_registered() {
2442        return None;
2443    }
2444    Some(items)
2445}
2446
2447/// A tree move guard's verdict (docs/tree.md). No `Retarget` yet: the drop vocabulary is
2448/// already positional, so a guard that wants a different target denies and the user drops
2449/// where it is allowed.
2450#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2451pub enum MoveVerdict {
2452    Allow,
2453    Deny,
2454}
2455
2456/// One addressable widget within a composite native backing (docs/tree.md,
2457/// docs/tweaks.md), Qt's name for the concept (`QStyle::SubControl`). A `list`'s or
2458/// `tree`'s node handle is its scroller; `Subcontrol::Content` is the widget inside it.
2459/// Backends resolve an unknown subcontrol to `None`, never to the host.
2460#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
2461pub enum Subcontrol {
2462    /// The node's own handle: what every tweak accessor reached before subcontrols existed.
2463    Host,
2464    /// The content widget inside the scroller (`NSOutlineView`, `NSTableView`, …).
2465    Content,
2466    /// The header view, where the widget has one. Day's lists and trees ship headerless, so
2467    /// this answers `None` until a kind grows a header.
2468    Header,
2469}
2470
2471// ---------------------------------------------------------------------------
2472// Capabilities, animation, a11y
2473// ---------------------------------------------------------------------------
2474
2475/// What to show on the app's icon in the Dock, launcher, home screen, or taskbar (docs/badge.md).
2476///
2477/// Distinct from `NavItem::badge`, which annotates a sidebar row inside the window. This one
2478/// decorates the application itself and is drawn by the shell, not by Day.
2479///
2480/// What each payload needs is asked separately (`Cap::AppBadgeCount`, `AppBadgeText`,
2481/// `AppBadgeDot`) because the platforms differ in what they accept more than in whether they have
2482/// a badge at all: macOS takes arbitrary text, iOS and the web take a number, Android takes nothing.
2483#[derive(Clone, Debug, PartialEq, Eq, Default)]
2484pub enum AppBadge {
2485    /// Clear the badge.
2486    #[default]
2487    None,
2488    /// A count. Zero clears it, matching every platform's own convention.
2489    Count(u32),
2490    /// Short arbitrary text (`"99+"`, `"beta"`). Only macOS renders it; probe `Cap::AppBadgeText`.
2491    Text(String),
2492    /// An indicator with no value.
2493    Dot,
2494}
2495
2496/// How wide a window is, in coarse buckets (docs/size-classes.md).
2497///
2498/// The breakpoints are Android's window size classes, in density-independent points, and they are
2499/// used verbatim on every backend rather than per-platform. One table means one answer: a 700pt
2500/// window is [`WidthClass::Medium`] on a Mac, in a browser, and on a tablet, so an app that lays
2501/// out from the class gets the same layout at the same size everywhere. Apple publishes only two
2502/// buckets (compact/regular); those map onto this table rather than replacing it, with
2503/// [`WidthClass::Compact`] the compact one and everything above it regular.
2504#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug, Default)]
2505pub enum WidthClass {
2506    /// `< 600dp`: a phone in portrait. One pane at a time.
2507    #[default]
2508    Compact,
2509    /// `600–839dp`: a tablet in portrait, a narrow desktop window.
2510    Medium,
2511    /// `840–1199dp`: a tablet in landscape, a typical desktop window.
2512    Expanded,
2513    /// `1200–1599dp`: a large desktop window.
2514    Large,
2515    /// `≥ 1600dp`: a maximized window on a big display.
2516    ExtraLarge,
2517}
2518
2519/// How tall a window is (docs/size-classes.md). Consulted far less than [`WidthClass`]: it is
2520/// what tells a phone in landscape (wide enough for two panes, too short for a tall list) that
2521/// it should not grow vertical chrome.
2522#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug, Default)]
2523pub enum HeightClass {
2524    /// `< 480dp`: a phone in landscape.
2525    #[default]
2526    Compact,
2527    /// `480–899dp`: a phone in portrait, a tablet in landscape.
2528    Medium,
2529    /// `≥ 900dp`: a tablet in portrait, most desktop windows.
2530    Expanded,
2531}
2532
2533/// A window's size class (docs/size-classes.md), reported by the backend and read by apps
2534/// through `day::size_class()`.
2535///
2536/// Per-window, not per-app: two windows of one process can sit in different classes at the same
2537/// time (a narrow and a wide window side by side, iPadOS Stage Manager, Android split-screen), and
2538/// an app that keyed off a single global would lay the second window out for the first one's size.
2539#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
2540pub struct SizeClass {
2541    pub width: WidthClass,
2542    pub height: HeightClass,
2543}
2544
2545impl SizeClass {
2546    /// The `Compact`/`Medium` width boundary in dp: the narrowest window where a second
2547    /// pane starts to fit. Backends that hand an adaptive container its pane widths derive
2548    /// them from this (Android's list + minimum-detail widths sum to it), so the platform's
2549    /// measure-time decision and this table agree by construction (docs/size-classes.md).
2550    pub const SPLIT_MIN_WIDTH: f64 = 600.0;
2551
2552    /// Bucket a window's size in points. The one place the breakpoint numbers appear.
2553    #[must_use]
2554    pub fn from_size(width: f64, height: f64) -> Self {
2555        SizeClass {
2556            width: match width {
2557                w if w >= 1600.0 => WidthClass::ExtraLarge,
2558                w if w >= 1200.0 => WidthClass::Large,
2559                w if w >= 840.0 => WidthClass::Expanded,
2560                w if w >= Self::SPLIT_MIN_WIDTH => WidthClass::Medium,
2561                _ => WidthClass::Compact,
2562            },
2563            height: match height {
2564                h if h >= 900.0 => HeightClass::Expanded,
2565                h if h >= 480.0 => HeightClass::Medium,
2566                _ => HeightClass::Compact,
2567            },
2568        }
2569    }
2570
2571    /// Whether a two-pane presentation fits. The rule behind an automatic
2572    /// [`props::NavPresentation`]: anything wider than compact gets both panes.
2573    #[must_use]
2574    pub fn prefers_split(self) -> bool {
2575        self.width > WidthClass::Compact
2576    }
2577}
2578
2579#[derive(Clone, Copy, PartialEq, Eq, Debug)]
2580pub enum Cap {
2581    /// Standard searchfield control.
2582    SearchField,
2583    /// Standard combobox control.
2584    ComboBox,
2585    /// Standard stepper control.
2586    Stepper,
2587    /// Standard datetime control.
2588    DateTimePicker,
2589    /// Standard colorpicker control.
2590    ColorPicker,
2591    /// Standard pullrefresh control.
2592    PullRefresh,
2593    /// Standard pager control.
2594    Pager,
2595    /// User-driven pull recognition, separate from a refresh indicator.
2596    PullRefreshGesture,
2597
2598    /// Native data-transfer source and destination callbacks.
2599    DragDrop,
2600    /// Transfers between independent native applications (inbound).
2601    DragExternalImport,
2602    /// Transfers to independent native applications, including arbitrary binary MIME data.
2603    DragExternalExport,
2604    /// Lossless ordered items and alternatives between Day applications.
2605    DragMultipleItems,
2606    /// Existing native file references, distinct from promised/generated files.
2607    DragFileReferences,
2608    /// Native result can wait for asynchronous data receipt.
2609    DragDeferredReceipt,
2610    /// Generated files supplied to a destination after dropping.
2611    DragFilePromises,
2612    /// External move acknowledgment safe for source deletion.
2613    DragExternalMove,
2614    ListRecycling,
2615    /// The toolkit fronts the app's undo stack with the platform's own undo system
2616    /// ([`Toolkit::set_undo_state`] + `Event::Undo`): `Native` where one exists
2617    /// (`NSUndoManager` on macOS/iOS, `QUndoStack`), `Unsupported` everywhere else, where
2618    /// Day's menu items and accelerators drive the stack directly and nothing platform-owned
2619    /// needs mirroring (docs/model.md).
2620    UndoBridge,
2621    /// The toolkit routes the platform's standard Cut/Copy/Paste to the app's edit bridge
2622    /// ([`Toolkit::set_edit_state`] + `Event::Edit`): the same menu items, shortcuts, and
2623    /// responder precedence the platform's text editing uses; a focused text widget keeps
2624    /// its own clipboard behavior, everything else reaches the app (docs/menus.md).
2625    /// `Native` where a system route exists (the responder chain, the browser's clipboard
2626    /// events), `Emulated` where Day's own menu items dispatch it, `Unsupported` elsewhere.
2627    EditBridge,
2628    /// The toolkit realizes `ListProps::reorderable` as drag-to-reorder rows: `Native` when the
2629    /// platform's own mechanism drives it (`NSTableView` drag/drop, `UITableView` drag delegates,
2630    /// `ItemTouchHelper`, …), `Emulated` for a pointer-tracked fake (web-dom). `Unsupported` ⇒ the
2631    /// list renders normally but rows cannot be dragged (docs/list.md).
2632    ListReorder,
2633    /// Sidebar destinations can be dragged to reorder (`NavBuilder::reorder_items`) and between
2634    /// sections (`NavBuilder::regroup_items`). `Native` when the toolkit's own sidebar drags them
2635    /// (`NavMenuProps::movable`, and across headers under `NavMenuProps::regroup`); `Emulated`
2636    /// when Day stands a reorderable list in for the sidebar. Independent of `ListReorder`: UIKit
2637    /// supports draggable content lists but retains its native navigation collection for
2638    /// sidebars.
2639    NavReorder,
2640    /// The toolkit realizes `ListProps::deletable` as the platform's delete gesture:
2641    /// `Native` where the platform ships one (UIKit's trailing swipe actions, Android's
2642    /// `ItemTouchHelper`, ArkUI's `ListItem.swipeAction`), `Unsupported` on the desktop toolkits,
2643    /// whose lists have no swipe idiom and where deletion belongs to a menu or a button
2644    /// (docs/list.md).
2645    ListDelete,
2646    /// The toolkit realizes `ListProps::swipe_actions` as edge swipe actions: buttons
2647    /// that reveal as the row tracks the swipe, with the far edge activating the first one
2648    /// (docs/list.md). `Native` where the platform ships the affordance: macos-appkit
2649    /// (`NSTableView` row actions, Mail's own machinery) and ios-uikit
2650    /// (`UISwipeActionsConfiguration`). `Unsupported` everywhere else: the affordance is
2651    /// absent, and the app's command lives in its explicit controls.
2652    ListSwipeActions,
2653    /// The toolkit realizes `ListProps::editing` as the platform's list editing mode: rows
2654    /// show their delete controls and reorder grips while the list is editing (docs/list.md).
2655    /// `Native` on ios-uikit (`UITableView` editing). `Unsupported` everywhere else, where a
2656    /// list has no separate editing mode: its rows already drag, swipe and open menus as they
2657    /// are, and the list renders as if `editing` were off.
2658    ListEditing,
2659    /// The toolkit realizes `kinds::LIST_ITEM` as its own list row content (docs/list.md "List
2660    /// items"): `Native` where the platform has a standard row it draws itself (UIKit's
2661    /// `UIListContentConfiguration`, a Material list item, AppKit's image-and-text table cell,
2662    /// a GTK row box), so the row takes the platform's fonts, icon size, spacing, secondary
2663    /// colors and check mark. `Unsupported` ⇒ the `list_item` piece composes the same content
2664    /// from plain pieces. Apps have no reason to probe this; the piece does.
2665    ListItem,
2666    /// The toolkit realizes `kinds::TREE` as a hierarchical tree view (docs/tree.md):
2667    /// `Native` where a platform tree widget hosts Day-built rows (`NSOutlineView`, the UIKit
2668    /// sidebar list, GtkListView+TreeListModel, WinUI `TreeView`, ArkTS `TreeView`), `Emulated`
2669    /// where Day flattens the tree onto its list machinery, `Unsupported` where neither
2670    /// exists yet. An app gates its tree UI on this answer rather than showing a placeholder.
2671    Tree,
2672    /// The toolkit realizes `TreeProps::movable` as drag-to-reparent/restack rows
2673    /// (docs/tree.md). A strictly smaller set than [`Cap::Tree`]: a backend can render a
2674    /// tree it cannot yet drag within.
2675    TreeMove,
2676    /// Native two-level section headers; general trees may still be composed.
2677    TreeSections,
2678    /// The toolkit answers [`Toolkit::first_baseline`], so rows can align text on its baseline
2679    /// rather than on the middle of its box (docs/baseline.md). `Native` where the platform
2680    /// reports the baseline itself (`NSView.firstBaselineOffsetFromTop`, `View.getBaseline`,
2681    /// `gtk_widget_measure`), `Emulated` where Day derives it from the widget's font metrics,
2682    /// `Unsupported` ⇒ baseline-aligned rows fall back to centering and look exactly as they do
2683    /// today.
2684    BaselineAlignment,
2685    /// The toolkit draws a label's [`TextRun`]s: bold, italic, color or a monospace face within
2686    /// one wrapping paragraph (docs/text-runs.md). `Unsupported` ⇒ the label renders its text
2687    /// uniformly, which reads correctly and loses only the emphasis.
2688    TextRuns,
2689    /// The toolkit makes a run carrying [`TextRun::link`] activatable, emitting
2690    /// [`Event::LinkActivated`]. A strictly smaller set than [`Cap::TextRuns`]: several toolkits
2691    /// draw a link run in link colors but have no way to hit-test it, and one (Android) can do
2692    /// links or selection but not both (docs/text-runs.md).
2693    TextLinks,
2694    Lottie,
2695    NativeSymbols,
2696    /// The toolkit can rasterize its window and hand back the pixels
2697    /// (`Toolkit::snapshot_window`): what the dayscript `screenshot` step captures in-process
2698    /// and what `day::window_image()` offers the app (docs/window-image.md). `Unsupported` where
2699    /// a backend cannot draw itself into a bitmap: web-dom, which would need a rasterizer
2700    /// shipped with it. Probe it before offering a "save a screenshot" affordance, rather than
2701    /// offering one that fails when pressed.
2702    Snapshot,
2703    /// The toolkit can present `nav()` as sidebar+detail split panes, a statement about the
2704    /// toolkit, not about the window it is currently drawing. Whether a given host is split right
2705    /// now follows from its [`SizeClass`]: the pieces layer resolves an automatic
2706    /// [`props::NavPresentation`] against both, and re-resolves on every class change. A backend
2707    /// with no split container answers `Unsupported` and stays stacked at every size.
2708    NavSplit,
2709    /// The toolkit can draw a navigation host's rows as its own chrome: a tab bar
2710    /// ([`props::NavPresentation::Tabs`]) and, where it has one, a rail
2711    /// ([`props::NavPresentation::Rail`]). Like [`Self::NavSplit`] this is a statement about the
2712    /// toolkit, not about the window it is drawing right now.
2713    ///
2714    /// This is what `NavStyle::Automatic` resolves against (docs/navigation.md): a backend
2715    /// answering `Unsupported` gets the sidebar resolver instead (`Split` ↔ `Stack`), which is
2716    /// what every backend did before adaptive navigation existed. So an unimplemented backend
2717    /// degrades to its previous behavior rather than to a hole.
2718    ///
2719    /// `Emulated` means the rows are composed from other widgets rather than drawn by a native
2720    /// tab container (Qt, web-dom). `Native` means a real one (`UITabBarController`, a Material
2721    /// `NavigationBarView`, `NavigationView`).
2722    NavTabs,
2723    /// A narrow window should become a tab bar here, a separate question from [`Self::NavTabs`],
2724    /// which only says the toolkit *can* draw one.
2725    ///
2726    /// The two differ on every desktop. macOS, GNOME, Qt and Windows can all draw a tab bar, and
2727    /// must, because an app is free to pin `NavStyle::Tabs`; but none of them grows one when
2728    /// its window is dragged narrow. A narrow Mail.app hides its sidebar and pushes; it does not
2729    /// sprout a bottom tab bar, and an app that did would look like a port. The phones and the web
2730    /// are the opposite: those are the surfaces whose window size ranges from a phone to a
2731    /// desktop, and a tab bar is what their users expect at the narrow end.
2732    ///
2733    /// So this is a statement about the platform's idiom, not about its widget set:
2734    ///
2735    /// - `Native`/`Emulated`: `NavStyle::Automatic` may resolve to
2736    ///   [`props::NavPresentation::Tabs`] on a compact window (ios-uikit, android-material,
2737    ///   harmony-arkui, web-dom).
2738    /// - `Unsupported`: it may not; a compact window collapses to
2739    ///   [`props::NavPresentation::Stack`] instead, exactly as `NavStyle::Sidebar` has always
2740    ///   done (macos-appkit, linux-gtk, linux-qt, windows-winui).
2741    ///
2742    /// [`props::NavPresentation::Rail`] is not gated by this. A narrow sidebar is an ordinary
2743    /// desktop shape (on Windows it is what `NavigationView` does at that width on its own), so
2744    /// the rail rung stays available everywhere `Cap::NavSplit` is.
2745    NavTabsAdaptive,
2746    /// How a navigation host's presentation follows the window (docs/size-classes.md). All three
2747    /// answers mean something different here, and the difference is who decides:
2748    ///
2749    /// - `Native`: **Day tells the toolkit.** The pieces layer resolves the presentation from
2750    ///   the [`SizeClass`], re-resolves on every change, and sends
2751    ///   [`props::NavPatch::Presentation`]; the toolkit rebuilds its chrome and re-homes the
2752    ///   pages it already has. The desktops and web-dom.
2753    /// - `Emulated`: **the toolkit tells Day.** Its own adaptive container owns the decision
2754    ///   (`UISplitViewController` collapsing as a Pro Max iPhone rotates, `SlidingPaneLayout`
2755    ///   measuring whether both panes fit), so Day must not push a presentation into it: that
2756    ///   would be a second decision racing the platform's own animation. The toolkit
2757    ///   reports what it did with [`Event::NavPresentationChanged`] and Day reconciles.
2758    /// - `Unsupported`: nobody re-presents. The presentation is resolved once, from
2759    ///   [`Cap::NavSplit`] alone, and the window's size never enters into it. A toolkit that
2760    ///   cannot change presentation must not have it decided by something that can, or a window
2761    ///   launched narrow would be stuck stacked with no way back.
2762    NavRepresent,
2763    /// The toolkit places a navigation host's content-list page ([`props::Pane::List`]) in its
2764    /// own pane between the sidebar and the detail, the Mail shape: mailboxes, message list,
2765    /// message (docs/navigation.md). The three answers differ on what happens when the host
2766    /// leaves the split:
2767    ///
2768    /// - `Native`: the pane exists at every presentation. A narrow window collapses the
2769    ///   sidebar but keeps the list beside the detail, exactly as a narrow Mail.app does
2770    ///   (macos-appkit: a `contentList` `NSSplitViewItem`).
2771    /// - `Emulated`: the pane exists while split and merges into the navigation stack when
2772    ///   the host collapses (ios-uikit: `UISplitViewController` triple-column). The pieces
2773    ///   layer then interposes the list between the sidebar root and the detail
2774    ///   ([`props::NavPatch::ListInStack`]) and gates the detail push on the app's
2775    ///   `detail_visible` binding.
2776    /// - `Unsupported`: the backend never sees [`props::Pane::List`] or
2777    ///   [`props::NavProps::list_width`]; the nav piece composes the pane beside (split)
2778    ///   or in place of (stacked) the destination content itself.
2779    NavContentList,
2780    /// The toolkit shows the current destination's title in a native header/bar, so a page
2781    /// needn't repeat it in its own content. `Native` on XAML (the `NavigationView` header),
2782    /// UIKit (`UINavigationBar`), Android (`MaterialToolbar`), and ArkUI (`NavDestination`
2783    /// title bars). The desktop custom back-headers (AppKit/Qt/web) show a title only in
2784    /// stack mode, so those backends stay `Unsupported` (docs/navigation.md).
2785    NavHeader,
2786    /// The toolkit applies a runtime appearance override (`set_appearance`): native widgets
2787    /// restyle in place and `dark_mode` answers the override. Probe before showing a theme
2788    /// picker; on `Unsupported` backends the call is ignored.
2789    Appearance,
2790    /// The toolkit renders an application menu bar (docs/menus.md), so `app_menu` is visible to
2791    /// the user, and `register_preferences` gets its automatic Settings… item.
2792    ///
2793    /// The question an app asks before deciding where a command lives. Settings is the usual
2794    /// case: on a platform with a menu bar it belongs in the App menu and putting it in the
2795    /// navigation as well is clutter; on one without, the menu is a no-op and a Settings row is
2796    /// the only way in. Distinct from `Cap::Toolbar`: web-dom draws a window toolbar and has no
2797    /// menu bar at all, so keying off the toolbar strands Settings there.
2798    AppMenu,
2799    /// The toolkit can present native alert/confirm/sheet/prompt modals (docs/dialogs.md).
2800    Dialogs,
2801    /// The toolkit can present native open/save file pickers (docs/files.md).
2802    FileDialogs,
2803    /// The toolkit can present a native folder chooser (`PresentSpec::OpenFolder`,
2804    /// docs/files.md). `Native` on the four desktop toolkits (AppKit, GTK, Qt, WinUI); the
2805    /// phone and web backends answer `Unsupported` and resolve the request as `Dismissed`, so
2806    /// an app hides its "Add Folder…" command where this is not `Native`.
2807    FolderDialog,
2808    /// The toolkit runs backend-executed animation for `AnimSpec` intents on
2809    /// `update`/`set_frame`/`set_opacity`/`set_transform` (§8.4). `Unsupported` ⇒ animated calls
2810    /// apply instantly (still correct, just not animated).
2811    Animation,
2812    /// The toolkit presents a `kinds::COVER` node as a native fullscreen modal surface
2813    /// (docs/cover.md). `Unsupported` ⇒ the `cover` piece's content never shows.
2814    Cover,
2815    /// The toolkit presents a `.sheet()` cover as a native modal sheet (AppKit's window sheet,
2816    /// UIKit's page sheet) over the page it covers (docs/cover.md "Modal sheet"). `Unsupported`
2817    /// ⇒ the `cover` piece composes the sheet itself: on a window wider than compact, a card
2818    /// centered over the dimmed page; on a compact one, the full window.
2819    CoverSheet,
2820    /// The toolkit can hide the system status bar while a `status_bar_hidden` subtree is
2821    /// mounted (`Toolkit::set_status_bar_hidden`, docs/cover.md). `Native` on the phone and
2822    /// tablet backends; desktop and web have no status bar, so a setting that offers to hide
2823    /// it should be offered only where this is not `Unsupported`.
2824    StatusBarHidden,
2825    /// The toolkit's `text_area` can be made read-only (`TextAreaProps::editable = false`).
2826    TextEditable,
2827    /// The toolkit's `text_area` selectability can be toggled (`TextAreaProps::selectable`).
2828    /// `Unsupported` where selection is always on (GTK); `Emulated` where the backend
2829    /// collapses native selections itself (XAML, ArkUI).
2830    TextSelectable,
2831    /// The toolkit's `text_area` has built-in spell-check/autocorrect (`TextAreaProps::spellcheck`).
2832    /// `Unsupported` where the toolkit ships none (GTK, Qt, ArkUI).
2833    TextSpellCheck,
2834    /// The toolkit can open additional native OS windows (`Toolkit::open_window`,
2835    /// docs/windows.md). `Native` on the desktop backends and on mobile backends whose
2836    /// platform has a real secondary-window surface (iPad scenes, Android document
2837    /// activities, OHOS multiton abilities). On `Unsupported` backends
2838    /// `day_core::open_window` still works; the content presents as a fullscreen cover in
2839    /// the primary window instead. Probe it to adapt chrome: an `Unsupported` tier has no
2840    /// native title bar or close button, so window content should carry its own close
2841    /// affordance.
2842    MultiWindow,
2843    /// The toolkit can put a count on the app icon (`Toolkit::set_app_badge`, docs/badge.md).
2844    /// `Emulated` where the call is made but the shell may ignore it: desktop Linux, where the
2845    /// Unity launcher protocol is honored by Plasma and Dash-to-Dock but not by stock GNOME.
2846    AppBadgeCount,
2847    /// The toolkit renders `AppBadge::Text` as written. macOS only: `NSDockTile.badgeLabel` is an
2848    /// arbitrary string, while every other platform's badge is a number or nothing.
2849    AppBadgeText,
2850    /// The toolkit can show a valueless indicator (`AppBadge::Dot`).
2851    AppBadgeDot,
2852    /// The toolkit gives a window chrome that persists across pages
2853    /// (`Toolkit::edit_toolbar`, docs/toolbars.md): `Native` on the desktop backends and the
2854    /// phones, `Emulated` on web-dom, `Unsupported` where the only chrome belongs to a page.
2855    ///
2856    /// It no longer decides whether a command can be shown at all: a toolbar item declared on a
2857    /// piece rides that piece's own chrome everywhere. Probe it only for a layout decision that
2858    /// turns on a persistent bar existing.
2859    Toolbar,
2860    /// The window toolbar can hold a search field (docs/search.md): `Native` on the desktop
2861    /// backends, `Emulated` on web-dom. `Unsupported` on the phones, whose bar is a row of actions
2862    /// (an Android app-bar menu, iOS bar buttons, ArkUI title-bar menus): their field goes on the
2863    /// navigation surface instead, so `SearchPlacement::Toolbar` resolves to `Inline` there.
2864    ToolbarSearch,
2865    /// The toolkit realizes `kinds::INSPECTOR` as its own trailing-pane container
2866    /// (docs/inspector.md): an `NSSplitView` inspector pane, a `GtkPaned` with the panel as
2867    /// its end child, a `QDockWidget`, a XAML `SplitView` right pane. `Unsupported` ⇒ the
2868    /// `inspector` piece composes the pane from plain containers instead (same panel, same
2869    /// signal, no native divider), so an unimplemented backend degrades to a drawn pane, not
2870    /// to a hole. Apps normally have no reason to probe this; the piece does.
2871    Inspector,
2872    /// The toolkit realizes `kinds::SPLIT` as its own splitter (docs/split.md): an
2873    /// `NSSplitView`, a `GtkPaned`, a `QSplitter`, each side by side or stacked and with the
2874    /// divider the user drags. `Unsupported` ⇒ the `split` piece composes the two panes and
2875    /// draws and drags the divider itself (the web, the mobile toolkits, XAML), so the piece
2876    /// behaves the same everywhere and only the divider's look is the toolkit's. Apps have no
2877    /// reason to probe this; the piece does.
2878    Split,
2879    /// The toolkit shapes the pointer over a node from the `.cursor()` decorator
2880    /// ([`Toolkit::set_cursor`], docs/cursor.md). `Native` where the platform draws the requested
2881    /// shape from its own set (AppKit, GTK, the DOM, Android's `PointerIcon`), `Emulated` where
2882    /// some shapes map to a nearest neighbor (Qt, XAML) or the platform draws pointer effects
2883    /// rather than shapes (iPadOS), `Unsupported` where nothing changes: a touch-only toolkit,
2884    /// or one whose pointer API Day does not reach yet. Apps ask before offering an affordance
2885    /// that only a cursor reveals, such as a resize handle with no other visual.
2886    Cursor,
2887    /// The toolkit can enumerate the platform's font families with the faces each ships
2888    /// ([`Toolkit::font_families`], docs/fonts.md). `Native` where an OS font database answers
2889    /// (`NSFontManager`, `UIFont`, Pango, `QFontDatabase`, Android's `fonts.xml`,
2890    /// `OH_Drawing_FontMgr`, DirectWrite); `Emulated` where the list is composed rather than
2891    /// read: web-dom answers the CSS generic families plus the bundled `document.fonts`, since
2892    /// a browser exposes no local font list without a permission prompt; `Unsupported` means
2893    /// the list is empty and an app should offer only the default face. Measurement
2894    /// ([`Toolkit::measure_text`]) has no probe: a `None` answer degrades to
2895    /// [`TextMetrics::approximate`]. Probe this before offering a font menu, not before
2896    /// drawing; a [`CanvasFont`] draws everywhere.
2897    FontList,
2898    /// The toolkit reads the user's reduce-motion setting ([`Toolkit::reduce_motion`],
2899    /// docs/accessibility.md) and reports when it changes. `Native` where the platform has the
2900    /// switch and Day reaches it; `Unsupported` where Day reaches none (the app then animates as
2901    /// it would with the setting off, and `DAY_REDUCE_MOTION=1` still forces it on).
2902    ReduceMotion,
2903    /// The toolkit can speak a sentence through the screen reader without moving its focus
2904    /// ([`Toolkit::announce`], docs/accessibility.md): "Saved", "3 results", "Upload failed".
2905    /// `Native` where the platform has an announcement request (`NSAccessibility`'s
2906    /// announcement notification, `UIAccessibility`'s, Android's accessibility event, GTK
2907    /// 4.14's `gtk_accessible_announce`, a WinUI notification event); `Emulated` on the web,
2908    /// where an ARIA live region carries it; `Unsupported` where Day reaches no announcement
2909    /// API yet. An app with a visible status label needs no announcement: screen readers read
2910    /// what changes on screen only when told to, so this is for the change the user cannot
2911    /// otherwise learn about.
2912    Announce,
2913    /// The toolkit can turn encoded image bytes into a native image
2914    /// ([`Toolkit::decode_image`], docs/images.md): what `image(bytes)`, a pasted screenshot and
2915    /// a canvas image all rest on. `Native` wherever the platform decoder takes a buffer;
2916    /// `Unsupported` means only staged asset names draw, so an app should not offer "open an
2917    /// image" at all. Every backend that decodes also answers [`Toolkit::image_info`], so pixel
2918    /// size needs no probe of its own.
2919    ImageDecode,
2920    /// The toolkit can encode a decoded image back to bytes ([`Toolkit::encode_image`]).
2921    /// Which formats it encodes is [`Toolkit::encode_formats`], the same shape as
2922    /// [`Cap::FontList`]/[`Toolkit::font_families`], because "can encode" and "can encode WebP"
2923    /// are different questions and only the second one needs a list.
2924    ImageEncode,
2925    /// The toolkit can read an image's metadata beyond its pixels: EXIF orientation, DPI,
2926    /// capture time ([`Toolkit::image_properties`]). `Native` where a platform metadata reader
2927    /// is already linked (WinRT's `BitmapPropertiesView`, Android's `ExifInterface`);
2928    /// `Unsupported` where reading it would mean shipping a parser or a new framework, which is
2929    /// most places. An app that wants orientation must handle `None`.
2930    ImageProperties,
2931    /// The toolkit can replay a canvas drawing into an offscreen bitmap
2932    /// ([`Toolkit::render_bitmap`], docs/canvas.md "Exporting"): what `Drawing::to_bitmap` and
2933    /// `Drawing::to_png` rest on. `Native` where the toolkit's own canvas painter can target an
2934    /// image surface (a `CGBitmapContext`, a cairo image surface, a `QImage`, an android
2935    /// `Bitmap`, an `OH_Drawing_Bitmap`, a detached `<canvas>`); `Unsupported` where the
2936    /// on-screen canvas has no painter to retarget (WinUI builds XAML shapes instead).
2937    CanvasBitmap,
2938    /// The toolkit can replay canvas drawings into a PDF document ([`Toolkit::render_pdf`],
2939    /// docs/canvas.md "Exporting"), with vector shapes and the platform's own font embedding.
2940    /// `Native` only where the platform ships a PDF writer the canvas painter can draw into
2941    /// (Core Graphics on AppKit and UIKit, cairo on GTK, `QPdfWriter` on Qt, `PdfDocument` on
2942    /// Android); `Unsupported` on ArkUI, the web and WinUI, which have none.
2943    CanvasPdf,
2944    /// The toolkit minimizes, zooms, hides and restores a window on request
2945    /// ([`WindowChange::State`], [`WindowChange::Visible`], docs/windows.md) and reports what the
2946    /// user does through [`Event::WindowStateChanged`]. `Native` on the desktop backends;
2947    /// `Unsupported` on the phones and the web, whose windows the OS sizes.
2948    WindowStates,
2949    /// The toolkit takes a window fullscreen on request and reports when it enters and leaves
2950    /// ([`WindowState::Fullscreen`]). `Native` on the desktops, on Android (system bars hidden
2951    /// through `WindowInsetsController`), on HarmonyOS and on the web (the Fullscreen API, which
2952    /// browsers allow only during a user gesture); `Emulated` on iOS, which hides the status bar
2953    /// and lets the home indicator fade but always keeps the app full-screen anyway.
2954    WindowFullscreen,
2955    /// The toolkit keeps a window out of screenshots, recordings and screen sharing
2956    /// ([`WindowChange::ContentProtected`]). `Native` on macOS (`NSWindowSharingNone`), Windows
2957    /// (`WDA_EXCLUDEFROMCAPTURE`), Android (`FLAG_SECURE`) and HarmonyOS (privacy mode);
2958    /// `Emulated` on iOS, which has no switch for it: Day covers the content while the screen is
2959    /// being recorded or mirrored, but a screenshot still captures it. `Unsupported` on Linux
2960    /// and the web.
2961    ContentProtection,
2962    /// The toolkit honors [`WindowOptions::tabbing`]: macOS window tabs. `Unsupported` everywhere
2963    /// else, where no system window tabs exist.
2964    WindowTabbing,
2965    /// The toolkit shows a Dock menu ([`Toolkit::set_dock_menu`], docs/menus.md): the app's
2966    /// shortcuts and `dock_menu(..)` entries above the system's own items. macOS only.
2967    DockMenu,
2968    /// The toolkit resizes a window and bounds its size on request ([`WindowChange::Frame`]'s
2969    /// size, [`WindowChange::Limits`], [`WindowChange::Resizable`]).
2970    WindowGeometry,
2971    /// The toolkit moves a window to a requested position ([`WindowChange::Frame`]'s origin).
2972    /// `Unsupported` on GTK 4, which removed window positioning, and wherever the compositor owns
2973    /// placement (Wayland).
2974    WindowPosition,
2975    /// The toolkit changes how a window stacks ([`WindowChange::Level`],
2976    /// [`WindowChange::OnAllWorkspaces`], [`WindowChange::SkipTaskbar`]).
2977    WindowLevel,
2978    /// The toolkit gives one window its own light/dark appearance ([`WindowChange::Appearance`]).
2979    /// Where it cannot, the app-wide [`Toolkit::set_appearance`] still applies to every window.
2980    WindowAppearance,
2981    /// The toolkit asks for the user's attention on request ([`WindowChange::RequestAttention`]):
2982    /// a Dock bounce, a flashing taskbar button.
2983    RequestAttention,
2984    /// The toolkit opens a window with no title bar or frame ([`WindowChrome::Frameless`],
2985    /// docs/window-chrome.md). Desktop backends only.
2986    FramelessWindow,
2987    /// The toolkit runs a window's content under its title bar with the window controls kept
2988    /// ([`WindowChrome::Overlay`]) and reports the bar's height as the safe-area top inset.
2989    OverlayTitleBar,
2990    /// The toolkit opens a window whose unpainted pixels show the desktop
2991    /// ([`WindowBackground::Transparent`]).
2992    TransparentWindow,
2993    /// The toolkit puts a translucent system material behind a window
2994    /// ([`WindowBackground::Material`]): macOS's visual-effect materials, Windows 11's Mica and
2995    /// Acrylic. `Emulated` where an approximation stands in.
2996    WindowMaterial,
2997    /// The toolkit lets a piece move its window like a title bar does
2998    /// ([`Toolkit::set_drag_region`], `.window_drag_region()`). `Emulated` on the web, where
2999    /// only an installed app with a window-controls overlay honors it.
3000    DragRegion,
3001    /// The toolkit shows status items ([`Toolkit::set_status_items`], docs/status-item.md): the
3002    /// macOS menu bar, the Windows notification area, a Linux tray. On Linux the answer depends
3003    /// on the desktop: `Native` while a `StatusNotifierItem` host is running (KDE Plasma, most
3004    /// panels, GNOME with the AppIndicator extension), `Unsupported` without one (stock GNOME),
3005    /// so an app can keep a window instead of vanishing into a tray nobody shows.
3006    StatusItem,
3007    /// The toolkit shows progress on the app's Dock or taskbar icon
3008    /// ([`Toolkit::set_app_progress`]). `Emulated` on Linux, where the Unity launcher protocol is
3009    /// honored by KDE Plasma and Dash to Dock but not by every dock.
3010    AppProgress,
3011    /// The toolkit can hide the app's Dock icon while it runs ([`Toolkit::set_dock_visible`]).
3012    /// macOS only.
3013    DockVisibility,
3014    /// The toolkit lists the displays and their work areas ([`Toolkit::monitors`]). `Emulated`
3015    /// where the one screen the app runs on is reported (a phone, the web).
3016    Monitors,
3017    /// The toolkit shows launcher shortcuts the app sets while it runs
3018    /// ([`Toolkit::set_launcher_shortcuts`]).
3019    DynamicShortcuts,
3020    /// How the toolkit draws a sectioned list's headers (`ListProps::sections`, docs/list.md
3021    /// "Sections"). `Native` where the platform's list has group headers that pin to the top
3022    /// while their section scrolls under them: macos-appkit (`NSTableView` group rows with
3023    /// `floatsGroupRows`) and ios-uikit (plain-style `UITableView` section headers).
3024    /// `Emulated` where the host pins a copy of the current header over the top of the list
3025    /// itself. Headers are unselectable rows on every toolkit, so an app needs this only to
3026    /// describe the difference, never to decide whether to call `.sections`.
3027    ListSections,
3028    /// The toolkit's share chooser carries the app's own actions ([`share::ShareSpec::actions`],
3029    /// docs/sharing.md): Add Bookmark or Find on Page beside the system's targets, each with
3030    /// its title and glyph. `Native` on ios-uikit (a `UIActivity` per action), macos-appkit (an
3031    /// `NSSharingService` per action, offered by the picker's delegate) and android-material
3032    /// on Android 14 and later (`ChooserAction`). `Unsupported` everywhere else: the chooser
3033    /// shows the system's targets only, and the app offers its actions in its own menu.
3034    ShareActions,
3035}
3036
3037impl Cap {
3038    /// Every capability, in declaration order: what a conformance run asks the toolkit about,
3039    /// so the evidence can be held against the declared coverage matrix (docs/testing.md).
3040    pub const ALL: [Cap; 91] = [
3041        Cap::DragDrop,
3042        Cap::DragExternalImport,
3043        Cap::DragExternalExport,
3044        Cap::DragMultipleItems,
3045        Cap::DragFileReferences,
3046        Cap::DragDeferredReceipt,
3047        Cap::DragFilePromises,
3048        Cap::DragExternalMove,
3049        Cap::ListRecycling,
3050        Cap::UndoBridge,
3051        Cap::EditBridge,
3052        Cap::ListReorder,
3053        Cap::NavReorder,
3054        Cap::ListDelete,
3055        Cap::ListSwipeActions,
3056        Cap::Tree,
3057        Cap::TreeMove,
3058        Cap::BaselineAlignment,
3059        Cap::TextRuns,
3060        Cap::TextLinks,
3061        Cap::Lottie,
3062        Cap::NativeSymbols,
3063        Cap::Snapshot,
3064        Cap::NavSplit,
3065        Cap::NavTabs,
3066        Cap::NavTabsAdaptive,
3067        Cap::NavRepresent,
3068        Cap::NavContentList,
3069        Cap::NavHeader,
3070        Cap::Appearance,
3071        Cap::AppMenu,
3072        Cap::Dialogs,
3073        Cap::FileDialogs,
3074        Cap::Animation,
3075        Cap::Cover,
3076        Cap::StatusBarHidden,
3077        Cap::TextEditable,
3078        Cap::TextSelectable,
3079        Cap::TextSpellCheck,
3080        Cap::MultiWindow,
3081        Cap::AppBadgeCount,
3082        Cap::AppBadgeText,
3083        Cap::AppBadgeDot,
3084        Cap::Toolbar,
3085        Cap::ToolbarSearch,
3086        Cap::Inspector,
3087        Cap::Cursor,
3088        Cap::FontList,
3089        Cap::ReduceMotion,
3090        Cap::Announce,
3091        Cap::ImageDecode,
3092        Cap::ImageEncode,
3093        Cap::ImageProperties,
3094        Cap::WindowStates,
3095        Cap::WindowFullscreen,
3096        Cap::ContentProtection,
3097        Cap::WindowTabbing,
3098        Cap::DockMenu,
3099        Cap::WindowGeometry,
3100        Cap::WindowPosition,
3101        Cap::WindowLevel,
3102        Cap::WindowAppearance,
3103        Cap::RequestAttention,
3104        Cap::FramelessWindow,
3105        Cap::OverlayTitleBar,
3106        Cap::TransparentWindow,
3107        Cap::WindowMaterial,
3108        Cap::DragRegion,
3109        Cap::StatusItem,
3110        Cap::AppProgress,
3111        Cap::DockVisibility,
3112        Cap::Monitors,
3113        Cap::DynamicShortcuts,
3114        Cap::Split,
3115        Cap::TreeSections,
3116        Cap::CoverSheet,
3117        Cap::ListEditing,
3118        Cap::ListItem,
3119        Cap::CanvasBitmap,
3120        Cap::CanvasPdf,
3121        Cap::SearchField,
3122        Cap::ComboBox,
3123        Cap::Stepper,
3124        Cap::DateTimePicker,
3125        Cap::ColorPicker,
3126        Cap::PullRefresh,
3127        Cap::Pager,
3128        Cap::PullRefreshGesture,
3129        Cap::FolderDialog,
3130        Cap::ListSections,
3131        Cap::ShareActions,
3132    ];
3133
3134    /// The capability's place in [`Cap::ALL`]. Exhaustive, so a new variant fails to compile
3135    /// here until it is given one, and the unit test below then holds `ALL` to it.
3136    #[must_use]
3137    pub const fn ordinal(self) -> usize {
3138        match self {
3139            Cap::DragDrop => 0,
3140            Cap::DragExternalImport => 1,
3141            Cap::DragExternalExport => 2,
3142            Cap::DragMultipleItems => 3,
3143            Cap::DragFileReferences => 4,
3144            Cap::DragDeferredReceipt => 5,
3145            Cap::DragFilePromises => 6,
3146            Cap::DragExternalMove => 7,
3147            Cap::ListRecycling => 8,
3148            Cap::UndoBridge => 9,
3149            Cap::EditBridge => 10,
3150            Cap::ListReorder => 11,
3151            Cap::NavReorder => 12,
3152            Cap::ListDelete => 13,
3153            Cap::ListSwipeActions => 14,
3154            Cap::Tree => 15,
3155            Cap::TreeMove => 16,
3156            Cap::BaselineAlignment => 17,
3157            Cap::TextRuns => 18,
3158            Cap::TextLinks => 19,
3159            Cap::Lottie => 20,
3160            Cap::NativeSymbols => 21,
3161            Cap::Snapshot => 22,
3162            Cap::NavSplit => 23,
3163            Cap::NavTabs => 24,
3164            Cap::NavTabsAdaptive => 25,
3165            Cap::NavRepresent => 26,
3166            Cap::NavContentList => 27,
3167            Cap::NavHeader => 28,
3168            Cap::Appearance => 29,
3169            Cap::AppMenu => 30,
3170            Cap::Dialogs => 31,
3171            Cap::FileDialogs => 32,
3172            Cap::Animation => 33,
3173            Cap::Cover => 34,
3174            Cap::StatusBarHidden => 35,
3175            Cap::TextEditable => 36,
3176            Cap::TextSelectable => 37,
3177            Cap::TextSpellCheck => 38,
3178            Cap::MultiWindow => 39,
3179            Cap::AppBadgeCount => 40,
3180            Cap::AppBadgeText => 41,
3181            Cap::AppBadgeDot => 42,
3182            Cap::Toolbar => 43,
3183            Cap::ToolbarSearch => 44,
3184            Cap::Inspector => 45,
3185            Cap::Cursor => 46,
3186            Cap::FontList => 47,
3187            Cap::ReduceMotion => 48,
3188            Cap::Announce => 49,
3189            Cap::ImageDecode => 50,
3190            Cap::ImageEncode => 51,
3191            Cap::ImageProperties => 52,
3192            Cap::WindowStates => 53,
3193            Cap::WindowFullscreen => 54,
3194            Cap::ContentProtection => 55,
3195            Cap::WindowTabbing => 56,
3196            Cap::DockMenu => 57,
3197            Cap::WindowGeometry => 58,
3198            Cap::WindowPosition => 59,
3199            Cap::WindowLevel => 60,
3200            Cap::WindowAppearance => 61,
3201            Cap::RequestAttention => 62,
3202            Cap::FramelessWindow => 63,
3203            Cap::OverlayTitleBar => 64,
3204            Cap::TransparentWindow => 65,
3205            Cap::WindowMaterial => 66,
3206            Cap::DragRegion => 67,
3207            Cap::StatusItem => 68,
3208            Cap::AppProgress => 69,
3209            Cap::DockVisibility => 70,
3210            Cap::Monitors => 71,
3211            Cap::DynamicShortcuts => 72,
3212            Cap::Split => 73,
3213            Cap::TreeSections => 74,
3214            Cap::CoverSheet => 75,
3215            Cap::ListEditing => 76,
3216            Cap::ListItem => 77,
3217            Cap::CanvasBitmap => 78,
3218            Cap::CanvasPdf => 79,
3219            Cap::SearchField => 80,
3220            Cap::ComboBox => 81,
3221            Cap::Stepper => 82,
3222            Cap::DateTimePicker => 83,
3223            Cap::ColorPicker => 84,
3224            Cap::PullRefresh => 85,
3225            Cap::Pager => 86,
3226            Cap::PullRefreshGesture => 87,
3227            Cap::FolderDialog => 88,
3228            Cap::ListSections => 89,
3229            Cap::ShareActions => 90,
3230        }
3231    }
3232}
3233
3234// ---------------------------------------------------------------------------
3235// Raster images (docs/images.md): the currency shared by the `image` piece, the canvas, and
3236// the decode/metadata/encode duties below.
3237// ---------------------------------------------------------------------------
3238
3239/// A decoded image the toolkit holds, addressed by an id day-core mints.
3240///
3241/// Opaque, because what sits behind it is an `NSImage`, a `UIImage`, a `GdkTexture`, a
3242/// `QPixmap`, a `BitmapImage`, an android `Bitmap` or an `ImageBitmap`, and none of those cross
3243/// the boundary. The id is released through [`Toolkit::release_image`] when the app's handle
3244/// drops, so a backend's side table never outlives the app's interest in it.
3245#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
3246pub struct BitmapId(pub u64);
3247
3248/// An encoded image format: what [`BitmapInfo::format`] reports and [`EncodeSpec::format`] asks
3249/// for. Not every backend encodes every one: ask [`Toolkit::encode_formats`] (the
3250/// [`Cap::ImageEncode`] pair of [`Toolkit::font_families`]/[`Cap::FontList`]) rather than
3251/// assuming.
3252#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default)]
3253pub enum ImageFormat {
3254    #[default]
3255    Png,
3256    Jpeg,
3257    Webp,
3258    Gif,
3259    Bmp,
3260    Tiff,
3261    /// HEIF/HEIC, Apple's camera format; decodable on the Apple backends and Android, and
3262    /// encodable almost nowhere.
3263    Heif,
3264    /// Decoded from bytes whose magic numbers [`ImageFormat::sniff`] does not know. A backend may
3265    /// still decode it: the platform decoders read more formats than Day names.
3266    Unknown,
3267}
3268
3269impl ImageFormat {
3270    /// The IANA media type, which is also the string the ArkUI packer, GDI+ and the browser's
3271    /// `toBlob` take. `Unknown` answers `application/octet-stream`.
3272    #[must_use]
3273    pub fn mime(self) -> &'static str {
3274        match self {
3275            ImageFormat::Png => "image/png",
3276            ImageFormat::Jpeg => "image/jpeg",
3277            ImageFormat::Webp => "image/webp",
3278            ImageFormat::Gif => "image/gif",
3279            ImageFormat::Bmp => "image/bmp",
3280            ImageFormat::Tiff => "image/tiff",
3281            ImageFormat::Heif => "image/heif",
3282            ImageFormat::Unknown => "application/octet-stream",
3283        }
3284    }
3285
3286    /// The pixel size the encoded bytes declare, read from the container's own header
3287    /// (docs/images.md).
3288    ///
3289    /// Every backend that decodes natively reports its own dimensions; this exists for the one
3290    /// that cannot. The XAML backend's (`windows-winui`) `BitmapImage` learns its size
3291    /// asynchronously, only once the element has been shown, so a synchronous `image_info` there
3292    /// would have nothing to say.
3293    /// Reading the header instead gives the same answer the decoder would, before any decoding.
3294    ///
3295    /// `None` when the header is absent, truncated, or a container this does not parse.
3296    #[must_use]
3297    pub fn dimensions(bytes: &[u8]) -> Option<(u32, u32)> {
3298        let be16 = |i: usize| -> Option<u32> {
3299            Some(u32::from(u16::from_be_bytes([
3300                *bytes.get(i)?,
3301                *bytes.get(i + 1)?,
3302            ])))
3303        };
3304        let le16 = |i: usize| -> Option<u32> {
3305            Some(u32::from(u16::from_le_bytes([
3306                *bytes.get(i)?,
3307                *bytes.get(i + 1)?,
3308            ])))
3309        };
3310        let be32 = |i: usize| -> Option<u32> {
3311            Some(u32::from_be_bytes([
3312                *bytes.get(i)?,
3313                *bytes.get(i + 1)?,
3314                *bytes.get(i + 2)?,
3315                *bytes.get(i + 3)?,
3316            ]))
3317        };
3318        let le32 = |i: usize| -> Option<u32> {
3319            Some(u32::from_le_bytes([
3320                *bytes.get(i)?,
3321                *bytes.get(i + 1)?,
3322                *bytes.get(i + 2)?,
3323                *bytes.get(i + 3)?,
3324            ]))
3325        };
3326        match Self::sniff(bytes)? {
3327            // IHDR is always the first chunk: 8-byte signature, 4-byte length, 4-byte type.
3328            ImageFormat::Png => Some((be32(16)?, be32(20)?)),
3329            // The logical screen descriptor follows the 6-byte version stamp, little-endian.
3330            ImageFormat::Gif => Some((le16(6)?, le16(8)?)),
3331            // The DIB header's width/height are signed; a negative height is a top-down bitmap.
3332            ImageFormat::Bmp => Some((
3333                le32(18)?.cast_signed().unsigned_abs(),
3334                le32(22)?.cast_signed().unsigned_abs(),
3335            )),
3336            // Walk the segment chain to the frame header. Every SOF marker carries the size at
3337            // the same offsets; the arithmetic-coded and progressive ones are SOFs too, which is
3338            // why this matches the whole range rather than SOF0 alone. DNL/DHP (0xC4, 0xC8,
3339            // 0xCC) are not frame headers and are skipped like any other segment.
3340            ImageFormat::Jpeg => {
3341                let mut i = 2usize;
3342                // `<=`, not `<`: a frame header that ends the buffer is still a frame header, and
3343                // the size sits in its last four bytes.
3344                while i + 9 <= bytes.len() {
3345                    if bytes[i] != 0xFF {
3346                        i += 1;
3347                        continue;
3348                    }
3349                    let marker = bytes[i + 1];
3350                    // Padding fill bytes and the standalone markers carry no length.
3351                    if marker == 0xFF || (0xD0..=0xD9).contains(&marker) || marker == 0x01 {
3352                        i += 1;
3353                        continue;
3354                    }
3355                    let is_sof = (0xC0..=0xCF).contains(&marker)
3356                        && marker != 0xC4
3357                        && marker != 0xC8
3358                        && marker != 0xCC;
3359                    if is_sof {
3360                        // [marker][len:2][precision:1][height:2][width:2]
3361                        return Some((be16(i + 7)?, be16(i + 5)?));
3362                    }
3363                    i += 2 + be16(i + 2)? as usize;
3364                }
3365                None
3366            }
3367            // RIFF: a 12-byte header, then a chunk id. VP8X states the size minus one in 24-bit
3368            // little-endian; lossy VP8 hides it in the 14 low bits after the start code; lossless
3369            // VP8L packs width-1 and height-1 into 14 bits each across four bytes.
3370            ImageFormat::Webp => match bytes.get(12..16)? {
3371                b"VP8X" => {
3372                    let w = u32::from(*bytes.get(24)?)
3373                        | u32::from(*bytes.get(25)?) << 8
3374                        | u32::from(*bytes.get(26)?) << 16;
3375                    let h = u32::from(*bytes.get(27)?)
3376                        | u32::from(*bytes.get(28)?) << 8
3377                        | u32::from(*bytes.get(29)?) << 16;
3378                    Some((w + 1, h + 1))
3379                }
3380                b"VP8 " => Some((le16(26)? & 0x3FFF, le16(28)? & 0x3FFF)),
3381                b"VP8L" => {
3382                    let bits = le32(21)?;
3383                    Some(((bits & 0x3FFF) + 1, ((bits >> 14) & 0x3FFF) + 1))
3384                }
3385                _ => None,
3386            },
3387            // TIFF's IFD is a pointer chase and HEIF's is a box tree; neither is worth parsing
3388            // here, because every backend that reads them decodes natively and answers for itself.
3389            ImageFormat::Tiff | ImageFormat::Heif | ImageFormat::Unknown => None,
3390        }
3391    }
3392
3393    /// The format `bytes` begins with, by magic number: enough to fill [`BitmapInfo::format`]
3394    /// on every backend, including the ones whose decoder never says what it decoded.
3395    ///
3396    /// Hand-rolled rather than a crate: it is a dozen byte comparisons against fixed prefixes,
3397    /// and the alternative is an image-decoding dependency in the one crate that must stay
3398    /// dependency-free.
3399    #[must_use]
3400    pub fn sniff(bytes: &[u8]) -> Option<ImageFormat> {
3401        let starts = |sig: &[u8]| bytes.len() >= sig.len() && &bytes[..sig.len()] == sig;
3402        if starts(&[0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a]) {
3403            return Some(ImageFormat::Png);
3404        }
3405        if starts(&[0xff, 0xd8, 0xff]) {
3406            return Some(ImageFormat::Jpeg);
3407        }
3408        if starts(b"GIF87a") || starts(b"GIF89a") {
3409            return Some(ImageFormat::Gif);
3410        }
3411        if starts(b"BM") {
3412            return Some(ImageFormat::Bmp);
3413        }
3414        if starts(&[0x49, 0x49, 0x2a, 0x00]) || starts(&[0x4d, 0x4d, 0x00, 0x2a]) {
3415            return Some(ImageFormat::Tiff);
3416        }
3417        // RIFF....WEBP and ....ftypheic/heix/mif1 both carry their tag past a 4-byte prefix.
3418        if starts(b"RIFF") && bytes.len() >= 12 && &bytes[8..12] == b"WEBP" {
3419            return Some(ImageFormat::Webp);
3420        }
3421        if bytes.len() >= 12 && &bytes[4..8] == b"ftyp" {
3422            let brand = &bytes[8..12];
3423            if brand == b"heic" || brand == b"heix" || brand == b"mif1" || brand == b"msf1" {
3424                return Some(ImageFormat::Heif);
3425            }
3426        }
3427        None
3428    }
3429}
3430
3431/// What a decoded image is, in the terms every backend can answer
3432/// ([`Toolkit::image_info`], docs/images.md).
3433///
3434/// `pixels` is the image's own pixel size, not the points it draws at: an asset that stages at
3435/// 2× reports twice its point size and a `scale` of 2, so an app sizing a frame divides. Bytes
3436/// carry no density, so a decoded buffer always answers `scale: 1.0`.
3437#[derive(Clone, Copy, Debug, Default, PartialEq)]
3438pub struct BitmapInfo {
3439    pub pixels: Size,
3440    /// Pixels per point (1.0 for decoded bytes; 2 or 3 for a catalog/drawable asset that staged
3441    /// a density variant).
3442    pub scale: f64,
3443    /// The encoded format it came from, where the backend knows or [`ImageFormat::sniff`] said.
3444    pub format: Option<ImageFormat>,
3445    pub has_alpha: bool,
3446}
3447
3448/// What [`Toolkit::encode_image`] should produce (docs/images.md).
3449///
3450/// A struct rather than three positional arguments, per docs/api-style.md: the call site reads
3451/// `EncodeSpec { format: ImageFormat::Jpeg, quality: Some(0.8), ..Default::default() }`.
3452#[derive(Clone, Copy, Debug, PartialEq)]
3453pub struct EncodeSpec {
3454    pub format: ImageFormat,
3455    /// Lossy quality in `0.0..=1.0`. `None` takes the platform's default; a lossless format
3456    /// ignores it.
3457    pub quality: Option<f64>,
3458    /// Scale the longest side down to fit this box first (aspect preserved). `None` encodes at
3459    /// the image's own size.
3460    pub fit: Option<Size>,
3461}
3462
3463impl Default for EncodeSpec {
3464    fn default() -> Self {
3465        EncodeSpec {
3466            format: ImageFormat::Png,
3467            quality: None,
3468            fit: None,
3469        }
3470    }
3471}
3472
3473/// The metadata an image file carries beyond its pixels ([`Toolkit::image_properties`]).
3474///
3475/// Sparse by construction: every field is what the platform's own reader answered, and a
3476/// backend with no metadata reader at all answers `None` to the whole call rather than an empty
3477/// struct. Probe [`Cap::ImageProperties`] before offering an affordance that depends on it.
3478#[derive(Clone, Debug, Default, PartialEq)]
3479pub struct ImageProperties {
3480    /// The EXIF orientation tag (1–8), where one was recorded.
3481    pub orientation: Option<u16>,
3482    /// Pixels per inch, where the file records a resolution.
3483    pub dpi: Option<f64>,
3484    /// The capture timestamp as the file spells it (no parsing: the formats disagree).
3485    pub created: Option<String>,
3486    /// Everything else the platform reader named, in its own vocabulary. Keys are the
3487    /// platform's, so read them defensively.
3488    pub extra: Vec<(String, String)>,
3489}
3490
3491/// Why an image operation could not answer.
3492#[derive(Clone, Copy, Debug, PartialEq, Eq)]
3493pub enum ImageError {
3494    /// The bytes are not an image this platform decodes.
3495    Decode,
3496    /// The image decoded, but this backend cannot encode the format asked for. `encode_formats`
3497    /// says which it can.
3498    Encode,
3499    /// The backend has no path for this at all (probe [`Cap::ImageDecode`] /
3500    /// [`Cap::ImageEncode`]).
3501    Unsupported,
3502    /// The id named no live image: released already, or never decoded.
3503    Gone,
3504}
3505
3506impl std::fmt::Display for ImageError {
3507    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3508        match self {
3509            ImageError::Decode => write!(f, "the bytes are not a decodable image"),
3510            ImageError::Encode => write!(f, "this backend cannot encode that format"),
3511            ImageError::Unsupported => write!(f, "image support is unavailable on this backend"),
3512            ImageError::Gone => write!(f, "the image was released"),
3513        }
3514    }
3515}
3516
3517impl std::error::Error for ImageError {}
3518
3519// ---------------------------------------------------------------------------
3520// Canvas export (docs/canvas.md "Exporting"): a recorded drawing replayed into an offscreen
3521// bitmap or a PDF by the same painter the on-screen canvas uses.
3522// ---------------------------------------------------------------------------
3523
3524/// The largest side, in pixels, a rendered bitmap may have (docs/canvas.md "Exporting").
3525/// day-core answers [`ExportError::TooLarge`] above it before any toolkit allocates.
3526pub const EXPORT_MAX_SIDE: u32 = 16_384;
3527
3528/// The most pixels a rendered bitmap may hold in total: 64 megapixels, 256 MB at four bytes a
3529/// pixel, which is already more than the tightest per-app heap (Android's) comfortably holds.
3530pub const EXPORT_MAX_PIXELS: u64 = 64 * 1024 * 1024;
3531
3532/// The pixel size a drawing of `size` points renders to at `scale` pixels per point: each side
3533/// rounded up, so a drawing never loses its last partial pixel. Shared by day-core's limit
3534/// check and every backend, so the bitmap a backend allocates is the one day-core approved.
3535#[must_use]
3536pub fn export_pixels(size: Size, scale: f64) -> (u32, u32) {
3537    let side = |v: f64| (v * scale).ceil().clamp(0.0, f64::from(u32::MAX)) as u32;
3538    (side(size.width), side(size.height))
3539}
3540
3541/// One page of a PDF [`Toolkit::render_pdf`] writes: the page size in PDF points (1/72 inch,
3542/// the same unit as canvas points) and the ops to replay onto it, origin top-left.
3543#[derive(Clone, Debug, PartialEq)]
3544pub struct PdfPage {
3545    pub size: Size,
3546    pub ops: Vec<DrawOp>,
3547}
3548
3549/// The document information a PDF carries. A backend whose writer has no metadata API (Android's
3550/// `PdfDocument`) ignores it.
3551#[derive(Clone, Debug, Default, PartialEq)]
3552pub struct PdfInfo {
3553    pub title: Option<String>,
3554    pub author: Option<String>,
3555}
3556
3557/// Why a canvas export could not answer (docs/canvas.md "Exporting").
3558#[derive(Clone, Debug, PartialEq)]
3559pub enum ExportError {
3560    /// This toolkit has no path for the export (probe [`Cap::CanvasBitmap`] /
3561    /// [`Cap::CanvasPdf`]).
3562    Unsupported,
3563    /// The bitmap would exceed [`EXPORT_MAX_SIDE`] or [`EXPORT_MAX_PIXELS`]; checked in
3564    /// day-core before the toolkit runs. The size is the one that was refused, in pixels.
3565    TooLarge { width: u32, height: u32 },
3566    /// A zero, negative or non-finite size or scale, or a PDF with no pages.
3567    Invalid,
3568    /// The platform refused (out of memory, a writer error); the text is the platform's.
3569    Failed(String),
3570}
3571
3572impl std::fmt::Display for ExportError {
3573    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3574        match self {
3575            ExportError::Unsupported => write!(f, "this export is unavailable on this backend"),
3576            ExportError::TooLarge { width, height } => {
3577                write!(
3578                    f,
3579                    "a {width} × {height} pixel bitmap is too large to render"
3580                )
3581            }
3582            ExportError::Invalid => write!(f, "the drawing has no size or the PDF has no pages"),
3583            ExportError::Failed(why) => write!(f, "rendering failed: {why}"),
3584        }
3585    }
3586}
3587
3588impl std::error::Error for ExportError {}
3589
3590/// Where a raster image's pixels come from (docs/images.md).
3591///
3592/// One currency for both halves of the same question: `Named` is the staged asset every
3593/// `image(res::images::…)` has always drawn, `Bytes` is an encoded PNG/JPEG the app already
3594/// holds (a download, a file the user picked, a clipboard paste), and `Decoded` names an image
3595/// the toolkit decoded once so several nodes (and the canvas) share it.
3596#[derive(Clone)]
3597pub enum ImageSource {
3598    /// A staged asset name, resolved through the backend's own pipeline (§18.2).
3599    Named(String),
3600    /// Encoded bytes (PNG/JPEG/…) the app owns, decoded by the platform's own decoder. Shared
3601    /// rather than copied: handing over a new buffer is a refcount bump.
3602    Bytes(std::sync::Arc<Vec<u8>>),
3603    /// An image already decoded through [`Toolkit::decode_image`].
3604    Decoded(BitmapId),
3605}
3606
3607impl Default for ImageSource {
3608    fn default() -> Self {
3609        ImageSource::Named(String::new())
3610    }
3611}
3612
3613/// Bytes compare by identity, not content.
3614///
3615/// This is the equality a binding gates on (§4.2), so it runs on every evaluation, and
3616/// comparing two multi-megabyte buffers byte by byte would cost far more than the redundant
3617/// decode it saves. Handing over a distinct buffer holding the same pixels therefore re-decodes,
3618/// which is the same trade `Arc::ptr_eq` makes wherever else Day carries shared buffers.
3619impl PartialEq for ImageSource {
3620    fn eq(&self, other: &Self) -> bool {
3621        match (self, other) {
3622            (ImageSource::Named(a), ImageSource::Named(b)) => a == b,
3623            (ImageSource::Bytes(a), ImageSource::Bytes(b)) => std::sync::Arc::ptr_eq(a, b),
3624            (ImageSource::Decoded(a), ImageSource::Decoded(b)) => a == b,
3625            _ => false,
3626        }
3627    }
3628}
3629
3630/// Logs the buffer's length, never its contents: a `Debug` that dumped a megabyte of pixels
3631/// into a trace line would make the trace useless and slow.
3632impl std::fmt::Debug for ImageSource {
3633    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3634        match self {
3635            ImageSource::Named(n) => f.debug_tuple("Named").field(n).finish(),
3636            ImageSource::Bytes(b) => f.debug_tuple("Bytes").field(&b.len()).finish(),
3637            ImageSource::Decoded(id) => f.debug_tuple("Decoded").field(&id.0).finish(),
3638        }
3639    }
3640}
3641
3642impl From<BitmapId> for ImageSource {
3643    fn from(id: BitmapId) -> Self {
3644        ImageSource::Decoded(id)
3645    }
3646}
3647
3648/// A staged asset name is a source, so `image(res::images::cover)` keeps compiling unchanged.
3649///
3650/// There is no `From<&str>` here, for the same reason [`resource::ImageName`] has none:
3651/// `image("typo")` must stay a compile error rather than a blank view at runtime (resource.rs).
3652/// A path or URL string is not a source either: read the bytes and hand those over.
3653impl From<resource::ImageName> for ImageSource {
3654    fn from(name: resource::ImageName) -> Self {
3655        ImageSource::Named(name.as_str().to_owned())
3656    }
3657}
3658
3659impl From<resource::VectorName> for ImageSource {
3660    fn from(name: resource::VectorName) -> Self {
3661        ImageSource::Named(name.as_str().to_owned())
3662    }
3663}
3664
3665impl From<std::sync::Arc<Vec<u8>>> for ImageSource {
3666    fn from(bytes: std::sync::Arc<Vec<u8>>) -> Self {
3667        ImageSource::Bytes(bytes)
3668    }
3669}
3670
3671/// An owned string is a name, not bytes: the same conversion [`resource::ImageName`] offers for
3672/// a name computed at runtime, and the reason `image(some_string)` keeps compiling. A `&str`
3673/// still converts nowhere, so `image("typo")` stays a compile error (resource.rs).
3674impl From<String> for ImageSource {
3675    fn from(name: String) -> Self {
3676        ImageSource::Named(name)
3677    }
3678}
3679
3680impl From<Vec<u8>> for ImageSource {
3681    fn from(bytes: Vec<u8>) -> Self {
3682        ImageSource::Bytes(std::sync::Arc::new(bytes))
3683    }
3684}
3685
3686/// What a text field collects (`text_field(..).input_purpose(_)`, docs/textfield.md).
3687///
3688/// One word for everything a platform keys off the kind of text: the on-screen keyboard's
3689/// layout, capitalization and correction, and the credential or contact the system offers to
3690/// fill in. A backend applies the parts its toolkit has: a desktop toolkit with no on-screen
3691/// keyboard still takes the autofill and correction half.
3692///
3693/// Purpose is independent of [`InputTraits::secure`]: a numeric PIN is `Number` and secure.
3694#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
3695pub enum InputPurpose {
3696    /// Free text: the default keyboard, with the platform's own capitalization and correction.
3697    #[default]
3698    Text,
3699    /// A person's name: words capitalized, never corrected.
3700    Name,
3701    /// An email address: the `@` keyboard, never capitalized or corrected.
3702    Email,
3703    /// A web address: the URL keyboard, never capitalized or corrected.
3704    Url,
3705    /// A telephone number: the phone pad.
3706    Phone,
3707    /// A whole number: the digit pad.
3708    Number,
3709    /// A number with a fractional part: the digit pad with a decimal separator.
3710    Decimal,
3711    /// An account name: never capitalized or corrected, and offered to the password manager.
3712    Username,
3713    /// An existing password, offered to the password manager for filling.
3714    Password,
3715    /// A password being chosen, so the password manager offers to make and save one.
3716    NewPassword,
3717    /// A code sent by message or mail, which the keyboard offers as it arrives. The keyboard
3718    /// stays the text one, since a code can carry letters.
3719    OneTimeCode,
3720}
3721
3722/// The on-screen keyboard's action key (`text_field(..).submit_label(_)`, docs/textfield.md).
3723///
3724/// The key always fires the field's `on_submit`; this names what it promises. A toolkit with
3725/// no on-screen keyboard ignores it.
3726#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
3727pub enum SubmitLabel {
3728    /// The platform's own key (Return).
3729    #[default]
3730    Return,
3731    Done,
3732    Go,
3733    Next,
3734    Search,
3735    Send,
3736}
3737
3738/// How a text field takes its text (docs/textfield.md): the whole set travels together through
3739/// [`Toolkit::set_input_traits`], so a backend that has to rebuild the widget for one member
3740/// has every other member in hand to dress the replacement.
3741#[derive(Clone, Debug, Default, PartialEq, Eq)]
3742pub struct InputTraits {
3743    /// Hide the characters (a password field).
3744    pub secure: bool,
3745    /// Show and select the text, take no edits.
3746    pub read_only: bool,
3747    pub purpose: InputPurpose,
3748    pub submit_label: SubmitLabel,
3749    /// The most characters (Unicode scalar values) the field takes; `None` is unbounded.
3750    /// day-pieces holds the bound on every backend. A toolkit applies its native limit as well
3751    /// only where that limit counts the same unit (GTK): one that counts UTF-16 units would
3752    /// refuse characters the bound allows.
3753    pub max_length: Option<u32>,
3754}
3755
3756/// The pointer's shape over a piece (the `.cursor()` decorator, docs/cursor.md).
3757///
3758/// The named variants are the CSS cursor vocabulary: the largest set any toolkit accepts as it
3759/// is (GTK and the DOM take the names verbatim), and every other toolkit's set is a subset of it
3760/// or maps onto it. A backend draws its own shape for each name, or the nearest one it has, and
3761/// answers [`Cap::Cursor`] with how faithful that is. [`Cursor::Native`] reaches a shape only one
3762/// toolkit names; the `day::cursor::<toolkit>` modules carry those as constants, gated on that
3763/// toolkit's feature, and every other backend ignores a name it does not know.
3764///
3765/// A cursor applies to the node and its descendants until a descendant sets its own.
3766/// [`Cursor::Default`] hands the shape back to the platform rather than pinning an arrow, so a
3767/// reactive cursor can release what it took.
3768#[derive(Clone, Debug, PartialEq, Eq, Hash, Default)]
3769pub enum Cursor {
3770    /// The platform default (an arrow), and the value that releases a node's cursor.
3771    #[default]
3772    Default,
3773    /// A pointing hand: links and other tap-to-activate content.
3774    Pointer,
3775    /// An I-beam over editable or selectable text.
3776    Text,
3777    /// An I-beam for vertical text.
3778    VerticalText,
3779    Crosshair,
3780    /// Four-way move.
3781    Move,
3782    /// An open hand: content that can be dragged.
3783    Grab,
3784    /// A closed hand: content being dragged.
3785    Grabbing,
3786    NotAllowed,
3787    /// The app is busy and cannot take input.
3788    Wait,
3789    /// The app is busy but still takes input.
3790    Progress,
3791    Help,
3792    ContextMenu,
3793    /// A drop will copy.
3794    Copy,
3795    /// A drop will link.
3796    Alias,
3797    /// A table cell.
3798    Cell,
3799    ZoomIn,
3800    ZoomOut,
3801    /// No pointer at all.
3802    None,
3803    /// Vertical (north–south) resize.
3804    NsResize,
3805    /// Horizontal (east–west) resize.
3806    EwResize,
3807    /// Diagonal resize, north-east to south-west.
3808    NeswResize,
3809    /// Diagonal resize, north-west to south-east.
3810    NwseResize,
3811    ColResize,
3812    RowResize,
3813    /// A toolkit's own named cursor, resolved by that backend's lookup and ignored by every
3814    /// other. Prefer the `day::cursor::<toolkit>` constants, which are gated on the toolkit.
3815    Native(std::borrow::Cow<'static, str>),
3816}
3817
3818impl Cursor {
3819    /// A toolkit-specific cursor by its native name (see [`Cursor::Native`]).
3820    #[must_use]
3821    pub const fn native(name: &'static str) -> Self {
3822        Cursor::Native(std::borrow::Cow::Borrowed(name))
3823    }
3824
3825    /// The CSS keyword for a named cursor, which GTK and the DOM take as it is. A native cursor
3826    /// answers its own name, so a backend keyed on CSS names may still recognize it.
3827    #[must_use]
3828    pub fn css_name(&self) -> &str {
3829        match self {
3830            Cursor::Default => "default",
3831            Cursor::Pointer => "pointer",
3832            Cursor::Text => "text",
3833            Cursor::VerticalText => "vertical-text",
3834            Cursor::Crosshair => "crosshair",
3835            Cursor::Move => "move",
3836            Cursor::Grab => "grab",
3837            Cursor::Grabbing => "grabbing",
3838            Cursor::NotAllowed => "not-allowed",
3839            Cursor::Wait => "wait",
3840            Cursor::Progress => "progress",
3841            Cursor::Help => "help",
3842            Cursor::ContextMenu => "context-menu",
3843            Cursor::Copy => "copy",
3844            Cursor::Alias => "alias",
3845            Cursor::Cell => "cell",
3846            Cursor::ZoomIn => "zoom-in",
3847            Cursor::ZoomOut => "zoom-out",
3848            Cursor::None => "none",
3849            Cursor::NsResize => "ns-resize",
3850            Cursor::EwResize => "ew-resize",
3851            Cursor::NeswResize => "nesw-resize",
3852            Cursor::NwseResize => "nwse-resize",
3853            Cursor::ColResize => "col-resize",
3854            Cursor::RowResize => "row-resize",
3855            Cursor::Native(name) => name,
3856        }
3857    }
3858
3859    /// Every named cursor, in declaration order, what a gallery or a test walks.
3860    pub const NAMED: [Cursor; 25] = [
3861        Cursor::Default,
3862        Cursor::Pointer,
3863        Cursor::Text,
3864        Cursor::VerticalText,
3865        Cursor::Crosshair,
3866        Cursor::Move,
3867        Cursor::Grab,
3868        Cursor::Grabbing,
3869        Cursor::NotAllowed,
3870        Cursor::Wait,
3871        Cursor::Progress,
3872        Cursor::Help,
3873        Cursor::ContextMenu,
3874        Cursor::Copy,
3875        Cursor::Alias,
3876        Cursor::Cell,
3877        Cursor::ZoomIn,
3878        Cursor::ZoomOut,
3879        Cursor::None,
3880        Cursor::NsResize,
3881        Cursor::EwResize,
3882        Cursor::NeswResize,
3883        Cursor::NwseResize,
3884        Cursor::ColResize,
3885        Cursor::RowResize,
3886    ];
3887}
3888
3889/// A set of screen edges, for the `defers_system_gestures` modifier (docs/cover.md). Mirrors
3890/// SwiftUI's `Edge.Set`: on iOS these map to `UIRectEdge` for
3891/// `preferredScreenEdgesDeferringSystemGestures`; on Android any non-empty set enters
3892/// swipe-to-reveal immersive mode (the closest platform analogue).
3893#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
3894pub struct Edges(pub u8);
3895
3896impl Edges {
3897    pub const NONE: Edges = Edges(0);
3898    pub const TOP: Edges = Edges(1);
3899    pub const BOTTOM: Edges = Edges(2);
3900    pub const LEADING: Edges = Edges(4);
3901    pub const TRAILING: Edges = Edges(8);
3902    pub const ALL: Edges = Edges(15);
3903
3904    #[must_use]
3905    pub fn contains(self, other: Edges) -> bool {
3906        self.0 & other.0 == other.0
3907    }
3908    #[must_use]
3909    pub fn union(self, other: Edges) -> Edges {
3910        Edges(self.0 | other.0)
3911    }
3912    #[must_use]
3913    pub fn is_empty(self) -> bool {
3914        self.0 == 0
3915    }
3916}
3917
3918impl std::ops::BitOr for Edges {
3919    type Output = Edges;
3920    fn bitor(self, rhs: Edges) -> Edges {
3921        self.union(rhs)
3922    }
3923}
3924
3925/// The timing curve of an animation (§8.4). Native backends map each variant onto their own
3926/// easing (`CAMediaTimingFunction`, `QEasingCurve`, ArkUI `ARKUI_CURVE_*`, spring animators); the
3927/// canvas/self-driven path samples it via [`Curve::fraction`]. `Spring` matches SwiftUI's
3928/// `.spring(response:dampingFraction:)`.
3929#[derive(Clone, Copy, Debug, PartialEq)]
3930pub enum Curve {
3931    Linear,
3932    EaseIn,
3933    EaseOut,
3934    EaseInOut,
3935    /// `response` = approximate settling period (seconds); `damping` = damping ratio (1.0 =
3936    /// critically damped, `<1` = bouncy overshoot).
3937    Spring {
3938        response: f64,
3939        damping: f64,
3940    },
3941}
3942
3943impl Curve {
3944    /// Fraction of the transition complete at `elapsed` seconds (0 at start, reaching 1, or
3945    /// overshooting it for an under-damped spring). Easing curves clamp to `duration`; springs
3946    /// evaluate their analytic unit-step response and use `duration` only as a settle cap. Drives
3947    /// the self-driven/canvas path; native backends interpolate on their own compositor instead.
3948    #[must_use]
3949    pub fn fraction(self, elapsed: f64, duration: f64) -> f64 {
3950        if let Curve::Spring { response, damping } = self {
3951            spring_step(response, damping, elapsed)
3952        } else {
3953            let t = if duration <= 0.0 {
3954                1.0
3955            } else {
3956                (elapsed / duration).clamp(0.0, 1.0)
3957            };
3958            self.ease(t)
3959        }
3960    }
3961
3962    /// Eased progress for normalized `t` in `0.0..=1.0` (springs pass through; use [`Self::fraction`]).
3963    #[inline]
3964    #[must_use]
3965    pub fn ease(self, t: f64) -> f64 {
3966        match self {
3967            Curve::Linear | Curve::Spring { .. } => t,
3968            Curve::EaseIn => t * t,
3969            Curve::EaseOut => 1.0 - (1.0 - t) * (1.0 - t),
3970            Curve::EaseInOut => t * t * (3.0 - 2.0 * t), // smoothstep
3971        }
3972    }
3973
3974    /// Whether the transition has settled, so the canvas frame clock can stop ticking it.
3975    #[must_use]
3976    pub fn is_settled(self, elapsed: f64, duration: f64) -> bool {
3977        match self {
3978            Curve::Spring { response, damping } => {
3979                let cap = response.max(0.0) * 4.0 + 0.2;
3980                if elapsed >= cap {
3981                    return true;
3982                }
3983                (spring_step(response, damping, elapsed) - 1.0).abs() < 0.001
3984                    && elapsed > response * 0.5
3985            }
3986            _ => elapsed >= duration.max(0.0),
3987        }
3988    }
3989}
3990
3991/// Unit-step response of a second-order spring (`response` = period seconds, `damping` = ratio),
3992/// evaluated at `t` seconds. Under-damped rings and overshoots; critically/over-damped eases in.
3993fn spring_step(response: f64, damping: f64, t: f64) -> f64 {
3994    if response <= 0.0 || t <= 0.0 {
3995        return if t <= 0.0 { 0.0 } else { 1.0 };
3996    }
3997    let omega0 = std::f64::consts::TAU / response;
3998    let zeta = damping.max(0.0);
3999    if zeta < 1.0 {
4000        let omega_d = omega0 * (1.0 - zeta * zeta).sqrt();
4001        let e = (-zeta * omega0 * t).exp();
4002        1.0 - e * ((omega_d * t).cos() + (zeta * omega0 / omega_d) * (omega_d * t).sin())
4003    } else {
4004        let e = (-omega0 * t).exp();
4005        1.0 - e * (1.0 + omega0 * t)
4006    }
4007}
4008
4009/// Animation intent (§8.4). Native-widget backends map it onto their own animator (Core Animation,
4010/// `ViewPropertyAnimator`, XAML Composition, `OH_ArkUI_AnimateTo`, …); the canvas/self-driven path
4011/// samples `curve` via [`Curve::fraction`]. Threaded through `Toolkit::update`/`set_frame`/
4012/// `set_opacity`/`set_transform`.
4013#[derive(Clone, Copy, Debug, PartialEq)]
4014pub struct AnimSpec {
4015    pub duration_ms: u32,
4016    pub delay_ms: u32,
4017    pub curve: Curve,
4018    /// Repeat count beyond the first play (`0` = play once); `u32::MAX` = repeat forever.
4019    pub repeat: u32,
4020    pub autoreverse: bool,
4021}
4022
4023impl Default for AnimSpec {
4024    /// The default feel: a smooth spring (SwiftUI's modern default).
4025    fn default() -> Self {
4026        AnimSpec {
4027            duration_ms: 350,
4028            delay_ms: 0,
4029            curve: Curve::Spring {
4030                response: 0.4,
4031                damping: 0.8,
4032            },
4033            repeat: 0,
4034            autoreverse: false,
4035        }
4036    }
4037}
4038
4039impl AnimSpec {
4040    /// A smooth spring: `response` = settling period (s), `damping` = ratio (1.0 = no bounce, `<1`
4041    /// bouncy). `duration_ms` is a nominal cap for backends that need a duration; spring backends
4042    /// use `response`/`damping` directly.
4043    pub fn spring(response: f64, damping: f64) -> Self {
4044        AnimSpec {
4045            // `response` is the animation's duration: every backend maps a spring to a
4046            // fixed-duration overshoot curve over exactly `duration_ms`, so timing is identical
4047            // across toolkits (a physics spring's settle time would vary per platform).
4048            duration_ms: (response * 1000.0).max(50.0) as u32,
4049            delay_ms: 0,
4050            curve: Curve::Spring { response, damping },
4051            repeat: 0,
4052            autoreverse: false,
4053        }
4054    }
4055    pub fn linear(duration_ms: u32) -> Self {
4056        Self::timed(duration_ms, Curve::Linear)
4057    }
4058    pub fn ease_in(duration_ms: u32) -> Self {
4059        Self::timed(duration_ms, Curve::EaseIn)
4060    }
4061    pub fn ease_out(duration_ms: u32) -> Self {
4062        Self::timed(duration_ms, Curve::EaseOut)
4063    }
4064    pub fn ease_in_out(duration_ms: u32) -> Self {
4065        Self::timed(duration_ms, Curve::EaseInOut)
4066    }
4067    fn timed(duration_ms: u32, curve: Curve) -> Self {
4068        AnimSpec {
4069            duration_ms,
4070            delay_ms: 0,
4071            curve,
4072            repeat: 0,
4073            autoreverse: false,
4074        }
4075    }
4076    /// Delay before the animation starts (builder).
4077    #[must_use]
4078    pub fn delay(mut self, ms: u32) -> Self {
4079        self.delay_ms = ms;
4080        self
4081    }
4082    /// Repeat `count` extra times (builder); `autoreverse` ping-pongs each cycle.
4083    #[must_use]
4084    pub fn repeat(mut self, count: u32, autoreverse: bool) -> Self {
4085        self.repeat = count;
4086        self.autoreverse = autoreverse;
4087        self
4088    }
4089    /// Repeat forever (builder), e.g. a pulsing indicator.
4090    #[must_use]
4091    pub fn repeat_forever(mut self, autoreverse: bool) -> Self {
4092        self.repeat = u32::MAX;
4093        self.autoreverse = autoreverse;
4094        self
4095    }
4096    #[inline]
4097    #[must_use]
4098    pub fn duration_secs(&self) -> f64 {
4099        f64::from(self.duration_ms) / 1000.0
4100    }
4101    #[inline]
4102    #[must_use]
4103    pub fn delay_secs(&self) -> f64 {
4104        f64::from(self.delay_ms) / 1000.0
4105    }
4106}
4107
4108#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
4109pub enum Role {
4110    #[default]
4111    None,
4112    Button,
4113    Toggle,
4114    Slider,
4115    TextInput,
4116    Heading(u8),
4117    Image,
4118    Meter,
4119    Group,
4120    /// A hierarchical tree container (docs/tree.md): `role="tree"`, `AXOutline`.
4121    Tree,
4122    /// One row of a tree: `role="treeitem"`, with level/expanded state where the platform
4123    /// carries them (docs/tree.md).
4124    TreeItem,
4125    /// One tab in a strip of peers (`role="tab"`, `AXTabButton`): the composed document
4126    /// strip's title buttons. Pair it with [`A11yProps::selected`] for the current one.
4127    Tab,
4128    /// The strip holding tabs (`role="tablist"`, `AXTabGroup`).
4129    TabList,
4130}
4131
4132impl Role {
4133    /// The a11y role a built-in piece kind reports natively, the audit's *expectation* when the
4134    /// user hasn't set an explicit `.role()`. Native controls already expose these, so Day records
4135    /// them for `a11y_audit` (§14.2) rather than overriding the widget; only canvas/custom pieces
4136    /// need Day to apply a role. Returns `None` for kinds with no inherent control role.
4137    #[must_use]
4138    pub fn for_kind(kind: PieceKind) -> Role {
4139        match kind {
4140            kinds::BUTTON => Role::Button,
4141            kinds::TOGGLE => Role::Toggle,
4142            kinds::SLIDER => Role::Slider,
4143            kinds::TEXT_FIELD => Role::TextInput,
4144            kinds::IMAGE => Role::Image,
4145            kinds::PROGRESS => Role::Meter,
4146            kinds::TREE => Role::Tree,
4147            _ => Role::None,
4148        }
4149    }
4150}
4151
4152#[derive(Clone, Debug, Default, PartialEq)]
4153pub struct A11yProps {
4154    pub label: Option<String>,
4155    pub hint: Option<String>,
4156    pub value: Option<String>,
4157    pub role: Role,
4158    pub identifier: Option<String>,
4159    pub hidden: bool,
4160    pub decorative: bool,
4161    /// Whether the element is the selected one among its peers (a tab, a row): the
4162    /// platform's selected state, read aloud as such. `None` leaves the widget's own answer.
4163    pub selected: Option<bool>,
4164}
4165
4166impl A11yProps {
4167    /// Merge another set of annotations onto this one: any field `other` sets (a `Some`, a
4168    /// non-`None` role, or a `true` flag) overrides ours; unset fields are left intact. Lets a
4169    /// node accumulate its `.a11y()`, `.id()`, and piece defaults into one stored result, so
4170    /// each `set_a11y` re-applies the full picture and `a11y_audit` has the complete expectation.
4171    pub fn merge(&mut self, other: &A11yProps) {
4172        if other.label.is_some() {
4173            self.label.clone_from(&other.label);
4174        }
4175        if other.hint.is_some() {
4176            self.hint.clone_from(&other.hint);
4177        }
4178        if other.value.is_some() {
4179            self.value.clone_from(&other.value);
4180        }
4181        if other.role != Role::None {
4182            self.role = other.role;
4183        }
4184        if other.identifier.is_some() {
4185            self.identifier.clone_from(&other.identifier);
4186        }
4187        self.hidden |= other.hidden;
4188        self.decorative |= other.decorative;
4189        if other.selected.is_some() {
4190            self.selected = other.selected;
4191        }
4192    }
4193
4194    /// The role to *expect* for a node of `kind` carrying these annotations: an explicit
4195    /// `.role()` wins, otherwise the kind's native default (`Role::for_kind`).
4196    #[must_use]
4197    pub fn resolved_role(&self, kind: PieceKind) -> Role {
4198        if self.role == Role::None {
4199            Role::for_kind(kind)
4200        } else {
4201            self.role
4202        }
4203    }
4204}
4205
4206/// A widget's actual native state, read back from the platform by `Toolkit::read_native`
4207/// (docs/testing.md): what the widget itself shows and reports, independently of Day's tree,
4208/// so `a11y_audit` and `assert_native` (§14.2) can diff it against Day's expectation.
4209///
4210/// Two groups. The accessibility fields (`role`, `label`, `value`, `identifier`) are read
4211/// together and `found` says whether they were: `found = false` means the backend cannot read
4212/// its accessibility tree, and the audit skips the node. Every other field is read on its own,
4213/// and `None` means "not read": the backend cannot read it, or it does not apply to this kind.
4214/// A reader never reports a field it did not take from the widget, so a `None` is a recorded
4215/// gap rather than a pass.
4216#[derive(Clone, Debug, Default, PartialEq)]
4217pub struct NativeSnapshot {
4218    /// The accessibility fields below were read.
4219    pub found: bool,
4220    /// The native role mapped back to Day's `Role` (best-effort).
4221    pub role: Role,
4222    /// The accessibility label the platform reports.
4223    pub label: Option<String>,
4224    /// The accessibility value the platform reports.
4225    pub value: Option<String>,
4226    /// The automation identifier, which Day sets from `.id()`.
4227    pub identifier: Option<String>,
4228    /// The text the widget displays: a label's string, a button's title, a text field's or
4229    /// text area's contents, without markup or mnemonic markers. `None` for a secure field
4230    /// that masks it.
4231    pub text: Option<String>,
4232    /// A slider's or progress indicator's value, in the range Day gave it.
4233    pub number: Option<f64>,
4234    /// A toggle's state, or a button's selected state (`ButtonProps::selected`).
4235    pub checked: Option<bool>,
4236    /// Whether the widget takes input.
4237    pub enabled: Option<bool>,
4238    /// Whether the widget is shown: not hidden itself, nor by an ancestor.
4239    pub visible: Option<bool>,
4240    /// The widget's frame in points, relative to the window's content area, origin top left.
4241    pub frame: Option<Rect>,
4242}
4243
4244// ---------------------------------------------------------------------------
4245// Canvas display list (§11): full op set lands with M8a; the types are v1.
4246// ---------------------------------------------------------------------------
4247
4248#[derive(Clone, Debug, PartialEq)]
4249pub enum Shape {
4250    Rect(Rect),
4251    RoundedRect(Rect, f64),
4252    Ellipse(Rect),
4253    /// Arc within `rect`'s inscribed ellipse; angles in degrees, 0 = +x axis, clockwise.
4254    Arc {
4255        rect: Rect,
4256        start_deg: f64,
4257        sweep_deg: f64,
4258    },
4259    Line(Point, Point),
4260    Polygon(Vec<Point>),
4261    /// An arbitrary path: curves, several contours, and a fill rule (docs/canvas.md).
4262    ///
4263    /// [`Shape::Polygon`] is the straight-line, single-contour special case, kept because it is
4264    /// what most drawing code wants and it encodes far more compactly.
4265    Path(Path),
4266}
4267
4268impl Shape {
4269    /// A rectangle rounded corner by corner (docs/canvas.md "Rounded corners"), as the simplest
4270    /// shape that draws it: a plain [`Shape::Rect`] when every corner is square, a
4271    /// [`Shape::RoundedRect`] (each toolkit's own rounded rectangle) when the corners agree, and a
4272    /// path ([`rounded_rect_segs`]) otherwise. The radii are [fitted](CornerRadii::fitted) first.
4273    ///
4274    /// ```
4275    /// use day_spec::{CornerRadii, Rect, Shape};
4276    ///
4277    /// // A bar standing on its axis: rounded on top, square where it meets the baseline.
4278    /// let bar = Shape::rounded_rect(Rect::new(0.0, 0.0, 20.0, 80.0), CornerRadii::top(6.0));
4279    /// std::assert_matches!(bar, Shape::Path(_));
4280    /// ```
4281    pub fn rounded_rect(rect: Rect, radii: CornerRadii) -> Shape {
4282        let r = radii.fitted(rect.size);
4283        if r.is_zero() || rect.size.width <= 0.0 || rect.size.height <= 0.0 {
4284            Shape::Rect(rect)
4285        } else if r.is_uniform() {
4286            Shape::RoundedRect(rect, r.top_left)
4287        } else {
4288            Shape::Path(Path {
4289                segs: rounded_rect_segs(rect, r),
4290                rule: FillRule::NonZero,
4291            })
4292        }
4293    }
4294
4295    /// The same shape moved by `(dx, dy)`.
4296    ///
4297    /// What a [`Stamp`] means by "the template translated by one point", and the one definition of
4298    /// it: a backend builds each copy of a batch with this rather than reaching for its own
4299    /// platform transform, so every toolkit stamps to the same coordinates.
4300    #[must_use]
4301    pub fn translated(&self, dx: f64, dy: f64) -> Shape {
4302        let r = |r: &Rect| {
4303            Rect::new(
4304                r.origin.x + dx,
4305                r.origin.y + dy,
4306                r.size.width,
4307                r.size.height,
4308            )
4309        };
4310        let p = |p: &Point| Point::new(p.x + dx, p.y + dy);
4311        match self {
4312            Shape::Rect(rect) => Shape::Rect(r(rect)),
4313            Shape::RoundedRect(rect, rad) => Shape::RoundedRect(r(rect), *rad),
4314            Shape::Ellipse(rect) => Shape::Ellipse(r(rect)),
4315            Shape::Arc {
4316                rect,
4317                start_deg,
4318                sweep_deg,
4319            } => Shape::Arc {
4320                rect: r(rect),
4321                start_deg: *start_deg,
4322                sweep_deg: *sweep_deg,
4323            },
4324            Shape::Line(a, b) => Shape::Line(p(a), p(b)),
4325            Shape::Polygon(pts) => Shape::Polygon(pts.iter().map(p).collect()),
4326            Shape::Path(path) => Shape::Path(Path {
4327                segs: path
4328                    .segs
4329                    .iter()
4330                    .map(|seg| match seg {
4331                        PathSeg::Move(a) => PathSeg::Move(p(a)),
4332                        PathSeg::Line(a) => PathSeg::Line(p(a)),
4333                        PathSeg::Quad(c, a) => PathSeg::Quad(p(c), p(a)),
4334                        PathSeg::Cubic(c1, c2, a) => PathSeg::Cubic(p(c1), p(c2), p(a)),
4335                        PathSeg::Close => PathSeg::Close,
4336                    })
4337                    .collect(),
4338                rule: path.rule,
4339            }),
4340        }
4341    }
4342
4343    /// The shape's bounding rectangle: the box gradient [`UnitPoint`]s resolve against.
4344    pub fn bounds(&self) -> Rect {
4345        match self {
4346            Shape::Rect(r) | Shape::RoundedRect(r, _) | Shape::Ellipse(r) => *r,
4347            Shape::Arc { rect, .. } => *rect,
4348            Shape::Line(a, b) => points_bounds(&[*a, *b]),
4349            Shape::Polygon(pts) => points_bounds(pts),
4350            Shape::Path(p) => p.bounds(),
4351        }
4352    }
4353}
4354
4355/// One step of a [`Path`]. Points are absolute, in the canvas's coordinate space.
4356#[derive(Clone, Copy, Debug, PartialEq)]
4357pub enum PathSeg {
4358    /// Start a new contour at this point.
4359    Move(Point),
4360    Line(Point),
4361    /// Quadratic bezier: one control point, then the end point.
4362    Quad(Point, Point),
4363    /// Cubic bezier: two control points, then the end point.
4364    Cubic(Point, Point, Point),
4365    /// Close the current contour back to its `Move`.
4366    Close,
4367}
4368
4369/// Which points count as inside when a path's contours overlap (docs/canvas.md).
4370///
4371/// This matters the moment a shape has a hole: the counter of an "o", a washer, a ring chart. It
4372/// is a property of the fill, so stroking ignores it.
4373#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
4374pub enum FillRule {
4375    /// Direction-sensitive: a hole needs its contour wound the opposite way. Every 2-D API's
4376    /// default, and what a font's glyph outlines assume.
4377    #[default]
4378    NonZero,
4379    /// Parity: any contour inside another cuts a hole regardless of winding. What PDF's `f*`
4380    /// operator and SVG's `fill-rule: evenodd` mean.
4381    EvenOdd,
4382}
4383
4384/// An arbitrary 2-D path: any number of contours, straight or curved, with a fill rule.
4385#[derive(Clone, Debug, PartialEq, Default)]
4386pub struct Path {
4387    pub segs: Vec<PathSeg>,
4388    pub rule: FillRule,
4389}
4390
4391impl Path {
4392    /// A conservative bounding box: the hull of every point including control points, which
4393    /// contains the true curve bounds (a bezier stays inside its control hull). Used only to
4394    /// resolve gradient unit points, where being slightly generous costs nothing and computing
4395    /// exact curve extrema would not.
4396    pub fn bounds(&self) -> Rect {
4397        let mut pts: Vec<Point> = Vec::with_capacity(self.segs.len() * 3);
4398        for seg in &self.segs {
4399            match seg {
4400                PathSeg::Move(p) | PathSeg::Line(p) => pts.push(*p),
4401                PathSeg::Quad(c, p) => pts.extend_from_slice(&[*c, *p]),
4402                PathSeg::Cubic(c1, c2, p) => pts.extend_from_slice(&[*c1, *c2, *p]),
4403                PathSeg::Close => {}
4404            }
4405        }
4406        points_bounds(&pts)
4407    }
4408}
4409
4410/// A radius for each corner of a rectangle, clockwise from the top left (docs/canvas.md "Rounded
4411/// corners"). The shape a bar in a chart wants (rounded at its value end, square against its
4412/// axis), a tab (rounded on top), or a card joined to its neighbor.
4413///
4414/// Radii are in points and never negative. [`CornerRadii::fitted`] shrinks them the way CSS
4415/// does when two radii on one side would overlap, which is what a caller animating a radius or
4416/// drawing a short bar needs to not think about.
4417#[derive(Clone, Copy, Debug, PartialEq, Default)]
4418pub struct CornerRadii {
4419    pub top_left: f64,
4420    pub top_right: f64,
4421    pub bottom_right: f64,
4422    pub bottom_left: f64,
4423}
4424
4425impl CornerRadii {
4426    /// The same radius on every corner: what [`Shape::RoundedRect`] draws.
4427    pub fn uniform(r: f64) -> Self {
4428        CornerRadii {
4429            top_left: r,
4430            top_right: r,
4431            bottom_right: r,
4432            bottom_left: r,
4433        }
4434    }
4435    /// Rounded along the top edge, square along the bottom: a bar standing on its axis.
4436    pub fn top(r: f64) -> Self {
4437        CornerRadii {
4438            top_left: r,
4439            top_right: r,
4440            ..Default::default()
4441        }
4442    }
4443    /// Rounded along the bottom edge: a bar hanging below its axis.
4444    pub fn bottom(r: f64) -> Self {
4445        CornerRadii {
4446            bottom_right: r,
4447            bottom_left: r,
4448            ..Default::default()
4449        }
4450    }
4451    /// Rounded along the left edge: a bar growing leftward from its axis.
4452    pub fn left(r: f64) -> Self {
4453        CornerRadii {
4454            top_left: r,
4455            bottom_left: r,
4456            ..Default::default()
4457        }
4458    }
4459    /// Rounded along the right edge: a bar growing rightward from its axis.
4460    pub fn right(r: f64) -> Self {
4461        CornerRadii {
4462            top_right: r,
4463            bottom_right: r,
4464            ..Default::default()
4465        }
4466    }
4467
4468    /// The four radii, clockwise from the top left.
4469    #[must_use]
4470    pub fn to_array(self) -> [f64; 4] {
4471        [
4472            self.top_left,
4473            self.top_right,
4474            self.bottom_right,
4475            self.bottom_left,
4476        ]
4477    }
4478
4479    /// Whether every corner is square.
4480    #[must_use]
4481    pub fn is_zero(self) -> bool {
4482        self.to_array().iter().all(|r| *r <= 0.0)
4483    }
4484
4485    /// Whether every corner has the same radius, so the rectangle is a [`Shape::RoundedRect`].
4486    #[must_use]
4487    #[expect(
4488        clippy::float_cmp,
4489        reason = "uniform means the four stored radii are exactly equal"
4490    )]
4491    pub fn is_uniform(self) -> bool {
4492        let [a, b, c, d] = self.to_array();
4493        a == b && b == c && c == d
4494    }
4495
4496    /// These radii made to fit a `size` rectangle, the rule CSS uses for `border-radius`: a
4497    /// negative or non-finite radius is square, and when the two radii along any side add up to
4498    /// more than that side, every radius is scaled down by the same factor until none overlap.
4499    /// Scaling all four together keeps the corners in proportion, where clamping each one alone
4500    /// would turn a pill into a lopsided shape.
4501    #[must_use]
4502    pub fn fitted(self, size: Size) -> Self {
4503        let clean = |r: f64| if r.is_finite() && r > 0.0 { r } else { 0.0 };
4504        let [tl, tr, br, bl] = self.to_array().map(clean);
4505        let (w, h) = (size.width.max(0.0), size.height.max(0.0));
4506        let factor = [(w, tl + tr), (w, bl + br), (h, tl + bl), (h, tr + br)]
4507            .into_iter()
4508            .filter(|(_, sum)| *sum > 0.0)
4509            .map(|(side, sum)| side / sum)
4510            .fold(1.0f64, f64::min);
4511        CornerRadii {
4512            top_left: tl * factor,
4513            top_right: tr * factor,
4514            bottom_right: br * factor,
4515            bottom_left: bl * factor,
4516        }
4517    }
4518}
4519
4520/// The point `angle_deg` round a circle: degrees, `0` = the +x axis, positive clockwise in device
4521/// space (y down), the convention [`Shape::Arc`] and every arc helper here use.
4522pub fn arc_point(center: Point, radius: f64, angle_deg: f64) -> Point {
4523    let a = angle_deg.to_radians();
4524    Point::new(center.x + radius * a.cos(), center.y + radius * a.sin())
4525}
4526
4527/// A circular arc as cubic beziers: `sweep_deg` of a circle of `radius` about `center`, from
4528/// `start_deg` ([`arc_point`]'s convention). The segments start *from* the arc's first point, which
4529/// the caller reaches itself (a move or a line); nothing for a zero or non-finite radius or sweep.
4530///
4531/// The arc is split into quarter turns at most, where a cubic tracks a circle best: the radial
4532/// error peaks at 2.7 × 10⁻⁴ of the radius, a quarter of a pixel on a circle a thousand points
4533/// across (docs/canvas.md "Paths"). The same beziers on every backend mean the same pixels on
4534/// every backend, which an arc op interpreted by nine rasterizers would not.
4535#[must_use]
4536pub fn arc_cubics(center: Point, radius: f64, start_deg: f64, sweep_deg: f64) -> Vec<PathSeg> {
4537    let (start, sweep) = (start_deg.to_radians(), sweep_deg.to_radians());
4538    if !radius.is_finite() || radius <= 0.0 || !sweep.is_finite() || sweep == 0.0 {
4539        return Vec::new();
4540    }
4541    let at = |a: f64| Point::new(center.x + radius * a.cos(), center.y + radius * a.sin());
4542    let steps = (sweep.abs() / std::f64::consts::FRAC_PI_2).ceil() as usize;
4543    let delta = sweep / steps as f64;
4544    // The exact control-handle length for a circular arc of this sweep. Negative for a negative
4545    // sweep, which is what turns the handles around for a counter-clockwise arc.
4546    let k = 4.0 / 3.0 * (delta / 4.0).tan() * radius;
4547    (0..steps)
4548        .map(|i| {
4549            let a = start + delta * i as f64;
4550            let b = a + delta;
4551            let (p0, p1) = (at(a), at(b));
4552            PathSeg::Cubic(
4553                Point::new(p0.x - k * a.sin(), p0.y + k * a.cos()),
4554                Point::new(p1.x + k * b.sin(), p1.y - k * b.cos()),
4555                p1,
4556            )
4557        })
4558        .collect()
4559}
4560
4561/// The closed contour of a rectangle rounded corner by corner, clockwise from the top left, with
4562/// the radii [fitted](CornerRadii::fitted) first. A square corner is a sharp point, not a
4563/// zero-length curve.
4564#[must_use]
4565pub fn rounded_rect_segs(rect: Rect, radii: CornerRadii) -> Vec<PathSeg> {
4566    let r = radii.fitted(rect.size);
4567    let (x0, y0) = (rect.origin.x, rect.origin.y);
4568    let (x1, y1) = (x0 + rect.size.width, y0 + rect.size.height);
4569    // Each corner: the point where its curve starts, then the quarter turn round its center.
4570    let corners = [
4571        (
4572            Point::new(x0 + r.top_left, y0 + r.top_left),
4573            r.top_left,
4574            180.0,
4575        ),
4576        (
4577            Point::new(x1 - r.top_right, y0 + r.top_right),
4578            r.top_right,
4579            270.0,
4580        ),
4581        (
4582            Point::new(x1 - r.bottom_right, y1 - r.bottom_right),
4583            r.bottom_right,
4584            0.0,
4585        ),
4586        (
4587            Point::new(x0 + r.bottom_left, y1 - r.bottom_left),
4588            r.bottom_left,
4589            90.0,
4590        ),
4591    ];
4592    let mut segs = Vec::with_capacity(14);
4593    for (i, (center, radius, start)) in corners.into_iter().enumerate() {
4594        let first = arc_point(center, radius, start);
4595        segs.push(if i == 0 {
4596            PathSeg::Move(first)
4597        } else {
4598            PathSeg::Line(first)
4599        });
4600        segs.extend(arc_cubics(center, radius, start, 90.0));
4601    }
4602    segs.push(PathSeg::Close);
4603    segs
4604}
4605
4606/// How a stroked line ends (docs/canvas.md). Names match PDF's `J`, SVG's `stroke-linecap`, and
4607/// every native 2-D API.
4608#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
4609pub enum LineCap {
4610    #[default]
4611    Butt,
4612    Round,
4613    Square,
4614}
4615
4616/// How two stroked segments meet (docs/canvas.md). Matches PDF's `j` and SVG's
4617/// `stroke-linejoin`.
4618#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
4619pub enum LineJoin {
4620    #[default]
4621    Miter,
4622    Round,
4623    Bevel,
4624}
4625
4626/// Everything about a stroke except its paint.
4627///
4628/// [`StrokeStyle::width`] and `From<f64>` keep the common "just a width" case a single
4629/// argument, so plain `stroke(shape, color, 2.0)` call sites read the same as they always did.
4630#[derive(Clone, Debug, PartialEq)]
4631pub struct StrokeStyle {
4632    pub width: f64,
4633    pub cap: LineCap,
4634    pub join: LineJoin,
4635    /// Ignored unless `join` is [`LineJoin::Miter`]. The 2-D convention: past this ratio of miter
4636    /// length to line width the join falls back to a bevel.
4637    pub miter_limit: f64,
4638    /// On/off run lengths, repeating. Empty means solid.
4639    pub dash: Vec<f64>,
4640    /// How far into the dash pattern the line starts.
4641    pub dash_phase: f64,
4642}
4643
4644impl Default for StrokeStyle {
4645    fn default() -> Self {
4646        // 10.0 is the miter limit PDF, PostScript, SVG and Cairo all default to.
4647        StrokeStyle {
4648            width: 1.0,
4649            cap: LineCap::Butt,
4650            join: LineJoin::Miter,
4651            miter_limit: 10.0,
4652            dash: Vec::new(),
4653            dash_phase: 0.0,
4654        }
4655    }
4656}
4657
4658impl StrokeStyle {
4659    /// A solid stroke of `width`, everything else default.
4660    #[must_use]
4661    pub fn width(width: f64) -> Self {
4662        StrokeStyle {
4663            width,
4664            ..Default::default()
4665        }
4666    }
4667    /// A dashed stroke: `dash` is on/off run lengths, repeating.
4668    #[must_use]
4669    pub fn dashed(width: f64, dash: Vec<f64>) -> Self {
4670        StrokeStyle {
4671            width,
4672            dash,
4673            ..Default::default()
4674        }
4675    }
4676    /// Rounded ends and joins, the shape a data line usually wants.
4677    #[must_use]
4678    pub fn round(width: f64) -> Self {
4679        StrokeStyle {
4680            width,
4681            cap: LineCap::Round,
4682            join: LineJoin::Round,
4683            ..Default::default()
4684        }
4685    }
4686    /// Is this the plain width-only stroke every pre-existing call site asks for? Backends use
4687    /// it to skip setting dash/cap/join state they would only have to set back.
4688    #[must_use]
4689    #[expect(
4690        clippy::float_cmp,
4691        reason = "10.0 is the stored default miter limit, compared as a sentinel"
4692    )]
4693    pub fn is_plain(&self) -> bool {
4694        self.cap == LineCap::Butt
4695            && self.join == LineJoin::Miter
4696            && self.dash.is_empty()
4697            && self.miter_limit == 10.0
4698    }
4699}
4700
4701impl From<f64> for StrokeStyle {
4702    fn from(width: f64) -> Self {
4703        StrokeStyle::width(width)
4704    }
4705}
4706
4707fn points_bounds(pts: &[Point]) -> Rect {
4708    let (mut x0, mut y0, mut x1, mut y1) = (f64::MAX, f64::MAX, f64::MIN, f64::MIN);
4709    for p in pts {
4710        x0 = x0.min(p.x);
4711        y0 = y0.min(p.y);
4712        x1 = x1.max(p.x);
4713        y1 = y1.max(p.y);
4714    }
4715    if pts.is_empty() {
4716        return Rect::ZERO;
4717    }
4718    Rect::new(x0, y0, x1 - x0, y1 - y0)
4719}
4720
4721/// A point in the unit space of a shape's bounding box: (0,0) = top-leading, (1,1) =
4722/// bottom-trailing. Gradient geometry is expressed in unit points so one paint value works for
4723/// any shape size (docs/shapes.md §3.2).
4724#[derive(Clone, Copy, Debug, PartialEq)]
4725pub struct UnitPoint {
4726    pub x: f64,
4727    pub y: f64,
4728}
4729
4730impl UnitPoint {
4731    #[must_use]
4732    pub const fn new(x: f64, y: f64) -> Self {
4733        UnitPoint { x, y }
4734    }
4735    pub const TOP: UnitPoint = UnitPoint::new(0.5, 0.0);
4736    pub const BOTTOM: UnitPoint = UnitPoint::new(0.5, 1.0);
4737    pub const LEADING: UnitPoint = UnitPoint::new(0.0, 0.5);
4738    pub const TRAILING: UnitPoint = UnitPoint::new(1.0, 0.5);
4739    pub const TOP_LEADING: UnitPoint = UnitPoint::new(0.0, 0.0);
4740    pub const TOP_TRAILING: UnitPoint = UnitPoint::new(1.0, 0.0);
4741    pub const BOTTOM_LEADING: UnitPoint = UnitPoint::new(0.0, 1.0);
4742    pub const BOTTOM_TRAILING: UnitPoint = UnitPoint::new(1.0, 1.0);
4743    pub const CENTER: UnitPoint = UnitPoint::new(0.5, 0.5);
4744
4745    /// Resolve to an absolute point within `rect`.
4746    pub fn resolve(&self, rect: Rect) -> Point {
4747        Point::new(
4748            rect.origin.x + self.x * rect.size.width,
4749            rect.origin.y + self.y * rect.size.height,
4750        )
4751    }
4752}
4753
4754/// A linear gradient (docs/shapes.md §3.2 / §7): color stops along the line from `start` to
4755/// `end`, both in the unit space of the filled shape's bounding box. Stops are
4756/// `(offset 0..=1, color)`, ascending.
4757#[derive(Clone, Debug, PartialEq)]
4758pub struct LinearGradient {
4759    pub start: UnitPoint,
4760    pub end: UnitPoint,
4761    pub stops: Vec<(f64, Color)>,
4762}
4763
4764impl LinearGradient {
4765    #[must_use]
4766    pub fn new(start: UnitPoint, end: UnitPoint, stops: Vec<(f64, Color)>) -> Self {
4767        LinearGradient { start, end, stops }
4768    }
4769    /// Top-to-bottom between two colors: the everyday sky/backdrop case.
4770    #[must_use]
4771    pub fn vertical(top: Color, bottom: Color) -> Self {
4772        LinearGradient::new(
4773            UnitPoint::TOP,
4774            UnitPoint::BOTTOM,
4775            vec![(0.0, top), (1.0, bottom)],
4776        )
4777    }
4778    /// Leading-to-trailing between two colors.
4779    #[must_use]
4780    pub fn horizontal(leading: Color, trailing: Color) -> Self {
4781        LinearGradient::new(
4782            UnitPoint::LEADING,
4783            UnitPoint::TRAILING,
4784            vec![(0.0, leading), (1.0, trailing)],
4785        )
4786    }
4787}
4788
4789/// A radial gradient (docs/shapes.md §3.2 / §7): color stops from `center` outward. Both the
4790/// center and the radius live in the unit space of the filled shape's bounding box, so the
4791/// gradient stretches into an ellipse when the bounds aren't square (the XAML relative-brush
4792/// behavior; the other backends reproduce it with a local matrix on a circular gradient). A
4793/// `radius` of `0.5` from the default center touches the edge midpoints of the bounds.
4794#[derive(Clone, Debug, PartialEq)]
4795pub struct RadialGradient {
4796    pub center: UnitPoint,
4797    pub radius: f64,
4798    pub stops: Vec<(f64, Color)>,
4799}
4800
4801impl RadialGradient {
4802    #[must_use]
4803    pub fn new(center: UnitPoint, radius: f64, stops: Vec<(f64, Color)>) -> Self {
4804        RadialGradient {
4805            center,
4806            radius,
4807            stops,
4808        }
4809    }
4810    /// Centered, edge-touching (radius 0.5) between two colors: the everyday glow case.
4811    #[must_use]
4812    pub fn centered(inner: Color, outer: Color) -> Self {
4813        RadialGradient::new(UnitPoint::CENTER, 0.5, vec![(0.0, inner), (1.0, outer)])
4814    }
4815}
4816
4817/// The payload of [`DrawOp::Stamp`]: one shape drawn at every position in `at`.
4818///
4819/// A scatter plot is the case this exists for. Drawn as individual ops, fifty thousand points are
4820/// fifty thousand `DrawOp`s, rebuilt, compared and cloned on every frame that re-records, before
4821/// a backend draws anything. As one `Stamp` they are one op and a flat array of coordinates, and
4822/// a backend can put every copy into one path and hand the rasterizer a single fill.
4823///
4824/// Every copy shares the shape, the size and the paint. Varying any of those means more than one
4825/// stamp: group by what varies, which for a chart is usually the series color.
4826#[derive(Clone, Debug, PartialEq)]
4827pub struct Stamp {
4828    /// The template, authored around the origin: each copy is this shape translated by one point.
4829    /// A 6-point dot is `Shape::Ellipse(Rect::new(-3.0, -3.0, 6.0, 6.0))`.
4830    pub shape: Shape,
4831    /// Where the copies go. Order is the drawing order, so later points paint over earlier ones.
4832    pub at: Vec<Point>,
4833    pub paint: Paint,
4834    /// `None` fills each copy; `Some` strokes it with this style.
4835    pub stroke: Option<StrokeStyle>,
4836}
4837
4838/// A fill source: a solid color, or a linear/radial gradient (docs/shapes.md §3.2; angular and
4839/// semantic tokens are later phases). `From<Color>` keeps every existing `fill(shape, color)`
4840/// call site compiling unchanged.
4841#[derive(Clone, Debug, PartialEq)]
4842pub enum Paint {
4843    Solid(Color),
4844    Linear(LinearGradient),
4845    Radial(RadialGradient),
4846}
4847
4848impl From<Color> for Paint {
4849    fn from(c: Color) -> Self {
4850        Paint::Solid(c)
4851    }
4852}
4853
4854impl From<LinearGradient> for Paint {
4855    fn from(g: LinearGradient) -> Self {
4856        Paint::Linear(g)
4857    }
4858}
4859
4860impl From<RadialGradient> for Paint {
4861    fn from(g: RadialGradient) -> Self {
4862        Paint::Radial(g)
4863    }
4864}
4865
4866/// Where `at` sits vertically. `Top`, `Middle` and `Bottom` are edges of the line box (ascent +
4867/// descent at the font's size, the box [`Toolkit::measure_text`] reports); `Baseline` is the
4868/// typographic baseline itself.
4869#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
4870pub enum TextVAlign {
4871    /// `at` is the top of the line box.
4872    #[default]
4873    Top,
4874    /// `at` is the vertical middle of the line box.
4875    Middle,
4876    /// `at` is the baseline itself: what every native 2-D text call takes, and what a run of labels
4877    /// sharing a line should align on rather than their individual boxes.
4878    Baseline,
4879    /// `at` is the bottom of the line box.
4880    Bottom,
4881}
4882
4883/// How canvas text hangs on its `at` point: one placement per axis (docs/canvas.md "Text").
4884///
4885/// Two axes rather than a list of named positions, because that is the shape of the problem and
4886/// of every native API underneath: `NSAttributedString` drawing, Pango extents,
4887/// `QFontMetricsF`, `Paint.Align`, `Canvas2D`'s `textAlign`/`textBaseline`. The alignment is done
4888/// by the backend, which is both cheaper and more accurate than doing it in app code: it already
4889/// has the laid-out metrics, where an app has to ask for them through
4890/// [`Toolkit::measure_text`] first.
4891///
4892/// [`TextAnchor::LEADING`] and [`TextAnchor::CENTERED`] name the two placements that used to be
4893/// this type's only variants.
4894#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
4895pub struct TextAnchor {
4896    /// The horizontal placement: the same three-way leading/center/trailing a wrapped label's
4897    /// lines take ([`props::TextAlign`]), because it is the same question with the same RTL rule.
4898    /// `Trailing` is what an axis label right-aligned against its axis wants, and the reason the
4899    /// horizontal axis is settable at all: emulating it in app code costs a
4900    /// [`Toolkit::measure_text`] call per label, where the backend already holds the width it is
4901    /// about to draw with.
4902    pub h: props::TextAlign,
4903    pub v: TextVAlign,
4904}
4905
4906impl TextAnchor {
4907    /// The top-leading corner of the line box, the default.
4908    pub const LEADING: TextAnchor = TextAnchor {
4909        h: props::TextAlign::Leading,
4910        v: TextVAlign::Top,
4911    };
4912    /// The center of the line box, both ways.
4913    pub const CENTERED: TextAnchor = TextAnchor {
4914        h: props::TextAlign::Center,
4915        v: TextVAlign::Middle,
4916    };
4917    /// The top-trailing corner of the line box.
4918    pub const TRAILING: TextAnchor = TextAnchor {
4919        h: props::TextAlign::Trailing,
4920        v: TextVAlign::Top,
4921    };
4922
4923    /// Where the text's top-leading corner goes, as an offset from `at`, given the line box this
4924    /// text measures to. The single definition of what an anchor means: every backend that draws
4925    /// in Rust calls this, and the C++/Java/JS shims repeat exactly this arithmetic.
4926    ///
4927    /// `height` is the line box (ascent + descent) and `ascent` the baseline's offset from its
4928    /// top, the two numbers [`TextMetrics`] carries.
4929    #[must_use]
4930    pub fn offset(self, width: f64, height: f64, ascent: f64) -> (f64, f64) {
4931        let dx = match self.h {
4932            props::TextAlign::Leading => 0.0,
4933            props::TextAlign::Center => -width / 2.0,
4934            props::TextAlign::Trailing => -width,
4935        };
4936        let dy = match self.v {
4937            TextVAlign::Top => 0.0,
4938            TextVAlign::Middle => -height / 2.0,
4939            TextVAlign::Baseline => -ascent,
4940            TextVAlign::Bottom => -height,
4941        };
4942        (dx, dy)
4943    }
4944
4945    /// The anchor as one number, for the numeric op stream the serializing backends share:
4946    /// `h * 4 + v`, so it still occupies the single slot the two-variant enum did.
4947    #[must_use]
4948    pub fn pack(self) -> f64 {
4949        f64::from(self.h as u8 * 4 + self.v as u8)
4950    }
4951
4952    /// Inverse of [`TextAnchor::pack`]. An unrecognized code answers the default rather than
4953    /// failing: a stream is only ever written by a matching encoder, and a drawing with text in
4954    /// the wrong corner beats one that panics inside a native draw callback.
4955    #[must_use]
4956    pub fn unpack(code: f64) -> TextAnchor {
4957        let c = code.round().clamp(0.0, 11.0) as u8;
4958        let h = match c / 4 {
4959            1 => props::TextAlign::Center,
4960            2 => props::TextAlign::Trailing,
4961            _ => props::TextAlign::Leading,
4962        };
4963        let v = match c % 4 {
4964            1 => TextVAlign::Middle,
4965            2 => TextVAlign::Baseline,
4966            3 => TextVAlign::Bottom,
4967            _ => TextVAlign::Top,
4968        };
4969        TextAnchor { h, v }
4970    }
4971}
4972
4973#[derive(Clone, Debug, PartialEq)]
4974pub enum DrawOp {
4975    Fill(Shape, Paint),
4976    /// Stroke `shape`. The paint may be a gradient, and [`StrokeStyle`] carries width, dash, cap
4977    /// and join; `Draw::stroke` builds the plain width-only case.
4978    Stroke(Shape, Paint, StrokeStyle),
4979    /// One line of text. `size` is absolute canvas points (no accessibility scale: canvas
4980    /// text is a label inside a drawing, docs/canvas.md); `font` picks the family, weight and
4981    /// slant, and its default is the platform's own UI face.
4982    Text {
4983        text: String,
4984        at: Point,
4985        size: f64,
4986        color: Color,
4987        anchor: TextAnchor,
4988        font: CanvasFont,
4989    },
4990    /// Draw one shape at many positions, the batched form of [`DrawOp::Fill`]/[`DrawOp::Stroke`]
4991    /// (docs/canvas.md "Stamping").
4992    ///
4993    /// Boxed because the payload is wider than the largest other op, and a bigger `DrawOp` would
4994    /// cost every op in every drawing, the exact thing this variant exists to stop paying.
4995    Stamp(Box<Stamp>),
4996    /// Draw an image into `rect` (docs/images.md).
4997    ///
4998    /// The source is a [`BitmapId`] and never bytes: a canvas re-records on every tracked read,
4999    /// so carrying a buffer here would hand the backend a megabyte to compare, and re-decode, on
5000    /// every frame. The app decodes once with `day::decode_image` and draws the handle.
5001    ///
5002    /// `opacity` multiplies the image's own alpha. A backend that cannot draw a bitmap at all
5003    /// draws nothing rather than a placeholder rectangle, the same way an unknown op is skipped.
5004    ///
5005    /// `source` is the region of the bitmap to draw, in the bitmap's own PIXELS (not points:
5006    /// [`BitmapInfo::scale`] says how many pixels make a point), `None` meaning the whole
5007    /// image. It is what lets one decoded sprite sheet serve every icon on a map: each draw
5008    /// picks its cell and scales it into `rect`. A region reaching outside the bitmap is clamped
5009    /// to it, never an error: the part inside draws where the mapping into `rect` puts it, and
5010    /// an empty intersection draws nothing. A backend without a sub-rect draw clips to `rect`
5011    /// and draws the whole image scaled so the region lands there ([`clamp_image_source`] is
5012    /// the shared arithmetic).
5013    Image {
5014        image: BitmapId,
5015        rect: Rect,
5016        opacity: f64,
5017        source: Option<Rect>,
5018    },
5019    /// Intersect the clip with `shape`; everything drawn afterwards is confined to it.
5020    ///
5021    /// Scoped by [`DrawOp::Save`]/[`DrawOp::Restore`], which is the only way to widen a clip
5022    /// again; every native 2-D context works this way, so there is no "unclip".
5023    Clip(Shape),
5024    /// Push the current transform + clip (§11, shapes). Backends map to save/restore of the
5025    /// native 2-D context; `Concat` multiplies an affine onto the CTM (shape rotate/scale/offset).
5026    Save,
5027    Restore,
5028    Concat(day_geometry::Affine),
5029}
5030
5031// ---------------------------------------------------------------------------
5032// Built-in piece descriptors: full props (realize) + sparse patches (update).
5033// One binding = one attribute = one patch value: sparseness by construction (§8.1).
5034// ---------------------------------------------------------------------------
5035
5036/// A semantic (logical) text style. Each maps to the platform's native text style where the
5037/// toolkit has one: `UIFont`/`NSFont.preferredFont(forTextStyle:)` on Apple (Dynamic Type), the
5038/// `*TextBlockStyle` resources on XAML. A Day app thus matches the OS's own typography and
5039/// inherits its accessibility text scaling with no extra work. Backends without semantic styles
5040/// (GTK/Qt/Android) approximate with sizes that still track the platform's text-scale /
5041/// font-scale accessibility setting.
5042///
5043/// The set mirrors SwiftUI `Font.TextStyle` (largest → smallest).
5044#[derive(Clone, Copy, Debug, PartialEq, Default)]
5045pub enum Font {
5046    LargeTitle,
5047    Title,
5048    Title2,
5049    Title3,
5050    Headline,
5051    Subheadline,
5052    #[default]
5053    Body,
5054    Callout,
5055    Footnote,
5056    Caption,
5057    Caption2,
5058    /// A custom point size. Backends scale it by the platform's accessibility text-scale (iOS via
5059    /// `UIFontMetrics`, Android via `sp`, GTK via text-scaling-factor) so it stays legible.
5060    System(f64),
5061    /// A bundled custom font by **family name**, at a point size (`Font::Custom("Pacifico",
5062    /// 24.0)`). The family must ship in the project's `fonts/` directory; `day build` stages the
5063    /// file into each platform's native font store and the backend registers it at startup
5064    /// (§18.4). The name is the family name baked into the font file (what Font Book /
5065    /// fontconfig report), not the file name. The size scales with the platform accessibility
5066    /// text-scale exactly like [`Font::System`]; weight/italic apply only where the family ships
5067    /// (or the platform synthesizes) such a face. An unknown family falls back to the system font
5068    /// of the same size, with a warning in the log.
5069    Custom(&'static str, f64),
5070}
5071
5072impl Font {
5073    /// A bundled custom font by **typed family**, at a point size, the checked form of
5074    /// [`Font::Custom`]. Pass a generated `res::fonts::…` constant
5075    /// (`Font::custom(res::fonts::pacifico, 24.0)`), which exists only if the family ships in the
5076    /// project's `fonts/` directory, so the font is guaranteed bundled. For a family name known
5077    /// another way, the untyped [`Font::Custom`] variant is the escape hatch.
5078    #[must_use]
5079    pub const fn custom(family: FontFamily, size: f64) -> Font {
5080        Font::Custom(family.as_str(), size)
5081    }
5082}
5083
5084/// Font weight, matching `UIFont.Weight` / SwiftUI `Font.Weight` (lightest → heaviest).
5085/// Ordered by heaviness, so backends can e.g. map `>= Semibold` to a synthesized bold face.
5086#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
5087pub enum FontWeight {
5088    UltraLight,
5089    Thin,
5090    Light,
5091    Regular,
5092    Medium,
5093    Semibold,
5094    Bold,
5095    Heavy,
5096    Black,
5097}
5098
5099impl FontWeight {
5100    /// Every rung, lightest first.
5101    pub const ALL: [FontWeight; 9] = [
5102        FontWeight::UltraLight,
5103        FontWeight::Thin,
5104        FontWeight::Light,
5105        FontWeight::Regular,
5106        FontWeight::Medium,
5107        FontWeight::Semibold,
5108        FontWeight::Bold,
5109        FontWeight::Heavy,
5110        FontWeight::Black,
5111    ];
5112
5113    /// The CSS / OpenType numeric weight (100 … 900), the one number every platform font API
5114    /// also speaks (`Typeface.create(base, weight, italic)`, `QFont::Weight`,
5115    /// `DWRITE_FONT_WEIGHT`, `OH_Drawing_FontWeight`), and what the canvas wire carries.
5116    #[must_use]
5117    pub const fn css(self) -> u16 {
5118        match self {
5119            FontWeight::UltraLight => 100,
5120            FontWeight::Thin => 200,
5121            FontWeight::Light => 300,
5122            FontWeight::Regular => 400,
5123            FontWeight::Medium => 500,
5124            FontWeight::Semibold => 600,
5125            FontWeight::Bold => 700,
5126            FontWeight::Heavy => 800,
5127            FontWeight::Black => 900,
5128        }
5129    }
5130
5131    /// The nearest rung to a CSS weight (ties round heavier, like CSS font matching); anything
5132    /// outside 100 … 900 clamps.
5133    #[must_use]
5134    pub fn from_css(n: u16) -> FontWeight {
5135        let n = n.clamp(100, 900);
5136        let idx = (usize::from(n) + 50) / 100; // 100 → 1 … 900 → 9
5137        FontWeight::ALL[idx.clamp(1, 9) - 1]
5138    }
5139
5140    /// The English face name for a rung ("Semibold"), for platforms whose enumeration names
5141    /// no face (see [`FontFace::synthesized_name`]).
5142    #[must_use]
5143    pub const fn name(self) -> &'static str {
5144        match self {
5145            FontWeight::UltraLight => "Ultra Light",
5146            FontWeight::Thin => "Thin",
5147            FontWeight::Light => "Light",
5148            FontWeight::Regular => "Regular",
5149            FontWeight::Medium => "Medium",
5150            FontWeight::Semibold => "Semibold",
5151            FontWeight::Bold => "Bold",
5152            FontWeight::Heavy => "Heavy",
5153            FontWeight::Black => "Black",
5154        }
5155    }
5156}
5157
5158/// One face a font family ships (docs/fonts.md): its display name ("Bold Italic"), weight and
5159/// slant. What [`FontFamilyInfo::faces`] lists and what a font menu's style picker offers.
5160#[derive(Clone, Debug, PartialEq, Eq)]
5161pub struct FontFace {
5162    pub name: String,
5163    pub weight: FontWeight,
5164    pub italic: bool,
5165}
5166
5167impl FontFace {
5168    /// A display name from weight + slant ("Semibold Italic") for platforms whose enumeration
5169    /// API names no face (Android's `fonts.xml`, the CSS generic families).
5170    #[must_use]
5171    pub fn synthesized_name(weight: FontWeight, italic: bool) -> String {
5172        if italic {
5173            format!("{} Italic", weight.name())
5174        } else {
5175            weight.name().to_string()
5176        }
5177    }
5178}
5179
5180/// A platform (or bundled) font family and the faces it can draw canvas text in
5181/// ([`Toolkit::font_families`], docs/fonts.md).
5182#[derive(Clone, Debug, PartialEq, Eq)]
5183pub struct FontFamilyInfo {
5184    pub family: String,
5185    pub faces: Vec<FontFace>,
5186}
5187
5188impl FontFamilyInfo {
5189    /// Whether any face is [`FontWeight::Bold`] or heavier.
5190    #[must_use]
5191    pub fn has_bold(&self) -> bool {
5192        self.faces.iter().any(|f| f.weight >= FontWeight::Bold)
5193    }
5194    /// Whether any face is italic.
5195    #[must_use]
5196    pub fn has_italic(&self) -> bool {
5197        self.faces.iter().any(|f| f.italic)
5198    }
5199    /// The nearest face: an exact slant match preferred, then the smallest weight distance
5200    /// (ties go heavier, like CSS font matching). `None` only when the family lists no faces.
5201    #[must_use]
5202    pub fn face_for(&self, weight: FontWeight, italic: bool) -> Option<&FontFace> {
5203        let want = i32::from(weight.css());
5204        self.faces.iter().min_by_key(|f| {
5205            let slant = i32::from(f.italic != italic);
5206            let dist = (i32::from(f.weight.css()) - want).abs();
5207            // Heavier wins a tie: subtracting the bool sorts the heavier face first.
5208            (slant, dist, i32::from(i32::from(f.weight.css()) < want))
5209        })
5210    }
5211}
5212
5213/// Single-line text measurement in canvas points ([`Toolkit::measure_text`], docs/fonts.md).
5214///
5215/// Two boxes, and the difference between them matters. `width`/`height` is the **line box**: the
5216/// typographic slot the text occupies, the same for every string in a face at a size, and what
5217/// [`TextAnchor`] positions. [`ink`](TextMetrics::ink) is the **ink box**: where the glyphs
5218/// put marks. A line of digits leaves the descender space of its line box empty, so the
5219/// two disagree, and which one is wanted depends on the question: laying text out in a column
5220/// wants the line box, and centering it on a rule or keeping it clear of a mark wants the ink.
5221#[derive(Clone, Copy, Debug, PartialEq)]
5222pub struct TextMetrics {
5223    /// The advance width of the whole string.
5224    pub width: f64,
5225    /// The line box: ascent + descent at this size (plus the line gap where the engine reports
5226    /// one), which is the box [`TextAnchor`] positions.
5227    pub height: f64,
5228    /// The baseline's offset from the top of the line box.
5229    pub ascent: f64,
5230    /// The face's cap height at this size: baseline to the top of a capital.
5231    ///
5232    /// A property of the font, not of this string, reported here because it is what optical
5233    /// centering needs and asking for it separately would be a second measurement. Text made of
5234    /// capitals and digits looks centered on a rule when its cap box straddles it, not its line
5235    /// box: the line box reserves descender room that digits never use, so centering by it sits
5236    /// every label a little low. The cap middle is `ascent - cap_height / 2.0` below the line
5237    /// box's top.
5238    pub cap_height: f64,
5239    /// The ink box, the tight bounds of what is drawn, with its origin relative to the line
5240    /// box's top-leading corner, so `ink.origin` is where the marks start inside the slot.
5241    ///
5242    /// Empty (zero-size) for text that draws nothing, a space included. Where a toolkit cannot
5243    /// report ink it answers the whole line box, which is a superset: an overlap test against it
5244    /// can only be too cautious, never wrong.
5245    pub ink: Rect,
5246}
5247
5248impl TextMetrics {
5249    /// The portable guess `day::measure_text` falls back to when a toolkit cannot measure:
5250    /// 0.6 × size per character, 1.2 × size tall, the baseline at 0.9 × size, caps at 0.7 × size.
5251    /// Its ink is the whole line box, the safe direction to be wrong in (see
5252    /// [`ink`](TextMetrics::ink)).
5253    #[must_use]
5254    pub fn approximate(text: &str, size: f64) -> TextMetrics {
5255        let (width, height) = (0.6 * size * text.chars().count() as f64, 1.2 * size);
5256        TextMetrics {
5257            width,
5258            height,
5259            ascent: 0.9 * size,
5260            cap_height: 0.7 * size,
5261            ink: Rect::new(0.0, 0.0, width, height),
5262        }
5263    }
5264
5265    /// Read the eight-slot form the serializing backends (qt, xaml, arkui, web) fill across their
5266    /// C ABI: advance, line height, ascent, cap height, then the ink box relative to the line
5267    /// box's top-leading corner. One definition so four shims cannot drift from each other.
5268    #[must_use]
5269    pub fn from_slots(out: &[f64; 8]) -> TextMetrics {
5270        TextMetrics {
5271            width: out[0],
5272            height: out[1],
5273            ascent: out[2],
5274            cap_height: out[3],
5275            ink: Rect::new(out[4], out[5], out[6], out[7]),
5276        }
5277    }
5278
5279    /// The line box's top-leading corner, given a baseline-relative measurement, the shape every
5280    /// backend's metrics come in. `ink_*` are relative to the drawing origin on the baseline
5281    /// (`ink_top` negative above it), the convention Skia, Core Text and Qt all report in.
5282    #[must_use]
5283    pub fn from_baseline(
5284        width: f64,
5285        ascent: f64,
5286        descent: f64,
5287        cap_height: f64,
5288        ink: Rect,
5289    ) -> TextMetrics {
5290        TextMetrics {
5291            width,
5292            height: ascent + descent,
5293            ascent,
5294            cap_height,
5295            // Baseline-relative to line-box-relative is one shift by the ascent.
5296            ink: Rect::new(
5297                ink.origin.x,
5298                ink.origin.y + ascent,
5299                ink.size.width,
5300                ink.size.height,
5301            ),
5302        }
5303    }
5304}
5305
5306/// What canvas text is drawn with beyond its size (docs/canvas.md "Text"): a family, a weight and
5307/// a slant. The default is the platform's own UI face, regular, upright, which is what every
5308/// backend drew before the field existed, so a default font encodes to nothing on the wire.
5309#[derive(Clone, Debug, PartialEq, Eq, Default)]
5310pub struct CanvasFont {
5311    /// A platform or bundled family name (as [`Toolkit::font_families`] lists it); `None` =
5312    /// the platform's default UI face.
5313    pub family: Option<String>,
5314    /// `None` = Regular.
5315    pub weight: Option<FontWeight>,
5316    pub italic: bool,
5317}
5318
5319impl CanvasFont {
5320    /// The family name to send over the wire, empty for the default.
5321    #[must_use]
5322    pub fn family_str(&self) -> &str {
5323        self.family.as_deref().unwrap_or("")
5324    }
5325    /// The CSS weight to send over the wire, 0 for the default.
5326    pub fn css_weight(&self) -> u16 {
5327        self.weight.map_or(0, FontWeight::css)
5328    }
5329}
5330
5331/// Field separator inside one family of the shim-side font list ([`parse_font_list`]).
5332pub const FONT_LIST_FIELD: char = '\u{1f}';
5333/// Family separator of the shim-side font list ([`parse_font_list`]).
5334pub const FONT_LIST_FAMILY: char = '\u{1e}';
5335
5336/// Decode the text a non-Rust font enumerator hands back (the Qt, XAML and ArkUI shims, the
5337/// Android bridge, the web shim all produce this one format): families separated by U+001E;
5338/// inside a family, U+001F-separated fields: the family name, then one (name, CSS weight,
5339/// italic `0`/`1`) triple per face. Tolerant: a malformed face or family is skipped, an empty
5340/// face name is synthesized from its weight and slant, and a family with no faces is kept
5341/// with none (the caller decides what a face-less family means).
5342pub fn parse_font_list(s: &str) -> Vec<FontFamilyInfo> {
5343    let mut out = Vec::new();
5344    for fam in s.split(FONT_LIST_FAMILY) {
5345        let mut fields = fam.split(FONT_LIST_FIELD);
5346        let Some(family) = fields.next().map(str::trim).filter(|f| !f.is_empty()) else {
5347            continue;
5348        };
5349        let rest: Vec<&str> = fields.collect();
5350        let mut faces = Vec::new();
5351        for face in rest.chunks(3) {
5352            let [name, weight, italic] = face else {
5353                continue;
5354            };
5355            let Ok(weight) = weight.trim().parse::<u16>() else {
5356                continue;
5357            };
5358            let weight = FontWeight::from_css(weight);
5359            let italic = matches!(italic.trim(), "1" | "true");
5360            let name = name.trim();
5361            let name = if name.is_empty() {
5362                FontFace::synthesized_name(weight, italic)
5363            } else {
5364                name.to_string()
5365            };
5366            if !faces
5367                .iter()
5368                .any(|f: &FontFace| f.weight == weight && f.italic == italic)
5369            {
5370                faces.push(FontFace {
5371                    name,
5372                    weight,
5373                    italic,
5374                });
5375            }
5376        }
5377        out.push(FontFamilyInfo {
5378            family: family.to_string(),
5379            faces,
5380        });
5381    }
5382    out
5383}
5384
5385/// The full font descriptor a label carries: a semantic (or custom) [`Font`] style plus an optional
5386/// weight override, an italic flag, and the tabular-figures request. Backends resolve this to one
5387/// native font.
5388#[derive(Clone, Copy, Debug, PartialEq)]
5389pub struct FontSpec {
5390    pub style: Font,
5391    pub weight: Option<FontWeight>,
5392    pub italic: bool,
5393    /// Ask for tabular (monospaced) figures: every digit takes the same advance, so a number that
5394    /// changes stops changing width.
5395    ///
5396    /// In a proportional system font `1` is narrower than `8`, so a readout beside a slider
5397    /// wobbles as the value changes even when the digit count is fixed. Every platform ships this
5398    /// as a font feature, so Day asks for the platform's own rather than substituting a monospaced
5399    /// family: the text keeps the system face, and only the digits change metrics.
5400    ///
5401    /// Reserving space (`Decorate::reserving`) and tabular figures solve the two halves of the
5402    /// same problem (reservation stops the box resizing, tabular stops the glyphs shifting inside
5403    /// it), and a numeric readout usually wants both.
5404    ///
5405    /// This rides the existing label realize/patch path rather than adding a Toolkit method, so it
5406    /// is not a backend duty and has no duty-matrix row. Every in-tree backend honors it: AppKit
5407    /// and UIKit re-pick the system face (`monospacedDigitSystemFont`), GTK and Qt and ArkUI set
5408    /// the `tnum` OpenType feature, Android `setFontFeatureSettings`, XAML the `Typography`
5409    /// `NumeralAlignment` property, and web-dom `font-variant-numeric`. A font with no `tnum` table,
5410    /// or an SDK predating the attribute, renders the stock proportional figures.
5411    pub tabular: bool,
5412    /// Ask for the platform's monospaced face at this style's size, what `` `code` `` in a
5413    /// markdown run needs (docs/text-runs.md).
5414    ///
5415    /// A flag rather than a `Font::Monospace(pt)` variant so the run keeps its semantic style:
5416    /// code inside a `Footnote` paragraph must stay footnote-sized and keep tracking the
5417    /// reader's text-size setting, which a fixed point size would throw away.
5418    ///
5419    /// Like [`Self::tabular`], this rides the label realize/patch path and is not a backend duty:
5420    /// every toolkit has a system monospace face (`monospacedSystemFont`, Pango's `monospace`
5421    /// family, `QFontDatabase::FixedFont`, `Typeface.MONOSPACE`, CSS `monospace`).
5422    pub monospace: bool,
5423    /// Multiply the resolved size. `1.0` is the style's own size, `1.6` a heading against a body
5424    /// paragraph, `0.8` a caption inside one.
5425    ///
5426    /// Relative rather than an absolute point size, so that an editor's font-size control can
5427    /// move this while text a person reads for an hour still tracks the platform's
5428    /// accessibility text-scale. `Font::System(pt)` remains the absolute escape hatch, and it
5429    /// is where an imported document's `\fs28` or `font-size: 14px` lands (docs/texteditor.md):
5430    /// faithful to the file, and no longer responsive to the reader, which is the trade that
5431    /// form makes.
5432    ///
5433    /// Three toolkits take it directly (`GtkTextTag::scale`, Android's `RelativeSizeSpan`, CSS
5434    /// `em`); the rest multiply it into the size they already compute.
5435    pub scale: f64,
5436}
5437
5438impl Default for FontSpec {
5439    fn default() -> Self {
5440        FontSpec {
5441            style: Font::Body,
5442            weight: None,
5443            italic: false,
5444            tabular: false,
5445            monospace: false,
5446            scale: 1.0,
5447        }
5448    }
5449}
5450
5451impl From<Font> for FontSpec {
5452    fn from(style: Font) -> Self {
5453        FontSpec {
5454            style,
5455            ..FontSpec::default()
5456        }
5457    }
5458}
5459
5460impl FontSpec {
5461    /// The plain descriptor for a style: no weight override, no italic, scale 1.0.
5462    pub fn new(style: Font) -> Self {
5463        FontSpec::from(style)
5464    }
5465    /// This descriptor at a different relative size (see [`FontSpec::scale`]).
5466    #[must_use]
5467    pub fn scaled(mut self, scale: f64) -> Self {
5468        self.scale = scale;
5469        self
5470    }
5471    /// The point size this descriptor resolves to, given the size the platform assigns its
5472    /// semantic style. The one place `scale` is applied, so every backend's font resolver
5473    /// multiplies the same way.
5474    #[must_use]
5475    pub fn resolved_points(&self, style_points: f64) -> f64 {
5476        let base = match self.style {
5477            Font::System(pt) | Font::Custom(_, pt) => pt,
5478            _ => style_points,
5479        };
5480        (base * self.scale).max(1.0)
5481    }
5482}
5483
5484/// One styled span of a label's text (docs/text-runs.md).
5485///
5486/// `range` is a byte range into the label's `text`. Bytes, not chars: every backend that takes a
5487/// structured attributed string wants UTF-16 or byte offsets, `str` slicing is byte-based, and a
5488/// char count would have to be converted at every boundary. Ranges must be non-overlapping and
5489/// ascending; a gap between them is unstyled text, drawn with the label's own font.
5490///
5491/// A run says only what differs. `font` is the whole descriptor rather than a delta because a
5492/// bold run inside a Body paragraph is `FontSpec { style: Body, weight: Some(Bold), .. }`. The
5493/// style has to travel with the weight or the run loses its semantic size.
5494#[derive(Clone, Debug, PartialEq)]
5495pub struct TextRun {
5496    pub range: std::ops::Range<usize>,
5497    pub font: FontSpec,
5498    pub color: Option<Color>,
5499    /// A highlight painted behind the glyphs. Every native text editor carries this attribute
5500    /// (docs/texteditor.md), and search hits and review comments are the two things an app is
5501    /// asked for the moment it has styled text at all.
5502    pub background: Option<Color>,
5503    /// A line under the text.
5504    pub underline: Underline,
5505    /// A line through the text. Separate from `FontSpec` because it is a decoration, not a face:
5506    /// no platform expresses it by picking a different font.
5507    pub strikethrough: bool,
5508    /// Makes this run a link to the given target. Rendering it is [`Cap::TextRuns`]; making it
5509    /// activatable is [`Cap::TextLinks`], which is a smaller set (see the docs).
5510    pub link: Option<String>,
5511}
5512
5513impl Default for TextRun {
5514    fn default() -> Self {
5515        TextRun {
5516            range: 0..0,
5517            font: FontSpec::default(),
5518            color: None,
5519            background: None,
5520            underline: Underline::None,
5521            strikethrough: false,
5522            link: None,
5523        }
5524    }
5525}
5526
5527impl TextRun {
5528    /// A run that only changes the font, the common case for emphasis.
5529    #[must_use]
5530    pub fn font(range: std::ops::Range<usize>, font: FontSpec) -> Self {
5531        TextRun {
5532            range,
5533            font,
5534            ..TextRun::default()
5535        }
5536    }
5537
5538    /// This run's attributes without its range: what a selection's style is compared against
5539    /// and what an editor's toolbar toggles (docs/texteditor.md).
5540    #[must_use]
5541    pub fn style(&self) -> RunStyle {
5542        RunStyle {
5543            font: self.font,
5544            color: self.color,
5545            background: self.background,
5546            underline: self.underline,
5547            strikethrough: self.strikethrough,
5548            link: self.link.clone(),
5549        }
5550    }
5551
5552    /// A run of `style` over `range`.
5553    #[must_use]
5554    pub fn styled(range: std::ops::Range<usize>, style: RunStyle) -> Self {
5555        TextRun {
5556            range,
5557            font: style.font,
5558            color: style.color,
5559            background: style.background,
5560            underline: style.underline,
5561            strikethrough: style.strikethrough,
5562            link: style.link,
5563        }
5564    }
5565}
5566
5567/// Serialize a label's text + runs as markup, for the two backends whose text widgets take a
5568/// string in their own dialect rather than a structured attributed string: GTK (Pango markup)
5569/// and Qt (its HTML subset). Shared so the escaping is written and tested once: a translated
5570/// string containing `&` or `<` corrupts the whole label otherwise, and it will be a translated
5571/// string that finds the bug.
5572///
5573/// `dialect` decides the spelling: Pango wants `<span foreground="#rrggbb"
5574/// font_family="monospace">`, Qt wants `<span style="color:#rrggbb">` with `<code>`. Both accept
5575/// `<b>`, `<i>`, `<u>`, `<s>` and `<a href>`, which is why one function can serve them.
5576///
5577/// `base_points` is the size the label itself resolved to. Only a relative-size run
5578/// ([`FontSpec::scale`]) needs it, and only in the Qt dialect: Pango markup takes a percentage
5579/// directly, while Qt's CSS subset understands `pt` and `px` and ignores `%`.
5580#[must_use]
5581pub fn runs_to_markup(
5582    text: &str,
5583    runs: &[TextRun],
5584    dialect: MarkupDialect,
5585    base_points: f64,
5586) -> String {
5587    let mut out = String::with_capacity(text.len() + runs.len() * 24);
5588    let mut at = 0usize;
5589    for r in runs {
5590        // Skip a run whose range does not address this string, without advancing `at`: dropping
5591        // the run loses styling, but advancing past it would drop the rest of the sentence.
5592        // `runs_are_valid` rejects these upstream; this keeps the failure cheap if one slips by.
5593        let Some(styled) = text.get(r.range.clone()) else {
5594            continue;
5595        };
5596        if r.range.start > at
5597            && let Some(plain) = text.get(at..r.range.start)
5598        {
5599            escape_markup_in(plain, &mut out, dialect);
5600        }
5601        open_run(r, dialect, base_points, &mut out);
5602        escape_markup_in(styled, &mut out, dialect);
5603        close_run(r, dialect, &mut out);
5604        at = r.range.end;
5605    }
5606    if let Some(tail) = text.get(at..) {
5607        escape_markup_in(tail, &mut out, dialect);
5608    }
5609    out
5610}
5611
5612impl Symbol {
5613    /// A 24×24 outline path for this symbol, Day's own drawing of it.
5614    ///
5615    /// The platform's icon comes first on every backend that has one (SF Symbols, the freedesktop
5616    /// icon theme, Fluent's glyph font). This is the fallback for when that lookup finds nothing,
5617    /// which is not an edge case: `view-filter-symbolic` exists on a GNOME desktop and nowhere
5618    /// else, so a GTK or Qt app run off that desktop drew a toolbar item with no icon at all.
5619    /// One table here means the same fallback shape everywhere instead of a gap per platform.
5620    ///
5621    /// `None` for a variant with no drawing yet: `Symbol` is `#[non_exhaustive]`, so a new one
5622    /// degrades to a label rather than failing to compile.
5623    #[must_use]
5624    pub fn outline_path(self) -> Option<&'static str> {
5625        use Symbol as S;
5626        // The wildcard is unreachable today (every variant is drawn below) and it is here for
5627        // the next one, which should degrade to a label rather than fail to compile.
5628        #[allow(unreachable_patterns)]
5629        Some(match self {
5630            S::Add => "M11 5h2v6h6v2h-6v6h-2v-6H5v-2h6z",
5631            S::Remove => "M5 11h14v2H5z",
5632            S::Delete => "M9 3h6l1 2h4v2H4V5h4zM6 8h12l-1 13H7z",
5633            S::Edit => {
5634                "M3 17.3V21h3.7L17.8 9.9l-3.7-3.7zM20.7 7a1 1 0 0 0 0-1.4l-2.3-2.3a1 1 0 0 0-1.4 0l-1.8 1.8 3.7 3.7z"
5635            }
5636            S::New => "M13 2H6v20h12V7h-5zm2 .5L19.5 7H15z",
5637            S::Open | S::Folder => "M2 5h7l2 2h11v12H2z",
5638            S::Save => "M3 3h13l5 5v13H3zm5 0h7v6H8zm-1 11h10v7H7z",
5639            S::Print => "M7 3h10v4H7zM4 8h16v8h-3v6H7v-6H4z",
5640            S::Refresh => "M12 4V1L8 5l4 4V6a6 6 0 1 1-6 6H4a8 8 0 1 0 8-8z",
5641            S::Search => {
5642                "M10 4a6 6 0 1 0 3.5 10.9l4.8 4.8 1.4-1.4-4.8-4.8A6 6 0 0 0 10 4m0 2a4 4 0 1 1 0 8 4 4 0 0 1 0-8"
5643            }
5644            S::Share => "M12 3l5 5h-3v7h-4V8H7zM5 17h14v4H5z",
5645            // An eight-tooth gear, round about the center (radius 10 at the teeth, 7.6 at the
5646            // roots) with a 3.2 hole: square in its box, so it sits in a row's 24-point icon
5647            // slot at the same size as its neighbors.
5648            S::Settings => {
5649                "M9.9 4.7L10.2 2.2L13.8 2.2L14.1 4.7A7.6 7.6 0 0 1 15.7 5.4L17.7 3.8L20.2 6.3L18.6 8.3A7.6 7.6 0 0 1 19.3 9.9L21.8 10.2L21.8 13.8L19.3 14.1A7.6 7.6 0 0 1 18.6 15.7L20.2 17.7L17.7 20.2L15.7 18.6A7.6 7.6 0 0 1 14.1 19.3L13.8 21.8L10.2 21.8L9.9 19.3A7.6 7.6 0 0 1 8.3 18.6L6.3 20.2L3.8 17.7L5.4 15.7A7.6 7.6 0 0 1 4.7 14.1L2.2 13.8L2.2 10.2L4.7 9.9A7.6 7.6 0 0 1 5.4 8.3L3.8 6.3L6.3 3.8L8.3 5.4A7.6 7.6 0 0 1 9.9 4.7zM12 8.8a3.2 3.2 0 1 0 0 6.4a3.2 3.2 0 1 0 0-6.4z"
5650            }
5651            S::Info => "M12 2a10 10 0 1 0 0 20 10 10 0 0 0 0-20m-1 5h2v2h-2zm0 4h2v6h-2z",
5652            S::Star => {
5653                "M12 2l2.9 6.3 6.9.8-5.1 4.7 1.4 6.8L12 17.3 5.9 20.6l1.4-6.8L2.2 9.1l6.9-.8z"
5654            }
5655            S::Bookmark => "M6 2h12v20l-6-4-6 4z",
5656            S::Back => "M15.4 5.4L14 4l-8 8 8 8 1.4-1.4L8.8 12z",
5657            S::Forward => "M8.6 5.4L10 4l8 8-8 8-1.4-1.4L15.2 12z",
5658            S::Up => "M5.4 15.4L4 14l8-8 8 8-1.4 1.4L12 8.8z",
5659            S::Down => "M5.4 8.6L4 10l8 8 8-8-1.4-1.4L12 15.2z",
5660            S::Home => "M12 3l9 8h-3v10h-5v-6h-2v6H6V11H3z",
5661            S::Sidebar => "M3 4h18v16H3zm2 2v12h4V6zm6 0v12h8V6z",
5662            S::Filter => "M3 5h18l-7 8v6l-4 2v-8z",
5663            S::Sort => "M8 4v12H4l4 4 4-4H10V4zM14 6h7v2h-7zm0 4h5v2h-5zm0 4h3v2h-3z",
5664            S::More => {
5665                "M6 10a2 2 0 1 0 0 4 2 2 0 0 0 0-4m6 0a2 2 0 1 0 0 4 2 2 0 0 0 0-4m6 0a2 2 0 1 0 0 4 2 2 0 0 0 0-4"
5666            }
5667            S::Play => "M8 5l11 7-11 7z",
5668            S::Pause => "M7 5h3v14H7zm7 0h3v14h-3z",
5669            S::Stop => "M6 6h12v12H6z",
5670            S::Camera => {
5671                "M9 3h6l1.5 2H20a2 2 0 0 1 2 2v12H2V7a2 2 0 0 1 2-2h3.5zm3 6a4.5 4.5 0 1 0 0 9 4.5 4.5 0 0 0 0-9m0 1.6a2.9 2.9 0 1 1 0 5.8 2.9 2.9 0 0 1 0-5.8"
5672            }
5673            S::Code => {
5674                "M9.4 16.6L4.8 12l4.6-4.6L8 6l-6 6 6 6zm5.2 0l4.6-4.6L14.6 7.4 16 6l6 6-6 6z"
5675            }
5676            S::Light => {
5677                "M12 7a5 5 0 1 0 0 10 5 5 0 0 0 0-10M11 1h2v3h-2zm0 19h2v3h-2zM1 11h3v2H1zm19 0h3v2h-3zM3.5 4.9l1.4-1.4 2.1 2.1-1.4 1.4zm13.5 13.5l1.4-1.4 2.1 2.1-1.4 1.4zM4.9 20.5l-1.4-1.4 2.1-2.1 1.4 1.4zm13.5-13.5l-1.4-1.4 2.1-2.1 1.4 1.4z"
5678            }
5679            S::Dark => "M12 3a9 9 0 1 0 9 9 7 7 0 0 1-9-9",
5680            // "Automatic": the half-filled circle every platform uses: the left half solid, the
5681            // right half an outline, which `evenodd` below turns into the ring it should be.
5682            S::Auto => "M12 2a10 10 0 0 0 0 20zM12 4a8 8 0 0 1 0 16v-1.6a6.4 6.4 0 0 0 0-12.8z",
5683            S::ZoomIn => {
5684                "M10 4a6 6 0 1 0 3.5 10.9l4.8 4.8 1.4-1.4-4.8-4.8A6 6 0 0 0 10 4M9 7h2v2h2v2h-2v2H9v-2H7V9h2z"
5685            }
5686            S::ZoomOut => {
5687                "M10 4a6 6 0 1 0 3.5 10.9l4.8 4.8 1.4-1.4-4.8-4.8A6 6 0 0 0 10 4M7 9h6v2H7z"
5688            }
5689            // The ZoomIn lens with a numeral 1 in it, "back to actual size".
5690            S::ZoomReset => {
5691                "M10 4a6 6 0 1 0 3.5 10.9l4.8 4.8 1.4-1.4-4.8-4.8A6 6 0 0 0 10 4M12 13h-1.7V9.3l-1.2.8-.9-1.3 2.4-1.8H12z"
5692            }
5693            S::Undo => "M12 5V2L7 7l5 5V9a5 5 0 1 1 0 10H8v2h4a7 7 0 0 0 0-14z",
5694            S::Redo => "M12 5V2l5 5-5 5V9a5 5 0 1 0 0 10h4v2h-4a7 7 0 0 1 0-14z",
5695            S::Copy => "M8 2h10v14H8zM4 6h2v14h12v2H4z",
5696            S::Cut => {
5697                "M9 4l5.5 9.5-1.2 2L7.8 6zM15 4L9.5 13.5l1.2 2L16.2 6zM6 16a3 3 0 1 0 0 6 3 3 0 0 0 0-6m12 0a3 3 0 1 0 0 6 3 3 0 0 0 0-6"
5698            }
5699            S::Paste => "M9 2h6v2h3v18H6V4h3zm0 2v2h6V4z",
5700            S::Mail => "M2 5h20v14H2zm2 3.2V17h16V8.2l-8 5z",
5701            S::Document => "M14 2H6v20h12V6zm.5.8L17.2 6H14.5z",
5702            S::Check => "M9 16.2L4.8 12l-1.4 1.4L9 19 21 7l-1.4-1.4z",
5703            S::Close => {
5704                "M19 6.4L17.6 5 12 10.6 6.4 5 5 6.4 10.6 12 5 17.6 6.4 19 12 13.4 17.6 19 19 17.6 13.4 12z"
5705            }
5706            S::Warning => "M12 2l10 19H2zm-1 7h2v6h-2zm0 8h2v2h-2z",
5707            // Shape outlines, stroked as a 2-unit band (an even-odd ring), so they read as
5708            // outlines at any size rather than filled blocks.
5709            S::Rectangle => "M3 5h18v14H3zm2 2v10h14V7z",
5710            S::Oval => {
5711                "M12 5c5 0 9 3.1 9 7s-4 7-9 7-9-3.1-9-7 4-7 9-7zm0 2c-3.9 0-7 2.2-7 5s3.1 5 7 5 7-2.2 7-5-3.1-5-7-5z"
5712            }
5713            // A circular ring (even-odd: outer disc minus inner) and its filled twin.
5714            S::Circle => "M12 4a8 8 0 1 0 0 16 8 8 0 0 0 0-16zm0 2a6 6 0 1 1 0 12 6 6 0 0 1 0-12z",
5715            S::CircleFilled => "M12 4a8 8 0 1 0 0 16 8 8 0 0 0 0-16z",
5716            S::Line => "M4.7 17.9l13.2-13.2 1.4 1.4L6.1 19.3z",
5717            // Group: a solid square stacked on another (the visible L of the back one);
5718            // Ungroup: the same two squares pulled apart.
5719            S::Group => "M8 4h12v12h-4V8H8zM4 8h12v12H4z",
5720            S::Ungroup => "M3 3h8v8H3zM13 13h8v8h-8z",
5721            // A crosshair: a dot in a ring with four ticks, the even-odd fill leaving the gap
5722            // between dot and ring empty.
5723            S::Location => {
5724                "M12 8a4 4 0 1 0 0 8 4 4 0 0 0 0-8m8.9 3A9 9 0 0 0 13 3.1V1h-2v2.1A9 9 0 0 0 3.1 11H1v2h2.1a9 9 0 0 0 7.9 7.9V23h2v-2.1a9 9 0 0 0 7.9-7.9H23v-2zM12 19a7 7 0 1 1 0-14 7 7 0 0 1 0 14"
5725            }
5726            // `Symbol` is `#[non_exhaustive]`: a variant added upstream draws nothing here rather
5727            // than failing to compile, and its item keeps its label.
5728            _ => return None,
5729        })
5730    }
5731
5732    /// [`Self::outline_path`] wrapped as a standalone SVG document.
5733    #[must_use]
5734    pub fn outline_svg(self) -> Option<String> {
5735        self.outline_path().map(|d| {
5736            format!(
5737                "<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 24 24\">\
5738                 <path fill-rule=\"evenodd\" d=\"{d}\"/></svg>"
5739            )
5740        })
5741    }
5742}
5743
5744/// Which markup dialect [`runs_to_markup`] should emit.
5745#[derive(Clone, Copy, Debug, PartialEq, Eq)]
5746pub enum MarkupDialect {
5747    /// Pango markup (GTK).
5748    Pango,
5749    /// Qt's rich-text HTML subset.
5750    QtHtml,
5751}
5752
5753/// XML-escape a run of plain text into `out`. `&` first, or the escapes escape each other.
5754///
5755/// Newlines are dialect-specific. Pango lays a literal `\n` out as a line break, but Qt's rich
5756/// text is HTML, where any run of whitespace collapses to one space, which silently ran a
5757/// two-paragraph body together into a single block. `<br>` is what says "break here" in HTML, so
5758/// the same string wraps the same way on both.
5759fn escape_markup_in(s: &str, out: &mut String, dialect: MarkupDialect) {
5760    for c in s.chars() {
5761        match c {
5762            '&' => out.push_str("&amp;"),
5763            '<' => out.push_str("&lt;"),
5764            '>' => out.push_str("&gt;"),
5765            '"' => out.push_str("&quot;"),
5766            '\'' => out.push_str("&#39;"),
5767            '\n' if dialect == MarkupDialect::QtHtml => out.push_str("<br>"),
5768            _ => out.push(c),
5769        }
5770    }
5771}
5772
5773/// [`escape_markup_in`] for the URL slot, where a newline cannot appear.
5774fn escape_markup(s: &str, out: &mut String) {
5775    escape_markup_in(s, out, MarkupDialect::Pango);
5776}
5777
5778fn hex(c: Color) -> String {
5779    format!(
5780        "#{:02x}{:02x}{:02x}",
5781        (c.r.clamp(0.0, 1.0) * 255.0) as u8,
5782        (c.g.clamp(0.0, 1.0) * 255.0) as u8,
5783        (c.b.clamp(0.0, 1.0) * 255.0) as u8
5784    )
5785}
5786
5787/// Does this run need a `<span>` in `dialect`, or do the plain tags cover it?
5788#[expect(
5789    clippy::float_cmp,
5790    reason = "a scale of exactly 1.0 is the unscaled default, compared as a sentinel"
5791)]
5792fn needs_span(r: &TextRun, dialect: MarkupDialect) -> bool {
5793    let extras = r.color.is_some() || r.background.is_some() || r.font.scale != 1.0;
5794    match dialect {
5795        // Pango expresses the monospace family as a span attribute; Qt cannot (see below).
5796        MarkupDialect::Pango => extras || r.font.monospace,
5797        MarkupDialect::QtHtml => extras,
5798    }
5799}
5800
5801#[expect(
5802    clippy::float_cmp,
5803    reason = "a scale of exactly 1.0 is the unscaled default, compared as a sentinel"
5804)]
5805fn open_run(r: &TextRun, dialect: MarkupDialect, base_points: f64, out: &mut String) {
5806    use std::fmt::Write as _;
5807
5808    if let Some(url) = r.link.as_deref() {
5809        out.push_str("<a href=\"");
5810        escape_markup(url, out);
5811        out.push_str("\">");
5812    }
5813    // The span carries the attributes that have no tag: colors, relative size, and (on Pango)
5814    // the monospace family. Bold/italic/strike/underline are tags in both dialects, which keeps
5815    // the attribute string short and the escaping trivial.
5816    let color = r.color.map(hex);
5817    let background = r.background.map(hex);
5818    let mono = r.font.monospace;
5819    if needs_span(r, dialect) {
5820        match dialect {
5821            MarkupDialect::Pango => {
5822                out.push_str("<span");
5823                if let Some(c) = &color {
5824                    let _ = write!(out, " foreground=\"{c}\"");
5825                }
5826                if let Some(c) = &background {
5827                    let _ = write!(out, " background=\"{c}\"");
5828                }
5829                if mono {
5830                    out.push_str(" font_family=\"monospace\"");
5831                }
5832                if r.font.scale != 1.0 {
5833                    // Absolute, in Pango units (1/1024 pt), not the `font_scale`/`size="N%"`
5834                    // pair: those are Pango 1.50 attributes, and a Pango that does not know an
5835                    // attribute fails the whole markup parse, which renders the label empty
5836                    // rather than merely unscaled. A point size still tracks the desktop's text
5837                    // scaling, since Pango resolves points through the Xft DPI.
5838                    let pts = r.font.resolved_points(base_points);
5839                    let _ = write!(out, " size=\"{}\"", (pts * 1024.0).round() as i64);
5840                }
5841                out.push('>');
5842            }
5843            MarkupDialect::QtHtml => {
5844                // Color only. Qt's rich text does not resolve the generic `monospace` family
5845                // from a style attribute (it rendered proportional), so the fixed face comes
5846                // from the `<code>` tag below, which Qt maps to its own fixed font.
5847                out.push_str("<span style=\"");
5848                if let Some(c) = &color {
5849                    let _ = write!(out, "color:{c};");
5850                }
5851                if let Some(c) = &background {
5852                    let _ = write!(out, "background-color:{c};");
5853                }
5854                if r.font.scale != 1.0 {
5855                    // Points, not a percentage: Qt's rich-text CSS subset understands `pt` and
5856                    // `px` and silently ignores `%`, which is why a scaled run rendered at the
5857                    // base size here while every other backend scaled it.
5858                    let pt = r.font.resolved_points(base_points);
5859                    let _ = write!(out, "font-size:{pt}pt;");
5860                }
5861                out.push_str("\">");
5862            }
5863        }
5864    }
5865    if dialect == MarkupDialect::QtHtml && mono {
5866        out.push_str("<code>");
5867    }
5868    if r.font.weight.is_some_and(|w| w >= FontWeight::Semibold) {
5869        out.push_str("<b>");
5870    }
5871    if r.font.italic {
5872        out.push_str("<i>");
5873    }
5874    if r.underline.is_on() {
5875        out.push_str("<u>");
5876    }
5877    if r.strikethrough {
5878        out.push_str("<s>");
5879    }
5880}
5881
5882fn close_run(r: &TextRun, dialect: MarkupDialect, out: &mut String) {
5883    if r.strikethrough {
5884        out.push_str("</s>");
5885    }
5886    if r.underline.is_on() {
5887        out.push_str("</u>");
5888    }
5889    if r.font.italic {
5890        out.push_str("</i>");
5891    }
5892    if r.font.weight.is_some_and(|w| w >= FontWeight::Semibold) {
5893        out.push_str("</b>");
5894    }
5895    if dialect == MarkupDialect::QtHtml && r.font.monospace {
5896        out.push_str("</code>");
5897    }
5898    if needs_span(r, dialect) {
5899        out.push_str("</span>");
5900    }
5901    if r.link.is_some() {
5902        out.push_str("</a>");
5903    }
5904}
5905
5906/// Are these runs well formed for `text`: ascending, non-overlapping, inside the string, and on
5907/// character boundaries?
5908///
5909/// Checked once in the pieces layer rather than in eight backends. A backend handed overlapping
5910/// ranges would produce a different wrong answer per platform, and a range splitting a multi-byte
5911/// character would panic on `str` slicing in some and render mojibake in others.
5912///
5913/// # Errors
5914///
5915/// Returns a message naming the first run that overlaps or precedes the run before it, ends
5916/// past the text, has an inverted range, or splits a multi-byte character.
5917pub fn runs_are_valid(text: &str, runs: &[TextRun]) -> Result<(), String> {
5918    let mut prev_end = 0usize;
5919    for (i, r) in runs.iter().enumerate() {
5920        if r.range.start < prev_end {
5921            return Err(format!(
5922                "run {i} starts at {} but the previous run ends at {prev_end} — runs must be \
5923                 ascending and non-overlapping",
5924                r.range.start
5925            ));
5926        }
5927        if r.range.end > text.len() {
5928            return Err(format!(
5929                "run {i} ends at {} but the text is {} bytes",
5930                r.range.end,
5931                text.len()
5932            ));
5933        }
5934        if r.range.start > r.range.end {
5935            return Err(format!("run {i} has an inverted range {:?}", r.range));
5936        }
5937        if !text.is_char_boundary(r.range.start) || !text.is_char_boundary(r.range.end) {
5938            return Err(format!(
5939                "run {i} range {:?} splits a multi-byte character",
5940                r.range
5941            ));
5942        }
5943        prev_end = r.range.end;
5944    }
5945    Ok(())
5946}
5947
5948pub mod props {
5949    use super::*;
5950
5951    #[derive(Clone, Debug, Default, PartialEq)]
5952    pub struct ContainerProps {
5953        pub background: Option<Color>,
5954        pub corner_radius: f64,
5955        pub clips: bool,
5956        /// Semantic, theme-adaptive surface, mapped by each backend to a native material that
5957        /// follows the platform's light/dark appearance automatically (unlike the fixed-RGBA
5958        /// `background`, which it overrides when set).
5959        pub role: Option<super::SurfaceRole>,
5960    }
5961    /// Reactive surface update for a `background(..)` decorator whose color is a signal/closure:
5962    /// the backend re-applies the fill on the container's native backing view. Corner radius and
5963    /// clipping are fixed at realize (the `corner_radius(r)` decorator takes a plain `f64`).
5964    #[derive(Clone, Debug, PartialEq)]
5965    pub enum ContainerPatch {
5966        Background(Option<Color>),
5967    }
5968
5969    /// Realize props for a `scroll` container: which axis it scrolls. Backends create the matching
5970    /// native scroll view (vertical `UIScrollView`/`ScrollView`, horizontal
5971    /// `HorizontalScrollView`, etc.).
5972    #[derive(Clone, Debug, Default, PartialEq)]
5973    pub struct ScrollProps {
5974        pub horizontal: bool,
5975    }
5976
5977    #[derive(Clone, Debug, Default, PartialEq)]
5978    pub struct LabelProps {
5979        pub text: String,
5980        pub font: FontSpec,
5981        pub color: Option<Color>,
5982        /// What the text means, for the color the platform gives it (docs/text.md).
5983        ///
5984        /// Semantic the way [`crate::Font`] is semantic: an app says "this is secondary text"
5985        /// and each platform answers with its own answer: `secondaryLabelColor` on Apple,
5986        /// `?android:textColorSecondary`, GTK's `dim-label`. That is the only way a de-emphasized
5987        /// label stays correct in both appearances, since a literal grey that reads well on white
5988        /// is wrong on black. An explicit [`Self::color`] still wins; a backend that has no such
5989        /// color renders primary, which is legible and correct, just not dimmed.
5990        pub role: TextRole,
5991        pub wraps: bool,
5992        /// Maximum rendered lines; zero is unlimited. Apple and Android plain labels truncate
5993        /// the last line. Other backends may retain their ordinary wrapping behavior.
5994        pub max_lines: u32,
5995        /// How the label's lines sit within its own width. Only observable on a label that
5996        /// wraps or carries explicit newlines: a single line fills its box, so its alignment is
5997        /// the container's business, not the label's.
5998        ///
5999        /// `Leading` is the default and is what running text wants; `Center` is for the short,
6000        /// centered block a welcome screen or an empty state uses. A backend that cannot set
6001        /// it renders leading-aligned, which is legible and correct, just not centered.
6002        pub align: TextAlign,
6003        /// Styled spans within `text` (docs/text-runs.md). Empty is the overwhelmingly common
6004        /// case and means exactly what a label has always meant: one font, one color. A backend
6005        /// that cannot draw runs ignores this and renders `text` uniformly, which is legible and
6006        /// correct, just unstyled.
6007        pub runs: Vec<crate::TextRun>,
6008    }
6009    /// What a label's text means, for the color the platform gives it (`LabelProps::role`).
6010    #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
6011    pub enum TextRole {
6012        /// Ordinary text, in the platform's primary label color.
6013        #[default]
6014        Primary,
6015        /// De-emphasized text: a caption, a hint, the "nothing selected" line an empty detail
6016        /// pane shows. Rendered in the platform's secondary label color.
6017        Secondary,
6018    }
6019
6020    /// How a wrapped label's lines sit within its width (`LabelProps::align`).
6021    ///
6022    /// There is no `Justified` variant because no toolkit in Day's set agrees on how to justify
6023    /// the last line, and the ones that can do it at all need a paragraph style the others have
6024    /// no equivalent for.
6025    #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
6026    pub enum TextAlign {
6027        /// Left in a left-to-right locale, right in an RTL one (docs/localization.md).
6028        #[default]
6029        Leading,
6030        Center,
6031        Trailing,
6032    }
6033
6034    #[derive(Clone, Debug, PartialEq)]
6035    pub enum LabelPatch {
6036        Text(String),
6037        Color(Option<Color>),
6038        Font(FontSpec),
6039        /// New text and its runs together. One patch, not two: a run's byte range is only
6040        /// meaningful against a particular string, so applying them separately would leave the
6041        /// widget briefly holding ranges that point into the wrong text.
6042        Runs(String, Vec<crate::TextRun>),
6043    }
6044
6045    /// A button's native styling tier. `Automatic` is the toolkit's stock look; `Bordered`
6046    /// asks for a visually contained button where the stock look is borderless (iOS's plain
6047    /// system button reads as a link); `Prominent` asks for the platform's accent-filled /
6048    /// default-action affordance. Toolkits whose stock buttons are already contained treat
6049    /// `Bordered` as `Automatic`.
6050    // `Eq` is gone with the `Tinted` color: `Color` holds floats. `PartialEq` is what the
6051    // props diff uses, and that is unaffected.
6052    #[derive(Clone, Copy, Debug, Default, PartialEq)]
6053    pub enum ButtonStyleSpec {
6054        #[default]
6055        Automatic,
6056        Bordered,
6057        Prominent,
6058        /// A filled button in an app-chosen color, still drawn by the native control: the
6059        /// platform keeps its own pressed, hover, focus and disabled rendering, its button role,
6060        /// and its keyboard activation. The label color is not carried; each backend picks the
6061        /// readable one for the fill (see [`ButtonStyleSpec::on_tint`]), the same call the
6062        /// platform's own tinted buttons make.
6063        ///
6064        /// A backend with no way to recolor its button ignores this and draws its ordinary
6065        /// button. That is the trade: a plain button everywhere beats a colored
6066        /// rectangle that is no longer a button on the platforms that cannot.
6067        Tinted(Color),
6068        /// A button no wider than its title asks for (a one-glyph "−" or "+" in a stepper,
6069        /// a "×" on a chip) on toolkits whose stock button carries a minimum width and wide
6070        /// insets (Material's 88 dp button turns a two-button stepper into 240 dp). The native
6071        /// control stays: only its minimum width and horizontal padding are reduced. A toolkit
6072        /// whose buttons already hug their title (AppKit, UIKit's plain button, Qt) draws its
6073        /// ordinary button.
6074        Compact,
6075        /// Borderless native action button; compact horizontal insets on Material.
6076        Plain,
6077    }
6078
6079    impl ButtonStyleSpec {
6080        /// The label color to draw on a [`ButtonStyleSpec::Tinted`] fill: whichever of black or
6081        /// white contrasts better against it, by WCAG's contrast ratio.
6082        ///
6083        /// Comparing the two ratios rather than thresholding the luminance is the difference
6084        /// between right and nearly right. A mid amber (`#F0A64C`) has a relative luminance of
6085        /// 0.44; under a "brighter than half" test it reads as dark and takes white text, at a
6086        /// hopeless 2.2:1. Its contrast against black is 9.7:1. The two ratios cross at a
6087        /// luminance of 0.179, not 0.5, and everything between those two numbers is a button
6088        /// nobody can read.
6089        pub fn on_tint(fill: Color) -> Color {
6090            // WCAG relative luminance: sRGB channels linearized, then weighted by the eye's
6091            // sensitivity to each.
6092            let lin = |c: f64| {
6093                let c = c.clamp(0.0, 1.0);
6094                if c <= 0.04045 {
6095                    c / 12.92
6096                } else {
6097                    ((c + 0.055) / 1.055).powf(2.4)
6098                }
6099            };
6100            let l = 0.2126 * lin(fill.r) + 0.7152 * lin(fill.g) + 0.0722 * lin(fill.b);
6101            // Contrast ratio is (lighter + 0.05) / (darker + 0.05); white is 1.0, black is 0.0.
6102            let against_white = 1.05 / (l + 0.05);
6103            let against_black = (l + 0.05) / 0.05;
6104            if against_black >= against_white {
6105                Color::BLACK
6106            } else {
6107                Color::WHITE
6108            }
6109        }
6110    }
6111
6112    #[derive(Clone, Debug, Default, PartialEq)]
6113    /// The visible content and accessible title of a button with an icon.
6114    pub struct ButtonContent {
6115        /// Also serves as the accessible name when only the icon is visible.
6116        pub title: String,
6117        pub icon: Option<Icon>,
6118        pub icon_only: bool,
6119    }
6120    #[derive(Clone, Debug, Default, PartialEq)]
6121    pub struct ButtonProps {
6122        pub title: String,
6123        pub icon: Option<Icon>,
6124        pub icon_only: bool,
6125        pub enabled: bool,
6126        pub style: ButtonStyleSpec,
6127        /// The button stands for the current choice among its siblings (a document tab, a
6128        /// view switcher): the platform's own checked or selected rendering, which keeps the
6129        /// button enabled, focusable and activatable, and tells assistive tech it is selected.
6130        /// A click never toggles it natively; only the app's next patch changes it.
6131        pub selected: bool,
6132    }
6133    #[derive(Clone, Debug, PartialEq)]
6134    pub enum ButtonPatch {
6135        Title(String),
6136        /// Update an icon button's label and icon together. Plain buttons still use `Title`.
6137        Content(ButtonContent),
6138        Enabled(bool),
6139        /// The selected state (see [`ButtonProps::selected`]).
6140        Selected(bool),
6141        /// A live style change: what a reactive `.tint(…)` sends, so a button can recolor with
6142        /// app state without being torn down and realized again.
6143        Style(ButtonStyleSpec),
6144    }
6145
6146    #[derive(Clone, Debug, Default, PartialEq)]
6147    pub struct ToggleProps {
6148        pub on: bool,
6149        pub enabled: bool,
6150    }
6151    #[derive(Clone, Debug, PartialEq)]
6152    pub enum TogglePatch {
6153        On(bool),
6154        Enabled(bool),
6155    }
6156
6157    #[derive(Clone, Debug, PartialEq)]
6158    pub struct SliderProps {
6159        pub value: f64,
6160        pub min: f64,
6161        pub max: f64,
6162        pub step: Option<f64>,
6163        pub enabled: bool,
6164    }
6165    impl Default for SliderProps {
6166        fn default() -> Self {
6167            SliderProps {
6168                value: 0.0,
6169                min: 0.0,
6170                max: 1.0,
6171                step: None,
6172                enabled: true,
6173            }
6174        }
6175    }
6176    #[derive(Clone, Debug, PartialEq)]
6177    pub enum SliderPatch {
6178        Value(f64),
6179        Enabled(bool),
6180    }
6181
6182    /// SwiftUI's `pickerStyle` analogue (`kinds::PICKER`). Each maps to a distinct native
6183    /// control per toolkit (docs/picker.md).
6184    #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
6185    pub enum PickerStyle {
6186        /// A dropdown/pop-up menu (`NSPopUpButton` / `GtkDropDown` / `QComboBox` / UIButton+UIMenu / Spinner).
6187        #[default]
6188        Menu,
6189        /// A horizontal segmented control (`NSSegmentedControl` / `UISegmentedControl` / linked toggles / …).
6190        Segmented,
6191        /// A vertical radio-button group laid out inline (`NSButton` radios / `GtkCheckButton` group / …).
6192        Inline,
6193    }
6194
6195    /// Full picker props (realize). `style` is set once at build; `options`, `selected` and
6196    /// `enabled` patch (via [`PickerPatch`]).
6197    #[derive(Clone, Debug, PartialEq)]
6198    pub struct PickerProps {
6199        /// Decorative boundaries before option indexes (not selectable options). Native menu
6200        /// grouping on AppKit/UIKit; ignored by other backends and non-menu styles.
6201        pub separators_before: Vec<usize>,
6202        pub options: Vec<String>,
6203        pub selected: usize,
6204        pub style: PickerStyle,
6205        /// Whether the picker takes input. Default `true`.
6206        pub enabled: bool,
6207    }
6208    impl Default for PickerProps {
6209        fn default() -> Self {
6210            PickerProps {
6211                separators_before: Vec::new(),
6212                options: Vec::new(),
6213                selected: 0,
6214                style: PickerStyle::default(),
6215                enabled: true,
6216            }
6217        }
6218    }
6219
6220    #[derive(Clone, Debug, PartialEq)]
6221    pub enum PickerPatch {
6222        Selected(usize),
6223        /// New option labels, for a picker whose choices come from data (a document list, a
6224        /// live count). The backend rebuilds its items and keeps the selected index where it
6225        /// still exists, clamping to the last option otherwise; a fresh
6226        /// [`PickerPatch::Selected`] follows whenever the app's own binding disagrees.
6227        Options(Vec<String>),
6228        /// Enable or disable the whole control, every style alike.
6229        Enabled(bool),
6230    }
6231
6232    /// Full text-area props (realize, `kinds::TEXT_AREA`; docs/textarea.md). `text` seeds the
6233    /// editor; `min_lines`/`max_lines` bound the auto-growing height in text lines
6234    /// (`max_lines == 0` = unbounded). `editable`/`selectable`/`spellcheck` control the native
6235    /// editor attributes (all default `true`); a backend that can't honor one answers
6236    /// `Cap::Text{Editable,Selectable,SpellCheck}` = `Unsupported`. `text` and the three attributes
6237    /// change after build (via [`TextAreaPatch`]); the rest are build-only.
6238    #[derive(Clone, Debug, PartialEq)]
6239    pub struct TextAreaProps {
6240        pub text: String,
6241        pub placeholder: String,
6242        pub min_lines: u32,
6243        pub max_lines: u32,
6244        /// Whether the user can edit the text (`false` = read-only). Default `true`.
6245        pub editable: bool,
6246        /// Whether the text can be selected (and copied). Default `true`.
6247        pub selectable: bool,
6248        /// Whether spell-check / autocorrect highlighting is on. Default `true`.
6249        pub spellcheck: bool,
6250        /// Plain Enter emits `Event::Submitted` instead of inserting a newline (Shift+Enter
6251        /// still inserts one where the platform can distinguish). Chat composers. Default
6252        /// `false`.
6253        pub submit_on_enter: bool,
6254    }
6255
6256    impl Default for TextAreaProps {
6257        fn default() -> Self {
6258            TextAreaProps {
6259                text: String::new(),
6260                placeholder: String::new(),
6261                min_lines: 1,
6262                max_lines: 0,
6263                editable: true,
6264                selectable: true,
6265                spellcheck: true,
6266                submit_on_enter: false,
6267            }
6268        }
6269    }
6270
6271    /// Imperative text-area updates: replace the text (programmatic sync), or flip one of the
6272    /// live attributes.
6273    #[derive(Clone, Debug, PartialEq)]
6274    pub enum TextAreaPatch {
6275        SetText(String),
6276        SetEditable(bool),
6277        SetSelectable(bool),
6278        SetSpellCheck(bool),
6279    }
6280
6281    #[derive(Clone, Debug, Default, PartialEq)]
6282    pub struct TextFieldProps {
6283        pub text: String,
6284        pub placeholder: String,
6285        pub enabled: bool,
6286    }
6287    #[derive(Clone, Debug, PartialEq)]
6288    pub enum TextFieldPatch {
6289        /// Origin-tagged write (§4.4): `from_native` suppresses the echo back into the widget.
6290        Text {
6291            text: String,
6292            from_native: bool,
6293        },
6294        Placeholder(String),
6295        Enabled(bool),
6296        /// Select a range of the field's text, or place the caret when the range is empty
6297        /// (docs/textfield.md "Selection"). Sent after any [`TextFieldPatch::Text`] of the same
6298        /// turn, so the range always counts the text the field now holds. A backend clamps it
6299        /// against its own text with [`TextSelection::utf16`] or [`TextSelection::bytes`] and
6300        /// applies it to a focused field; whether an unfocused field keeps it is the platform's
6301        /// (docs/textfield.md).
6302        Select(TextSelection),
6303    }
6304
6305    /// A range of a text field's text in Unicode scalar values (Rust `char`s), the unit
6306    /// [`TextFieldPatch::Select`] carries on every backend. `start..end` is half-open, and an
6307    /// empty range is a caret position. The helpers clamp to the text and convert to the unit a
6308    /// native field counts: UTF-16 code units (Apple, Android, Qt, WinUI, the web, ArkUI) or
6309    /// bytes. GTK counts characters, which is [`TextSelection::clamped`].
6310    #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
6311    pub struct TextSelection {
6312        pub start: usize,
6313        pub end: usize,
6314    }
6315
6316    impl TextSelection {
6317        /// The range from `start` to `end`, ordered so that `start <= end`.
6318        pub fn new(start: usize, end: usize) -> Self {
6319            TextSelection {
6320                start: start.min(end),
6321                end: start.max(end),
6322            }
6323        }
6324
6325        /// The range held to `text`: both ends at most its character count, `start <= end`.
6326        #[must_use]
6327        pub fn clamped(self, text: &str) -> Self {
6328            let n = text.chars().count();
6329            TextSelection::new(self.start.min(n), self.end.min(n))
6330        }
6331
6332        /// The clamped range as UTF-16 code-unit offsets into `text`: `(start, end)`.
6333        #[must_use]
6334        pub fn utf16(self, text: &str) -> (usize, usize) {
6335            let r = self.clamped(text);
6336            let at = |chars: usize| -> usize {
6337                text.chars().take(chars).map(char::len_utf16).sum::<usize>()
6338            };
6339            (at(r.start), at(r.end))
6340        }
6341
6342        /// The clamped range as UTF-8 byte offsets into `text`: `(start, end)`, each on a
6343        /// character boundary.
6344        #[must_use]
6345        pub fn bytes(self, text: &str) -> (usize, usize) {
6346            let r = self.clamped(text);
6347            let at = |chars: usize| -> usize {
6348                text.char_indices()
6349                    .nth(chars)
6350                    .map_or(text.len(), |(i, _)| i)
6351            };
6352            (at(r.start), at(r.end))
6353        }
6354    }
6355
6356    #[cfg(test)]
6357    mod text_selection_tests {
6358        use super::TextSelection;
6359
6360        #[test]
6361        fn orders_and_clamps() {
6362            assert_eq!(TextSelection::new(5, 2), TextSelection { start: 2, end: 5 });
6363            let r = TextSelection::new(3, usize::MAX).clamped("github.com");
6364            assert_eq!(r, TextSelection { start: 3, end: 10 });
6365            let past = TextSelection::new(40, 50).clamped("git");
6366            assert_eq!(past, TextSelection { start: 3, end: 3 });
6367            assert_eq!(
6368                TextSelection::new(0, 9).clamped(""),
6369                TextSelection::default()
6370            );
6371        }
6372
6373        #[test]
6374        fn converts_to_native_units() {
6375            // "é" is one char, one UTF-16 unit and two bytes; "😀" is one char, two UTF-16
6376            // units and four bytes.
6377            let text = "aé😀b";
6378            assert_eq!(TextSelection::new(1, 3).utf16(text), (1, 4));
6379            assert_eq!(TextSelection::new(1, 3).bytes(text), (1, 7));
6380            assert_eq!(TextSelection::new(0, usize::MAX).utf16(text), (0, 5));
6381            assert_eq!(TextSelection::new(0, usize::MAX).bytes(text), (0, 8));
6382            assert_eq!(TextSelection::new(4, 4).bytes(text), (8, 8));
6383        }
6384    }
6385
6386    /// How an image is scaled to fill its frame (§18.3). Maps to each toolkit's native scaling.
6387    #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
6388    pub enum ContentMode {
6389        /// Scale to fit entirely inside the frame, preserving aspect ratio (letterboxed). The
6390        /// default: an image never stretches unless asked. SwiftUI's `.scaledToFit`.
6391        #[default]
6392        Fit,
6393        /// Scale to fill the frame, preserving aspect ratio and cropping the overflow. SwiftUI's
6394        /// `.scaledToFill`.
6395        Fill,
6396        /// Stretch to fill the frame exactly, ignoring aspect ratio.
6397        Stretch,
6398    }
6399
6400    #[derive(Clone, Debug, Default, PartialEq)]
6401    pub struct ImageProps {
6402        /// Which pixels to draw: a staged asset name, encoded bytes, or an already-decoded
6403        /// image ([`ImageSource`], docs/images.md). A name resolves through the backend's own
6404        /// pipeline (§18.2); bytes and decoded ids need [`Cap::ImageDecode`], and a backend
6405        /// without it draws nothing rather than guessing.
6406        pub source: ImageSource,
6407        pub decorative: bool,
6408        /// How the image scales within its frame (default [`ContentMode::Fit`], no stretching).
6409        pub content_mode: ContentMode,
6410        /// Optional width:height ratio the view is constrained to (e.g. `16.0/9.0`). `None` lets the
6411        /// image take its allocated frame.
6412        pub aspect_ratio: Option<f64>,
6413        /// Monochrome tint for a template/vector glyph (docs/vectors.md): backends that can,
6414        /// recolor natively (template rendering on Apple, drawable tint on Android, pixel
6415        /// recolor on GTK); backends that can't yet ignore it and draw the source colors.
6416        /// `None` (the default, and every raster `image(…)`) means "as authored".
6417        pub tint: Option<Color>,
6418        /// A monochrome template glyph (docs/vectors.md "Template"): with no `tint`, it draws
6419        /// in the foreground of the surface it sits on — the theme's label color on the
6420        /// desktops, the cell's tint on UIKit, `currentColor` on the web — and follows a
6421        /// theme switch. What a sidebar row's untinted icon is: a tinted glyph recolors the
6422        /// same way with or without this, and `false` (the default) draws an untinted glyph as
6423        /// authored. [`ImagePatch::Tint`]`(None)` on a template returns to that foreground,
6424        /// not to the authored colors.
6425        pub template: bool,
6426    }
6427
6428    /// A list row's standard content (`kinds::LIST_ITEM`, docs/list.md "List items"). Empty
6429    /// text means the part is absent.
6430    #[derive(Clone, Debug, Default, PartialEq)]
6431    pub struct ListItemProps {
6432        pub title: String,
6433        /// A second line under the title, in the platform's secondary style.
6434        pub subtitle: String,
6435        /// Trailing text (a count, a value), in the platform's secondary style.
6436        pub detail: String,
6437        /// The leading glyph: a symbol or a bundled image.
6438        pub icon: Option<crate::Icon>,
6439        /// The glyph's color; `None` takes the platform's own (template glyphs follow the
6440        /// foreground, the tint color on UIKit).
6441        pub icon_tint: Option<Color>,
6442        /// A trailing check mark: the platform's selected-option mark (UIKit's checkmark
6443        /// accessory, a Material check icon), announced as checked.
6444        pub checked: bool,
6445    }
6446
6447    /// A live change to a realized list item; every part changes in place.
6448    #[derive(Clone, Debug, PartialEq)]
6449    pub enum ListItemPatch {
6450        Title(String),
6451        Subtitle(String),
6452        Detail(String),
6453        Icon(Option<crate::Icon>),
6454        IconTint(Option<Color>),
6455        Checked(bool),
6456    }
6457
6458    /// A live change to a realized image or vector glyph.
6459    ///
6460    /// `content_mode` and the rest still describe which art this is and how it fills its frame,
6461    /// which a rebuild expresses better than a patch. Two things do want to follow a signal: the
6462    /// tint (a glyph that recolors with the selection or the theme should repaint, not be torn
6463    /// down and realized again, docs/vectors.md "Tint") and the source, now that it can be a
6464    /// buffer the app swaps (a download landing, a new photo picked, docs/images.md). Replacing
6465    /// the pixels of a view that is already on screen is what a patch is for; realizing a second
6466    /// view would flash.
6467    #[derive(Clone, Debug, PartialEq)]
6468    pub enum ImagePatch {
6469        /// Recolor the glyph, or `None` to draw the authored colors again.
6470        Tint(Option<Color>),
6471        /// Draw different pixels in the same view. A backend that cannot decode the new source
6472        /// (bytes where [`Cap::ImageDecode`] is `Unsupported`) leaves what it was drawing.
6473        Source(ImageSource),
6474    }
6475
6476    #[derive(Clone, Debug, Default, PartialEq)]
6477    pub struct CanvasProps {
6478        pub ops: Vec<DrawOp>,
6479    }
6480
6481    /// Progress indicator. `value` is the completed fraction in `0.0..=1.0`; `None` means
6482    /// indeterminate (an animated spinner / busy bar, no known extent). Backends map this to
6483    /// their native determinate/indeterminate widgets (docs/progress.md).
6484    #[derive(Clone, Debug, PartialEq)]
6485    pub struct ProgressProps {
6486        pub value: Option<f64>,
6487        /// Whether an indeterminate indicator animates; ignored for a determinate bar.
6488        pub animating: bool,
6489        /// The platform's large indicator size.
6490        pub large: bool,
6491    }
6492    impl Default for ProgressProps {
6493        fn default() -> Self {
6494            Self {
6495                value: None,
6496                animating: true,
6497                large: false,
6498            }
6499        }
6500    }
6501    #[derive(Clone, Debug, PartialEq)]
6502    pub enum ProgressPatch {
6503        Animating(bool),
6504        /// New completed fraction, or `None` to switch to indeterminate.
6505        Value(Option<f64>),
6506    }
6507
6508    /// A rule between neighbors (`divider()`): a hairline across the width it is offered, or,
6509    /// with `vertical`, down the height it is offered (`divider().vertical()`, between a
6510    /// row's panes). A toolkit measures both the same way, as a horizontal rule, because the
6511    /// pieces layer swaps the axes of a vertical one's proposal and answer; realization is
6512    /// where the orientation matters, for the few widgets that draw a horizontal line
6513    /// regardless of their frame.
6514    #[derive(Clone, Debug, Default, PartialEq)]
6515    pub struct DividerProps {
6516        pub vertical: bool,
6517    }
6518
6519    /// How a navigation host lays its panes out (docs/navigation.md).
6520    ///
6521    /// This is the resolved presentation, what the toolkit must draw right now. The app asks for
6522    /// one through `Nav::presentation`, where leaving it unset means "automatic": the pieces
6523    /// layer resolves it from the window's [`SizeClass`] and the toolkit's `Cap::NavSplit`, and
6524    /// re-resolves it whenever the class changes. There is no `Auto` variant here because a
6525    /// backend can only ever draw a concrete one, so the undecided state stays on the app's side
6526    /// of the boundary where it can still be decided.
6527    #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
6528    pub enum NavPresentation {
6529        /// Sidebar beside detail, both visible (`NSSplitViewController`, nested `GtkPaned`s,
6530        /// a `NavigationView`). The sidebar pane gets its own container.
6531        Split,
6532        /// One page at a time, back-navigable. The sidebar pane becomes the stack's root.
6533        #[default]
6534        Stack,
6535        /// The rows drawn as a tab bar, one page's content beside it, no back stack: what a
6536        /// phone-shaped window wants from a one-of-N surface (`UITabBarController`, a Material
6537        /// `NavigationBarView`, `NavigationView.PaneDisplayMode = Top`). The `Pane::Sidebar` page
6538        /// is not drawn at all: its rows are the chrome.
6539        Tabs,
6540        /// The rows drawn as a narrow icon strip beside the content, the `Medium`-width answer
6541        /// between [`Self::Tabs`] and [`Self::Split`] (a Material `NavigationRailView`,
6542        /// `PaneDisplayMode = LeftCompact`, an ArkUI vertical `Tabs`).
6543        ///
6544        /// A backend with no rail rounds it to a neighbor of its own choosing rather than
6545        /// failing: UIKit answers `Tabs` (which is what iPadOS does at that width), GTK the same.
6546        /// Rounding is expected and correct; this variant is a request, not a contract.
6547        Rail,
6548    }
6549
6550    impl NavPresentation {
6551        /// `true` for [`NavPresentation::Split`], the shape most backend code wants.
6552        #[must_use]
6553        pub fn is_split(self) -> bool {
6554            self == NavPresentation::Split
6555        }
6556
6557        /// `true` when the rows are the chrome rather than a drawn page: [`Self::Tabs`] and
6558        /// [`Self::Rail`]. Both hide the `Pane::Sidebar` page and render its rows themselves, so
6559        /// backend code that only cares about that distinction asks this instead of matching both.
6560        #[must_use]
6561        pub fn rows_are_chrome(self) -> bool {
6562            matches!(self, NavPresentation::Tabs | NavPresentation::Rail)
6563        }
6564    }
6565
6566    /// Navigation host (docs/navigation.md).
6567    #[derive(Clone, Debug, Default, PartialEq)]
6568    pub struct NavProps {
6569        /// Document-tab chrome, independent of navigation destinations.
6570        pub documents: Option<DocumentTabsConfig>,
6571        pub title: String,
6572        /// The presentation to draw now; re-presented in place by [`NavPatch::Presentation`].
6573        pub presentation: NavPresentation,
6574        /// The app left the presentation automatic (`NavStyle::Automatic`, or a `Sidebar`
6575        /// nav host with no `.presentation(…)` pin), so it is free to follow the window.
6576        ///
6577        /// Only a toolkit answering `Cap::NavRepresent = Emulated` needs this: its own adaptive
6578        /// container owns the morph, and it must know whether the app asked for one at all before
6579        /// building it. With two presentations that bit could be inferred from a lowered `Split`;
6580        /// with four it cannot, so it is carried explicitly rather than encoded.
6581        ///
6582        /// `Native` re-presenters ignore it (they are told each presentation as it is resolved),
6583        /// and so do toolkits that cannot re-present.
6584        pub adaptive: bool,
6585        /// Draw the platform's own show/hide-sidebar affordance on this host's chrome
6586        /// (docs/toolbars.md). `true` for every `nav(Sidebar)` unless the app opted out:
6587        /// the toolkit owns both the button and the behavior
6588        /// (`NSToolbarToggleSidebarItemIdentifier`, the split view's collapse on GTK,
6589        /// `NavigationView.IsPaneOpen` on XAML), so an app that once declared the item by hand
6590        /// now declares nothing. Hosts with no sidebar ignore it.
6591        pub sidebar_toggle: bool,
6592        /// Search over this navigation surface (`Nav::searchable`, docs/search.md).
6593        /// `None` = the surface is not searchable and no field is rendered anywhere.
6594        pub search: Option<SearchProps>,
6595        /// `Some(width)` = this host has a content-list pane ([`Pane::List`]) at this preferred
6596        /// width in points, between the sidebar and the detail (docs/navigation.md). Read at
6597        /// realize, because a backend that builds a different container for a three-pane host
6598        /// (UIKit's triple-column style is init-only) needs to know before it builds. `None` on
6599        /// every host without one, including all of them on backends answering
6600        /// [`crate::Cap::NavContentList`] `Unsupported`: the pieces layer composes there and
6601        /// the prop is never set.
6602        pub list_width: Option<f64>,
6603        /// Whether that pane is showing for the destination the host opens on
6604        /// (`Nav::content_list_for`). Read at realize, like `list_width`, and for a
6605        /// related reason: a backend whose pane is a real split item can only honor a
6606        /// collapsed state reliably by setting it before the item joins the split. Told
6607        /// afterwards (by `NavPatch::ListVisible`, on a window that has not been displayed
6608        /// yet), AppKit reports the item collapsed and then lays it back out from its holding
6609        /// priorities, and the app opens with a list beside a page that does not own one.
6610        /// `true` on every host whose first destination has a list, and on hosts with no pane
6611        /// at all, where it means nothing.
6612        pub list_visible: bool,
6613    }
6614
6615    /// Switch only tab chrome; resident contents must retain their native identity.
6616    #[derive(Clone, Copy, Debug, PartialEq)]
6617    pub struct DocumentTabsPatch {
6618        pub native: bool,
6619    }
6620
6621    /// Localized document-tab chrome. Native callbacks emit stable route keys.
6622    #[derive(Clone, Debug, Default, PartialEq)]
6623    pub struct DocumentTabsConfig {
6624        pub new_label: String,
6625        pub close_label: String,
6626        pub can_add: bool,
6627    }
6628
6629    /// Where a searchable surface's field should be drawn.
6630    ///
6631    /// A preference, not an instruction: a backend that cannot honor the request falls back to
6632    /// whatever its platform does, exactly as SwiftUI's `searchable(placement:)` does ("depending
6633    /// on the containing view hierarchy and platform, the requested placement may not be able to
6634    /// be fulfilled"). `Automatic` is the one to reach for: it is what lets the field live in the
6635    /// window toolbar on a wide window and move into the navigation list on a narrow one.
6636    #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
6637    pub enum SearchPlacement {
6638        /// The platform decides, from the window's size class and its own convention.
6639        #[default]
6640        Automatic,
6641        /// In the window's toolbar (`NSSearchToolbarItem`, an `AdwHeaderBar` entry, a
6642        /// `CommandBar` `AutoSuggestBox`). `Inline` where the toolbar cannot hold a search field
6643        /// (`Cap::ToolbarSearch`).
6644        Toolbar,
6645        /// Attached to the navigation surface itself: above the sidebar list, or in the
6646        /// navigation bar's search drawer on the phones.
6647        Inline,
6648    }
6649
6650    /// Search over a navigation surface (docs/search.md). The query itself stays an app-owned
6651    /// signal; this carries only what the toolkit must draw, so moving the field between
6652    /// placements never moves the state.
6653    #[derive(Clone, Debug, Default, PartialEq)]
6654    pub struct SearchProps {
6655        /// Current text. Two-way: the user typing emits [`Event::SearchChanged`], and the app's
6656        /// own writes arrive as [`SearchPatch::Text`].
6657        pub text: String,
6658        /// Empty-state prompt.
6659        pub prompt: String,
6660        pub placement: SearchPlacement,
6661        /// Opt into native scrolling search/title chrome on mobile. Default false keeps
6662        /// the field pinned. Desktop toolbar search is unchanged.
6663        pub hides_on_scroll: bool,
6664        /// Start the UIKit navigation search drawer collapsed, with a compact toolbar title.
6665        /// Implies scrolling search on UIKit; ignored by other backends. Default false.
6666        pub initially_hidden: bool,
6667        /// Scope titles, empty = no scope bar. One-of-N: a `UISearchBar` scope bar, a Material
6668        /// `ChipGroup` of single-selection filter chips, an ArkUI `SegmentButtonV2`, an
6669        /// `NSSegmentedControl` (docs/search.md has the per-backend table).
6670        pub scopes: Vec<String>,
6671        /// Index into `scopes`; meaningless when `scopes` is empty.
6672        pub scope: usize,
6673        /// Completions offered for the current text. On a navigation surface these complete the
6674        /// field rather than replacing the list: the list is already the result set, so an
6675        /// overlay of results would cover the thing it is filtering.
6676        pub suggestions: Vec<String>,
6677    }
6678
6679    /// A targeted update to a live search field, the path a bound signal writes through, so
6680    /// syncing text never rebuilds (and refocuses) the field mid-word.
6681    #[derive(Clone, Debug, PartialEq)]
6682    pub enum SearchPatch {
6683        Focus,
6684        Text(String),
6685        Scope(usize),
6686        Suggestions(Vec<String>),
6687    }
6688    /// Applied to the nav host after a page child is attached / before it is removed;
6689    /// the toolkit animates its native presentation accordingly.
6690    #[derive(Clone, Debug, PartialEq)]
6691    pub enum NavPatch {
6692        /// The just-attached last page child became the top of the stack. `immersive` marks a
6693        /// page that keeps the floating transparent chrome on backends with an immersive nav
6694        /// mode (day-toolkit-material edge-to-edge today; ignored elsewhere). Unmarked pages get the
6695        /// standard opaque bar.
6696        Pushed { title: String, immersive: bool },
6697        /// The top page is about to be removed; present its predecessor.
6698        Popped,
6699        /// Current top-of-stack title changed.
6700        Title(String),
6701        /// The top page has a back guard (`NavStack::on_back`, docs/navigation.md): while `true`,
6702        /// the toolkit must not auto-pop on a native back gesture/button but route it to
6703        /// Day as `Event::NavBack { already_popped: false }` so the app's guard decides. On
6704        /// backends whose back already routes through Day (AppKit/Qt/XAML/web custom headers)
6705        /// this is a no-op; iOS disables the swipe, Android holds its callback, GTK sets the
6706        /// page `can-pop=false`, ArkUI consumes `onBackPressed`.
6707        GuardTop(bool),
6708        /// Re-present the host: the window's size class crossed a breakpoint, or the app wrote a
6709        /// new `presentation`. The page children do not change: the toolkit rebuilds its
6710        /// chrome and re-homes the pages it already has, each one landing by its
6711        /// [`NavPageProps::pane`]. Rebuilding them instead would drop scroll offsets, field
6712        /// focus, and every native animation in flight, which is why this is a patch and not
6713        /// a rebuild.
6714        ///
6715        /// Backends with no split container ignore it and stay stacked.
6716        Presentation(NavPresentation),
6717        /// Show the resident [`Pane::Detail`] page at this index, counting the host's detail
6718        /// children in attach order. The counterpart to [`Self::Pushed`]/[`Self::Popped`] for the
6719        /// presentations where pages are resident rather than stacked
6720        /// ([`NavPresentation::rows_are_chrome`]): a tab bar switches between pages that all stay
6721        /// alive, so there is nothing to push and nothing to pop.
6722        ///
6723        /// Applied without re-emitting [`crate::Event::SelectionChanged`], per the from-native
6724        /// echo rule: this is the programmatic-sync direction.
6725        ///
6726        /// A backend drawing a stacked presentation never receives it; the pieces layer sends
6727        /// push/pop there instead.
6728        Select(usize),
6729        /// Reorder resident detail pages by their previous indices without rebuilding them.
6730        Reorder(Vec<usize>),
6731        /// Show or collapse the content-list pane ([`Pane::List`]), the per-destination
6732        /// visibility switch (`Nav::content_list_for`, docs/navigation.md): a nav host
6733        /// section that spans the whole detail area (a settings page) collapses the pane, and
6734        /// selecting a list-backed section brings it back. Only sent to hosts whose
6735        /// [`NavProps::list_width`] is set. Applied directly, not through an animator proxy:
6736        /// the screenshot step captures the instant the patch returns (the sidebar-toggle rule).
6737        ListVisible(bool),
6738        /// Stacked presentations on a merged-pane backend ([`crate::Cap::NavContentList`]
6739        /// `Emulated`) only: the resident [`Pane::List`] page joins (`true`) or leaves
6740        /// (`false`) the navigation stack directly above the sidebar root. The pieces layer
6741        /// sends it as the selection gains or loses a list-backed destination; the backend
6742        /// realizes the membership change through its platform's navigation APIs (UIKit:
6743        /// `showColumn(.supplementary)` / a pop to the root; never a manual splice, which
6744        /// destroys the split's collapse bookkeeping). Never sent to `Native` backends (their
6745        /// pane persists through every presentation) nor while split.
6746        ListInStack(bool),
6747    }
6748
6749    /// Which pane of a navigation host a page belongs to (docs/navigation.md).
6750    ///
6751    /// A page's pane is a fact about the model, not about how the host currently draws it: a
6752    /// nav host's list page is [`Pane::Sidebar`] whether the toolkit is showing a sidebar beside
6753    /// a detail or stacking the two. What the presentation decides is where each pane lands:
6754    /// its own splitter pane in [`NavPresentation::Split`], the root of the stack in
6755    /// [`NavPresentation::Stack`]. Keeping the two separate is what lets a host re-present on a
6756    /// size-class change (`NavPatch::Presentation`) by re-homing the pages it already has,
6757    /// instead of tearing the tree down and rebuilding it.
6758    #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
6759    pub enum Pane {
6760        /// The list / master pane of a nav host. At most one page per host.
6761        Sidebar,
6762        /// The content-list pane between the sidebar and the detail, Mail's message list
6763        /// (`Nav::content_list`, docs/navigation.md). At most one page per host, and only
6764        /// on hosts whose [`NavProps::list_width`] is set; a backend answering
6765        /// [`crate::Cap::NavContentList`] `Unsupported` never sees one.
6766        List,
6767        /// A destination page. Every page of a `nav_stack` presentation is one of these.
6768        #[default]
6769        Detail,
6770    }
6771
6772    /// One destination's native container.
6773    #[derive(Clone, Debug, Default, PartialEq)]
6774    pub struct NavPageProps {
6775        pub title: String,
6776        pub pane: Pane,
6777    }
6778
6779    /// The largest a modal sheet grows on a desktop, in points: the window less a margin up to
6780    /// this (docs/cover.md "Modal sheet"). AppKit's native sheet and the composed card share it.
6781    pub const SHEET_MAX: crate::Size = crate::Size::new(640.0, 620.0);
6782    /// The largest a [`CoverProps::large`] sheet grows (docs/cover.md "Large sheet").
6783    pub const LARGE_SHEET_MAX: crate::Size = crate::Size::new(1040.0, 880.0);
6784
6785    /// A fullscreen cover's content container (docs/cover.md). Realized detached and hidden;
6786    /// `CoverPatch::Present` shows it over the whole window.
6787    #[derive(Clone, Debug, Default, PartialEq)]
6788    pub struct CoverProps {
6789        /// Prefer a native sheet; toolkits without sheet presentation keep their modal cover.
6790        pub sheet: bool,
6791        /// A half-height sheet rising from the bottom edge, the window content above it
6792        /// staying on show and, where the platform allows, interactive: an inspector over the
6793        /// canvas it describes. Implies `sheet`. The toolkit reports the sheet's own content
6794        /// size through `FrameChanged`, as for any cover (docs/cover.md "Half sheet").
6795        pub half: bool,
6796        /// A large sheet: most of the window, less a margin, for a document or web page that
6797        /// needs the room (docs/cover.md "Large sheet"). Implies `sheet`.
6798        pub large: bool,
6799    }
6800
6801    /// Applied to a `kinds::COVER` node as its bound signal opens and closes it.
6802    #[derive(Clone, Debug, PartialEq)]
6803    pub enum CoverPatch {
6804        /// Present the cover fullscreen (slide up where the platform animates modals).
6805        /// `background` paints the whole surface edge-to-edge (under the status bar / home
6806        /// indicator); the content container is inset to the safe area within it.
6807        /// `dismiss_disabled` = the user must not be able to dismiss it interactively
6808        /// (system back / sheet gestures); programmatic dismissal still works.
6809        Present {
6810            background: Option<Color>,
6811            dismiss_disabled: bool,
6812        },
6813        /// The `interactive_dismiss_disabled` state changed while presented.
6814        DismissDisabled(bool),
6815        /// Dismiss the cover. When the hide transition finishes the backend emits
6816        /// [`crate::Event::CoverHidden`] on the node (trampoline backends send
6817        /// `BridgeKind::CoverHidden`), letting the piece dispose the content only after it
6818        /// left the screen.
6819        Dismiss,
6820    }
6821
6822    /// A `kinds::INSPECTOR` split (docs/inspector.md): content beside a trailing inspector
6823    /// pane. The pane's visibility is Day-owned state (the piece's bound signal), so the
6824    /// props carry the value to draw and [`InspectorPatch::Visible`] keeps it current;
6825    /// a native affordance hiding the pane (a dock close button, a dragged-shut divider)
6826    /// reports back with [`crate::Event::InspectorChanged`].
6827    #[derive(Clone, Debug, PartialEq)]
6828    pub struct InspectorProps {
6829        /// Whether the pane is showing now.
6830        pub visible: bool,
6831        /// The pane's preferred width in points. A backend with a user-draggable divider
6832        /// treats it as the initial width; one without draws it at exactly this.
6833        pub width: f64,
6834        /// Which side of the content the pane sits on. `Trailing` is the classic inspector;
6835        /// `Leading` is a utility pane like a layer panel (docs/tree.md).
6836        pub edge: PaneEdge,
6837    }
6838
6839    /// Which side an inspector pane occupies (docs/inspector.md).
6840    #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
6841    pub enum PaneEdge {
6842        #[default]
6843        Trailing,
6844        Leading,
6845    }
6846
6847    /// Applied to a `kinds::INSPECTOR` node as its bound signal changes.
6848    #[derive(Clone, Debug, PartialEq)]
6849    pub enum InspectorPatch {
6850        /// Show or hide the pane (animated where the platform animates panes). The
6851        /// programmatic-sync direction: applying it must not re-emit
6852        /// [`crate::Event::InspectorChanged`], per the from-native echo rule.
6853        Visible(bool),
6854    }
6855
6856    /// One pane of a `kinds::INSPECTOR` split (docs/inspector.md).
6857    #[derive(Clone, Debug, Default, PartialEq)]
6858    pub struct InspectorPaneProps {
6859        /// `true` for the inspector panel itself, `false` for the content pane.
6860        pub panel: bool,
6861    }
6862
6863    /// How a `kinds::SPLIT` lays its two panes (docs/split.md): beside each other, the divider
6864    /// standing, or stacked, the divider lying. Named by where the panes go, since that is
6865    /// what an app's "layout" toggle means; the divider runs the other way.
6866    #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
6867    pub enum SplitAxis {
6868        /// The panes side by side (first leading), the divider vertical.
6869        #[default]
6870        Horizontal,
6871        /// The panes stacked (first on top), the divider horizontal.
6872        Vertical,
6873    }
6874
6875    /// A `kinds::SPLIT` (docs/split.md): two panes with a divider the user drags. The first
6876    /// pane's share is Day-owned state (the piece's bound signal): the props carry the value
6877    /// to draw, [`SplitPatch::Fraction`] keeps it current, and a divider the user moved
6878    /// reports back as [`crate::Event::ValueChanged`] with the new share, which applying the
6879    /// patch must never re-emit (the from-native echo rule).
6880    #[derive(Clone, Debug, PartialEq)]
6881    pub struct SplitProps {
6882        pub axis: SplitAxis,
6883        /// The first pane's share of the split's length along `axis`, `0.0..=1.0`.
6884        pub fraction: f64,
6885        /// The least length either pane may be dragged to, in points.
6886        pub min_pane: f64,
6887    }
6888
6889    /// Applied to a `kinds::SPLIT` node as its bound signals change.
6890    #[derive(Clone, Debug, PartialEq)]
6891    pub enum SplitPatch {
6892        /// Turn the split the other way, keeping the share.
6893        Axis(SplitAxis),
6894        /// Move the divider so the first pane takes this share. The programmatic-sync
6895        /// direction: applying it must not re-emit [`crate::Event::ValueChanged`].
6896        Fraction(f64),
6897    }
6898
6899    /// One pane of a `kinds::SPLIT` (docs/split.md).
6900    #[derive(Clone, Debug, Default, PartialEq)]
6901    pub struct SplitPaneProps {
6902        /// `false` for the first pane, `true` for the second.
6903        pub second: bool,
6904    }
6905
6906    /// Native navigation item list. `items` are display titles in route order;
6907    /// `selected` highlights the active route (split presentation; None on mobile roots).
6908    /// `icons` (parallel to `items`, `None` = no icon) are bundled image names resolved by each
6909    /// backend via `resource::resolve_image_file`; a backend that can't decorate its rows just
6910    /// ignores them.
6911    #[derive(Clone, Debug, Default, PartialEq)]
6912    pub struct NavMenuProps {
6913        /// Stable document identities, parallel to items; empty for ordinary navigation.
6914        pub document_keys: Vec<String>,
6915        pub items: Vec<String>,
6916        pub icons: Vec<Option<String>>,
6917        /// A trailing accessory per row: an unread count, a status. Rendered right-aligned and
6918        /// de-emphasized, opposite the label. Parallel to `items`; `None` draws nothing.
6919        pub badges: Vec<Option<String>>,
6920        /// A trailing symbol accessory per row, in the same slot as [`Self::badges`] and drawn
6921        /// after it: a bundled image name resolved the way [`Self::icons`] is. This is what a
6922        /// row-level status glyph rides on (a starred page's star) where `badges` carries only
6923        /// text. Parallel to `items`; `None` draws nothing.
6924        pub badge_icons: Vec<Option<String>>,
6925        /// The tint for [`Self::badge_icons`], parallel to `items`. `None` leaves the glyph at
6926        /// the backend's neutral template tint; a status glyph that means something (a yellow
6927        /// star) names its own color here, exactly as [`Self::tints`] does for the leading icon.
6928        pub badge_tints: Vec<Option<Color>>,
6929        /// A per-row icon tint (docs/vectors.md): the row's glyph recolored to this instead of
6930        /// the backend's neutral template tint. Parallel to `items`; `None` keeps the default.
6931        pub tints: Vec<Option<Color>>,
6932        /// A section header introducing the row at the same index. `Some` opens a new group
6933        /// before that row; `None` continues the current one. Parallel to `items`, so adding a
6934        /// header never shifts the selection indices the rows are addressed by.
6935        pub sections: Vec<Option<String>>,
6936        /// A per-row context menu (docs/menus.md): shown on secondary-click / long-press on
6937        /// that row, the same [`crate::MenuItem`] model as everywhere else: items carry
6938        /// registered action ids, so a chosen entry dispatches [`crate::Event::MenuAction`]
6939        /// exactly like a piece context menu. Parallel to `items`; empty = no menu.
6940        pub menus: Vec<Vec<crate::MenuItem>>,
6941        /// Which rows drag to reorder (docs/navigation.md "Reordering sidebar destinations"),
6942        /// parallel to `items`; empty when the sidebar does not reorder. A row moves only
6943        /// within the run of movable rows around it, which a section header or a fixed row
6944        /// ends. A toolkit whose `Cap::NavReorder` is `Native` drags the rows in its own
6945        /// sidebar and reports a drop as [`crate::Event::ListReorder`] in item indices: `from`
6946        /// is the moved row, `to` the row whose position it takes, in the order before the move.
6947        pub movable: Vec<bool>,
6948        /// The sidebar regroups (docs/navigation.md "Moving rows between sections"): a movable
6949        /// row may also cross section headers, into any section whose rows are all movable. A
6950        /// toolkit whose `Cap::NavReorder` is `Native` offers those drops too and reports every
6951        /// drop as [`crate::Event::NavRegroup`] instead of [`crate::Event::ListReorder`]. `false`
6952        /// keeps [`Self::movable`]'s run rule.
6953        pub regroup: bool,
6954        /// Which movable rows keep the app's sorted order within their own section, parallel to
6955        /// `items`; empty when the sidebar does not regroup. Under [`Self::regroup`], a sorted
6956        /// row drops only into another section: no gap in its own section is offered.
6957        pub sorted: Vec<bool>,
6958        pub selected: Option<usize>,
6959    }
6960    #[derive(Clone, Debug, PartialEq)]
6961    // `Items` carries every row array; a patch travels boxed (`Box<dyn Any>`) and lives for one
6962    // update, so the variants' size difference costs nothing worth an indirection.
6963    #[allow(clippy::large_enum_variant)]
6964    pub enum NavMenuPatch {
6965        /// Active icon overlays by row index: None spins, Some(0..=1) fills a circle.
6966        /// Rows absent from this complete snapshot have no overlay. Does not relayout rows.
6967        /// Currently rendered by AppKit/UIKit; other backends may ignore this decoration.
6968        IconProgress(Vec<(usize, Option<f64>)>),
6969        /// Programmatic highlight sync: toolkits apply without re-emitting
6970        /// `SelectionChanged` (the `TextField` `from_native` echo rule).
6971        Selected(Option<usize>),
6972        /// The item set changed (data-driven `nav().items(signal, …)`): rebuild the rows
6973        /// from these labels/icons, then apply `selected` (docs/navigation.md). Applied without
6974        /// re-emitting `SelectionChanged`.
6975        ///
6976        /// `rows_changed` is `Some` when the rows themselves are the ones already shown (same
6977        /// keys, sections and row menus) and only these rows' title, icon, tint or badge moved:
6978        /// a count ticking, a language change. A backend updates those rows in place (a tab's
6979        /// badge, a menu item's title) rather than rebuilding, which on most platforms re-lays
6980        /// the bar and replays its selection animation; one that cannot rebuilds as for `None`.
6981        Items {
6982            rows_changed: Option<Box<[usize]>>,
6983            document_keys: Box<[String]>,
6984            items: Vec<String>,
6985            icons: Vec<Option<String>>,
6986            badges: Vec<Option<String>>,
6987            badge_icons: Vec<Option<String>>,
6988            badge_tints: Vec<Option<Color>>,
6989            sections: Vec<Option<String>>,
6990            tints: Vec<Option<Color>>,
6991            menus: Vec<Vec<crate::MenuItem>>,
6992            /// [`NavMenuProps::movable`] for the new rows.
6993            movable: Vec<bool>,
6994            /// [`NavMenuProps::sorted`] for the new rows ([`NavMenuProps::regroup`] holds for
6995            /// the sidebar's life).
6996            sorted: Vec<bool>,
6997            selected: Option<usize>,
6998        },
6999    }
7000
7001    /// How a recycling list sizes its rows (docs/list.md).
7002    #[derive(Clone, Copy, Debug, PartialEq, Default)]
7003    pub enum RowHeight {
7004        /// Every row is this tall, a true layout boundary; the fastest path.
7005        Uniform(f64),
7006        /// Rows self-size from their content (host re-measures on change; slower).
7007        #[default]
7008        Automatic,
7009    }
7010
7011    /// Configure a navigation sidebar's native pull-to-refresh control. Not a synthetic pan:
7012    /// supported toolkits own gesture arbitration and the progress indicator. A false state
7013    /// ends a pull, including a request the application declines. Never emits an event.
7014    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
7015    pub struct RefreshPatch {
7016        pub refreshing: bool,
7017    }
7018
7019    /// Native recycling list (docs/list.md). The host owns scrolling + cell reuse; Day supplies
7020    /// row content on demand through the injected `ListSource` (see `Toolkit::attach_list`).
7021    #[derive(Clone, Debug, Default, PartialEq)]
7022    pub struct ListProps {
7023        /// Whether the app handles row activation. Do not claim activation keys when false.
7024        pub activatable: bool,
7025        pub row_height: RowHeight,
7026        /// Whether the native list reports row selection (`Event::SelectionChanged` with the row).
7027        pub selectable: bool,
7028        /// Whether the native list allows selecting several rows at once. Where honored
7029        /// (docs/list.md has the matrix), every selection change reports the full set via
7030        /// `Event::SelectionSet`; single-selection backends keep reporting
7031        /// `Event::SelectionChanged` and treat this as `selectable`.
7032        pub multi_select: bool,
7033        /// Whether rows can be drag-reordered. The toolkit enables its native drag machinery and
7034        /// drives `ListSource::reorder` (validate via `can_move`, commit via `move_row`);
7035        /// probe `Cap::ListReorder` for per-backend support (docs/list.md).
7036        pub reorderable: bool,
7037        /// Whether rows can be deleted by the platform's own delete gesture: a trailing swipe on
7038        /// iOS and ArkUI, an `ItemTouchHelper` swipe on Android. The toolkit drives
7039        /// `ListSource::delete` (offer via `can_delete`, commit via `delete_row`); probe
7040        /// `Cap::ListDelete` for per-backend support (docs/list.md). Desktop toolkits have no such
7041        /// gesture and answer `Unsupported`; an app that must delete everywhere pairs this with an
7042        /// explicit control (a menu item, a button) rather than relying on the swipe.
7043        pub deletable: bool,
7044        /// The label on that affordance, already localized by the app. A toolkit cannot invent
7045        /// translated text (it has no access to the app's catalog), so the string arrives with
7046        /// the props. Empty means "no text": each backend falls back to its platform's own
7047        /// wordless idiom (a trash glyph), which works in every language.
7048        pub delete_label: String,
7049        /// The rows offer edge swipe actions (docs/list.md) through the injected
7050        /// `ListSource::swipe` (offer via `actions_at`, commit via `perform`); probe
7051        /// [`crate::Cap::ListSwipeActions`] for per-backend support. A backend without the
7052        /// affordance never shows one; an app that must offer the command everywhere
7053        /// pairs the swipe with an explicit control, exactly as `deletable` documents.
7054        pub swipe_actions: bool,
7055        /// Row separators, drawn by the host at the row boundary (docs/list.md), so they
7056        /// align with the native selection and ride the platform's own row animations (a
7057        /// macOS/iOS swipe slides the row content past a stationary separator, exactly as
7058        /// Mail's does). `None` keeps each platform's own default (iOS draws them, the
7059        /// desktops don't); `Some(true)`/`Some(false)` forces. A backend without a separator
7060        /// mechanism ignores a force (the matrix in docs/list.md says which); rows there
7061        /// separate by their pitch alone.
7062        pub separators: Option<bool>,
7063        /// The list starts in the platform's editing mode (docs/list.md): delete controls on
7064        /// the rows `deletable` offers, reorder grips on the rows `reorderable` moves, and a
7065        /// tap that still activates. Later changes arrive as [`ListPatch::Editing`]. Probe
7066        /// [`crate::Cap::ListEditing`]; a backend without an editing mode ignores it.
7067        pub editing: bool,
7068        /// The rows fall into sections, each opened by a header row (docs/list.md
7069        /// "Sections"): `ListSource::is_header` says which rows. Probe
7070        /// [`crate::Cap::ListSections`] for whether headers float natively.
7071        pub sections: bool,
7072        /// Draw the rows as the platform's inset grouped list (docs/list.md "Appearance"):
7073        /// rounded groups set in from the edges on a grouped background, as iOS Settings and
7074        /// Safari's History draw them. ios-uikit (`UITableViewStyleInsetGrouped`) and
7075        /// macos-appkit (`NSTableViewStyleInset`); the other toolkits draw their plain list.
7076        pub inset_grouped: bool,
7077    }
7078
7079    /// One row-level result-set change. Indexes are sequential (each delta describes the
7080    /// set as the previous ones left it), so a host applies them one at a time (or falls back
7081    /// to a reload; the source's snapshot already holds the final state either way).
7082    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
7083    pub enum RowDelta {
7084        Insert(usize),
7085        Remove(usize),
7086        Move(usize, usize),
7087    }
7088
7089    /// Immutable-at-realize props of a `kinds::TREE` host (docs/tree.md). Everything that
7090    /// changes after realize flows through [`TreePatch`] or the injected `TreeSource`.
7091    #[derive(Clone, Debug, PartialEq)]
7092    pub struct TreeProps {
7093        /// Two-level sectioned list: root branches are non-selectable headings.
7094        pub section_headers: bool,
7095        pub row_height: RowHeight,
7096        /// Rows highlight and report selection ([`crate::Event::TreeSelection`]).
7097        pub selectable: bool,
7098        /// Several rows may be selected at once; every change reports the full token set.
7099        pub multi_select: bool,
7100        /// Rows drag to a new parent/position through the platform's own mechanism, driving
7101        /// `TreeSource::moves`. Probe [`crate::Cap::TreeMove`] for support.
7102        pub movable: bool,
7103        /// Indentation per depth level, in points. `None` = the platform's default step.
7104        pub indent: Option<f64>,
7105    }
7106
7107    /// Post-realize changes to a `kinds::TREE` host (docs/tree.md). Token-addressed
7108    /// throughout; see [`crate::TreeSource`] for why indices cannot address tree rows.
7109    #[derive(Clone, Debug, PartialEq)]
7110    pub enum TreePatch {
7111        /// The node set changed (count/order/parentage/content): the host re-queries its
7112        /// `TreeSource`. Expansion and selection survive by token (docs/tree.md).
7113        Reload,
7114        /// Programmatically disclose (`true`) or collapse (`false`) one row. Applied without
7115        /// re-emitting [`crate::Event::TreeExpanded`] (the from-native echo rule).
7116        Expand(u64, bool),
7117        /// Programmatic selection sync (tokens; empty = clear), applied without re-emitting
7118        /// [`crate::Event::TreeSelection`].
7119        Selected(Vec<u64>),
7120        /// Scroll this row into view, realizing it if needed. The piece has already expanded
7121        /// the row's ancestors (through the app's expansion signal) before issuing this.
7122        Reveal(u64),
7123    }
7124
7125    #[derive(Clone, Debug, PartialEq)]
7126    pub enum ListPatch {
7127        /// The row set changed (count/order/content): the host re-queries its `ListSource`.
7128        Reload,
7129        /// The row set changed by exactly these deltas: a host that can, animates each row
7130        /// in, out, or across; one that cannot treats this as [`ListPatch::Reload`]. The
7131        /// data source answers with the final state throughout.
7132        Splice(Vec<RowDelta>),
7133        /// An `Automatic`-height row was re-laid at a new height after its first layout (its
7134        /// text changed, a wrapped line appeared, the backend corrected its width): the host
7135        /// gives the row bound to physical cell `cell` (the handle `ListSource::bind_row` got,
7136        /// as `usize`) the new `height`, padding included, the same value
7137        /// `ListSource::cell_height` now answers for it.
7138        ///
7139        /// Sent from inside a day-core layout pass, with the tree borrowed: a host applies it
7140        /// after the pass (posted to its main loop), never by asking the source anything
7141        /// synchronously, which would read a `0.0` height (docs/list.md "Row heights").
7142        RowSizeInvalidated { cell: usize, height: f64 },
7143        /// Imperatively scroll the native list so its last row is fully visible (a chat timeline
7144        /// sticking to the newest message). No-op when the list is empty (docs/list.md).
7145        ScrollToEnd,
7146        /// Imperatively scroll the native list so this row is visible, realizing it if needed
7147        /// (docs/list.md). Clamped to the row count; no-op when the list is empty.
7148        ScrollToRow(usize),
7149        /// Programmatic selection sync (row indices; empty = clear): toolkits apply without
7150        /// re-emitting a selection event, like every other programmatic sync.
7151        Selected(Vec<usize>),
7152        /// Enter (`true`) or leave (`false`) the platform's list editing mode, animated
7153        /// (docs/list.md, [`ListProps::editing`]). Ignored where `Cap::ListEditing` is
7154        /// `Unsupported`.
7155        Editing(bool),
7156    }
7157}
7158
7159// ---------------------------------------------------------------------------
7160// Imperative presentation (docs/dialogs.md)
7161// ---------------------------------------------------------------------------
7162
7163/// Sharing (docs/sharing.md): what [`Toolkit::share`] presents.
7164pub mod share {
7165    use crate::Symbol;
7166
7167    /// A share request: the page or link to share, and the app's own actions to offer beside
7168    /// the system's targets.
7169    #[derive(Clone, Debug, Default, PartialEq)]
7170    pub struct ShareSpec {
7171        /// The URL handed to the chosen target.
7172        pub url: String,
7173        /// Its title: the subject of a mail, the header of the chooser where it shows one.
7174        pub title: String,
7175        /// The app's actions, in order (`Cap::ShareActions`).
7176        pub actions: Vec<ShareAction>,
7177    }
7178
7179    /// One of the app's actions in a share chooser.
7180    #[derive(Clone, Debug, PartialEq)]
7181    pub struct ShareAction {
7182        /// The dispatch id a choice reports, as `Event::MenuAction(id)`.
7183        pub id: u64,
7184        /// The action's name, already localized.
7185        pub title: String,
7186        /// Its glyph, where the chooser draws one.
7187        pub symbol: Option<Symbol>,
7188    }
7189}
7190
7191pub mod present {
7192    /// A dialog button's semantic role: styling + default/cancel placement on each toolkit.
7193    #[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
7194    pub enum ButtonRole {
7195        #[default]
7196        Default,
7197        Cancel,
7198        Destructive,
7199    }
7200
7201    #[derive(Clone, Debug, PartialEq)]
7202    pub struct PresentButton {
7203        pub label: String,
7204        pub role: ButtonRole,
7205    }
7206
7207    /// A named group of file extensions for a file dialog (e.g. "Text" → `["txt", "md"]`).
7208    /// An empty `extensions` list means "all files".
7209    #[derive(Clone, Debug, PartialEq, Default)]
7210    pub struct FileFilter {
7211        pub name: String,
7212        pub extensions: Vec<String>,
7213    }
7214
7215    /// What a backend should present for a `req`. Kept toolkit-agnostic; the pieces layer
7216    /// maps a chosen button index back to a typed payload.
7217    #[derive(Clone, Debug, PartialEq)]
7218    pub enum PresentSpec {
7219        /// Alert / confirmation / action sheet: title + optional message + ordered buttons.
7220        /// `sheet` = present from the bottom on mobile (desktop falls back to an alert).
7221        Dialog {
7222            title: String,
7223            message: Option<String>,
7224            buttons: Vec<PresentButton>,
7225            sheet: bool,
7226        },
7227        /// A dialog with a single text field.
7228        Prompt {
7229            title: String,
7230            message: Option<String>,
7231            placeholder: String,
7232            initial: String,
7233            ok: String,
7234            cancel: String,
7235        },
7236        /// Native "open file" picker (docs/files.md). The backend must answer with
7237        /// `PresentResult::Files` whose entries are **readable local paths**: desktop returns
7238        /// the chosen path directly; iOS/Android copy the selection into app storage first, so
7239        /// the pieces layer can read it with `std::fs` regardless of platform. `multiple` lets
7240        /// the user pick several files at once; the answer then carries every chosen path, in
7241        /// the picker's order. A backend that cannot select more than one file still answers
7242        /// with the single pick.
7243        OpenFile {
7244            title: String,
7245            filters: Vec<FileFilter>,
7246            multiple: bool,
7247        },
7248        /// Native "choose folder" picker (docs/files.md). The backend answers with
7249        /// `PresentResult::Files` holding the one chosen directory path, or `Dismissed`. Only
7250        /// backends answering [`Cap::FolderDialog`](crate::Cap::FolderDialog) as `Native` show a
7251        /// chooser; the others resolve the request as `Dismissed` at once, so the await never hangs.
7252        OpenFolder { title: String },
7253        /// Native "save file" picker (docs/files.md). `src_path` is a Day-written temp file
7254        /// holding the bytes to save; iOS/Android deliver it to the chosen destination natively,
7255        /// and the pieces layer best-effort copies it to a chosen local path otherwise.
7256        SaveFile {
7257            title: String,
7258            suggested_name: String,
7259            src_path: String,
7260            filters: Vec<FileFilter>,
7261        },
7262    }
7263
7264    /// The user's answer to a presentation.
7265    #[derive(Clone, Debug, PartialEq)]
7266    pub enum PresentResult {
7267        /// A dialog button at `index` (in spec order) was chosen.
7268        Button(i64),
7269        /// A prompt was confirmed with `text`.
7270        Text(String),
7271        /// One or more file locators chosen from an open/save picker (docs/files.md). Each is a
7272        /// local filesystem path or, on Android save, a `content://` URI.
7273        Files(Vec<String>),
7274        /// Dismissed without choosing (tap-outside / Esc / cancel gesture).
7275        Dismissed,
7276    }
7277
7278    /// The unit-separator that joins string lists across the C ABI (Qt shim / Android JNI), the
7279    /// same encoding the nav menu, combobox, and dialog-button shims use.
7280    pub const UNIT_SEP: char = '\u{1f}';
7281
7282    std::thread_local! {
7283        /// An app-writable scratch directory. Backends whose OS temp dir isn't app-writable
7284        /// (Android → `getCacheDir()`) set this at startup; elsewhere it stays `None` and callers
7285        /// fall back to `std::env::temp_dir()`.
7286        // False positive, and only when checking an android target: the initializer already is
7287        // the `const` block the lint asks for. Android's TLS model makes the macro expand to a
7288        // form clippy reads as lazy, so the suggestion is unfollowable as well as unneeded.
7289        #[allow(clippy::missing_const_for_thread_local)]
7290        static APP_TEMP_DIR: std::cell::RefCell<Option<std::path::PathBuf>> =
7291            const { std::cell::RefCell::new(None) };
7292    }
7293
7294    /// Record an app-writable scratch directory (see [`app_temp_dir`]). Called by a backend at
7295    /// startup when the OS temp dir isn't writable by the app (Android).
7296    pub fn set_app_temp_dir(dir: impl Into<std::path::PathBuf>) {
7297        APP_TEMP_DIR.with(|d| *d.borrow_mut() = Some(dir.into()));
7298    }
7299
7300    /// An app-writable scratch directory: the backend-supplied one, else `std::env::temp_dir()`.
7301    /// Used by the file-save flow (docs/files.md) to stage bytes before the native save picker.
7302    #[must_use]
7303    pub fn app_temp_dir() -> std::path::PathBuf {
7304        APP_TEMP_DIR.with(|d| {
7305            d.borrow().clone().unwrap_or_else(|| {
7306                #[cfg(target_arch = "wasm32")]
7307                {
7308                    // A browser has no filesystem and std's `temp_dir()` panics on wasm. A
7309                    // nominal path keeps join/display plumbing alive; actual reads and writes
7310                    // fail with ordinary io errors the file flows already surface.
7311                    std::path::PathBuf::from("/day-tmp")
7312                }
7313                #[cfg(not(target_arch = "wasm32"))]
7314                std::env::temp_dir()
7315            })
7316        })
7317    }
7318
7319    /// The web build's file bytes (wasm32-unknown-unknown only): a browser has no filesystem,
7320    /// so the open/save flows carry bytes through this per-page store instead of `std::fs`:
7321    /// day-toolkit-dom writes a picked file's bytes here and answers with its virtual path; the pieces
7322    /// layer stages save bytes here for the shim to download. Paths are plain strings under
7323    /// `/day-web/`; lifetimes are one picker round-trip (the flows remove what they stage).
7324    #[cfg(all(target_family = "wasm", target_os = "unknown"))]
7325    pub mod web_files {
7326        std::thread_local! {
7327            static FILES: std::cell::RefCell<std::collections::HashMap<String, Vec<u8>>> =
7328                std::cell::RefCell::new(std::collections::HashMap::new());
7329        }
7330
7331        /// Store `bytes` under `path` (replacing any prior content).
7332        pub fn write(path: &str, bytes: Vec<u8>) {
7333            FILES.with(|f| f.borrow_mut().insert(path.to_string(), bytes));
7334        }
7335
7336        /// The bytes at `path`, if present.
7337        #[must_use]
7338        pub fn read(path: &str) -> Option<Vec<u8>> {
7339            FILES.with(|f| f.borrow().get(path).cloned())
7340        }
7341
7342        /// Drop `path`'s bytes.
7343        pub fn remove(path: &str) {
7344            FILES.with(|f| {
7345                f.borrow_mut().remove(path);
7346            });
7347        }
7348    }
7349
7350    impl PresentResult {
7351        /// Flat wire tag for the C ABI (Qt shim / Android JNI): 0 dismissed, 1 button, 2 text,
7352        /// 3 files (`text` is the chosen locators joined by the unit separator).
7353        pub fn decode(tag: i32, index: i64, text: String) -> PresentResult {
7354            match tag {
7355                1 => PresentResult::Button(index),
7356                2 => PresentResult::Text(text),
7357                3 => PresentResult::Files(
7358                    text.split(UNIT_SEP)
7359                        .filter(|s| !s.is_empty())
7360                        .map(str::to_string)
7361                        .collect(),
7362                ),
7363                _ => PresentResult::Dismissed,
7364            }
7365        }
7366    }
7367
7368    impl PresentSpec {
7369        /// Backend-facing flattening for the C ABI: `(title, message, button labels, button
7370        /// roles as ints, sheet-or-prompt fields)`. Pure-Rust backends read the enum directly.
7371        #[must_use]
7372        pub fn title(&self) -> &str {
7373            match self {
7374                PresentSpec::Dialog { title, .. }
7375                | PresentSpec::Prompt { title, .. }
7376                | PresentSpec::OpenFile { title, .. }
7377                | PresentSpec::OpenFolder { title }
7378                | PresentSpec::SaveFile { title, .. } => title,
7379            }
7380        }
7381        #[must_use]
7382        pub fn message(&self) -> Option<&str> {
7383            match self {
7384                PresentSpec::Dialog { message, .. } | PresentSpec::Prompt { message, .. } => {
7385                    message.as_deref()
7386                }
7387                _ => None,
7388            }
7389        }
7390        /// Button labels joined with [`UNIT_SEP`], the encoding the nav menu and combobox
7391        /// shims already use for string lists.
7392        #[must_use]
7393        pub fn buttons_joined(&self) -> String {
7394            match self {
7395                PresentSpec::Dialog { buttons, .. } => buttons
7396                    .iter()
7397                    .map(|b| b.label.as_str())
7398                    .collect::<Vec<_>>()
7399                    .join(&UNIT_SEP.to_string()),
7400                PresentSpec::Prompt { ok, cancel, .. } => format!("{ok}{UNIT_SEP}{cancel}"),
7401                _ => String::new(),
7402            }
7403        }
7404        /// Button roles as ints (0 default, 1 cancel, 2 destructive), joined with commas.
7405        #[must_use]
7406        pub fn roles_joined(&self) -> String {
7407            let roles: Vec<i32> = match self {
7408                PresentSpec::Dialog { buttons, .. } => {
7409                    buttons.iter().map(|b| b.role as i32).collect()
7410                }
7411                PresentSpec::Prompt { .. } => {
7412                    vec![ButtonRole::Default as i32, ButtonRole::Cancel as i32]
7413                }
7414                _ => vec![],
7415            };
7416            roles
7417                .iter()
7418                .map(std::string::ToString::to_string)
7419                .collect::<Vec<_>>()
7420                .join(",")
7421        }
7422
7423        // --- file-dialog accessors (docs/files.md) ---
7424
7425        /// The file filters, if this is a file dialog.
7426        #[must_use]
7427        pub fn filters(&self) -> &[FileFilter] {
7428            match self {
7429                PresentSpec::OpenFile { filters, .. } | PresentSpec::SaveFile { filters, .. } => {
7430                    filters
7431                }
7432                _ => &[],
7433            }
7434        }
7435        /// Whether an open-file dialog lets the user pick several files (`false` for every
7436        /// other spec).
7437        #[must_use]
7438        pub fn multiple(&self) -> bool {
7439            matches!(self, PresentSpec::OpenFile { multiple: true, .. })
7440        }
7441        /// The suggested file name for a save dialog (empty otherwise).
7442        #[must_use]
7443        pub fn suggested_name(&self) -> &str {
7444            match self {
7445                PresentSpec::SaveFile { suggested_name, .. } => suggested_name,
7446                _ => "",
7447            }
7448        }
7449        /// The Day-written temp source path for a save dialog (empty otherwise).
7450        #[must_use]
7451        pub fn src_path(&self) -> &str {
7452            match self {
7453                PresentSpec::SaveFile { src_path, .. } => src_path,
7454                _ => "",
7455            }
7456        }
7457        /// Filters flattened for the C ABI: each filter is `name|ext1,ext2`, joined by
7458        /// [`UNIT_SEP`]. A trailing `|` (no extensions) means "all files". Empty when unfiltered.
7459        #[must_use]
7460        pub fn filters_joined(&self) -> String {
7461            self.filters()
7462                .iter()
7463                .map(|f| format!("{}|{}", f.name, f.extensions.join(",")))
7464                .collect::<Vec<_>>()
7465                .join(&UNIT_SEP.to_string())
7466        }
7467    }
7468}
7469
7470// ---------------------------------------------------------------------------
7471// The Toolkit trait (§8.1)
7472// ---------------------------------------------------------------------------
7473
7474/// Timing supplied by a native display scheduler. Seconds on a monotonic clock; its epoch
7475/// is platform-specific. `target_timestamp` is absent when the platform cannot predict presentation.
7476#[derive(Clone, Copy, Debug, PartialEq)]
7477pub struct FrameStamp {
7478    pub timestamp: f64,
7479    pub target_timestamp: Option<f64>,
7480}
7481impl FrameStamp {
7482    #[must_use]
7483    pub fn new(timestamp: f64) -> Self {
7484        Self {
7485            timestamp,
7486            target_timestamp: None,
7487        }
7488    }
7489}
7490/// A one-shot native frame callback, always delivered asynchronously on the UI thread.
7491pub type FrameCallback = Box<dyn FnOnce(FrameStamp)>;
7492/// Cancels a pending callback and releases its native registration. UI-thread only, idempotent
7493/// in effect, and safe during/after delivery. Dropping without calling is allowed after delivery.
7494pub type CancelFrame = Box<dyn FnOnce()>;
7495
7496/// The margins and minimum height a native list gives each row ([`Toolkit::list_row_metrics`],
7497/// docs/list.md "Row metrics"): a `UITableView` cell's layout margins, a Material list item's
7498/// 16dp sides and 56dp height.
7499#[derive(Clone, Copy, Debug, Default, PartialEq)]
7500pub struct RowMetrics {
7501    /// Space between the row's edges and its content.
7502    pub insets: Insets,
7503    /// The least height a row takes, margins included; content centers vertically in it.
7504    pub min_height: f64,
7505}
7506
7507/// Platform colors for custom drawing. Native controls keep their own semantic styling.
7508#[derive(Clone, Copy, Debug, PartialEq, Eq)]
7509#[repr(u8)]
7510pub enum SystemColor {
7511    Accent,
7512    Text,
7513    SecondaryText,
7514    Background,
7515    Surface,
7516}
7517
7518impl SystemColor {
7519    /// All roles, in discriminant order, for toolkit palette snapshots.
7520    pub const ALL: [Self; 5] = [
7521        Self::Accent,
7522        Self::Text,
7523        Self::SecondaryText,
7524        Self::Background,
7525        Self::Surface,
7526    ];
7527
7528    /// Day's fallback palette when the toolkit cannot resolve a role.
7529    /// These are fixed sRGB colors, not an approximation of a user-selected system accent.
7530    pub const fn fallback(self, dark: bool) -> Color {
7531        Color::hex(match (self, dark) {
7532            (Self::Accent, false) => 0x000a_66ff,
7533            (Self::Accent, true) => 0x003f_83ff,
7534            (Self::Text, false) => 0x001d_1d1f,
7535            (Self::Text, true) => 0x00f5_f5f7,
7536            (Self::SecondaryText, false) => 0x006e_6e73,
7537            (Self::SecondaryText, true) => 0x0098_989d,
7538            (Self::Background, false) => 0x00ff_ffff,
7539            (Self::Background, true) => 0x001e_1e20,
7540            (Self::Surface, false) => 0x00f3_f2f7,
7541            (Self::Surface, true) => 0x002c_2c2e,
7542        })
7543    }
7544}
7545
7546pub trait Toolkit: Sized + 'static {
7547    // `'static` so a handle clone can cross the object-safe TreeOps boundary boxed as `Any`
7548    // (`node_handle_any`, the tweaks door, docs/tweaks.md).
7549    type Handle: Clone + 'static;
7550
7551    /// Request one frame for the window containing `host`. Never call inline. Each native source
7552    /// must stop after delivery unless requested again; no polling timer. Hidden/unmapped windows
7553    /// may defer delivery until visible. Native callbacks must reach the UI thread before calling
7554    /// Rust. The returned closure cancels safely, including when the window has closed.
7555    /// The mock intentionally stays pending: tests inject a manual scheduler in day-core.
7556    fn request_frame(&mut self, _host: &Self::Handle, _cb: FrameCallback) -> CancelFrame {
7557        Box::new(|| {})
7558    }
7559
7560    fn capability(&self, _cap: Cap) -> Support {
7561        Support::Unsupported
7562    }
7563
7564    // node lifecycle
7565    fn realize(&mut self, kind: PieceKind, props: &dyn Any, id: NodeId) -> Self::Handle;
7566    fn update(
7567        &mut self,
7568        h: &Self::Handle,
7569        kind: PieceKind,
7570        patch: &dyn Any,
7571        anim: Option<&AnimSpec>,
7572    );
7573    /// Called from the turn-boundary release queue; backends may defer destruction further.
7574    fn release(&mut self, h: Self::Handle);
7575    /// Give a satellite piece a chance to drop its own per-view state, immediately before
7576    /// [`release`](Toolkit::release) frees `h` (§15.2).
7577    ///
7578    /// A backend that hosts third-party pieces implements this by looking `kind` up in its renderer
7579    /// registry and calling that piece's `release` hook. Defaulted to nothing: a backend with no
7580    /// registry has nothing to dispatch, and one that has not wired this yet leaves piece
7581    /// teardown unrun rather than failing to build.
7582    fn release_piece(&mut self, _kind: PieceKind, _h: &Self::Handle) {}
7583
7584    // tree
7585    fn insert(&mut self, parent: &Self::Handle, child: &Self::Handle, index: usize);
7586    fn remove(&mut self, parent: &Self::Handle, child: &Self::Handle);
7587    /// Put `child` at index `to` among `parent`'s native children: day's z-order resync, which
7588    /// walks the whole sibling row and asks for every position in turn. A child already at `to`
7589    /// must therefore cost nothing: a backend that re-parents unconditionally pays for the
7590    /// untouched siblings too, and where re-parenting means detach-then-add (no `ViewGroup` move
7591    /// primitive on Android) the detach resigns the focus of everything inside the subtree,
7592    /// which is how a text field being typed into loses the keyboard (docs/focus.md).
7593    fn move_child(&mut self, parent: &Self::Handle, child: &Self::Handle, to: usize);
7594
7595    // geometry (§7): frames are in the nearest realized native ancestor's space, in points.
7596    fn measure(&mut self, h: &Self::Handle, kind: PieceKind, p: Proposal) -> Size;
7597    /// Distance from the top of the widget's frame to its first text baseline, in points, when
7598    /// the widget is `size` (docs/baseline.md). `None` ⇒ it has no text baseline (an image, a
7599    /// slider, a bare container) and a baseline-aligned row falls back to box alignment for it.
7600    ///
7601    /// This is a measurement, not a layout mode: day places every frame itself (§7.1) and never
7602    /// hands a row to a native baseline-aligning container, so what it needs from the toolkit is
7603    /// where the text sits inside the box. Backends that cannot answer keep the default and rows
7604    /// stay centered, which is what every row did before this existed.
7605    fn first_baseline(&mut self, _h: &Self::Handle, _kind: PieceKind, _size: Size) -> Option<f64> {
7606        None
7607    }
7608    fn set_frame(&mut self, h: &Self::Handle, frame: Rect, anim: Option<&AnimSpec>);
7609
7610    // animatable visual channels (§8.4): cheap per-node opacity + transform that don't relayout.
7611    // Defaulted no-ops so backends adopt them incrementally; `anim = Some` ⇒ animate to the value
7612    // on the toolkit's own compositor, `None` ⇒ set instantly.
7613    fn set_opacity(&mut self, _h: &Self::Handle, _opacity: f64, _anim: Option<&AnimSpec>) {}
7614    fn set_transform(
7615        &mut self,
7616        _h: &Self::Handle,
7617        _t: Transform,
7618        _size: Size,
7619        _anim: Option<&AnimSpec>,
7620    ) {
7621    }
7622
7623    // text selection (docs/text.md): make this node's text user-selectable (copy/drag). Applied
7624    // once from the `.selectable()` modifier (day-pieces) to the widget it wraps (a `label`'s
7625    // native text view, most usefully). Unmanaged: Day sets it here and never patches it, so it
7626    // survives text updates. The default no-op means a backend without a selection affordance
7627    // silently leaves the text unselectable.
7628    //
7629    // Returns `Some(replacement)` when the toolkit had to rebuild the widget as a different
7630    // native class to gain a selection affordance (UIKit: `UILabel` has none, so the label
7631    // becomes a read-only `UITextView`); day-core re-points the node's handle at the
7632    // replacement, so later patches and layout reach the widget that is actually on screen.
7633    // Every property-flip backend returns `None`.
7634    fn set_selectable(&mut self, _h: &Self::Handle, _selectable: bool) -> Option<Self::Handle> {
7635        None
7636    }
7637
7638    // text entry (docs/textfield.md): how a `text_field` takes its text: hidden characters,
7639    // read-only, the keyboard and autofill purpose, the action key, the length bound. Called
7640    // once after `realize` when a field asks for anything but the defaults, and again with the
7641    // whole set whenever a reactive member changes, so the setter is idempotent.
7642    //
7643    // Returns `Some(replacement)` when hiding the characters takes a different native class
7644    // (AppKit: `NSSecureTextField`; WinUI: `PasswordBox`), the same contract as
7645    // `set_selectable`: the backend carries the text, the placeholder and its own event wiring
7646    // over, takes the old widget's place in the native tree, and day-core re-points the node's
7647    // handle. Required, with no default: a backend that left this out would show a password in
7648    // the clear. A member the toolkit has no notion of (an action key on a desktop) is ignored.
7649    fn set_input_traits(&mut self, h: &Self::Handle, traits: &InputTraits) -> Option<Self::Handle>;
7650
7651    // pointer shape (docs/cursor.md): the cursor to show while the pointer is over this node
7652    // and its descendants, from the `.cursor()` modifier. Called again whenever a reactive
7653    // cursor changes, so the setter is idempotent and cheap; `Cursor::Default` releases the
7654    // node. The default no-op is a backend with no pointer API to reach (`Cap::Cursor`
7655    // answers `Unsupported` there).
7656    fn set_cursor(&mut self, _h: &Self::Handle, _cursor: Cursor) {}
7657
7658    /// Show or hide a retained subtree, including its input and accessibility participation.
7659    /// The layout and reactive scope stay alive while hidden.
7660    fn set_presented(&mut self, _h: &Self::Handle, _visible: bool) {}
7661
7662    /// Attach overscroll delivery to a refresh host; the caller owns the mounted scope.
7663    fn attach_refresh(&mut self, _h: &Self::Handle, _host: NodeId) {}
7664
7665    // scroll (§7.6)
7666    fn set_scroll_content(&mut self, _h: &Self::Handle, _content: Size) {}
7667    // The room a classic (non-overlay) scroll bar takes out of a scroll view's content area
7668    // while the content overflows along `vertical`'s axis: its width for a vertical scroll, its
7669    // height for a horizontal one (docs/scroll.md). Day lays overflowing content out that much
7670    // narrower, so it fits beside the bar instead of reaching under it. 0 — the default — is
7671    // every backend whose bars overlay the content (AppKit, GTK, UIKit, Android, XAML, DOM).
7672    fn scroll_bar_inset(&mut self, _h: &Self::Handle, _vertical: bool) -> f64 {
7673        0.0
7674    }
7675    // The margins and minimum height the platform's own list gives a row (docs/list.md "Row
7676    // metrics"), asked of list `h` each time day-core lays a row. Day insets the row's content by
7677    // the margins and keeps it at least that tall, so a row reads at the platform's size without
7678    // the app padding it per platform. Zero — the default — leaves the row to its content.
7679    fn list_row_metrics(&mut self, _h: &Self::Handle) -> RowMetrics {
7680        RowMetrics::default()
7681    }
7682    fn scroll_to(&mut self, _h: &Self::Handle, _target: Rect, _animated: bool) {}
7683    /// Scroll a native navigation menu to its top or bottom without changing selection.
7684    /// The widget owns its content extent. Return false when the handle is unsupported.
7685    fn nav_scroll_to_edge(&mut self, _h: &Self::Handle, _bottom: bool) -> bool {
7686        false
7687    }
7688    fn scroll_offset(&mut self, _h: &Self::Handle) -> Point {
7689        Point::ZERO
7690    }
7691
7692    // events: one trampoline, node-id keyed; enqueue-only contract (§8.3).
7693    fn set_event_sink(&mut self, sink: EventSink);
7694
7695    // gestures (docs/shapes.md): attach a native recognizer for `kind` to `h`, emitting
7696    // `Event::Tap/LongPress/Drag` for `node` (enqueue-only). Default no gesture; a piece opts in
7697    // when it has a handler. Idempotent per (handle, kind).
7698    fn enable_gesture(&mut self, _h: &Self::Handle, _node: NodeId, _kind: GestureKind) {}
7699
7700    // focus (docs/focus.md): move native keyboard focus to (or away from) this control.
7701    // `focused = true` requests focus (on mobile this also raises the soft keyboard for text
7702    // inputs); `false` resigns it (dismissing the keyboard; platforms without a "focus nothing"
7703    // state resign to a focusable root). Backends report the resulting state, user- or
7704    // programmatic, with `Event::FocusChanged(bool)` through the sink; a request that cannot
7705    // be honored (unfocusable, unmounted) produces no event. The default no-op means a
7706    // backend without focus support neither moves nor reports focus.
7707    fn focus(&mut self, _h: &Self::Handle, _node: NodeId, _focused: bool) {}
7708
7709    // focusability (docs/focus.md): opt this container into the platform's focus system, the
7710    // canvas contract generalized (`Decorate::focusable`). A focusable container accepts focus,
7711    // takes it on a press (before the press reaches its gesture recognizers), reports both
7712    // directions with `Event::FocusChanged`, and delivers the non-text keys it hears while
7713    // focused as `Event::Key` for `node` (gated on `keys::handled`, like a canvas). The default
7714    // no-op means the piece renders normally but never joins the focus order: `.focused(…)`
7715    // bindings stay quiet and `.on_key(…)` never fires, the same graceful silence unfocusable
7716    // controls already have. Idempotent; only `true` is ever sent today (a piece opts in at
7717    // build, it does not opt back out).
7718    fn set_focusable(&mut self, _h: &Self::Handle, _node: NodeId, _focusable: bool) {}
7719
7720    // recycling list (docs/list.md, §10): day-core hands the `LIST` host its row-pull `source`
7721    // once, right after realize. A recycling backend stores it and calls it from its native
7722    // data-source; the default no-op means a backend without list support renders nothing.
7723    fn attach_list(&mut self, _host: &Self::Handle, _source: ListSource) {}
7724
7725    // hierarchical tree (docs/tree.md): day-core hands the `TREE` host its token-addressed
7726    // row-pull `source` once, right after realize. A backend with a native tree stores it and
7727    // answers its data-source from it; the default no-op means a backend without tree support
7728    // renders nothing (`Cap::Tree` answers `Unsupported`, and apps gate on that).
7729    fn attach_tree(&mut self, _host: &Self::Handle, _source: TreeSource) {}
7730
7731    // routes (docs/navigation.md): day-core reports the app's current route path here whenever
7732    // it changes ("" = everything at its root), so a backend with a native notion of location
7733    // can mirror it: web-dom writes the URL hash (`#controls`), and browser back/forward or a
7734    // hand-edited hash comes back as `Event::RouteRequested`. Default no-op: most toolkits
7735    // have nowhere to put a route.
7736    fn set_route(&mut self, _route: &str) {}
7737
7738    // undo bridge (docs/model.md): mirror the app's undo stack into the platform's own undo
7739    // objects, so the stock Edit menu retitles and enables itself and the platform's gestures
7740    // land: the native front of one Day-owned history. The state flows down whenever it
7741    // changes; the user's invocation comes back up as `Event::Undo`. Default no-op: a backend
7742    // without a native undo system answers `Cap::UndoBridge` `Unsupported`, and the app's own
7743    // affordances (menu items, buttons, accelerators) drive the stack instead.
7744    fn set_undo_state(&mut self, _state: &UndoState) {}
7745
7746    // edit bridge (docs/menus.md): mirror what the app's standard-edit handlers can do, so
7747    // the platform's own menu validation enables Cut/Copy/Paste exactly as it does for text
7748    // widgets; invocations come back up as `Event::Edit`. Default no-op: a backend without
7749    // a native edit-command route answers `Cap::EditBridge` accordingly.
7750    fn set_edit_state(&mut self, _state: &EditState) {}
7751
7752    // ambient modifiers (docs/menus.md): the keyboard modifiers held right now, for
7753    // interactions whose meaning they change (shift-click multi-select). Pull-based: the
7754    // platforms expose exactly this query (NSEvent.modifierFlags, the shim's tracked mask).
7755    // Touch-only backends keep the all-false default.
7756    fn modifiers(&mut self) -> Modifiers {
7757        Modifiers::default()
7758    }
7759
7760    // Dynamic context menu (docs/menus.md): the menu is built when it is summoned. The provider
7761    // is called synchronously from the platform's own menu callback (UI thread, outside any
7762    // day-core borrow) with the location in the node's local coordinates, and its result is
7763    // shown. The static `set_context_menu` below stays the simple path; this one exists for
7764    // surfaces whose menu depends on what is under the pointer (a canvas selection,
7765    // docs/tree.md). Default no-op: a backend without the affordance shows nothing.
7766    fn set_drag_source(&mut self, _h: &Self::Handle, _source: transfer::Source) {}
7767    fn set_drop_target(&mut self, _h: &Self::Handle, _target: transfer::Target) {}
7768
7769    fn set_context_menu_fn(&mut self, _h: &Self::Handle, _node: NodeId, _f: ContextMenuFn) {}
7770
7771    // menus (§ menus): render `items` with the backend's native menu affordance, firing
7772    // `Event::MenuAction(id)` (enqueue-only) for each id'd item; `role` items use the native standard
7773    // command. Default no-op: a toolkit without a menu bar / context menu shows nothing.
7774    /// The application menu (macOS/Windows/Linux menu bar; the app-bar overflow on Android; the
7775    /// `UIMenuBuilder` main menu on iPadOS/Catalyst). Replaces any previous app menu.
7776    fn set_app_menu(&mut self, _items: &[MenuItem]) {}
7777    /// A context menu for `h`, shown on secondary-click (desktop) or long-press (mobile). Passing an
7778    /// empty slice removes it.
7779    fn set_context_menu(&mut self, _h: &Self::Handle, _node: NodeId, _items: &[MenuItem]) {}
7780    /// Make the button `h` (a [`kinds::BUTTON`] node) a pull-down menu button (docs/menus.md
7781    /// "Menu buttons"): its primary press (a click, a tap, the keyboard's Space or Return, the
7782    /// accessibility press) asks `f` for the menu at that moment and shows it under the button
7783    /// with the toolkit's own menu, instead of reporting [`Event::Pressed`]. `f` is called on
7784    /// the UI thread, outside any day-core borrow, with [`Point::ZERO`] (where on the button
7785    /// the press landed does not change its menu); an empty result shows nothing. Chosen items
7786    /// fire [`Event::MenuAction`] as a context menu's do.
7787    ///
7788    /// A toolkit with no native menu to show reports [`Event::ContextMenu`] for `node` instead,
7789    /// with `window` at the button's bottom-leading corner, and the pieces layer presents the
7790    /// composed menu there. Called once per realized button; the release sweep reclaims `f`.
7791    /// Resolve the press through [`resolve_button_menu`], which re-checks after `f` runs that
7792    /// the button was not released by it. Default no-op: the button stays an inert button.
7793    fn set_button_menu(&mut self, _h: &Self::Handle, _node: NodeId, _f: ContextMenuFn) {}
7794
7795    // toolbars (docs/toolbars.md): a window's native toolbar: NSToolbar, AdwHeaderBar, QToolBar,
7796    // CommandBar. `h` is the window root's handle (the same handle `open_window` returned, or the
7797    // primary root's); the backend walks from it to the window it belongs to. Default no-op: a
7798    // toolkit with no toolbar shows nothing rather than a drawn imitation, and reports
7799    // `Cap::Toolbar` as `Unsupported` so an app can put the command somewhere else.
7800    /// Edit the window's toolbar (docs/toolbars.md): the [`ToolbarOp`]s, removals first, then
7801    /// insertions in ascending position. The bar starts empty, and becomes empty again when every
7802    /// item has been removed, at which point the backend takes it off the window.
7803    ///
7804    /// An item no op names must keep its native widget untouched, which is what keeps a search
7805    /// field focused while the page around it changes. Day sends an edit only when the bar
7806    /// changed, at most once per turn, and an item keeps its [`ToolbarItem::action`] for as long
7807    /// as its window shows an item with that id, so a native item's handler never needs
7808    /// repointing. Keep a [`ToolbarMirror`] and place each new item after
7809    /// [`ToolbarMirror::prev_where`] its group.
7810    ///
7811    /// Returns whether the edit was applied. `false` (the window has no bar to edit yet) makes
7812    /// Day send the whole bar again at the next change rather than assume this one landed.
7813    fn edit_toolbar(&mut self, _h: &Self::Handle, _ops: &[ToolbarOp]) -> bool {
7814        true
7815    }
7816    /// Apply a targeted change to one live toolbar item, the path a bound signal writes through,
7817    /// so syncing a search field does not rebuild the bar. No-op if the item is not present.
7818    fn update_toolbar(&mut self, _h: &Self::Handle, _patch: &ToolbarPatch) {}
7819
7820    // lifecycle (docs/lifecycle.md): does this backend deliver `phase`? The default answers "yes" for
7821    // the universal phases (launch/activation/termination) and "no" for the mobile-only ones. Backends
7822    // that wire up more (the mobile ones) override this; it must agree with the crate's
7823    // `const fn lifecycle_supported`, which drives compile-time guards in `day::require_lifecycle!`.
7824    fn supports_lifecycle(&self, phase: Lifecycle) -> bool {
7825        phase.is_universal()
7826    }
7827
7828    // pillars
7829    /// Apply a node's accessibility annotations (docs/accessibility.md): the label, hint and
7830    /// value the screen reader speaks, an explicit role, whether the node is hidden from
7831    /// assistive technology, and the automation identifier. Called with the node's whole
7832    /// accumulated set each time any of it changes, so every member is written on every call.
7833    /// Only an explicit role is applied: a native control reports its own.
7834    fn set_a11y(&mut self, _h: &Self::Handle, _a11y: &A11yProps) {}
7835    /// Speak `text` through the screen reader without moving its focus (docs/accessibility.md;
7836    /// probe [`Cap::Announce`]). `urgent` interrupts what is being read; otherwise the sentence
7837    /// waits its turn. Nothing happens when no screen reader is running. The default is a
7838    /// backend that reaches no announcement API.
7839    fn announce(&mut self, _text: &str, _urgent: bool) {}
7840    /// Read a widget's native state back from the platform for `a11y_audit` and
7841    /// `assert_native` (§14.2, docs/testing.md) to diff against Day's expectation. Default:
7842    /// nothing read; the audit skips the node and `assert_native` records each field as unread.
7843    fn read_native(&self, _h: &Self::Handle) -> NativeSnapshot {
7844        NativeSnapshot::default()
7845    }
7846    fn replay(&mut self, _h: &Self::Handle, _ops: &[DrawOp], _size: Size) {}
7847
7848    /// Every family this toolkit can draw canvas text in, with the faces each ships
7849    /// (docs/fonts.md; probe [`Cap::FontList`]). Default: none. `day::font_families` calls
7850    /// this once per process and caches the answer: enumeration is slow on every platform
7851    /// (fontconfig, a DirectWrite collection, an XML parse on Android) and the set does not
7852    /// change under a running app.
7853    fn font_families(&mut self) -> Vec<FontFamilyInfo> {
7854        Vec::new()
7855    }
7856
7857    /// Measure one line of canvas text at `size` points in `font`, in the same engine
7858    /// [`Toolkit::replay`] draws [`DrawOp::Text`] with, so a `TextAnchor::LEADING` anchor plus
7859    /// the returned `ascent` lands on the drawn baseline. `None` = cannot measure; the facade
7860    /// then answers [`TextMetrics::approximate`].
7861    fn measure_text(&mut self, _text: &str, _size: f64, _font: &CanvasFont) -> Option<TextMetrics> {
7862        None
7863    }
7864    // --- raster images (docs/images.md) -------------------------------------------------
7865    //
7866    // Request-id shaped rather than blocking, because one backend can never answer
7867    // synchronously: a browser decodes through `createImageBitmap`, which is a promise. Every
7868    // other backend decodes inline and raises the completion before returning, so the shape
7869    // costs them nothing but a line, and the app-facing API can be one thing everywhere
7870    // instead of two (docs/async.md rule 3: a callback and a future, never a runtime).
7871
7872    /// Decode encoded image bytes (PNG/JPEG/…) into a native image, answering `req` with
7873    /// [`Event::ImageDecoded`].
7874    ///
7875    /// The id in that event is minted by the caller (day-core), not the backend: the backend
7876    /// keeps its own side table from that id to whatever it decoded.
7877    ///
7878    /// The default does nothing because a default body cannot reach the event sink
7879    /// (it is installed per backend by [`Toolkit::set_event_sink`], not reachable through this
7880    /// trait), so there is no way for it to answer. day-core asks [`Cap::ImageDecode`] first and
7881    /// resolves the request as [`ImageError::Unsupported`] itself, which is why a backend with
7882    /// no decoder needs no code here at all.
7883    fn decode_image(&mut self, _req: u64, _id: BitmapId, _bytes: &[u8]) {}
7884
7885    /// What a decoded image is: pixel size, scale, format, alpha ([`BitmapInfo`]).
7886    ///
7887    /// Synchronous: every backend that decoded the image already holds these facts. `None` means
7888    /// the id names nothing live.
7889    fn image_info(&mut self, _id: BitmapId) -> Option<BitmapInfo> {
7890        None
7891    }
7892
7893    /// The metadata beyond the pixels: EXIF orientation, DPI, capture time
7894    /// ([`ImageProperties`], probe [`Cap::ImageProperties`]). `None` where the backend has no
7895    /// metadata reader, which is most of them.
7896    fn image_properties(&mut self, _id: BitmapId) -> Option<ImageProperties> {
7897        None
7898    }
7899
7900    /// Encode a decoded image back to bytes per `spec`, answering `req` with
7901    /// [`Event::ImageEncoded`]. A format outside [`Self::encode_formats`] answers
7902    /// [`ImageError::Encode`] rather than silently substituting another one.
7903    ///
7904    /// Defaulted to nothing for the same reason as [`Self::decode_image`]: day-core probes
7905    /// [`Cap::ImageEncode`] and answers `Unsupported` without ever calling this.
7906    fn encode_image(&mut self, _req: u64, _id: BitmapId, _spec: &EncodeSpec) {}
7907
7908    /// Which formats [`Self::encode_image`] can write, the [`Cap::ImageEncode`]
7909    /// counterpart of [`Self::font_families`]/[`Cap::FontList`]. Empty by default.
7910    fn encode_formats(&mut self) -> Vec<ImageFormat> {
7911        Vec::new()
7912    }
7913
7914    /// Drop a decoded image and everything the backend cached for it. Called when the app's
7915    /// last handle to it goes away; an id the backend never saw is a no-op.
7916    fn release_image(&mut self, _id: BitmapId) {}
7917
7918    // --- canvas export (docs/canvas.md "Exporting") --------------------------------------
7919    //
7920    // Request-id shaped like the image duties above, for the same reason: the browser's
7921    // `createImageBitmap` is a promise, and a native toolkit may paint on another thread. A
7922    // backend may also answer inline, before returning. day-core validates sizes, enforces
7923    // the pixel limits and probes the caps first, so a backend sees only requests it can
7924    // attempt.
7925
7926    /// Replay `ops` into a new offscreen bitmap of `size` points at `scale` pixels per point
7927    /// ([`export_pixels`] gives the pixel size), with a transparent background and the
7928    /// canvas's top-left origin. Store it under `id` in the same table [`Self::decode_image`]
7929    /// fills, so `image_info`, `encode_image`, `release_image`, the `image` piece and
7930    /// [`DrawOp::Image`] all take it, then answer `req` with [`Event::BitmapRendered`] (its
7931    /// [`BitmapInfo::scale`] is `scale`).
7932    ///
7933    /// The painter must be the one [`Self::replay`] uses, so text, gradients, clips and stamps
7934    /// match the screen. Where the platform's 2-D API draws into a memory surface from any
7935    /// thread, the paint runs on a thread of [`offscreen`] and the answer is posted back, so
7936    /// a long replay never stalls the UI; the toolkit resolves on the UI thread, before it
7937    /// hands the job over, everything the painter would otherwise read from UI-thread state
7938    /// (the decoded images the ops reference, the fonts their text runs need). The contract
7939    /// holds either way: one answer per request, carrying that request's `req`, raised on the
7940    /// UI thread, and the bitmap in the table before it. Defaulted to nothing: day-core probes
7941    /// [`Cap::CanvasBitmap`] and answers [`ExportError::Unsupported`] itself.
7942    fn render_bitmap(
7943        &mut self,
7944        _req: u64,
7945        _id: BitmapId,
7946        _ops: &[DrawOp],
7947        _size: Size,
7948        _scale: f64,
7949    ) {
7950    }
7951
7952    /// Replay each page into one PDF document and answer `req` with [`Event::PdfRendered`].
7953    /// Units are PDF points, top-left origin; shapes and text stay vector, and images embed at
7954    /// their pixel size. `pages` is never empty. Defaulted to nothing: day-core probes
7955    /// [`Cap::CanvasPdf`] first.
7956    fn render_pdf(&mut self, _req: u64, _pages: &[PdfPage], _info: &PdfInfo) {}
7957
7958    /// Capture the primary window's content as encoded image bytes (the dayscript `screenshot`
7959    /// step, docs/window-image.md).
7960    ///
7961    /// # Errors
7962    ///
7963    /// Returns a message when the backend cannot capture; the default always does.
7964    fn snapshot_window(&mut self) -> Result<Vec<u8>, String> {
7965        Err("snapshot unsupported".into())
7966    }
7967    /// Where `root`, the primary window's root container, sits in [`Self::snapshot_window`]'s
7968    /// image, in points from its top-left. A reader of the capture (dayscript `sample_pixel`)
7969    /// maps Day's frames into it with this; it matters where the capture spans more than Day's
7970    /// content on more than one side, as Android's edge-to-edge content does (status bar
7971    /// above, navigation bar below).
7972    ///
7973    /// Defaulted to `None`, which the reader takes as "any rows beyond Day's content are
7974    /// above it", true where the only extra area is a title bar.
7975    fn snapshot_origin(&mut self, _root: &Self::Handle) -> Option<Point> {
7976        None
7977    }
7978    /// Establish a fresh screenshot checkpoint after reactive work and native transitions.
7979    /// `revision` is stable across retries and unique to the request; `host` selects a
7980    /// secondary window, or None for the primary. Never block the UI thread waiting for
7981    /// a frame. Pending requests are retried within the dayscript deadline.
7982    ///
7983    /// Ready means the platform render checkpoint completed, not that a vsync callback
7984    /// proves pixels were displayed. `OnCapture` delegates freshness to `snapshot_window`.
7985    ///
7986    /// # Errors
7987    ///
7988    /// Returns a message when the checkpoint cannot be established, for example because the
7989    /// window closed.
7990    fn prepare_snapshot(
7991        &mut self,
7992        _host: Option<&Self::Handle>,
7993        _revision: u32,
7994    ) -> Result<capture::Readiness, String> {
7995        // Compatible with external toolkits predating this hook: their synchronous
7996        // snapshot owns freshness, and no external-capture acknowledgment is fabricated.
7997        Ok(capture::Readiness::OnCapture)
7998    }
7999
8000    /// The same capture with the window's own chrome: title bar, toolbar, whatever the platform
8001    /// draws around the content (docs/window-image.md).
8002    ///
8003    /// Defaulted to [`Self::snapshot_window`]: a backend that cannot separate the two
8004    /// (or has no chrome to speak of, a phone) answers with the content shot rather than an
8005    /// error, so an app asking for chrome degrades to "what there was" instead of failing. The
8006    /// dayscript `screenshot` step never calls this, which is what keeps every captured gallery
8007    /// baseline byte-identical to before it existed.
8008    ///
8009    /// # Errors
8010    ///
8011    /// Returns a message when the backend cannot capture the window.
8012    fn snapshot_window_chrome(&mut self) -> Result<Vec<u8>, String> {
8013        self.snapshot_window()
8014    }
8015    /// Show/hide the sidebar pane of the navigation host `host`, which is what the sidebar
8016    /// affordance a `nav(Sidebar)` contributes for itself drives ([`SIDEBAR_TOGGLE_ID`]).
8017    /// `false` when `host` has no pane to toggle (a stack, a tab bar, no sidebar concept at all).
8018    ///
8019    /// Per host, not per process: a second window's button collapses that window's sidebar
8020    /// and not the first's. The item's own action makes the call, and dayscript's `toolbar:`
8021    /// step presses the item like any other, so a walkthrough drives exactly the path a click
8022    /// takes. Defaulted, so a backend with no sidebar needs no code. docs/toolbars.md,
8023    /// docs/navigation.md.
8024    fn toggle_sidebar(&mut self, _host: &Self::Handle) -> bool {
8025        false
8026    }
8027    /// Press the platform's own back affordance (the navigation bar's back button on iOS,
8028    /// the system back on Android) on the innermost navigation host that has something to
8029    /// pop. What `nav_back()` does not do: that is Day's rail, which pops the model and lets the
8030    /// backend follow, while this runs the native path first (the bar's `shouldPop`, the
8031    /// dispatcher's callbacks, the pop itself) and lets the backend report it to Day as a user
8032    /// back, guard and all. dayscript's `nav_back: { native: true }` drives it, so a walkthrough
8033    /// can cover the code that a real tap runs and Day's rail never reaches. `false` when this
8034    /// toolkit has no native back or nothing is popped by it. Defaulted, so a desktop needs no
8035    /// code. docs/navigation.md.
8036    fn native_back(&mut self) -> bool {
8037        false
8038    }
8039    /// Take (`true`) or release (`false`) the platform's system back for the app's own
8040    /// handlers ([`Decorate::on_system_back`](/api/day_pieces/trait.Decorate.html#method.on_system_back)):
8041    /// day-core arms it while at least one mounted handler is enabled. Armed, a system back that
8042    /// nothing native consumes first (a presented cover, a pushed page, an armed guard) reaches
8043    /// Day as [`Event::NavBack`] on [`WINDOW_NODE`] instead of leaving the app; released, the
8044    /// platform's default runs, predictive-back preview and all. Android registers an
8045    /// `OnBackPressedCallback` beneath its own; HarmonyOS consumes the page's `onBackPress`.
8046    /// Defaulted, so a toolkit with no system back (desktop, iOS, the web) needs no code.
8047    /// docs/navigation.md "Handling the system Back".
8048    fn set_system_back(&mut self, _armed: bool) {}
8049    /// Whether the UI has settled, with no native transition (modal present/dismiss, nav push)
8050    /// still animating. The dayscript `screenshot` step polls this before capturing so shots
8051    /// never catch a half-faded dialog or half-pushed page. Backends without async
8052    /// transitions (or without a way to know) report `true`.
8053    fn ui_idle(&mut self) -> bool {
8054        true
8055    }
8056
8057    // imperative presentation (docs/dialogs.md): show a native modal for request `req`;
8058    // the backend answers by enqueuing `Event::PresentResult { req, .. }`. `dismiss` is
8059    // used only when Day resolves programmatically (dayscript) while the modal is still up.
8060    fn present(&mut self, _req: u64, _spec: &present::PresentSpec) {}
8061    fn dismiss(&mut self, _req: u64) {}
8062
8063    /// Open `url` in the platform's default handler: the system browser for `http(s)`, the mail
8064    /// client for `mailto:`, etc. Backs the [`link`](/api/day_pieces/fn.link.html) piece. Fire and
8065    /// forget: there is no result, and an unopenable URL is ignored. The default no-ops so a
8066    /// backend that hasn't wired it up still compiles.
8067    fn open_url(&mut self, _url: &str) {}
8068
8069    /// Whether a native share chooser is available. Does not probe installed share targets.
8070    fn share_support(&self) -> Support {
8071        Support::Unsupported
8072    }
8073    /// Present the system share chooser for `spec` (docs/sharing.md). True means presentation
8074    /// started, not that sharing completed. Never sends data without the user's choice of a
8075    /// target. Where the chooser can carry the app's own actions (`Cap::ShareActions`), each
8076    /// of `spec.actions` appears with its title and glyph, and choosing one enqueues
8077    /// `Event::MenuAction(action.id)`; elsewhere the actions are left out. `anchor` is the
8078    /// control the chooser points at where it is a popover (iPad, macOS); without one the
8079    /// chooser uses the window's top trailing corner.
8080    fn share(&mut self, _spec: &share::ShareSpec, _anchor: Option<&Self::Handle>) -> bool {
8081        false
8082    }
8083
8084    /// Read current OS associations. Unsupported platforms must not fabricate a default.
8085    ///
8086    /// # Errors
8087    ///
8088    /// Returns [`applications::ApplicationError::Unsupported`] where the platform has no
8089    /// association query (the default), or the platform's own failure.
8090    fn application_handlers(
8091        &mut self,
8092        _query: &applications::HandlerQuery,
8093    ) -> Result<applications::ApplicationHandlers, applications::ApplicationError> {
8094        Err(applications::ApplicationError::Unsupported)
8095    }
8096
8097    /// Open with an opaque application identifier returned by `application_handlers`.
8098    fn open_url_with_application(
8099        &mut self,
8100        _url: &str,
8101        _application: &str,
8102        completion: applications::OpenApplicationCompletion,
8103    ) {
8104        completion(Err(applications::ApplicationError::Unsupported));
8105    }
8106
8107    /// Ask the OS to require a second swipe for its edge gestures on `edges` (docs/cover.md):
8108    /// the union requested by every mounted `defers_system_gestures` modifier, re-sent whenever
8109    /// that set changes (`Edges::NONE` when the last one unmounts). iOS defers the home
8110    /// indicator / notification edges; Android enters swipe-to-reveal immersive mode while
8111    /// non-empty. The default no-ops (desktop has no system edge gestures).
8112    fn defer_system_gestures(&mut self, _edges: Edges) {}
8113
8114    /// Hide (`true`) or show the system status bar (docs/cover.md): whether any mounted
8115    /// `status_bar_hidden` modifier currently asks for it hidden, re-sent whenever that answer
8116    /// may have changed (`false` when the last request unmounts). iOS answers the root and
8117    /// cover view controllers' `prefersStatusBarHidden`; Android and HarmonyOS hide the status
8118    /// bar through their window inset controls. The default no-ops (desktop and web have no
8119    /// status bar); report `Cap::StatusBarHidden` alongside an implementation.
8120    fn set_status_bar_hidden(&mut self, _hidden: bool) {}
8121
8122    /// Whether the platform is rendering in dark appearance right now. Apps painting
8123    /// custom surfaces (opaque overlay panels, scrims) branch on this so their fills track
8124    /// the theme the default text colors already follow; hardcoding either theme's
8125    /// surface produces dark-on-dark or light-on-light text on the other. Queried at
8126    /// build time (a piece rebuilt after a theme change re-queries). The default honors a
8127    /// `DAY_THEME` launch override and otherwise answers light.
8128    /// Resolve a semantic color for custom artwork. Backends with native palette access
8129    /// override this; the default follows light/dark appearance using Day's fixed palette.
8130    fn system_color(&mut self, role: SystemColor) -> Color {
8131        role.fallback(self.dark_mode())
8132    }
8133
8134    fn dark_mode(&mut self) -> bool {
8135        std::env::var("DAY_THEME").ok().as_deref() == Some("dark")
8136    }
8137    /// Whether the user asked the system for less motion (docs/accessibility.md; probe
8138    /// [`Cap::ReduceMotion`]): macOS and iOS "Reduce Motion", Android "Remove animations" (an
8139    /// animator duration scale of zero), GTK's `gtk-enable-animations` off, Windows "Show
8140    /// animations" off, the web's `prefers-reduced-motion`. Read at launch; a backend that
8141    /// watches the setting calls `day_core::note_motion_changed` when it flips. Day then applies
8142    /// every finite animation at its destination and keeps only indeterminate motion. The default
8143    /// is a backend that reads no such setting.
8144    fn reduce_motion(&mut self) -> bool {
8145        false
8146    }
8147
8148    /// App-level appearance override: `Some(true)` forces dark, `Some(false)` forces light,
8149    /// `None` returns to following the system. Backends restyle their native widgets in
8150    /// place and answer the override from [`dark_mode`](Self::dark_mode); app-painted
8151    /// surfaces pick it up on their next rebuild. `Cap::Appearance` reports whether the
8152    /// backend honors this; the default ignores the call.
8153    fn set_appearance(&mut self, _dark: Option<bool>) {}
8154
8155    /// Put `badge` on the app's icon in the Dock / launcher / home screen (docs/badge.md).
8156    ///
8157    /// Fire-and-forget, like `set_appearance`: a payload this toolkit cannot render is ignored, and
8158    /// the app probes `Cap::AppBadge{Count,Text,Dot}` before choosing one. Never substitute: a
8159    /// backend that turned `Text("beta")` into `Count(1)` would put a wrong number on a user's
8160    /// icon, which is worse than showing nothing. The default ignores every call.
8161    fn set_app_badge(&mut self, _badge: &AppBadge) {}
8162
8163    // app lifecycle (mobile; desktop backends no-op)
8164    fn on_suspend(&mut self) {}
8165    fn on_resume(&mut self) {}
8166    fn on_memory_warning(&mut self) {}
8167
8168    // adoption of foreign native handles (polyglot pieces, §15.3)
8169    fn adopt(&mut self, _raw: RawHandle) -> Self::Handle {
8170        unimplemented!("this toolkit does not adopt foreign handles yet")
8171    }
8172
8173    // secondary windows (docs/windows.md)
8174
8175    /// Open a native OS window per `options` + `kind`: create and show the window, wire its
8176    /// events to `id` (`WindowResized` with the content size in points, `WindowClosed` after
8177    /// the native close, `WindowFocused` on key/active changes), and answer with its content
8178    /// container handle, the same contract as the `ready` root container. Backends whose
8179    /// window creation is asynchronous (a scene, an activity, an ability) answer
8180    /// [`WindowOpenReply::Pending`] and complete later through
8181    /// `day_core::finish_window_open(id, raw, size)`, which goes through [`Toolkit::adopt`].
8182    /// The default answers `Unsupported`; day-core then presents the content as a
8183    /// fullscreen cover in the primary window instead.
8184    fn open_window(
8185        &mut self,
8186        _id: NodeId,
8187        _options: &WindowOptions,
8188        _kind: WindowKind,
8189    ) -> WindowOpenReply<Self::Handle> {
8190        WindowOpenReply::Unsupported
8191    }
8192
8193    /// Close the native window whose content container is `host` (a handle `open_window`
8194    /// produced). Asynchronous: the platform confirms with `Event::WindowClosed` on the
8195    /// window's root node, and only then does day-core tear the subtree down. Idempotent; unknown
8196    /// hosts are ignored. Never called with the primary window's container.
8197    fn close_window(&mut self, _host: &Self::Handle) {}
8198
8199    /// End the application: the last window with [`WindowRole::Primary`] has closed
8200    /// (docs/windows.md). day-core decides when, since it owns the window registry and the role
8201    /// each window carries; the backend supplies only the platform's exit:
8202    /// `NSApplication.terminate`, `QCoreApplication::quit`, `GtkApplication.quit`,
8203    /// `PostQuitMessage`. Everything day-core wanted to happen first (secondary windows
8204    /// disposed, `WillTerminate` delivered) already has by the time this is called.
8205    ///
8206    /// The default does nothing, which is right for the backends whose process lifetime is
8207    /// not theirs to end: a browser tab, an Android activity, an iOS scene.
8208    fn quit_app(&mut self) {}
8209
8210    /// Bring the window whose content container is `host` to front and make it key/active:
8211    /// the focus half of open-or-focus singleton windows. Default no-op.
8212    fn focus_window(&mut self, _host: &Self::Handle) {}
8213
8214    /// Retitle the window whose content container is `host`. Default no-op.
8215    fn set_window_title(&mut self, _host: &Self::Handle, _title: &str) {}
8216
8217    /// Resize the window whose content container is `host` to fit `size` of content, and pin it
8218    /// there: what `WindowOptions::size_to_fit` asks for (docs/windows.md).
8219    ///
8220    /// `size` is the content size Day measured, not the window's outer frame: the backend adds
8221    /// its chrome. A settings panel is the case this exists for, and every desktop platform
8222    /// sizes one to its content rather than to a number the app guessed; a fixed height either
8223    /// clips the last row or leaves a band of empty panel under it, and which one you get depends
8224    /// on the user's text size.
8225    ///
8226    /// Default no-op, so a toolkit that cannot resize a live window keeps the size it was
8227    /// opened at, which is what every backend did before this existed.
8228    fn fit_window(&mut self, _host: &Self::Handle, _size: Size) {}
8229
8230    /// Snapshot the window whose content container is `host` (the dayscript `screenshot`
8231    /// step's `window:` target). The default answers the primary snapshot, so backends that
8232    /// never open windows stay correct without changes.
8233    ///
8234    /// # Errors
8235    ///
8236    /// Returns a message when the backend cannot capture that window.
8237    fn snapshot_window_of(&mut self, _host: &Self::Handle) -> Result<Vec<u8>, String> {
8238        self.snapshot_window()
8239    }
8240
8241    /// Apply one property change to the window whose content container is `host`
8242    /// (docs/windows.md "Window properties"). The primary window arrives with its root container,
8243    /// like [`set_window_title`](Self::set_window_title).
8244    ///
8245    /// Fire-and-forget, like [`set_app_badge`](Self::set_app_badge): a change this toolkit cannot
8246    /// make is ignored, and the app probes the matching `Cap` (named on each [`WindowChange`]
8247    /// variant) before relying on it. A change the platform completes later (a fullscreen
8248    /// transition, a zoom animation) reports its outcome through
8249    /// [`Event::WindowStateChanged`], never by assuming the request took. The default ignores
8250    /// every change.
8251    fn apply_window(&mut self, _host: &Self::Handle, _change: &WindowChange) {}
8252
8253    /// True OS window groups, as distinct from native tab widgets.
8254    fn native_window_tabs(&self) -> bool {
8255        false
8256    }
8257    /// Native in-window document/section tab control; OS grouping is reported separately.
8258    fn native_document_tabs(&self) -> bool {
8259        false
8260    }
8261    /// Join/reorder these windows in an OS tab group. Content remains window-owned.
8262    fn group_windows(&mut self, _hosts: &[Self::Handle]) {}
8263    /// Current native order of the group containing this window, including detached groups.
8264    fn window_tab_order(&self, _host: &Self::Handle) -> Vec<NodeId> {
8265        Vec::new()
8266    }
8267
8268    /// Install the app's Dock menu (docs/menus.md "Dock menu"): the items macOS shows above
8269    /// its own when the user right-clicks the app's Dock icon, built from the app's
8270    /// `[[shortcuts]]` and its `dock_menu(..)` entries. Same item model and dispatch as
8271    /// [`set_app_menu`](Self::set_app_menu); an empty slice removes the menu. `Cap::DockMenu`
8272    /// reports support; the default ignores the call.
8273    fn set_dock_menu(&mut self, _items: &[MenuItem]) {}
8274
8275    /// Make the node at `h` move its window when the user drags it, as a title bar does
8276    /// (`.window_drag_region()`, docs/window-chrome.md): the region's own background starts a
8277    /// native window drag (with the platform's snapping and edge tiling), a double click does
8278    /// what the user's title-bar double-click setting says, and controls inside the region keep
8279    /// receiving their own clicks. `false` releases it. `Cap::DragRegion`; the default ignores
8280    /// the call, so on a phone the region is an ordinary view.
8281    fn set_drag_region(&mut self, _h: &Self::Handle, _drag: bool) {}
8282
8283    /// Show these status items, replacing the previous set (docs/status-item.md): add the
8284    /// ones whose `id` is new, update the ones that changed, remove the ones no longer listed.
8285    /// A click on an item runs its `activate` action or opens its menu; menu choices dispatch
8286    /// [`Event::MenuAction`] like the app menu's. `Cap::StatusItem`; the default ignores the
8287    /// call, which is what a phone and the web do.
8288    fn set_status_items(&mut self, _items: &[StatusItemSpec]) {}
8289
8290    /// Show `progress` on the app's Dock or taskbar icon (docs/status-item.md).
8291    /// `Cap::AppProgress`; the default ignores it.
8292    fn set_app_progress(&mut self, _progress: AppProgress) {}
8293
8294    /// Show or hide the app's Dock icon while it runs: a menu-bar app hides it and lives in its
8295    /// status item (macOS activation policy). `Cap::DockVisibility`; the default ignores it.
8296    fn set_dock_visible(&mut self, _visible: bool) {}
8297
8298    /// Keep the process running when its last window closes (docs/windows.md "Keeping the app
8299    /// running"). When `true`, the backend must not end the app on its own as windows close: it
8300    /// reports every close, the first window's included, as `Event::WindowClosed`, and day-core
8301    /// decides whether to call [`quit_app`](Self::quit_app). When `false`, the backend keeps its
8302    /// platform's own rule. A backend whose process lifetime is not its own (a phone, a browser
8303    /// tab) ignores it, which is the default.
8304    fn set_keep_running(&mut self, _keep: bool) {}
8305
8306    /// The displays attached now (docs/windows.md "Monitors"). `Cap::Monitors`; the default
8307    /// answers none, and day-core then describes the primary window's own size as one display.
8308    fn monitors(&self) -> Vec<Monitor> {
8309        Vec::new()
8310    }
8311
8312    /// The outer frame of the window whose content container is `host`, in points on the
8313    /// desktop's coordinate space (top-left origin), or `None` where the platform does not say
8314    /// (a phone, Wayland's positions). Read when the app asks for it and when day-core saves a
8315    /// remembered frame (`WindowOptions::remember_frame`).
8316    fn window_frame(&self, _host: &Self::Handle) -> Option<Rect> {
8317        None
8318    }
8319
8320    /// Replace the launcher shortcuts the app set while running (docs/deep-links.md "Launcher
8321    /// shortcuts"), shown beside the ones Day.toml declares: iOS Home Screen quick actions,
8322    /// Android dynamic shortcuts, the macOS Dock menu. Each opens its route through the deep-link
8323    /// intake. `Cap::DynamicShortcuts`; the default ignores the call.
8324    fn set_launcher_shortcuts(&mut self, _shortcuts: &[LauncherShortcut]) {}
8325}
8326
8327/// What a secondary window is, so backends can apply platform conventions (docs/windows.md).
8328#[derive(Clone, Copy, PartialEq, Eq, Debug)]
8329pub enum WindowKind {
8330    /// A regular document/tool window: resizable, miniaturizable, platform-default tabbing.
8331    Normal,
8332    /// A settings/preferences window: singleton by convention; macOS disallows window
8333    /// tabbing and drops the resize/minimize chrome, mobile presents it modally. Pairs with
8334    /// day-core's key-singleton reopen (`open_window` with a key).
8335    Preferences,
8336    /// The About window (docs/settings.md): the same fixed, centered, untabbed panel chrome
8337    /// as [`Self::Preferences`] (every desktop treats the two alike), presented modally on
8338    /// mobile. Singleton under day-core's `day.about` key.
8339    About,
8340}
8341
8342impl WindowKind {
8343    /// Whether this is a panel (settings or About) rather than a document window: the kinds
8344    /// every desktop draws fixed-size, centered and out of the Window menu, and mobile presents
8345    /// as a cover.
8346    #[must_use]
8347    pub fn is_panel(self) -> bool {
8348        !matches!(self, WindowKind::Normal)
8349    }
8350}
8351
8352/// Whether a window keeps the app alive (docs/windows.md close policy).
8353///
8354/// A separate axis from [`WindowKind`], which describes chrome. They correlate (a
8355/// preferences panel is the archetypal window that should not hold an app open), but they are
8356/// not the same question, and conflating them would leave no way to say "an ordinary-looking
8357/// tool window that shouldn't outlive the documents".
8358///
8359/// Note the word "secondary" is overloaded around windows: elsewhere in day it means "a window
8360/// other than the first one opened". Here it means "does not keep the app alive", which is
8361/// about lifetime, not about order of creation.
8362#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
8363pub enum WindowRole {
8364    /// Closing the last one of these ends the app.
8365    #[default]
8366    Primary,
8367    /// Never keeps the app alive: when the last `Primary` closes, the app exits and takes
8368    /// these with it, however many are open.
8369    Secondary,
8370}
8371
8372impl From<WindowKind> for WindowRole {
8373    /// The default pairing: an ordinary window holds the app open, a preferences panel does
8374    /// not. An app that needs a different answer sets the role itself.
8375    fn from(kind: WindowKind) -> WindowRole {
8376        match kind {
8377            WindowKind::Normal => WindowRole::Primary,
8378            WindowKind::Preferences | WindowKind::About => WindowRole::Secondary,
8379        }
8380    }
8381}
8382
8383/// A backend's answer to [`Toolkit::open_window`] (docs/windows.md).
8384pub enum WindowOpenReply<H> {
8385    /// The window exists now; here is its content container (desktop backends).
8386    Open(H),
8387    /// Native creation started but completes asynchronously (a scene, an activity, an
8388    /// ability); the backend will call `day_core::finish_window_open` when the content
8389    /// container exists. day-core parks the window record until then.
8390    Pending,
8391    /// This toolkit cannot open windows (`Cap::MultiWindow` = `Unsupported`); day-core
8392    /// falls back to presenting the content as a fullscreen cover in the primary window.
8393    Unsupported,
8394}
8395
8396/// How a window is shown (docs/windows.md "Window properties"): what the window's `state()`
8397/// signal holds and what [`WindowChange::State`] asks for.
8398#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
8399pub enum WindowState {
8400    /// On screen at its own size: neither minimized, maximized nor fullscreen.
8401    #[default]
8402    Normal,
8403    /// Minimized to the Dock, taskbar or shelf. `Cap::WindowStates`.
8404    Minimized,
8405    /// Zoomed to fill the screen's work area, keeping its chrome. `Cap::WindowStates`.
8406    Maximized,
8407    /// Covering the whole screen with no window chrome; on a phone, the system bars hidden.
8408    /// `Cap::WindowFullscreen`.
8409    Fullscreen,
8410}
8411
8412impl WindowState {
8413    /// The wire code of [`bridge::BridgeKind::WindowStateChanged`].
8414    #[must_use]
8415    pub const fn code(self) -> i32 {
8416        match self {
8417            WindowState::Normal => 0,
8418            WindowState::Minimized => 1,
8419            WindowState::Maximized => 2,
8420            WindowState::Fullscreen => 3,
8421        }
8422    }
8423
8424    /// The state a wire code names; an unknown code reads as `Normal`.
8425    #[must_use]
8426    pub const fn from_code(code: i32) -> WindowState {
8427        match code {
8428            1 => WindowState::Minimized,
8429            2 => WindowState::Maximized,
8430            3 => WindowState::Fullscreen,
8431            _ => WindowState::Normal,
8432        }
8433    }
8434}
8435
8436/// How a window stacks against other apps' windows ([`WindowChange::Level`], `Cap::WindowLevel`).
8437#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
8438pub enum WindowLevel {
8439    /// Ordinary stacking: the focused app's windows come forward.
8440    #[default]
8441    Normal,
8442    /// Stays above other apps' ordinary windows: a palette, a timer, a video peek.
8443    Floating,
8444}
8445
8446/// How strongly a window asks for the user's attention ([`WindowChange::RequestAttention`]).
8447#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
8448pub enum Attention {
8449    /// Once: one Dock bounce, a taskbar button that flashes a few times.
8450    #[default]
8451    Informational,
8452    /// Until the user switches to the app.
8453    Critical,
8454}
8455
8456/// One change to one window (docs/windows.md "Window properties"), carried by
8457/// [`Toolkit::apply_window`]. Each variant names the `Cap` that reports whether the running
8458/// toolkit makes it.
8459#[derive(Clone, Debug, PartialEq)]
8460pub enum WindowChange {
8461    /// Minimize, zoom, take fullscreen, or return to normal. `Cap::WindowStates` for the
8462    /// first two, `Cap::WindowFullscreen` for fullscreen. The outcome comes back as
8463    /// [`Event::WindowStateChanged`].
8464    State(WindowState),
8465    /// Keep the window's content out of screenshots, recordings and screen sharing.
8466    /// `Cap::ContentProtection`.
8467    ContentProtected(bool),
8468    /// Move and/or resize. `origin` is the outer frame's top-left corner in points on the
8469    /// desktop's coordinate space (top-left origin, `Cap::WindowPosition`); `size` is the size Day
8470    /// lays the content out at, in points, the same size `WindowResized` reports
8471    /// (`Cap::WindowGeometry`): the backend adds its own chrome around it.
8472    Frame {
8473        origin: Option<Point>,
8474        size: Option<Size>,
8475    },
8476    /// The content size the user can resize the window to. `None` lifts that bound.
8477    /// `Cap::WindowGeometry`.
8478    Limits {
8479        min: Option<Size>,
8480        max: Option<Size>,
8481    },
8482    /// Stacking against other apps' windows. `Cap::WindowLevel`.
8483    Level(WindowLevel),
8484    /// Show the window on every virtual desktop / Space. `Cap::WindowLevel`.
8485    OnAllWorkspaces(bool),
8486    /// Leave the window out of the taskbar and the window switcher. `Cap::WindowLevel`.
8487    SkipTaskbar(bool),
8488    /// Whether the user can resize the window. `Cap::WindowGeometry`.
8489    Resizable(bool),
8490    /// Whether the window offers a minimize control. `Cap::WindowStates`.
8491    Minimizable(bool),
8492    /// Whether the window offers a maximize / zoom control. `Cap::WindowStates`.
8493    Maximizable(bool),
8494    /// Whether the window offers a close control. `Cap::WindowStates`.
8495    Closable(bool),
8496    /// Hide the window without closing it, or show it again. `Cap::WindowStates`.
8497    Visible(bool),
8498    /// This window's light/dark override over the app-wide [`Toolkit::set_appearance`].
8499    /// `Cap::WindowAppearance`.
8500    Appearance(Option<bool>),
8501    /// Bounce the Dock icon, flash the taskbar button. `Cap::RequestAttention`.
8502    RequestAttention(Attention),
8503}
8504
8505/// The frame a window wears (docs/window-chrome.md), set once when it opens.
8506#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
8507pub enum WindowChrome {
8508    /// The platform's title bar and frame.
8509    #[default]
8510    Standard,
8511    /// The content runs to the window's top edge, under the title bar, and the platform's own
8512    /// window controls (close, minimize, zoom) stay where they are. For a custom title bar: the
8513    /// backend reports the bar's height as the window's safe-area top inset (`day::safe_area()`),
8514    /// so the app pads its content by it and paints its background under it. Mark the draggable
8515    /// part with `.window_drag_region()`. `Cap::OverlayTitleBar`; where unsupported the window
8516    /// keeps its standard bar.
8517    Overlay,
8518    /// No title bar and no frame: a splash screen, a heads-up panel, a borderless utility. The
8519    /// window still resizes from its edges when resizable; mark the part that moves it with
8520    /// `.window_drag_region()`. `Cap::FramelessWindow`; where unsupported the window keeps its
8521    /// standard frame.
8522    Frameless,
8523}
8524
8525/// What shows behind a window's content (docs/window-chrome.md).
8526#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
8527pub enum WindowBackground {
8528    /// The platform's window background.
8529    #[default]
8530    Opaque,
8531    /// Nothing: pixels the content leaves unpainted show the desktop through the window. For
8532    /// rounded or shaped splash screens and overlays. `Cap::TransparentWindow`.
8533    Transparent,
8534    /// A translucent system material that blurs what is behind the window.
8535    /// `Cap::WindowMaterial`; where unsupported the window stays opaque.
8536    Material(WindowMaterial),
8537}
8538
8539/// The system materials a window background can use ([`WindowBackground::Material`]).
8540#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
8541pub enum WindowMaterial {
8542    /// The main-window material: macOS's window background, Windows 11's Mica.
8543    Window,
8544    /// A sidebar or source list: macOS's sidebar material, Windows 11's Mica Alt (tabbed).
8545    Sidebar,
8546    /// A transient surface (a popover, a menu-like panel, a heads-up display): macOS's popover
8547    /// material, Windows 11's Acrylic.
8548    Transient,
8549}
8550
8551/// Where a window opens ([`WindowOptions::placement`]).
8552#[derive(Clone, Copy, Debug, Default, PartialEq)]
8553pub enum WindowPlacement {
8554    /// The platform's choice: macOS cascades, Windows and Linux let the window manager decide.
8555    #[default]
8556    Automatic,
8557    /// Centered on the screen with the active window.
8558    Centered,
8559    /// The outer frame's top-left corner at this point, in points on the desktop's coordinate
8560    /// space (top-left origin). Falls back to `Automatic` without `Cap::WindowPosition`.
8561    At(Point),
8562}
8563
8564/// A small runtime RGBA image for a status item: charts, meters, or a grid of results.
8565///
8566/// Rows run top to bottom; samples are tightly packed, non-premultiplied sRGB RGBA8.
8567/// `scale` is pixels per logical point (2 for Retina). This owns its bytes, independent of
8568/// any window or decoded-image registry. Currently rendered by AppKit; other backends use
8569/// [`StatusItemSpec::icon`] as a fallback. See docs/status-item.md.
8570#[derive(Clone, PartialEq)]
8571pub struct StatusImage {
8572    width: u32,
8573    height: u32,
8574    scale: f64,
8575    rgba: std::sync::Arc<[u8]>,
8576}
8577
8578impl StatusImage {
8579    /// Validate a runtime image. Rejects empty/mismatched pixels, invalid scales, and images
8580    /// exceeding 16 MiB or 4096 logical points on either axis. No platform allocation occurs.
8581    pub fn rgba(
8582        width: u32,
8583        height: u32,
8584        scale: f64,
8585        pixels: impl Into<std::sync::Arc<[u8]>>,
8586    ) -> Option<Self> {
8587        let rgba = pixels.into();
8588        let expected = (width as usize)
8589            .checked_mul(height as usize)?
8590            .checked_mul(4)?;
8591        if width == 0
8592            || height == 0
8593            || expected > 16 * 1024 * 1024
8594            || rgba.len() != expected
8595            || !scale.is_finite()
8596            || scale <= 0.0
8597            || f64::from(width) / scale > 4096.0
8598            || f64::from(height) / scale > 4096.0
8599        {
8600            return None;
8601        }
8602        Some(Self {
8603            width,
8604            height,
8605            scale,
8606            rgba,
8607        })
8608    }
8609
8610    #[must_use]
8611    pub fn width(&self) -> u32 {
8612        self.width
8613    }
8614    #[must_use]
8615    pub fn height(&self) -> u32 {
8616        self.height
8617    }
8618    #[must_use]
8619    pub fn scale(&self) -> f64 {
8620        self.scale
8621    }
8622    #[must_use]
8623    pub fn pixels(&self) -> &[u8] {
8624        &self.rgba
8625    }
8626    pub fn size(&self) -> Size {
8627        Size::new(
8628            f64::from(self.width) / self.scale,
8629            f64::from(self.height) / self.scale,
8630        )
8631    }
8632}
8633
8634impl std::fmt::Debug for StatusImage {
8635    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
8636        f.debug_struct("StatusImage")
8637            .field("width", &self.width)
8638            .field("height", &self.height)
8639            .field("scale", &self.scale)
8640            .field("bytes", &self.rgba.len())
8641            .finish()
8642    }
8643}
8644
8645#[cfg(test)]
8646mod status_image_tests {
8647    use super::*;
8648
8649    #[test]
8650    fn validates_pixel_layout_and_logical_size() {
8651        let image = StatusImage::rgba(120, 36, 2.0, vec![255; 120 * 36 * 4]).unwrap();
8652        assert_eq!(image.size(), Size::new(60.0, 18.0));
8653        assert_eq!(image.clone(), image);
8654        assert!(StatusImage::rgba(0, 1, 1.0, vec![]).is_none());
8655        assert!(StatusImage::rgba(1, 1, 1.0, vec![0; 3]).is_none());
8656        assert!(StatusImage::rgba(u32::MAX, u32::MAX, 1.0, vec![]).is_none());
8657        for scale in [0.0, -1.0, f64::NAN, f64::INFINITY, 0.00001] {
8658            assert!(StatusImage::rgba(1, 1, scale, vec![0; 4]).is_none());
8659        }
8660    }
8661}
8662
8663/// One status item: an icon in the menu bar (macOS), the notification area (Windows) or a
8664/// `StatusNotifierItem` host's tray (Linux), with a menu (docs/status-item.md).
8665#[derive(Clone, Debug, PartialEq)]
8666pub struct StatusItemSpec {
8667    /// The app's name for the item, stable across updates: what a backend diffs by.
8668    pub id: String,
8669    /// The glyph. `None` shows the title alone (macOS) or the app's icon (elsewhere).
8670    pub icon: Option<Icon>,
8671    /// A runtime image. AppKit prefers this over `icon`, preserving aspect ratio and point
8672    /// size up to 18pt high; other backends ignore it and show `icon`/`title` as before.
8673    pub raster: Option<StatusImage>,
8674    /// Draw the icon as a template: its shape only, in the menu bar's or panel's own color, so
8675    /// it reads in light and dark. Symbols are always templates.
8676    pub template: bool,
8677    /// Text beside the icon where the platform shows one (the macOS menu bar). Empty: icon only.
8678    pub title: String,
8679    /// The hover text.
8680    pub tooltip: String,
8681    /// The menu the item opens. Same model and dispatch as the app menu.
8682    pub menu: Vec<MenuItem>,
8683    /// A dispatch id (the [`Event::MenuAction`] registry) run when the user clicks the item
8684    /// itself, where the platform separates a click from opening the menu (a left click on macOS
8685    /// and Windows, the host's "activate" on Linux). 0: a click opens the menu.
8686    pub activate: u64,
8687}
8688
8689/// One display (docs/windows.md "Monitors"), in points on the desktop's coordinate space:
8690/// top-left origin at the primary display's top-left corner.
8691#[derive(Clone, Debug, PartialEq)]
8692pub struct Monitor {
8693    /// Stable for the display across launches where the platform offers it (a display UUID, a
8694    /// connector name); an index otherwise.
8695    pub id: String,
8696    /// The display's name, for a picker ("Built-in Retina Display", "DELL U2720Q").
8697    pub name: String,
8698    /// The display's whole area.
8699    pub frame: Rect,
8700    /// The part windows should use: the frame minus the menu bar, Dock, taskbar or panels.
8701    pub work_area: Rect,
8702    /// Device pixels per point.
8703    pub scale: f64,
8704    /// The display the desktop's menu bar or primary taskbar is on.
8705    pub primary: bool,
8706}
8707
8708/// A launcher shortcut the app sets while it runs (docs/deep-links.md "Launcher shortcuts"): a
8709/// route to open and the label the launcher shows, already localized.
8710#[derive(Clone, Debug, PartialEq, Eq)]
8711pub struct LauncherShortcut {
8712    /// The route the shortcut opens, through the deep-link intake.
8713    pub route: String,
8714    /// What the launcher shows.
8715    pub label: String,
8716}
8717
8718/// A progress indicator on the app's Dock or taskbar icon ([`Toolkit::set_app_progress`],
8719/// docs/status-item.md).
8720#[derive(Clone, Copy, Debug, Default, PartialEq)]
8721pub enum AppProgress {
8722    /// No indicator.
8723    #[default]
8724    None,
8725    /// Work of unknown length.
8726    Indeterminate,
8727    /// A fraction done, 0.0 to 1.0.
8728    Value(f64),
8729    /// A fraction done, paused. Platforms without a paused state show `Value`.
8730    Paused(f64),
8731    /// A fraction done when the work failed. Platforms without an error state show `Value`.
8732    Error(f64),
8733}
8734
8735/// Whether and how a window joins macOS window tabs ([`WindowOptions::tabbing`],
8736/// `Cap::WindowTabbing`). Other platforms have no system window tabs and ignore it.
8737#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
8738pub enum WindowTabbing {
8739    /// The platform default for the window's kind: an ordinary window tabs with the app's other
8740    /// ordinary windows when the user's "Prefer tabs" setting says so; preferences never tab.
8741    #[default]
8742    Automatic,
8743    /// Tab only with windows of the same group, following the user's setting. The tab bar's
8744    /// "+" opens the builder registered for this group (`register_new_window_for`).
8745    Group(String),
8746    /// Always open as a tab of an existing window of the same group, whatever the setting.
8747    Preferred(String),
8748    /// Never become a tab.
8749    Disallowed,
8750}
8751
8752/// An app's generated locale catalog: `(DEFAULT, CATALOG)`, exactly what `day-build` emits as
8753/// `res::locales::{DEFAULT, CATALOG}` (§18.5). Carried in [`WindowOptions::locales`] so the
8754/// framework can install it at the one moment that is correct.
8755pub type AppLocales = (&'static str, &'static [(&'static str, &'static str)]);
8756
8757#[derive(Clone, Debug)]
8758pub struct WindowOptions {
8759    pub title: String,
8760    pub size: Size,
8761    pub min_size: Option<Size>,
8762    /// Create and mount the window without showing it or activating the app. Supported on
8763    /// AppKit; other backends currently ignore this option. Defaults to false.
8764    ///
8765    /// Menu-bar apps can keep their initial host hidden and open Preferences on demand.
8766    /// The window still exists and can be shown with `WindowHandle::set_visible(true)`;
8767    /// this does not change the app's keep-running policy.
8768    pub start_hidden: bool,
8769    /// Ask the backend to size this window to its content once it has been built and laid out,
8770    /// rather than keeping [`Self::size`] (docs/windows.md). `size` still decides the width and
8771    /// acts as the height ceiling, so a panel with more content than fits the screen scrolls
8772    /// instead of growing past it.
8773    ///
8774    /// What a preferences panel wants on every desktop. Ignored by backends that cannot resize a
8775    /// live window, and by the ones with no windows at all.
8776    pub size_to_fit: bool,
8777    /// The app's display name for the standard application menu / About (macOS). `None` falls back
8778    /// to `title`; set it when `title` carries extra decoration you don't want in `About <name>`
8779    /// (e.g. the showcase's window title is "Day Showcase (AppKit)" but its app name is "Showcase").
8780    pub app_name: Option<String>,
8781    /// The app's locale catalog, installed by `day::launch` (docs/localization.md).
8782    ///
8783    /// The order is why this is the framework's job: the OS's languages reach day-localization from the
8784    /// live backend, and the catalog has to be registered after that hint and before the first
8785    /// localized string is read. An app that installs it itself (before `launch`, where there
8786    /// is no backend yet) registers against an empty hint list and resolves to `DEFAULT`, so a
8787    /// French device opens an English window.
8788    pub locales: Option<AppLocales>,
8789    /// The title, computed once the catalog above is installed: how a window title comes from
8790    /// the catalog rather than a literal. Takes precedence over [`Self::title`], which stays the
8791    /// fallback for the moment before (and for apps with nothing to translate).
8792    ///
8793    /// A plain `fn` rather than a closure: this struct is `Clone`, and the callers are a
8794    /// non-capturing `|| res::str::app_title().format()`, which coerces.
8795    pub title_fn: Option<fn() -> String>,
8796    /// The app's version, for Day's exit line (`Clean exit for <app> v<version> …`,
8797    /// docs/lifecycle.md): `env!("CARGO_PKG_VERSION")` in the app crate, which the scaffold's
8798    /// `window()` sets. `None` falls back to the `DAY_APP_VERSION` the `day` CLI sets on a launch.
8799    pub version: Option<String>,
8800    /// macOS window tabbing for this window (`Cap::WindowTabbing`); ignored elsewhere.
8801    pub tabbing: WindowTabbing,
8802    /// The window's frame: standard, a title bar the content runs under, or none
8803    /// (docs/window-chrome.md). Desktop only; phones and the web ignore it.
8804    pub chrome: WindowChrome,
8805    /// What shows behind the content: the window background, nothing, or a system material.
8806    pub background: WindowBackground,
8807    /// Whether the window casts the platform's drop shadow. A transparent, shaped window often
8808    /// wants none.
8809    pub shadow: bool,
8810    /// Whether the user can resize the window by its edges.
8811    pub resizable: bool,
8812    /// Where the window opens.
8813    pub placement: WindowPlacement,
8814    /// The largest content size the user can resize the window to (`Cap::WindowGeometry`).
8815    pub max_size: Option<Size>,
8816    /// Remember this window's size, position and maximized state under this key, and reopen it
8817    /// that way next launch (docs/windows.md "Remembered frames"). A position that no attached
8818    /// display shows any more is dropped, so a window never reopens off-screen.
8819    pub remember_frame: Option<String>,
8820    /// The logical window this opens (docs/windows.md): `open_window` focuses an already-open
8821    /// window with the same key instead of opening a second (the preferences pattern). `None`
8822    /// always opens a new one.
8823    pub key: Option<String>,
8824    /// The kind of window: a regular one, a preferences panel, an About panel.
8825    pub kind: WindowKind,
8826}
8827
8828impl WindowOptions {
8829    /// The window title. Replaces a [`title_fn`](Self::title_fn) set earlier (the generated
8830    /// `res::window_options()` sets one), so the last title named wins.
8831    #[must_use]
8832    pub fn title(mut self, title: impl Into<String>) -> Self {
8833        self.title = title.into();
8834        self.title_fn = None;
8835        self
8836    }
8837    /// The content size the window opens at (desktop; phones fill the screen).
8838    #[must_use]
8839    pub fn size(mut self, width: f64, height: f64) -> Self {
8840        self.size = Size::new(width, height);
8841        self
8842    }
8843    /// The smallest content size the user can resize to.
8844    #[must_use]
8845    pub fn min_size(mut self, width: f64, height: f64) -> Self {
8846        self.min_size = Some(Size::new(width, height));
8847        self
8848    }
8849    /// The largest content size the user can resize to (`Cap::WindowGeometry`).
8850    #[must_use]
8851    pub fn max_size(mut self, width: f64, height: f64) -> Self {
8852        self.max_size = Some(Size::new(width, height));
8853        self
8854    }
8855    /// Create and mount the window without showing it; see [`Self::start_hidden`].
8856    #[must_use]
8857    pub fn start_hidden(mut self) -> Self {
8858        self.start_hidden = true;
8859        self
8860    }
8861    /// Size the window to its content once built; see [`Self::size_to_fit`].
8862    #[must_use]
8863    pub fn size_to_fit(mut self) -> Self {
8864        self.size_to_fit = true;
8865        self
8866    }
8867    /// The app's display name for the application menu and About; see [`Self::app_name`].
8868    #[must_use]
8869    pub fn app_name(mut self, name: impl Into<String>) -> Self {
8870        self.app_name = Some(name.into());
8871        self
8872    }
8873    /// The app's locale catalog, as `res::locales::{DEFAULT, CATALOG}`; see [`Self::locales`].
8874    #[must_use]
8875    pub fn locales(
8876        mut self,
8877        default: &'static str,
8878        catalog: &'static [(&'static str, &'static str)],
8879    ) -> Self {
8880        self.locales = Some((default, catalog));
8881        self
8882    }
8883    /// The title, computed once the catalog is installed; see [`Self::title_fn`].
8884    #[must_use]
8885    pub fn title_fn(mut self, f: fn() -> String) -> Self {
8886        self.title_fn = Some(f);
8887        self
8888    }
8889    /// The app's version, for Day's exit line; see [`Self::version`].
8890    #[must_use]
8891    pub fn version(mut self, version: impl Into<String>) -> Self {
8892        self.version = Some(version.into());
8893        self
8894    }
8895    /// macOS window tabbing for this window; see [`Self::tabbing`].
8896    #[must_use]
8897    pub fn tabbing(mut self, tabbing: WindowTabbing) -> Self {
8898        self.tabbing = tabbing;
8899        self
8900    }
8901    /// The window's frame; see [`Self::chrome`].
8902    #[must_use]
8903    pub fn chrome(mut self, chrome: WindowChrome) -> Self {
8904        self.chrome = chrome;
8905        self
8906    }
8907    /// What shows behind the content; see [`Self::background`].
8908    #[must_use]
8909    pub fn background(mut self, background: WindowBackground) -> Self {
8910        self.background = background;
8911        self
8912    }
8913    /// No drop shadow, for a transparent or shaped window; see [`Self::shadow`].
8914    #[must_use]
8915    pub fn no_shadow(mut self) -> Self {
8916        self.shadow = false;
8917        self
8918    }
8919    /// A window the user cannot resize; see [`Self::resizable`].
8920    #[must_use]
8921    pub fn fixed_size(mut self) -> Self {
8922        self.resizable = false;
8923        self
8924    }
8925    /// Where the window opens; see [`Self::placement`].
8926    #[must_use]
8927    pub fn placement(mut self, placement: WindowPlacement) -> Self {
8928        self.placement = placement;
8929        self
8930    }
8931    /// Remember and restore this window's frame under `key`; see [`Self::remember_frame`].
8932    #[must_use]
8933    pub fn remember_frame(mut self, key: impl Into<String>) -> Self {
8934        self.remember_frame = Some(key.into());
8935        self
8936    }
8937    /// The logical window this opens; see [`Self::key`].
8938    #[must_use]
8939    pub fn key(mut self, key: impl Into<String>) -> Self {
8940        self.key = Some(key.into());
8941        self
8942    }
8943    /// The kind of window; see [`Self::kind`].
8944    #[must_use]
8945    pub fn kind(mut self, kind: WindowKind) -> Self {
8946        self.kind = kind;
8947        self
8948    }
8949}
8950
8951impl Default for WindowOptions {
8952    fn default() -> Self {
8953        WindowOptions {
8954            title: "Day".into(),
8955            size: Size::new(480.0, 640.0),
8956            min_size: None,
8957            start_hidden: false,
8958            size_to_fit: false,
8959            app_name: None,
8960            locales: None,
8961            title_fn: None,
8962            version: None,
8963            tabbing: WindowTabbing::Automatic,
8964            chrome: WindowChrome::Standard,
8965            background: WindowBackground::Opaque,
8966            shadow: true,
8967            resizable: true,
8968            placement: WindowPlacement::Automatic,
8969            max_size: None,
8970            remember_frame: None,
8971            key: None,
8972            kind: WindowKind::Normal,
8973        }
8974    }
8975}
8976
8977/// A platform backend: owns the native main loop and exactly one window in v1 (§8.1).
8978///
8979/// `run` sets up the native app + window, installs the reactive scheduler + main poster,
8980/// then hands `(self, root_container, content_size)` to `ready` (which mounts the tree and
8981/// takes ownership of the backend), and finally runs the native main loop.
8982pub trait Platform: Toolkit {
8983    /// The process-constant target id, e.g. `"macos-appkit"`.
8984    const TARGET: &'static str;
8985    /// The toolkit half of the target, e.g. `"appkit"`.
8986    const TOOLKIT: &'static str;
8987    /// Whether [`Platform::run`] returning means the app is over. True for a backend that
8988    /// drives the native loop itself until the app quits (GTK, Qt, XAML; AppKit's never
8989    /// returns). False where the host owns the loop and `run` hands back at once, with the
8990    /// app still to come (ArkUI's ability, Android's activity, the web page, the mock's test):
8991    /// their `DidExit` is the host's last callback, not the return (docs/lifecycle.md).
8992    const RUN_ENDS_APP: bool = true;
8993
8994    fn run(self, options: WindowOptions, ready: Box<dyn FnOnce(Self, Self::Handle, Size)>);
8995
8996    /// Post a closure onto the native main loop. Callable from any thread; this is the
8997    /// single door the reactive scheduler and `Setter` deliveries ride (§3.3).
8998    fn post(f: Box<dyn FnOnce() + Send>);
8999
9000    /// Post `f` onto the native main loop after (at least) `ms` milliseconds: the timer
9001    /// door behind `day::sleep` (docs/async.md). Every shipped backend overrides it with the
9002    /// loop's own timer (`dispatch_after`, `Handler.postDelayed`, `g_timeout_add`,
9003    /// `QTimer::singleShot`, `SetTimer`, `setTimeout`), so a sleep costs no thread. The
9004    /// default is the fallback for a backend without one: a helper thread that sleeps the
9005    /// whole delay and rides [`Platform::post`] home. It is correct, but a thread per sleep
9006    /// adds up under a ticking loop, so the first use says so once in the log.
9007    fn post_delayed(ms: u32, f: Box<dyn FnOnce() + Send>) {
9008        static SAID: std::sync::Once = std::sync::Once::new();
9009        SAID.call_once(|| {
9010            log::warn!(
9011                "day: {} has no native timer door; `day::sleep` falls back to a helper thread \
9012                 per delay (implement `Platform::post_delayed`)",
9013                Self::TARGET
9014            );
9015        });
9016        std::thread::spawn(move || {
9017            std::thread::sleep(std::time::Duration::from_millis(u64::from(ms)));
9018            Self::post(f);
9019        });
9020    }
9021
9022    /// Ordered OS locale preference list (BCP-47), for fluent-langneg (§12.2).
9023    fn locale_hints(&self) -> Vec<String> {
9024        Vec::new()
9025    }
9026}
9027
9028// ---------------------------------------------------------------------------
9029// Open renderer registry (§8.2)
9030// ---------------------------------------------------------------------------
9031
9032/// The scale a window snapshot is rendered at, when a scripted run states one
9033/// (`DAY_CAPTURE_SCALE=2`, set by `day launch --script` from Day.toml `[screenshots]`).
9034///
9035/// For the backends that render their own snapshot (GTK, Qt): the capture then measures
9036/// window points times this, whatever display the host has, which is what makes a CI capture
9037/// under a 1x xvfb the same 2560x1600 pixels a HiDPI laptop produces. A backend that reads the
9038/// compositor's pixels back (AppKit, XAML) captures at the display's own scale and ignores it.
9039/// `None` when unset or unparseable: capture at the backend's natural scale.
9040#[must_use]
9041pub fn capture_scale() -> Option<f64> {
9042    std::env::var("DAY_CAPTURE_SCALE")
9043        .ok()
9044        .and_then(|v| v.trim().parse::<f64>().ok())
9045        .filter(|s| s.is_finite() && (0.5..=4.0).contains(s))
9046}
9047
9048/// Seconds on a monotonic clock since the first call: the frame timestamp for a backend that
9049/// does not expose a native timestamp (§8.4). The origin is arbitrary. Not for the web
9050/// build, where `Instant` is unavailable and `requestAnimationFrame` stamps the frame itself.
9051pub fn frame_timestamp() -> f64 {
9052    static ORIGIN: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new();
9053    ORIGIN
9054        .get_or_init(std::time::Instant::now)
9055        .elapsed()
9056        .as_secs_f64()
9057}
9058
9059/// The user's language preference from the POSIX environment, newest-first, as BCP-47 tags.
9060///
9061/// `LANGUAGE` is the GNU multi-language list (`fr:en`); `LC_ALL`, `LC_MESSAGES` and `LANG` each
9062/// carry one locale in POSIX form (`fr_FR.UTF-8`), which becomes `fr-FR`. Shared by the backends
9063/// whose platform has no richer API to ask (§12.2, docs/localization.md).
9064#[must_use]
9065pub fn posix_locale_hints() -> Vec<String> {
9066    let mut out: Vec<String> = Vec::new();
9067    let mut push = |tag: &str| {
9068        // "C" and "POSIX" are the absence of a preference, not a language.
9069        let tag = tag.split('.').next().unwrap_or(tag).replace('_', "-");
9070        if tag.is_empty() || tag == "C" || tag == "POSIX" {
9071            return;
9072        }
9073        if !out.contains(&tag) {
9074            out.push(tag);
9075        }
9076    };
9077    if let Ok(list) = std::env::var("LANGUAGE") {
9078        for tag in list.split(':') {
9079            push(tag);
9080        }
9081    }
9082    for key in ["LC_ALL", "LC_MESSAGES", "LANG"] {
9083        if let Ok(v) = std::env::var(key) {
9084            push(&v);
9085        }
9086    }
9087    out
9088}
9089
9090/// Optional custom measure for a third-party piece (§8.2).
9091pub type MeasureFn<B> = fn(&mut B, &<B as Toolkit>::Handle, Proposal) -> Size;
9092
9093/// A third-party piece's per-toolkit implementation. `make` receives the concrete backend
9094/// (public helper surface) and returns a native handle the backend then owns like any built-in.
9095pub struct Renderer<B: Toolkit> {
9096    pub kind: PieceKind,
9097    pub make: fn(&mut B, &dyn Any, NodeId) -> B::Handle,
9098    pub update: fn(&mut B, &B::Handle, &dyn Any),
9099    pub measure: Option<MeasureFn<B>>,
9100    /// Teardown, run from the release queue just before [`Toolkit::release`] frees the handle.
9101    ///
9102    /// A piece that keeps per-view state (a retained delegate, a session map, a native
9103    /// observer) has no other place to drop it: `make`/`update` are the only other hooks, and a
9104    /// disposed node never calls them again. Without this a piece leaks one entry per realized
9105    /// view, and any map keyed by the handle's address can go on to answer for a later view that
9106    /// the allocator hands the same address.
9107    ///
9108    /// `None` for the pieces that own nothing (most of them).
9109    pub release: Option<fn(&mut B, &B::Handle)>,
9110}
9111
9112pub struct Registry<B: Toolkit> {
9113    map: HashMap<PieceKind, Renderer<B>>,
9114}
9115
9116impl<B: Toolkit> Default for Registry<B> {
9117    fn default() -> Self {
9118        Registry {
9119            map: HashMap::new(),
9120        }
9121    }
9122}
9123
9124impl<B: Toolkit> Registry<B> {
9125    pub fn register(&mut self, r: Renderer<B>) {
9126        let kind = r.kind;
9127        if self.map.insert(kind, r).is_some() {
9128            // Two pieces claiming one kind is last-linked-wins in link order, effectively
9129            // nondeterministic. Fail loudly in debug; in release, say so once at boot rather
9130            // than render the wrong widget silently.
9131            debug_assert!(
9132                false,
9133                "duplicate renderer registered for piece kind {kind:?}"
9134            );
9135            log::warn!("duplicate renderer for piece kind {kind:?} — later registration wins");
9136        }
9137    }
9138    #[must_use]
9139    pub fn get(&self, kind: PieceKind) -> Option<&Renderer<B>> {
9140        self.map.get(kind)
9141    }
9142    pub fn kinds(&self) -> impl Iterator<Item = PieceKind> + '_ {
9143        self.map.keys().copied()
9144    }
9145}
9146
9147/// The canvas wire op codes (§11, §15.3): slot 0 of every 9-number record in
9148/// [`encode_ops`]'s output. The numeric values are the frozen wire contract: the JNI, C++,
9149/// and JS decoders each hand-write these as constants, so a value here may never be reused
9150/// or renumbered; new ops append. `ALL` drives the density test that keeps this enum and
9151/// the encoder in step.
9152#[derive(Clone, Copy, Debug, PartialEq, Eq)]
9153#[repr(i32)]
9154pub enum OpCode {
9155    /// Fill a rect (a,b=origin, c,d=size).
9156    FillRect = 0,
9157    /// Stroke a rect (g=width).
9158    StrokeRect = 1,
9159    /// Fill a rounded rect (e=radius).
9160    FillRrect = 2,
9161    /// Fill an ellipse in a rect.
9162    FillEllipse = 3,
9163    /// Stroke an ellipse (g=width).
9164    StrokeEllipse = 4,
9165    /// Stroke an arc (e=start°, f=sweep°, g=width). `Fill(Shape::Arc)` also encodes as
9166    /// this with width 0, the known asymmetry; see [`encode_ops`].
9167    StrokeArc = 5,
9168    /// Line a,b → c,d (g=width).
9169    Line = 6,
9170    /// Text at a,b (e=size, f=anchor: 0 leading / 1 centered); the string rides the texts
9171    /// channel.
9172    Text = 7,
9173    /// Save the graphics state.
9174    Save = 8,
9175    /// Restore the graphics state.
9176    Restore = 9,
9177    /// Concat an affine transform (a..f).
9178    Concat = 10,
9179    /// Fill a polygon; points ride the texts channel as "x,y x,y …" (closed automatically),
9180    /// or the geometry channel of [`encode_ops_with_geometry`] (b = offset, c = count, and
9181    /// the texts entry is empty). `a` = the [`geometry_key`] of those points, or 0 for none.
9182    FillPolygon = 11,
9183    /// Stroke a polygon (g=width); points and key as [`OpCode::FillPolygon`].
9184    StrokePolygon = 12,
9185    /// Stroke a rounded rect (e=radius, g=width).
9186    StrokeRrect = 13,
9187    /// Set a gradient for the next shape record (f=type: 0 linear with a,b=start / c,d=end
9188    /// unit points; 1 radial with a,b=center unit point, c=unit radius; e=stop count).
9189    /// Stops ride the texts channel as "offset,aarrggbb offset,aarrggbb …". Unit geometry
9190    /// resolves against the shape's bounding box.
9191    SetGradient = 14,
9192    /// Fill a path (f=fill rule: 0 non-zero / 1 even-odd); segments ride the texts channel
9193    /// (see [`encode_path`]), or the geometry channel of [`encode_ops_with_geometry`]
9194    /// (b = offset, c = count, see [`path_numbers`]; the texts entry is empty). `a` = the
9195    /// [`geometry_key`] of those segments, or 0 for none.
9196    ///
9197    /// The key is a cache handle, not a payload: a decoder that recognizes it may keep the
9198    /// native geometry it built last time and skip re-parsing the segments, but it must still
9199    /// consume the texts entry either way, because that channel is positional and a skipped
9200    /// entry desynchronizes every record after it.
9201    FillPath = 15,
9202    /// Stroke a path (g=width); segments and key as [`OpCode::FillPath`].
9203    StrokePath = 16,
9204    /// Clip to a shape (f=shape kind: 0 rect / 1 rrect(e=radius) / 2 ellipse / 3 path
9205    /// (e=fill rule) / 4 polygon; a..d=geometry; path/polygon payloads ride the texts
9206    /// channel).
9207    ///
9208    /// For the two payload-bearing kinds (3 and 4) there is no geometry in the slots, so `a`
9209    /// carries the [`geometry_key`] instead, b and c the geometry channel's offset and count
9210    /// when there is one, and d stays 0. The other three kinds put real geometry in a..d and
9211    /// have nothing to cache.
9212    Clip = 17,
9213    /// Stroke style for the next stroke record (a=cap, b=join, c=miter limit, d=dash
9214    /// phase, e=dash count; the dash array rides the texts channel).
9215    StrokeStyle = 18,
9216    /// Font for the next text record (a=CSS weight 100 … 900, 0 = default; b=italic 0/1); the
9217    /// family name rides the texts channel, `""` = the platform's default face. Like
9218    /// [`OpCode::SetGradient`] and [`OpCode::StrokeStyle`] it is consumed by the record that
9219    /// follows and then cleared; a default [`CanvasFont`] emits no record at all, so a drawing
9220    /// without fonts encodes exactly as it did before this op existed.
9221    SetFont = 19,
9222    /// The next shape record is a template, drawn once per stamped position rather than once
9223    /// (docs/canvas.md "Stamping"). `a` = how many positions follow. Like [`OpCode::SetGradient`],
9224    /// [`OpCode::StrokeStyle`] and [`OpCode::SetFont`] it is a prefix, consumed by the record it
9225    /// applies to and then cleared.
9226    ///
9227    /// Between this and that template record come `ceil(a / 4)` [`OpCode::StampPoints`] records
9228    /// carrying the coordinates. A drawing with no stamps encodes exactly as it did before.
9229    Stamp = 20,
9230    /// Four stamped positions, filling the record edge to edge: `[op, x0, y0, x1, y1, x2, y2,
9231    /// x3, y3]`, the one record that uses its last slot for geometry instead of a color, because
9232    /// it carries no color of its own. The final record of a run is padded; the count in the
9233    /// [`OpCode::Stamp`] header says how many of the pairs are real.
9234    StampPoints = 21,
9235    /// Draw a decoded image: `a,b` = origin, `c,d` = size, `e` = the [`BitmapId`], `f` = opacity
9236    /// in `0.0..=1.0` (docs/images.md).
9237    ///
9238    /// The id rides the numeric channel because it is a number, and an `f64` carries a `u64` id
9239    /// exactly up to 2^53; ids are minted from 1 per process, so that ceiling is unreachable.
9240    /// Nothing rides the texts channel for this op.
9241    Image = 22,
9242    /// The source region for the next image record (`a,b` = origin, `c,d` = size, in the
9243    /// bitmap's own pixels): [`DrawOp::Image`]'s `source`. Like [`OpCode::SetFont`] it is a
9244    /// prefix, consumed by the record that follows and then cleared, and a whole-image draw
9245    /// emits none, so a drawing without regions encodes exactly as it did before this op
9246    /// existed. A decoder clamps the region to the bitmap and draws nothing for an empty
9247    /// intersection ([`clamp_image_source`]).
9248    ImageSource = 23,
9249}
9250
9251impl OpCode {
9252    /// Every code, in wire order. The density test iterates this so a new variant that
9253    /// forgets to join fails loudly.
9254    pub const ALL: [OpCode; 24] = [
9255        OpCode::FillRect,
9256        OpCode::StrokeRect,
9257        OpCode::FillRrect,
9258        OpCode::FillEllipse,
9259        OpCode::StrokeEllipse,
9260        OpCode::StrokeArc,
9261        OpCode::Line,
9262        OpCode::Text,
9263        OpCode::Save,
9264        OpCode::Restore,
9265        OpCode::Concat,
9266        OpCode::FillPolygon,
9267        OpCode::StrokePolygon,
9268        OpCode::StrokeRrect,
9269        OpCode::SetGradient,
9270        OpCode::FillPath,
9271        OpCode::StrokePath,
9272        OpCode::Clip,
9273        OpCode::StrokeStyle,
9274        OpCode::SetFont,
9275        OpCode::Stamp,
9276        OpCode::StampPoints,
9277        OpCode::Image,
9278        OpCode::ImageSource,
9279    ];
9280
9281    /// The code back from a wire number (a decoder-side aid and the round-trip test's
9282    /// reference); `None` for anything outside the table.
9283    #[must_use]
9284    #[expect(
9285        clippy::float_cmp,
9286        reason = "wire codes are small integers, which f64 represents exactly"
9287    )]
9288    pub fn from_wire(n: f64) -> Option<OpCode> {
9289        OpCode::ALL.into_iter().find(|c| f64::from(*c as i32) == n)
9290    }
9291}
9292
9293/// Flat numeric encoding of a display list for shim/JNI boundaries (§11, §15.3): per op
9294/// 9 numbers [kind, a, b, c, d, e, f, g, rgba-bits]; text payloads ride separately in order.
9295/// The kind slot carries an [`OpCode`]; its doc comments are the per-slot contract.
9296///
9297/// Transports join `texts` with the unit separator U+001F (one entry per text-carrying
9298/// record, in order), so text payloads must not contain U+001F. Known asymmetry:
9299/// `Fill(Shape::Arc)` encodes as [`OpCode::StrokeArc`] with width 0. Filled arcs render
9300/// only on the direct-replay backends (AppKit/UIKit); use a polygon fan if a filled arc
9301/// must be portable.
9302/// Serialize a path for the `texts` side-channel: one space-separated token per segment,
9303/// `M x y` / `L x y` / `Q cx cy x y` / `C c1x c1y c2x c2y x y` / `Z`.
9304///
9305/// Text rather than numbers because that is the channel the encoder already has for
9306/// variable-length payloads, and every decoder (JS, Java, C++) can already split a string. The
9307/// numeric channel is a flat `[f64; 9]`-per-record array with no length prefix, so a path could
9308/// not ride it without changing the record shape for every backend at once.
9309/// A content key for a shape's variable-length geometry: the handle a backend caches decoded
9310/// native geometry under (a `Path2D`, a `QPainterPath`, an `android.graphics.Path`) so an
9311/// unchanged path is rebuilt once instead of re-parsed out of the texts channel every frame.
9312///
9313/// It hashes the geometry, not the op's position or its identity, so that a draw closure that
9314/// rebuilds its `PathBuilder` chain from scratch on every frame (which is what canvas consumers
9315/// do) produces an equal path, hashes the same and hits the same entry. An identity would miss
9316/// every time.
9317///
9318/// Two different paths that collided would draw each other, so the width matters: FNV-1a over the
9319/// IEEE bits, masked to the 53 bits an `f64` wire slot carries exactly. `0.0` is reserved for "no
9320/// key": a decoder seeing it must decode the payload as it always did, which is also what every
9321/// decoder written before this key existed does with the slot.
9322#[must_use]
9323pub fn geometry_key(shape: &Shape) -> f64 {
9324    fn mix(h: &mut u64, v: f64) {
9325        for byte in v.to_bits().to_le_bytes() {
9326            *h ^= u64::from(byte);
9327            *h = h.wrapping_mul(0x0000_0100_0000_01b3);
9328        }
9329    }
9330    fn mix_point(h: &mut u64, p: Point) {
9331        mix(h, p.x);
9332        mix(h, p.y);
9333    }
9334    let mut h: u64 = 0xcbf2_9ce4_8422_2325;
9335    match shape {
9336        Shape::Polygon(pts) => {
9337            // The discriminant joins the hash so a polygon and a path of the same points can
9338            // never share an entry: they decode to different geometry.
9339            mix(&mut h, 11.0);
9340            for p in pts {
9341                mix_point(&mut h, *p);
9342            }
9343        }
9344        Shape::Path(path) => {
9345            mix(&mut h, 15.0);
9346            mix(&mut h, rule_bits(path.rule));
9347            for seg in &path.segs {
9348                match seg {
9349                    PathSeg::Move(a) => {
9350                        mix(&mut h, 0.0);
9351                        mix_point(&mut h, *a);
9352                    }
9353                    PathSeg::Line(a) => {
9354                        mix(&mut h, 1.0);
9355                        mix_point(&mut h, *a);
9356                    }
9357                    PathSeg::Quad(c, a) => {
9358                        mix(&mut h, 2.0);
9359                        mix_point(&mut h, *c);
9360                        mix_point(&mut h, *a);
9361                    }
9362                    PathSeg::Cubic(c1, c2, a) => {
9363                        mix(&mut h, 3.0);
9364                        mix_point(&mut h, *c1);
9365                        mix_point(&mut h, *c2);
9366                        mix_point(&mut h, *a);
9367                    }
9368                    PathSeg::Close => mix(&mut h, 4.0),
9369                }
9370            }
9371        }
9372        // Everything else puts its whole geometry in the record's own slots, so there is nothing
9373        // to parse and nothing worth caching.
9374        _ => return 0.0,
9375    }
9376    let masked = h & ((1u64 << 53) - 1);
9377    // 0 means "no key", so the one hash that lands there borrows its neighbor.
9378    if masked == 0 { 1.0 } else { masked as f64 }
9379}
9380
9381/// Append a coordinate to the texts channel: a plain decimal with up to six fractional digits
9382/// and no trailing zeros (`12`, `-0.5`, `183.472938`), never an exponent.
9383///
9384/// Six decimals of a canvas point is a millionth of a point, far below anything a transform an
9385/// app would draw under can bring to a pixel, and the fixed form costs a tenth of the shortest
9386/// round-trip repr: one integer write instead of a float formatter and a temporary `String` per
9387/// coordinate, which was the larger half of a map tile's export on Android. The decoders parse
9388/// with their platform's general float reader, so a value the fixed form cannot carry (a
9389/// non-finite number, a magnitude past 2^53 millionths) falls back to `Display`.
9390fn push_wire_num(out: &mut String, v: f64) {
9391    use std::fmt::Write as _;
9392    const SCALE: f64 = 1_000_000.0;
9393    let scaled = (v * SCALE).round();
9394    if scaled.is_nan() || scaled.abs() >= 9.0e15 {
9395        let _ = write!(out, "{v}");
9396        return;
9397    }
9398    let mut n = scaled as i64;
9399    if n < 0 {
9400        out.push('-');
9401        n = -n;
9402    }
9403    let whole = n / 1_000_000;
9404    let mut frac = n % 1_000_000;
9405    let _ = write!(out, "{whole}");
9406    if frac != 0 {
9407        let mut digits = 6;
9408        while frac % 10 == 0 {
9409            frac /= 10;
9410            digits -= 1;
9411        }
9412        out.push('.');
9413        let _ = write!(out, "{frac:0digits$}");
9414    }
9415}
9416
9417/// Polygon points for the texts channel: `"x,y x,y …"`, numbers as [`push_wire_num`] writes
9418/// them.
9419fn encode_points(pts: &[Point]) -> String {
9420    let mut out = String::with_capacity(pts.len() * 16);
9421    for p in pts {
9422        if !out.is_empty() {
9423            out.push(' ');
9424        }
9425        push_wire_num(&mut out, p.x);
9426        out.push(',');
9427        push_wire_num(&mut out, p.y);
9428    }
9429    out
9430}
9431
9432/// Path segments for the texts channel: `"M x y L x y Q cx cy x y C … Z"`, one token per
9433/// command or number. Coordinates use up to six decimal places, without trailing zeros;
9434/// non-finite values and magnitudes outside the fixed-point range use their display form.
9435#[must_use]
9436pub fn encode_path(path: &Path) -> String {
9437    let mut out = String::with_capacity(path.segs.len() * 16);
9438    let points = |out: &mut String, cmd: char, pts: &[Point]| {
9439        if !out.is_empty() {
9440            out.push(' ');
9441        }
9442        out.push(cmd);
9443        for p in pts {
9444            out.push(' ');
9445            push_wire_num(out, p.x);
9446            out.push(' ');
9447            push_wire_num(out, p.y);
9448        }
9449    };
9450    for seg in &path.segs {
9451        match seg {
9452            PathSeg::Move(p) => points(&mut out, 'M', &[*p]),
9453            PathSeg::Line(p) => points(&mut out, 'L', &[*p]),
9454            PathSeg::Quad(c, p) => points(&mut out, 'Q', &[*c, *p]),
9455            PathSeg::Cubic(a, b, p) => points(&mut out, 'C', &[*a, *b, *p]),
9456            PathSeg::Close => points(&mut out, 'Z', &[]),
9457        }
9458    }
9459    out
9460}
9461
9462/// Clamp a [`DrawOp::Image`] `source` region to the bitmap it indexes (`pixels` wide and high),
9463/// keeping the region's mapping into `rect`: the answer is the part of the region inside the
9464/// bitmap and the part of `rect` it lands in.
9465///
9466/// The single definition of what an out-of-range region means. The mapping is kept rather than
9467/// the clamped part stretched over the whole of `rect`, because that is what every native
9468/// sub-rect draw does on its own (Qt, the HTML canvas) and what the clip-and-scale fallback
9469/// gives for free, so the backends agree. `None` (an empty region, an empty intersection, or a
9470/// bitmap with no pixels) draws nothing. Every backend that replays in Rust calls this; the
9471/// C++/Java/JS decoders repeat the same arithmetic.
9472#[must_use]
9473pub fn clamp_image_source(source: Rect, rect: Rect, pixels: Size) -> Option<(Rect, Rect)> {
9474    if !(source.size.width > 0.0 && source.size.height > 0.0) {
9475        return None;
9476    }
9477    let x0 = source.origin.x.max(0.0);
9478    let y0 = source.origin.y.max(0.0);
9479    let x1 = (source.origin.x + source.size.width).min(pixels.width);
9480    let y1 = (source.origin.y + source.size.height).min(pixels.height);
9481    if !(x1 > x0 && y1 > y0) {
9482        return None;
9483    }
9484    let kx = rect.size.width / source.size.width;
9485    let ky = rect.size.height / source.size.height;
9486    let dest = Rect::new(
9487        rect.origin.x + (x0 - source.origin.x) * kx,
9488        rect.origin.y + (y0 - source.origin.y) * ky,
9489        (x1 - x0) * kx,
9490        (y1 - y0) * ky,
9491    );
9492    Some((Rect::new(x0, y0, x1 - x0, y1 - y0), dest))
9493}
9494
9495/// `FillRule` as a wire number: 0 non-zero, 1 even-odd.
9496fn rule_bits(rule: FillRule) -> f64 {
9497    match rule {
9498        FillRule::NonZero => 0.0,
9499        FillRule::EvenOdd => 1.0,
9500    }
9501}
9502
9503/// Encode a display list for a decoder written in another language (Java, C++, JS): the
9504/// numbers channel, nine `f64` slots per record (`[kind, a, b, c, d, e, f, g, color]`, kinds
9505/// from [`OpCode`]), and the texts channel, one entry per record that carries text or
9506/// variable-length geometry, in record order.
9507#[must_use]
9508pub fn encode_ops(ops: &[DrawOp]) -> (Vec<f64>, Vec<String>) {
9509    encode_ops_into(ops, None)
9510}
9511
9512/// [`encode_ops`] with a third, geometry channel: the points of every path and polygon (fills,
9513/// strokes, clips) as numbers instead of text. Such a record's slot `b` is its offset into the
9514/// channel and slot `c` its count, and its texts entry is empty, so that channel stays
9515/// positional for a decoder that ignores the third one. Paths are written by
9516/// [`path_numbers`], polygons by [`point_numbers`].
9517///
9518/// Formatting a coordinate and parsing it back were, together, half of what a map tile's export
9519/// cost on Android (docs/canvas.md "Exporting"); a decoder that can take an array of doubles
9520/// across its boundary skips both.
9521#[must_use]
9522pub fn encode_ops_with_geometry(ops: &[DrawOp]) -> (Vec<f64>, Vec<String>, Vec<f64>) {
9523    let mut geometry = Vec::new();
9524    let (nums, texts) = encode_ops_into(ops, Some(&mut geometry));
9525    (nums, texts, geometry)
9526}
9527
9528/// A path's segments for the geometry channel: a command code, then its points — `0` move
9529/// (x y), `1` line (x y), `2` quad (cx cy x y), `3` cubic (x1 y1 x2 y2 x y), `4` close.
9530pub fn path_numbers(path: &Path, out: &mut Vec<f64>) {
9531    for seg in &path.segs {
9532        match seg {
9533            PathSeg::Move(p) => out.extend_from_slice(&[0.0, p.x, p.y]),
9534            PathSeg::Line(p) => out.extend_from_slice(&[1.0, p.x, p.y]),
9535            PathSeg::Quad(c, p) => out.extend_from_slice(&[2.0, c.x, c.y, p.x, p.y]),
9536            PathSeg::Cubic(a, b, p) => out.extend_from_slice(&[3.0, a.x, a.y, b.x, b.y, p.x, p.y]),
9537            PathSeg::Close => out.push(4.0),
9538        }
9539    }
9540}
9541
9542/// A polygon's points for the geometry channel: x then y, per point.
9543pub fn point_numbers(pts: &[Point], out: &mut Vec<f64>) {
9544    for p in pts {
9545        out.push(p.x);
9546        out.push(p.y);
9547    }
9548}
9549
9550/// Put a path's or polygon's points on the wire: on the geometry channel when the caller opened
9551/// one, as `numbers` writes them, answering (offset, count) for slots b and c and leaving an
9552/// empty texts entry; else as `text` on the texts channel, answering (0, 0).
9553fn geometry_payload(
9554    geometry: &mut Option<&mut Vec<f64>>,
9555    texts: &mut Vec<String>,
9556    text: impl FnOnce() -> String,
9557    numbers: impl FnOnce(&mut Vec<f64>),
9558) -> (f64, f64) {
9559    if let Some(g) = geometry {
9560        let offset = g.len();
9561        numbers(g);
9562        texts.push(String::new());
9563        (offset as f64, (g.len() - offset) as f64)
9564    } else {
9565        texts.push(text());
9566        (0.0, 0.0)
9567    }
9568}
9569
9570fn encode_ops_into(ops: &[DrawOp], mut geometry: Option<&mut Vec<f64>>) -> (Vec<f64>, Vec<String>) {
9571    fn color_bits(c: Color) -> f64 {
9572        let r = (c.r.clamp(0.0, 1.0) * 255.0) as u32;
9573        let g = (c.g.clamp(0.0, 1.0) * 255.0) as u32;
9574        let b = (c.b.clamp(0.0, 1.0) * 255.0) as u32;
9575        let a = (c.a.clamp(0.0, 1.0) * 255.0) as u32;
9576        f64::from((a << 24) | (r << 16) | (g << 8) | b)
9577    }
9578    #[allow(clippy::too_many_arguments)]
9579    fn push(
9580        k: OpCode,
9581        a: f64,
9582        b: f64,
9583        c: f64,
9584        d: f64,
9585        e: f64,
9586        f: f64,
9587        g: f64,
9588        col: Color,
9589        nums: &mut Vec<f64>,
9590    ) {
9591        nums.extend_from_slice(&[f64::from(k as i32), a, b, c, d, e, f, g, color_bits(col)]);
9592    }
9593    /// The kind-18 prefix a non-plain stroke style emits, applying to the next stroke record,
9594    /// the same "modifier record" rule the gradient and font records follow. A plain style emits
9595    /// nothing, so a drawing without dashes or caps encodes exactly as it always did.
9596    fn stroke_style_record(style: &StrokeStyle, nums: &mut Vec<f64>, texts: &mut Vec<String>) {
9597        if style.is_plain() {
9598            return;
9599        }
9600        push(
9601            OpCode::StrokeStyle,
9602            match style.cap {
9603                LineCap::Butt => 0.0,
9604                LineCap::Round => 1.0,
9605                LineCap::Square => 2.0,
9606            },
9607            match style.join {
9608                LineJoin::Miter => 0.0,
9609                LineJoin::Round => 1.0,
9610                LineJoin::Bevel => 2.0,
9611            },
9612            style.miter_limit,
9613            style.dash_phase,
9614            style.dash.len() as f64,
9615            0.0,
9616            0.0,
9617            Color::CLEAR,
9618            nums,
9619        );
9620        texts.push(
9621            style
9622                .dash
9623                .iter()
9624                .map(std::string::ToString::to_string)
9625                .collect::<Vec<_>>()
9626                .join(" "),
9627        );
9628    }
9629
9630    /// One shape record (the fill/stroke kinds shared by both ops).
9631    fn shape_record(
9632        stroke: bool,
9633        shape: &Shape,
9634        w: f64,
9635        col: Color,
9636        nums: &mut Vec<f64>,
9637        texts: &mut Vec<String>,
9638        geometry: &mut Option<&mut Vec<f64>>,
9639    ) {
9640        match shape {
9641            Shape::Rect(r) => push(
9642                if stroke {
9643                    OpCode::StrokeRect
9644                } else {
9645                    OpCode::FillRect
9646                },
9647                r.origin.x,
9648                r.origin.y,
9649                r.size.width,
9650                r.size.height,
9651                0.0,
9652                0.0,
9653                w,
9654                col,
9655                nums,
9656            ),
9657            Shape::RoundedRect(r, rad) => push(
9658                if stroke {
9659                    OpCode::StrokeRrect
9660                } else {
9661                    OpCode::FillRrect
9662                },
9663                r.origin.x,
9664                r.origin.y,
9665                r.size.width,
9666                r.size.height,
9667                *rad,
9668                0.0,
9669                w,
9670                col,
9671                nums,
9672            ),
9673            Shape::Ellipse(r) => push(
9674                if stroke {
9675                    OpCode::StrokeEllipse
9676                } else {
9677                    OpCode::FillEllipse
9678                },
9679                r.origin.x,
9680                r.origin.y,
9681                r.size.width,
9682                r.size.height,
9683                0.0,
9684                0.0,
9685                w,
9686                col,
9687                nums,
9688            ),
9689            Shape::Arc {
9690                rect,
9691                start_deg,
9692                sweep_deg,
9693            } => push(
9694                OpCode::StrokeArc,
9695                rect.origin.x,
9696                rect.origin.y,
9697                rect.size.width,
9698                rect.size.height,
9699                *start_deg,
9700                *sweep_deg,
9701                w,
9702                col,
9703                nums,
9704            ),
9705            Shape::Line(p1, p2) => {
9706                push(OpCode::Line, p1.x, p1.y, p2.x, p2.y, 0.0, 0.0, w, col, nums);
9707            }
9708            Shape::Polygon(pts) => {
9709                // Variable-length points ride the texts side-channel ("x,y x,y …"),
9710                // consumed in record order exactly like text payloads, or the geometry
9711                // channel when there is one (slots b, c).
9712                let (offset, count) = geometry_payload(
9713                    geometry,
9714                    texts,
9715                    || encode_points(pts),
9716                    |g| point_numbers(pts, g),
9717                );
9718                push(
9719                    if stroke {
9720                        OpCode::StrokePolygon
9721                    } else {
9722                        OpCode::FillPolygon
9723                    },
9724                    geometry_key(shape),
9725                    offset,
9726                    count,
9727                    0.0,
9728                    0.0,
9729                    0.0,
9730                    w,
9731                    col,
9732                    nums,
9733                );
9734            }
9735            Shape::Path(path) => {
9736                // Same side-channels as Polygon, one token per segment (see `encode_path`).
9737                // The fill rule rides slot f; stroking ignores it.
9738                let (offset, count) = geometry_payload(
9739                    geometry,
9740                    texts,
9741                    || encode_path(path),
9742                    |g| path_numbers(path, g),
9743                );
9744                push(
9745                    if stroke {
9746                        OpCode::StrokePath
9747                    } else {
9748                        OpCode::FillPath
9749                    },
9750                    geometry_key(shape),
9751                    offset,
9752                    count,
9753                    0.0,
9754                    0.0,
9755                    rule_bits(path.rule),
9756                    w,
9757                    col,
9758                    nums,
9759                );
9760            }
9761        }
9762    }
9763    /// A gradient applies to the next shape record, fill or stroke. Geometry per type rides
9764    /// slots a..d and the type discriminant slot f: one record shape, so every decoder keeps a
9765    /// single gradient code path.
9766    fn gradient_record(
9767        geo: [f64; 4],
9768        kind: f64,
9769        stops: &[(f64, Color)],
9770        nums: &mut Vec<f64>,
9771        texts: &mut Vec<String>,
9772    ) {
9773        push(
9774            OpCode::SetGradient,
9775            geo[0],
9776            geo[1],
9777            geo[2],
9778            geo[3],
9779            stops.len() as f64,
9780            kind,
9781            0.0,
9782            Color::CLEAR,
9783            nums,
9784        );
9785        texts.push(
9786            stops
9787                .iter()
9788                .map(|(o, c)| format!("{o},{:08x}", color_bits(*c) as u32))
9789                .collect::<Vec<_>>()
9790                .join(" "),
9791        );
9792    }
9793    let mut nums = Vec::with_capacity(ops.len() * 9);
9794    let mut texts = Vec::new();
9795    for op in ops {
9796        match op {
9797            DrawOp::Fill(shape, paint) => {
9798                // A gradient emits one kind-14 set-gradient record before its shape record;
9799                // the stops ride the texts channel as "offset,aarrggbb offset,aarrggbb …".
9800                // Geometry per type rides slots a..d, the type discriminant slot f: one
9801                // record shape, so every decoder keeps a single gradient code path.
9802                let col = match paint {
9803                    Paint::Solid(c) => *c,
9804                    Paint::Linear(g) => {
9805                        gradient_record(
9806                            [g.start.x, g.start.y, g.end.x, g.end.y],
9807                            0.0,
9808                            &g.stops,
9809                            &mut nums,
9810                            &mut texts,
9811                        );
9812                        // The gradient replaces the shape record's color, but it must be
9813                        // opaque, not clear: Skia-based decoders (Android Paint, OH_Drawing)
9814                        // modulate a shader by the paint alpha, so a clear slot would render
9815                        // the whole gradient invisible.
9816                        Color::WHITE
9817                    }
9818                    Paint::Radial(g) => {
9819                        gradient_record(
9820                            [g.center.x, g.center.y, g.radius, 0.0],
9821                            1.0,
9822                            &g.stops,
9823                            &mut nums,
9824                            &mut texts,
9825                        );
9826                        Color::WHITE
9827                    }
9828                };
9829                shape_record(false, shape, 0.0, col, &mut nums, &mut texts, &mut geometry);
9830            }
9831            DrawOp::Stamp(st) => {
9832                // No copies means no drawing. Some native decoders use an empty point
9833                // buffer to mean an ordinary (unstamped) template, so omit the entire op.
9834                if st.at.is_empty() {
9835                    continue;
9836                }
9837                // A prefix record, then the coordinates, then the template shape record: the
9838                // "applies to the next record" rule the gradient, stroke style and font records
9839                // already follow, so a decoder needs no new kind of state, only one more slot in
9840                // the state it keeps. The template goes last because a decoder has to hold the
9841                // points before it can draw with them.
9842                //
9843                // The points are numbers on the numeric channel, not the texts channel a
9844                // polygon's points ride: this op exists for tens of thousands of them, and
9845                // formatting that many floats into a string every frame would cost more than
9846                // the individual ops it replaces.
9847                let col = match &st.paint {
9848                    Paint::Solid(c) => *c,
9849                    Paint::Linear(g) => {
9850                        gradient_record(
9851                            [g.start.x, g.start.y, g.end.x, g.end.y],
9852                            0.0,
9853                            &g.stops,
9854                            &mut nums,
9855                            &mut texts,
9856                        );
9857                        Color::WHITE
9858                    }
9859                    Paint::Radial(g) => {
9860                        gradient_record(
9861                            [g.center.x, g.center.y, g.radius, 0.0],
9862                            1.0,
9863                            &g.stops,
9864                            &mut nums,
9865                            &mut texts,
9866                        );
9867                        Color::WHITE
9868                    }
9869                };
9870                push(
9871                    OpCode::Stamp,
9872                    st.at.len() as f64,
9873                    0.0,
9874                    0.0,
9875                    0.0,
9876                    0.0,
9877                    0.0,
9878                    0.0,
9879                    Color::CLEAR,
9880                    &mut nums,
9881                );
9882                for chunk in st.at.chunks(4) {
9883                    // Written directly rather than through `push`: this is the one record whose
9884                    // last slot is a coordinate rather than a color, which is what lets four
9885                    // points fit with nothing wasted.
9886                    let mut rec = [
9887                        f64::from(OpCode::StampPoints as i32),
9888                        0.0,
9889                        0.0,
9890                        0.0,
9891                        0.0,
9892                        0.0,
9893                        0.0,
9894                        0.0,
9895                        0.0,
9896                    ];
9897                    for (i, p) in chunk.iter().enumerate() {
9898                        rec[1 + i * 2] = p.x;
9899                        rec[2 + i * 2] = p.y;
9900                    }
9901                    nums.extend_from_slice(&rec);
9902                }
9903                match &st.stroke {
9904                    None => shape_record(
9905                        false,
9906                        &st.shape,
9907                        0.0,
9908                        col,
9909                        &mut nums,
9910                        &mut texts,
9911                        &mut geometry,
9912                    ),
9913                    Some(style) => {
9914                        stroke_style_record(style, &mut nums, &mut texts);
9915                        shape_record(
9916                            true,
9917                            &st.shape,
9918                            style.width,
9919                            col,
9920                            &mut nums,
9921                            &mut texts,
9922                            &mut geometry,
9923                        );
9924                    }
9925                }
9926            }
9927            DrawOp::Stroke(shape, paint, style) => {
9928                // A styled stroke emits one kind-18 record first, applying to the next stroke
9929                // only, the same "modifier record" shape the gradient uses, so decoders keep
9930                // one rule: consume, apply to the next shape record, reset.
9931                stroke_style_record(style, &mut nums, &mut texts);
9932                let col = match paint {
9933                    Paint::Solid(c) => *c,
9934                    Paint::Linear(g) => {
9935                        gradient_record(
9936                            [g.start.x, g.start.y, g.end.x, g.end.y],
9937                            0.0,
9938                            &g.stops,
9939                            &mut nums,
9940                            &mut texts,
9941                        );
9942                        Color::WHITE
9943                    }
9944                    Paint::Radial(g) => {
9945                        gradient_record(
9946                            [g.center.x, g.center.y, g.radius, 0.0],
9947                            1.0,
9948                            &g.stops,
9949                            &mut nums,
9950                            &mut texts,
9951                        );
9952                        Color::WHITE
9953                    }
9954                };
9955                shape_record(
9956                    true,
9957                    shape,
9958                    style.width,
9959                    col,
9960                    &mut nums,
9961                    &mut texts,
9962                    &mut geometry,
9963                );
9964            }
9965            DrawOp::Clip(shape) => {
9966                // One record for every clip shape, with the shape kind in slot f and the
9967                // geometry in a..e; a path or polygon puts its points on the texts channel.
9968                // Encoding clips as a variant of `shape_record` instead would need a third
9969                // kind code per shape, which is five more numbers every decoder must learn.
9970                let (kind, geo, extra, payload): (f64, [f64; 4], f64, Option<String>) = match shape
9971                {
9972                    Shape::Rect(r) => (
9973                        0.0,
9974                        [r.origin.x, r.origin.y, r.size.width, r.size.height],
9975                        0.0,
9976                        None,
9977                    ),
9978                    Shape::RoundedRect(r, rad) => (
9979                        1.0,
9980                        [r.origin.x, r.origin.y, r.size.width, r.size.height],
9981                        *rad,
9982                        None,
9983                    ),
9984                    Shape::Ellipse(r) => (
9985                        2.0,
9986                        [r.origin.x, r.origin.y, r.size.width, r.size.height],
9987                        0.0,
9988                        None,
9989                    ),
9990                    // Slot a carries the geometry key for these two sub-kinds only. The other
9991                    // three put real geometry there, which is why the key rides the same slot
9992                    // the payload-bearing kinds leave empty; b and c are the geometry
9993                    // channel's offset and count when there is one.
9994                    Shape::Path(p) => {
9995                        let (offset, count) = geometry_payload(
9996                            &mut geometry,
9997                            &mut texts,
9998                            || encode_path(p),
9999                            |g| path_numbers(p, g),
10000                        );
10001                        (
10002                            3.0,
10003                            [geometry_key(shape), offset, count, 0.0],
10004                            rule_bits(p.rule),
10005                            None,
10006                        )
10007                    }
10008                    Shape::Polygon(pts) => {
10009                        let (offset, count) = geometry_payload(
10010                            &mut geometry,
10011                            &mut texts,
10012                            || encode_points(pts),
10013                            |g| point_numbers(pts, g),
10014                        );
10015                        (4.0, [geometry_key(shape), offset, count, 0.0], 0.0, None)
10016                    }
10017                    // A clip to a line or an arc has no interior to clip to. Clipping to an
10018                    // empty region would blank everything after it, so clip to the shape's
10019                    // bounds instead: wrong in the same direction as no clip at all.
10020                    Shape::Line(..) | Shape::Arc { .. } => {
10021                        let r = shape.bounds();
10022                        (
10023                            0.0,
10024                            [r.origin.x, r.origin.y, r.size.width, r.size.height],
10025                            0.0,
10026                            None,
10027                        )
10028                    }
10029                };
10030                push(
10031                    OpCode::Clip,
10032                    geo[0],
10033                    geo[1],
10034                    geo[2],
10035                    geo[3],
10036                    extra,
10037                    kind,
10038                    0.0,
10039                    Color::CLEAR,
10040                    &mut nums,
10041                );
10042                if let Some(s) = payload {
10043                    texts.push(s);
10044                }
10045            }
10046            DrawOp::Text {
10047                text,
10048                at,
10049                size,
10050                color,
10051                anchor,
10052                font,
10053            } => {
10054                if *font != CanvasFont::default() {
10055                    push(
10056                        OpCode::SetFont,
10057                        f64::from(font.css_weight()),
10058                        f64::from(u8::from(font.italic)),
10059                        0.0,
10060                        0.0,
10061                        0.0,
10062                        0.0,
10063                        0.0,
10064                        Color::CLEAR,
10065                        &mut nums,
10066                    );
10067                    texts.push(
10068                        font.family_str()
10069                            .replace([FONT_LIST_FIELD, FONT_LIST_FAMILY], " "),
10070                    );
10071                }
10072                push(
10073                    OpCode::Text,
10074                    at.x,
10075                    at.y,
10076                    0.0,
10077                    0.0,
10078                    *size,
10079                    anchor.pack(),
10080                    0.0,
10081                    *color,
10082                    &mut nums,
10083                );
10084                texts.push(text.clone());
10085            }
10086            DrawOp::Image {
10087                image,
10088                rect,
10089                opacity,
10090                source,
10091            } => {
10092                if let Some(src) = source {
10093                    push(
10094                        OpCode::ImageSource,
10095                        src.origin.x,
10096                        src.origin.y,
10097                        src.size.width,
10098                        src.size.height,
10099                        0.0,
10100                        0.0,
10101                        0.0,
10102                        Color::CLEAR,
10103                        &mut nums,
10104                    );
10105                }
10106                push(
10107                    OpCode::Image,
10108                    rect.origin.x,
10109                    rect.origin.y,
10110                    rect.size.width,
10111                    rect.size.height,
10112                    image.0 as f64,
10113                    *opacity,
10114                    0.0,
10115                    Color::CLEAR,
10116                    &mut nums,
10117                );
10118            }
10119            DrawOp::Save => push(
10120                OpCode::Save,
10121                0.0,
10122                0.0,
10123                0.0,
10124                0.0,
10125                0.0,
10126                0.0,
10127                0.0,
10128                Color::CLEAR,
10129                &mut nums,
10130            ),
10131            DrawOp::Restore => push(
10132                OpCode::Restore,
10133                0.0,
10134                0.0,
10135                0.0,
10136                0.0,
10137                0.0,
10138                0.0,
10139                0.0,
10140                Color::CLEAR,
10141                &mut nums,
10142            ),
10143            DrawOp::Concat(m) => push(
10144                OpCode::Concat,
10145                m.a,
10146                m.b,
10147                m.c,
10148                m.d,
10149                m.tx,
10150                m.ty,
10151                0.0,
10152                Color::CLEAR,
10153                &mut nums,
10154            ),
10155        }
10156    }
10157    (nums, texts)
10158}
10159
10160#[cfg(test)]
10161mod font_list_tests {
10162    use super::*;
10163
10164    #[test]
10165    fn css_weights_round_trip_and_snap_to_the_nearest_rung() {
10166        for w in FontWeight::ALL {
10167            assert_eq!(FontWeight::from_css(w.css()), w);
10168        }
10169        assert_eq!(FontWeight::from_css(0), FontWeight::UltraLight);
10170        assert_eq!(FontWeight::from_css(350), FontWeight::Regular); // ties go heavier
10171        assert_eq!(FontWeight::from_css(649), FontWeight::Semibold);
10172        assert_eq!(FontWeight::from_css(1200), FontWeight::Black);
10173    }
10174
10175    fn sans() -> FontFamilyInfo {
10176        FontFamilyInfo {
10177            family: "Day Sans".into(),
10178            faces: vec![
10179                FontFace {
10180                    name: "Regular".into(),
10181                    weight: FontWeight::Regular,
10182                    italic: false,
10183                },
10184                FontFace {
10185                    name: "Bold".into(),
10186                    weight: FontWeight::Bold,
10187                    italic: false,
10188                },
10189                FontFace {
10190                    name: "Light Italic".into(),
10191                    weight: FontWeight::Light,
10192                    italic: true,
10193                },
10194            ],
10195        }
10196    }
10197
10198    #[test]
10199    fn face_for_prefers_the_slant_then_the_nearest_weight() {
10200        let f = sans();
10201        assert!(f.has_bold() && f.has_italic());
10202        assert_eq!(f.face_for(FontWeight::Bold, false).unwrap().name, "Bold");
10203        assert_eq!(
10204            f.face_for(FontWeight::Semibold, false).unwrap().name,
10205            "Bold"
10206        );
10207        assert_eq!(
10208            f.face_for(FontWeight::Medium, false).unwrap().name,
10209            "Regular"
10210        );
10211        let tie = FontFamilyInfo {
10212            family: "Tie".into(),
10213            faces: vec![
10214                FontFace {
10215                    name: "Light".into(),
10216                    weight: FontWeight::Light,
10217                    italic: false,
10218                },
10219                FontFace {
10220                    name: "Bold".into(),
10221                    weight: FontWeight::Bold,
10222                    italic: false,
10223                },
10224            ],
10225        };
10226        // Medium sits 200 from both; the heavier face wins the tie.
10227        assert_eq!(
10228            tie.face_for(FontWeight::Medium, false).unwrap().name,
10229            "Bold"
10230        );
10231        assert_eq!(
10232            f.face_for(FontWeight::Black, true).unwrap().name,
10233            "Light Italic"
10234        );
10235        let none = FontFamilyInfo {
10236            family: "Empty".into(),
10237            faces: vec![],
10238        };
10239        assert!(none.face_for(FontWeight::Regular, false).is_none());
10240        assert!(!none.has_bold());
10241    }
10242
10243    #[test]
10244    fn the_shim_list_format_decodes_tolerantly() {
10245        let s = "Day Sans\u{1f}Regular\u{1f}400\u{1f}0\u{1f}\u{1f}700\u{1f}1\u{1f}Broken\u{1f}x\u{1f}0\
10246                 \u{1e}\u{1e}Day Mono\u{1f}Regular\u{1f}400\u{1f}0\u{1e}Faceless";
10247        let list = parse_font_list(s);
10248        assert_eq!(list.len(), 3);
10249        assert_eq!(list[0].family, "Day Sans");
10250        assert_eq!(list[0].faces.len(), 2, "the bad weight is skipped");
10251        assert_eq!(list[0].faces[1].name, "Bold Italic"); // synthesized from 700 + italic
10252        assert_eq!(list[1].family, "Day Mono");
10253        assert_eq!(list[2].family, "Faceless");
10254        assert_eq!(list[2].faces, [] as [FontFace; 0]);
10255    }
10256
10257    #[test]
10258    fn approximate_metrics_scale_with_size_and_length() {
10259        let m = TextMetrics::approximate("abc", 10.0);
10260        assert_eq!((m.width, m.height, m.ascent), (18.0, 12.0, 9.0));
10261        assert_eq!(TextMetrics::approximate("", 10.0).width, 0.0);
10262    }
10263
10264    #[test]
10265    fn a_default_canvas_font_is_the_platform_face() {
10266        let f = CanvasFont::default();
10267        assert_eq!((f.family_str(), f.css_weight(), f.italic), ("", 0, false));
10268    }
10269}
10270
10271#[cfg(test)]
10272mod image_header_tests {
10273    use super::*;
10274
10275    /// A 4×2 PNG: signature, then an IHDR whose width and height are big-endian.
10276    fn png(w: u32, h: u32) -> Vec<u8> {
10277        let mut v = vec![0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a];
10278        v.extend(13u32.to_be_bytes());
10279        v.extend(b"IHDR");
10280        v.extend(w.to_be_bytes());
10281        v.extend(h.to_be_bytes());
10282        v
10283    }
10284
10285    /// A JPEG whose frame header sits behind one other segment, so the walk has to skip it.
10286    fn jpeg(w: u16, h: u16) -> Vec<u8> {
10287        let mut v = vec![0xFF, 0xD8]; // SOI
10288        v.extend([0xFF, 0xE0, 0x00, 0x04, 0x00, 0x00]); // APP0, length 4
10289        v.extend([0xFF, 0xC0, 0x00, 0x11, 0x08]); // SOF0, length 17, precision 8
10290        v.extend(h.to_be_bytes());
10291        v.extend(w.to_be_bytes());
10292        v
10293    }
10294
10295    #[test]
10296    fn a_header_states_the_size_before_anything_decodes() {
10297        assert_eq!(ImageFormat::dimensions(&png(512, 512)), Some((512, 512)));
10298        assert_eq!(ImageFormat::dimensions(&png(1, 65535)), Some((1, 65535)));
10299        // The JPEG walk must step over the APP0 segment to reach the frame header.
10300        assert_eq!(ImageFormat::dimensions(&jpeg(640, 480)), Some((640, 480)));
10301
10302        let mut gif = b"GIF89a".to_vec();
10303        gif.extend(320u16.to_le_bytes());
10304        gif.extend(240u16.to_le_bytes());
10305        assert_eq!(ImageFormat::dimensions(&gif), Some((320, 240)));
10306
10307        // A top-down BMP states its height as a negative number; the size is still positive.
10308        let mut bmp = b"BM".to_vec();
10309        bmp.resize(18, 0);
10310        bmp.extend(64i32.to_le_bytes());
10311        bmp.extend((-32i32).to_le_bytes());
10312        assert_eq!(ImageFormat::dimensions(&bmp), Some((64, 32)));
10313    }
10314
10315    #[test]
10316    fn a_truncated_or_unknown_header_answers_nothing_rather_than_a_guess() {
10317        assert_eq!(ImageFormat::dimensions(&[]), None);
10318        // The signature is there but the IHDR is not.
10319        assert_eq!(ImageFormat::dimensions(&png(8, 8)[..12]), None);
10320        // Not an image at all.
10321        assert_eq!(ImageFormat::dimensions(b"not an image"), None);
10322        // A JPEG that never reaches a frame header must not loop or invent a size.
10323        assert_eq!(
10324            ImageFormat::dimensions(&[0xFF, 0xD8, 0xFF, 0xE0, 0x00, 0x04, 0, 0]),
10325            None
10326        );
10327    }
10328}
10329
10330#[cfg(test)]
10331mod encode_ops_tests {
10332    use super::*;
10333
10334    /// The texts channel carries plain decimals: whole numbers without a point, fractions to
10335    /// six places with the trailing zeros gone, and the general form only past what the fixed
10336    /// one can hold.
10337    #[test]
10338    fn wire_numbers_are_short_plain_decimals() {
10339        let text = |v: f64| {
10340            let mut out = String::new();
10341            push_wire_num(&mut out, v);
10342            out
10343        };
10344        assert_eq!(text(12.0), "12");
10345        assert_eq!(text(-0.5), "-0.5");
10346        assert_eq!(text(183.472_938_472_938_4), "183.472938");
10347        assert_eq!(text(0.1 + 0.2), "0.3");
10348        assert_eq!(text(-0.000_000_1), "0");
10349        assert_eq!(text(2.000_05), "2.00005");
10350        assert_eq!(text(f64::INFINITY), "inf");
10351        assert_eq!(text(1.0e17), "100000000000000000");
10352        let path = Path {
10353            segs: vec![
10354                PathSeg::Move(Point::new(1.5, 2.0)),
10355                PathSeg::Line(Point::new(-3.25, 4.0)),
10356                PathSeg::Close,
10357            ],
10358            rule: FillRule::NonZero,
10359        };
10360        assert_eq!(encode_path(&path), "M 1.5 2 L -3.25 4 Z");
10361        assert_eq!(
10362            encode_points(&[Point::new(0.0, 0.0), Point::new(10.0, 0.125)]),
10363            "0,0 10,0.125"
10364        );
10365    }
10366
10367    /// With the geometry channel open, a path's and a polygon's points leave the texts channel
10368    /// (an empty entry keeps it positional) for the numbers, with offset and count in slots b
10369    /// and c; without it the texts channel carries them exactly as before.
10370    #[test]
10371    fn geometry_channel_carries_points_as_numbers() {
10372        let path = Shape::Path(Path {
10373            segs: vec![
10374                PathSeg::Move(Point::new(1.0, 2.0)),
10375                PathSeg::Quad(Point::new(3.0, 4.0), Point::new(5.0, 6.0)),
10376                PathSeg::Close,
10377            ],
10378            rule: FillRule::EvenOdd,
10379        });
10380        let polygon = Shape::Polygon(vec![Point::new(0.0, 0.0), Point::new(7.0, 8.0)]);
10381        let ops = vec![
10382            DrawOp::Clip(path.clone()),
10383            DrawOp::Fill(path.clone(), Paint::Solid(Color::WHITE)),
10384            DrawOp::Stroke(
10385                polygon.clone(),
10386                Paint::Solid(Color::WHITE),
10387                StrokeStyle::default(),
10388            ),
10389        ];
10390        let (nums, texts, geometry) = encode_ops_with_geometry(&ops);
10391        assert_eq!(texts, vec!["", "", ""]);
10392        assert_eq!(
10393            geometry,
10394            vec![
10395                0.0, 1.0, 2.0, 2.0, 3.0, 4.0, 5.0, 6.0, 4.0, 0.0, 1.0, 2.0, 2.0, 3.0, 4.0, 5.0,
10396                6.0, 4.0, 0.0, 0.0, 7.0, 8.0
10397            ]
10398        );
10399        // The clip (kind 17, sub-kind 3 in f) and the fill (kind 15) point at the two copies
10400        // of the path, the stroke (kind 12) at the polygon's four numbers.
10401        assert_eq!((nums[0], nums[2], nums[3], nums[6]), (17.0, 0.0, 9.0, 3.0));
10402        assert_eq!(
10403            (nums[9], nums[11], nums[12], nums[15]),
10404            (15.0, 9.0, 9.0, 1.0)
10405        );
10406        assert_eq!((nums[18], nums[20], nums[21]), (12.0, 18.0, 4.0));
10407        let (plain_nums, plain_texts) = encode_ops(&ops);
10408        assert_eq!(plain_texts[1], "M 1 2 Q 3 4 5 6 Z");
10409        assert_eq!(plain_texts[2], "0,0 7,8");
10410        assert_eq!((plain_nums[11], plain_nums[12]), (0.0, 0.0));
10411    }
10412
10413    /// A region outside the bitmap is clamped to it with its mapping into the rect kept, and an
10414    /// empty intersection draws nothing.
10415    #[test]
10416    fn image_source_clamps_to_the_bitmap() {
10417        let px = Size::new(64.0, 32.0);
10418        let dest = Rect::new(100.0, 200.0, 32.0, 32.0); // 2 points per source pixel
10419        assert_eq!(
10420            clamp_image_source(Rect::new(-8.0, -8.0, 16.0, 16.0), dest, px),
10421            Some((
10422                Rect::new(0.0, 0.0, 8.0, 8.0),
10423                Rect::new(116.0, 216.0, 16.0, 16.0)
10424            ))
10425        );
10426        assert_eq!(
10427            clamp_image_source(Rect::new(60.0, 28.0, 16.0, 16.0), dest, px),
10428            Some((
10429                Rect::new(60.0, 28.0, 4.0, 4.0),
10430                Rect::new(100.0, 200.0, 8.0, 8.0)
10431            ))
10432        );
10433        assert_eq!(
10434            clamp_image_source(Rect::new(16.0, 8.0, 16.0, 16.0), dest, px),
10435            Some((Rect::new(16.0, 8.0, 16.0, 16.0), dest))
10436        );
10437        assert_eq!(
10438            clamp_image_source(Rect::new(64.0, 0.0, 8.0, 8.0), dest, px),
10439            None
10440        );
10441        assert_eq!(
10442            clamp_image_source(Rect::new(0.0, 0.0, 0.0, 8.0), dest, px),
10443            None
10444        );
10445        assert_eq!(
10446            clamp_image_source(Rect::new(0.0, 0.0, 8.0, 8.0), dest, Size::new(0.0, 0.0)),
10447            None
10448        );
10449    }
10450
10451    /// The wire codes are a frozen dense table: any gap, duplicate, or variant missing from
10452    /// `ALL` breaks a decoder somewhere, so it must break here first.
10453    #[test]
10454    fn op_codes_are_dense_and_round_trip() {
10455        for (i, code) in OpCode::ALL.into_iter().enumerate() {
10456            assert_eq!(code as i32, i as i32, "{code:?} broke wire density");
10457            assert_eq!(OpCode::from_wire(i as f64), Some(code));
10458        }
10459        assert_eq!(OpCode::from_wire(OpCode::ALL.len() as f64), None);
10460        assert_eq!(OpCode::from_wire(-1.0), None);
10461        assert_eq!(OpCode::from_wire(0.5), None);
10462    }
10463
10464    /// Reference decode of a display list covering every op arm: the record stream must be
10465    /// whole 9-slot records of known codes, and the texts channel must carry exactly one
10466    /// entry per text-carrying record, in order: the contract every shim decoder assumes.
10467    #[test]
10468    #[expect(
10469        clippy::float_cmp,
10470        reason = "wire slots hold integer codes and exact test constants"
10471    )]
10472    fn encode_ops_emits_whole_records_and_matched_text_payloads() {
10473        let r = Rect::new(1.0, 2.0, 3.0, 4.0);
10474        let red = Color::rgb(1.0, 0.0, 0.0);
10475        let ops = vec![
10476            DrawOp::Fill(Shape::Rect(r), Paint::Solid(red)),
10477            DrawOp::Stroke(Shape::Rect(r), Paint::Solid(red), StrokeStyle::round(2.0)),
10478            DrawOp::Fill(Shape::RoundedRect(r, 5.0), Paint::Solid(red)),
10479            DrawOp::Fill(Shape::Ellipse(r), Paint::Solid(red)),
10480            // The documented asymmetry: a filled arc encodes as StrokeArc with width 0.
10481            DrawOp::Fill(
10482                Shape::Arc {
10483                    rect: r,
10484                    start_deg: 0.0,
10485                    sweep_deg: 90.0,
10486                },
10487                Paint::Solid(red),
10488            ),
10489            DrawOp::Stroke(
10490                Shape::Line(Point::new(0.0, 0.0), Point::new(9.0, 9.0)),
10491                Paint::Solid(red),
10492                StrokeStyle::width(1.0),
10493            ),
10494            DrawOp::Fill(
10495                Shape::Polygon(vec![
10496                    Point::new(0.0, 0.0),
10497                    Point::new(4.0, 0.0),
10498                    Point::new(2.0, 3.0),
10499                ]),
10500                Paint::Solid(red),
10501            ),
10502            DrawOp::Fill(
10503                Shape::Path(Path {
10504                    segs: vec![
10505                        PathSeg::Move(Point::new(0.0, 0.0)),
10506                        PathSeg::Line(Point::new(5.0, 5.0)),
10507                        PathSeg::Close,
10508                    ],
10509                    rule: FillRule::EvenOdd,
10510                }),
10511                Paint::Linear(LinearGradient::new(
10512                    UnitPoint::new(0.0, 0.0),
10513                    UnitPoint::new(1.0, 1.0),
10514                    vec![(0.0, red), (1.0, Color::WHITE)],
10515                )),
10516            ),
10517            DrawOp::Clip(Shape::Rect(r)),
10518            DrawOp::Clip(Shape::Polygon(vec![
10519                Point::new(0.0, 0.0),
10520                Point::new(1.0, 0.0),
10521                Point::new(0.0, 1.0),
10522            ])),
10523            DrawOp::Text {
10524                text: "hi".into(),
10525                at: Point::new(7.0, 8.0),
10526                size: 12.0,
10527                color: red,
10528                anchor: TextAnchor::LEADING,
10529                font: CanvasFont::default(),
10530            },
10531            DrawOp::Text {
10532                text: "bold".into(),
10533                at: Point::new(7.0, 8.0),
10534                size: 12.0,
10535                color: red,
10536                anchor: TextAnchor::CENTERED,
10537                font: CanvasFont {
10538                    family: Some("Day Sans".into()),
10539                    weight: Some(FontWeight::Bold),
10540                    italic: true,
10541                },
10542            },
10543            DrawOp::Save,
10544            DrawOp::Concat(Affine::IDENTITY),
10545            DrawOp::Restore,
10546            DrawOp::Image {
10547                image: BitmapId(7),
10548                rect: r,
10549                opacity: 0.5,
10550                source: None,
10551            },
10552            DrawOp::Image {
10553                image: BitmapId(7),
10554                rect: r,
10555                opacity: 1.0,
10556                source: Some(Rect::new(16.0, 32.0, 8.0, 8.0)),
10557            },
10558        ];
10559        let (nums, texts) = encode_ops(&ops);
10560        assert_eq!(nums.len() % 9, 0, "partial record on the wire");
10561
10562        let mut expected_texts = 0usize;
10563        let mut decoded = Vec::new();
10564        for rec in nums.chunks(9) {
10565            let code = OpCode::from_wire(rec[0])
10566                .unwrap_or_else(|| panic!("unknown op code {} on the wire", rec[0]));
10567            decoded.push(code);
10568            expected_texts += match code {
10569                OpCode::Text
10570                | OpCode::FillPolygon
10571                | OpCode::StrokePolygon
10572                | OpCode::SetGradient
10573                | OpCode::FillPath
10574                | OpCode::StrokePath
10575                | OpCode::StrokeStyle
10576                | OpCode::SetFont => 1,
10577                // Clip carries a payload only for its path (3) / polygon (4) sub-kinds.
10578                OpCode::Clip => usize::from(rec[6] == 3.0 || rec[6] == 4.0),
10579                _ => 0,
10580            };
10581        }
10582        assert_eq!(
10583            texts.len(),
10584            expected_texts,
10585            "texts channel out of step with the records that consume it"
10586        );
10587        // No payload may carry the transport separator.
10588        assert!(texts.iter().all(|t| !t.contains('\u{1f}')));
10589
10590        let expected = {
10591            use OpCode::*;
10592            vec![
10593                FillRect,
10594                StrokeStyle, // ::round(2.0) is not plain, so the style modifier precedes
10595                StrokeRect,
10596                FillRrect,
10597                FillEllipse,
10598                StrokeArc, // the filled arc's stroke encoding…
10599                Line,
10600                FillPolygon,
10601                SetGradient, // gradient precedes its shape record
10602                FillPath,
10603                Clip,
10604                Clip,
10605                Text,
10606                SetFont, // a non-default font precedes its text record…
10607                Text,
10608                Save,
10609                Concat,
10610                Restore,
10611                Image,
10612                ImageSource, // a region precedes its image record; a whole-image draw has none
10613                Image,
10614            ]
10615        };
10616        assert_eq!(decoded, expected);
10617        // The bitmap id rides the numeric channel intact (an f64 holds a u64 id exactly well
10618        // past any id this process will mint), and nothing of an image reaches the texts channel.
10619        let img = nums
10620            .chunks(9)
10621            .find(|r| r[0] == f64::from(OpCode::Image as i32))
10622            .expect("Image record");
10623        assert_eq!(&img[1..7], &[1.0, 2.0, 3.0, 4.0, 7.0, 0.5]);
10624        // The region rides its own prefix record, in bitmap pixels, with nothing else in it.
10625        let src = nums
10626            .chunks(9)
10627            .find(|r| r[0] == f64::from(OpCode::ImageSource as i32))
10628            .expect("ImageSource record");
10629        assert_eq!(&src[1..8], &[16.0, 32.0, 8.0, 8.0, 0.0, 0.0, 0.0]);
10630        // …carrying the CSS weight and the slant, with the family on the texts channel.
10631        let font_rec = nums
10632            .chunks(9)
10633            .find(|r| r[0] == f64::from(OpCode::SetFont as i32))
10634            .expect("SetFont record");
10635        assert_eq!(&font_rec[1..3], &[700.0, 1.0]);
10636        assert_eq!(texts.iter().filter(|t| *t == "Day Sans").count(), 1);
10637        // …with width 0, per the documented asymmetry.
10638        let arc = nums
10639            .chunks(9)
10640            .find(|r| r[0] == f64::from(OpCode::StrokeArc as i32));
10641        assert_eq!(arc.map(|r| r[7]), Some(0.0));
10642        // A gradient-filled shape's color slot is opaque white, never clear (Skia decoders
10643        // modulate the shader by it).
10644        let path_rec = nums
10645            .chunks(9)
10646            .find(|r| r[0] == f64::from(OpCode::FillPath as i32));
10647        assert_eq!(
10648            path_rec.map(|r| r[8] as u32),
10649            Some(0xFFFF_FFFF),
10650            "gradient shape record must carry opaque white"
10651        );
10652    }
10653
10654    #[test]
10655    #[expect(
10656        clippy::float_cmp,
10657        reason = "wire slots hold integer codes and exact test constants"
10658    )]
10659    fn variable_length_geometry_carries_a_content_key() {
10660        let path = |x: f64| {
10661            Shape::Path(Path {
10662                segs: vec![
10663                    PathSeg::Move(Point::new(x, 0.0)),
10664                    PathSeg::Cubic(
10665                        Point::new(1.0, 1.0),
10666                        Point::new(2.0, 2.0),
10667                        Point::new(3.0, 3.0),
10668                    ),
10669                    PathSeg::Close,
10670                ],
10671                rule: FillRule::NonZero,
10672            })
10673        };
10674        let poly = Shape::Polygon(vec![
10675            Point::new(0.0, 0.0),
10676            Point::new(1.0, 0.0),
10677            Point::new(0.0, 1.0),
10678        ]);
10679
10680        // Equal geometry keys equal though the two were built separately. The key exists for
10681        // this: a draw closure rebuilds its paths from scratch on every frame.
10682        assert_eq!(geometry_key(&path(0.0)), geometry_key(&path(0.0)));
10683        assert_ne!(geometry_key(&path(0.0)), geometry_key(&path(1.0)));
10684        // The fill rule decides what the path draws, so it belongs to the key.
10685        let even_odd = Shape::Path(Path {
10686            segs: match path(0.0) {
10687                Shape::Path(p) => p.segs,
10688                _ => unreachable!(),
10689            },
10690            rule: FillRule::EvenOdd,
10691        });
10692        assert_ne!(geometry_key(&path(0.0)), geometry_key(&even_odd));
10693        // A polygon and a path decode to different geometry and never share an entry.
10694        assert_ne!(geometry_key(&poly), geometry_key(&path(0.0)));
10695        // Fixed-size shapes keep 0: their geometry rides the record's own slots.
10696        assert_eq!(
10697            geometry_key(&Shape::Rect(Rect::new(0.0, 0.0, 1.0, 1.0))),
10698            0.0
10699        );
10700        // And a key survives an f64 wire slot exactly, which is what the 53-bit mask buys.
10701        let k = geometry_key(&path(0.0));
10702        assert!(
10703            k > 0.0 && k < (1u64 << 53) as f64 && k.fract() == 0.0,
10704            "{k}"
10705        );
10706
10707        // It reaches the wire in slot a, for exactly the ops whose payload rides the texts
10708        // channel, and never displaces geometry that is already there.
10709        let (nums, _) = encode_ops(&[
10710            DrawOp::Fill(path(0.0), Paint::Solid(Color::WHITE)),
10711            DrawOp::Fill(poly.clone(), Paint::Solid(Color::WHITE)),
10712            DrawOp::Clip(path(0.0)),
10713            DrawOp::Clip(Shape::Rect(Rect::new(1.0, 2.0, 3.0, 4.0))),
10714        ]);
10715        let slot_a = |code: OpCode| {
10716            nums.chunks(9)
10717                .find(|r| r[0] == f64::from(code as i32))
10718                .unwrap_or_else(|| panic!("no {code:?} record"))[1]
10719        };
10720        assert_eq!(slot_a(OpCode::FillPath), geometry_key(&path(0.0)));
10721        assert_eq!(slot_a(OpCode::FillPolygon), geometry_key(&poly));
10722        let clips: Vec<&[f64]> = nums
10723            .chunks(9)
10724            .filter(|r| r[0] == f64::from(OpCode::Clip as i32))
10725            .collect();
10726        assert_eq!(clips[0][1], geometry_key(&path(0.0)), "path clip keys");
10727        assert_eq!(
10728            &clips[1][1..5],
10729            &[1.0, 2.0, 3.0, 4.0],
10730            "a rect clip still puts its geometry in a..d"
10731        );
10732    }
10733}
10734
10735#[cfg(test)]
10736mod markup_tests {
10737    use super::*;
10738
10739    fn bold(range: std::ops::Range<usize>) -> TextRun {
10740        TextRun::font(
10741            range,
10742            FontSpec {
10743                style: Font::Body,
10744                weight: Some(FontWeight::Bold),
10745                ..Default::default()
10746            },
10747        )
10748    }
10749
10750    #[test]
10751    fn plain_text_is_escaped_in_both_dialects() {
10752        // The case a translated string will find: markup metacharacters in the content.
10753        let text = "5 < 6 & \"quoted\" <b>not bold</b>";
10754        for d in [MarkupDialect::Pango, MarkupDialect::QtHtml] {
10755            let m = runs_to_markup(text, &[], d, 16.0);
10756            assert!(!m.contains("<b>"), "content tag survived into markup: {m}");
10757            assert!(m.contains("&lt;b&gt;"), "{m}");
10758            assert!(m.contains("&amp;"), "{m}");
10759            assert!(m.contains("5 &lt; 6"), "{m}");
10760        }
10761    }
10762
10763    #[test]
10764    fn a_styled_run_is_wrapped_and_its_text_escaped() {
10765        let text = "a <b> c";
10766        let m = runs_to_markup(text, &[bold(2..5)], MarkupDialect::Pango, 16.0);
10767        assert_eq!(m, "a <b>&lt;b&gt;</b> c");
10768    }
10769
10770    #[test]
10771    fn color_and_monospace_differ_per_dialect() {
10772        let text = "code";
10773        let run = TextRun {
10774            range: 0..4,
10775            font: FontSpec {
10776                style: Font::Body,
10777                monospace: true,
10778                ..Default::default()
10779            },
10780            color: Some(Color::rgb(1.0, 0.0, 0.0)),
10781            ..TextRun::default()
10782        };
10783        let pango = runs_to_markup(text, std::slice::from_ref(&run), MarkupDialect::Pango, 16.0);
10784        assert!(pango.contains("foreground=\"#ff0000\""), "{pango}");
10785        assert!(pango.contains("font_family=\"monospace\""), "{pango}");
10786        let qt = runs_to_markup(
10787            text,
10788            std::slice::from_ref(&run),
10789            MarkupDialect::QtHtml,
10790            16.0,
10791        );
10792        assert!(qt.contains("color:#ff0000"), "{qt}");
10793        // Qt takes its fixed face from <code>: a `font-family:monospace` style attribute
10794        // renders proportional (observed on Qt 6.11).
10795        assert!(qt.contains("<code>") && qt.contains("</code>"), "{qt}");
10796    }
10797
10798    #[test]
10799    fn the_new_attributes_reach_both_dialects() {
10800        let run = TextRun {
10801            range: 0..2,
10802            font: FontSpec::default().scaled(1.5),
10803            background: Some(Color::rgb(0.0, 1.0, 0.0)),
10804            underline: Underline::Single,
10805            ..TextRun::default()
10806        };
10807        let pango = runs_to_markup("hi", std::slice::from_ref(&run), MarkupDialect::Pango, 16.0);
10808        assert!(pango.contains("background=\"#00ff00\""), "{pango}");
10809        // Pango takes an absolute size in 1/1024 pt (16 pt base × 1.5 = 24 pt), because the
10810        // relative attributes are Pango 1.50's and an unknown attribute empties the whole label.
10811        assert!(pango.contains("size=\"24576\""), "{pango}");
10812        assert!(pango.contains("<u>hi</u>"), "{pango}");
10813        let qt = runs_to_markup(
10814            "hi",
10815            std::slice::from_ref(&run),
10816            MarkupDialect::QtHtml,
10817            16.0,
10818        );
10819        assert!(qt.contains("background-color:#00ff00"), "{qt}");
10820        // Qt takes points: 16 pt base × 1.5 (observed; its CSS subset ignores a percentage).
10821        assert!(qt.contains("font-size:24pt"), "{qt}");
10822        assert!(qt.contains("<u>hi</u>"), "{qt}");
10823    }
10824
10825    #[test]
10826    fn a_link_target_is_escaped_too() {
10827        // A URL carrying `&` between query parameters is ordinary, and unescaped it truncates
10828        // the attribute and swallows the rest of the label.
10829        let text = "docs";
10830        let run = TextRun {
10831            range: 0..4,
10832            link: Some("https://x.dev/?a=1&b=2".into()),
10833            ..TextRun::default()
10834        };
10835        let m = runs_to_markup(text, &[run], MarkupDialect::Pango, 16.0);
10836        assert!(m.contains("a=1&amp;b=2"), "{m}");
10837    }
10838
10839    #[test]
10840    fn tags_nest_and_close_in_reverse() {
10841        let run = TextRun {
10842            range: 0..2,
10843            font: FontSpec {
10844                style: Font::Body,
10845                weight: Some(FontWeight::Bold),
10846                italic: true,
10847                ..Default::default()
10848            },
10849            strikethrough: true,
10850            link: Some("u".into()),
10851            ..TextRun::default()
10852        };
10853        let m = runs_to_markup("hi", &[run], MarkupDialect::Pango, 16.0);
10854        assert_eq!(m, "<a href=\"u\"><b><i><s>hi</s></i></b></a>");
10855    }
10856
10857    #[test]
10858    fn runs_out_of_bounds_are_skipped_not_panicked() {
10859        // `runs_are_valid` rejects these upstream; this is the belt-and-braces path.
10860        let m = runs_to_markup("hi", &[bold(0..99)], MarkupDialect::Pango, 16.0);
10861        assert_eq!(m, "hi");
10862    }
10863
10864    #[test]
10865    fn validation_catches_the_four_ways_runs_go_wrong() {
10866        let text = "héllo";
10867        assert!(runs_are_valid(text, &[bold(0..1)]).is_ok());
10868        // Overlapping.
10869        assert!(runs_are_valid(text, &[bold(0..3), bold(2..4)]).is_err());
10870        // Past the end.
10871        assert!(runs_are_valid(text, &[bold(0..99)]).is_err());
10872        // Inverted. Built from parts, since a literal `3..1` is a clippy error in its own right.
10873        let (hi, lo) = (3, 1);
10874        assert!(runs_are_valid(text, &[bold(hi..lo)]).is_err());
10875        // Splitting the 2-byte `é`.
10876        assert!(runs_are_valid(text, &[bold(0..2)]).is_err());
10877    }
10878}
10879
10880#[cfg(test)]
10881mod route_of_url_tests {
10882    use super::route_of_url;
10883
10884    #[test]
10885    fn strips_the_scheme_and_keeps_route_and_params() {
10886        assert_eq!(
10887            route_of_url("notes://mail/inbox?hint=x"),
10888            "mail/inbox?hint=x"
10889        );
10890        assert_eq!(route_of_url("notes://home"), "home");
10891        // No scheme: already a route, unchanged.
10892        assert_eq!(route_of_url("mail/inbox"), "mail/inbox");
10893        assert_eq!(route_of_url(""), "");
10894        // Percent-encoding passes through; the route parser decodes, not this mapping.
10895        assert_eq!(route_of_url("n://a/b%2Fc?q=1%202"), "a/b%2Fc?q=1%202");
10896    }
10897}
10898
10899#[cfg(test)]
10900mod builtin_kind_tests {
10901    use super::*;
10902
10903    /// Every built-in round-trips through its wire key, and the keys are unique. Guards the
10904    /// `builtin_kinds!` expansion: a copy-paste slip in the table would alias two kinds.
10905    #[test]
10906    fn keys_round_trip_and_are_unique() {
10907        let mut seen = std::collections::HashSet::new();
10908        for &b in Builtin::ALL {
10909            assert_eq!(Builtin::from_key(b.key()), Some(b), "{b:?} key round-trip");
10910            assert!(seen.insert(b.key()), "duplicate key {:?}", b.key());
10911            assert!(
10912                b.key().starts_with("day."),
10913                "built-in {b:?} must use the reserved `day.` prefix"
10914            );
10915        }
10916    }
10917
10918    /// The `kinds::*` constants are the enum's keys, so the two spellings cannot drift.
10919    #[test]
10920    fn kinds_constants_match_the_enum() {
10921        assert_eq!(kinds::LABEL, Builtin::Label.key());
10922        assert_eq!(kinds::LIST_CELL, Builtin::ListCell.key());
10923        assert_eq!(kinds::COVER, Builtin::Cover.key());
10924        assert_eq!(kinds::INSPECTOR, Builtin::Inspector.key());
10925        assert_eq!(kinds::TREE, Builtin::Tree.key());
10926        // 19 after `Tabs`/`TabsPage` retired (the tab bar is a NAV presentation, not a kind),
10927        // +2 for the inspector split and its panes (docs/inspector.md), +1 for the tree
10928        // (docs/tree.md).
10929        assert_eq!(Builtin::ALL.len(), 25);
10930    }
10931
10932    /// An extension piece's kind is not a built-in.
10933    #[test]
10934    fn extension_kinds_are_not_builtin() {
10935        assert_eq!(Builtin::from_key("acme.combobox"), None);
10936        assert_eq!(Builtin::from_key("day.not_a_real_kind"), None);
10937    }
10938}
10939
10940#[cfg(test)]
10941mod locale_tests {
10942    /// POSIX locale strings are not BCP-47 tags, and "C" is not a language; that difference is
10943    /// the job of `posix_locale_hints` (§12.2).
10944    #[test]
10945    fn posix_hints_parse_and_drop_the_c_locale() {
10946        // The parsing is exercised through the same normalization the function applies.
10947        let normalize = |v: &str| v.split('.').next().unwrap_or(v).replace('_', "-");
10948        assert_eq!(normalize("fr_FR.UTF-8"), "fr-FR");
10949        assert_eq!(normalize("en_US"), "en-US");
10950        assert_eq!(normalize("C"), "C");
10951        // A real read never panics whatever this host's environment holds.
10952        let hints = super::posix_locale_hints();
10953        assert!(
10954            hints
10955                .iter()
10956                .all(|h| !h.is_empty() && h != "C" && h != "POSIX")
10957        );
10958    }
10959}
10960
10961#[cfg(test)]
10962mod sidetable_tests {
10963    use super::sidetable::{SideTable, sweep};
10964    use std::cell::Cell;
10965    use std::rc::Rc;
10966
10967    /// The registry exists so that one `sweep(key)` clears every table without any
10968    /// table needing its own line in a backend's `release()`.
10969    #[test]
10970    fn sweep_clears_every_registered_table_and_runs_teardowns() {
10971        let torn = Rc::new(Cell::new(0u32));
10972        let t2 = torn.clone();
10973        let plain: SideTable<&'static str> = SideTable::new();
10974        let hooked: SideTable<u32> = SideTable::with_teardown(move |_| t2.set(t2.get() + 1));
10975
10976        plain.insert(7, "a");
10977        hooked.insert(7, 1);
10978        hooked.insert(8, 2);
10979        sweep(7);
10980        assert!(!plain.contains(7));
10981        assert!(!hooked.contains(7), "swept from every table");
10982        assert!(hooked.contains(8), "other keys untouched");
10983        assert_eq!(torn.get(), 1, "teardown ran for the swept value");
10984
10985        // remove() runs the teardown too; take() bypasses it for ownership transfer.
10986        let _ = hooked.remove(8);
10987        assert_eq!(torn.get(), 2);
10988        hooked.insert(9, 3);
10989        assert_eq!(hooked.take(9), Some(3));
10990        assert_eq!(torn.get(), 2, "take() skips the hook");
10991    }
10992
10993    #[test]
10994    fn contain_returns_default_on_panic() {
10995        let ok = super::ffi_guard::contain(0i32, || 5);
10996        assert_eq!(ok, 5);
10997        let prev = std::panic::take_hook();
10998        std::panic::set_hook(Box::new(|_| {}));
10999        let contained = super::ffi_guard::contain(-1i32, || panic!("boom"));
11000        std::panic::set_hook(prev);
11001        assert_eq!(contained, -1, "the panic must not escape the guard");
11002    }
11003}
11004
11005#[cfg(test)]
11006mod cursor_tests {
11007    use super::Cursor;
11008
11009    /// Every named cursor has a distinct CSS keyword, and `NAMED` lists each exactly once: the
11010    /// gallery and every backend's table key on the keyword.
11011    #[test]
11012    fn named_cursors_have_distinct_css_names() {
11013        let mut seen = std::collections::BTreeSet::new();
11014        for c in &Cursor::NAMED {
11015            assert!(
11016                seen.insert(c.css_name().to_string()),
11017                "duplicate: {}",
11018                c.css_name()
11019            );
11020            assert!(!matches!(c, Cursor::Native(_)));
11021        }
11022        assert_eq!(seen.len(), Cursor::NAMED.len());
11023        assert_eq!(Cursor::native("dragCopy").css_name(), "dragCopy");
11024        assert_eq!(Cursor::default(), Cursor::Default);
11025    }
11026}
11027
11028#[cfg(test)]
11029mod text_anchor_tests {
11030    /// The anchor arithmetic every backend repeats. A drawing whose text lands in the wrong
11031    /// corner is a per-backend bug that only a screenshot catches, so the shared definition is
11032    /// pinned here and each shim is written to match it.
11033    #[test]
11034    fn text_anchor_offsets_place_the_line_box() {
11035        use crate::props::TextAlign;
11036        use crate::{TextAnchor, TextVAlign};
11037        // A 40-wide, 20-tall line box whose baseline sits 16 below its top.
11038        let (w, h, asc) = (40.0, 20.0, 16.0);
11039        let at = |ha, va| TextAnchor { h: ha, v: va }.offset(w, h, asc);
11040
11041        // The default is the drawing origin itself, every backend's native "draw here".
11042        assert_eq!(at(TextAlign::Leading, TextVAlign::Top), (0.0, 0.0));
11043        assert_eq!(TextAnchor::default(), TextAnchor::LEADING);
11044        // Horizontal: the box's leading edge, its middle, its trailing edge.
11045        assert_eq!(at(TextAlign::Center, TextVAlign::Top).0, -20.0);
11046        assert_eq!(at(TextAlign::Trailing, TextVAlign::Top).0, -40.0);
11047        // Vertical: top, middle, the baseline itself, bottom.
11048        assert_eq!(at(TextAlign::Leading, TextVAlign::Middle).1, -10.0);
11049        assert_eq!(at(TextAlign::Leading, TextVAlign::Baseline).1, -16.0);
11050        assert_eq!(at(TextAlign::Leading, TextVAlign::Bottom).1, -20.0);
11051        // The two named placements are the ones the two-variant enum used to have.
11052        assert_eq!(TextAnchor::CENTERED.offset(w, h, asc), (-20.0, -10.0));
11053        assert_eq!(TextAnchor::TRAILING.offset(w, h, asc), (-40.0, 0.0));
11054    }
11055
11056    /// The wire code the serializing backends (qt, xaml, arkui, android, web) decode by hand.
11057    #[test]
11058    fn text_anchor_packs_into_one_slot_and_round_trips() {
11059        use crate::props::TextAlign;
11060        use crate::{TextAnchor, TextVAlign};
11061        let mut seen = std::collections::BTreeSet::new();
11062        for h in [TextAlign::Leading, TextAlign::Center, TextAlign::Trailing] {
11063            for v in [
11064                TextVAlign::Top,
11065                TextVAlign::Middle,
11066                TextVAlign::Baseline,
11067                TextVAlign::Bottom,
11068            ] {
11069                let a = TextAnchor { h, v };
11070                let code = a.pack();
11071                assert!(
11072                    (0.0..=11.0).contains(&code),
11073                    "{code} outside the packed range"
11074                );
11075                assert!(seen.insert(code as u64), "two anchors share code {code}");
11076                assert_eq!(TextAnchor::unpack(code), a);
11077            }
11078        }
11079        assert_eq!(seen.len(), 12);
11080        // The shims decode as `h = code / 4`, `v = code % 4` in integer arithmetic.
11081        assert_eq!(TextAnchor::LEADING.pack(), 0.0);
11082        assert_eq!(TextAnchor::CENTERED.pack(), 5.0);
11083        // Junk answers the default rather than failing inside a native draw callback.
11084        assert_eq!(TextAnchor::unpack(-3.0), TextAnchor::LEADING);
11085        assert_eq!(TextAnchor::unpack(99.0), TextAnchor::unpack(11.0));
11086    }
11087
11088    /// The two shapes a backend's own metrics arrive in. Both land on the same contract: the line
11089    /// box's top-leading corner is the origin, and `ink` is relative to it.
11090    #[test]
11091    fn metrics_convert_from_a_backends_own_shape() {
11092        use crate::{Rect, TextMetrics};
11093        // Baseline-relative, y up-negative; Core Text, Skia and Qt all report like this.
11094        let m = TextMetrics::from_baseline(
11095            40.0,
11096            16.0,
11097            4.0,
11098            11.0,
11099            // Ink starting 1 right of the origin, from 11 above the baseline to 2 below it.
11100            Rect::new(1.0, -11.0, 38.0, 13.0),
11101        );
11102        assert_eq!(
11103            (m.width, m.height, m.ascent, m.cap_height),
11104            (40.0, 20.0, 16.0, 11.0)
11105        );
11106        // Shifted down by the ascent: the ink now starts 5 below the line box's top, which is
11107        // where a cap begins in a slot whose baseline is at 16.
11108        assert_eq!(m.ink, Rect::new(1.0, 5.0, 38.0, 13.0));
11109        assert_eq!(m.ascent - m.cap_height, m.ink.origin.y);
11110
11111        // The eight-slot wire form is already line-box-relative and passes straight through.
11112        let w = TextMetrics::from_slots(&[40.0, 20.0, 16.0, 11.0, 1.0, 5.0, 38.0, 13.0]);
11113        assert_eq!(w, m);
11114    }
11115
11116    /// The fallback must be usable, not merely present: a caller frames text with it on a toolkit
11117    /// that cannot measure, and every relation it relies on has to hold.
11118    #[test]
11119    fn the_approximation_is_internally_consistent() {
11120        use crate::TextMetrics;
11121        let m = TextMetrics::approximate("Agy", 20.0);
11122        assert!(m.ascent < m.height, "the baseline sits inside the line box");
11123        assert!(
11124            m.cap_height < m.ascent,
11125            "caps do not reach above the ascent"
11126        );
11127        // The ink box is the whole line box: a superset, so an overlap test using it can only be
11128        // too cautious. Never a claim to be tighter than it knows.
11129        assert_eq!(m.ink.origin.x, 0.0);
11130        assert_eq!(m.ink.origin.y, 0.0);
11131        assert_eq!(m.ink.size.width, m.width);
11132        assert_eq!(m.ink.size.height, m.height);
11133        // Empty text still answers a usable (zero-width, full-height) slot.
11134        let e = TextMetrics::approximate("", 20.0);
11135        assert_eq!(e.width, 0.0);
11136        assert!(e.height > 0.0);
11137    }
11138}
11139
11140#[cfg(test)]
11141mod cap_list_tests {
11142    use super::Cap;
11143
11144    #[test]
11145    fn every_capability_is_listed_once_in_its_place() {
11146        for (i, cap) in Cap::ALL.iter().enumerate() {
11147            assert_eq!(cap.ordinal(), i, "{cap:?} is out of place in Cap::ALL");
11148        }
11149    }
11150}
11151
11152#[cfg(test)]
11153mod button_menu_tests {
11154    use super::*;
11155    use std::cell::Cell;
11156    use std::rc::Rc;
11157
11158    fn action(label: &str) -> MenuItem {
11159        MenuItem::Action {
11160            id: None,
11161            action: 1,
11162            label: label.into(),
11163            shortcut: None,
11164            enabled: true,
11165            checked: None,
11166            role: None,
11167            icon: None,
11168        }
11169    }
11170
11171    #[test]
11172    fn a_provider_that_releases_its_button_shows_nothing() {
11173        let registered = Rc::new(Cell::new(true));
11174        let r = registered.clone();
11175        // The provider's app code removes the button (here: unregisters it), then still answers.
11176        let provider: ContextMenuFn = Rc::new(move |_| {
11177            r.set(false);
11178            vec![action("Open")]
11179        });
11180        assert!(resolve_button_menu(&provider, || registered.get()).is_none());
11181    }
11182
11183    #[test]
11184    fn a_live_button_shows_its_items_and_an_empty_menu_shows_nothing() {
11185        let provider: ContextMenuFn = Rc::new(|_| vec![action("Open")]);
11186        assert_eq!(
11187            resolve_button_menu(&provider, || true).map(|i| i.len()),
11188            Some(1)
11189        );
11190        let empty: ContextMenuFn = Rc::new(|_| Vec::new());
11191        let mut asked = false;
11192        assert!(
11193            resolve_button_menu(&empty, || {
11194                asked = true;
11195                true
11196            })
11197            .is_none()
11198        );
11199        assert!(!asked, "an empty menu needs no registry check");
11200    }
11201}