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
14pub mod controls;
15pub use controls::datetime::{DayDate, DayTime};
16
17pub mod applications;
18pub mod capture;
19/// Inline markdown → styled runs (docs/markdown.md). Lives here rather than in day-pieces
20/// because it produces `TextRun`s, and every format codec beside it reads the same model.
21pub mod markdown;
22/// Bundled-resource random-access API + the per-backend `ResourceOpener` hook (§18.3).
23pub mod resource;
24/// Styled text: the document model `label().runs(…)` renders and `day-piece-text-editor` edits,
25/// with the Markdown / HTML / RTF codecs over it (docs/texteditor.md).
26pub mod styled;
27/// Import and export for [`StyledText`]: Markdown, HTML and RTF (docs/texteditor.md).
28pub mod styled_codec;
29pub mod transfer;
30
31pub use resource::{
32    AssetDir, AssetName, FontFamily, ImageName, Resource, ResourceOpener, VectorName,
33    resolve_asset_dir, resolve_image_file, resource, set_resource_opener,
34};
35pub use styled::{
36    ListStyle, ParagraphAlign, ParagraphRun, ParagraphStyle, RunStyle, StyledText, Underline,
37    coalesce_runs, paragraph_bounds, paragraphs_are_valid,
38};
39pub use styled_codec::{
40    DocStyle, html_to_styled, markdown_to_styled, rtf_to_styled, styled_to_html,
41    styled_to_markdown, styled_to_rtf,
42};
43
44/// Bundled custom fonts: name-table parsing, runtime font directory, family → file resolution
45/// (§18.4). Shared by the CLI stagers and the backends' startup registration. Lives in the leaf
46/// `day-fonts` crate (pure std, no `day-geometry`), re-exported here so `day_spec::fonts::…` is
47/// unchanged for the backends while the CLI can depend on `day-fonts` alone.
48pub use day_fonts as fonts;
49
50/// The route inside a deep-link URL (docs/deep-links.md): everything after `scheme://`,
51/// query included (`notes://mail/inbox?hint=x` ⇒ `mail/inbox?hint=x`). A string with no
52/// scheme passes through unchanged (it is already a route). One definition, shared by every
53/// platform's intake and the dayscript `deep_link` step, so a URL maps to the same route
54/// bytes everywhere; percent-decoding stays with the route parser (docs/navigation.md).
55pub fn route_of_url(url: &str) -> String {
56    match url.split_once("://") {
57        Some((_, rest)) => rest.to_string(),
58        None => url.to_string(),
59    }
60}
61
62// ---------------------------------------------------------------------------
63// Identity
64// ---------------------------------------------------------------------------
65
66/// Interned piece-kind key, e.g. `"day.label"` or `"acme.combobox"`.
67pub type PieceKind = &'static str;
68
69/// Declare the built-in piece vocabulary once: the [`Builtin`] enum, its string keys, and the
70/// `kinds::*` constants are all generated from this list, so they can never drift apart.
71///
72/// Adding a variant here is a breaking change for backends: every `Toolkit` must decide how
73/// to realize the new kind, and the exhaustive `match Builtin` in each backend's `realize`
74/// turns that decision into a compile error rather than a runtime placeholder.
75macro_rules! builtin_kinds {
76    ($( $(#[$meta:meta])* $variant:ident = $konst:ident => $key:literal ),+ $(,)?) => {
77        /// Every piece kind Day itself defines (§5.3). Backends match on this exhaustively in
78        /// `realize`; anything outside it is an extension piece resolved through the
79        /// [`Registry`] by its string [`PieceKind`].
80        #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
81        pub enum Builtin {
82            $( $(#[$meta])* $variant, )+
83        }
84
85        impl Builtin {
86            /// This kind's wire key: the same string as the matching `kinds::*` constant.
87            pub const fn key(self) -> PieceKind {
88                match self { $( Builtin::$variant => $key, )+ }
89            }
90
91            /// The built-in this key names, or `None` for an extension piece's kind.
92            pub fn from_key(kind: PieceKind) -> Option<Builtin> {
93                match kind {
94                    $( $key => Some(Builtin::$variant), )+
95                    _ => None,
96                }
97            }
98
99            /// Every built-in, in declaration order (conformance tests iterate it).
100            pub const ALL: &'static [Builtin] = &[ $( Builtin::$variant, )+ ];
101        }
102
103        /// The built-in piece keys as plain strings, for the registry and the `PieceKind` API.
104        pub mod kinds {
105            $( $(#[$meta])* pub const $konst: super::PieceKind = super::Builtin::$variant.key(); )+
106        }
107    };
108}
109
110builtin_kinds! {
111    /// A dumb native panel (the column/row/stack backing).
112    Container = CONTAINER => "day.container",
113    Label = LABEL => "day.label",
114    Button = BUTTON => "day.button",
115    Toggle = TOGGLE => "day.toggle",
116    Slider = SLIDER => "day.slider",
117    TextField = TEXT_FIELD => "day.text_field",
118    /// A native multi-line text editor (docs/textarea.md). Built-in since 2026-07 (previously
119    /// the satellite `day-piece-textarea`).
120    TextArea = TEXT_AREA => "day.text_area",
121    /// A native option picker with menu/segmented/inline stylings (docs/picker.md). Built-in
122    /// since 2026-07 (previously the satellite `day-piece-picker`).
123    Picker = PICKER => "day.picker",
124    Divider = DIVIDER => "day.divider",
125    Scroll = SCROLL => "day.scroll",
126    Image = IMAGE => "day.image",
127    /// Progress indicator: determinate bar (fraction) or indeterminate spinner.
128    Progress = PROGRESS => "day.progress",
129    Canvas = CANVAS => "day.canvas",
130    /// Navigation host (docs/navigation.md): stack on mobile, split panes on desktop.
131    Nav = NAV => "day.nav",
132    /// One destination's native container inside a NAV host.
133    NavPage = NAV_PAGE => "day.nav_page",
134    /// Native navigation item list (docs/navigation.md): NSOutlineView source list /
135    /// GtkListBox navigation-sidebar / QListWidget / UITableView rows with chevrons.
136    NavMenu = NAV_MENU => "day.nav_menu",
137    /// Native recycling list (docs/list.md): NSTableView / UITableView / RecyclerView /
138    /// GtkListView / QListView. Owns scrolling + cell reuse; Day binds row content on demand.
139    List = LIST => "day.list",
140    /// A recycled row's content anchor inside a `LIST`; Day adopts the native cell as its handle.
141    /// Adopted, never realized: `Toolkit::adopt` wraps the native cell, so backends' `realize`
142    /// never sees this kind.
143    ListCell = LIST_CELL => "day.list_cell",
144    /// Native hierarchical tree (docs/tree.md): NSOutlineView / sidebar collection list /
145    /// GtkListView+TreeListModel / WinUI TreeView / ArkTS TreeView. Rows nest, disclose, and
146    /// drag-to-reparent; Day binds row content on demand through `Toolkit::attach_tree`.
147    /// Row cells are adopted (the same `LIST_CELL` anchor path as `List`).
148    Tree = TREE => "day.tree",
149    /// A fullscreen cover (docs/cover.md): a modal surface presented over the whole window,
150    /// edge-to-edge, driven by `CoverPatch::{Present,Dismiss}`. The handle is the cover's
151    /// content container; its frame is native-owned while presented (the backend sizes it to
152    /// the safe area and reports it via `Event::FrameChanged`).
153    Cover = COVER => "day.cover",
154    /// Content beside a trailing inspector pane (docs/inspector.md): the native split whose
155    /// second pane is a show/hidable properties panel. Exactly two `INSPECTOR_PANE` children:
156    /// the content, then the panel (`InspectorPaneProps::panel`). Only realized where
157    /// `Cap::Inspector` answers `Native`; everywhere else the `inspector` piece composes the
158    /// pane from plain containers and this kind never reaches the backend.
159    Inspector = INSPECTOR => "day.inspector",
160    /// One pane's container inside an `INSPECTOR` host: the `NAV_PAGE` of the inspector split.
161    /// Its frame is native-owned (the splitter/dock sizes it), reported via
162    /// `Event::FrameChanged` on this node; Day lays the pane's content out inside it.
163    InspectorPane = INSPECTOR_PANE => "day.inspector_pane",
164    /// Two panes with a divider the user drags (docs/split.md): the toolkit's own splitter,
165    /// side by side or stacked (`SplitProps::axis`), the first pane's share bound to the app
166    /// (`SplitProps::fraction`, reported back as `Event::ValueChanged`). Exactly two
167    /// `SPLIT_PANE` children, first then second. Only realized where `Cap::Split` answers
168    /// `Native`; everywhere else the `split` piece composes the panes and draws the divider
169    /// itself, and this kind never reaches the backend.
170    Split = SPLIT => "day.split",
171    /// One pane's container inside a `SPLIT` host: native-owned frame (the splitter sizes it),
172    /// reported via `Event::FrameChanged` on this node, like an `INSPECTOR_PANE`.
173    SplitPane = SPLIT_PANE => "day.split_pane",
174    /// A list row's standard content (docs/list.md "List items"): a leading icon, a title, an
175    /// optional subtitle and trailing detail, and a check mark, drawn the way the platform
176    /// draws its own list rows: a `UIListContentView` with the cell's default content
177    /// configuration, a Material list item, an `NSTableCellView`'s image and text, a GTK row
178    /// box. Only realized where `Cap::ListItem` answers `Native`; everywhere else the
179    /// `list_item` piece composes the same content and this kind never reaches the backend.
180    ListItem = LIST_ITEM => "day.list_item",
181}
182
183/// Whether a kind is worth asking [`Toolkit::first_baseline`] about (docs/baseline.md).
184///
185/// A blocklist, not an allowlist: the structural and graphic kinds below have no text of their
186/// own, and everything else (including extension pieces like the date/time pickers, whose kinds
187/// day-spec has never heard of) is assumed to be worth asking. An extension piece that turns
188/// out to have no baseline answers `None`, which costs one query; an allowlist would instead
189/// silently leave every extension piece centered, which is the bug this shape avoids.
190pub fn kind_has_baseline(kind: PieceKind) -> bool {
191    !matches!(
192        Builtin::from_key(kind),
193        Some(
194            Builtin::Container
195                | Builtin::Scroll
196                | Builtin::Divider
197                | Builtin::Image
198                | Builtin::Canvas
199                | Builtin::Slider
200                | Builtin::Toggle
201                | Builtin::Progress
202                | Builtin::Nav
203                | Builtin::NavPage
204                | Builtin::NavMenu
205                | Builtin::Split
206                | Builtin::SplitPane
207                | Builtin::List
208                | Builtin::ListCell
209                | Builtin::Cover
210                | Builtin::Inspector
211                | Builtin::InspectorPane
212        )
213    )
214}
215
216/// Placeholder leaves: the one hole in Day's rendering that is invisible to a screenshot.
217///
218/// When a backend has no renderer for a kind it realizes a visible `⟨kind⟩` label rather than
219/// failing. That is the right runtime behavior, but it means a missing renderer looks like a
220/// rendered app: the walkthrough passes, and the gallery's validator (which counts distinct
221/// colors) sees nothing wrong. That is how a stale `skip_on:` survived in the showcase
222/// walkthrough after the renderer it skipped had landed.
223///
224/// So every backend reports here instead of keeping its own warn-once set. The table is process-
225/// wide and append-only, which gives dayscript's `assert_no_placeholders` something to assert on
226/// (`crates/day-script`): a placeholder becomes a test failure instead of a silent gap.
227pub mod placeholder {
228    use super::PieceKind;
229    use std::collections::BTreeSet;
230    use std::sync::{Mutex, OnceLock};
231
232    fn table() -> &'static Mutex<BTreeSet<PieceKind>> {
233        static TABLE: OnceLock<Mutex<BTreeSet<PieceKind>>> = OnceLock::new();
234        TABLE.get_or_init(|| Mutex::new(BTreeSet::new()))
235    }
236
237    /// Record that `toolkit` had no renderer for `kind` and warn, once per kind, however many
238    /// nodes of it are realized. Call from a backend's `realize` fallback arm.
239    pub fn report(kind: PieceKind, toolkit: &str) {
240        let Ok(mut seen) = table().lock() else { return };
241        if seen.insert(kind) {
242            log::warn!(
243                "no renderer for piece kind \"{kind}\" on {toolkit} — is the piece's \
244                 {toolkit} feature enabled? (rendering a placeholder)"
245            );
246        }
247    }
248
249    /// Every kind that has rendered a placeholder in this process, sorted. Empty is the goal.
250    pub fn seen() -> Vec<PieceKind> {
251        table()
252            .lock()
253            .map(|s| s.iter().copied().collect())
254            .unwrap_or_default()
255    }
256}
257
258/// Downcast a realize/update payload to the props/patch type a backend arm expects,
259/// warning (once per kind, via [`placeholder::report`]) instead of panicking on a
260/// mismatch. A mismatch means a piece registered under a builtin key or a day-core
261/// regression; degrade to the placeholder path, never abort: most backend arms run
262/// inside native up-calls, where a panic is a process kill.
263pub fn props_of<'a, T: 'static>(
264    kind: PieceKind,
265    toolkit: &str,
266    any: &'a dyn std::any::Any,
267) -> Option<&'a T> {
268    let p = any.downcast_ref::<T>();
269    if p.is_none() {
270        placeholder::report(kind, toolkit);
271    }
272    p
273}
274
275/// Pointer-keyed per-view side tables with an automatic release sweep.
276///
277/// Backends keep auxiliary per-view state in thread-local maps keyed by the native
278/// handle's address. Historically each map needed its own line in `release()`, a
279/// checklist that drifted repeatedly (missed entries have produced both leaks and
280/// stale-pointer CI segfaults, since a freed address gets recycled). A [`crate::sidetable::SideTable`]
281/// registers itself with a per-thread sweeper list at construction, so a backend's
282/// `release()` calls [`crate::sidetable::sweep`] once and every table, present and future, drops its
283/// entry for that handle, running its teardown hook if one was given.
284pub mod sidetable {
285    use std::cell::RefCell;
286    use std::collections::HashMap;
287    use std::rc::Rc;
288
289    /// One table's "remove this key" hook, registered at construction.
290    type Sweeper = Rc<dyn Fn(usize)>;
291
292    thread_local! {
293        static SWEEPERS: RefCell<Vec<Sweeper>> = const { RefCell::new(Vec::new()) };
294    }
295
296    /// A pointer-keyed map swept automatically by [`crate::sidetable::sweep`]. Construct inside a
297    /// `thread_local!` initializer; the optional teardown hook runs for each removed
298    /// value (release a retained native object, dispose an owned child, …), both on sweep
299    /// and on plain [`SideTable::remove`], so teardown cannot be bypassed by accident.
300    pub struct SideTable<V: 'static> {
301        map: Rc<RefCell<HashMap<usize, V>>>,
302        teardown: Option<Rc<dyn Fn(V)>>,
303    }
304
305    impl<V> Default for SideTable<V> {
306        fn default() -> Self {
307            Self::new()
308        }
309    }
310
311    impl<V> SideTable<V> {
312        pub fn new() -> Self {
313            Self::build(None)
314        }
315
316        /// A table whose values need active teardown when their view goes away.
317        pub fn with_teardown(teardown: impl Fn(V) + 'static) -> Self {
318            Self::build(Some(Rc::new(teardown)))
319        }
320
321        fn build(teardown: Option<Rc<dyn Fn(V)>>) -> Self {
322            let map: Rc<RefCell<HashMap<usize, V>>> = Rc::default();
323            let (m, t) = (map.clone(), teardown.clone());
324            SWEEPERS.with(|s| {
325                s.borrow_mut().push(Rc::new(move |key| {
326                    // Remove under the borrow, tear down outside it: hooks may re-enter
327                    // toolkit code that reads other tables.
328                    let v = m.borrow_mut().remove(&key);
329                    if let (Some(v), Some(t)) = (v, &t) {
330                        t(v);
331                    }
332                }));
333            });
334            SideTable { map, teardown }
335        }
336
337        pub fn insert(&self, key: usize, value: V) -> Option<V> {
338            self.map.borrow_mut().insert(key, value)
339        }
340
341        /// Remove and tear down the entry (returns `None` always when a teardown hook
342        /// exists, because the value is consumed by it; use [`SideTable::take`] to skip it).
343        pub fn remove(&self, key: usize) -> Option<V> {
344            let v = self.map.borrow_mut().remove(&key)?;
345            match &self.teardown {
346                Some(t) => {
347                    t(v);
348                    None
349                }
350                None => Some(v),
351            }
352        }
353
354        /// Remove without running the teardown hook (the caller takes ownership).
355        pub fn take(&self, key: usize) -> Option<V> {
356            self.map.borrow_mut().remove(&key)
357        }
358
359        pub fn contains(&self, key: usize) -> bool {
360            self.map.borrow().contains_key(&key)
361        }
362
363        pub fn get(&self, key: usize) -> Option<V>
364        where
365            V: Clone,
366        {
367            self.map.borrow().get(&key).cloned()
368        }
369
370        /// Run `f` on the value in place (returns `None` if absent).
371        pub fn with<R>(&self, key: usize, f: impl FnOnce(&mut V) -> R) -> Option<R> {
372            self.map.borrow_mut().get_mut(&key).map(f)
373        }
374
375        /// Run `f` over every `(key, value)` (immutable; do not re-enter this table).
376        pub fn for_each(&self, mut f: impl FnMut(usize, &V)) {
377            for (k, v) in self.map.borrow().iter() {
378                f(*k, v);
379            }
380        }
381    }
382
383    /// Remove `key` from every table registered on this thread, running teardowns.
384    /// Call once from a backend's `release()` (and once per auxiliary native object a
385    /// release frees, e.g. an owned content container).
386    pub fn sweep(key: usize) {
387        // Clone the sweeper list first: a teardown may construct a new SideTable
388        // (registering a sweeper) without deadlocking on the borrow.
389        let sweepers: Vec<Sweeper> = SWEEPERS.with(|s| s.borrow().clone());
390        for f in sweepers {
391            f(key);
392        }
393    }
394}
395
396/// Containment for FFI entry points: native callbacks, JNI up-calls, posted-closure
397/// trampolines. A Rust panic unwinding out of an `extern "C"` frame is undefined
398/// behavior (an abort), so every backend trampoline runs its body through
399/// [`ffi_guard::contain`]: a caught panic is reported, the installed recovery hook
400/// restores runtime coherence (day-core installs the reactive runtime's
401/// `recover_from_panic` at boot), and the given default is returned.
402pub mod ffi_guard {
403    use std::sync::OnceLock;
404
405    static RECOVERY: OnceLock<fn()> = OnceLock::new();
406
407    /// Install the post-panic recovery hook (idempotent; first install wins). day-core
408    /// registers `day_reactive::recover_from_panic` here so a contained panic cannot
409    /// leave the reactive observer stack stranded.
410    pub fn set_recovery(f: fn()) {
411        let _ = RECOVERY.set(f);
412    }
413
414    /// Run `f`, containing any panic; on panic, report, run the recovery hook, and
415    /// return `default`.
416    pub fn contain<R>(default: R, f: impl FnOnce() -> R) -> R {
417        match std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)) {
418            Ok(r) => r,
419            Err(payload) => {
420                let msg = payload
421                    .downcast_ref::<&str>()
422                    .map(|s| s.to_string())
423                    .or_else(|| payload.downcast_ref::<String>().cloned())
424                    .unwrap_or_else(|| "<non-string panic>".into());
425                log::error!("panic contained at an FFI boundary: {msg}");
426                if let Some(recover) = RECOVERY.get() {
427                    recover();
428                }
429                default
430            }
431        }
432    }
433}
434
435/// The painting threads behind the offscreen exports (docs/canvas.md "Exporting").
436///
437/// `Toolkit::render_bitmap` answers with an event, so a toolkit whose 2-D API can draw into a
438/// memory surface from any thread paints there and posts the answer back to the UI thread. The
439/// pool is shared by every toolkit in the process: a few threads, one short of the cores and
440/// never more than four, so a screenful of requests cannot starve the UI thread or the app's
441/// own work. Jobs run in the order they were queued.
442///
443/// Not built for the web: a browser's `createImageBitmap` is already asynchronous, and
444/// `wasm32-unknown-unknown` has no threads to spawn.
445#[cfg(not(target_arch = "wasm32"))]
446pub mod offscreen {
447    use std::sync::atomic::{AtomicUsize, Ordering};
448    use std::sync::{Arc, Mutex, OnceLock, mpsc};
449
450    type Job = Box<dyn FnOnce() + Send + 'static>;
451
452    static QUEUE: OnceLock<Mutex<mpsc::Sender<Job>>> = OnceLock::new();
453    /// How many painting threads started; zero means every job runs where it was queued.
454    static WORKERS: AtomicUsize = AtomicUsize::new(0);
455
456    /// Run `job` on a painting thread, or inline when none could be started. A panic inside
457    /// `job` is contained ([`crate::ffi_guard::contain`]) so one bad replay cannot take the
458    /// thread, and with it every later export, down; the job itself should answer its request
459    /// in that case, which is why toolkits wrap the paint and not the post.
460    pub fn spawn(job: impl FnOnce() + Send + 'static) {
461        let queue = QUEUE.get_or_init(start);
462        if WORKERS.load(Ordering::Acquire) == 0 {
463            crate::ffi_guard::contain((), job);
464            return;
465        }
466        let job: Job = Box::new(job);
467        // The receivers live as long as the process, so a refused send means every worker left
468        // its loop; the job still runs, inline, rather than a request going unanswered.
469        let refused = match queue.lock() {
470            Ok(sender) => sender.send(job).err().map(|e| e.0),
471            Err(_) => Some(job),
472        };
473        if let Some(job) = refused {
474            crate::ffi_guard::contain((), job);
475        }
476    }
477
478    fn start() -> Mutex<mpsc::Sender<Job>> {
479        let (tx, rx) = mpsc::channel::<Job>();
480        let rx = Arc::new(Mutex::new(rx));
481        let want = std::thread::available_parallelism()
482            .map(|n| n.get())
483            .unwrap_or(2)
484            .saturating_sub(1)
485            .clamp(1, 4);
486        let mut started = 0;
487        for i in 0..want {
488            let rx = Arc::clone(&rx);
489            let spawned = std::thread::Builder::new()
490                .name(format!("day-paint-{i}"))
491                .spawn(move || {
492                    loop {
493                        // The lock is held only while waiting for the next job, never while
494                        // running one, so the other workers queue behind it fairly.
495                        let next = match rx.lock() {
496                            Ok(guard) => guard.recv(),
497                            Err(_) => return,
498                        };
499                        match next {
500                            Ok(job) => crate::ffi_guard::contain((), job),
501                            Err(_) => return,
502                        }
503                    }
504                });
505            match spawned {
506                Ok(_) => started += 1,
507                Err(e) => log::error!("day-spec: could not start a painting thread: {e}"),
508            }
509        }
510        WORKERS.store(started, Ordering::Release);
511        Mutex::new(tx)
512    }
513}
514
515/// Realized-node identity as seen by backends (day-core's slotmap key, FFI-encoded).
516#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
517pub struct NodeId(pub u64);
518
519/// Default navigation sidebar width (split presentation) until the pane reports its size.
520/// Semantic container surfaces (see `ContainerProps::role`): each backend maps a role to its
521/// own theme-adaptive material so the fill tracks light/dark mode without app code.
522#[derive(Clone, Copy, Debug, PartialEq, Eq)]
523pub enum SurfaceRole {
524    /// A form `section` card, the platform's grouped-content background: AppKit quaternary
525    /// system fill, libadwaita `.card`, Qt `palette(alternate-base)`, UIKit tertiary system
526    /// fill, Material surface-container, XAML card background brush.
527    SectionCard,
528    /// The window's own background, the surface a page sits on: what an opaque cover paints
529    /// by default, and the card of a composed modal sheet (docs/cover.md "Modal sheet").
530    Window,
531    /// The layer between a composed modal sheet and the page under it, which says the page is
532    /// out of reach until the sheet goes. The container's `background` is the plain dimming a
533    /// backend draws when it has no material of its own; the web frosts the page instead.
534    Scrim,
535}
536
537pub const NAV_SIDEBAR_WIDTH: f64 = 240.0;
538
539/// Drag limits for a navigation host's sidebar pane, around [`NAV_SIDEBAR_WIDTH`]. Shared by the
540/// desktops whose divider the user can drag (docs/navigation.md): AppKit enforces both through
541/// its `NSSplitViewItem`; Qt honors the minimum through the pane's own minimum size and leaves
542/// the maximum to the user.
543pub const NAV_SIDEBAR_MIN_W: f64 = 160.0;
544pub const NAV_SIDEBAR_MAX_W: f64 = 400.0;
545
546/// Default preferred width of a navigation host's content-list pane
547/// (`props::NavProps::list_width`, docs/navigation.md), Mail's message-list proportion.
548pub const NAV_LIST_WIDTH: f64 = 300.0;
549
550/// Drag limits for the content-list pane, around the app's preferred width; the same split of
551/// duties as the sidebar's.
552pub const NAV_LIST_MIN_W: f64 = 220.0;
553pub const NAV_LIST_MAX_W: f64 = 560.0;
554
555/// Reserved id for window-level events (resize, lifecycle): day-core routes it to the root.
556pub const WINDOW_NODE: NodeId = NodeId(u64::MAX);
557
558/// Which nodes handle the non-text keys (docs/menus.md). Keys follow focus (the focused piece
559/// hears them and nobody else), so a backend whose focused view would have to claim a key from
560/// the platform's own dispatch (AppKit's responder chain, the DOM's default action) has to know
561/// whether the app wants it before swallowing it. An unclaimed arrow has to keep traveling, or
562/// a canvas inside a scroll view would silently eat the keys that scroll it.
563///
564/// It lives here, in day-spec, rather than in day-core: `day-toolkit-dom` depends on day-spec alone,
565/// and this is a fact about a node that both sides need.
566pub mod keys {
567    use super::NodeId;
568    use std::cell::RefCell;
569    use std::collections::HashSet;
570
571    thread_local! {
572        static HANDLED: RefCell<HashSet<NodeId>> = RefCell::new(HashSet::new());
573    }
574
575    /// Declare that `node` has a key handler (what `Decorate::on_key` records at build).
576    pub fn mark(node: NodeId) {
577        HANDLED.with(|h| h.borrow_mut().insert(node));
578    }
579
580    /// Whether `node` has one.
581    pub fn handled(node: NodeId) -> bool {
582        HANDLED.with(|h| h.borrow().contains(&node))
583    }
584
585    thread_local! {
586        static TEXT: RefCell<HashSet<NodeId>> = RefCell::new(HashSet::new());
587    }
588
589    /// Declare that `node` takes the whole keyboard while focused (what `Decorate::keyboard`
590    /// records at build): every key the platform delivers reaches its handler, named the way
591    /// [`super::KeyEvent`] describes for the full route, and a touch platform raises its soft
592    /// keyboard for it.
593    pub fn mark_text(node: NodeId) {
594        TEXT.with(|h| h.borrow_mut().insert(node));
595    }
596
597    /// Whether `node` takes the whole keyboard: it declared so AND it [`handled`]s keys. A
598    /// declaration with no `.on_key` behind it claims nothing, so every backend asks this one
599    /// question before it raises a soft keyboard, names a letter or claims a Tab.
600    pub fn text(node: NodeId) -> bool {
601        TEXT.with(|h| h.borrow().contains(&node)) && handled(node)
602    }
603
604    /// The keys a focused single-line text field hands to its key handler instead of acting
605    /// on them itself (docs/textfield.md "Keys"): what an address bar needs to walk a
606    /// suggestion list and to cancel an edit. Return stays the field's submit, Tab its focus
607    /// walk, and every other key its editing.
608    pub const FIELD_KEYS: [&str; 3] = ["ArrowUp", "ArrowDown", "Escape"];
609
610    /// Whether a focused text field at `node` claims the key named `key` (web name, see
611    /// [`super::KeyEvent::key`]) pressed with `modifiers`: one of [`FIELD_KEYS`], no modifier
612    /// held, and a handler declared for the field. A backend that answers yes reports
613    /// `Event::Key` for `node` and keeps the key from the native field.
614    pub fn field_claims(node: NodeId, key: &str, modifiers: u8) -> bool {
615        modifiers == 0 && FIELD_KEYS.contains(&key) && handled(node)
616    }
617
618    /// Drop both marks for a node that left the tree (day-core calls it from its removal
619    /// path). Node ids are generational, so a stale id would never match a new node; this
620    /// keeps the registries from growing with every rebuilt canvas.
621    pub fn forget(node: NodeId) {
622        HANDLED.with(|h| h.borrow_mut().remove(&node));
623        TEXT.with(|h| h.borrow_mut().remove(&node));
624    }
625}
626
627/// Raw foreign native handle for polyglot adoption (§15.3).
628pub type RawHandle = *mut std::ffi::c_void;
629
630// ---------------------------------------------------------------------------
631// Events (§8.3)
632// ---------------------------------------------------------------------------
633
634/// The wire table for backends whose native side reaches Rust through one numeric-kind
635/// trampoline (Android's JNI `nativeOnEvent`, ArkUI's `day_arkui_on_event`). This enum
636/// defines those kind numbers; the Java and C++ sides carry mirrored constants that parity
637/// tests check against these discriminants (so a collision or drift fails `cargo test` on the
638/// host instead of silently mis-decoding events on a device). AppKit/UIKit/GTK/Qt emit `Event`
639/// values directly and never use these numbers; XAML uses per-event callbacks with its own
640/// small local codes.
641///
642/// Payload conventions ride `(num: f64, text: String)` per kind, documented on each variant.
643pub mod bridge {
644    /// One numeric event kind. `as i32` is the wire value.
645    #[repr(i32)]
646    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
647    pub enum BridgeKind {
648        /// Click/press. No payload.
649        Pressed = 0,
650        /// `text` = the field's full new text.
651        TextChanged = 1,
652        /// `num` != 0 ⇒ on.
653        ToggleChanged = 2,
654        /// `num` = the new value.
655        ValueChanged = 3,
656        /// `num` = the selected index.
657        SelectionChanged = 4,
658        /// `num` == 1 ⇒ the native side already popped (predictive back / up arrow).
659        NavBack = 5,
660        /// Nav/tab page size report; `text` = `"w,h"` in px (Rust divides by density).
661        FrameChanged = 6,
662        /// Warm deep link; `text` = the route.
663        Deeplink = 7,
664        /// Modal answered with a button; `num` = the button index.
665        PresentButton = 8,
666        /// Modal answered with text; `text` = the entry.
667        PresentText = 9,
668        /// Modal dismissed.
669        PresentDismissed = 10,
670        /// Gesture; `num` = phase (0 tap, 1 began, 2 changed, 3 ended), `text` = `"x,y,tx,ty"` px.
671        Gesture = 11,
672        /// Piece-defined open channel (`Event::Custom` with an empty tag): the piece reads the
673        /// raw `num`/`text` payload.
674        Custom = 12,
675        /// Menu selection; the event's node id is the chosen action's dispatch id.
676        MenuAction = 13,
677        /// App lifecycle; `num` = the phase code (`day_spec::Lifecycle` order).
678        Lifecycle = 14,
679        /// File-picker answer; `text` = chosen locators joined by the unit separator.
680        PresentFile = 15,
681        /// `num` != 0 ⇒ gained keyboard focus.
682        FocusChanged = 16,
683        /// IME action / Return.
684        Submitted = 17,
685        /// Root size change; `text` = `"w,h"` in px. Routed to `WINDOW_NODE` as a window
686        /// resize (the rail rotation, late inset passes, and the soft keyboard ride).
687        WindowResized = 18,
688        /// Safe-area report from an edge-to-edge backend; `text` =
689        /// `"top,bottom,leading,trailing"` in px (Rust divides by density and feeds
690        /// `day_core::set_safe_area`). Node id ignored; no `Event` is emitted.
691        SafeArea = 19,
692        /// A secondary window closed (docs/windows.md); the node id is the window's root.
693        WindowClosed = 20,
694        /// A secondary window's key/active state changed; `num` != 0 ⇒ focused.
695        WindowFocused = 21,
696        /// `num` = the settled value: the drag ended (see `Event::ValueCommitted`). A backend
697        /// that cannot tell a settled value from a moving one sends only `ValueChanged`.
698        ValueCommitted = 22,
699        /// Inline search on a `.searchable()` navigation surface (docs/search.md): the field's
700        /// new text, against the nav host's node. `num` = 1 ⇒ the text was submitted (Return or
701        /// the keyboard's Search key), decoding to [`crate::Event::SearchSubmitted`].
702        SearchChanged = 23,
703        /// The toolkit's own adaptive nav container changed presentation and is reporting it
704        /// (docs/size-classes.md). `num` = 1.0 for split, 0.0 for stacked.
705        NavPresentation = 24,
706        /// The system switched between light and dark appearance. No payload; node id ignored
707        /// and no `Event` is emitted; Rust calls `day_core::note_appearance_changed`, the same
708        /// thing AppKit's and GTK's own scheme observers do.
709        AppearanceChanged = 25,
710        /// A fullscreen cover's hide transition finished (docs/cover.md); no payload, and the
711        /// node id is the cover's. Decodes to [`crate::Event::CoverHidden`].
712        CoverHidden = 26,
713        /// A styled text run's link was tapped (docs/text-runs.md); `text` = the run's target.
714        /// Decodes to [`crate::Event::LinkActivated`].
715        LinkActivated = 27,
716        /// The platform's own undo affordance fired (⌘Z, a three-finger swipe, the Edit menu
717        /// through a native front); `num` != 0 ⇒ redo.
718        UndoInvoked = 28,
719        /// A toolbar item produced a value (docs/toolbars.md): the node id is the item's
720        /// dispatch action; `text` = `"on"` with `num` != 0 ⇒ a toggle turned on, `"on"` with
721        /// 0 ⇒ off, `"sel"` with `num` = the chosen segment, `"text:<query>"` ⇒ a search
722        /// item's new text, `"submit:<query>"` ⇒ that text submitted. Decodes to
723        /// [`crate::Event::ToolbarChanged`]. A plain toolbar button sends `MenuAction`.
724        ToolbarChanged = 30,
725        /// An activated list row; `num` is its current index.
726        ListActivated = 31,
727        /// External document copied into app storage; `text` = its local locator.
728        DocumentOpened = 32,
729        /// The user's reduce-motion setting flipped (docs/accessibility.md). No payload; node
730        /// id ignored and no `Event` is emitted; Rust calls `day_core::note_motion_changed`, as
731        /// the desktop backends' own observers do.
732        ReduceMotionChanged = 33,
733        /// Text committed on the full key route (docs/menus.md "The full route"): `text` =
734        /// what the input method or the key typed, `num` = the modifier mask. Decodes to an
735        /// [`crate::Event::Key`] whose `text` is set; a key that typed nothing rides `Key`.
736        Text = 36,
737        /// A non-text key reached the focused node (docs/menus.md); `text` = the day key name
738        /// (`"ArrowLeft"`, `"5"`, …), `num` = the [`crate::KeyEvent`] modifier mask. Decodes to
739        /// [`crate::Event::Key`].
740        Key = 29,
741        /// A window's display state changed (docs/windows.md): `num` = the
742        /// [`crate::WindowState`] code (0 normal, 1 minimized, 2 maximized, 3 fullscreen), against
743        /// the window's root node, or [`crate::WINDOW_NODE`] for the primary. Decodes to
744        /// [`crate::Event::WindowStateChanged`] through [`crate::WindowState::from_code`].
745        WindowStateChanged = 34,
746        /// Native pull-to-refresh request; no payload.
747        RefreshRequested = 35,
748        /// Text shared to the app from the system share sheet (Day.toml `share_target`,
749        /// docs/deep-links.md): `text` = the shared text, then the unit separator and the
750        /// subject when one came with it. Node id ignored and no `Event` is emitted; Rust calls
751        /// `day_core::request_shared_text`, which sends a web link in it to `on_open_url`.
752        SharedText = 37,
753    }
754
755    impl BridgeKind {
756        /// Every variant, for uniqueness/parity tests and exhaustive dispatch.
757        pub const ALL: [BridgeKind; 38] = [
758            BridgeKind::Pressed,
759            BridgeKind::TextChanged,
760            BridgeKind::ToggleChanged,
761            BridgeKind::ValueChanged,
762            BridgeKind::SelectionChanged,
763            BridgeKind::NavBack,
764            BridgeKind::FrameChanged,
765            BridgeKind::Deeplink,
766            BridgeKind::PresentButton,
767            BridgeKind::PresentText,
768            BridgeKind::PresentDismissed,
769            BridgeKind::Gesture,
770            BridgeKind::Custom,
771            BridgeKind::MenuAction,
772            BridgeKind::Lifecycle,
773            BridgeKind::PresentFile,
774            BridgeKind::FocusChanged,
775            BridgeKind::Submitted,
776            BridgeKind::WindowResized,
777            BridgeKind::SafeArea,
778            BridgeKind::WindowClosed,
779            BridgeKind::WindowFocused,
780            BridgeKind::ValueCommitted,
781            BridgeKind::SearchChanged,
782            BridgeKind::NavPresentation,
783            BridgeKind::AppearanceChanged,
784            BridgeKind::CoverHidden,
785            BridgeKind::LinkActivated,
786            BridgeKind::UndoInvoked,
787            BridgeKind::Key,
788            BridgeKind::ToolbarChanged,
789            BridgeKind::ListActivated,
790            BridgeKind::DocumentOpened,
791            BridgeKind::ReduceMotionChanged,
792            BridgeKind::WindowStateChanged,
793            BridgeKind::RefreshRequested,
794            BridgeKind::Text,
795            BridgeKind::SharedText,
796        ];
797    }
798
799    #[cfg(test)]
800    mod tests {
801        use super::BridgeKind;
802
803        /// The kind-15 lesson: two meanings on one number decode silently as the first. Every
804        /// discriminant must be unique, and the table must stay dense enough to spot gaps.
805        #[test]
806        fn discriminants_are_unique() {
807            let mut seen = std::collections::BTreeSet::new();
808            for k in BridgeKind::ALL {
809                assert!(
810                    seen.insert(k as i32),
811                    "duplicate bridge kind number {} ({k:?})",
812                    k as i32
813                );
814            }
815            assert_eq!(seen.len(), BridgeKind::ALL.len());
816        }
817
818        /// `ALL` is what the uniqueness check above sees, so a variant left out of it is a variant
819        /// nothing checks, which is how `SearchChanged` and `NavPresentation` sat outside the
820        /// table. The wire numbers are assigned densely from 0, so demanding the set be exactly
821        /// `0..len` catches both a gap and an omission.
822        #[test]
823        fn table_covers_every_wire_number() {
824            let mut nums: Vec<i32> = BridgeKind::ALL.iter().map(|k| *k as i32).collect();
825            nums.sort_unstable();
826            let dense: Vec<i32> = (0..BridgeKind::ALL.len() as i32).collect();
827            assert_eq!(
828                nums, dense,
829                "bridge kinds must be dense from 0 — a missing entry means a variant no test sees"
830            );
831        }
832    }
833}
834
835#[derive(Clone, Debug, PartialEq)]
836pub enum Event {
837    Pressed,
838    TextChanged(String),
839    Submitted,
840    ToggleChanged(bool),
841    ValueChanged(f64),
842    /// A continuous control's value settled: the drag ended (mouse/touch up), or the value moved
843    /// by a discrete action (a keyboard arrow, a click on the track). Always preceded by the
844    /// `ValueChanged` carrying the same value.
845    ///
846    /// The pair exists because one gesture produces two different facts. `ValueChanged` is the
847    /// live one (bindings follow it so the UI tracks the thumb) and it fires continuously, which
848    /// is why nothing durable should key off it: a drag from 1 to 100 and back to 50 emits every
849    /// value in between. `ValueCommitted` fires once, with the value the user chose, and is what
850    /// a recording, a log, or a refetch should use.
851    ///
852    /// A backend that cannot tell the two apart emits only `ValueChanged`; its sliders then do not
853    /// record (docs/coverage-matrix.md).
854    ValueCommitted(f64),
855    SelectionChanged(i64),
856    /// A list row was activated: desktop double-click/Enter, or a touch tap.
857    /// Separate from selection so keyboard browsing need not open or play the row.
858    ListActivated(usize),
859    /// The platform's own undo affordance fired through a native front (⌘Z on the Edit menu,
860    /// a three-finger swipe, shake-to-undo); `redo` distinguishes the pair. Only backends
861    /// with a native undo system emit it; everywhere else the app's own controls call the
862    /// stack directly and this event never exists (docs/model.md).
863    Undo {
864        redo: bool,
865    },
866    /// The platform's own standard edit command fired through its native route (Edit ▸
867    /// Cut/Copy/Paste, ⌘X/⌘C/⌘V, the browser's `copy`/`paste` DOM events) with no text
868    /// widget claiming it first; the app's edit bridge answers (docs/menus.md). Transport
869    /// is the system clipboard (day-part-clipboard), not the event.
870    Edit(EditOp),
871    /// A multi-select list's selection changed: the full set of selected row indices,
872    /// ascending (empty = nothing selected). Emitted instead of `SelectionChanged` where
873    /// `ListProps::multi_select` is honored (docs/list.md).
874    SelectionSet(Vec<i64>),
875    FocusChanged(bool),
876    Tap(Point),
877    /// A link run inside a label was activated; the payload is [`TextRun::link`] verbatim.
878    LinkActivated(String),
879    LongPress(Point),
880    /// A context-menu summon reported by a toolkit that presents no native menu of its own
881    /// (web-dom): the pieces layer shows the composed menu (docs/menus.md). `local` is the
882    /// point in the node's own coordinates (what the app's provider receives); `window` the
883    /// same point in window coordinates (where the composed panel goes). Toolkits that serve
884    /// context menus natively never emit this.
885    ContextMenu {
886        local: Point,
887        window: Point,
888    },
889    /// A drag/pan gesture (docs/shapes.md). `location` is in the node's local coordinates;
890    /// `translation` is the cumulative movement since `Began`.
891    Drag {
892        phase: DragPhase,
893        location: Point,
894        translation: Point,
895    },
896    /// A pinch/magnify gesture over the node (docs/shapes.md): `scale` is cumulative since
897    /// `Began` (1.0 = unchanged), `location` the gesture's centroid in local coordinates,
898    /// the anchor a zoom keeps stationary. Only nodes that enabled
899    /// [`GestureKind::Pinch`] receive it; a backend with no recognizer emits nothing.
900    Pinch {
901        phase: DragPhase,
902        scale: f64,
903        location: Point,
904    },
905    /// A two-finger rotation over the node (docs/canvas.md "Zoom and pan"): `rotation` is in
906    /// radians, cumulative since `Began`, positive clockwise on screen; `location` the
907    /// gesture's centroid in local coordinates ([`Point::ZERO`] where the platform gives
908    /// none). A trackpad's rotate tick has no gesture session and arrives as a lone `Changed`
909    /// carrying that tick's own angle. Only nodes that enabled [`GestureKind::Rotate`]
910    /// receive it; a backend with no recognizer emits nothing.
911    Rotate {
912        phase: DragPhase,
913        rotation: f64,
914        location: Point,
915    },
916    /// A viewport pan over the node (docs/shapes.md): `delta` is the movement since the
917    /// previous event; incremental, not cumulative, because desktop wheels have no gesture
918    /// session to accumulate over (a discrete wheel tick arrives as a lone `Changed`).
919    /// Two-finger touch pans bracket theirs with `Began`/`Ended`. Distinct from
920    /// [`Event::Drag`], the primary pointer's press-drag.
921    Pan {
922        phase: DragPhase,
923        delta: Point,
924        location: Point,
925    },
926    /// The pointer moved over the node, or left it (docs/canvas.md "Interaction"). `location` is
927    /// in the node's local coordinates. Phases follow the drag vocabulary: `Began` on entry,
928    /// `Changed` for each move, `Ended` on exit, where `location` is the last point seen inside,
929    /// so a handler always knows where the pointer went out.
930    ///
931    /// Only nodes that enabled [`GestureKind::Hover`] receive it, and only on a device with a
932    /// pointer at all.
933    Hover {
934        phase: DragPhase,
935        location: Point,
936    },
937    ScrollChanged(Point),
938    /// A canvas node was re-framed by layout; re-record (§11). Nav pane/page containers
939    /// also report their allocated size with this (docs/navigation.md).
940    FrameChanged(Size),
941    /// Native back navigation (iOS back button/swipe, Android system back or toolbar up).
942    /// `already_popped` = the toolkit already performed the pop natively (iOS); the nav
943    /// host then syncs its stack without re-issuing `NavPatch::Popped`.
944    NavBack {
945        already_popped: bool,
946    },
947    /// A nav host's own adaptive container changed presentation, and Day is being told about it
948    /// after the fact (docs/size-classes.md).
949    ///
950    /// The counterpart to [`props::NavPatch::Presentation`], for the toolkits that answer
951    /// `Cap::NavRepresent = Emulated`: `UISplitViewController` collapsing as a Pro Max iPhone
952    /// rotates into portrait, `SlidingPaneLayout` deciding at measure time that two panes no
953    /// longer fit. Day did not ask for it and must not fight it; the pieces layer only
954    /// reconciles what follows, which is the selection rule (a split presentation cannot draw an
955    /// empty detail pane, so expanding with nothing selected picks the first item).
956    ///
957    /// Emitted on the NAV host node, and only when the presentation actually changed.
958    NavPresentationChanged(props::NavPresentation),
959    Key(KeyEvent),
960    Pointer(PointerEvent),
961    WindowResized(Size),
962    /// The platform asks the app to show a route (docs/navigation.md), a runtime deep link:
963    /// on web-dom, the URL hash changing under the app (hand-edited, or browser back/forward);
964    /// on mobile, a warm scheme link (iOS `application:openURL:`, Android `onNewIntent` via
965    /// `BridgeKind::Deeplink`). Emitted on [`WINDOW_NODE`] (day-core answers with `navigate()`
966    /// when the route differs from the current one) or on the active nav host's node (the nav
967    /// piece answers with `navigate()` itself, docs/deep-links.md). Launch-time deep links use
968    /// `DAY_DEEPLINK`/`set_launch_deeplink` instead; this variant is for changes while the
969    /// app runs.
970    RouteRequested(String),
971    /// A native modal answered request `req` (docs/dialogs.md).
972    PresentResult {
973        req: u64,
974        result: present::PresentResult,
975    },
976    /// A decode started by [`Toolkit::decode_image`] finished (docs/images.md).
977    ///
978    /// Keyed by request id like [`Event::PresentResult`], and for the same reason: the answer
979    /// belongs to a waiting caller, not to a tree node. It never crosses a native boundary
980    /// (every backend raises it from its own Rust arm once the platform decoder answers), so it
981    /// has no [`bridge::BridgeKind`], exactly like the completion events dialogs use in-process.
982    ///
983    /// No bitmap id rides here: day-core minted it and handed it to the backend with the bytes,
984    /// so it already knows which image a request answers for. A backend that stored the image
985    /// under that id has nothing more to say than the facts it read.
986    ImageDecoded {
987        req: u64,
988        result: Result<BitmapInfo, ImageError>,
989    },
990    /// An encode started by [`Toolkit::encode_image`] finished (docs/images.md): the encoded
991    /// bytes, or why they could not be produced.
992    ImageEncoded {
993        req: u64,
994        result: Result<Vec<u8>, ImageError>,
995    },
996    /// A canvas drawing started by [`Toolkit::render_bitmap`] finished rendering
997    /// (docs/canvas.md "Exporting"). Keyed by request id like [`Event::ImageDecoded`], and like
998    /// it carries no bitmap id: day-core minted the id and handed it over with the ops, so the
999    /// answer is only the facts of the image the backend stored under it.
1000    BitmapRendered {
1001        req: u64,
1002        result: Result<BitmapInfo, ExportError>,
1003    },
1004    /// A PDF started by [`Toolkit::render_pdf`] finished (docs/canvas.md "Exporting"): the
1005    /// document's bytes, or why they could not be produced.
1006    PdfRendered {
1007        req: u64,
1008        result: Result<Vec<u8>, ExportError>,
1009    },
1010    /// An open, piece-defined event (§8.2). `tag` names the event for in-process emitters (a static
1011    /// literal); it is empty for events that cross a native boundary (JNI/C-ABI), which carry only the
1012    /// primitive `num`/`text` payload. A piece's `cx.on` reads whichever fields it needs. This is the
1013    /// escape hatch for events the fixed variants above don't cover (a web view's URL, a picked date, …).
1014    Custom {
1015        tag: &'static str,
1016        num: f64,
1017        text: String,
1018    },
1019    /// A menu item (app menu or context menu) with this action id was activated (§ menus). day-core
1020    /// routes it to the app closure registered for the id. Standard-role items don't carry an id
1021    /// (`role` items are handled natively) so they never emit this.
1022    MenuAction(u64),
1023    /// A toolbar item produced a value: a search field's text, a toggle's new state
1024    /// (docs/toolbars.md). `action` is the item's dispatch id, from the same registry
1025    /// [`Event::MenuAction`] uses, and day-core routes it to the closure registered for it.
1026    /// A plain toolbar button has no value and emits `MenuAction` instead.
1027    ToolbarChanged {
1028        action: u64,
1029        value: ToolbarValue,
1030    },
1031    /// A searchable navigation surface's field changed (docs/search.md). Emitted against the nav
1032    /// host's node, not through the toolbar's dispatch registry: search belongs to the surface,
1033    /// so the field can move between the toolbar and the navigation list without the app
1034    /// re-registering anything.
1035    SearchChanged(String),
1036    /// The user picked a different scope. Carries the index into `SearchProps::scopes`.
1037    SearchScopeChanged(usize),
1038    /// The user chose one of `SearchProps::suggestions`, by index. The toolkit has already put
1039    /// that completion in the field and emitted [`Event::SearchChanged`] for it; this says which
1040    /// one, for an app that wants to act on the choice itself.
1041    SearchSuggestionChosen(usize),
1042    /// The user submitted the inline field's text with its Return or Search key. Emitted
1043    /// after the last [`Event::SearchChanged`], with the text as submitted, for a search that
1044    /// runs on demand (a server query) rather than narrowing as the text changes.
1045    SearchSubmitted(String),
1046    /// The app moved through a lifecycle phase (docs/lifecycle.md). Backends emit this from the
1047    /// native app/activity delegate; day-core routes it to the app's `on_lifecycle` handlers.
1048    Lifecycle(Lifecycle),
1049    /// A secondary native window closed (the title-bar close, a platform gesture such as an
1050    /// app-switcher swipe or an activity finish, or `Toolkit::close_window`); emitted on the
1051    /// window's root node after the platform committed the close. day-core disposes the
1052    /// window's subtree on receipt, so native and programmatic closes share one teardown
1053    /// path (docs/windows.md). Never emitted for the primary window (its close terminates
1054    /// the app).
1055    WindowClosed,
1056    /// A secondary window's key/active state changed; emitted on the window's root node.
1057    /// day-core tracks the focused window with it (dialog parenting, dayscript targeting).
1058    WindowFocused(bool),
1059    /// A window's display state changed (docs/windows.md): the user minimized, zoomed or took it
1060    /// fullscreen, or a [`WindowChange::State`] request landed. Emitted on the window's root node
1061    /// (the primary's may arrive on [`WINDOW_NODE`]); day-core feeds the window's `state()`
1062    /// signal with it, so the app reads what the platform did rather than what it asked for.
1063    WindowStateChanged(WindowState),
1064    /// A native list committed a drag-reorder (docs/list.md): row `from` landed at row `to`.
1065    /// Emitted on the `LIST` node by the list piece's commit hook: the reorder driver
1066    /// rotates its snapshot synchronously inside the platform's drop callback, then reports
1067    /// through the event queue so the app's `on_reorder` never runs inside a native animation
1068    /// callstack.
1069    ListReorder {
1070        from: usize,
1071        to: usize,
1072    },
1073    /// A regrouping sidebar committed a drop (`props::NavMenuProps::regroup`, docs/navigation.md
1074    /// "Moving rows between sections"), in item indices into the rows as they were before the
1075    /// move: row `from` now sits in the section whose first row is item `section` (item 0 for
1076    /// rows above the first header), before item `before`, or at that section's end for
1077    /// `None`. `before` is never `from`. Emitted on the `NAV_MENU` node by a toolkit whose
1078    /// `Cap::NavReorder` is `Native`, deferred through the event queue exactly as
1079    /// [`Event::ListReorder`] is; the nav validates it against the app's rules before reporting.
1080    NavRegroup {
1081        from: usize,
1082        section: usize,
1083        before: Option<usize>,
1084    },
1085    /// A native list committed a swipe-delete (docs/list.md): the row at this index is gone.
1086    /// Deferred through the event queue exactly as [`Event::ListReorder`] is.
1087    ListDelete(usize),
1088    /// The native pull-to-refresh control requested an update. The app owns its busy state.
1089    RefreshRequested,
1090    /// A native list activated a swipe action (docs/list.md): the user pressed button `action`
1091    /// (an index into the row's [`ListSwipe::actions_at`] offer for `edge`) on row `index`, or
1092    /// swiped clear across for the edge's first action. Emitted on the `LIST` node by the list
1093    /// piece's commit hook and deferred through the event queue exactly as
1094    /// [`Event::ListReorder`] is, so the app's handler never runs inside a native animation
1095    /// callstack.
1096    ListSwipe {
1097        index: usize,
1098        edge: SwipeEdge,
1099        action: usize,
1100    },
1101    /// A fullscreen cover's hide transition finished (docs/cover.md): the content can now be
1102    /// disposed. Answers [`props::CoverPatch::Dismiss`]; delivery is a hard guarantee, and
1103    /// backends over-report rather than under-report; consumers gate on their own closing
1104    /// flag, so duplicates and belated reports are no-ops.
1105    CoverHidden,
1106    /// The user showed or hid an inspector pane through a native affordance (a dock widget's
1107    /// close button, a divider dragged shut) rather than through Day (docs/inspector.md).
1108    /// Emitted on the `kinds::INSPECTOR` node, and only when the visibility actually changed;
1109    /// the piece writes it back to the bound signal. Applying
1110    /// [`props::InspectorPatch::Visible`] must never re-emit it (the from-native echo rule).
1111    InspectorChanged(bool),
1112    /// The user disclosed or collapsed a tree row through the native affordance (docs/tree.md).
1113    /// Emitted on the `kinds::TREE` node; the piece writes it back to the app's expansion
1114    /// signal. Applying [`props::TreePatch::Expand`] must never re-emit it (the from-native
1115    /// echo rule).
1116    TreeExpanded {
1117        token: u64,
1118        expanded: bool,
1119    },
1120    /// A native tree committed a drag move (docs/tree.md): `token` now sits under `parent`
1121    /// (`None` = the root) at `index` (`None` = dropped onto the parent, an append). Deferred
1122    /// through the event queue exactly as [`Event::ListReorder`] is; the app's `on_move`
1123    /// writes its own data, whose refresh reloads the tree.
1124    TreeMove {
1125        token: u64,
1126        parent: Option<u64>,
1127        index: Option<usize>,
1128    },
1129    /// A tree's selection changed: the full set of selected row tokens (empty = cleared).
1130    /// Token-addressed, since a tree cannot speak row indices: expanding a row renumbers
1131    /// everything below it (docs/tree.md).
1132    TreeSelection(Vec<u64>),
1133}
1134
1135impl Event {
1136    /// Build a text-carrying [`Event::Custom`] (with `num` defaulted to 0), the common case for an
1137    /// in-process piece reporting a value back: `emit(node, Event::custom("webview:url", url))`.
1138    pub fn custom(tag: &'static str, text: impl Into<String>) -> Event {
1139        Event::Custom {
1140            tag,
1141            num: 0.0,
1142            text: text.into(),
1143        }
1144    }
1145}
1146
1147/// An app-lifecycle phase (docs/lifecycle.md). Each backend maps these onto its OS's native app /
1148/// activity delegate. Some phases only exist on some platforms (a mobile app enters the
1149/// background and can be low on memory, a desktop app cannot), so [`Lifecycle::is_universal`]
1150/// marks the ones every backend delivers, and [`Toolkit::supports_lifecycle`] reports per-backend
1151/// truth.
1152///
1153/// Rough native mapping:
1154///
1155/// | phase | AppKit | UIKit | GTK | Qt | Android | XAML |
1156/// |---|---|---|---|---|---|---|
1157/// | `WillLaunch` / `DidLaunch` | `applicationWill/DidFinishLaunching` | same | `startup`/mount | mount | `onCreate` | window create |
1158/// | `DidBecomeActive` | `didBecomeActive` | `didBecomeActive` | `notify::is-active` | `ApplicationActive` | `onResume` | `Activated` |
1159/// | `WillResignActive` | `willResignActive` | `willResignActive` | `notify::is-active` | `ApplicationInactive` | `onPause` | `Deactivated` |
1160/// | `WillEnterForeground` | — | `willEnterForeground` | — | — | `onStart` | — |
1161/// | `DidEnterBackground` | — | `didEnterBackground` | — | — | `onStop` | — |
1162/// | `DidReceiveMemoryWarning` | — | `didReceiveMemoryWarning` | — | — | `onTrimMemory` | — |
1163/// | `WillTerminate` | `willTerminate` | `willTerminate` | `shutdown` | `aboutToQuit` | `onDestroy` | window close |
1164/// | `DidExit` | after `willTerminate` | after `willTerminate` | `run` returned | `exec` returned | after `onDestroy` | loop returned |
1165#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1166pub enum Lifecycle {
1167    /// Before the window and UI are built: the first thing to run. Set up global state here.
1168    WillLaunch,
1169    /// The UI is mounted and the app is about to start running. Kick off startup work here.
1170    DidLaunch,
1171    /// The app came to the foreground and is the active, focused app receiving input.
1172    DidBecomeActive,
1173    /// The app is about to stop being active (an interruption, app switch, or losing focus).
1174    WillResignActive,
1175    /// The app is about to return to the foreground (mobile). Refresh what background invalidated.
1176    WillEnterForeground,
1177    /// The app left the foreground and is no longer visible (mobile). Persist state, release UI work.
1178    DidEnterBackground,
1179    /// The system is low on memory (mobile). Drop caches and non-essential memory now.
1180    DidReceiveMemoryWarning,
1181    /// The app is about to terminate: the last chance to save. Triggered by the Quit command,
1182    /// the platform's quit shortcut, or the OS reclaiming the app.
1183    WillTerminate,
1184    /// The run loop is over and nothing of the app will run after this: the last phase, after
1185    /// every `WillTerminate` handler. Day logs its exit line ("Clean exit for …") once the
1186    /// handlers have run, so a handler here is the app's last word before it.
1187    DidExit,
1188}
1189
1190impl Lifecycle {
1191    /// Every phase, in delivery order (launch → run → quit). Handy for logging/registration sweeps.
1192    pub const ALL: [Lifecycle; 9] = [
1193        Lifecycle::WillLaunch,
1194        Lifecycle::DidLaunch,
1195        Lifecycle::DidBecomeActive,
1196        Lifecycle::WillResignActive,
1197        Lifecycle::WillEnterForeground,
1198        Lifecycle::DidEnterBackground,
1199        Lifecycle::DidReceiveMemoryWarning,
1200        Lifecycle::WillTerminate,
1201        Lifecycle::DidExit,
1202    ];
1203
1204    /// True for phases every backend delivers (launch, activation, termination). The remaining
1205    /// phases (`WillEnterForeground`, `DidEnterBackground`, `DidReceiveMemoryWarning`) are mobile
1206    /// concepts and are only delivered by the mobile backends. `const` so it composes into a
1207    /// backend's `const fn lifecycle_supported` and thus into compile-time guards.
1208    pub const fn is_universal(self) -> bool {
1209        matches!(
1210            self,
1211            Lifecycle::WillLaunch
1212                | Lifecycle::DidLaunch
1213                | Lifecycle::DidBecomeActive
1214                | Lifecycle::WillResignActive
1215                | Lifecycle::WillTerminate
1216                | Lifecycle::DidExit
1217        )
1218    }
1219
1220    /// A stable, human-readable name (for logs/warnings).
1221    pub const fn name(self) -> &'static str {
1222        match self {
1223            Lifecycle::WillLaunch => "WillLaunch",
1224            Lifecycle::DidLaunch => "DidLaunch",
1225            Lifecycle::DidBecomeActive => "DidBecomeActive",
1226            Lifecycle::WillResignActive => "WillResignActive",
1227            Lifecycle::WillEnterForeground => "WillEnterForeground",
1228            Lifecycle::DidEnterBackground => "DidEnterBackground",
1229            Lifecycle::DidReceiveMemoryWarning => "DidReceiveMemoryWarning",
1230            Lifecycle::WillTerminate => "WillTerminate",
1231            Lifecycle::DidExit => "DidExit",
1232        }
1233    }
1234}
1235
1236/// The phase of a drag gesture (docs/shapes.md).
1237#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1238pub enum DragPhase {
1239    Began,
1240    Changed,
1241    Ended,
1242}
1243
1244/// A gesture a node wants delivered. Backends attach the matching native recognizer when day-core
1245/// calls [`Toolkit::enable_gesture`]; the default is no gesture (recognizers cost, so opt-in).
1246#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1247pub enum GestureKind {
1248    Tap,
1249    LongPress,
1250    Drag,
1251    /// The pointer moving over the node without pressing (docs/canvas.md "Interaction"), and
1252    /// leaving it. Delivered only where a pointer exists: every desktop, an iPad with a trackpad
1253    /// or pencil, an Android device with a mouse or stylus. A touch-only device reports none,
1254    /// which is the right answer, not a gap, so anything reachable by hover must also be
1255    /// reachable by a tap.
1256    Hover,
1257    /// Pinch/magnify (docs/shapes.md): trackpad magnification, two-finger touch pinch.
1258    Pinch,
1259    /// Rotation (docs/canvas.md "Zoom and pan"): trackpad rotate, two-finger touch twist.
1260    Rotate,
1261    /// Viewport pan (docs/shapes.md): trackpad two-finger scroll, two-finger touch pan.
1262    /// Distinct from [`GestureKind::Drag`], the primary pointer's press-drag.
1263    Pan,
1264}
1265
1266// ---------------------------------------------------------------------------
1267// Menus (app menu bar + context menus). The model is a toolkit-neutral tree; each backend renders
1268// it with its native affordance (NSMenu / GMenu+GtkPopoverMenu / QMenu / UIMenu / Android
1269// PopupMenu / XAML MenuFlyout) and its own conventions, so day imposes no menu manager of its own.
1270// ---------------------------------------------------------------------------
1271
1272/// A keyboard shortcut for a menu item. `primary` is the platform's command modifier (⌘ on Apple,
1273/// Ctrl on GTK/Qt/XAML) so one declaration reads correctly everywhere. `key` is a single character
1274/// (`"s"`, `"."`) or a named key (`"Return"`, `"Delete"`, `"Left"`, `"F1"`).
1275#[derive(Clone, Debug, PartialEq, Eq, Default)]
1276pub struct Shortcut {
1277    pub key: String,
1278    /// ⌘ (Apple) / Ctrl (elsewhere). The conventional command modifier.
1279    pub primary: bool,
1280    pub shift: bool,
1281    /// ⌥ / Alt.
1282    pub alt: bool,
1283    /// Literal Control (⌃ on Apple). Rare; prefer `primary` for the command modifier.
1284    pub control: bool,
1285}
1286
1287impl Shortcut {
1288    /// `primary`+`key` (⌘S / Ctrl+S), the common case: `Shortcut::primary("s").shift()`.
1289    pub fn primary(key: impl Into<String>) -> Shortcut {
1290        Shortcut {
1291            key: key.into(),
1292            primary: true,
1293            ..Default::default()
1294        }
1295    }
1296    /// `key` with no modifiers (e.g. `F1`, plain `Delete`).
1297    pub fn plain(key: impl Into<String>) -> Shortcut {
1298        Shortcut {
1299            key: key.into(),
1300            ..Default::default()
1301        }
1302    }
1303    pub fn shift(mut self) -> Shortcut {
1304        self.shift = true;
1305        self
1306    }
1307    pub fn alt(mut self) -> Shortcut {
1308        self.alt = true;
1309        self
1310    }
1311    pub fn control(mut self) -> Shortcut {
1312        self.control = true;
1313        self
1314    }
1315}
1316
1317/// A standard/system command. The backend supplies the native item, a selector on AppKit/UIKit
1318/// (`cut:`/`copy:`/`paste:`…) or a stock action on GTK/Qt/XAML, so it targets the focused
1319/// control, gets the platform's default label + shortcut, and enables/disables itself
1320/// automatically. This is how default items (Edit ▸ Cut/Copy/Paste, the app's Quit/About) are
1321/// accommodated without the app re-implementing them.
1322#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1323pub enum MenuRole {
1324    Cut,
1325    Copy,
1326    Paste,
1327    SelectAll,
1328    Undo,
1329    Redo,
1330    Delete,
1331    /// The app's About command (docs/settings.md). With an About registered through
1332    /// `day::register_about` the item lowers to that dispatch action (a Day-rendered About
1333    /// window, or the toolkit's own About dialog where one exists); without one AppKit shows
1334    /// its stock Info.plist panel and the other desktops show the label alone.
1335    About,
1336    Quit,
1337    Preferences,
1338    Minimize,
1339    CloseWindow,
1340    Fullscreen,
1341    /// File ▸ New Window (docs/windows.md): opens another window through the builder the
1342    /// app registered with `day::register_new_window`. No platform has a native selector
1343    /// for it, so the item lowers to the registered dispatch action (disabled when none).
1344    NewWindow,
1345    /// Check for Updates… (docs/settings.md): placed directly under About in the macOS App
1346    /// menu (the Sparkle convention) and in Help elsewhere. Lowers to the action an updater
1347    /// registered with `day::register_check_for_updates`; absent from the bar when none did.
1348    CheckForUpdates,
1349}
1350
1351/// The keyboard modifiers held at an interaction, queryable ambiently
1352/// ([`Toolkit::modifiers`]): `primary` is the platform's command key (⌘ on Apple platforms,
1353/// Ctrl elsewhere, the same convention [`Shortcut::primary`] uses). Touch-only backends
1354/// answer all-false.
1355#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1356pub struct Modifiers {
1357    pub shift: bool,
1358    pub primary: bool,
1359    pub alt: bool,
1360}
1361
1362/// A standard edit command a platform route delivered ([`Event::Edit`]).
1363#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1364pub enum EditOp {
1365    Cut,
1366    Copy,
1367    Paste,
1368    SelectAll,
1369}
1370
1371/// What the app's edit bridge can currently do, mirrored into the toolkit
1372/// ([`Toolkit::set_edit_state`]) so native menu validation enables the stock items.
1373/// `can_paste` is the app's half ("a paste handler is installed"); the toolkit combines it
1374/// with its own clipboard-has-text check where one exists.
1375#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1376pub struct EditState {
1377    pub can_cut: bool,
1378    pub can_copy: bool,
1379    pub can_paste: bool,
1380    pub can_select_all: bool,
1381}
1382
1383/// The undo stack's face, as a native front mirrors it ([`Toolkit::set_undo_state`]): what is
1384/// possible and what the menu titles should say. Labels arrive already localized: a toolkit
1385/// cannot invent translated text, the same rule as every other label in this file.
1386#[derive(Clone, Debug, PartialEq, Default)]
1387pub struct UndoState {
1388    pub can_undo: bool,
1389    pub can_redo: bool,
1390    /// The next undo unit's display label ("Rename"), empty when nothing is undoable. Fronts
1391    /// interpolate it into the platform's own title form ("Undo Rename").
1392    pub undo_label: String,
1393    pub redo_label: String,
1394}
1395
1396/// One entry in a menu (recursive: a `Submenu` nests).
1397#[derive(Clone, Debug, PartialEq)]
1398pub enum MenuItem {
1399    /// A command. `action` (nonzero) dispatches [`Event::MenuAction`] to the app; a `role`-only item
1400    /// uses the native standard command instead (action 0). `label`/`shortcut` override the role's
1401    /// defaults. `icon` is the platform's own glyph beside the title where menus carry one (macOS,
1402    /// Windows, GNOME, KDE, Android); a backend whose menus are text-only ignores it.
1403    ///
1404    /// The `id`/`action` split is [`ToolbarItem`]'s: `id` names the item and `action` is what it
1405    /// runs. They are separate because a label cannot serve as a name (it is localized, and an
1406    /// item that shows its own state changes it), so anything addressing an item from outside
1407    /// (dayscript's `menu: { id: … }`) needs something that does not move.
1408    Action {
1409        /// The app's own name for this item, where it gave one. Stable across locales and across
1410        /// a change of `checked`, and unique within the menu it is installed in.
1411        id: Option<String>,
1412        /// The item's command, as a dispatch id from the same registry [`Event::MenuAction`] uses
1413        /// (0 = no command), so a toolbar button and its menu twin can share one closure.
1414        action: u64,
1415        label: String,
1416        shortcut: Option<Shortcut>,
1417        enabled: bool,
1418        /// On/off state where the item stands for a setting or one of several choices, drawn with
1419        /// the platform's own check mark. `None` is a plain command and reserves no mark; `Some`
1420        /// makes the item checkable and says which way it currently sits.
1421        ///
1422        /// The item still runs its `action` when chosen; a backend never flips this on its own.
1423        /// The app owns the state, and re-installing the menu (`app_menu`, which re-lowers on change) is what moves
1424        /// the mark, so what the menu shows can never disagree with what the app thinks.
1425        checked: Option<bool>,
1426        role: Option<MenuRole>,
1427        icon: Option<Icon>,
1428    },
1429    /// A nested submenu. At the top level of an app menu a `role` claims one of the platform's
1430    /// standard menu-bar slots: the backend then uses this menu instead of its stock one, and
1431    /// places it where the platform expects that menu to sit.
1432    Submenu {
1433        label: String,
1434        items: Vec<MenuItem>,
1435        role: Option<MenuBarRole>,
1436    },
1437    /// A visual separator.
1438    Separator,
1439}
1440
1441/// A standard menu-bar slot (macOS's File/Edit/View/Window/Help, and their counterparts
1442/// elsewhere). A backend that has a house style for the menu bar fills every slot an app did
1443/// not claim with its own stock menu, so an app never has to restate the platform's furniture,
1444/// and can still replace any of it by tagging its own submenu with the matching role.
1445#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1446#[non_exhaustive]
1447pub enum MenuBarRole {
1448    File,
1449    Edit,
1450    View,
1451    /// KDE/Plasma's Settings menu (`Configure <App>`, Configure Shortcuts). No counterpart on
1452    /// macOS, where preferences live in the app menu, or on GNOME/Windows.
1453    Settings,
1454    /// macOS's Window menu. Windows and Linux desktops do not have one.
1455    Window,
1456    Help,
1457}
1458
1459// ---------------------------------------------------------------------------
1460// Window toolbars (docs/toolbars.md)
1461// ---------------------------------------------------------------------------
1462
1463/// A standard icon, named by what it means rather than by how it looks, so each backend can
1464/// draw the platform's own glyph for it: an SF Symbol on macOS, a freedesktop icon name on
1465/// GTK and Qt, a Fluent glyph on Windows. This is the only way an icon looks native on every
1466/// desktop at once; a bundled PNG cannot, because it is one artist's take on all four.
1467///
1468/// The set is kept small: the commands that recur across toolbars. Anything
1469/// app-specific is an [`Icon::Image`].
1470#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1471#[non_exhaustive]
1472pub enum Symbol {
1473    Add,
1474    Remove,
1475    Delete,
1476    Edit,
1477    New,
1478    Open,
1479    Save,
1480    Print,
1481    Refresh,
1482    Search,
1483    Share,
1484    Settings,
1485    Info,
1486    Star,
1487    Bookmark,
1488    Back,
1489    Forward,
1490    Up,
1491    Down,
1492    Home,
1493    /// Show/hide the sidebar, the leading item of most desktop toolbars.
1494    Sidebar,
1495    Filter,
1496    Sort,
1497    /// An overflow affordance (macOS `ellipsis`, Android's vertical `more_vert`, GNOME's hamburger,
1498    /// Fluent `More`).
1499    More,
1500    Play,
1501    Pause,
1502    Stop,
1503    /// A photo capture: a screenshot command, a camera control.
1504    Camera,
1505    /// Source code.
1506    Code,
1507    /// Light appearance (a sun). The three below are the vocabulary of a theme chooser, which
1508    /// every platform draws with the same three ideas.
1509    Light,
1510    /// Dark appearance (a moon).
1511    Dark,
1512    /// Follow the system: the half-filled circle every platform uses for "automatic".
1513    Auto,
1514    ZoomIn,
1515    ZoomOut,
1516    /// Back to actual size: the 100% zoom command between [`Symbol::ZoomIn`] and
1517    /// [`Symbol::ZoomOut`].
1518    ZoomReset,
1519    Undo,
1520    Redo,
1521    Copy,
1522    Cut,
1523    Paste,
1524    Mail,
1525    Folder,
1526    Document,
1527    Check,
1528    Close,
1529    Warning,
1530    /// A rectangle: the shape vocabulary a drawing surface needs (docs/shapes.md), and the
1531    /// glyphs every drawing, diagram and annotation tool puts in the same place.
1532    Rectangle,
1533    /// An ellipse.
1534    Oval,
1535    /// An outlined circle: the read/unread vocabulary (a read row, its dot removed), and the
1536    /// generic ring glyph.
1537    Circle,
1538    /// A filled circle: the unread dot itself.
1539    CircleFilled,
1540    /// A straight line segment.
1541    Line,
1542    /// Combine the selection into a group: the drawing-tool command (two stacked squares).
1543    Group,
1544    /// Dissolve a group back into its members (two separated squares).
1545    Ungroup,
1546    /// Text: a line of type as a drawing element (the drawing-tool "T").
1547    Text,
1548    /// The device's own position: a map's "show my location" button (Apple's arrow, the
1549    /// crosshair elsewhere).
1550    Location,
1551    /// The open tabs or windows: a browser's tab switcher (two overlapping squares).
1552    Tabs,
1553    /// A book: a library of bookmarks or saved reading (Safari's bookmarks button).
1554    Book,
1555    /// Past activity: a history list (a clock with a turning arrow).
1556    History,
1557}
1558
1559/// The SF Symbol each standard symbol draws as. The system's own glyphs match the user's
1560/// device: weight, optical size, accent color and all. Shared by both Apple backends
1561/// (toolbars on macOS, menus on both).
1562///
1563/// The match is exhaustive so that a new [`Symbol`] must name its glyph here rather than
1564/// silently drawing nothing on Apple. A name this OS release does not know still resolves to
1565/// no image, and the item falls back to its label.
1566pub fn sf_symbol_name(s: Symbol) -> &'static str {
1567    match s {
1568        Symbol::Add => "plus",
1569        Symbol::Remove => "minus",
1570        Symbol::Delete => "trash",
1571        Symbol::Edit => "pencil",
1572        Symbol::New => "square.and.pencil",
1573        Symbol::Open => "folder",
1574        Symbol::Save => "square.and.arrow.down",
1575        Symbol::Print => "printer",
1576        Symbol::Refresh => "arrow.clockwise",
1577        Symbol::Search => "magnifyingglass",
1578        Symbol::Share => "square.and.arrow.up",
1579        Symbol::Settings => "gearshape",
1580        Symbol::Info => "info.circle",
1581        Symbol::Star => "star",
1582        Symbol::Bookmark => "bookmark",
1583        Symbol::Back => "chevron.backward",
1584        Symbol::Forward => "chevron.forward",
1585        Symbol::Up => "chevron.up",
1586        Symbol::Down => "chevron.down",
1587        Symbol::Home => "house",
1588        Symbol::Sidebar => "sidebar.leading",
1589        Symbol::Filter => "line.3.horizontal.decrease",
1590        Symbol::Sort => "arrow.up.arrow.down",
1591        Symbol::More => "ellipsis",
1592        Symbol::Play => "play.fill",
1593        Symbol::Pause => "pause.fill",
1594        Symbol::Stop => "stop.fill",
1595        Symbol::Camera => "camera",
1596        Symbol::Code => "chevron.left.forwardslash.chevron.right",
1597        Symbol::Light => "sun.max",
1598        Symbol::Dark => "moon",
1599        Symbol::Auto => "circle.lefthalf.filled",
1600        Symbol::ZoomIn => "plus.magnifyingglass",
1601        Symbol::ZoomReset => "1.magnifyingglass",
1602        Symbol::ZoomOut => "minus.magnifyingglass",
1603        Symbol::Undo => "arrow.uturn.backward",
1604        Symbol::Redo => "arrow.uturn.forward",
1605        Symbol::Copy => "doc.on.doc",
1606        Symbol::Cut => "scissors",
1607        Symbol::Paste => "doc.on.clipboard",
1608        Symbol::Mail => "envelope",
1609        Symbol::Folder => "folder",
1610        Symbol::Document => "doc",
1611        Symbol::Check => "checkmark",
1612        Symbol::Close => "xmark",
1613        Symbol::Warning => "exclamationmark.triangle",
1614        Symbol::Rectangle => "rectangle",
1615        Symbol::Oval => "oval",
1616        Symbol::Circle => "circle",
1617        Symbol::CircleFilled => "circle.fill",
1618        Symbol::Line => "line.diagonal",
1619        Symbol::Group => "square.on.square",
1620        Symbol::Ungroup => "square.on.square.dashed",
1621        Symbol::Text => "textformat",
1622        Symbol::Location => "location",
1623        Symbol::Tabs => "square.on.square",
1624        Symbol::Book => "book",
1625        Symbol::History => "clock.arrow.circlepath",
1626    }
1627}
1628
1629/// A button or toolbar item's picture: a standard [`Symbol`] (drawn with the platform's own icon set) or
1630/// a bundled image from `resource/images` for something only this app has.
1631#[derive(Clone, Debug, PartialEq)]
1632pub enum Icon {
1633    Symbol(Symbol),
1634    /// A bundled image name, resolved the same way [`ImageName`] is elsewhere.
1635    Image(String),
1636}
1637
1638/// What a toolbar item is. The variants are the vocabulary every desktop toolbar shares; each
1639/// backend realizes one with its native control, never with a drawn imitation.
1640#[derive(Clone, Debug, PartialEq)]
1641pub enum ToolbarItemKind {
1642    /// A push button running the item's `action`.
1643    Button,
1644    /// A two-state button. `on` seeds it; the user flipping it emits
1645    /// [`ToolbarValue::On`], and the app's own writes arrive as [`ToolbarPatch::On`].
1646    Toggle { on: bool },
1647    /// A button that drops a menu: the same [`MenuItem`] model the menu bar uses, so a
1648    /// toolbar menu and its menu-bar twin are one list of commands.
1649    Menu { items: Vec<MenuItem> },
1650    /// A search field. Edits emit [`ToolbarValue::Text`]; the app's own writes arrive as
1651    /// [`ToolbarPatch::Text`].
1652    ///
1653    /// Day creates this item itself, from a `.searchable()` surface whose placement resolved to
1654    /// the toolbar (docs/search.md); apps declare search on the surface, never here.
1655    Search {
1656        text: String,
1657        placeholder: String,
1658        /// Completions for the current text, drawn by the field's own completion affordance
1659        /// where it has one (`AutoSuggestBox`, `QCompleter`, `<datalist>`). Empty = none.
1660        suggestions: Vec<String>,
1661    },
1662    /// A row of mutually exclusive choices drawn as one control: the native segmented control
1663    /// (`NSSegmentedControl`, a linked GTK/Qt button box, a XAML toggle strip, `.day-segmented`
1664    /// on the web).
1665    ///
1666    /// This is what a set of related toolbar toggles should be when exactly one of them is on at
1667    /// a time: three separate toggles say "three independent switches" to the eye and to a screen
1668    /// reader, and leave the app to keep them exclusive. Choosing a segment emits
1669    /// [`ToolbarValue::Selected`]; the app's own writes arrive as [`ToolbarPatch::Selected`].
1670    Segmented {
1671        /// One entry per segment. A segment with an icon draws it in place of its title where
1672        /// the platform does that, and keeps the title as its accessible name.
1673        segments: Vec<ToolbarSegment>,
1674        selected: usize,
1675    },
1676    /// Static text, for a status or a caption.
1677    Label,
1678    /// A divider between neighbors in the same placement bucket, where the platform draws one
1679    /// (macOS toolbars have no separator, so AppKit renders it as a fixed space,
1680    /// docs/toolbars.md). Grouping is all it does: alignment is [`ToolbarPlacement`]'s job.
1681    Separator,
1682}
1683
1684/// One choice inside a [`ToolbarItemKind::Segmented`] control.
1685#[derive(Clone, Debug, PartialEq)]
1686pub struct ToolbarSegment {
1687    /// The segment's name: its label where the platform shows text, its accessible name always.
1688    pub title: String,
1689    pub icon: Option<Icon>,
1690}
1691
1692/// The reserved id of the sidebar affordance a `nav(Sidebar)` supplies for itself
1693/// (docs/toolbars.md). Backends with a system item for the job (AppKit's
1694/// `NSToolbarToggleSidebarItem`) recognize it by this id and draw theirs instead; dayscript
1695/// recognizes it to drive the toolkit's own duty rather than an app closure.
1696pub const SIDEBAR_TOGGLE_ID: &str = "day::sidebar_toggle";
1697
1698/// The reserved id of a `.searchable()` surface's field (docs/search.md): the `ToolbarItem` a
1699/// desktop bar draws for it, and the name dayscript's `toolbar:` step drives it by wherever the
1700/// platform put it — on the bar, or inline on the navigation surface where the bar holds no
1701/// field, in which case day-core resolves the id to that host instead.
1702pub const SEARCH_ITEM_ID: &str = "day::search";
1703
1704/// One item in a window's toolbar (docs/toolbars.md).
1705#[derive(Clone, Debug, PartialEq)]
1706pub struct ToolbarItem {
1707    /// Stable identity: the native item identifier, the dayscript target, and the key a
1708    /// [`ToolbarPatch`] addresses. Unique within a toolbar.
1709    pub id: String,
1710    pub kind: ToolbarItemKind,
1711    /// The item's name. Shown beside or below the icon where the platform does that, and used
1712    /// verbatim in the overflow and customization menus, so it is never optional, even on a
1713    /// toolbar that only shows icons. It is also the item's accessible name.
1714    pub label: String,
1715    /// Hover help. Defaults to `label` where the platform expects a tooltip and none is given.
1716    pub tooltip: Option<String>,
1717    pub icon: Option<Icon>,
1718    pub enabled: bool,
1719    /// The item's command, as a dispatch id from the same registry [`Event::MenuAction`] uses
1720    /// (0 = no command), so a toolbar button and its menu twin can share one closure.
1721    pub action: u64,
1722    /// This item's role on the chrome carrying it (docs/toolbars.md). It never names a surface:
1723    /// Which chrome an item rides is decided by where the app declared it, so this says only
1724    /// where on that chrome it belongs.
1725    pub placement: ToolbarPlacement,
1726    /// Whether the item draws its title, its icon, or both, where the platform can do more than
1727    /// one. An item folded into an overflow menu shows its title whatever this asks for; a menu
1728    /// row with no words is not a menu row.
1729    pub label_style: LabelStyle,
1730    /// Draw this item in the platform's emphasized style (a tinted/filled bar button, a
1731    /// prominent `NSToolbarItem`). For the one action a chrome is really offering.
1732    pub prominent: bool,
1733    /// Which column of a multi-pane window this item came from (docs/toolbars.md), set by Day
1734    /// from the piece that declared it, never by an app.
1735    ///
1736    /// A desktop toolbar spans every column at once, and a three-pane app expects each column's
1737    /// commands to sit over that column: the sidebar's against the first divider, the list's over
1738    /// the list, the rest over the detail. That is what Mail, Notes and Finder do, and it is only
1739    /// expressible because the declaration site already said which pane the command belongs to.
1740    /// Backends that draw one undivided bar ignore it.
1741    pub column: ToolbarColumn,
1742}
1743
1744/// Which pane of a window's navigation a toolbar item was declared in (docs/toolbars.md).
1745#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1746pub enum ToolbarColumn {
1747    /// The window itself, over no particular column. Draws with the detail's items, which is
1748    /// where a command that acts on the whole window belongs when the panes are side by side.
1749    #[default]
1750    Window,
1751    /// The sidebar / master column.
1752    Sidebar,
1753    /// The content-list column between the sidebar and the detail.
1754    List,
1755    /// The detail column.
1756    Detail,
1757}
1758
1759/// Where an item sits on the chrome that carries it (docs/toolbars.md).
1760///
1761/// A placement is a role, never a surface. Which toolbar, navigation bar or column an item
1762/// rides follows from the piece that declared it, so an app never spells that out twice.
1763#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1764pub enum ToolbarPlacement {
1765    /// The natural spot on this chrome: after the leading group on a desktop toolbar, the
1766    /// trailing item group on a navigation bar, an `IF_ROOM` menu action on Android.
1767    #[default]
1768    Automatic,
1769    /// The leading edge: a pane toggle, a control that reveals what is to its left.
1770    Navigation,
1771    /// Centered: a title accessory, a transport, a status readout.
1772    Principal,
1773    /// Trailing, and the last thing a crowded chrome gives up.
1774    Primary,
1775    /// Trailing, and the first thing a crowded chrome folds into its overflow.
1776    Secondary,
1777    /// A bottom bar where the platform has one (iOS `toolbarItems`, an Android bottom app bar);
1778    /// [`ToolbarPlacement::Secondary`] everywhere else.
1779    Bottom,
1780}
1781
1782/// Which halves of an item's label a platform draws, where it can draw more than one.
1783#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1784pub enum LabelStyle {
1785    /// The platform's own convention for this chrome.
1786    #[default]
1787    Automatic,
1788    /// The icon alone (the title stays as the accessible name and the tooltip).
1789    IconOnly,
1790    /// The title alone, even where an icon was given.
1791    TitleOnly,
1792    /// Both, where the chrome has room for both.
1793    TitleAndIcon,
1794}
1795
1796/// A value a toolbar item produced.
1797#[derive(Clone, Debug, PartialEq)]
1798pub enum ToolbarValue {
1799    /// A search item's full new text.
1800    Text(String),
1801    /// A search item's text, submitted with the field's Return or Search key. Sent after the
1802    /// last [`ToolbarValue::Text`]; it changes no state of its own.
1803    Submit(String),
1804    /// A toggle item's new state.
1805    On(bool),
1806    /// A segmented item's newly chosen index.
1807    Selected(usize),
1808}
1809
1810/// A targeted update to one live toolbar item: the path that keeps a bound signal in sync
1811/// without rebuilding the bar (which would drop the search field's focus mid-keystroke).
1812#[derive(Clone, Debug, PartialEq)]
1813pub enum ToolbarPatch {
1814    /// Focus a search control and select its text without changing its value.
1815    Focus { item: String },
1816    /// Replace a search item's text.
1817    Text { item: String, text: String },
1818    /// Set a toggle item's state.
1819    On { item: String, on: bool },
1820    /// Select a segmented item's index.
1821    Selected { item: String, index: usize },
1822    /// Enable or disable any item.
1823    Enabled { item: String, on: bool },
1824    /// Replace a search item's completions (docs/search.md). Targeted rather than a rebuild,
1825    /// because these change on every keystroke and rebuilding the bar would take the field's
1826    /// focus with it.
1827    Suggestions { item: String, list: Vec<String> },
1828    /// Replace an item's words (a language change): its label, which an icon-only item still
1829    /// carries for the overflow menu and assistive technology, and its tooltip. The item keeps
1830    /// its native widget, its action and its place.
1831    Label {
1832        item: String,
1833        label: String,
1834        tooltip: Option<String>,
1835    },
1836    /// Replace a search item's empty-state prompt (docs/search.md), in the live field.
1837    Placeholder { item: String, text: String },
1838}
1839
1840impl ToolbarPatch {
1841    /// The id of the item this patch addresses.
1842    pub fn item(&self) -> &str {
1843        match self {
1844            ToolbarPatch::Focus { item }
1845            | ToolbarPatch::Text { item, .. }
1846            | ToolbarPatch::On { item, .. }
1847            | ToolbarPatch::Selected { item, .. }
1848            | ToolbarPatch::Enabled { item, .. }
1849            | ToolbarPatch::Suggestions { item, .. }
1850            | ToolbarPatch::Label { item, .. }
1851            | ToolbarPatch::Placeholder { item, .. } => item,
1852        }
1853    }
1854
1855    /// Write this patch's value into `items`, the model of a bar. `false` when no item there
1856    /// takes it (an unknown id, or a kind the value does not apply to).
1857    pub fn apply_to(&self, items: &mut [ToolbarItem]) -> bool {
1858        let Some(it) = items.iter_mut().find(|i| i.id == self.item()) else {
1859            return false;
1860        };
1861        match (self, &mut it.kind) {
1862            (ToolbarPatch::Focus { .. }, ToolbarItemKind::Search { .. }) => (),
1863            (ToolbarPatch::Text { text, .. }, ToolbarItemKind::Search { text: t, .. }) => {
1864                *t = text.clone()
1865            }
1866            (
1867                ToolbarPatch::Suggestions { list, .. },
1868                ToolbarItemKind::Search { suggestions, .. },
1869            ) => *suggestions = list.clone(),
1870            (ToolbarPatch::On { on, .. }, ToolbarItemKind::Toggle { on: o }) => *o = *on,
1871            (
1872                ToolbarPatch::Selected { index, .. },
1873                ToolbarItemKind::Segmented { segments, selected },
1874            ) if *index < segments.len() => *selected = *index,
1875            (ToolbarPatch::Enabled { on, .. }, _) => it.enabled = *on,
1876            (ToolbarPatch::Label { label, tooltip, .. }, _) => {
1877                it.label = label.clone();
1878                it.tooltip = tooltip.clone();
1879            }
1880            (
1881                ToolbarPatch::Placeholder { text, .. },
1882                ToolbarItemKind::Search { placeholder, .. },
1883            ) => *placeholder = text.clone(),
1884            _ => return false,
1885        }
1886        true
1887    }
1888}
1889
1890/// One step of an edit to a window's toolbar (docs/toolbars.md).
1891///
1892/// Day hands a backend its bar as edits, never as a whole new model to rebuild, for the same
1893/// reason the view tree arrives as `insert`/`remove` rather than as a fresh tree: an item the
1894/// edit does not name keeps its native widget, and with it the keyboard focus, the caret, a
1895/// menu that is open. A value (search text, a toggle) never travels as an edit; it is a
1896/// [`ToolbarPatch`] on the live item.
1897///
1898/// An edit lists every [`ToolbarOp::Remove`] first, then every [`ToolbarOp::Insert`] in
1899/// ascending `index`, so applying them in order to the bar's current items (a
1900/// [`ToolbarMirror`] does exactly that) produces the new bar. Items keep their relative order
1901/// across an edit: an item that moves arrives as a remove and an insert, like one whose
1902/// presentation changed.
1903#[derive(Clone, Debug, PartialEq)]
1904pub enum ToolbarOp {
1905    /// The item with this id leaves the bar.
1906    Remove { id: String },
1907    /// `item` joins the bar at `index`, its position once this edit is complete.
1908    Insert { index: usize, item: ToolbarItem },
1909}
1910
1911impl ToolbarOp {
1912    /// Apply this op to `items`, a bar's model in order.
1913    pub fn apply_to(&self, items: &mut Vec<ToolbarItem>) {
1914        match self {
1915            ToolbarOp::Remove { id } => items.retain(|i| i.id != *id),
1916            ToolbarOp::Insert { index, item } => {
1917                items.insert((*index).min(items.len()), item.clone())
1918            }
1919        }
1920    }
1921}
1922
1923/// A backend's copy of one window's toolbar, kept in step with the [`ToolbarOp`]s and
1924/// [`ToolbarPatch`]es that reach it, and the one place a backend works out where a new item
1925/// goes (docs/toolbars.md).
1926///
1927/// Every backend lays its bar out as a few groups (the leading and trailing ends of a header
1928/// bar, the columns of a split window, the primary and overflow commands of a command bar) and
1929/// keeps model order within each. So an inserted item always goes right after
1930/// [`ToolbarMirror::prev_where`] its own group, or first in the group when that is `None`, and
1931/// nothing already on the bar moves.
1932#[derive(Clone, Debug, Default)]
1933pub struct ToolbarMirror {
1934    items: Vec<ToolbarItem>,
1935}
1936
1937impl ToolbarMirror {
1938    /// The bar's items, in model order.
1939    pub fn items(&self) -> &[ToolbarItem] {
1940        &self.items
1941    }
1942
1943    pub fn is_empty(&self) -> bool {
1944        self.items.is_empty()
1945    }
1946
1947    /// The item with this id.
1948    pub fn get(&self, id: &str) -> Option<&ToolbarItem> {
1949        self.items.iter().find(|i| i.id == id)
1950    }
1951
1952    /// The item dispatching `action`: how a backend whose native bar reports only an action
1953    /// id (a menu tap) finds what was tapped.
1954    pub fn by_action(&self, action: u64) -> Option<&ToolbarItem> {
1955        self.items
1956            .iter()
1957            .find(|i| i.action == action && action != 0)
1958    }
1959
1960    /// Take the item with `id` out, returning it.
1961    pub fn remove(&mut self, id: &str) -> Option<ToolbarItem> {
1962        let at = self.items.iter().position(|i| i.id == id)?;
1963        Some(self.items.remove(at))
1964    }
1965
1966    /// Put `item` at `index` (clamped to the end).
1967    pub fn insert(&mut self, index: usize, item: ToolbarItem) {
1968        let at = index.min(self.items.len());
1969        self.items.insert(at, item);
1970    }
1971
1972    /// Apply one op to the model: what a backend that repaints its whole native bar from the
1973    /// model (a menu of actions) does with each.
1974    pub fn apply(&mut self, op: &ToolbarOp) {
1975        op.apply_to(&mut self.items);
1976    }
1977
1978    /// Write a value patch into the model. `false` when no item takes it.
1979    pub fn patch(&mut self, patch: &ToolbarPatch) -> bool {
1980        patch.apply_to(&mut self.items)
1981    }
1982
1983    /// The nearest item before `index` that `same_group` accepts: the native item a new one at
1984    /// `index` goes right after, in that group. `None` = it goes first in the group.
1985    pub fn prev_where(
1986        &self,
1987        index: usize,
1988        same_group: impl Fn(&ToolbarItem) -> bool,
1989    ) -> Option<&ToolbarItem> {
1990        self.items[..index.min(self.items.len())]
1991            .iter()
1992            .rev()
1993            .find(|i| same_group(i))
1994    }
1995}
1996
1997#[derive(Clone, Debug, PartialEq)]
1998pub struct KeyEvent {
1999    /// The key's name, in the web `KeyboardEvent.key` vocabulary every platform can map onto:
2000    /// the four arrows ("ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown") and the ten digits
2001    /// ("0" through "9", from the main row or the numeric keypad) everywhere, plus
2002    /// "Delete" and "Backspace" on backends with no menu bar ([`Cap::AppMenu`] unsupported),
2003    /// where no accelerator can own those keys. A focused piece claims every key the route
2004    /// carries, so offering them on a menu-bar platform would let a canvas swallow the Delete
2005    /// its own Edit menu was about to act on (docs/menus.md). The two delete keys keep the
2006    /// names the platform gives the physical keys (a Mac's ⌫ is "Backspace" and its ⌦ is
2007    /// "Delete"), so a handler that means "remove this" takes both. A digit arrives only while
2008    /// neither [`KeyEvent::PRIMARY`] nor [`KeyEvent::ALT`] (nor a Mac's Control) is held: ⌘1
2009    /// and Ctrl+1 are accelerators, and a canvas claiming them would starve the menu. Most
2010    /// backends name the digit the keypress types, so a layout whose number row needs Shift for
2011    /// digits reports "1" with [`KeyEvent::SHIFT`] set; XAML and ArkUI read the physical key.
2012    /// Backends emit `Event::Key` only while no text widget has focus; a field's own editing
2013    /// keys never surface here. The one exception is a single-line text field with a key
2014    /// handler ([`keys::handled`] for its node): it hands "ArrowUp", "ArrowDown" and "Escape",
2015    /// pressed with no modifier, to that handler instead of acting on them itself, so an
2016    /// address bar can walk a suggestion list (docs/textfield.md "Keys").
2017    ///
2018    /// A piece that declared `Decorate::keyboard()` takes the full route instead: every key
2019    /// the platform delivers while it is focused. A key that types nothing is named by its
2020    /// web name ([`KeyEvent::NAMED`]: "Enter", "Tab", "Escape", "Backspace", "Delete", "Home",
2021    /// "End", "PageUp", "PageDown", "Insert", the arrows and "F1" through "F12"); a key that
2022    /// types is named by its unmodified character ("a", "A" under Shift, "8", "ü" on a layout
2023    /// that has one), and what it typed rides in [`KeyEvent::text`]. Under Control or Alt the
2024    /// name stays that character ("c" with [`KeyEvent::CONTROL`] set, never the control code
2025    /// it would type). Text an input method commits (a dead-key accent, a Japanese phrase,
2026    /// the soft keyboard's word) arrives with the text alone and an empty name: no single
2027    /// key is behind it. Only the platform's command chords stay out: ⌘ on Apple platforms
2028    /// and the browser's own shortcuts belong to the menu and the browser, so a terminal's
2029    /// ⌘C still copies. [`KeyEvent::typed`] is the question a text consumer asks.
2030    pub key: String,
2031    /// A [`KeyEvent::SHIFT`]/[`KeyEvent::PRIMARY`]/[`KeyEvent::ALT`]/[`KeyEvent::CONTROL`]
2032    /// mask.
2033    pub modifiers: u8,
2034    /// The text this press committed, on the full route: what the key typed ("a", "A", "é"
2035    /// after a dead key, the whole string an input method committed at once), or `None` for
2036    /// a key that typed nothing (a named key, a Control or Alt chord, a composition still in
2037    /// progress). Separate from [`KeyEvent::key`] so that a committed "Enter" is text and the
2038    /// Enter key is a key, whatever the input method sends. Always `None` on the short route.
2039    pub text: Option<String>,
2040}
2041
2042impl KeyEvent {
2043    pub const SHIFT: u8 = 1;
2044    /// The platform's command key: ⌘ on Apple platforms, Ctrl elsewhere (the
2045    /// [`Shortcut::primary`] convention).
2046    pub const PRIMARY: u8 = 2;
2047    pub const ALT: u8 = 4;
2048    /// The Control key itself, wherever it sits: on Apple platforms it is a different key from
2049    /// [`KeyEvent::PRIMARY`] (⌘), elsewhere the same one, so a Ctrl+C on Linux sets both.
2050    /// Carried on the full route only (`Decorate::keyboard`).
2051    pub const CONTROL: u8 = 8;
2052
2053    /// The ten digit key names, indexed by value.
2054    pub const DIGITS: [&'static str; 10] = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"];
2055
2056    /// Every name the full route gives a key that types nothing (the web `KeyboardEvent.key`
2057    /// vocabulary). A key outside this list is named by the text it types.
2058    pub const NAMED: [&'static str; 26] = [
2059        "ArrowLeft",
2060        "ArrowRight",
2061        "ArrowUp",
2062        "ArrowDown",
2063        "Enter",
2064        "Tab",
2065        "Escape",
2066        "Backspace",
2067        "Delete",
2068        "Home",
2069        "End",
2070        "PageUp",
2071        "PageDown",
2072        "Insert",
2073        "F1",
2074        "F2",
2075        "F3",
2076        "F4",
2077        "F5",
2078        "F6",
2079        "F7",
2080        "F8",
2081        "F9",
2082        "F10",
2083        "F11",
2084        "F12",
2085    ];
2086
2087    /// The text this press typed ([`KeyEvent::text`]), or `None` for a key that typed nothing.
2088    pub fn typed(&self) -> Option<&str> {
2089        self.text.as_deref()
2090    }
2091
2092    /// A key that types nothing (one of [`KeyEvent::NAMED`], or a chord's character under
2093    /// Control or Alt), on either route.
2094    pub fn named(key: impl Into<String>, modifiers: u8) -> KeyEvent {
2095        KeyEvent {
2096            key: key.into(),
2097            modifiers,
2098            text: None,
2099        }
2100    }
2101
2102    /// Text a press committed on the full route. The key is named by the text when the text
2103    /// is one character (the press typed it), and left empty for a longer commit, which no
2104    /// single key is behind.
2105    pub fn typed_text(text: impl Into<String>, modifiers: u8) -> KeyEvent {
2106        let text = text.into();
2107        let mut chars = text.chars();
2108        let key = match (chars.next(), chars.next()) {
2109            (Some(_), None) => text.clone(),
2110            _ => String::new(),
2111        };
2112        KeyEvent {
2113            key,
2114            modifiers,
2115            text: Some(text),
2116        }
2117    }
2118
2119    /// Text a press committed on the full route, named by the key that produced it
2120    /// (`key`, in the vocabulary above) when the backend knows it.
2121    pub fn typed_by(key: impl Into<String>, text: impl Into<String>, modifiers: u8) -> KeyEvent {
2122        KeyEvent {
2123            key: key.into(),
2124            modifiers,
2125            text: Some(text.into()),
2126        }
2127    }
2128
2129    /// The web name for the function key `F<n>`, `1..=12`.
2130    pub fn function_name(n: u8) -> Option<&'static str> {
2131        match n {
2132            1..=12 => Some(Self::NAMED[13 + n as usize]),
2133            _ => None,
2134        }
2135    }
2136
2137    /// The key name for a typed character when it is one of the ten digits: what a backend
2138    /// reports for a keypress that types `0`–`9`.
2139    pub fn digit_name(c: char) -> Option<&'static str> {
2140        c.to_digit(10).map(|d| Self::DIGITS[d as usize])
2141    }
2142
2143    /// The value of a digit key, or `None` for every other key.
2144    pub fn digit(&self) -> Option<u8> {
2145        match self.key.as_bytes() {
2146            [d @ b'0'..=b'9'] => Some(d - b'0'),
2147            _ => None,
2148        }
2149    }
2150
2151    pub fn shift(&self) -> bool {
2152        self.modifiers & Self::SHIFT != 0
2153    }
2154    pub fn primary(&self) -> bool {
2155        self.modifiers & Self::PRIMARY != 0
2156    }
2157    pub fn alt(&self) -> bool {
2158        self.modifiers & Self::ALT != 0
2159    }
2160    pub fn control(&self) -> bool {
2161        self.modifiers & Self::CONTROL != 0
2162    }
2163}
2164
2165#[cfg(test)]
2166mod key_event_tests {
2167    use super::KeyEvent;
2168
2169    #[test]
2170    fn digit_names_read_back_as_values() {
2171        for (value, c) in ('0'..='9').enumerate() {
2172            let name = KeyEvent::digit_name(c).expect("an ASCII digit names itself");
2173            let key = KeyEvent::named(name, 0);
2174            assert_eq!(key.digit(), Some(value as u8));
2175        }
2176        // Only the ASCII digits: a letter, an Arabic-Indic three, and a named key are not.
2177        assert_eq!(KeyEvent::digit_name('a'), None);
2178        assert_eq!(KeyEvent::digit_name('٣'), None);
2179        let arrow = KeyEvent::named("ArrowUp", 0);
2180        assert_eq!(arrow.digit(), None);
2181    }
2182
2183    #[test]
2184    fn typed_text_is_told_from_named_keys() {
2185        let a = KeyEvent::typed_text("a", 0);
2186        assert_eq!((a.key.as_str(), a.typed()), ("a", Some("a")));
2187        let space = KeyEvent::typed_text(" ", 0);
2188        assert_eq!((space.key.as_str(), space.typed()), (" ", Some(" ")));
2189        assert_eq!(KeyEvent::typed_text("7", 0).digit(), Some(7));
2190        // A longer commit has no key behind it.
2191        let phrase = KeyEvent::typed_text("こんにちは", 0);
2192        assert_eq!(
2193            (phrase.key.as_str(), phrase.typed()),
2194            ("", Some("こんにちは"))
2195        );
2196        // Text that spells a key name is still text, and the key is still a key.
2197        for name in KeyEvent::NAMED {
2198            assert_eq!(
2199                KeyEvent::named(name, 0).typed(),
2200                None,
2201                "{name} types nothing"
2202            );
2203            assert_eq!(KeyEvent::typed_text(name, 0).typed(), Some(name));
2204        }
2205        let accent = KeyEvent::typed_by("e", "é", 0);
2206        assert_eq!((accent.key.as_str(), accent.typed()), ("e", Some("é")));
2207        assert_eq!(KeyEvent::function_name(1), Some("F1"));
2208        assert_eq!(KeyEvent::function_name(12), Some("F12"));
2209        assert_eq!(KeyEvent::function_name(13), None);
2210        let chord = KeyEvent::named("c", KeyEvent::CONTROL | KeyEvent::SHIFT);
2211        assert!(chord.control() && chord.shift() && !chord.primary());
2212        assert_eq!(chord.typed(), None);
2213    }
2214
2215    #[test]
2216    fn a_declaration_claims_nothing_without_a_handler() {
2217        let node = super::NodeId(0xdead_0001);
2218        super::keys::mark_text(node);
2219        assert!(!super::keys::text(node), "no handler, no claim");
2220        super::keys::mark(node);
2221        assert!(super::keys::text(node) && super::keys::handled(node));
2222        super::keys::forget(node);
2223        assert!(!super::keys::text(node) && !super::keys::handled(node));
2224    }
2225}
2226
2227#[derive(Clone, Copy, Debug, PartialEq)]
2228pub struct PointerEvent {
2229    pub position: Point,
2230    pub down: bool,
2231}
2232
2233/// The event sink: enqueue-only. It may be invoked re-entrantly from inside any Toolkit method;
2234/// day-core drains queued events at safe points, each as a fresh batch (§3.3).
2235pub type EventSink = Box<dyn Fn(NodeId, Event)>;
2236
2237/// The synchronous row-pull closures for recycling lists (docs/list.md, §10). day-core injects one
2238/// per `LIST` host via [`Toolkit::attach_list`]; a recycling backend stores it and calls it from
2239/// its native data-source (on the UI thread, outside any day-core borrow). Each closure re-enters
2240/// day-core, so, unlike [`EventSink`], these run to completion synchronously (`bind_row` even
2241/// flushes + lays out the row before returning, so the host can measure the cell immediately).
2242#[derive(Clone)]
2243pub struct ListSource {
2244    /// Report the first actually visible row (exclude overscan). Enqueue-only; optional,
2245    /// so hosts without a viewport binding incur no app event work.
2246    pub first_visible: Option<std::rc::Rc<dyn Fn(usize)>>,
2247    /// Current row count.
2248    pub len: std::rc::Rc<dyn Fn() -> usize>,
2249    /// Present on a sectioned list (`ListProps::sections`, docs/list.md "Sections"): whether
2250    /// row `index` is a section header. Every row index the host sees counts headers, and
2251    /// day-core translates to the app's items. A header row is not selectable, activatable or
2252    /// swipeable; the host draws it in its platform's group-header style, sized to its content
2253    /// even in a `Uniform` list, and floats it where the platform does (macOS group rows,
2254    /// UIKit plain-table section headers).
2255    pub is_header: Option<std::rc::Rc<dyn Fn(usize) -> bool>>,
2256    /// Stable identity token for the row at `index` (for native diffing / animation).
2257    pub token_at: std::rc::Rc<dyn Fn(usize) -> u64>,
2258    /// Build (first use of this cell) or rebind (recycled cell) row `index` into the native cell.
2259    pub bind_row: std::rc::Rc<dyn Fn(usize, RawHandle)>,
2260    /// A host that emulates `Cap::ListSections` binds the header it pins over the top of the
2261    /// list with this instead of `bind_row` (docs/list.md "Sections"): the same build or
2262    /// rebind, but the copy carries no element ids, so a dayscript or accessibility lookup of a
2263    /// header finds the header row in the list, never its pinned copy.
2264    pub bind_pinned: std::rc::Rc<dyn Fn(usize, RawHandle)>,
2265    /// The native cell left the viewport; Day may drop per-cell bookkeeping (optional).
2266    pub recycle: std::rc::Rc<dyn Fn(RawHandle)>,
2267    /// The native host is done with this cell for good (a `GtkListItemFactory::teardown`, a
2268    /// `UITableViewCell` deallocating): Day disposes the row it built there, its scope, nodes
2269    /// and element ids. Without this a host that discards cells, as every pool does on a far
2270    /// jump, leaves one dead row behind in day-core per discarded cell. Safe inside a day-core
2271    /// borrow (the work is held for the borrow's end) and for a cell Day never saw.
2272    pub release: std::rc::Rc<dyn Fn(RawHandle)>,
2273    /// Re-lay the row bound to this cell at `width`, called from the cell's own native layout
2274    /// pass, the hook [`TreeSource::layout_cell`] already gives trees. day-core lays a row at the
2275    /// `LIST`'s width first, which is right wherever the cell is the row itself; a backend
2276    /// whose native row wraps the cell in chrome (GtkListView's themed `row` node pads it)
2277    /// corrects it here, so the row fits the cell the platform gave it instead of holding the
2278    /// whole list wider than its frame. Skips quietly when called inside a day-core borrow (a
2279    /// snapshot pass).
2280    pub layout_cell: std::rc::Rc<dyn Fn(RawHandle, f64)>,
2281    /// The height day-core last laid the row bound to this cell at: the row's own height,
2282    /// padding included, as `RowHeight` resolves it. A backend whose cell measures itself
2283    /// (GtkListView's `DayCell`) reports it as the cell's height, so a padded row keeps its
2284    /// bottom padding rather than the height of its last child's frame. `0.0` before the row's
2285    /// first layout, or inside a day-core borrow.
2286    pub cell_height: std::rc::Rc<dyn Fn(RawHandle) -> f64>,
2287    /// Drag-to-reorder closures, present when `ListProps::reorderable` (docs/list.md). `None` on
2288    /// non-reorderable lists; backends must not enable their drag machinery without it.
2289    pub reorder: Option<ListReorder>,
2290    /// Swipe-to-delete closures, present when `ListProps::deletable` (docs/list.md). `None` on
2291    /// non-deletable lists; backends must not offer their delete affordance without it.
2292    pub delete: Option<ListDelete>,
2293    /// Swipe-actions closures, present when `ListProps::swipe_actions` (docs/list.md). `None` on
2294    /// lists that declared none; backends must not install their row-action machinery
2295    /// without it.
2296    pub swipe: Option<ListSwipe>,
2297}
2298
2299/// The synchronous drag-to-reorder half of [`ListSource`] (docs/list.md). Both closures follow
2300/// `bind_row`'s discipline: called on the UI thread from inside native drag callbacks, outside
2301/// any day-core borrow, and they run to completion synchronously.
2302#[derive(Clone)]
2303pub struct ListReorder {
2304    /// May row `from` drop at row `to`? Called from the native validate/hover hook so the
2305    /// affordance (gap, insertion mark, forbidden cursor) reflects the app's answer live.
2306    /// Returns the accepted target index: `to` itself to allow, another index to retarget the
2307    /// drop, or `-1` to deny.
2308    pub can_move: std::rc::Rc<dyn Fn(usize, usize) -> i64>,
2309    /// Commit: row `from` dropped at row `to` (an index `can_move` accepted). Rotates Day's row
2310    /// snapshot before returning (so `len`/`token_at`/`bind_row` reflect the new order while the
2311    /// native move animates) and defers the app's own callback to the next event drain.
2312    pub move_row: std::rc::Rc<dyn Fn(usize, usize)>,
2313}
2314
2315/// The synchronous swipe-to-delete half of [`ListSource`] (docs/list.md), shaped exactly like
2316/// [`ListReorder`]: both closures are called on the UI thread from inside native swipe callbacks,
2317/// outside any day-core borrow, and run to completion synchronously.
2318///
2319/// Each platform spells the gesture its own way (a trailing swipe action on iOS, an
2320/// `ItemTouchHelper` swipe on Android, a `ListItem` swipe action on ArkUI), but all three ask the
2321/// same two questions, so this struct is one pair of closures rather than three shapes.
2322#[derive(Clone)]
2323pub struct ListDelete {
2324    /// May row `index` be deleted? Called before the affordance is offered, so a row the app
2325    /// protects shows no delete action at all rather than one that fails on use.
2326    pub can_delete: std::rc::Rc<dyn Fn(usize) -> bool>,
2327    /// Commit: delete row `index`. Removes it from Day's row snapshot before returning (so
2328    /// `len`/`token_at`/`bind_row` already reflect the shorter list while the native row-removal
2329    /// animates) and defers the app's own callback to the next event drain.
2330    pub delete_row: std::rc::Rc<dyn Fn(usize)>,
2331}
2332
2333/// Which edge of a row a swipe action rides (docs/list.md). Semantic, not geometric:
2334/// `Leading` follows the reading direction (the left edge in LTR, the right in RTL), the
2335/// mapping every platform's swipe API already makes.
2336#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2337pub enum SwipeEdge {
2338    Leading,
2339    Trailing,
2340}
2341
2342/// One offered swipe action (docs/list.md): pure data. The pieces layer keeps the handlers;
2343/// the backend answers a tap through [`ListSwipe::perform`] by index into the offer.
2344#[derive(Clone, Debug, PartialEq)]
2345pub struct ListSwipeAction {
2346    /// The word on the button, already localized (a toolkit cannot translate).
2347    pub label: String,
2348    /// Destructive styling: the platform's red.
2349    pub destructive: bool,
2350    /// Explicit button color; `None` = the platform's default for the style.
2351    pub tint: Option<Color>,
2352    /// A glyph for the button where the platform draws one: above the label on macOS, in
2353    /// place of it on iOS (docs/list.md).
2354    pub symbol: Option<Symbol>,
2355}
2356
2357/// The synchronous swipe-actions half of [`ListSource`] (docs/list.md), the generalized
2358/// sibling of [`ListDelete`]: reveal-as-you-swipe buttons on either row edge. The offer is
2359/// pulled per row at gesture time, so labels follow row state ("Mark Read" on an unread row,
2360/// "Mark Unread" on a read one); the commit defers to the event drain like every closure here.
2361#[derive(Clone)]
2362pub struct ListSwipe {
2363    /// The offer: the actions for row `index` on `edge`, called inside the platform's swipe
2364    /// callback, so keep it pure. Empty = no affordance for that row and edge. The first action
2365    /// is the full-swipe action where the platform activates one at the far edge.
2366    pub actions_at: std::rc::Rc<dyn Fn(usize, SwipeEdge) -> Vec<ListSwipeAction>>,
2367    /// The commit: the user activated action `action` (an index into the offer) on row
2368    /// `index`, `edge`. Unlike a delete this never reshapes the row snapshot; the app's
2369    /// handler is deferred to the next event drain, never run inside the native callback.
2370    pub perform: std::rc::Rc<dyn Fn(usize, SwipeEdge, usize)>,
2371}
2372
2373/// The synchronous row-pull closures for hierarchical trees (docs/tree.md): [`ListSource`]'s
2374/// shape, addressed by token instead of row index, because expanding a row renumbers every
2375/// index below it while tokens hold still. day-core injects one per `TREE` host via
2376/// [`Toolkit::attach_tree`]; the backend answers its native data-source from it. The same
2377/// synchronous discipline as [`ListSource`]: UI thread, outside any day-core borrow;
2378/// `bind_row` flushes and lays the row out before returning.
2379#[derive(Clone)]
2380pub struct TreeSource {
2381    /// How many children `parent` has (`None` = the root level).
2382    pub children_len: std::rc::Rc<dyn Fn(Option<u64>) -> usize>,
2383    /// The i-th child of `parent`: the stable token every backend keys its rows by.
2384    pub child_token: std::rc::Rc<dyn Fn(Option<u64>, usize) -> u64>,
2385    /// Whether this token can hold children at all: what draws (or omits) the disclosure.
2386    pub expandable: std::rc::Rc<dyn Fn(u64) -> bool>,
2387    /// Non-selectable section heading, separate from a navigation destination.
2388    pub section_header: std::rc::Rc<dyn Fn(u64) -> bool>,
2389    /// Current desired expansion, including restoration before the first native reload.
2390    pub expanded: std::rc::Rc<dyn Fn(u64) -> bool>,
2391    /// Build (first use of this cell) or rebind (recycled cell) the row for `token` into the
2392    /// native cell.
2393    pub bind_row: std::rc::Rc<dyn Fn(u64, RawHandle)>,
2394    /// The native cell left the viewport; Day may drop per-cell bookkeeping (optional).
2395    pub recycle: std::rc::Rc<dyn Fn(RawHandle)>,
2396    /// Re-lay the row bound to this cell at `width`, called from the cell's own native
2397    /// layout pass. Trees need this where lists don't: indentation makes every cell's
2398    /// content width per-row, so the host-width layout `bind_row` did is only a first
2399    /// approximation. Skips quietly when called inside a day-core borrow (a snapshot pass).
2400    pub layout_cell: std::rc::Rc<dyn Fn(RawHandle, f64)>,
2401    /// Native bounds for controls whose group headers have a different height from leaves.
2402    /// Overrides the initial row-height estimate and preserves the native height on rebind.
2403    pub layout_cell_size: std::rc::Rc<dyn Fn(RawHandle, Size)>,
2404    /// The height day-core last laid this cell's row at (see [`ListSource::cell_height`]).
2405    pub cell_height: std::rc::Rc<dyn Fn(RawHandle) -> f64>,
2406    /// The row's type-ahead string (docs/tree.md): what native type-select matches against.
2407    pub type_select_text: std::rc::Rc<dyn Fn(u64) -> String>,
2408    /// The row's context menu, built when the menu is summoned (docs/menus.md "Dynamic context
2409    /// menus"), called on the UI thread from the platform's own menu callback, outside any
2410    /// day-core borrow, like every closure here. `None` = rows carry no menu; an empty
2411    /// result suppresses the menu for that row.
2412    pub row_menu: Option<std::rc::Rc<dyn Fn(u64) -> Vec<MenuItem>>>,
2413    /// Drag-to-move closures, present when `TreeProps::movable` (docs/tree.md). `None` on
2414    /// immovable trees; backends must not enable their drag machinery without it.
2415    pub moves: Option<TreeMoves>,
2416}
2417
2418/// The synchronous drag half of [`TreeSource`] (docs/tree.md). Both closures follow
2419/// `bind_row`'s discipline: called on the UI thread from inside native drag callbacks.
2420#[derive(Clone)]
2421pub struct TreeMoves {
2422    /// The live verdict, consulted while the drag is over a target: may `token` land under
2423    /// `parent` at `index`? `index: None` means "dropped onto the parent" (append). Pure, since
2424    /// it runs inside the platform's drag-validate callback.
2425    #[allow(clippy::type_complexity)]
2426    pub can_move: std::rc::Rc<dyn Fn(u64, Option<u64>, Option<usize>) -> MoveVerdict>,
2427    /// Commit an accepted drop. Defers the app's `on_move` through the event queue
2428    /// ([`Event::TreeMove`]); the app's own data write drives the reload.
2429    #[allow(clippy::type_complexity)]
2430    pub move_node: std::rc::Rc<dyn Fn(u64, Option<u64>, Option<usize>)>,
2431}
2432
2433/// A summon-time context-menu provider (docs/menus.md): local-point in, menu out.
2434pub type ContextMenuFn = std::rc::Rc<dyn Fn(Point) -> Vec<MenuItem>>;
2435
2436/// Ask a menu button's provider for its menu at press time ([`Toolkit::set_button_menu`]), and
2437/// answer the items to show, or `None` to show nothing: an empty menu, or a provider that
2438/// removed its own button. The provider is app code; a signal it writes can rebuild the tree
2439/// synchronously and release the very button being pressed. `still_registered` asks the
2440/// toolkit's own registry, AFTER the provider has returned, whether the button is still the one
2441/// registered for this press; a toolkit holding a raw native handle must not touch it otherwise.
2442pub fn resolve_button_menu(
2443    provider: &ContextMenuFn,
2444    still_registered: impl FnOnce() -> bool,
2445) -> Option<Vec<MenuItem>> {
2446    let items = provider(Point::ZERO);
2447    if items.is_empty() || !still_registered() {
2448        return None;
2449    }
2450    Some(items)
2451}
2452
2453/// A tree move guard's verdict (docs/tree.md). No `Retarget` yet: the drop vocabulary is
2454/// already positional, so a guard that wants a different target denies and the user drops
2455/// where it is allowed.
2456#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2457pub enum MoveVerdict {
2458    Allow,
2459    Deny,
2460}
2461
2462/// One addressable widget within a composite native backing (docs/tree.md,
2463/// docs/tweaks.md), Qt's name for the concept (`QStyle::SubControl`). A `list`'s or
2464/// `tree`'s node handle is its scroller; `Subcontrol::Content` is the widget inside it.
2465/// Backends resolve an unknown subcontrol to `None`, never to the host.
2466#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
2467pub enum Subcontrol {
2468    /// The node's own handle: what every tweak accessor reached before subcontrols existed.
2469    Host,
2470    /// The content widget inside the scroller (`NSOutlineView`, `NSTableView`, …).
2471    Content,
2472    /// The header view, where the widget has one. Day's lists and trees ship headerless, so
2473    /// this answers `None` until a kind grows a header.
2474    Header,
2475}
2476
2477// ---------------------------------------------------------------------------
2478// Capabilities, animation, a11y
2479// ---------------------------------------------------------------------------
2480
2481/// What to show on the app's icon in the Dock, launcher, home screen, or taskbar (docs/badge.md).
2482///
2483/// Distinct from `NavItem::badge`, which annotates a sidebar row inside the window. This one
2484/// decorates the application itself and is drawn by the shell, not by Day.
2485///
2486/// What each payload needs is asked separately (`Cap::AppBadgeCount`, `AppBadgeText`,
2487/// `AppBadgeDot`) because the platforms differ in what they accept more than in whether they have
2488/// a badge at all: macOS takes arbitrary text, iOS and the web take a number, Android takes nothing.
2489#[derive(Clone, Debug, PartialEq, Eq, Default)]
2490pub enum AppBadge {
2491    /// Clear the badge.
2492    #[default]
2493    None,
2494    /// A count. Zero clears it, matching every platform's own convention.
2495    Count(u32),
2496    /// Short arbitrary text (`"99+"`, `"beta"`). Only macOS renders it; probe `Cap::AppBadgeText`.
2497    Text(String),
2498    /// An indicator with no value.
2499    Dot,
2500}
2501
2502/// How wide a window is, in coarse buckets (docs/size-classes.md).
2503///
2504/// The breakpoints are Android's window size classes, in density-independent points, and they are
2505/// used verbatim on every backend rather than per-platform. One table means one answer: a 700pt
2506/// window is [`WidthClass::Medium`] on a Mac, in a browser, and on a tablet, so an app that lays
2507/// out from the class gets the same layout at the same size everywhere. Apple publishes only two
2508/// buckets (compact/regular); those map onto this table rather than replacing it, with
2509/// [`WidthClass::Compact`] the compact one and everything above it regular.
2510#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug, Default)]
2511pub enum WidthClass {
2512    /// `< 600dp`: a phone in portrait. One pane at a time.
2513    #[default]
2514    Compact,
2515    /// `600–839dp`: a tablet in portrait, a narrow desktop window.
2516    Medium,
2517    /// `840–1199dp`: a tablet in landscape, a typical desktop window.
2518    Expanded,
2519    /// `1200–1599dp`: a large desktop window.
2520    Large,
2521    /// `≥ 1600dp`: a maximized window on a big display.
2522    ExtraLarge,
2523}
2524
2525/// How tall a window is (docs/size-classes.md). Consulted far less than [`WidthClass`]: it is
2526/// what tells a phone in landscape (wide enough for two panes, too short for a tall list) that
2527/// it should not grow vertical chrome.
2528#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug, Default)]
2529pub enum HeightClass {
2530    /// `< 480dp`: a phone in landscape.
2531    #[default]
2532    Compact,
2533    /// `480–899dp`: a phone in portrait, a tablet in landscape.
2534    Medium,
2535    /// `≥ 900dp`: a tablet in portrait, most desktop windows.
2536    Expanded,
2537}
2538
2539/// A window's size class (docs/size-classes.md), reported by the backend and read by apps
2540/// through `day::size_class()`.
2541///
2542/// Per-window, not per-app: two windows of one process can sit in different classes at the same
2543/// time (a narrow and a wide window side by side, iPadOS Stage Manager, Android split-screen), and
2544/// an app that keyed off a single global would lay the second window out for the first one's size.
2545#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
2546pub struct SizeClass {
2547    pub width: WidthClass,
2548    pub height: HeightClass,
2549}
2550
2551impl SizeClass {
2552    /// The `Compact`/`Medium` width boundary in dp: the narrowest window where a second
2553    /// pane starts to fit. Backends that hand an adaptive container its pane widths derive
2554    /// them from this (Android's list + minimum-detail widths sum to it), so the platform's
2555    /// measure-time decision and this table agree by construction (docs/size-classes.md).
2556    pub const SPLIT_MIN_WIDTH: f64 = 600.0;
2557
2558    /// Bucket a window's size in points. The one place the breakpoint numbers appear.
2559    pub fn from_size(width: f64, height: f64) -> Self {
2560        SizeClass {
2561            width: match width {
2562                w if w >= 1600.0 => WidthClass::ExtraLarge,
2563                w if w >= 1200.0 => WidthClass::Large,
2564                w if w >= 840.0 => WidthClass::Expanded,
2565                w if w >= Self::SPLIT_MIN_WIDTH => WidthClass::Medium,
2566                _ => WidthClass::Compact,
2567            },
2568            height: match height {
2569                h if h >= 900.0 => HeightClass::Expanded,
2570                h if h >= 480.0 => HeightClass::Medium,
2571                _ => HeightClass::Compact,
2572            },
2573        }
2574    }
2575
2576    /// Whether a two-pane presentation fits. The rule behind an automatic
2577    /// [`props::NavPresentation`]: anything wider than compact gets both panes.
2578    pub fn prefers_split(self) -> bool {
2579        self.width > WidthClass::Compact
2580    }
2581}
2582
2583#[derive(Clone, Copy, PartialEq, Eq, Debug)]
2584pub enum Cap {
2585    /// Standard searchfield control.
2586    SearchField,
2587    /// Standard combobox control.
2588    ComboBox,
2589    /// Standard stepper control.
2590    Stepper,
2591    /// Standard datetime control.
2592    DateTimePicker,
2593    /// Standard colorpicker control.
2594    ColorPicker,
2595    /// Standard pullrefresh control.
2596    PullRefresh,
2597    /// Standard pager control.
2598    Pager,
2599    /// User-driven pull recognition, separate from a refresh indicator.
2600    PullRefreshGesture,
2601
2602    /// Native data-transfer source and destination callbacks.
2603    DragDrop,
2604    /// Transfers between independent native applications (inbound).
2605    DragExternalImport,
2606    /// Transfers to independent native applications, including arbitrary binary MIME data.
2607    DragExternalExport,
2608    /// Lossless ordered items and alternatives between Day applications.
2609    DragMultipleItems,
2610    /// Existing native file references, distinct from promised/generated files.
2611    DragFileReferences,
2612    /// Native result can wait for asynchronous data receipt.
2613    DragDeferredReceipt,
2614    /// Generated files supplied to a destination after dropping.
2615    DragFilePromises,
2616    /// External move acknowledgment safe for source deletion.
2617    DragExternalMove,
2618    ListRecycling,
2619    /// The toolkit fronts the app's undo stack with the platform's own undo system
2620    /// ([`Toolkit::set_undo_state`] + `Event::Undo`): `Native` where one exists
2621    /// (`NSUndoManager` on macOS/iOS, `QUndoStack`), `Unsupported` everywhere else, where
2622    /// Day's menu items and accelerators drive the stack directly and nothing platform-owned
2623    /// needs mirroring (docs/model.md).
2624    UndoBridge,
2625    /// The toolkit routes the platform's standard Cut/Copy/Paste to the app's edit bridge
2626    /// ([`Toolkit::set_edit_state`] + `Event::Edit`): the same menu items, shortcuts, and
2627    /// responder precedence the platform's text editing uses; a focused text widget keeps
2628    /// its own clipboard behavior, everything else reaches the app (docs/menus.md).
2629    /// `Native` where a system route exists (the responder chain, the browser's clipboard
2630    /// events), `Emulated` where Day's own menu items dispatch it, `Unsupported` elsewhere.
2631    EditBridge,
2632    /// The toolkit realizes `ListProps::reorderable` as drag-to-reorder rows: `Native` when the
2633    /// platform's own mechanism drives it (NSTableView drag/drop, UITableView drag delegates,
2634    /// ItemTouchHelper, …), `Emulated` for a pointer-tracked fake (web-dom). `Unsupported` ⇒ the
2635    /// list renders normally but rows cannot be dragged (docs/list.md).
2636    ListReorder,
2637    /// Sidebar destinations can be dragged to reorder (`NavBuilder::reorder_items`) and between
2638    /// sections (`NavBuilder::regroup_items`). `Native` when the toolkit's own sidebar drags them
2639    /// (`NavMenuProps::movable`, and across headers under `NavMenuProps::regroup`); `Emulated`
2640    /// when Day stands a reorderable list in for the sidebar. Independent of `ListReorder`: UIKit
2641    /// supports draggable content lists but retains its native navigation collection for
2642    /// sidebars.
2643    NavReorder,
2644    /// The toolkit realizes `ListProps::deletable` as the platform's delete gesture:
2645    /// `Native` where the platform ships one (UIKit's trailing swipe actions, Android's
2646    /// `ItemTouchHelper`, ArkUI's `ListItem.swipeAction`), `Unsupported` on the desktop toolkits,
2647    /// whose lists have no swipe idiom and where deletion belongs to a menu or a button
2648    /// (docs/list.md).
2649    ListDelete,
2650    /// The toolkit realizes `ListProps::swipe_actions` as edge swipe actions: buttons
2651    /// that reveal as the row tracks the swipe, with the far edge activating the first one
2652    /// (docs/list.md). `Native` where the platform ships the affordance: macos-appkit
2653    /// (`NSTableView` row actions, Mail's own machinery) and ios-uikit
2654    /// (`UISwipeActionsConfiguration`). `Unsupported` everywhere else: the affordance is
2655    /// absent, and the app's command lives in its explicit controls.
2656    ListSwipeActions,
2657    /// The toolkit realizes `ListProps::editing` as the platform's list editing mode: rows
2658    /// show their delete controls and reorder grips while the list is editing (docs/list.md).
2659    /// `Native` on ios-uikit (`UITableView` editing). `Unsupported` everywhere else, where a
2660    /// list has no separate editing mode: its rows already drag, swipe and open menus as they
2661    /// are, and the list renders as if `editing` were off.
2662    ListEditing,
2663    /// The toolkit realizes `kinds::LIST_ITEM` as its own list row content (docs/list.md "List
2664    /// items"): `Native` where the platform has a standard row it draws itself (UIKit's
2665    /// `UIListContentConfiguration`, a Material list item, AppKit's image-and-text table cell,
2666    /// a GTK row box), so the row takes the platform's fonts, icon size, spacing, secondary
2667    /// colors and check mark. `Unsupported` ⇒ the `list_item` piece composes the same content
2668    /// from plain pieces. Apps have no reason to probe this; the piece does.
2669    ListItem,
2670    /// The toolkit realizes `kinds::TREE` as a hierarchical tree view (docs/tree.md):
2671    /// `Native` where a platform tree widget hosts Day-built rows (NSOutlineView, the UIKit
2672    /// sidebar list, GtkListView+TreeListModel, WinUI TreeView, ArkTS TreeView), `Emulated`
2673    /// where Day flattens the tree onto its list machinery, `Unsupported` where neither
2674    /// exists yet. An app gates its tree UI on this answer rather than showing a placeholder.
2675    Tree,
2676    /// The toolkit realizes `TreeProps::movable` as drag-to-reparent/restack rows
2677    /// (docs/tree.md). A strictly smaller set than [`Cap::Tree`]: a backend can render a
2678    /// tree it cannot yet drag within.
2679    TreeMove,
2680    /// Native two-level section headers; general trees may still be composed.
2681    TreeSections,
2682    /// The toolkit answers [`Toolkit::first_baseline`], so rows can align text on its baseline
2683    /// rather than on the middle of its box (docs/baseline.md). `Native` where the platform
2684    /// reports the baseline itself (`NSView.firstBaselineOffsetFromTop`, `View.getBaseline`,
2685    /// `gtk_widget_measure`), `Emulated` where Day derives it from the widget's font metrics,
2686    /// `Unsupported` ⇒ baseline-aligned rows fall back to centering and look exactly as they do
2687    /// today.
2688    BaselineAlignment,
2689    /// The toolkit draws a label's [`TextRun`]s: bold, italic, color or a monospace face within
2690    /// one wrapping paragraph (docs/text-runs.md). `Unsupported` ⇒ the label renders its text
2691    /// uniformly, which reads correctly and loses only the emphasis.
2692    TextRuns,
2693    /// The toolkit makes a run carrying [`TextRun::link`] activatable, emitting
2694    /// [`Event::LinkActivated`]. A strictly smaller set than [`Cap::TextRuns`]: several toolkits
2695    /// draw a link run in link colors but have no way to hit-test it, and one (Android) can do
2696    /// links or selection but not both (docs/text-runs.md).
2697    TextLinks,
2698    Lottie,
2699    NativeSymbols,
2700    /// The toolkit can rasterize its window and hand back the pixels
2701    /// (`Toolkit::snapshot_window`): what the dayscript `screenshot` step captures in-process
2702    /// and what `day::window_image()` offers the app (docs/window-image.md). `Unsupported` where
2703    /// a backend cannot draw itself into a bitmap: web-dom, which would need a rasterizer
2704    /// shipped with it. Probe it before offering a "save a screenshot" affordance, rather than
2705    /// offering one that fails when pressed.
2706    Snapshot,
2707    /// The toolkit can present `nav()` as sidebar+detail split panes, a statement about the
2708    /// toolkit, not about the window it is currently drawing. Whether a given host is split right
2709    /// now follows from its [`SizeClass`]: the pieces layer resolves an automatic
2710    /// [`props::NavPresentation`] against both, and re-resolves on every class change. A backend
2711    /// with no split container answers `Unsupported` and stays stacked at every size.
2712    NavSplit,
2713    /// The toolkit can draw a navigation host's rows as its own chrome: a tab bar
2714    /// ([`props::NavPresentation::Tabs`]) and, where it has one, a rail
2715    /// ([`props::NavPresentation::Rail`]). Like [`Self::NavSplit`] this is a statement about the
2716    /// toolkit, not about the window it is drawing right now.
2717    ///
2718    /// This is what `NavStyle::Automatic` resolves against (docs/navigation.md): a backend
2719    /// answering `Unsupported` gets the sidebar resolver instead (`Split` ↔ `Stack`), which is
2720    /// what every backend did before adaptive navigation existed. So an unimplemented backend
2721    /// degrades to its previous behavior rather than to a hole.
2722    ///
2723    /// `Emulated` means the rows are composed from other widgets rather than drawn by a native
2724    /// tab container (Qt, web-dom). `Native` means a real one (`UITabBarController`, a Material
2725    /// `NavigationBarView`, `NavigationView`).
2726    NavTabs,
2727    /// A narrow window should become a tab bar here, a separate question from [`Self::NavTabs`],
2728    /// which only says the toolkit *can* draw one.
2729    ///
2730    /// The two differ on every desktop. macOS, GNOME, Qt and Windows can all draw a tab bar, and
2731    /// must, because an app is free to pin `NavStyle::Tabs`; but none of them grows one when
2732    /// its window is dragged narrow. A narrow Mail.app hides its sidebar and pushes; it does not
2733    /// sprout a bottom tab bar, and an app that did would look like a port. The phones and the web
2734    /// are the opposite: those are the surfaces whose window size ranges from a phone to a
2735    /// desktop, and a tab bar is what their users expect at the narrow end.
2736    ///
2737    /// So this is a statement about the platform's idiom, not about its widget set:
2738    ///
2739    /// - `Native`/`Emulated`: `NavStyle::Automatic` may resolve to
2740    ///   [`props::NavPresentation::Tabs`] on a compact window (ios-uikit, android-material,
2741    ///   harmony-arkui, web-dom).
2742    /// - `Unsupported`: it may not; a compact window collapses to
2743    ///   [`props::NavPresentation::Stack`] instead, exactly as `NavStyle::Sidebar` has always
2744    ///   done (macos-appkit, linux-gtk, linux-qt, windows-winui).
2745    ///
2746    /// [`props::NavPresentation::Rail`] is not gated by this. A narrow sidebar is an ordinary
2747    /// desktop shape (on Windows it is what `NavigationView` does at that width on its own), so
2748    /// the rail rung stays available everywhere `Cap::NavSplit` is.
2749    NavTabsAdaptive,
2750    /// How a navigation host's presentation follows the window (docs/size-classes.md). All three
2751    /// answers mean something different here, and the difference is who decides:
2752    ///
2753    /// - `Native`: **Day tells the toolkit.** The pieces layer resolves the presentation from
2754    ///   the [`SizeClass`], re-resolves on every change, and sends
2755    ///   [`props::NavPatch::Presentation`]; the toolkit rebuilds its chrome and re-homes the
2756    ///   pages it already has. The desktops and web-dom.
2757    /// - `Emulated`: **the toolkit tells Day.** Its own adaptive container owns the decision
2758    ///   (`UISplitViewController` collapsing as a Pro Max iPhone rotates, `SlidingPaneLayout`
2759    ///   measuring whether both panes fit), so Day must not push a presentation into it: that
2760    ///   would be a second decision racing the platform's own animation. The toolkit
2761    ///   reports what it did with [`Event::NavPresentationChanged`] and Day reconciles.
2762    /// - `Unsupported`: nobody re-presents. The presentation is resolved once, from
2763    ///   [`Cap::NavSplit`] alone, and the window's size never enters into it. A toolkit that
2764    ///   cannot change presentation must not have it decided by something that can, or a window
2765    ///   launched narrow would be stuck stacked with no way back.
2766    NavRepresent,
2767    /// The toolkit places a navigation host's content-list page ([`props::Pane::List`]) in its
2768    /// own pane between the sidebar and the detail, the Mail shape: mailboxes, message list,
2769    /// message (docs/navigation.md). The three answers differ on what happens when the host
2770    /// leaves the split:
2771    ///
2772    /// - `Native`: the pane exists at every presentation. A narrow window collapses the
2773    ///   sidebar but keeps the list beside the detail, exactly as a narrow Mail.app does
2774    ///   (macos-appkit: a `contentList` `NSSplitViewItem`).
2775    /// - `Emulated`: the pane exists while split and merges into the navigation stack when
2776    ///   the host collapses (ios-uikit: `UISplitViewController` triple-column). The pieces
2777    ///   layer then interposes the list between the sidebar root and the detail
2778    ///   ([`props::NavPatch::ListInStack`]) and gates the detail push on the app's
2779    ///   `detail_visible` binding.
2780    /// - `Unsupported`: the backend never sees [`props::Pane::List`] or
2781    ///   [`props::NavProps::list_width`]; the nav piece composes the pane beside (split)
2782    ///   or in place of (stacked) the destination content itself.
2783    NavContentList,
2784    /// The toolkit shows the current destination's title in a native header/bar, so a page
2785    /// needn't repeat it in its own content. `Native` on XAML (the NavigationView header),
2786    /// UIKit (`UINavigationBar`), Android (`MaterialToolbar`), and ArkUI (`NavDestination`
2787    /// title bars). The desktop custom back-headers (AppKit/Qt/web) show a title only in
2788    /// stack mode, so those backends stay `Unsupported` (docs/navigation.md).
2789    NavHeader,
2790    /// The toolkit applies a runtime appearance override (`set_appearance`): native widgets
2791    /// restyle in place and `dark_mode` answers the override. Probe before showing a theme
2792    /// picker; on `Unsupported` backends the call is ignored.
2793    Appearance,
2794    /// The toolkit renders an application menu bar (docs/menus.md), so `app_menu` is visible to
2795    /// the user, and `register_preferences` gets its automatic Settings… item.
2796    ///
2797    /// The question an app asks before deciding where a command lives. Settings is the usual
2798    /// case: on a platform with a menu bar it belongs in the App menu and putting it in the
2799    /// navigation as well is clutter; on one without, the menu is a no-op and a Settings row is
2800    /// the only way in. Distinct from `Cap::Toolbar`: web-dom draws a window toolbar and has no
2801    /// menu bar at all, so keying off the toolbar strands Settings there.
2802    AppMenu,
2803    /// The toolkit can present native alert/confirm/sheet/prompt modals (docs/dialogs.md).
2804    Dialogs,
2805    /// The toolkit can present native open/save file pickers (docs/files.md).
2806    FileDialogs,
2807    /// The toolkit can present a native folder chooser (`PresentSpec::OpenFolder`,
2808    /// docs/files.md). `Native` on the four desktop toolkits (AppKit, GTK, Qt, WinUI); the
2809    /// phone and web backends answer `Unsupported` and resolve the request as `Dismissed`, so
2810    /// an app hides its "Add Folder…" command where this is not `Native`.
2811    FolderDialog,
2812    /// The toolkit runs backend-executed animation for `AnimSpec` intents on
2813    /// `update`/`set_frame`/`set_opacity`/`set_transform` (§8.4). `Unsupported` ⇒ animated calls
2814    /// apply instantly (still correct, just not animated).
2815    Animation,
2816    /// The toolkit presents a `kinds::COVER` node as a native fullscreen modal surface
2817    /// (docs/cover.md). `Unsupported` ⇒ the `cover` piece's content never shows.
2818    Cover,
2819    /// The toolkit presents a `.sheet()` cover as a native modal sheet (AppKit's window sheet,
2820    /// UIKit's page sheet) over the page it covers (docs/cover.md "Modal sheet"). `Unsupported`
2821    /// ⇒ the `cover` piece composes the sheet itself: on a window wider than compact, a card
2822    /// centered over the dimmed page; on a compact one, the full window.
2823    CoverSheet,
2824    /// The toolkit can hide the system status bar while a `status_bar_hidden` subtree is
2825    /// mounted (`Toolkit::set_status_bar_hidden`, docs/cover.md). `Native` on the phone and
2826    /// tablet backends; desktop and web have no status bar, so a setting that offers to hide
2827    /// it should be offered only where this is not `Unsupported`.
2828    StatusBarHidden,
2829    /// The toolkit's `text_area` can be made read-only (`TextAreaProps::editable = false`).
2830    TextEditable,
2831    /// The toolkit's `text_area` selectability can be toggled (`TextAreaProps::selectable`).
2832    /// `Unsupported` where selection is always on (GTK); `Emulated` where the backend
2833    /// collapses native selections itself (XAML, ArkUI).
2834    TextSelectable,
2835    /// The toolkit's `text_area` has built-in spell-check/autocorrect (`TextAreaProps::spellcheck`).
2836    /// `Unsupported` where the toolkit ships none (GTK, Qt, ArkUI).
2837    TextSpellCheck,
2838    /// The toolkit can open additional native OS windows (`Toolkit::open_window`,
2839    /// docs/windows.md). `Native` on the desktop backends and on mobile backends whose
2840    /// platform has a real secondary-window surface (iPad scenes, Android document
2841    /// activities, OHOS multiton abilities). On `Unsupported` backends
2842    /// `day_core::open_window` still works; the content presents as a fullscreen cover in
2843    /// the primary window instead. Probe it to adapt chrome: an `Unsupported` tier has no
2844    /// native title bar or close button, so window content should carry its own close
2845    /// affordance.
2846    MultiWindow,
2847    /// The toolkit can put a count on the app icon (`Toolkit::set_app_badge`, docs/badge.md).
2848    /// `Emulated` where the call is made but the shell may ignore it: desktop Linux, where the
2849    /// Unity launcher protocol is honored by Plasma and Dash-to-Dock but not by stock GNOME.
2850    AppBadgeCount,
2851    /// The toolkit renders `AppBadge::Text` as written. macOS only: `NSDockTile.badgeLabel` is an
2852    /// arbitrary string, while every other platform's badge is a number or nothing.
2853    AppBadgeText,
2854    /// The toolkit can show a valueless indicator (`AppBadge::Dot`).
2855    AppBadgeDot,
2856    /// The toolkit gives a window chrome that persists across pages
2857    /// (`Toolkit::edit_toolbar`, docs/toolbars.md): `Native` on the desktop backends and the
2858    /// phones, `Emulated` on web-dom, `Unsupported` where the only chrome belongs to a page.
2859    ///
2860    /// It no longer decides whether a command can be shown at all: a toolbar item declared on a
2861    /// piece rides that piece's own chrome everywhere. Probe it only for a layout decision that
2862    /// turns on a persistent bar existing.
2863    Toolbar,
2864    /// The window toolbar can hold a search field (docs/search.md): `Native` on the desktop
2865    /// backends, `Emulated` on web-dom. `Unsupported` on the phones, whose bar is a row of actions
2866    /// (an Android app-bar menu, iOS bar buttons, ArkUI title-bar menus): their field goes on the
2867    /// navigation surface instead, so `SearchPlacement::Toolbar` resolves to `Inline` there.
2868    ToolbarSearch,
2869    /// The toolkit realizes `kinds::INSPECTOR` as its own trailing-pane container
2870    /// (docs/inspector.md): an `NSSplitView` inspector pane, a `GtkPaned` with the panel as
2871    /// its end child, a `QDockWidget`, a XAML `SplitView` right pane. `Unsupported` ⇒ the
2872    /// `inspector` piece composes the pane from plain containers instead (same panel, same
2873    /// signal, no native divider), so an unimplemented backend degrades to a drawn pane, not
2874    /// to a hole. Apps normally have no reason to probe this; the piece does.
2875    Inspector,
2876    /// The toolkit realizes `kinds::SPLIT` as its own splitter (docs/split.md): an
2877    /// `NSSplitView`, a `GtkPaned`, a `QSplitter`, each side by side or stacked and with the
2878    /// divider the user drags. `Unsupported` ⇒ the `split` piece composes the two panes and
2879    /// draws and drags the divider itself (the web, the mobile toolkits, XAML), so the piece
2880    /// behaves the same everywhere and only the divider's look is the toolkit's. Apps have no
2881    /// reason to probe this; the piece does.
2882    Split,
2883    /// The toolkit shapes the pointer over a node from the `.cursor()` decorator
2884    /// ([`Toolkit::set_cursor`], docs/cursor.md). `Native` where the platform draws the requested
2885    /// shape from its own set (AppKit, GTK, the DOM, Android's `PointerIcon`), `Emulated` where
2886    /// some shapes map to a nearest neighbor (Qt, XAML) or the platform draws pointer effects
2887    /// rather than shapes (iPadOS), `Unsupported` where nothing changes: a touch-only toolkit,
2888    /// or one whose pointer API Day does not reach yet. Apps ask before offering an affordance
2889    /// that only a cursor reveals, such as a resize handle with no other visual.
2890    Cursor,
2891    /// The toolkit can enumerate the platform's font families with the faces each ships
2892    /// ([`Toolkit::font_families`], docs/fonts.md). `Native` where an OS font database answers
2893    /// (NSFontManager, UIFont, Pango, QFontDatabase, Android's `fonts.xml`,
2894    /// `OH_Drawing_FontMgr`, DirectWrite); `Emulated` where the list is composed rather than
2895    /// read: web-dom answers the CSS generic families plus the bundled `document.fonts`, since
2896    /// a browser exposes no local font list without a permission prompt; `Unsupported` means
2897    /// the list is empty and an app should offer only the default face. Measurement
2898    /// ([`Toolkit::measure_text`]) has no probe: a `None` answer degrades to
2899    /// [`TextMetrics::approximate`]. Probe this before offering a font menu, not before
2900    /// drawing; a [`CanvasFont`] draws everywhere.
2901    FontList,
2902    /// The toolkit reads the user's reduce-motion setting ([`Toolkit::reduce_motion`],
2903    /// docs/accessibility.md) and reports when it changes. `Native` where the platform has the
2904    /// switch and Day reaches it; `Unsupported` where Day reaches none (the app then animates as
2905    /// it would with the setting off, and `DAY_REDUCE_MOTION=1` still forces it on).
2906    ReduceMotion,
2907    /// The toolkit can speak a sentence through the screen reader without moving its focus
2908    /// ([`Toolkit::announce`], docs/accessibility.md): "Saved", "3 results", "Upload failed".
2909    /// `Native` where the platform has an announcement request (`NSAccessibility`'s
2910    /// announcement notification, `UIAccessibility`'s, Android's accessibility event, GTK
2911    /// 4.14's `gtk_accessible_announce`, a WinUI notification event); `Emulated` on the web,
2912    /// where an ARIA live region carries it; `Unsupported` where Day reaches no announcement
2913    /// API yet. An app with a visible status label needs no announcement: screen readers read
2914    /// what changes on screen only when told to, so this is for the change the user cannot
2915    /// otherwise learn about.
2916    Announce,
2917    /// The toolkit can turn encoded image bytes into a native image
2918    /// ([`Toolkit::decode_image`], docs/images.md): what `image(bytes)`, a pasted screenshot and
2919    /// a canvas image all rest on. `Native` wherever the platform decoder takes a buffer;
2920    /// `Unsupported` means only staged asset names draw, so an app should not offer "open an
2921    /// image" at all. Every backend that decodes also answers [`Toolkit::image_info`], so pixel
2922    /// size needs no probe of its own.
2923    ImageDecode,
2924    /// The toolkit can encode a decoded image back to bytes ([`Toolkit::encode_image`]).
2925    /// Which formats it encodes is [`Toolkit::encode_formats`], the same shape as
2926    /// [`Cap::FontList`]/[`Toolkit::font_families`], because "can encode" and "can encode WebP"
2927    /// are different questions and only the second one needs a list.
2928    ImageEncode,
2929    /// The toolkit can read an image's metadata beyond its pixels: EXIF orientation, DPI,
2930    /// capture time ([`Toolkit::image_properties`]). `Native` where a platform metadata reader
2931    /// is already linked (WinRT's `BitmapPropertiesView`, Android's `ExifInterface`);
2932    /// `Unsupported` where reading it would mean shipping a parser or a new framework, which is
2933    /// most places. An app that wants orientation must handle `None`.
2934    ImageProperties,
2935    /// The toolkit can replay a canvas drawing into an offscreen bitmap
2936    /// ([`Toolkit::render_bitmap`], docs/canvas.md "Exporting"): what `Drawing::to_bitmap` and
2937    /// `Drawing::to_png` rest on. `Native` where the toolkit's own canvas painter can target an
2938    /// image surface (a `CGBitmapContext`, a cairo image surface, a `QImage`, an android
2939    /// `Bitmap`, an `OH_Drawing_Bitmap`, a detached `<canvas>`); `Unsupported` where the
2940    /// on-screen canvas has no painter to retarget (WinUI builds XAML shapes instead).
2941    CanvasBitmap,
2942    /// The toolkit can replay canvas drawings into a PDF document ([`Toolkit::render_pdf`],
2943    /// docs/canvas.md "Exporting"), with vector shapes and the platform's own font embedding.
2944    /// `Native` only where the platform ships a PDF writer the canvas painter can draw into
2945    /// (Core Graphics on AppKit and UIKit, cairo on GTK, `QPdfWriter` on Qt, `PdfDocument` on
2946    /// Android); `Unsupported` on ArkUI, the web and WinUI, which have none.
2947    CanvasPdf,
2948    /// The toolkit minimizes, zooms, hides and restores a window on request
2949    /// ([`WindowChange::State`], [`WindowChange::Visible`], docs/windows.md) and reports what the
2950    /// user does through [`Event::WindowStateChanged`]. `Native` on the desktop backends;
2951    /// `Unsupported` on the phones and the web, whose windows the OS sizes.
2952    WindowStates,
2953    /// The toolkit takes a window fullscreen on request and reports when it enters and leaves
2954    /// ([`WindowState::Fullscreen`]). `Native` on the desktops, on Android (system bars hidden
2955    /// through `WindowInsetsController`), on HarmonyOS and on the web (the Fullscreen API, which
2956    /// browsers allow only during a user gesture); `Emulated` on iOS, which hides the status bar
2957    /// and lets the home indicator fade but always keeps the app full-screen anyway.
2958    WindowFullscreen,
2959    /// The toolkit keeps a window out of screenshots, recordings and screen sharing
2960    /// ([`WindowChange::ContentProtected`]). `Native` on macOS (`NSWindowSharingNone`), Windows
2961    /// (`WDA_EXCLUDEFROMCAPTURE`), Android (`FLAG_SECURE`) and HarmonyOS (privacy mode);
2962    /// `Emulated` on iOS, which has no switch for it: Day covers the content while the screen is
2963    /// being recorded or mirrored, but a screenshot still captures it. `Unsupported` on Linux
2964    /// and the web.
2965    ContentProtection,
2966    /// The toolkit honors [`WindowOptions::tabbing`]: macOS window tabs. `Unsupported` everywhere
2967    /// else, where no system window tabs exist.
2968    WindowTabbing,
2969    /// The toolkit shows a Dock menu ([`Toolkit::set_dock_menu`], docs/menus.md): the app's
2970    /// shortcuts and `dock_menu(..)` entries above the system's own items. macOS only.
2971    DockMenu,
2972    /// The toolkit resizes a window and bounds its size on request ([`WindowChange::Frame`]'s
2973    /// size, [`WindowChange::Limits`], [`WindowChange::Resizable`]).
2974    WindowGeometry,
2975    /// The toolkit moves a window to a requested position ([`WindowChange::Frame`]'s origin).
2976    /// `Unsupported` on GTK 4, which removed window positioning, and wherever the compositor owns
2977    /// placement (Wayland).
2978    WindowPosition,
2979    /// The toolkit changes how a window stacks ([`WindowChange::Level`],
2980    /// [`WindowChange::OnAllWorkspaces`], [`WindowChange::SkipTaskbar`]).
2981    WindowLevel,
2982    /// The toolkit gives one window its own light/dark appearance ([`WindowChange::Appearance`]).
2983    /// Where it cannot, the app-wide [`Toolkit::set_appearance`] still applies to every window.
2984    WindowAppearance,
2985    /// The toolkit asks for the user's attention on request ([`WindowChange::RequestAttention`]):
2986    /// a Dock bounce, a flashing taskbar button.
2987    RequestAttention,
2988    /// The toolkit opens a window with no title bar or frame ([`WindowChrome::Frameless`],
2989    /// docs/window-chrome.md). Desktop backends only.
2990    FramelessWindow,
2991    /// The toolkit runs a window's content under its title bar with the window controls kept
2992    /// ([`WindowChrome::Overlay`]) and reports the bar's height as the safe-area top inset.
2993    OverlayTitleBar,
2994    /// The toolkit opens a window whose unpainted pixels show the desktop
2995    /// ([`WindowBackground::Transparent`]).
2996    TransparentWindow,
2997    /// The toolkit puts a translucent system material behind a window
2998    /// ([`WindowBackground::Material`]): macOS's visual-effect materials, Windows 11's Mica and
2999    /// Acrylic. `Emulated` where an approximation stands in.
3000    WindowMaterial,
3001    /// The toolkit lets a piece move its window like a title bar does
3002    /// ([`Toolkit::set_drag_region`], `.window_drag_region()`). `Emulated` on the web, where
3003    /// only an installed app with a window-controls overlay honors it.
3004    DragRegion,
3005    /// The toolkit shows status items ([`Toolkit::set_status_items`], docs/status-item.md): the
3006    /// macOS menu bar, the Windows notification area, a Linux tray. On Linux the answer depends
3007    /// on the desktop: `Native` while a StatusNotifierItem host is running (KDE Plasma, most
3008    /// panels, GNOME with the AppIndicator extension), `Unsupported` without one (stock GNOME),
3009    /// so an app can keep a window instead of vanishing into a tray nobody shows.
3010    StatusItem,
3011    /// The toolkit shows progress on the app's Dock or taskbar icon
3012    /// ([`Toolkit::set_app_progress`]). `Emulated` on Linux, where the Unity launcher protocol is
3013    /// honored by KDE Plasma and Dash to Dock but not by every dock.
3014    AppProgress,
3015    /// The toolkit can hide the app's Dock icon while it runs ([`Toolkit::set_dock_visible`]).
3016    /// macOS only.
3017    DockVisibility,
3018    /// The toolkit lists the displays and their work areas ([`Toolkit::monitors`]). `Emulated`
3019    /// where the one screen the app runs on is reported (a phone, the web).
3020    Monitors,
3021    /// The toolkit shows launcher shortcuts the app sets while it runs
3022    /// ([`Toolkit::set_launcher_shortcuts`]).
3023    DynamicShortcuts,
3024    /// How the toolkit draws a sectioned list's headers (`ListProps::sections`, docs/list.md
3025    /// "Sections"). `Native` where the platform's list has group headers that pin to the top
3026    /// while their section scrolls under them: macos-appkit (`NSTableView` group rows with
3027    /// `floatsGroupRows`) and ios-uikit (plain-style `UITableView` section headers).
3028    /// `Emulated` where the host pins a copy of the current header over the top of the list
3029    /// itself. Headers are unselectable rows on every toolkit, so an app needs this only to
3030    /// describe the difference, never to decide whether to call `.sections`.
3031    ListSections,
3032    /// The toolkit's share chooser carries the app's own actions ([`share::ShareSpec::actions`],
3033    /// docs/sharing.md): Add Bookmark or Find on Page beside the system's targets, each with
3034    /// its title and glyph. `Native` on ios-uikit (a `UIActivity` per action), macos-appkit (an
3035    /// `NSSharingService` per action, offered by the picker's delegate) and android-material
3036    /// on Android 14 and later (`ChooserAction`). `Unsupported` everywhere else: the chooser
3037    /// shows the system's targets only, and the app offers its actions in its own menu.
3038    ShareActions,
3039}
3040
3041impl Cap {
3042    /// Every capability, in declaration order: what a conformance run asks the toolkit about,
3043    /// so the evidence can be held against the declared coverage matrix (docs/testing.md).
3044    pub const ALL: [Cap; 91] = [
3045        Cap::DragDrop,
3046        Cap::DragExternalImport,
3047        Cap::DragExternalExport,
3048        Cap::DragMultipleItems,
3049        Cap::DragFileReferences,
3050        Cap::DragDeferredReceipt,
3051        Cap::DragFilePromises,
3052        Cap::DragExternalMove,
3053        Cap::ListRecycling,
3054        Cap::UndoBridge,
3055        Cap::EditBridge,
3056        Cap::ListReorder,
3057        Cap::NavReorder,
3058        Cap::ListDelete,
3059        Cap::ListSwipeActions,
3060        Cap::Tree,
3061        Cap::TreeMove,
3062        Cap::BaselineAlignment,
3063        Cap::TextRuns,
3064        Cap::TextLinks,
3065        Cap::Lottie,
3066        Cap::NativeSymbols,
3067        Cap::Snapshot,
3068        Cap::NavSplit,
3069        Cap::NavTabs,
3070        Cap::NavTabsAdaptive,
3071        Cap::NavRepresent,
3072        Cap::NavContentList,
3073        Cap::NavHeader,
3074        Cap::Appearance,
3075        Cap::AppMenu,
3076        Cap::Dialogs,
3077        Cap::FileDialogs,
3078        Cap::Animation,
3079        Cap::Cover,
3080        Cap::StatusBarHidden,
3081        Cap::TextEditable,
3082        Cap::TextSelectable,
3083        Cap::TextSpellCheck,
3084        Cap::MultiWindow,
3085        Cap::AppBadgeCount,
3086        Cap::AppBadgeText,
3087        Cap::AppBadgeDot,
3088        Cap::Toolbar,
3089        Cap::ToolbarSearch,
3090        Cap::Inspector,
3091        Cap::Cursor,
3092        Cap::FontList,
3093        Cap::ReduceMotion,
3094        Cap::Announce,
3095        Cap::ImageDecode,
3096        Cap::ImageEncode,
3097        Cap::ImageProperties,
3098        Cap::WindowStates,
3099        Cap::WindowFullscreen,
3100        Cap::ContentProtection,
3101        Cap::WindowTabbing,
3102        Cap::DockMenu,
3103        Cap::WindowGeometry,
3104        Cap::WindowPosition,
3105        Cap::WindowLevel,
3106        Cap::WindowAppearance,
3107        Cap::RequestAttention,
3108        Cap::FramelessWindow,
3109        Cap::OverlayTitleBar,
3110        Cap::TransparentWindow,
3111        Cap::WindowMaterial,
3112        Cap::DragRegion,
3113        Cap::StatusItem,
3114        Cap::AppProgress,
3115        Cap::DockVisibility,
3116        Cap::Monitors,
3117        Cap::DynamicShortcuts,
3118        Cap::Split,
3119        Cap::TreeSections,
3120        Cap::CoverSheet,
3121        Cap::ListEditing,
3122        Cap::ListItem,
3123        Cap::CanvasBitmap,
3124        Cap::CanvasPdf,
3125        Cap::SearchField,
3126        Cap::ComboBox,
3127        Cap::Stepper,
3128        Cap::DateTimePicker,
3129        Cap::ColorPicker,
3130        Cap::PullRefresh,
3131        Cap::Pager,
3132        Cap::PullRefreshGesture,
3133        Cap::FolderDialog,
3134        Cap::ListSections,
3135        Cap::ShareActions,
3136    ];
3137
3138    /// The capability's place in [`Cap::ALL`]. Exhaustive, so a new variant fails to compile
3139    /// here until it is given one, and the unit test below then holds `ALL` to it.
3140    pub const fn ordinal(self) -> usize {
3141        match self {
3142            Cap::DragDrop => 0,
3143            Cap::DragExternalImport => 1,
3144            Cap::DragExternalExport => 2,
3145            Cap::DragMultipleItems => 3,
3146            Cap::DragFileReferences => 4,
3147            Cap::DragDeferredReceipt => 5,
3148            Cap::DragFilePromises => 6,
3149            Cap::DragExternalMove => 7,
3150            Cap::ListRecycling => 8,
3151            Cap::UndoBridge => 9,
3152            Cap::EditBridge => 10,
3153            Cap::ListReorder => 11,
3154            Cap::NavReorder => 12,
3155            Cap::ListDelete => 13,
3156            Cap::ListSwipeActions => 14,
3157            Cap::Tree => 15,
3158            Cap::TreeMove => 16,
3159            Cap::BaselineAlignment => 17,
3160            Cap::TextRuns => 18,
3161            Cap::TextLinks => 19,
3162            Cap::Lottie => 20,
3163            Cap::NativeSymbols => 21,
3164            Cap::Snapshot => 22,
3165            Cap::NavSplit => 23,
3166            Cap::NavTabs => 24,
3167            Cap::NavTabsAdaptive => 25,
3168            Cap::NavRepresent => 26,
3169            Cap::NavContentList => 27,
3170            Cap::NavHeader => 28,
3171            Cap::Appearance => 29,
3172            Cap::AppMenu => 30,
3173            Cap::Dialogs => 31,
3174            Cap::FileDialogs => 32,
3175            Cap::Animation => 33,
3176            Cap::Cover => 34,
3177            Cap::StatusBarHidden => 35,
3178            Cap::TextEditable => 36,
3179            Cap::TextSelectable => 37,
3180            Cap::TextSpellCheck => 38,
3181            Cap::MultiWindow => 39,
3182            Cap::AppBadgeCount => 40,
3183            Cap::AppBadgeText => 41,
3184            Cap::AppBadgeDot => 42,
3185            Cap::Toolbar => 43,
3186            Cap::ToolbarSearch => 44,
3187            Cap::Inspector => 45,
3188            Cap::Cursor => 46,
3189            Cap::FontList => 47,
3190            Cap::ReduceMotion => 48,
3191            Cap::Announce => 49,
3192            Cap::ImageDecode => 50,
3193            Cap::ImageEncode => 51,
3194            Cap::ImageProperties => 52,
3195            Cap::WindowStates => 53,
3196            Cap::WindowFullscreen => 54,
3197            Cap::ContentProtection => 55,
3198            Cap::WindowTabbing => 56,
3199            Cap::DockMenu => 57,
3200            Cap::WindowGeometry => 58,
3201            Cap::WindowPosition => 59,
3202            Cap::WindowLevel => 60,
3203            Cap::WindowAppearance => 61,
3204            Cap::RequestAttention => 62,
3205            Cap::FramelessWindow => 63,
3206            Cap::OverlayTitleBar => 64,
3207            Cap::TransparentWindow => 65,
3208            Cap::WindowMaterial => 66,
3209            Cap::DragRegion => 67,
3210            Cap::StatusItem => 68,
3211            Cap::AppProgress => 69,
3212            Cap::DockVisibility => 70,
3213            Cap::Monitors => 71,
3214            Cap::DynamicShortcuts => 72,
3215            Cap::Split => 73,
3216            Cap::TreeSections => 74,
3217            Cap::CoverSheet => 75,
3218            Cap::ListEditing => 76,
3219            Cap::ListItem => 77,
3220            Cap::CanvasBitmap => 78,
3221            Cap::CanvasPdf => 79,
3222            Cap::SearchField => 80,
3223            Cap::ComboBox => 81,
3224            Cap::Stepper => 82,
3225            Cap::DateTimePicker => 83,
3226            Cap::ColorPicker => 84,
3227            Cap::PullRefresh => 85,
3228            Cap::Pager => 86,
3229            Cap::PullRefreshGesture => 87,
3230            Cap::FolderDialog => 88,
3231            Cap::ListSections => 89,
3232            Cap::ShareActions => 90,
3233        }
3234    }
3235}
3236
3237// ---------------------------------------------------------------------------
3238// Raster images (docs/images.md): the currency shared by the `image` piece, the canvas, and
3239// the decode/metadata/encode duties below.
3240// ---------------------------------------------------------------------------
3241
3242/// A decoded image the toolkit holds, addressed by an id day-core mints.
3243///
3244/// Opaque, because what sits behind it is an `NSImage`, a `UIImage`, a `GdkTexture`, a
3245/// `QPixmap`, a `BitmapImage`, an android `Bitmap` or an `ImageBitmap`, and none of those cross
3246/// the boundary. The id is released through [`Toolkit::release_image`] when the app's handle
3247/// drops, so a backend's side table never outlives the app's interest in it.
3248#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
3249pub struct BitmapId(pub u64);
3250
3251/// An encoded image format: what [`BitmapInfo::format`] reports and [`EncodeSpec::format`] asks
3252/// for. Not every backend encodes every one: ask [`Toolkit::encode_formats`] (the
3253/// [`Cap::ImageEncode`] pair of [`Toolkit::font_families`]/[`Cap::FontList`]) rather than
3254/// assuming.
3255#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default)]
3256pub enum ImageFormat {
3257    #[default]
3258    Png,
3259    Jpeg,
3260    Webp,
3261    Gif,
3262    Bmp,
3263    Tiff,
3264    /// HEIF/HEIC, Apple's camera format; decodable on the Apple backends and Android, and
3265    /// encodable almost nowhere.
3266    Heif,
3267    /// Decoded from bytes whose magic numbers [`ImageFormat::sniff`] does not know. A backend may
3268    /// still decode it: the platform decoders read more formats than Day names.
3269    Unknown,
3270}
3271
3272impl ImageFormat {
3273    /// The IANA media type, which is also the string the ArkUI packer, GDI+ and the browser's
3274    /// `toBlob` take. `Unknown` answers `application/octet-stream`.
3275    pub fn mime(self) -> &'static str {
3276        match self {
3277            ImageFormat::Png => "image/png",
3278            ImageFormat::Jpeg => "image/jpeg",
3279            ImageFormat::Webp => "image/webp",
3280            ImageFormat::Gif => "image/gif",
3281            ImageFormat::Bmp => "image/bmp",
3282            ImageFormat::Tiff => "image/tiff",
3283            ImageFormat::Heif => "image/heif",
3284            ImageFormat::Unknown => "application/octet-stream",
3285        }
3286    }
3287
3288    /// The pixel size the encoded bytes declare, read from the container's own header
3289    /// (docs/images.md).
3290    ///
3291    /// Every backend that decodes natively reports its own dimensions; this exists for the one
3292    /// that cannot. The XAML backend's (`windows-winui`) `BitmapImage` learns its size
3293    /// asynchronously, only once the element has been shown, so a synchronous `image_info` there
3294    /// would have nothing to say.
3295    /// Reading the header instead gives the same answer the decoder would, before any decoding.
3296    ///
3297    /// `None` when the header is absent, truncated, or a container this does not parse.
3298    pub fn dimensions(bytes: &[u8]) -> Option<(u32, u32)> {
3299        let be16 = |i: usize| -> Option<u32> {
3300            Some(u32::from(u16::from_be_bytes([
3301                *bytes.get(i)?,
3302                *bytes.get(i + 1)?,
3303            ])))
3304        };
3305        let le16 = |i: usize| -> Option<u32> {
3306            Some(u32::from(u16::from_le_bytes([
3307                *bytes.get(i)?,
3308                *bytes.get(i + 1)?,
3309            ])))
3310        };
3311        let be32 = |i: usize| -> Option<u32> {
3312            Some(u32::from_be_bytes([
3313                *bytes.get(i)?,
3314                *bytes.get(i + 1)?,
3315                *bytes.get(i + 2)?,
3316                *bytes.get(i + 3)?,
3317            ]))
3318        };
3319        let le32 = |i: usize| -> Option<u32> {
3320            Some(u32::from_le_bytes([
3321                *bytes.get(i)?,
3322                *bytes.get(i + 1)?,
3323                *bytes.get(i + 2)?,
3324                *bytes.get(i + 3)?,
3325            ]))
3326        };
3327        match Self::sniff(bytes)? {
3328            // IHDR is always the first chunk: 8-byte signature, 4-byte length, 4-byte type.
3329            ImageFormat::Png => Some((be32(16)?, be32(20)?)),
3330            // The logical screen descriptor follows the 6-byte version stamp, little-endian.
3331            ImageFormat::Gif => Some((le16(6)?, le16(8)?)),
3332            // The DIB header's width/height are signed; a negative height is a top-down bitmap.
3333            ImageFormat::Bmp => Some((
3334                le32(18)?.cast_signed().unsigned_abs(),
3335                le32(22)?.cast_signed().unsigned_abs(),
3336            )),
3337            // Walk the segment chain to the frame header. Every SOF marker carries the size at
3338            // the same offsets; the arithmetic-coded and progressive ones are SOFs too, which is
3339            // why this matches the whole range rather than SOF0 alone. DNL/DHP (0xC4, 0xC8,
3340            // 0xCC) are not frame headers and are skipped like any other segment.
3341            ImageFormat::Jpeg => {
3342                let mut i = 2usize;
3343                // `<=`, not `<`: a frame header that ends the buffer is still a frame header, and
3344                // the size sits in its last four bytes.
3345                while i + 9 <= bytes.len() {
3346                    if bytes[i] != 0xFF {
3347                        i += 1;
3348                        continue;
3349                    }
3350                    let marker = bytes[i + 1];
3351                    // Padding fill bytes and the standalone markers carry no length.
3352                    if marker == 0xFF || (0xD0..=0xD9).contains(&marker) || marker == 0x01 {
3353                        i += 1;
3354                        continue;
3355                    }
3356                    let is_sof = (0xC0..=0xCF).contains(&marker)
3357                        && marker != 0xC4
3358                        && marker != 0xC8
3359                        && marker != 0xCC;
3360                    if is_sof {
3361                        // [marker][len:2][precision:1][height:2][width:2]
3362                        return Some((be16(i + 7)?, be16(i + 5)?));
3363                    }
3364                    i += 2 + be16(i + 2)? as usize;
3365                }
3366                None
3367            }
3368            // RIFF: a 12-byte header, then a chunk id. VP8X states the size minus one in 24-bit
3369            // little-endian; lossy VP8 hides it in the 14 low bits after the start code; lossless
3370            // VP8L packs width-1 and height-1 into 14 bits each across four bytes.
3371            ImageFormat::Webp => match bytes.get(12..16)? {
3372                b"VP8X" => {
3373                    let w = u32::from(*bytes.get(24)?)
3374                        | u32::from(*bytes.get(25)?) << 8
3375                        | u32::from(*bytes.get(26)?) << 16;
3376                    let h = u32::from(*bytes.get(27)?)
3377                        | u32::from(*bytes.get(28)?) << 8
3378                        | u32::from(*bytes.get(29)?) << 16;
3379                    Some((w + 1, h + 1))
3380                }
3381                b"VP8 " => Some((le16(26)? & 0x3FFF, le16(28)? & 0x3FFF)),
3382                b"VP8L" => {
3383                    let bits = le32(21)?;
3384                    Some(((bits & 0x3FFF) + 1, ((bits >> 14) & 0x3FFF) + 1))
3385                }
3386                _ => None,
3387            },
3388            // TIFF's IFD is a pointer chase and HEIF's is a box tree; neither is worth parsing
3389            // here, because every backend that reads them decodes natively and answers for itself.
3390            ImageFormat::Tiff | ImageFormat::Heif | ImageFormat::Unknown => None,
3391        }
3392    }
3393
3394    /// The format `bytes` begins with, by magic number: enough to fill [`BitmapInfo::format`]
3395    /// on every backend, including the ones whose decoder never says what it decoded.
3396    ///
3397    /// Hand-rolled rather than a crate: it is a dozen byte comparisons against fixed prefixes,
3398    /// and the alternative is an image-decoding dependency in the one crate that must stay
3399    /// dependency-free.
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.
3535pub fn export_pixels(size: Size, scale: f64) -> (u32, u32) {
3536    let side = |v: f64| (v * scale).ceil().clamp(0.0, u32::MAX as f64) as u32;
3537    (side(size.width), side(size.height))
3538}
3539
3540/// One page of a PDF [`Toolkit::render_pdf`] writes: the page size in PDF points (1/72 inch,
3541/// the same unit as canvas points) and the ops to replay onto it, origin top-left.
3542#[derive(Clone, Debug, PartialEq)]
3543pub struct PdfPage {
3544    pub size: Size,
3545    pub ops: Vec<DrawOp>,
3546}
3547
3548/// The document information a PDF carries. A backend whose writer has no metadata API (Android's
3549/// `PdfDocument`) ignores it.
3550#[derive(Clone, Debug, Default, PartialEq)]
3551pub struct PdfInfo {
3552    pub title: Option<String>,
3553    pub author: Option<String>,
3554}
3555
3556/// Why a canvas export could not answer (docs/canvas.md "Exporting").
3557#[derive(Clone, Debug, PartialEq)]
3558pub enum ExportError {
3559    /// This toolkit has no path for the export (probe [`Cap::CanvasBitmap`] /
3560    /// [`Cap::CanvasPdf`]).
3561    Unsupported,
3562    /// The bitmap would exceed [`EXPORT_MAX_SIDE`] or [`EXPORT_MAX_PIXELS`]; checked in
3563    /// day-core before the toolkit runs. The size is the one that was refused, in pixels.
3564    TooLarge { width: u32, height: u32 },
3565    /// A zero, negative or non-finite size or scale, or a PDF with no pages.
3566    Invalid,
3567    /// The platform refused (out of memory, a writer error); the text is the platform's.
3568    Failed(String),
3569}
3570
3571impl std::fmt::Display for ExportError {
3572    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3573        match self {
3574            ExportError::Unsupported => write!(f, "this export is unavailable on this backend"),
3575            ExportError::TooLarge { width, height } => {
3576                write!(
3577                    f,
3578                    "a {width} × {height} pixel bitmap is too large to render"
3579                )
3580            }
3581            ExportError::Invalid => write!(f, "the drawing has no size or the PDF has no pages"),
3582            ExportError::Failed(why) => write!(f, "rendering failed: {why}"),
3583        }
3584    }
3585}
3586
3587impl std::error::Error for ExportError {}
3588
3589/// Where a raster image's pixels come from (docs/images.md).
3590///
3591/// One currency for both halves of the same question: `Named` is the staged asset every
3592/// `image(res::images::…)` has always drawn, `Bytes` is an encoded PNG/JPEG the app already
3593/// holds (a download, a file the user picked, a clipboard paste), and `Decoded` names an image
3594/// the toolkit decoded once so several nodes (and the canvas) share it.
3595#[derive(Clone)]
3596pub enum ImageSource {
3597    /// A staged asset name, resolved through the backend's own pipeline (§18.2).
3598    Named(String),
3599    /// Encoded bytes (PNG/JPEG/…) the app owns, decoded by the platform's own decoder. Shared
3600    /// rather than copied: handing over a new buffer is a refcount bump.
3601    Bytes(std::sync::Arc<Vec<u8>>),
3602    /// An image already decoded through [`Toolkit::decode_image`].
3603    Decoded(BitmapId),
3604}
3605
3606impl Default for ImageSource {
3607    fn default() -> Self {
3608        ImageSource::Named(String::new())
3609    }
3610}
3611
3612/// Bytes compare by identity, not content.
3613///
3614/// This is the equality a binding gates on (§4.2), so it runs on every evaluation, and
3615/// comparing two multi-megabyte buffers byte by byte would cost far more than the redundant
3616/// decode it saves. Handing over a distinct buffer holding the same pixels therefore re-decodes,
3617/// which is the same trade `Arc::ptr_eq` makes wherever else Day carries shared buffers.
3618impl PartialEq for ImageSource {
3619    fn eq(&self, other: &Self) -> bool {
3620        match (self, other) {
3621            (ImageSource::Named(a), ImageSource::Named(b)) => a == b,
3622            (ImageSource::Bytes(a), ImageSource::Bytes(b)) => std::sync::Arc::ptr_eq(a, b),
3623            (ImageSource::Decoded(a), ImageSource::Decoded(b)) => a == b,
3624            _ => false,
3625        }
3626    }
3627}
3628
3629/// Logs the buffer's length, never its contents: a `Debug` that dumped a megabyte of pixels
3630/// into a trace line would make the trace useless and slow.
3631impl std::fmt::Debug for ImageSource {
3632    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3633        match self {
3634            ImageSource::Named(n) => f.debug_tuple("Named").field(n).finish(),
3635            ImageSource::Bytes(b) => f.debug_tuple("Bytes").field(&b.len()).finish(),
3636            ImageSource::Decoded(id) => f.debug_tuple("Decoded").field(&id.0).finish(),
3637        }
3638    }
3639}
3640
3641impl From<BitmapId> for ImageSource {
3642    fn from(id: BitmapId) -> Self {
3643        ImageSource::Decoded(id)
3644    }
3645}
3646
3647/// A staged asset name is a source, so `image(res::images::cover)` keeps compiling unchanged.
3648///
3649/// There is no `From<&str>` here, for the same reason [`resource::ImageName`] has none:
3650/// `image("typo")` must stay a compile error rather than a blank view at runtime (resource.rs).
3651/// A path or URL string is not a source either: read the bytes and hand those over.
3652impl From<resource::ImageName> for ImageSource {
3653    fn from(name: resource::ImageName) -> Self {
3654        ImageSource::Named(name.as_str().to_owned())
3655    }
3656}
3657
3658impl From<resource::VectorName> for ImageSource {
3659    fn from(name: resource::VectorName) -> Self {
3660        ImageSource::Named(name.as_str().to_owned())
3661    }
3662}
3663
3664impl From<std::sync::Arc<Vec<u8>>> for ImageSource {
3665    fn from(bytes: std::sync::Arc<Vec<u8>>) -> Self {
3666        ImageSource::Bytes(bytes)
3667    }
3668}
3669
3670/// An owned string is a name, not bytes: the same conversion [`resource::ImageName`] offers for
3671/// a name computed at runtime, and the reason `image(some_string)` keeps compiling. A `&str`
3672/// still converts nowhere, so `image("typo")` stays a compile error (resource.rs).
3673impl From<String> for ImageSource {
3674    fn from(name: String) -> Self {
3675        ImageSource::Named(name)
3676    }
3677}
3678
3679impl From<Vec<u8>> for ImageSource {
3680    fn from(bytes: Vec<u8>) -> Self {
3681        ImageSource::Bytes(std::sync::Arc::new(bytes))
3682    }
3683}
3684
3685#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
3686pub enum Support {
3687    Native,
3688    Emulated,
3689    /// The default: what an unimplemented capability answers everywhere.
3690    #[default]
3691    Unsupported,
3692}
3693
3694/// What a text field collects (`text_field(..).input_purpose(_)`, docs/textfield.md).
3695///
3696/// One word for everything a platform keys off the kind of text: the on-screen keyboard's
3697/// layout, capitalization and correction, and the credential or contact the system offers to
3698/// fill in. A backend applies the parts its toolkit has: a desktop toolkit with no on-screen
3699/// keyboard still takes the autofill and correction half.
3700///
3701/// Purpose is independent of [`InputTraits::secure`]: a numeric PIN is `Number` and secure.
3702#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
3703pub enum InputPurpose {
3704    /// Free text: the default keyboard, with the platform's own capitalization and correction.
3705    #[default]
3706    Text,
3707    /// A person's name: words capitalized, never corrected.
3708    Name,
3709    /// An email address: the `@` keyboard, never capitalized or corrected.
3710    Email,
3711    /// A web address: the URL keyboard, never capitalized or corrected.
3712    Url,
3713    /// A telephone number: the phone pad.
3714    Phone,
3715    /// A whole number: the digit pad.
3716    Number,
3717    /// A number with a fractional part: the digit pad with a decimal separator.
3718    Decimal,
3719    /// An account name: never capitalized or corrected, and offered to the password manager.
3720    Username,
3721    /// An existing password, offered to the password manager for filling.
3722    Password,
3723    /// A password being chosen, so the password manager offers to make and save one.
3724    NewPassword,
3725    /// A code sent by message or mail, which the keyboard offers as it arrives. The keyboard
3726    /// stays the text one, since a code can carry letters.
3727    OneTimeCode,
3728}
3729
3730/// The on-screen keyboard's action key (`text_field(..).submit_label(_)`, docs/textfield.md).
3731///
3732/// The key always fires the field's `on_submit`; this names what it promises. A toolkit with
3733/// no on-screen keyboard ignores it.
3734#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
3735pub enum SubmitLabel {
3736    /// The platform's own key (Return).
3737    #[default]
3738    Return,
3739    Done,
3740    Go,
3741    Next,
3742    Search,
3743    Send,
3744}
3745
3746/// How a text field takes its text (docs/textfield.md): the whole set travels together through
3747/// [`Toolkit::set_input_traits`], so a backend that has to rebuild the widget for one member
3748/// has every other member in hand to dress the replacement.
3749#[derive(Clone, Debug, Default, PartialEq, Eq)]
3750pub struct InputTraits {
3751    /// Hide the characters (a password field).
3752    pub secure: bool,
3753    /// Show and select the text, take no edits.
3754    pub read_only: bool,
3755    pub purpose: InputPurpose,
3756    pub submit_label: SubmitLabel,
3757    /// The most characters (Unicode scalar values) the field takes; `None` is unbounded.
3758    /// day-pieces holds the bound on every backend. A toolkit applies its native limit as well
3759    /// only where that limit counts the same unit (GTK): one that counts UTF-16 units would
3760    /// refuse characters the bound allows.
3761    pub max_length: Option<u32>,
3762}
3763
3764/// The pointer's shape over a piece (the `.cursor()` decorator, docs/cursor.md).
3765///
3766/// The named variants are the CSS cursor vocabulary: the largest set any toolkit accepts as it
3767/// is (GTK and the DOM take the names verbatim), and every other toolkit's set is a subset of it
3768/// or maps onto it. A backend draws its own shape for each name, or the nearest one it has, and
3769/// answers [`Cap::Cursor`] with how faithful that is. [`Cursor::Native`] reaches a shape only one
3770/// toolkit names; the `day::cursor::<toolkit>` modules carry those as constants, gated on that
3771/// toolkit's feature, and every other backend ignores a name it does not know.
3772///
3773/// A cursor applies to the node and its descendants until a descendant sets its own.
3774/// [`Cursor::Default`] hands the shape back to the platform rather than pinning an arrow, so a
3775/// reactive cursor can release what it took.
3776#[derive(Clone, Debug, PartialEq, Eq, Hash, Default)]
3777pub enum Cursor {
3778    /// The platform default (an arrow), and the value that releases a node's cursor.
3779    #[default]
3780    Default,
3781    /// A pointing hand: links and other tap-to-activate content.
3782    Pointer,
3783    /// An I-beam over editable or selectable text.
3784    Text,
3785    /// An I-beam for vertical text.
3786    VerticalText,
3787    Crosshair,
3788    /// Four-way move.
3789    Move,
3790    /// An open hand: content that can be dragged.
3791    Grab,
3792    /// A closed hand: content being dragged.
3793    Grabbing,
3794    NotAllowed,
3795    /// The app is busy and cannot take input.
3796    Wait,
3797    /// The app is busy but still takes input.
3798    Progress,
3799    Help,
3800    ContextMenu,
3801    /// A drop will copy.
3802    Copy,
3803    /// A drop will link.
3804    Alias,
3805    /// A table cell.
3806    Cell,
3807    ZoomIn,
3808    ZoomOut,
3809    /// No pointer at all.
3810    None,
3811    /// Vertical (north–south) resize.
3812    NsResize,
3813    /// Horizontal (east–west) resize.
3814    EwResize,
3815    /// Diagonal resize, north-east to south-west.
3816    NeswResize,
3817    /// Diagonal resize, north-west to south-east.
3818    NwseResize,
3819    ColResize,
3820    RowResize,
3821    /// A toolkit's own named cursor, resolved by that backend's lookup and ignored by every
3822    /// other. Prefer the `day::cursor::<toolkit>` constants, which are gated on the toolkit.
3823    Native(std::borrow::Cow<'static, str>),
3824}
3825
3826impl Cursor {
3827    /// A toolkit-specific cursor by its native name (see [`Cursor::Native`]).
3828    pub const fn native(name: &'static str) -> Self {
3829        Cursor::Native(std::borrow::Cow::Borrowed(name))
3830    }
3831
3832    /// The CSS keyword for a named cursor, which GTK and the DOM take as it is. A native cursor
3833    /// answers its own name, so a backend keyed on CSS names may still recognize it.
3834    pub fn css_name(&self) -> &str {
3835        match self {
3836            Cursor::Default => "default",
3837            Cursor::Pointer => "pointer",
3838            Cursor::Text => "text",
3839            Cursor::VerticalText => "vertical-text",
3840            Cursor::Crosshair => "crosshair",
3841            Cursor::Move => "move",
3842            Cursor::Grab => "grab",
3843            Cursor::Grabbing => "grabbing",
3844            Cursor::NotAllowed => "not-allowed",
3845            Cursor::Wait => "wait",
3846            Cursor::Progress => "progress",
3847            Cursor::Help => "help",
3848            Cursor::ContextMenu => "context-menu",
3849            Cursor::Copy => "copy",
3850            Cursor::Alias => "alias",
3851            Cursor::Cell => "cell",
3852            Cursor::ZoomIn => "zoom-in",
3853            Cursor::ZoomOut => "zoom-out",
3854            Cursor::None => "none",
3855            Cursor::NsResize => "ns-resize",
3856            Cursor::EwResize => "ew-resize",
3857            Cursor::NeswResize => "nesw-resize",
3858            Cursor::NwseResize => "nwse-resize",
3859            Cursor::ColResize => "col-resize",
3860            Cursor::RowResize => "row-resize",
3861            Cursor::Native(name) => name,
3862        }
3863    }
3864
3865    /// Every named cursor, in declaration order, what a gallery or a test walks.
3866    pub const NAMED: [Cursor; 25] = [
3867        Cursor::Default,
3868        Cursor::Pointer,
3869        Cursor::Text,
3870        Cursor::VerticalText,
3871        Cursor::Crosshair,
3872        Cursor::Move,
3873        Cursor::Grab,
3874        Cursor::Grabbing,
3875        Cursor::NotAllowed,
3876        Cursor::Wait,
3877        Cursor::Progress,
3878        Cursor::Help,
3879        Cursor::ContextMenu,
3880        Cursor::Copy,
3881        Cursor::Alias,
3882        Cursor::Cell,
3883        Cursor::ZoomIn,
3884        Cursor::ZoomOut,
3885        Cursor::None,
3886        Cursor::NsResize,
3887        Cursor::EwResize,
3888        Cursor::NeswResize,
3889        Cursor::NwseResize,
3890        Cursor::ColResize,
3891        Cursor::RowResize,
3892    ];
3893}
3894
3895/// A set of screen edges, for the `defers_system_gestures` modifier (docs/cover.md). Mirrors
3896/// SwiftUI's `Edge.Set`: on iOS these map to `UIRectEdge` for
3897/// `preferredScreenEdgesDeferringSystemGestures`; on Android any non-empty set enters
3898/// swipe-to-reveal immersive mode (the closest platform analogue).
3899#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
3900pub struct Edges(pub u8);
3901
3902impl Edges {
3903    pub const NONE: Edges = Edges(0);
3904    pub const TOP: Edges = Edges(1);
3905    pub const BOTTOM: Edges = Edges(2);
3906    pub const LEADING: Edges = Edges(4);
3907    pub const TRAILING: Edges = Edges(8);
3908    pub const ALL: Edges = Edges(15);
3909
3910    pub fn contains(self, other: Edges) -> bool {
3911        self.0 & other.0 == other.0
3912    }
3913    pub fn union(self, other: Edges) -> Edges {
3914        Edges(self.0 | other.0)
3915    }
3916    pub fn is_empty(self) -> bool {
3917        self.0 == 0
3918    }
3919}
3920
3921impl std::ops::BitOr for Edges {
3922    type Output = Edges;
3923    fn bitor(self, rhs: Edges) -> Edges {
3924        self.union(rhs)
3925    }
3926}
3927
3928/// The timing curve of an animation (§8.4). Native backends map each variant onto their own
3929/// easing (`CAMediaTimingFunction`, `QEasingCurve`, ArkUI `ARKUI_CURVE_*`, spring animators); the
3930/// canvas/self-driven path samples it via [`Curve::fraction`]. `Spring` matches SwiftUI's
3931/// `.spring(response:dampingFraction:)`.
3932#[derive(Clone, Copy, Debug, PartialEq)]
3933pub enum Curve {
3934    Linear,
3935    EaseIn,
3936    EaseOut,
3937    EaseInOut,
3938    /// `response` = approximate settling period (seconds); `damping` = damping ratio (1.0 =
3939    /// critically damped, `<1` = bouncy overshoot).
3940    Spring {
3941        response: f64,
3942        damping: f64,
3943    },
3944}
3945
3946impl Curve {
3947    /// Fraction of the transition complete at `elapsed` seconds (0 at start, reaching 1, or
3948    /// overshooting it for an under-damped spring). Easing curves clamp to `duration`; springs
3949    /// evaluate their analytic unit-step response and use `duration` only as a settle cap. Drives
3950    /// the self-driven/canvas path; native backends interpolate on their own compositor instead.
3951    pub fn fraction(self, elapsed: f64, duration: f64) -> f64 {
3952        match self {
3953            Curve::Spring { response, damping } => spring_step(response, damping, elapsed),
3954            _ => {
3955                let t = if duration <= 0.0 {
3956                    1.0
3957                } else {
3958                    (elapsed / duration).clamp(0.0, 1.0)
3959                };
3960                self.ease(t)
3961            }
3962        }
3963    }
3964
3965    /// Eased progress for normalized `t` in `0.0..=1.0` (springs pass through; use [`Self::fraction`]).
3966    #[inline]
3967    pub fn ease(self, t: f64) -> f64 {
3968        match self {
3969            Curve::Linear | Curve::Spring { .. } => t,
3970            Curve::EaseIn => t * t,
3971            Curve::EaseOut => 1.0 - (1.0 - t) * (1.0 - t),
3972            Curve::EaseInOut => t * t * (3.0 - 2.0 * t), // smoothstep
3973        }
3974    }
3975
3976    /// Whether the transition has settled, so the canvas frame clock can stop ticking it.
3977    pub fn is_settled(self, elapsed: f64, duration: f64) -> bool {
3978        match self {
3979            Curve::Spring { response, damping } => {
3980                let cap = response.max(0.0) * 4.0 + 0.2;
3981                if elapsed >= cap {
3982                    return true;
3983                }
3984                (spring_step(response, damping, elapsed) - 1.0).abs() < 0.001
3985                    && elapsed > response * 0.5
3986            }
3987            _ => elapsed >= duration.max(0.0),
3988        }
3989    }
3990}
3991
3992/// Unit-step response of a second-order spring (`response` = period seconds, `damping` = ratio),
3993/// evaluated at `t` seconds. Under-damped rings and overshoots; critically/over-damped eases in.
3994fn spring_step(response: f64, damping: f64, t: f64) -> f64 {
3995    if response <= 0.0 || t <= 0.0 {
3996        return if t <= 0.0 { 0.0 } else { 1.0 };
3997    }
3998    let omega0 = std::f64::consts::TAU / response;
3999    let zeta = damping.max(0.0);
4000    if zeta < 1.0 {
4001        let omega_d = omega0 * (1.0 - zeta * zeta).sqrt();
4002        let e = (-zeta * omega0 * t).exp();
4003        1.0 - e * ((omega_d * t).cos() + (zeta * omega0 / omega_d) * (omega_d * t).sin())
4004    } else {
4005        let e = (-omega0 * t).exp();
4006        1.0 - e * (1.0 + omega0 * t)
4007    }
4008}
4009
4010/// Animation intent (§8.4). Native-widget backends map it onto their own animator (Core Animation,
4011/// `ViewPropertyAnimator`, XAML Composition, `OH_ArkUI_AnimateTo`, …); the canvas/self-driven path
4012/// samples `curve` via [`Curve::fraction`]. Threaded through `Toolkit::update`/`set_frame`/
4013/// `set_opacity`/`set_transform`.
4014#[derive(Clone, Copy, Debug, PartialEq)]
4015pub struct AnimSpec {
4016    pub duration_ms: u32,
4017    pub delay_ms: u32,
4018    pub curve: Curve,
4019    /// Repeat count beyond the first play (`0` = play once); `u32::MAX` = repeat forever.
4020    pub repeat: u32,
4021    pub autoreverse: bool,
4022}
4023
4024impl Default for AnimSpec {
4025    /// The default feel: a smooth spring (SwiftUI's modern default).
4026    fn default() -> Self {
4027        AnimSpec {
4028            duration_ms: 350,
4029            delay_ms: 0,
4030            curve: Curve::Spring {
4031                response: 0.4,
4032                damping: 0.8,
4033            },
4034            repeat: 0,
4035            autoreverse: false,
4036        }
4037    }
4038}
4039
4040impl AnimSpec {
4041    /// A smooth spring: `response` = settling period (s), `damping` = ratio (1.0 = no bounce, `<1`
4042    /// bouncy). `duration_ms` is a nominal cap for backends that need a duration; spring backends
4043    /// use `response`/`damping` directly.
4044    pub fn spring(response: f64, damping: f64) -> Self {
4045        AnimSpec {
4046            // `response` is the animation's duration: every backend maps a spring to a
4047            // fixed-duration overshoot curve over exactly `duration_ms`, so timing is identical
4048            // across toolkits (a physics spring's settle time would vary per platform).
4049            duration_ms: (response * 1000.0).max(50.0) as u32,
4050            delay_ms: 0,
4051            curve: Curve::Spring { response, damping },
4052            repeat: 0,
4053            autoreverse: false,
4054        }
4055    }
4056    pub fn linear(duration_ms: u32) -> Self {
4057        Self::timed(duration_ms, Curve::Linear)
4058    }
4059    pub fn ease_in(duration_ms: u32) -> Self {
4060        Self::timed(duration_ms, Curve::EaseIn)
4061    }
4062    pub fn ease_out(duration_ms: u32) -> Self {
4063        Self::timed(duration_ms, Curve::EaseOut)
4064    }
4065    pub fn ease_in_out(duration_ms: u32) -> Self {
4066        Self::timed(duration_ms, Curve::EaseInOut)
4067    }
4068    fn timed(duration_ms: u32, curve: Curve) -> Self {
4069        AnimSpec {
4070            duration_ms,
4071            delay_ms: 0,
4072            curve,
4073            repeat: 0,
4074            autoreverse: false,
4075        }
4076    }
4077    /// Delay before the animation starts (builder).
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    pub fn repeat(mut self, count: u32, autoreverse: bool) -> Self {
4084        self.repeat = count;
4085        self.autoreverse = autoreverse;
4086        self
4087    }
4088    /// Repeat forever (builder), e.g. a pulsing indicator.
4089    pub fn repeat_forever(mut self, autoreverse: bool) -> Self {
4090        self.repeat = u32::MAX;
4091        self.autoreverse = autoreverse;
4092        self
4093    }
4094    #[inline]
4095    pub fn duration_secs(&self) -> f64 {
4096        self.duration_ms as f64 / 1000.0
4097    }
4098    #[inline]
4099    pub fn delay_secs(&self) -> f64 {
4100        self.delay_ms as f64 / 1000.0
4101    }
4102}
4103
4104#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
4105pub enum Role {
4106    #[default]
4107    None,
4108    Button,
4109    Toggle,
4110    Slider,
4111    TextInput,
4112    Heading(u8),
4113    Image,
4114    Meter,
4115    Group,
4116    /// A hierarchical tree container (docs/tree.md): `role="tree"`, `AXOutline`.
4117    Tree,
4118    /// One row of a tree: `role="treeitem"`, with level/expanded state where the platform
4119    /// carries them (docs/tree.md).
4120    TreeItem,
4121    /// One tab in a strip of peers (`role="tab"`, `AXTabButton`): the composed document
4122    /// strip's title buttons. Pair it with [`A11yProps::selected`] for the current one.
4123    Tab,
4124    /// The strip holding tabs (`role="tablist"`, `AXTabGroup`).
4125    TabList,
4126}
4127
4128impl Role {
4129    /// The a11y role a built-in piece kind reports natively, the audit's *expectation* when the
4130    /// user hasn't set an explicit `.role()`. Native controls already expose these, so Day records
4131    /// them for `a11y_audit` (§14.2) rather than overriding the widget; only canvas/custom pieces
4132    /// need Day to apply a role. Returns `None` for kinds with no inherent control role.
4133    pub fn for_kind(kind: PieceKind) -> Role {
4134        match kind {
4135            kinds::BUTTON => Role::Button,
4136            kinds::TOGGLE => Role::Toggle,
4137            kinds::SLIDER => Role::Slider,
4138            kinds::TEXT_FIELD => Role::TextInput,
4139            kinds::IMAGE => Role::Image,
4140            kinds::PROGRESS => Role::Meter,
4141            kinds::TREE => Role::Tree,
4142            _ => Role::None,
4143        }
4144    }
4145}
4146
4147#[derive(Clone, Debug, Default, PartialEq)]
4148pub struct A11yProps {
4149    pub label: Option<String>,
4150    pub hint: Option<String>,
4151    pub value: Option<String>,
4152    pub role: Role,
4153    pub identifier: Option<String>,
4154    pub hidden: bool,
4155    pub decorative: bool,
4156    /// Whether the element is the selected one among its peers (a tab, a row): the
4157    /// platform's selected state, read aloud as such. `None` leaves the widget's own answer.
4158    pub selected: Option<bool>,
4159}
4160
4161impl A11yProps {
4162    /// Merge another set of annotations onto this one: any field `other` sets (a `Some`, a
4163    /// non-`None` role, or a `true` flag) overrides ours; unset fields are left intact. Lets a
4164    /// node accumulate its `.a11y()`, `.id()`, and piece defaults into one stored result, so
4165    /// each `set_a11y` re-applies the full picture and `a11y_audit` has the complete expectation.
4166    pub fn merge(&mut self, other: &A11yProps) {
4167        if other.label.is_some() {
4168            self.label = other.label.clone();
4169        }
4170        if other.hint.is_some() {
4171            self.hint = other.hint.clone();
4172        }
4173        if other.value.is_some() {
4174            self.value = other.value.clone();
4175        }
4176        if other.role != Role::None {
4177            self.role = other.role;
4178        }
4179        if other.identifier.is_some() {
4180            self.identifier = other.identifier.clone();
4181        }
4182        self.hidden |= other.hidden;
4183        self.decorative |= other.decorative;
4184        if other.selected.is_some() {
4185            self.selected = other.selected;
4186        }
4187    }
4188
4189    /// The role to *expect* for a node of `kind` carrying these annotations: an explicit
4190    /// `.role()` wins, otherwise the kind's native default (`Role::for_kind`).
4191    pub fn resolved_role(&self, kind: PieceKind) -> Role {
4192        if self.role != Role::None {
4193            self.role
4194        } else {
4195            Role::for_kind(kind)
4196        }
4197    }
4198}
4199
4200/// A widget's actual native state, read back from the platform by `Toolkit::read_native`
4201/// (docs/testing.md): what the widget itself shows and reports, independently of Day's tree,
4202/// so `a11y_audit` and `assert_native` (§14.2) can diff it against Day's expectation.
4203///
4204/// Two groups. The accessibility fields (`role`, `label`, `value`, `identifier`) are read
4205/// together and `found` says whether they were: `found = false` means the backend cannot read
4206/// its accessibility tree, and the audit skips the node. Every other field is read on its own,
4207/// and `None` means "not read": the backend cannot read it, or it does not apply to this kind.
4208/// A reader never reports a field it did not take from the widget, so a `None` is a recorded
4209/// gap rather than a pass.
4210#[derive(Clone, Debug, Default, PartialEq)]
4211pub struct NativeSnapshot {
4212    /// The accessibility fields below were read.
4213    pub found: bool,
4214    /// The native role mapped back to Day's `Role` (best-effort).
4215    pub role: Role,
4216    /// The accessibility label the platform reports.
4217    pub label: Option<String>,
4218    /// The accessibility value the platform reports.
4219    pub value: Option<String>,
4220    /// The automation identifier, which Day sets from `.id()`.
4221    pub identifier: Option<String>,
4222    /// The text the widget displays: a label's string, a button's title, a text field's or
4223    /// text area's contents, without markup or mnemonic markers. `None` for a secure field
4224    /// that masks it.
4225    pub text: Option<String>,
4226    /// A slider's or progress indicator's value, in the range Day gave it.
4227    pub number: Option<f64>,
4228    /// A toggle's state, or a button's selected state (`ButtonProps::selected`).
4229    pub checked: Option<bool>,
4230    /// Whether the widget takes input.
4231    pub enabled: Option<bool>,
4232    /// Whether the widget is shown: not hidden itself, nor by an ancestor.
4233    pub visible: Option<bool>,
4234    /// The widget's frame in points, relative to the window's content area, origin top left.
4235    pub frame: Option<Rect>,
4236}
4237
4238// ---------------------------------------------------------------------------
4239// Canvas display list (§11): full op set lands with M8a; the types are v1.
4240// ---------------------------------------------------------------------------
4241
4242#[derive(Clone, Debug, PartialEq)]
4243pub enum Shape {
4244    Rect(Rect),
4245    RoundedRect(Rect, f64),
4246    Ellipse(Rect),
4247    /// Arc within `rect`'s inscribed ellipse; angles in degrees, 0 = +x axis, clockwise.
4248    Arc {
4249        rect: Rect,
4250        start_deg: f64,
4251        sweep_deg: f64,
4252    },
4253    Line(Point, Point),
4254    Polygon(Vec<Point>),
4255    /// An arbitrary path: curves, several contours, and a fill rule (docs/canvas.md).
4256    ///
4257    /// [`Shape::Polygon`] is the straight-line, single-contour special case, kept because it is
4258    /// what most drawing code wants and it encodes far more compactly.
4259    Path(Path),
4260}
4261
4262impl Shape {
4263    /// A rectangle rounded corner by corner (docs/canvas.md "Rounded corners"), as the simplest
4264    /// shape that draws it: a plain [`Shape::Rect`] when every corner is square, a
4265    /// [`Shape::RoundedRect`] (each toolkit's own rounded rectangle) when the corners agree, and a
4266    /// path ([`rounded_rect_segs`]) otherwise. The radii are [fitted](CornerRadii::fitted) first.
4267    ///
4268    /// ```
4269    /// use day_spec::{CornerRadii, Rect, Shape};
4270    ///
4271    /// // A bar standing on its axis: rounded on top, square where it meets the baseline.
4272    /// let bar = Shape::rounded_rect(Rect::new(0.0, 0.0, 20.0, 80.0), CornerRadii::top(6.0));
4273    /// assert!(matches!(bar, Shape::Path(_)));
4274    /// ```
4275    pub fn rounded_rect(rect: Rect, radii: CornerRadii) -> Shape {
4276        let r = radii.fitted(rect.size);
4277        if r.is_zero() || rect.size.width <= 0.0 || rect.size.height <= 0.0 {
4278            Shape::Rect(rect)
4279        } else if r.is_uniform() {
4280            Shape::RoundedRect(rect, r.top_left)
4281        } else {
4282            Shape::Path(Path {
4283                segs: rounded_rect_segs(rect, r),
4284                rule: FillRule::NonZero,
4285            })
4286        }
4287    }
4288
4289    /// The same shape moved by `(dx, dy)`.
4290    ///
4291    /// What a [`Stamp`] means by "the template translated by one point", and the one definition of
4292    /// it: a backend builds each copy of a batch with this rather than reaching for its own
4293    /// platform transform, so every toolkit stamps to the same coordinates.
4294    pub fn translated(&self, dx: f64, dy: f64) -> Shape {
4295        let r = |r: &Rect| {
4296            Rect::new(
4297                r.origin.x + dx,
4298                r.origin.y + dy,
4299                r.size.width,
4300                r.size.height,
4301            )
4302        };
4303        let p = |p: &Point| Point::new(p.x + dx, p.y + dy);
4304        match self {
4305            Shape::Rect(rect) => Shape::Rect(r(rect)),
4306            Shape::RoundedRect(rect, rad) => Shape::RoundedRect(r(rect), *rad),
4307            Shape::Ellipse(rect) => Shape::Ellipse(r(rect)),
4308            Shape::Arc {
4309                rect,
4310                start_deg,
4311                sweep_deg,
4312            } => Shape::Arc {
4313                rect: r(rect),
4314                start_deg: *start_deg,
4315                sweep_deg: *sweep_deg,
4316            },
4317            Shape::Line(a, b) => Shape::Line(p(a), p(b)),
4318            Shape::Polygon(pts) => Shape::Polygon(pts.iter().map(p).collect()),
4319            Shape::Path(path) => Shape::Path(Path {
4320                segs: path
4321                    .segs
4322                    .iter()
4323                    .map(|seg| match seg {
4324                        PathSeg::Move(a) => PathSeg::Move(p(a)),
4325                        PathSeg::Line(a) => PathSeg::Line(p(a)),
4326                        PathSeg::Quad(c, a) => PathSeg::Quad(p(c), p(a)),
4327                        PathSeg::Cubic(c1, c2, a) => PathSeg::Cubic(p(c1), p(c2), p(a)),
4328                        PathSeg::Close => PathSeg::Close,
4329                    })
4330                    .collect(),
4331                rule: path.rule,
4332            }),
4333        }
4334    }
4335
4336    /// The shape's bounding rectangle: the box gradient [`UnitPoint`]s resolve against.
4337    pub fn bounds(&self) -> Rect {
4338        match self {
4339            Shape::Rect(r) | Shape::RoundedRect(r, _) | Shape::Ellipse(r) => *r,
4340            Shape::Arc { rect, .. } => *rect,
4341            Shape::Line(a, b) => points_bounds(&[*a, *b]),
4342            Shape::Polygon(pts) => points_bounds(pts),
4343            Shape::Path(p) => p.bounds(),
4344        }
4345    }
4346}
4347
4348/// One step of a [`Path`]. Points are absolute, in the canvas's coordinate space.
4349#[derive(Clone, Copy, Debug, PartialEq)]
4350pub enum PathSeg {
4351    /// Start a new contour at this point.
4352    Move(Point),
4353    Line(Point),
4354    /// Quadratic bezier: one control point, then the end point.
4355    Quad(Point, Point),
4356    /// Cubic bezier: two control points, then the end point.
4357    Cubic(Point, Point, Point),
4358    /// Close the current contour back to its `Move`.
4359    Close,
4360}
4361
4362/// Which points count as inside when a path's contours overlap (docs/canvas.md).
4363///
4364/// This matters the moment a shape has a hole: the counter of an "o", a washer, a ring chart. It
4365/// is a property of the fill, so stroking ignores it.
4366#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
4367pub enum FillRule {
4368    /// Direction-sensitive: a hole needs its contour wound the opposite way. Every 2-D API's
4369    /// default, and what a font's glyph outlines assume.
4370    #[default]
4371    NonZero,
4372    /// Parity: any contour inside another cuts a hole regardless of winding. What PDF's `f*`
4373    /// operator and SVG's `fill-rule: evenodd` mean.
4374    EvenOdd,
4375}
4376
4377/// An arbitrary 2-D path: any number of contours, straight or curved, with a fill rule.
4378#[derive(Clone, Debug, PartialEq, Default)]
4379pub struct Path {
4380    pub segs: Vec<PathSeg>,
4381    pub rule: FillRule,
4382}
4383
4384impl Path {
4385    /// A conservative bounding box: the hull of every point including control points, which
4386    /// contains the true curve bounds (a bezier stays inside its control hull). Used only to
4387    /// resolve gradient unit points, where being slightly generous costs nothing and computing
4388    /// exact curve extrema would not.
4389    pub fn bounds(&self) -> Rect {
4390        let mut pts: Vec<Point> = Vec::with_capacity(self.segs.len() * 3);
4391        for seg in &self.segs {
4392            match seg {
4393                PathSeg::Move(p) | PathSeg::Line(p) => pts.push(*p),
4394                PathSeg::Quad(c, p) => pts.extend_from_slice(&[*c, *p]),
4395                PathSeg::Cubic(c1, c2, p) => pts.extend_from_slice(&[*c1, *c2, *p]),
4396                PathSeg::Close => {}
4397            }
4398        }
4399        points_bounds(&pts)
4400    }
4401}
4402
4403/// A radius for each corner of a rectangle, clockwise from the top left (docs/canvas.md "Rounded
4404/// corners"). The shape a bar in a chart wants (rounded at its value end, square against its
4405/// axis), a tab (rounded on top), or a card joined to its neighbor.
4406///
4407/// Radii are in points and never negative. [`CornerRadii::fitted`] shrinks them the way CSS
4408/// does when two radii on one side would overlap, which is what a caller animating a radius or
4409/// drawing a short bar needs to not think about.
4410#[derive(Clone, Copy, Debug, PartialEq, Default)]
4411pub struct CornerRadii {
4412    pub top_left: f64,
4413    pub top_right: f64,
4414    pub bottom_right: f64,
4415    pub bottom_left: f64,
4416}
4417
4418impl CornerRadii {
4419    /// The same radius on every corner: what [`Shape::RoundedRect`] draws.
4420    pub fn uniform(r: f64) -> Self {
4421        CornerRadii {
4422            top_left: r,
4423            top_right: r,
4424            bottom_right: r,
4425            bottom_left: r,
4426        }
4427    }
4428    /// Rounded along the top edge, square along the bottom: a bar standing on its axis.
4429    pub fn top(r: f64) -> Self {
4430        CornerRadii {
4431            top_left: r,
4432            top_right: r,
4433            ..Default::default()
4434        }
4435    }
4436    /// Rounded along the bottom edge: a bar hanging below its axis.
4437    pub fn bottom(r: f64) -> Self {
4438        CornerRadii {
4439            bottom_right: r,
4440            bottom_left: r,
4441            ..Default::default()
4442        }
4443    }
4444    /// Rounded along the left edge: a bar growing leftward from its axis.
4445    pub fn left(r: f64) -> Self {
4446        CornerRadii {
4447            top_left: r,
4448            bottom_left: r,
4449            ..Default::default()
4450        }
4451    }
4452    /// Rounded along the right edge: a bar growing rightward from its axis.
4453    pub fn right(r: f64) -> Self {
4454        CornerRadii {
4455            top_right: r,
4456            bottom_right: r,
4457            ..Default::default()
4458        }
4459    }
4460
4461    /// The four radii, clockwise from the top left.
4462    pub fn to_array(self) -> [f64; 4] {
4463        [
4464            self.top_left,
4465            self.top_right,
4466            self.bottom_right,
4467            self.bottom_left,
4468        ]
4469    }
4470
4471    /// Whether every corner is square.
4472    pub fn is_zero(self) -> bool {
4473        self.to_array().iter().all(|r| *r <= 0.0)
4474    }
4475
4476    /// Whether every corner has the same radius, so the rectangle is a [`Shape::RoundedRect`].
4477    pub fn is_uniform(self) -> bool {
4478        let [a, b, c, d] = self.to_array();
4479        a == b && b == c && c == d
4480    }
4481
4482    /// These radii made to fit a `size` rectangle, the rule CSS uses for `border-radius`: a
4483    /// negative or non-finite radius is square, and when the two radii along any side add up to
4484    /// more than that side, every radius is scaled down by the same factor until none overlap.
4485    /// Scaling all four together keeps the corners in proportion, where clamping each one alone
4486    /// would turn a pill into a lopsided shape.
4487    pub fn fitted(self, size: Size) -> Self {
4488        let clean = |r: f64| if r.is_finite() && r > 0.0 { r } else { 0.0 };
4489        let [tl, tr, br, bl] = self.to_array().map(clean);
4490        let (w, h) = (size.width.max(0.0), size.height.max(0.0));
4491        let factor = [(w, tl + tr), (w, bl + br), (h, tl + bl), (h, tr + br)]
4492            .into_iter()
4493            .filter(|(_, sum)| *sum > 0.0)
4494            .map(|(side, sum)| side / sum)
4495            .fold(1.0f64, f64::min);
4496        CornerRadii {
4497            top_left: tl * factor,
4498            top_right: tr * factor,
4499            bottom_right: br * factor,
4500            bottom_left: bl * factor,
4501        }
4502    }
4503}
4504
4505/// The point `angle_deg` round a circle: degrees, `0` = the +x axis, positive clockwise in device
4506/// space (y down), the convention [`Shape::Arc`] and every arc helper here use.
4507pub fn arc_point(center: Point, radius: f64, angle_deg: f64) -> Point {
4508    let a = angle_deg.to_radians();
4509    Point::new(center.x + radius * a.cos(), center.y + radius * a.sin())
4510}
4511
4512/// A circular arc as cubic beziers: `sweep_deg` of a circle of `radius` about `center`, from
4513/// `start_deg` ([`arc_point`]'s convention). The segments start *from* the arc's first point, which
4514/// the caller reaches itself (a move or a line); nothing for a zero or non-finite radius or sweep.
4515///
4516/// The arc is split into quarter turns at most, where a cubic tracks a circle best: the radial
4517/// error peaks at 2.7 × 10⁻⁴ of the radius, a quarter of a pixel on a circle a thousand points
4518/// across (docs/canvas.md "Paths"). The same beziers on every backend mean the same pixels on
4519/// every backend, which an arc op interpreted by nine rasterizers would not.
4520pub fn arc_cubics(center: Point, radius: f64, start_deg: f64, sweep_deg: f64) -> Vec<PathSeg> {
4521    let (start, sweep) = (start_deg.to_radians(), sweep_deg.to_radians());
4522    if !radius.is_finite() || radius <= 0.0 || !sweep.is_finite() || sweep == 0.0 {
4523        return Vec::new();
4524    }
4525    let at = |a: f64| Point::new(center.x + radius * a.cos(), center.y + radius * a.sin());
4526    let steps = (sweep.abs() / std::f64::consts::FRAC_PI_2).ceil() as usize;
4527    let delta = sweep / steps as f64;
4528    // The exact control-handle length for a circular arc of this sweep. Negative for a negative
4529    // sweep, which is what turns the handles around for a counter-clockwise arc.
4530    let k = 4.0 / 3.0 * (delta / 4.0).tan() * radius;
4531    (0..steps)
4532        .map(|i| {
4533            let a = start + delta * i as f64;
4534            let b = a + delta;
4535            let (p0, p1) = (at(a), at(b));
4536            PathSeg::Cubic(
4537                Point::new(p0.x - k * a.sin(), p0.y + k * a.cos()),
4538                Point::new(p1.x + k * b.sin(), p1.y - k * b.cos()),
4539                p1,
4540            )
4541        })
4542        .collect()
4543}
4544
4545/// The closed contour of a rectangle rounded corner by corner, clockwise from the top left, with
4546/// the radii [fitted](CornerRadii::fitted) first. A square corner is a sharp point, not a
4547/// zero-length curve.
4548pub fn rounded_rect_segs(rect: Rect, radii: CornerRadii) -> Vec<PathSeg> {
4549    let r = radii.fitted(rect.size);
4550    let (x0, y0) = (rect.origin.x, rect.origin.y);
4551    let (x1, y1) = (x0 + rect.size.width, y0 + rect.size.height);
4552    // Each corner: the point where its curve starts, then the quarter turn round its center.
4553    let corners = [
4554        (
4555            Point::new(x0 + r.top_left, y0 + r.top_left),
4556            r.top_left,
4557            180.0,
4558        ),
4559        (
4560            Point::new(x1 - r.top_right, y0 + r.top_right),
4561            r.top_right,
4562            270.0,
4563        ),
4564        (
4565            Point::new(x1 - r.bottom_right, y1 - r.bottom_right),
4566            r.bottom_right,
4567            0.0,
4568        ),
4569        (
4570            Point::new(x0 + r.bottom_left, y1 - r.bottom_left),
4571            r.bottom_left,
4572            90.0,
4573        ),
4574    ];
4575    let mut segs = Vec::with_capacity(14);
4576    for (i, (center, radius, start)) in corners.into_iter().enumerate() {
4577        let first = arc_point(center, radius, start);
4578        segs.push(if i == 0 {
4579            PathSeg::Move(first)
4580        } else {
4581            PathSeg::Line(first)
4582        });
4583        segs.extend(arc_cubics(center, radius, start, 90.0));
4584    }
4585    segs.push(PathSeg::Close);
4586    segs
4587}
4588
4589/// How a stroked line ends (docs/canvas.md). Names match PDF's `J`, SVG's `stroke-linecap`, and
4590/// every native 2-D API.
4591#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
4592pub enum LineCap {
4593    #[default]
4594    Butt,
4595    Round,
4596    Square,
4597}
4598
4599/// How two stroked segments meet (docs/canvas.md). Matches PDF's `j` and SVG's
4600/// `stroke-linejoin`.
4601#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
4602pub enum LineJoin {
4603    #[default]
4604    Miter,
4605    Round,
4606    Bevel,
4607}
4608
4609/// Everything about a stroke except its paint.
4610///
4611/// [`StrokeStyle::width`] and `From<f64>` keep the common "just a width" case a single
4612/// argument, so plain `stroke(shape, color, 2.0)` call sites read the same as they always did.
4613#[derive(Clone, Debug, PartialEq)]
4614pub struct StrokeStyle {
4615    pub width: f64,
4616    pub cap: LineCap,
4617    pub join: LineJoin,
4618    /// Ignored unless `join` is [`LineJoin::Miter`]. The 2-D convention: past this ratio of miter
4619    /// length to line width the join falls back to a bevel.
4620    pub miter_limit: f64,
4621    /// On/off run lengths, repeating. Empty means solid.
4622    pub dash: Vec<f64>,
4623    /// How far into the dash pattern the line starts.
4624    pub dash_phase: f64,
4625}
4626
4627impl Default for StrokeStyle {
4628    fn default() -> Self {
4629        // 10.0 is the miter limit PDF, PostScript, SVG and Cairo all default to.
4630        StrokeStyle {
4631            width: 1.0,
4632            cap: LineCap::Butt,
4633            join: LineJoin::Miter,
4634            miter_limit: 10.0,
4635            dash: Vec::new(),
4636            dash_phase: 0.0,
4637        }
4638    }
4639}
4640
4641impl StrokeStyle {
4642    /// A solid stroke of `width`, everything else default.
4643    pub fn width(width: f64) -> Self {
4644        StrokeStyle {
4645            width,
4646            ..Default::default()
4647        }
4648    }
4649    /// A dashed stroke: `dash` is on/off run lengths, repeating.
4650    pub fn dashed(width: f64, dash: Vec<f64>) -> Self {
4651        StrokeStyle {
4652            width,
4653            dash,
4654            ..Default::default()
4655        }
4656    }
4657    /// Rounded ends and joins, the shape a data line usually wants.
4658    pub fn round(width: f64) -> Self {
4659        StrokeStyle {
4660            width,
4661            cap: LineCap::Round,
4662            join: LineJoin::Round,
4663            ..Default::default()
4664        }
4665    }
4666    /// Is this the plain width-only stroke every pre-existing call site asks for? Backends use
4667    /// it to skip setting dash/cap/join state they would only have to set back.
4668    pub fn is_plain(&self) -> bool {
4669        self.cap == LineCap::Butt
4670            && self.join == LineJoin::Miter
4671            && self.dash.is_empty()
4672            && self.miter_limit == 10.0
4673    }
4674}
4675
4676impl From<f64> for StrokeStyle {
4677    fn from(width: f64) -> Self {
4678        StrokeStyle::width(width)
4679    }
4680}
4681
4682fn points_bounds(pts: &[Point]) -> Rect {
4683    let (mut x0, mut y0, mut x1, mut y1) = (f64::MAX, f64::MAX, f64::MIN, f64::MIN);
4684    for p in pts {
4685        x0 = x0.min(p.x);
4686        y0 = y0.min(p.y);
4687        x1 = x1.max(p.x);
4688        y1 = y1.max(p.y);
4689    }
4690    if pts.is_empty() {
4691        return Rect::ZERO;
4692    }
4693    Rect::new(x0, y0, x1 - x0, y1 - y0)
4694}
4695
4696/// A point in the unit space of a shape's bounding box: (0,0) = top-leading, (1,1) =
4697/// bottom-trailing. Gradient geometry is expressed in unit points so one paint value works for
4698/// any shape size (docs/shapes.md §3.2).
4699#[derive(Clone, Copy, Debug, PartialEq)]
4700pub struct UnitPoint {
4701    pub x: f64,
4702    pub y: f64,
4703}
4704
4705impl UnitPoint {
4706    pub const fn new(x: f64, y: f64) -> Self {
4707        UnitPoint { x, y }
4708    }
4709    pub const TOP: UnitPoint = UnitPoint::new(0.5, 0.0);
4710    pub const BOTTOM: UnitPoint = UnitPoint::new(0.5, 1.0);
4711    pub const LEADING: UnitPoint = UnitPoint::new(0.0, 0.5);
4712    pub const TRAILING: UnitPoint = UnitPoint::new(1.0, 0.5);
4713    pub const TOP_LEADING: UnitPoint = UnitPoint::new(0.0, 0.0);
4714    pub const TOP_TRAILING: UnitPoint = UnitPoint::new(1.0, 0.0);
4715    pub const BOTTOM_LEADING: UnitPoint = UnitPoint::new(0.0, 1.0);
4716    pub const BOTTOM_TRAILING: UnitPoint = UnitPoint::new(1.0, 1.0);
4717    pub const CENTER: UnitPoint = UnitPoint::new(0.5, 0.5);
4718
4719    /// Resolve to an absolute point within `rect`.
4720    pub fn resolve(&self, rect: Rect) -> Point {
4721        Point::new(
4722            rect.origin.x + self.x * rect.size.width,
4723            rect.origin.y + self.y * rect.size.height,
4724        )
4725    }
4726}
4727
4728/// A linear gradient (docs/shapes.md §3.2 / §7): color stops along the line from `start` to
4729/// `end`, both in the unit space of the filled shape's bounding box. Stops are
4730/// `(offset 0..=1, color)`, ascending.
4731#[derive(Clone, Debug, PartialEq)]
4732pub struct LinearGradient {
4733    pub start: UnitPoint,
4734    pub end: UnitPoint,
4735    pub stops: Vec<(f64, Color)>,
4736}
4737
4738impl LinearGradient {
4739    pub fn new(start: UnitPoint, end: UnitPoint, stops: Vec<(f64, Color)>) -> Self {
4740        LinearGradient { start, end, stops }
4741    }
4742    /// Top-to-bottom between two colors: the everyday sky/backdrop case.
4743    pub fn vertical(top: Color, bottom: Color) -> Self {
4744        LinearGradient::new(
4745            UnitPoint::TOP,
4746            UnitPoint::BOTTOM,
4747            vec![(0.0, top), (1.0, bottom)],
4748        )
4749    }
4750    /// Leading-to-trailing between two colors.
4751    pub fn horizontal(leading: Color, trailing: Color) -> Self {
4752        LinearGradient::new(
4753            UnitPoint::LEADING,
4754            UnitPoint::TRAILING,
4755            vec![(0.0, leading), (1.0, trailing)],
4756        )
4757    }
4758}
4759
4760/// A radial gradient (docs/shapes.md §3.2 / §7): color stops from `center` outward. Both the
4761/// center and the radius live in the unit space of the filled shape's bounding box, so the
4762/// gradient stretches into an ellipse when the bounds aren't square (the XAML relative-brush
4763/// behavior; the other backends reproduce it with a local matrix on a circular gradient). A
4764/// `radius` of `0.5` from the default center touches the edge midpoints of the bounds.
4765#[derive(Clone, Debug, PartialEq)]
4766pub struct RadialGradient {
4767    pub center: UnitPoint,
4768    pub radius: f64,
4769    pub stops: Vec<(f64, Color)>,
4770}
4771
4772impl RadialGradient {
4773    pub fn new(center: UnitPoint, radius: f64, stops: Vec<(f64, Color)>) -> Self {
4774        RadialGradient {
4775            center,
4776            radius,
4777            stops,
4778        }
4779    }
4780    /// Centered, edge-touching (radius 0.5) between two colors: the everyday glow case.
4781    pub fn centered(inner: Color, outer: Color) -> Self {
4782        RadialGradient::new(UnitPoint::CENTER, 0.5, vec![(0.0, inner), (1.0, outer)])
4783    }
4784}
4785
4786/// The payload of [`DrawOp::Stamp`]: one shape drawn at every position in `at`.
4787///
4788/// A scatter plot is the case this exists for. Drawn as individual ops, fifty thousand points are
4789/// fifty thousand `DrawOp`s, rebuilt, compared and cloned on every frame that re-records, before
4790/// a backend draws anything. As one `Stamp` they are one op and a flat array of coordinates, and
4791/// a backend can put every copy into one path and hand the rasterizer a single fill.
4792///
4793/// Every copy shares the shape, the size and the paint. Varying any of those means more than one
4794/// stamp: group by what varies, which for a chart is usually the series color.
4795#[derive(Clone, Debug, PartialEq)]
4796pub struct Stamp {
4797    /// The template, authored around the origin: each copy is this shape translated by one point.
4798    /// A 6-point dot is `Shape::Ellipse(Rect::new(-3.0, -3.0, 6.0, 6.0))`.
4799    pub shape: Shape,
4800    /// Where the copies go. Order is the drawing order, so later points paint over earlier ones.
4801    pub at: Vec<Point>,
4802    pub paint: Paint,
4803    /// `None` fills each copy; `Some` strokes it with this style.
4804    pub stroke: Option<StrokeStyle>,
4805}
4806
4807/// A fill source: a solid color, or a linear/radial gradient (docs/shapes.md §3.2; angular and
4808/// semantic tokens are later phases). `From<Color>` keeps every existing `fill(shape, color)`
4809/// call site compiling unchanged.
4810#[derive(Clone, Debug, PartialEq)]
4811pub enum Paint {
4812    Solid(Color),
4813    Linear(LinearGradient),
4814    Radial(RadialGradient),
4815}
4816
4817impl From<Color> for Paint {
4818    fn from(c: Color) -> Self {
4819        Paint::Solid(c)
4820    }
4821}
4822
4823impl From<LinearGradient> for Paint {
4824    fn from(g: LinearGradient) -> Self {
4825        Paint::Linear(g)
4826    }
4827}
4828
4829impl From<RadialGradient> for Paint {
4830    fn from(g: RadialGradient) -> Self {
4831        Paint::Radial(g)
4832    }
4833}
4834
4835/// Where `at` sits vertically. `Top`, `Middle` and `Bottom` are edges of the line box (ascent +
4836/// descent at the font's size, the box [`Toolkit::measure_text`] reports); `Baseline` is the
4837/// typographic baseline itself.
4838#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
4839pub enum TextVAlign {
4840    /// `at` is the top of the line box.
4841    #[default]
4842    Top,
4843    /// `at` is the vertical middle of the line box.
4844    Middle,
4845    /// `at` is the baseline itself: what every native 2-D text call takes, and what a run of labels
4846    /// sharing a line should align on rather than their individual boxes.
4847    Baseline,
4848    /// `at` is the bottom of the line box.
4849    Bottom,
4850}
4851
4852/// How canvas text hangs on its `at` point: one placement per axis (docs/canvas.md "Text").
4853///
4854/// Two axes rather than a list of named positions, because that is the shape of the problem and
4855/// of every native API underneath: `NSAttributedString` drawing, Pango extents,
4856/// `QFontMetricsF`, `Paint.Align`, Canvas2D's `textAlign`/`textBaseline`. The alignment is done
4857/// by the backend, which is both cheaper and more accurate than doing it in app code: it already
4858/// has the laid-out metrics, where an app has to ask for them through
4859/// [`Toolkit::measure_text`] first.
4860///
4861/// [`TextAnchor::LEADING`] and [`TextAnchor::CENTERED`] name the two placements that used to be
4862/// this type's only variants.
4863#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
4864pub struct TextAnchor {
4865    /// The horizontal placement: the same three-way leading/center/trailing a wrapped label's
4866    /// lines take ([`props::TextAlign`]), because it is the same question with the same RTL rule.
4867    /// `Trailing` is what an axis label right-aligned against its axis wants, and the reason the
4868    /// horizontal axis is settable at all: emulating it in app code costs a
4869    /// [`Toolkit::measure_text`] call per label, where the backend already holds the width it is
4870    /// about to draw with.
4871    pub h: props::TextAlign,
4872    pub v: TextVAlign,
4873}
4874
4875impl TextAnchor {
4876    /// The top-leading corner of the line box, the default.
4877    pub const LEADING: TextAnchor = TextAnchor {
4878        h: props::TextAlign::Leading,
4879        v: TextVAlign::Top,
4880    };
4881    /// The center of the line box, both ways.
4882    pub const CENTERED: TextAnchor = TextAnchor {
4883        h: props::TextAlign::Center,
4884        v: TextVAlign::Middle,
4885    };
4886    /// The top-trailing corner of the line box.
4887    pub const TRAILING: TextAnchor = TextAnchor {
4888        h: props::TextAlign::Trailing,
4889        v: TextVAlign::Top,
4890    };
4891
4892    /// Where the text's top-leading corner goes, as an offset from `at`, given the line box this
4893    /// text measures to. The single definition of what an anchor means: every backend that draws
4894    /// in Rust calls this, and the C++/Java/JS shims repeat exactly this arithmetic.
4895    ///
4896    /// `height` is the line box (ascent + descent) and `ascent` the baseline's offset from its
4897    /// top, the two numbers [`TextMetrics`] carries.
4898    pub fn offset(self, width: f64, height: f64, ascent: f64) -> (f64, f64) {
4899        let dx = match self.h {
4900            props::TextAlign::Leading => 0.0,
4901            props::TextAlign::Center => -width / 2.0,
4902            props::TextAlign::Trailing => -width,
4903        };
4904        let dy = match self.v {
4905            TextVAlign::Top => 0.0,
4906            TextVAlign::Middle => -height / 2.0,
4907            TextVAlign::Baseline => -ascent,
4908            TextVAlign::Bottom => -height,
4909        };
4910        (dx, dy)
4911    }
4912
4913    /// The anchor as one number, for the numeric op stream the serializing backends share:
4914    /// `h * 4 + v`, so it still occupies the single slot the two-variant enum did.
4915    pub fn pack(self) -> f64 {
4916        (self.h as u8 * 4 + self.v as u8) as f64
4917    }
4918
4919    /// Inverse of [`TextAnchor::pack`]. An unrecognized code answers the default rather than
4920    /// failing: a stream is only ever written by a matching encoder, and a drawing with text in
4921    /// the wrong corner beats one that panics inside a native draw callback.
4922    pub fn unpack(code: f64) -> TextAnchor {
4923        let c = code.round().clamp(0.0, 11.0) as u8;
4924        let h = match c / 4 {
4925            1 => props::TextAlign::Center,
4926            2 => props::TextAlign::Trailing,
4927            _ => props::TextAlign::Leading,
4928        };
4929        let v = match c % 4 {
4930            1 => TextVAlign::Middle,
4931            2 => TextVAlign::Baseline,
4932            3 => TextVAlign::Bottom,
4933            _ => TextVAlign::Top,
4934        };
4935        TextAnchor { h, v }
4936    }
4937}
4938
4939#[derive(Clone, Debug, PartialEq)]
4940pub enum DrawOp {
4941    Fill(Shape, Paint),
4942    /// Stroke `shape`. The paint may be a gradient, and [`StrokeStyle`] carries width, dash, cap
4943    /// and join; `Draw::stroke` builds the plain width-only case.
4944    Stroke(Shape, Paint, StrokeStyle),
4945    /// One line of text. `size` is absolute canvas points (no accessibility scale: canvas
4946    /// text is a label inside a drawing, docs/canvas.md); `font` picks the family, weight and
4947    /// slant, and its default is the platform's own UI face.
4948    Text {
4949        text: String,
4950        at: Point,
4951        size: f64,
4952        color: Color,
4953        anchor: TextAnchor,
4954        font: CanvasFont,
4955    },
4956    /// Draw one shape at many positions, the batched form of [`DrawOp::Fill`]/[`DrawOp::Stroke`]
4957    /// (docs/canvas.md "Stamping").
4958    ///
4959    /// Boxed because the payload is wider than the largest other op, and a bigger `DrawOp` would
4960    /// cost every op in every drawing, the exact thing this variant exists to stop paying.
4961    Stamp(Box<Stamp>),
4962    /// Draw an image into `rect` (docs/images.md).
4963    ///
4964    /// The source is a [`BitmapId`] and never bytes: a canvas re-records on every tracked read,
4965    /// so carrying a buffer here would hand the backend a megabyte to compare, and re-decode, on
4966    /// every frame. The app decodes once with `day::decode_image` and draws the handle.
4967    ///
4968    /// `opacity` multiplies the image's own alpha. A backend that cannot draw a bitmap at all
4969    /// draws nothing rather than a placeholder rectangle, the same way an unknown op is skipped.
4970    ///
4971    /// `source` is the region of the bitmap to draw, in the bitmap's own PIXELS (not points:
4972    /// [`BitmapInfo::scale`] says how many pixels make a point), `None` meaning the whole
4973    /// image. It is what lets one decoded sprite sheet serve every icon on a map: each draw
4974    /// picks its cell and scales it into `rect`. A region reaching outside the bitmap is clamped
4975    /// to it, never an error: the part inside draws where the mapping into `rect` puts it, and
4976    /// an empty intersection draws nothing. A backend without a sub-rect draw clips to `rect`
4977    /// and draws the whole image scaled so the region lands there ([`clamp_image_source`] is
4978    /// the shared arithmetic).
4979    Image {
4980        image: BitmapId,
4981        rect: Rect,
4982        opacity: f64,
4983        source: Option<Rect>,
4984    },
4985    /// Intersect the clip with `shape`; everything drawn afterwards is confined to it.
4986    ///
4987    /// Scoped by [`DrawOp::Save`]/[`DrawOp::Restore`], which is the only way to widen a clip
4988    /// again; every native 2-D context works this way, so there is no "unclip".
4989    Clip(Shape),
4990    /// Push the current transform + clip (§11, shapes). Backends map to save/restore of the
4991    /// native 2-D context; `Concat` multiplies an affine onto the CTM (shape rotate/scale/offset).
4992    Save,
4993    Restore,
4994    Concat(day_geometry::Affine),
4995}
4996
4997// ---------------------------------------------------------------------------
4998// Built-in piece descriptors: full props (realize) + sparse patches (update).
4999// One binding = one attribute = one patch value: sparseness by construction (§8.1).
5000// ---------------------------------------------------------------------------
5001
5002/// A semantic (logical) text style. Each maps to the platform's native text style where the
5003/// toolkit has one: `UIFont`/`NSFont.preferredFont(forTextStyle:)` on Apple (Dynamic Type), the
5004/// `*TextBlockStyle` resources on XAML. A Day app thus matches the OS's own typography and
5005/// inherits its accessibility text scaling with no extra work. Backends without semantic styles
5006/// (GTK/Qt/Android) approximate with sizes that still track the platform's text-scale /
5007/// font-scale accessibility setting.
5008///
5009/// The set mirrors SwiftUI `Font.TextStyle` (largest → smallest).
5010#[derive(Clone, Copy, Debug, PartialEq, Default)]
5011pub enum Font {
5012    LargeTitle,
5013    Title,
5014    Title2,
5015    Title3,
5016    Headline,
5017    Subheadline,
5018    #[default]
5019    Body,
5020    Callout,
5021    Footnote,
5022    Caption,
5023    Caption2,
5024    /// A custom point size. Backends scale it by the platform's accessibility text-scale (iOS via
5025    /// `UIFontMetrics`, Android via `sp`, GTK via text-scaling-factor) so it stays legible.
5026    System(f64),
5027    /// A bundled custom font by **family name**, at a point size (`Font::Custom("Pacifico",
5028    /// 24.0)`). The family must ship in the project's `fonts/` directory; `day build` stages the
5029    /// file into each platform's native font store and the backend registers it at startup
5030    /// (§18.4). The name is the family name baked into the font file (what Font Book /
5031    /// fontconfig report), not the file name. The size scales with the platform accessibility
5032    /// text-scale exactly like [`Font::System`]; weight/italic apply only where the family ships
5033    /// (or the platform synthesizes) such a face. An unknown family falls back to the system font
5034    /// of the same size, with a warning in the log.
5035    Custom(&'static str, f64),
5036}
5037
5038impl Font {
5039    /// A bundled custom font by **typed family**, at a point size, the checked form of
5040    /// [`Font::Custom`]. Pass a generated `res::fonts::…` constant
5041    /// (`Font::custom(res::fonts::pacifico, 24.0)`), which exists only if the family ships in the
5042    /// project's `fonts/` directory, so the font is guaranteed bundled. For a family name known
5043    /// another way, the untyped [`Font::Custom`] variant is the escape hatch.
5044    pub const fn custom(family: FontFamily, size: f64) -> Font {
5045        Font::Custom(family.as_str(), size)
5046    }
5047}
5048
5049/// Font weight, matching `UIFont.Weight` / SwiftUI `Font.Weight` (lightest → heaviest).
5050/// Ordered by heaviness, so backends can e.g. map `>= Semibold` to a synthesized bold face.
5051#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
5052pub enum FontWeight {
5053    UltraLight,
5054    Thin,
5055    Light,
5056    Regular,
5057    Medium,
5058    Semibold,
5059    Bold,
5060    Heavy,
5061    Black,
5062}
5063
5064impl FontWeight {
5065    /// Every rung, lightest first.
5066    pub const ALL: [FontWeight; 9] = [
5067        FontWeight::UltraLight,
5068        FontWeight::Thin,
5069        FontWeight::Light,
5070        FontWeight::Regular,
5071        FontWeight::Medium,
5072        FontWeight::Semibold,
5073        FontWeight::Bold,
5074        FontWeight::Heavy,
5075        FontWeight::Black,
5076    ];
5077
5078    /// The CSS / OpenType numeric weight (100 … 900), the one number every platform font API
5079    /// also speaks (`Typeface.create(base, weight, italic)`, `QFont::Weight`,
5080    /// `DWRITE_FONT_WEIGHT`, `OH_Drawing_FontWeight`), and what the canvas wire carries.
5081    pub const fn css(self) -> u16 {
5082        match self {
5083            FontWeight::UltraLight => 100,
5084            FontWeight::Thin => 200,
5085            FontWeight::Light => 300,
5086            FontWeight::Regular => 400,
5087            FontWeight::Medium => 500,
5088            FontWeight::Semibold => 600,
5089            FontWeight::Bold => 700,
5090            FontWeight::Heavy => 800,
5091            FontWeight::Black => 900,
5092        }
5093    }
5094
5095    /// The nearest rung to a CSS weight (ties round heavier, like CSS font matching); anything
5096    /// outside 100 … 900 clamps.
5097    pub fn from_css(n: u16) -> FontWeight {
5098        let n = n.clamp(100, 900);
5099        let idx = (usize::from(n) + 50) / 100; // 100 → 1 … 900 → 9
5100        FontWeight::ALL[idx.clamp(1, 9) - 1]
5101    }
5102
5103    /// The English face name for a rung ("Semibold"), for platforms whose enumeration names
5104    /// no face (see [`FontFace::synthesized_name`]).
5105    pub const fn name(self) -> &'static str {
5106        match self {
5107            FontWeight::UltraLight => "Ultra Light",
5108            FontWeight::Thin => "Thin",
5109            FontWeight::Light => "Light",
5110            FontWeight::Regular => "Regular",
5111            FontWeight::Medium => "Medium",
5112            FontWeight::Semibold => "Semibold",
5113            FontWeight::Bold => "Bold",
5114            FontWeight::Heavy => "Heavy",
5115            FontWeight::Black => "Black",
5116        }
5117    }
5118}
5119
5120/// One face a font family ships (docs/fonts.md): its display name ("Bold Italic"), weight and
5121/// slant. What [`FontFamilyInfo::faces`] lists and what a font menu's style picker offers.
5122#[derive(Clone, Debug, PartialEq, Eq)]
5123pub struct FontFace {
5124    pub name: String,
5125    pub weight: FontWeight,
5126    pub italic: bool,
5127}
5128
5129impl FontFace {
5130    /// A display name from weight + slant ("Semibold Italic") for platforms whose enumeration
5131    /// API names no face (Android's `fonts.xml`, the CSS generic families).
5132    pub fn synthesized_name(weight: FontWeight, italic: bool) -> String {
5133        if italic {
5134            format!("{} Italic", weight.name())
5135        } else {
5136            weight.name().to_string()
5137        }
5138    }
5139}
5140
5141/// A platform (or bundled) font family and the faces it can draw canvas text in
5142/// ([`Toolkit::font_families`], docs/fonts.md).
5143#[derive(Clone, Debug, PartialEq, Eq)]
5144pub struct FontFamilyInfo {
5145    pub family: String,
5146    pub faces: Vec<FontFace>,
5147}
5148
5149impl FontFamilyInfo {
5150    /// Whether any face is [`FontWeight::Bold`] or heavier.
5151    pub fn has_bold(&self) -> bool {
5152        self.faces.iter().any(|f| f.weight >= FontWeight::Bold)
5153    }
5154    /// Whether any face is italic.
5155    pub fn has_italic(&self) -> bool {
5156        self.faces.iter().any(|f| f.italic)
5157    }
5158    /// The nearest face: an exact slant match preferred, then the smallest weight distance
5159    /// (ties go heavier, like CSS font matching). `None` only when the family lists no faces.
5160    pub fn face_for(&self, weight: FontWeight, italic: bool) -> Option<&FontFace> {
5161        let want = i32::from(weight.css());
5162        self.faces.iter().min_by_key(|f| {
5163            let slant = i32::from(f.italic != italic);
5164            let dist = (i32::from(f.weight.css()) - want).abs();
5165            // Heavier wins a tie: subtracting the bool sorts the heavier face first.
5166            (slant, dist, i32::from(i32::from(f.weight.css()) < want))
5167        })
5168    }
5169}
5170
5171/// Single-line text measurement in canvas points ([`Toolkit::measure_text`], docs/fonts.md).
5172///
5173/// Two boxes, and the difference between them matters. `width`/`height` is the **line box**: the
5174/// typographic slot the text occupies, the same for every string in a face at a size, and what
5175/// [`TextAnchor`] positions. [`ink`](TextMetrics::ink) is the **ink box**: where the glyphs
5176/// put marks. A line of digits leaves the descender space of its line box empty, so the
5177/// two disagree, and which one is wanted depends on the question: laying text out in a column
5178/// wants the line box, and centering it on a rule or keeping it clear of a mark wants the ink.
5179#[derive(Clone, Copy, Debug, PartialEq)]
5180pub struct TextMetrics {
5181    /// The advance width of the whole string.
5182    pub width: f64,
5183    /// The line box: ascent + descent at this size (plus the line gap where the engine reports
5184    /// one), which is the box [`TextAnchor`] positions.
5185    pub height: f64,
5186    /// The baseline's offset from the top of the line box.
5187    pub ascent: f64,
5188    /// The face's cap height at this size: baseline to the top of a capital.
5189    ///
5190    /// A property of the font, not of this string, reported here because it is what optical
5191    /// centering needs and asking for it separately would be a second measurement. Text made of
5192    /// capitals and digits looks centered on a rule when its cap box straddles it, not its line
5193    /// box: the line box reserves descender room that digits never use, so centering by it sits
5194    /// every label a little low. The cap middle is `ascent - cap_height / 2.0` below the line
5195    /// box's top.
5196    pub cap_height: f64,
5197    /// The ink box, the tight bounds of what is drawn, with its origin relative to the line
5198    /// box's top-leading corner, so `ink.origin` is where the marks start inside the slot.
5199    ///
5200    /// Empty (zero-size) for text that draws nothing, a space included. Where a toolkit cannot
5201    /// report ink it answers the whole line box, which is a superset: an overlap test against it
5202    /// can only be too cautious, never wrong.
5203    pub ink: Rect,
5204}
5205
5206impl TextMetrics {
5207    /// The portable guess `day::measure_text` falls back to when a toolkit cannot measure:
5208    /// 0.6 × size per character, 1.2 × size tall, the baseline at 0.9 × size, caps at 0.7 × size.
5209    /// Its ink is the whole line box, the safe direction to be wrong in (see
5210    /// [`ink`](TextMetrics::ink)).
5211    pub fn approximate(text: &str, size: f64) -> TextMetrics {
5212        let (width, height) = (0.6 * size * text.chars().count() as f64, 1.2 * size);
5213        TextMetrics {
5214            width,
5215            height,
5216            ascent: 0.9 * size,
5217            cap_height: 0.7 * size,
5218            ink: Rect::new(0.0, 0.0, width, height),
5219        }
5220    }
5221
5222    /// Read the eight-slot form the serializing backends (qt, xaml, arkui, web) fill across their
5223    /// C ABI: advance, line height, ascent, cap height, then the ink box relative to the line
5224    /// box's top-leading corner. One definition so four shims cannot drift from each other.
5225    pub fn from_slots(out: &[f64; 8]) -> TextMetrics {
5226        TextMetrics {
5227            width: out[0],
5228            height: out[1],
5229            ascent: out[2],
5230            cap_height: out[3],
5231            ink: Rect::new(out[4], out[5], out[6], out[7]),
5232        }
5233    }
5234
5235    /// The line box's top-leading corner, given a baseline-relative measurement, the shape every
5236    /// backend's metrics come in. `ink_*` are relative to the drawing origin on the baseline
5237    /// (`ink_top` negative above it), the convention Skia, Core Text and Qt all report in.
5238    pub fn from_baseline(
5239        width: f64,
5240        ascent: f64,
5241        descent: f64,
5242        cap_height: f64,
5243        ink: Rect,
5244    ) -> TextMetrics {
5245        TextMetrics {
5246            width,
5247            height: ascent + descent,
5248            ascent,
5249            cap_height,
5250            // Baseline-relative to line-box-relative is one shift by the ascent.
5251            ink: Rect::new(
5252                ink.origin.x,
5253                ink.origin.y + ascent,
5254                ink.size.width,
5255                ink.size.height,
5256            ),
5257        }
5258    }
5259}
5260
5261/// What canvas text is drawn with beyond its size (docs/canvas.md "Text"): a family, a weight and
5262/// a slant. The default is the platform's own UI face, regular, upright, which is what every
5263/// backend drew before the field existed, so a default font encodes to nothing on the wire.
5264#[derive(Clone, Debug, PartialEq, Eq, Default)]
5265pub struct CanvasFont {
5266    /// A platform or bundled family name (as [`Toolkit::font_families`] lists it); `None` =
5267    /// the platform's default UI face.
5268    pub family: Option<String>,
5269    /// `None` = Regular.
5270    pub weight: Option<FontWeight>,
5271    pub italic: bool,
5272}
5273
5274impl CanvasFont {
5275    /// The family name to send over the wire, empty for the default.
5276    pub fn family_str(&self) -> &str {
5277        self.family.as_deref().unwrap_or("")
5278    }
5279    /// The CSS weight to send over the wire, 0 for the default.
5280    pub fn css_weight(&self) -> u16 {
5281        self.weight.map(FontWeight::css).unwrap_or(0)
5282    }
5283}
5284
5285/// Field separator inside one family of the shim-side font list ([`parse_font_list`]).
5286pub const FONT_LIST_FIELD: char = '\u{1f}';
5287/// Family separator of the shim-side font list ([`parse_font_list`]).
5288pub const FONT_LIST_FAMILY: char = '\u{1e}';
5289
5290/// Decode the text a non-Rust font enumerator hands back (the Qt, XAML and ArkUI shims, the
5291/// Android bridge, the web shim all produce this one format): families separated by U+001E;
5292/// inside a family, U+001F-separated fields: the family name, then one (name, CSS weight,
5293/// italic `0`/`1`) triple per face. Tolerant: a malformed face or family is skipped, an empty
5294/// face name is synthesized from its weight and slant, and a family with no faces is kept
5295/// with none (the caller decides what a face-less family means).
5296pub fn parse_font_list(s: &str) -> Vec<FontFamilyInfo> {
5297    let mut out = Vec::new();
5298    for fam in s.split(FONT_LIST_FAMILY) {
5299        let mut fields = fam.split(FONT_LIST_FIELD);
5300        let Some(family) = fields.next().map(str::trim).filter(|f| !f.is_empty()) else {
5301            continue;
5302        };
5303        let rest: Vec<&str> = fields.collect();
5304        let mut faces = Vec::new();
5305        for face in rest.chunks(3) {
5306            let [name, weight, italic] = face else {
5307                continue;
5308            };
5309            let Ok(weight) = weight.trim().parse::<u16>() else {
5310                continue;
5311            };
5312            let weight = FontWeight::from_css(weight);
5313            let italic = matches!(italic.trim(), "1" | "true");
5314            let name = name.trim();
5315            let name = if name.is_empty() {
5316                FontFace::synthesized_name(weight, italic)
5317            } else {
5318                name.to_string()
5319            };
5320            if !faces
5321                .iter()
5322                .any(|f: &FontFace| f.weight == weight && f.italic == italic)
5323            {
5324                faces.push(FontFace {
5325                    name,
5326                    weight,
5327                    italic,
5328                });
5329            }
5330        }
5331        out.push(FontFamilyInfo {
5332            family: family.to_string(),
5333            faces,
5334        });
5335    }
5336    out
5337}
5338
5339/// The full font descriptor a label carries: a semantic (or custom) [`Font`] style plus an optional
5340/// weight override, an italic flag, and the tabular-figures request. Backends resolve this to one
5341/// native font.
5342#[derive(Clone, Copy, Debug, PartialEq)]
5343pub struct FontSpec {
5344    pub style: Font,
5345    pub weight: Option<FontWeight>,
5346    pub italic: bool,
5347    /// Ask for tabular (monospaced) figures: every digit takes the same advance, so a number that
5348    /// changes stops changing width.
5349    ///
5350    /// In a proportional system font `1` is narrower than `8`, so a readout beside a slider
5351    /// wobbles as the value changes even when the digit count is fixed. Every platform ships this
5352    /// as a font feature, so Day asks for the platform's own rather than substituting a monospaced
5353    /// family: the text keeps the system face, and only the digits change metrics.
5354    ///
5355    /// Reserving space (`Decorate::reserving`) and tabular figures solve the two halves of the
5356    /// same problem (reservation stops the box resizing, tabular stops the glyphs shifting inside
5357    /// it), and a numeric readout usually wants both.
5358    ///
5359    /// This rides the existing label realize/patch path rather than adding a Toolkit method, so it
5360    /// is not a backend duty and has no duty-matrix row. Every in-tree backend honors it: AppKit
5361    /// and UIKit re-pick the system face (`monospacedDigitSystemFont`), GTK and Qt and ArkUI set
5362    /// the `tnum` OpenType feature, Android `setFontFeatureSettings`, XAML the `Typography`
5363    /// NumeralAlignment property, and web-dom `font-variant-numeric`. A font with no `tnum` table,
5364    /// or an SDK predating the attribute, renders the stock proportional figures.
5365    pub tabular: bool,
5366    /// Ask for the platform's monospaced face at this style's size, what `` `code` `` in a
5367    /// markdown run needs (docs/text-runs.md).
5368    ///
5369    /// A flag rather than a `Font::Monospace(pt)` variant so the run keeps its semantic style:
5370    /// code inside a `Footnote` paragraph must stay footnote-sized and keep tracking the
5371    /// reader's text-size setting, which a fixed point size would throw away.
5372    ///
5373    /// Like [`Self::tabular`], this rides the label realize/patch path and is not a backend duty:
5374    /// every toolkit has a system monospace face (`monospacedSystemFont`, Pango's `monospace`
5375    /// family, `QFontDatabase::FixedFont`, `Typeface.MONOSPACE`, CSS `monospace`).
5376    pub monospace: bool,
5377    /// Multiply the resolved size. `1.0` is the style's own size, `1.6` a heading against a body
5378    /// paragraph, `0.8` a caption inside one.
5379    ///
5380    /// Relative rather than an absolute point size, so that an editor's font-size control can
5381    /// move this while text a person reads for an hour still tracks the platform's
5382    /// accessibility text-scale. `Font::System(pt)` remains the absolute escape hatch, and it
5383    /// is where an imported document's `\fs28` or `font-size: 14px` lands (docs/texteditor.md):
5384    /// faithful to the file, and no longer responsive to the reader, which is the trade that
5385    /// form makes.
5386    ///
5387    /// Three toolkits take it directly (`GtkTextTag::scale`, Android's `RelativeSizeSpan`, CSS
5388    /// `em`); the rest multiply it into the size they already compute.
5389    pub scale: f64,
5390}
5391
5392impl Default for FontSpec {
5393    fn default() -> Self {
5394        FontSpec {
5395            style: Font::Body,
5396            weight: None,
5397            italic: false,
5398            tabular: false,
5399            monospace: false,
5400            scale: 1.0,
5401        }
5402    }
5403}
5404
5405impl From<Font> for FontSpec {
5406    fn from(style: Font) -> Self {
5407        FontSpec {
5408            style,
5409            ..FontSpec::default()
5410        }
5411    }
5412}
5413
5414impl FontSpec {
5415    /// The plain descriptor for a style: no weight override, no italic, scale 1.0.
5416    pub fn new(style: Font) -> Self {
5417        FontSpec::from(style)
5418    }
5419    /// This descriptor at a different relative size (see [`FontSpec::scale`]).
5420    pub fn scaled(mut self, scale: f64) -> Self {
5421        self.scale = scale;
5422        self
5423    }
5424    /// The point size this descriptor resolves to, given the size the platform assigns its
5425    /// semantic style. The one place `scale` is applied, so every backend's font resolver
5426    /// multiplies the same way.
5427    pub fn resolved_points(&self, style_points: f64) -> f64 {
5428        let base = match self.style {
5429            Font::System(pt) | Font::Custom(_, pt) => pt,
5430            _ => style_points,
5431        };
5432        (base * self.scale).max(1.0)
5433    }
5434}
5435
5436/// One styled span of a label's text (docs/text-runs.md).
5437///
5438/// `range` is a byte range into the label's `text`. Bytes, not chars: every backend that takes a
5439/// structured attributed string wants UTF-16 or byte offsets, `str` slicing is byte-based, and a
5440/// char count would have to be converted at every boundary. Ranges must be non-overlapping and
5441/// ascending; a gap between them is unstyled text, drawn with the label's own font.
5442///
5443/// A run says only what differs. `font` is the whole descriptor rather than a delta because a
5444/// bold run inside a Body paragraph is `FontSpec { style: Body, weight: Some(Bold), .. }`. The
5445/// style has to travel with the weight or the run loses its semantic size.
5446#[derive(Clone, Debug, PartialEq)]
5447pub struct TextRun {
5448    pub range: std::ops::Range<usize>,
5449    pub font: FontSpec,
5450    pub color: Option<Color>,
5451    /// A highlight painted behind the glyphs. Every native text editor carries this attribute
5452    /// (docs/texteditor.md), and search hits and review comments are the two things an app is
5453    /// asked for the moment it has styled text at all.
5454    pub background: Option<Color>,
5455    /// A line under the text.
5456    pub underline: Underline,
5457    /// A line through the text. Separate from `FontSpec` because it is a decoration, not a face:
5458    /// no platform expresses it by picking a different font.
5459    pub strikethrough: bool,
5460    /// Makes this run a link to the given target. Rendering it is [`Cap::TextRuns`]; making it
5461    /// activatable is [`Cap::TextLinks`], which is a smaller set (see the docs).
5462    pub link: Option<String>,
5463}
5464
5465impl Default for TextRun {
5466    fn default() -> Self {
5467        TextRun {
5468            range: 0..0,
5469            font: FontSpec::default(),
5470            color: None,
5471            background: None,
5472            underline: Underline::None,
5473            strikethrough: false,
5474            link: None,
5475        }
5476    }
5477}
5478
5479impl TextRun {
5480    /// A run that only changes the font, the common case for emphasis.
5481    pub fn font(range: std::ops::Range<usize>, font: FontSpec) -> Self {
5482        TextRun {
5483            range,
5484            font,
5485            ..TextRun::default()
5486        }
5487    }
5488
5489    /// This run's attributes without its range: what a selection's style is compared against
5490    /// and what an editor's toolbar toggles (docs/texteditor.md).
5491    pub fn style(&self) -> RunStyle {
5492        RunStyle {
5493            font: self.font,
5494            color: self.color,
5495            background: self.background,
5496            underline: self.underline,
5497            strikethrough: self.strikethrough,
5498            link: self.link.clone(),
5499        }
5500    }
5501
5502    /// A run of `style` over `range`.
5503    pub fn styled(range: std::ops::Range<usize>, style: RunStyle) -> Self {
5504        TextRun {
5505            range,
5506            font: style.font,
5507            color: style.color,
5508            background: style.background,
5509            underline: style.underline,
5510            strikethrough: style.strikethrough,
5511            link: style.link,
5512        }
5513    }
5514}
5515
5516/// Serialize a label's text + runs as markup, for the two backends whose text widgets take a
5517/// string in their own dialect rather than a structured attributed string: GTK (Pango markup)
5518/// and Qt (its HTML subset). Shared so the escaping is written and tested once: a translated
5519/// string containing `&` or `<` corrupts the whole label otherwise, and it will be a translated
5520/// string that finds the bug.
5521///
5522/// `dialect` decides the spelling: Pango wants `<span foreground="#rrggbb"
5523/// font_family="monospace">`, Qt wants `<span style="color:#rrggbb">` with `<code>`. Both accept
5524/// `<b>`, `<i>`, `<u>`, `<s>` and `<a href>`, which is why one function can serve them.
5525///
5526/// `base_points` is the size the label itself resolved to. Only a relative-size run
5527/// ([`FontSpec::scale`]) needs it, and only in the Qt dialect: Pango markup takes a percentage
5528/// directly, while Qt's CSS subset understands `pt` and `px` and ignores `%`.
5529pub fn runs_to_markup(
5530    text: &str,
5531    runs: &[TextRun],
5532    dialect: MarkupDialect,
5533    base_points: f64,
5534) -> String {
5535    let mut out = String::with_capacity(text.len() + runs.len() * 24);
5536    let mut at = 0usize;
5537    for r in runs {
5538        // Skip a run whose range does not address this string, without advancing `at`: dropping
5539        // the run loses styling, but advancing past it would drop the rest of the sentence.
5540        // `runs_are_valid` rejects these upstream; this keeps the failure cheap if one slips by.
5541        let Some(styled) = text.get(r.range.clone()) else {
5542            continue;
5543        };
5544        if r.range.start > at
5545            && let Some(plain) = text.get(at..r.range.start)
5546        {
5547            escape_markup_in(plain, &mut out, dialect);
5548        }
5549        open_run(r, dialect, base_points, &mut out);
5550        escape_markup_in(styled, &mut out, dialect);
5551        close_run(r, dialect, &mut out);
5552        at = r.range.end;
5553    }
5554    if let Some(tail) = text.get(at..) {
5555        escape_markup_in(tail, &mut out, dialect);
5556    }
5557    out
5558}
5559
5560impl Symbol {
5561    /// A 24×24 outline path for this symbol, Day's own drawing of it.
5562    ///
5563    /// The platform's icon comes first on every backend that has one (SF Symbols, the freedesktop
5564    /// icon theme, Fluent's glyph font). This is the fallback for when that lookup finds nothing,
5565    /// which is not an edge case: `view-filter-symbolic` exists on a GNOME desktop and nowhere
5566    /// else, so a GTK or Qt app run off that desktop drew a toolbar item with no icon at all.
5567    /// One table here means the same fallback shape everywhere instead of a gap per platform.
5568    ///
5569    /// `None` for a variant with no drawing yet: `Symbol` is `#[non_exhaustive]`, so a new one
5570    /// degrades to a label rather than failing to compile.
5571    pub fn outline_path(self) -> Option<&'static str> {
5572        use Symbol as S;
5573        // The wildcard is unreachable today (every variant is drawn below) and it is here for
5574        // the next one, which should degrade to a label rather than fail to compile.
5575        #[allow(unreachable_patterns)]
5576        Some(match self {
5577            S::Add => "M11 5h2v6h6v2h-6v6h-2v-6H5v-2h6z",
5578            S::Remove => "M5 11h14v2H5z",
5579            S::Delete => "M9 3h6l1 2h4v2H4V5h4zM6 8h12l-1 13H7z",
5580            S::Edit => {
5581                "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"
5582            }
5583            S::New => "M13 2H6v20h12V7h-5zm2 .5L19.5 7H15z",
5584            S::Open => "M2 5h7l2 2h11v12H2z",
5585            S::Save => "M3 3h13l5 5v13H3zm5 0h7v6H8zm-1 11h10v7H7z",
5586            S::Print => "M7 3h10v4H7zM4 8h16v8h-3v6H7v-6H4z",
5587            S::Refresh => "M12 4V1L8 5l4 4V6a6 6 0 1 1-6 6H4a8 8 0 1 0 8-8z",
5588            S::Search => {
5589                "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"
5590            }
5591            S::Share => "M12 3l5 5h-3v7h-4V8H7zM5 17h14v4H5z",
5592            // An eight-tooth gear, round about the center (radius 10 at the teeth, 7.6 at the
5593            // roots) with a 3.2 hole: square in its box, so it sits in a row's 24-point icon
5594            // slot at the same size as its neighbors.
5595            S::Settings => {
5596                "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"
5597            }
5598            S::Info => "M12 2a10 10 0 1 0 0 20 10 10 0 0 0 0-20m-1 5h2v2h-2zm0 4h2v6h-2z",
5599            S::Star => {
5600                "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"
5601            }
5602            S::Bookmark => "M6 2h12v20l-6-4-6 4z",
5603            S::Back => "M15.4 5.4L14 4l-8 8 8 8 1.4-1.4L8.8 12z",
5604            S::Forward => "M8.6 5.4L10 4l8 8-8 8-1.4-1.4L15.2 12z",
5605            S::Up => "M5.4 15.4L4 14l8-8 8 8-1.4 1.4L12 8.8z",
5606            S::Down => "M5.4 8.6L4 10l8 8 8-8-1.4-1.4L12 15.2z",
5607            S::Home => "M12 3l9 8h-3v10h-5v-6h-2v6H6V11H3z",
5608            S::Sidebar => "M3 4h18v16H3zm2 2v12h4V6zm6 0v12h8V6z",
5609            S::Filter => "M3 5h18l-7 8v6l-4 2v-8z",
5610            S::Sort => "M8 4v12H4l4 4 4-4H10V4zM14 6h7v2h-7zm0 4h5v2h-5zm0 4h3v2h-3z",
5611            S::More => {
5612                "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"
5613            }
5614            S::Play => "M8 5l11 7-11 7z",
5615            S::Pause => "M7 5h3v14H7zm7 0h3v14h-3z",
5616            S::Stop => "M6 6h12v12H6z",
5617            S::Camera => {
5618                "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"
5619            }
5620            S::Code => {
5621                "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"
5622            }
5623            S::Light => {
5624                "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"
5625            }
5626            S::Dark => "M12 3a9 9 0 1 0 9 9 7 7 0 0 1-9-9",
5627            // "Automatic": the half-filled circle every platform uses: the left half solid, the
5628            // right half an outline, which `evenodd` below turns into the ring it should be.
5629            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",
5630            S::ZoomIn => {
5631                "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"
5632            }
5633            S::ZoomOut => {
5634                "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"
5635            }
5636            // The ZoomIn lens with a numeral 1 in it, "back to actual size".
5637            S::ZoomReset => {
5638                "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"
5639            }
5640            S::Undo => "M12 5V2L7 7l5 5V9a5 5 0 1 1 0 10H8v2h4a7 7 0 0 0 0-14z",
5641            S::Redo => "M12 5V2l5 5-5 5V9a5 5 0 1 0 0 10h4v2h-4a7 7 0 0 1 0-14z",
5642            S::Copy => "M8 2h10v14H8zM4 6h2v14h12v2H4z",
5643            S::Cut => {
5644                "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"
5645            }
5646            S::Paste => "M9 2h6v2h3v18H6V4h3zm0 2v2h6V4z",
5647            S::Mail => "M2 5h20v14H2zm2 3.2V17h16V8.2l-8 5z",
5648            S::Folder => "M2 5h7l2 2h11v12H2z",
5649            S::Document => "M14 2H6v20h12V6zm.5.8L17.2 6H14.5z",
5650            S::Check => "M9 16.2L4.8 12l-1.4 1.4L9 19 21 7l-1.4-1.4z",
5651            S::Close => {
5652                "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"
5653            }
5654            S::Warning => "M12 2l10 19H2zm-1 7h2v6h-2zm0 8h2v2h-2z",
5655            // Shape outlines, stroked as a 2-unit band (an even-odd ring), so they read as
5656            // outlines at any size rather than filled blocks.
5657            S::Rectangle => "M3 5h18v14H3zm2 2v10h14V7z",
5658            S::Oval => {
5659                "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"
5660            }
5661            // A circular ring (even-odd: outer disc minus inner) and its filled twin.
5662            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",
5663            S::CircleFilled => "M12 4a8 8 0 1 0 0 16 8 8 0 0 0 0-16z",
5664            S::Line => "M4.7 17.9l13.2-13.2 1.4 1.4L6.1 19.3z",
5665            // Group: a solid square stacked on another (the visible L of the back one);
5666            // Ungroup: the same two squares pulled apart.
5667            S::Group => "M8 4h12v12h-4V8H8zM4 8h12v12H4z",
5668            S::Ungroup => "M3 3h8v8H3zM13 13h8v8h-8z",
5669            // A crosshair: a dot in a ring with four ticks, the even-odd fill leaving the gap
5670            // between dot and ring empty.
5671            S::Location => {
5672                "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"
5673            }
5674            // `Symbol` is `#[non_exhaustive]`: a variant added upstream draws nothing here rather
5675            // than failing to compile, and its item keeps its label.
5676            _ => return None,
5677        })
5678    }
5679
5680    /// [`Self::outline_path`] wrapped as a standalone SVG document.
5681    pub fn outline_svg(self) -> Option<String> {
5682        self.outline_path().map(|d| {
5683            format!(
5684                "<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 24 24\">\
5685                 <path fill-rule=\"evenodd\" d=\"{d}\"/></svg>"
5686            )
5687        })
5688    }
5689}
5690
5691/// Which markup dialect [`runs_to_markup`] should emit.
5692#[derive(Clone, Copy, Debug, PartialEq, Eq)]
5693pub enum MarkupDialect {
5694    /// Pango markup (GTK).
5695    Pango,
5696    /// Qt's rich-text HTML subset.
5697    QtHtml,
5698}
5699
5700/// XML-escape a run of plain text into `out`. `&` first, or the escapes escape each other.
5701///
5702/// Newlines are dialect-specific. Pango lays a literal `\n` out as a line break, but Qt's rich
5703/// text is HTML, where any run of whitespace collapses to one space, which silently ran a
5704/// two-paragraph body together into a single block. `<br>` is what says "break here" in HTML, so
5705/// the same string wraps the same way on both.
5706fn escape_markup_in(s: &str, out: &mut String, dialect: MarkupDialect) {
5707    for c in s.chars() {
5708        match c {
5709            '&' => out.push_str("&amp;"),
5710            '<' => out.push_str("&lt;"),
5711            '>' => out.push_str("&gt;"),
5712            '"' => out.push_str("&quot;"),
5713            '\'' => out.push_str("&#39;"),
5714            '\n' if dialect == MarkupDialect::QtHtml => out.push_str("<br>"),
5715            _ => out.push(c),
5716        }
5717    }
5718}
5719
5720/// [`escape_markup_in`] for the URL slot, where a newline cannot appear.
5721fn escape_markup(s: &str, out: &mut String) {
5722    escape_markup_in(s, out, MarkupDialect::Pango);
5723}
5724
5725fn hex(c: Color) -> String {
5726    format!(
5727        "#{:02x}{:02x}{:02x}",
5728        (c.r.clamp(0.0, 1.0) * 255.0) as u8,
5729        (c.g.clamp(0.0, 1.0) * 255.0) as u8,
5730        (c.b.clamp(0.0, 1.0) * 255.0) as u8
5731    )
5732}
5733
5734/// Does this run need a `<span>` in `dialect`, or do the plain tags cover it?
5735fn needs_span(r: &TextRun, dialect: MarkupDialect) -> bool {
5736    let extras = r.color.is_some() || r.background.is_some() || r.font.scale != 1.0;
5737    match dialect {
5738        // Pango expresses the monospace family as a span attribute; Qt cannot (see below).
5739        MarkupDialect::Pango => extras || r.font.monospace,
5740        MarkupDialect::QtHtml => extras,
5741    }
5742}
5743
5744fn open_run(r: &TextRun, dialect: MarkupDialect, base_points: f64, out: &mut String) {
5745    if let Some(url) = r.link.as_deref() {
5746        out.push_str("<a href=\"");
5747        escape_markup(url, out);
5748        out.push_str("\">");
5749    }
5750    // The span carries the attributes that have no tag: colors, relative size, and (on Pango)
5751    // the monospace family. Bold/italic/strike/underline are tags in both dialects, which keeps
5752    // the attribute string short and the escaping trivial.
5753    let color = r.color.map(hex);
5754    let background = r.background.map(hex);
5755    let mono = r.font.monospace;
5756    if needs_span(r, dialect) {
5757        match dialect {
5758            MarkupDialect::Pango => {
5759                out.push_str("<span");
5760                if let Some(c) = &color {
5761                    out.push_str(&format!(" foreground=\"{c}\""));
5762                }
5763                if let Some(c) = &background {
5764                    out.push_str(&format!(" background=\"{c}\""));
5765                }
5766                if mono {
5767                    out.push_str(" font_family=\"monospace\"");
5768                }
5769                if r.font.scale != 1.0 {
5770                    // Absolute, in Pango units (1/1024 pt), not the `font_scale`/`size="N%"`
5771                    // pair: those are Pango 1.50 attributes, and a Pango that does not know an
5772                    // attribute fails the whole markup parse, which renders the label empty
5773                    // rather than merely unscaled. A point size still tracks the desktop's text
5774                    // scaling, since Pango resolves points through the Xft DPI.
5775                    let pts = r.font.resolved_points(base_points);
5776                    out.push_str(&format!(" size=\"{}\"", (pts * 1024.0).round() as i64));
5777                }
5778                out.push('>');
5779            }
5780            MarkupDialect::QtHtml => {
5781                // Color only. Qt's rich text does not resolve the generic `monospace` family
5782                // from a style attribute (it rendered proportional), so the fixed face comes
5783                // from the `<code>` tag below, which Qt maps to its own fixed font.
5784                out.push_str("<span style=\"");
5785                if let Some(c) = &color {
5786                    out.push_str(&format!("color:{c};"));
5787                }
5788                if let Some(c) = &background {
5789                    out.push_str(&format!("background-color:{c};"));
5790                }
5791                if r.font.scale != 1.0 {
5792                    // Points, not a percentage: Qt's rich-text CSS subset understands `pt` and
5793                    // `px` and silently ignores `%`, which is why a scaled run rendered at the
5794                    // base size here while every other backend scaled it.
5795                    let pt = r.font.resolved_points(base_points);
5796                    out.push_str(&format!("font-size:{pt}pt;"));
5797                }
5798                out.push_str("\">");
5799            }
5800        }
5801    }
5802    if dialect == MarkupDialect::QtHtml && mono {
5803        out.push_str("<code>");
5804    }
5805    if r.font.weight.is_some_and(|w| w >= FontWeight::Semibold) {
5806        out.push_str("<b>");
5807    }
5808    if r.font.italic {
5809        out.push_str("<i>");
5810    }
5811    if r.underline.is_on() {
5812        out.push_str("<u>");
5813    }
5814    if r.strikethrough {
5815        out.push_str("<s>");
5816    }
5817}
5818
5819fn close_run(r: &TextRun, dialect: MarkupDialect, out: &mut String) {
5820    if r.strikethrough {
5821        out.push_str("</s>");
5822    }
5823    if r.underline.is_on() {
5824        out.push_str("</u>");
5825    }
5826    if r.font.italic {
5827        out.push_str("</i>");
5828    }
5829    if r.font.weight.is_some_and(|w| w >= FontWeight::Semibold) {
5830        out.push_str("</b>");
5831    }
5832    if dialect == MarkupDialect::QtHtml && r.font.monospace {
5833        out.push_str("</code>");
5834    }
5835    if needs_span(r, dialect) {
5836        out.push_str("</span>");
5837    }
5838    if r.link.is_some() {
5839        out.push_str("</a>");
5840    }
5841}
5842
5843/// Are these runs well formed for `text`: ascending, non-overlapping, inside the string, and on
5844/// character boundaries?
5845///
5846/// Checked once in the pieces layer rather than in eight backends. A backend handed overlapping
5847/// ranges would produce a different wrong answer per platform, and a range splitting a multi-byte
5848/// character would panic on `str` slicing in some and render mojibake in others.
5849pub fn runs_are_valid(text: &str, runs: &[TextRun]) -> Result<(), String> {
5850    let mut prev_end = 0usize;
5851    for (i, r) in runs.iter().enumerate() {
5852        if r.range.start < prev_end {
5853            return Err(format!(
5854                "run {i} starts at {} but the previous run ends at {prev_end} — runs must be \
5855                 ascending and non-overlapping",
5856                r.range.start
5857            ));
5858        }
5859        if r.range.end > text.len() {
5860            return Err(format!(
5861                "run {i} ends at {} but the text is {} bytes",
5862                r.range.end,
5863                text.len()
5864            ));
5865        }
5866        if r.range.start > r.range.end {
5867            return Err(format!("run {i} has an inverted range {:?}", r.range));
5868        }
5869        if !text.is_char_boundary(r.range.start) || !text.is_char_boundary(r.range.end) {
5870            return Err(format!(
5871                "run {i} range {:?} splits a multi-byte character",
5872                r.range
5873            ));
5874        }
5875        prev_end = r.range.end;
5876    }
5877    Ok(())
5878}
5879
5880pub mod props {
5881    use super::*;
5882
5883    #[derive(Clone, Debug, Default, PartialEq)]
5884    pub struct ContainerProps {
5885        pub background: Option<Color>,
5886        pub corner_radius: f64,
5887        pub clips: bool,
5888        /// Semantic, theme-adaptive surface, mapped by each backend to a native material that
5889        /// follows the platform's light/dark appearance automatically (unlike the fixed-RGBA
5890        /// `background`, which it overrides when set).
5891        pub role: Option<super::SurfaceRole>,
5892    }
5893    /// Reactive surface update for a `background(..)` decorator whose color is a signal/closure:
5894    /// the backend re-applies the fill on the container's native backing view. Corner radius and
5895    /// clipping are fixed at realize (the `corner_radius(r)` decorator takes a plain `f64`).
5896    #[derive(Clone, Debug, PartialEq)]
5897    pub enum ContainerPatch {
5898        Background(Option<Color>),
5899    }
5900
5901    /// Realize props for a `scroll` container: which axis it scrolls. Backends create the matching
5902    /// native scroll view (vertical `UIScrollView`/`ScrollView`, horizontal
5903    /// `HorizontalScrollView`, etc.).
5904    #[derive(Clone, Debug, Default, PartialEq)]
5905    pub struct ScrollProps {
5906        pub horizontal: bool,
5907    }
5908
5909    #[derive(Clone, Debug, Default, PartialEq)]
5910    pub struct LabelProps {
5911        pub text: String,
5912        pub font: FontSpec,
5913        pub color: Option<Color>,
5914        /// What the text means, for the color the platform gives it (docs/text.md).
5915        ///
5916        /// Semantic the way [`crate::Font`] is semantic: an app says "this is secondary text"
5917        /// and each platform answers with its own answer: `secondaryLabelColor` on Apple,
5918        /// `?android:textColorSecondary`, GTK's `dim-label`. That is the only way a de-emphasized
5919        /// label stays correct in both appearances, since a literal grey that reads well on white
5920        /// is wrong on black. An explicit [`Self::color`] still wins; a backend that has no such
5921        /// color renders primary, which is legible and correct, just not dimmed.
5922        pub role: TextRole,
5923        pub wraps: bool,
5924        /// Maximum rendered lines; zero is unlimited. Apple and Android plain labels truncate
5925        /// the last line. Other backends may retain their ordinary wrapping behavior.
5926        pub max_lines: u32,
5927        /// How the label's lines sit within its own width. Only observable on a label that
5928        /// wraps or carries explicit newlines: a single line fills its box, so its alignment is
5929        /// the container's business, not the label's.
5930        ///
5931        /// `Leading` is the default and is what running text wants; `Center` is for the short,
5932        /// centered block a welcome screen or an empty state uses. A backend that cannot set
5933        /// it renders leading-aligned, which is legible and correct, just not centered.
5934        pub align: TextAlign,
5935        /// Styled spans within `text` (docs/text-runs.md). Empty is the overwhelmingly common
5936        /// case and means exactly what a label has always meant: one font, one color. A backend
5937        /// that cannot draw runs ignores this and renders `text` uniformly, which is legible and
5938        /// correct, just unstyled.
5939        pub runs: Vec<crate::TextRun>,
5940    }
5941    /// What a label's text means, for the color the platform gives it (`LabelProps::role`).
5942    #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
5943    pub enum TextRole {
5944        /// Ordinary text, in the platform's primary label color.
5945        #[default]
5946        Primary,
5947        /// De-emphasized text: a caption, a hint, the "nothing selected" line an empty detail
5948        /// pane shows. Rendered in the platform's secondary label color.
5949        Secondary,
5950    }
5951
5952    /// How a wrapped label's lines sit within its width (`LabelProps::align`).
5953    ///
5954    /// There is no `Justified` variant because no toolkit in Day's set agrees on how to justify
5955    /// the last line, and the ones that can do it at all need a paragraph style the others have
5956    /// no equivalent for.
5957    #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
5958    pub enum TextAlign {
5959        /// Left in a left-to-right locale, right in an RTL one (docs/localization.md).
5960        #[default]
5961        Leading,
5962        Center,
5963        Trailing,
5964    }
5965
5966    #[derive(Clone, Debug, PartialEq)]
5967    pub enum LabelPatch {
5968        Text(String),
5969        Color(Option<Color>),
5970        Font(FontSpec),
5971        /// New text and its runs together. One patch, not two: a run's byte range is only
5972        /// meaningful against a particular string, so applying them separately would leave the
5973        /// widget briefly holding ranges that point into the wrong text.
5974        Runs(String, Vec<crate::TextRun>),
5975    }
5976
5977    /// A button's native styling tier. `Automatic` is the toolkit's stock look; `Bordered`
5978    /// asks for a visually contained button where the stock look is borderless (iOS's plain
5979    /// system button reads as a link); `Prominent` asks for the platform's accent-filled /
5980    /// default-action affordance. Toolkits whose stock buttons are already contained treat
5981    /// `Bordered` as `Automatic`.
5982    // `Eq` is gone with the `Tinted` color: `Color` holds floats. `PartialEq` is what the
5983    // props diff uses, and that is unaffected.
5984    #[derive(Clone, Copy, Debug, Default, PartialEq)]
5985    pub enum ButtonStyleSpec {
5986        #[default]
5987        Automatic,
5988        Bordered,
5989        Prominent,
5990        /// A filled button in an app-chosen color, still drawn by the native control: the
5991        /// platform keeps its own pressed, hover, focus and disabled rendering, its button role,
5992        /// and its keyboard activation. The label color is not carried; each backend picks the
5993        /// readable one for the fill (see [`ButtonStyleSpec::on_tint`]), the same call the
5994        /// platform's own tinted buttons make.
5995        ///
5996        /// A backend with no way to recolor its button ignores this and draws its ordinary
5997        /// button. That is the trade: a plain button everywhere beats a colored
5998        /// rectangle that is no longer a button on the platforms that cannot.
5999        Tinted(Color),
6000        /// A button no wider than its title asks for (a one-glyph "−" or "+" in a stepper,
6001        /// a "×" on a chip) on toolkits whose stock button carries a minimum width and wide
6002        /// insets (Material's 88 dp button turns a two-button stepper into 240 dp). The native
6003        /// control stays: only its minimum width and horizontal padding are reduced. A toolkit
6004        /// whose buttons already hug their title (AppKit, UIKit's plain button, Qt) draws its
6005        /// ordinary button.
6006        Compact,
6007        /// Borderless native action button; compact horizontal insets on Material.
6008        Plain,
6009    }
6010
6011    impl ButtonStyleSpec {
6012        /// The label color to draw on a [`ButtonStyleSpec::Tinted`] fill: whichever of black or
6013        /// white contrasts better against it, by WCAG's contrast ratio.
6014        ///
6015        /// Comparing the two ratios rather than thresholding the luminance is the difference
6016        /// between right and nearly right. A mid amber (`#F0A64C`) has a relative luminance of
6017        /// 0.44; under a "brighter than half" test it reads as dark and takes white text, at a
6018        /// hopeless 2.2:1. Its contrast against black is 9.7:1. The two ratios cross at a
6019        /// luminance of 0.179, not 0.5, and everything between those two numbers is a button
6020        /// nobody can read.
6021        pub fn on_tint(fill: Color) -> Color {
6022            // WCAG relative luminance: sRGB channels linearized, then weighted by the eye's
6023            // sensitivity to each.
6024            let lin = |c: f64| {
6025                let c = c.clamp(0.0, 1.0);
6026                if c <= 0.04045 {
6027                    c / 12.92
6028                } else {
6029                    ((c + 0.055) / 1.055).powf(2.4)
6030                }
6031            };
6032            let l = 0.2126 * lin(fill.r) + 0.7152 * lin(fill.g) + 0.0722 * lin(fill.b);
6033            // Contrast ratio is (lighter + 0.05) / (darker + 0.05); white is 1.0, black is 0.0.
6034            let against_white = 1.05 / (l + 0.05);
6035            let against_black = (l + 0.05) / 0.05;
6036            if against_black >= against_white {
6037                Color::BLACK
6038            } else {
6039                Color::WHITE
6040            }
6041        }
6042    }
6043
6044    #[derive(Clone, Debug, Default, PartialEq)]
6045    /// The visible content and accessible title of a button with an icon.
6046    pub struct ButtonContent {
6047        /// Also serves as the accessible name when only the icon is visible.
6048        pub title: String,
6049        pub icon: Option<Icon>,
6050        pub icon_only: bool,
6051    }
6052    #[derive(Clone, Debug, Default, PartialEq)]
6053    pub struct ButtonProps {
6054        pub title: String,
6055        pub icon: Option<Icon>,
6056        pub icon_only: bool,
6057        pub enabled: bool,
6058        pub style: ButtonStyleSpec,
6059        /// The button stands for the current choice among its siblings (a document tab, a
6060        /// view switcher): the platform's own checked or selected rendering, which keeps the
6061        /// button enabled, focusable and activatable, and tells assistive tech it is selected.
6062        /// A click never toggles it natively; only the app's next patch changes it.
6063        pub selected: bool,
6064    }
6065    #[derive(Clone, Debug, PartialEq)]
6066    pub enum ButtonPatch {
6067        Title(String),
6068        /// Update an icon button's label and icon together. Plain buttons still use `Title`.
6069        Content(ButtonContent),
6070        Enabled(bool),
6071        /// The selected state (see [`ButtonProps::selected`]).
6072        Selected(bool),
6073        /// A live style change: what a reactive `.tint(…)` sends, so a button can recolor with
6074        /// app state without being torn down and realized again.
6075        Style(ButtonStyleSpec),
6076    }
6077
6078    #[derive(Clone, Debug, Default, PartialEq)]
6079    pub struct ToggleProps {
6080        pub on: bool,
6081        pub enabled: bool,
6082    }
6083    #[derive(Clone, Debug, PartialEq)]
6084    pub enum TogglePatch {
6085        On(bool),
6086        Enabled(bool),
6087    }
6088
6089    #[derive(Clone, Debug, PartialEq)]
6090    pub struct SliderProps {
6091        pub value: f64,
6092        pub min: f64,
6093        pub max: f64,
6094        pub step: Option<f64>,
6095        pub enabled: bool,
6096    }
6097    impl Default for SliderProps {
6098        fn default() -> Self {
6099            SliderProps {
6100                value: 0.0,
6101                min: 0.0,
6102                max: 1.0,
6103                step: None,
6104                enabled: true,
6105            }
6106        }
6107    }
6108    #[derive(Clone, Debug, PartialEq)]
6109    pub enum SliderPatch {
6110        Value(f64),
6111        Enabled(bool),
6112    }
6113
6114    /// SwiftUI's `pickerStyle` analogue (kinds::PICKER). Each maps to a distinct native
6115    /// control per toolkit (docs/picker.md).
6116    #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
6117    pub enum PickerStyle {
6118        /// A dropdown/pop-up menu (NSPopUpButton / GtkDropDown / QComboBox / UIButton+UIMenu / Spinner).
6119        #[default]
6120        Menu,
6121        /// A horizontal segmented control (NSSegmentedControl / UISegmentedControl / linked toggles / …).
6122        Segmented,
6123        /// A vertical radio-button group laid out inline (NSButton radios / GtkCheckButton group / …).
6124        Inline,
6125    }
6126
6127    /// Full picker props (realize). `style` is set once at build; `options`, `selected` and
6128    /// `enabled` patch (via [`PickerPatch`]).
6129    #[derive(Clone, Debug, PartialEq)]
6130    pub struct PickerProps {
6131        /// Decorative boundaries before option indexes (not selectable options). Native menu
6132        /// grouping on AppKit/UIKit; ignored by other backends and non-menu styles.
6133        pub separators_before: Vec<usize>,
6134        pub options: Vec<String>,
6135        pub selected: usize,
6136        pub style: PickerStyle,
6137        /// Whether the picker takes input. Default `true`.
6138        pub enabled: bool,
6139    }
6140    impl Default for PickerProps {
6141        fn default() -> Self {
6142            PickerProps {
6143                separators_before: Vec::new(),
6144                options: Vec::new(),
6145                selected: 0,
6146                style: PickerStyle::default(),
6147                enabled: true,
6148            }
6149        }
6150    }
6151
6152    #[derive(Clone, Debug, PartialEq)]
6153    pub enum PickerPatch {
6154        Selected(usize),
6155        /// New option labels, for a picker whose choices come from data (a document list, a
6156        /// live count). The backend rebuilds its items and keeps the selected index where it
6157        /// still exists, clamping to the last option otherwise; a fresh
6158        /// [`PickerPatch::Selected`] follows whenever the app's own binding disagrees.
6159        Options(Vec<String>),
6160        /// Enable or disable the whole control, every style alike.
6161        Enabled(bool),
6162    }
6163
6164    /// Full text-area props (realize, kinds::TEXT_AREA; docs/textarea.md). `text` seeds the
6165    /// editor; `min_lines`/`max_lines` bound the auto-growing height in text lines
6166    /// (`max_lines == 0` = unbounded). `editable`/`selectable`/`spellcheck` control the native
6167    /// editor attributes (all default `true`); a backend that can't honor one answers
6168    /// `Cap::Text{Editable,Selectable,SpellCheck}` = `Unsupported`. `text` and the three attributes
6169    /// change after build (via [`TextAreaPatch`]); the rest are build-only.
6170    #[derive(Clone, Debug, PartialEq)]
6171    pub struct TextAreaProps {
6172        pub text: String,
6173        pub placeholder: String,
6174        pub min_lines: u32,
6175        pub max_lines: u32,
6176        /// Whether the user can edit the text (`false` = read-only). Default `true`.
6177        pub editable: bool,
6178        /// Whether the text can be selected (and copied). Default `true`.
6179        pub selectable: bool,
6180        /// Whether spell-check / autocorrect highlighting is on. Default `true`.
6181        pub spellcheck: bool,
6182        /// Plain Enter emits `Event::Submitted` instead of inserting a newline (Shift+Enter
6183        /// still inserts one where the platform can distinguish). Chat composers. Default
6184        /// `false`.
6185        pub submit_on_enter: bool,
6186    }
6187
6188    impl Default for TextAreaProps {
6189        fn default() -> Self {
6190            TextAreaProps {
6191                text: String::new(),
6192                placeholder: String::new(),
6193                min_lines: 1,
6194                max_lines: 0,
6195                editable: true,
6196                selectable: true,
6197                spellcheck: true,
6198                submit_on_enter: false,
6199            }
6200        }
6201    }
6202
6203    /// Imperative text-area updates: replace the text (programmatic sync), or flip one of the
6204    /// live attributes.
6205    #[derive(Clone, Debug, PartialEq)]
6206    pub enum TextAreaPatch {
6207        SetText(String),
6208        SetEditable(bool),
6209        SetSelectable(bool),
6210        SetSpellCheck(bool),
6211    }
6212
6213    #[derive(Clone, Debug, Default, PartialEq)]
6214    pub struct TextFieldProps {
6215        pub text: String,
6216        pub placeholder: String,
6217        pub enabled: bool,
6218    }
6219    #[derive(Clone, Debug, PartialEq)]
6220    pub enum TextFieldPatch {
6221        /// Origin-tagged write (§4.4): `from_native` suppresses the echo back into the widget.
6222        Text {
6223            text: String,
6224            from_native: bool,
6225        },
6226        Placeholder(String),
6227        Enabled(bool),
6228        /// Select a range of the field's text, or place the caret when the range is empty
6229        /// (docs/textfield.md "Selection"). Sent after any [`TextFieldPatch::Text`] of the same
6230        /// turn, so the range always counts the text the field now holds. A backend clamps it
6231        /// against its own text with [`TextSelection::utf16`] or [`TextSelection::bytes`] and
6232        /// applies it to a focused field; whether an unfocused field keeps it is the platform's
6233        /// (docs/textfield.md).
6234        Select(TextSelection),
6235    }
6236
6237    /// A range of a text field's text in Unicode scalar values (Rust `char`s), the unit
6238    /// [`TextFieldPatch::Select`] carries on every backend. `start..end` is half-open, and an
6239    /// empty range is a caret position. The helpers clamp to the text and convert to the unit a
6240    /// native field counts: UTF-16 code units (Apple, Android, Qt, WinUI, the web, ArkUI) or
6241    /// bytes. GTK counts characters, which is [`TextSelection::clamped`].
6242    #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
6243    pub struct TextSelection {
6244        pub start: usize,
6245        pub end: usize,
6246    }
6247
6248    impl TextSelection {
6249        /// The range from `start` to `end`, ordered so that `start <= end`.
6250        pub fn new(start: usize, end: usize) -> Self {
6251            TextSelection {
6252                start: start.min(end),
6253                end: start.max(end),
6254            }
6255        }
6256
6257        /// The range held to `text`: both ends at most its character count, `start <= end`.
6258        pub fn clamped(self, text: &str) -> Self {
6259            let n = text.chars().count();
6260            TextSelection::new(self.start.min(n), self.end.min(n))
6261        }
6262
6263        /// The clamped range as UTF-16 code-unit offsets into `text`: `(start, end)`.
6264        pub fn utf16(self, text: &str) -> (usize, usize) {
6265            let r = self.clamped(text);
6266            let at = |chars: usize| -> usize {
6267                text.chars().take(chars).map(char::len_utf16).sum::<usize>()
6268            };
6269            (at(r.start), at(r.end))
6270        }
6271
6272        /// The clamped range as UTF-8 byte offsets into `text`: `(start, end)`, each on a
6273        /// character boundary.
6274        pub fn bytes(self, text: &str) -> (usize, usize) {
6275            let r = self.clamped(text);
6276            let at = |chars: usize| -> usize {
6277                text.char_indices()
6278                    .nth(chars)
6279                    .map_or(text.len(), |(i, _)| i)
6280            };
6281            (at(r.start), at(r.end))
6282        }
6283    }
6284
6285    #[cfg(test)]
6286    mod text_selection_tests {
6287        use super::TextSelection;
6288
6289        #[test]
6290        fn orders_and_clamps() {
6291            assert_eq!(TextSelection::new(5, 2), TextSelection { start: 2, end: 5 });
6292            let r = TextSelection::new(3, usize::MAX).clamped("github.com");
6293            assert_eq!(r, TextSelection { start: 3, end: 10 });
6294            let past = TextSelection::new(40, 50).clamped("git");
6295            assert_eq!(past, TextSelection { start: 3, end: 3 });
6296            assert_eq!(
6297                TextSelection::new(0, 9).clamped(""),
6298                TextSelection::default()
6299            );
6300        }
6301
6302        #[test]
6303        fn converts_to_native_units() {
6304            // "é" is one char, one UTF-16 unit and two bytes; "😀" is one char, two UTF-16
6305            // units and four bytes.
6306            let text = "aé😀b";
6307            assert_eq!(TextSelection::new(1, 3).utf16(text), (1, 4));
6308            assert_eq!(TextSelection::new(1, 3).bytes(text), (1, 7));
6309            assert_eq!(TextSelection::new(0, usize::MAX).utf16(text), (0, 5));
6310            assert_eq!(TextSelection::new(0, usize::MAX).bytes(text), (0, 8));
6311            assert_eq!(TextSelection::new(4, 4).bytes(text), (8, 8));
6312        }
6313    }
6314
6315    /// How an image is scaled to fill its frame (§18.3). Maps to each toolkit's native scaling.
6316    #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
6317    pub enum ContentMode {
6318        /// Scale to fit entirely inside the frame, preserving aspect ratio (letterboxed). The
6319        /// default: an image never stretches unless asked. SwiftUI's `.scaledToFit`.
6320        #[default]
6321        Fit,
6322        /// Scale to fill the frame, preserving aspect ratio and cropping the overflow. SwiftUI's
6323        /// `.scaledToFill`.
6324        Fill,
6325        /// Stretch to fill the frame exactly, ignoring aspect ratio.
6326        Stretch,
6327    }
6328
6329    #[derive(Clone, Debug, Default, PartialEq)]
6330    pub struct ImageProps {
6331        /// Which pixels to draw: a staged asset name, encoded bytes, or an already-decoded
6332        /// image ([`ImageSource`], docs/images.md). A name resolves through the backend's own
6333        /// pipeline (§18.2); bytes and decoded ids need [`Cap::ImageDecode`], and a backend
6334        /// without it draws nothing rather than guessing.
6335        pub source: ImageSource,
6336        pub decorative: bool,
6337        /// How the image scales within its frame (default [`ContentMode::Fit`], no stretching).
6338        pub content_mode: ContentMode,
6339        /// Optional width:height ratio the view is constrained to (e.g. `16.0/9.0`). `None` lets the
6340        /// image take its allocated frame.
6341        pub aspect_ratio: Option<f64>,
6342        /// Monochrome tint for a template/vector glyph (docs/vectors.md): backends that can,
6343        /// recolor natively (template rendering on Apple, drawable tint on Android, pixel
6344        /// recolor on GTK); backends that can't yet ignore it and draw the source colors.
6345        /// `None` (the default, and every raster `image(…)`) means "as authored".
6346        pub tint: Option<Color>,
6347        /// A monochrome template glyph (docs/vectors.md "Template"): with no `tint`, it draws
6348        /// in the foreground of the surface it sits on — the theme's label color on the
6349        /// desktops, the cell's tint on UIKit, `currentColor` on the web — and follows a
6350        /// theme switch. What a sidebar row's untinted icon is: a tinted glyph recolors the
6351        /// same way with or without this, and `false` (the default) draws an untinted glyph as
6352        /// authored. [`ImagePatch::Tint`]`(None)` on a template returns to that foreground,
6353        /// not to the authored colors.
6354        pub template: bool,
6355    }
6356
6357    /// A list row's standard content (`kinds::LIST_ITEM`, docs/list.md "List items"). Empty
6358    /// text means the part is absent.
6359    #[derive(Clone, Debug, Default, PartialEq)]
6360    pub struct ListItemProps {
6361        pub title: String,
6362        /// A second line under the title, in the platform's secondary style.
6363        pub subtitle: String,
6364        /// Trailing text (a count, a value), in the platform's secondary style.
6365        pub detail: String,
6366        /// The leading glyph: a symbol or a bundled image.
6367        pub icon: Option<crate::Icon>,
6368        /// The glyph's color; `None` takes the platform's own (template glyphs follow the
6369        /// foreground, the tint color on UIKit).
6370        pub icon_tint: Option<Color>,
6371        /// A trailing check mark: the platform's selected-option mark (UIKit's checkmark
6372        /// accessory, a Material check icon), announced as checked.
6373        pub checked: bool,
6374    }
6375
6376    /// A live change to a realized list item; every part changes in place.
6377    #[derive(Clone, Debug, PartialEq)]
6378    pub enum ListItemPatch {
6379        Title(String),
6380        Subtitle(String),
6381        Detail(String),
6382        Icon(Option<crate::Icon>),
6383        IconTint(Option<Color>),
6384        Checked(bool),
6385    }
6386
6387    /// A live change to a realized image or vector glyph.
6388    ///
6389    /// `content_mode` and the rest still describe which art this is and how it fills its frame,
6390    /// which a rebuild expresses better than a patch. Two things do want to follow a signal: the
6391    /// tint (a glyph that recolors with the selection or the theme should repaint, not be torn
6392    /// down and realized again, docs/vectors.md "Tint") and the source, now that it can be a
6393    /// buffer the app swaps (a download landing, a new photo picked, docs/images.md). Replacing
6394    /// the pixels of a view that is already on screen is what a patch is for; realizing a second
6395    /// view would flash.
6396    #[derive(Clone, Debug, PartialEq)]
6397    pub enum ImagePatch {
6398        /// Recolor the glyph, or `None` to draw the authored colors again.
6399        Tint(Option<Color>),
6400        /// Draw different pixels in the same view. A backend that cannot decode the new source
6401        /// (bytes where [`Cap::ImageDecode`] is `Unsupported`) leaves what it was drawing.
6402        Source(ImageSource),
6403    }
6404
6405    #[derive(Clone, Debug, Default, PartialEq)]
6406    pub struct CanvasProps {
6407        pub ops: Vec<DrawOp>,
6408    }
6409
6410    /// Progress indicator. `value` is the completed fraction in `0.0..=1.0`; `None` means
6411    /// indeterminate (an animated spinner / busy bar, no known extent). Backends map this to
6412    /// their native determinate/indeterminate widgets (docs/progress.md).
6413    #[derive(Clone, Debug, PartialEq)]
6414    pub struct ProgressProps {
6415        pub value: Option<f64>,
6416        /// Whether an indeterminate indicator animates; ignored for a determinate bar.
6417        pub animating: bool,
6418        /// The platform's large indicator size.
6419        pub large: bool,
6420    }
6421    impl Default for ProgressProps {
6422        fn default() -> Self {
6423            Self {
6424                value: None,
6425                animating: true,
6426                large: false,
6427            }
6428        }
6429    }
6430    #[derive(Clone, Debug, PartialEq)]
6431    pub enum ProgressPatch {
6432        Animating(bool),
6433        /// New completed fraction, or `None` to switch to indeterminate.
6434        Value(Option<f64>),
6435    }
6436
6437    /// A rule between neighbors (`divider()`): a hairline across the width it is offered, or,
6438    /// with `vertical`, down the height it is offered (`divider().vertical()`, between a
6439    /// row's panes). A toolkit measures both the same way, as a horizontal rule, because the
6440    /// pieces layer swaps the axes of a vertical one's proposal and answer; realization is
6441    /// where the orientation matters, for the few widgets that draw a horizontal line
6442    /// regardless of their frame.
6443    #[derive(Clone, Debug, Default, PartialEq)]
6444    pub struct DividerProps {
6445        pub vertical: bool,
6446    }
6447
6448    /// How a navigation host lays its panes out (docs/navigation.md).
6449    ///
6450    /// This is the resolved presentation, what the toolkit must draw right now. The app asks for
6451    /// one through `Nav::presentation`, where leaving it unset means "automatic": the pieces
6452    /// layer resolves it from the window's [`SizeClass`] and the toolkit's `Cap::NavSplit`, and
6453    /// re-resolves it whenever the class changes. There is no `Auto` variant here because a
6454    /// backend can only ever draw a concrete one, so the undecided state stays on the app's side
6455    /// of the boundary where it can still be decided.
6456    #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
6457    pub enum NavPresentation {
6458        /// Sidebar beside detail, both visible (`NSSplitViewController`, nested `GtkPaned`s,
6459        /// a `NavigationView`). The sidebar pane gets its own container.
6460        Split,
6461        /// One page at a time, back-navigable. The sidebar pane becomes the stack's root.
6462        #[default]
6463        Stack,
6464        /// The rows drawn as a tab bar, one page's content beside it, no back stack: what a
6465        /// phone-shaped window wants from a one-of-N surface (`UITabBarController`, a Material
6466        /// `NavigationBarView`, `NavigationView.PaneDisplayMode = Top`). The `Pane::Sidebar` page
6467        /// is not drawn at all: its rows are the chrome.
6468        Tabs,
6469        /// The rows drawn as a narrow icon strip beside the content, the `Medium`-width answer
6470        /// between [`Self::Tabs`] and [`Self::Split`] (a Material `NavigationRailView`,
6471        /// `PaneDisplayMode = LeftCompact`, an ArkUI vertical `Tabs`).
6472        ///
6473        /// A backend with no rail rounds it to a neighbor of its own choosing rather than
6474        /// failing: UIKit answers `Tabs` (which is what iPadOS does at that width), GTK the same.
6475        /// Rounding is expected and correct; this variant is a request, not a contract.
6476        Rail,
6477    }
6478
6479    impl NavPresentation {
6480        /// `true` for [`NavPresentation::Split`], the shape most backend code wants.
6481        pub fn is_split(self) -> bool {
6482            self == NavPresentation::Split
6483        }
6484
6485        /// `true` when the rows are the chrome rather than a drawn page: [`Self::Tabs`] and
6486        /// [`Self::Rail`]. Both hide the `Pane::Sidebar` page and render its rows themselves, so
6487        /// backend code that only cares about that distinction asks this instead of matching both.
6488        pub fn rows_are_chrome(self) -> bool {
6489            matches!(self, NavPresentation::Tabs | NavPresentation::Rail)
6490        }
6491    }
6492
6493    /// Navigation host (docs/navigation.md).
6494    #[derive(Clone, Debug, Default, PartialEq)]
6495    pub struct NavProps {
6496        /// Document-tab chrome, independent of navigation destinations.
6497        pub documents: Option<DocumentTabsConfig>,
6498        pub title: String,
6499        /// The presentation to draw now; re-presented in place by [`NavPatch::Presentation`].
6500        pub presentation: NavPresentation,
6501        /// The app left the presentation automatic (`NavStyle::Automatic`, or a `Sidebar`
6502        /// nav host with no `.presentation(…)` pin), so it is free to follow the window.
6503        ///
6504        /// Only a toolkit answering `Cap::NavRepresent = Emulated` needs this: its own adaptive
6505        /// container owns the morph, and it must know whether the app asked for one at all before
6506        /// building it. With two presentations that bit could be inferred from a lowered `Split`;
6507        /// with four it cannot, so it is carried explicitly rather than encoded.
6508        ///
6509        /// `Native` re-presenters ignore it (they are told each presentation as it is resolved),
6510        /// and so do toolkits that cannot re-present.
6511        pub adaptive: bool,
6512        /// Draw the platform's own show/hide-sidebar affordance on this host's chrome
6513        /// (docs/toolbars.md). `true` for every `nav(Sidebar)` unless the app opted out:
6514        /// the toolkit owns both the button and the behavior
6515        /// (`NSToolbarToggleSidebarItemIdentifier`, the split view's collapse on GTK,
6516        /// `NavigationView.IsPaneOpen` on XAML), so an app that once declared the item by hand
6517        /// now declares nothing. Hosts with no sidebar ignore it.
6518        pub sidebar_toggle: bool,
6519        /// Search over this navigation surface (`Nav::searchable`, docs/search.md).
6520        /// `None` = the surface is not searchable and no field is rendered anywhere.
6521        pub search: Option<SearchProps>,
6522        /// `Some(width)` = this host has a content-list pane ([`Pane::List`]) at this preferred
6523        /// width in points, between the sidebar and the detail (docs/navigation.md). Read at
6524        /// realize, because a backend that builds a different container for a three-pane host
6525        /// (UIKit's triple-column style is init-only) needs to know before it builds. `None` on
6526        /// every host without one, including all of them on backends answering
6527        /// [`crate::Cap::NavContentList`] `Unsupported`: the pieces layer composes there and
6528        /// the prop is never set.
6529        pub list_width: Option<f64>,
6530        /// Whether that pane is showing for the destination the host opens on
6531        /// (`Nav::content_list_for`). Read at realize, like `list_width`, and for a
6532        /// related reason: a backend whose pane is a real split item can only honor a
6533        /// collapsed state reliably by setting it before the item joins the split. Told
6534        /// afterwards (by `NavPatch::ListVisible`, on a window that has not been displayed
6535        /// yet), AppKit reports the item collapsed and then lays it back out from its holding
6536        /// priorities, and the app opens with a list beside a page that does not own one.
6537        /// `true` on every host whose first destination has a list, and on hosts with no pane
6538        /// at all, where it means nothing.
6539        pub list_visible: bool,
6540    }
6541
6542    /// Switch only tab chrome; resident contents must retain their native identity.
6543    #[derive(Clone, Copy, Debug, PartialEq)]
6544    pub struct DocumentTabsPatch {
6545        pub native: bool,
6546    }
6547
6548    /// Localized document-tab chrome. Native callbacks emit stable route keys.
6549    #[derive(Clone, Debug, Default, PartialEq)]
6550    pub struct DocumentTabsConfig {
6551        pub new_label: String,
6552        pub close_label: String,
6553        pub can_add: bool,
6554    }
6555
6556    /// Where a searchable surface's field should be drawn.
6557    ///
6558    /// A preference, not an instruction: a backend that cannot honor the request falls back to
6559    /// whatever its platform does, exactly as SwiftUI's `searchable(placement:)` does ("depending
6560    /// on the containing view hierarchy and platform, the requested placement may not be able to
6561    /// be fulfilled"). `Automatic` is the one to reach for: it is what lets the field live in the
6562    /// window toolbar on a wide window and move into the navigation list on a narrow one.
6563    #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
6564    pub enum SearchPlacement {
6565        /// The platform decides, from the window's size class and its own convention.
6566        #[default]
6567        Automatic,
6568        /// In the window's toolbar (`NSSearchToolbarItem`, an `AdwHeaderBar` entry, a
6569        /// `CommandBar` `AutoSuggestBox`). `Inline` where the toolbar cannot hold a search field
6570        /// (`Cap::ToolbarSearch`).
6571        Toolbar,
6572        /// Attached to the navigation surface itself: above the sidebar list, or in the
6573        /// navigation bar's search drawer on the phones.
6574        Inline,
6575    }
6576
6577    /// Search over a navigation surface (docs/search.md). The query itself stays an app-owned
6578    /// signal; this carries only what the toolkit must draw, so moving the field between
6579    /// placements never moves the state.
6580    #[derive(Clone, Debug, Default, PartialEq)]
6581    pub struct SearchProps {
6582        /// Current text. Two-way: the user typing emits [`Event::SearchChanged`], and the app's
6583        /// own writes arrive as [`SearchPatch::Text`].
6584        pub text: String,
6585        /// Empty-state prompt.
6586        pub prompt: String,
6587        pub placement: SearchPlacement,
6588        /// Opt into native scrolling search/title chrome on mobile. Default false keeps
6589        /// the field pinned. Desktop toolbar search is unchanged.
6590        pub hides_on_scroll: bool,
6591        /// Start the UIKit navigation search drawer collapsed, with a compact toolbar title.
6592        /// Implies scrolling search on UIKit; ignored by other backends. Default false.
6593        pub initially_hidden: bool,
6594        /// Scope titles, empty = no scope bar. One-of-N: a `UISearchBar` scope bar, a Material
6595        /// `ChipGroup` of single-selection filter chips, an ArkUI `SegmentButtonV2`, an
6596        /// `NSSegmentedControl` (docs/search.md has the per-backend table).
6597        pub scopes: Vec<String>,
6598        /// Index into `scopes`; meaningless when `scopes` is empty.
6599        pub scope: usize,
6600        /// Completions offered for the current text. On a navigation surface these complete the
6601        /// field rather than replacing the list: the list is already the result set, so an
6602        /// overlay of results would cover the thing it is filtering.
6603        pub suggestions: Vec<String>,
6604    }
6605
6606    /// A targeted update to a live search field, the path a bound signal writes through, so
6607    /// syncing text never rebuilds (and refocuses) the field mid-word.
6608    #[derive(Clone, Debug, PartialEq)]
6609    pub enum SearchPatch {
6610        Focus,
6611        Text(String),
6612        Scope(usize),
6613        Suggestions(Vec<String>),
6614    }
6615    /// Applied to the nav host after a page child is attached / before it is removed;
6616    /// the toolkit animates its native presentation accordingly.
6617    #[derive(Clone, Debug, PartialEq)]
6618    pub enum NavPatch {
6619        /// The just-attached last page child became the top of the stack. `immersive` marks a
6620        /// page that keeps the floating transparent chrome on backends with an immersive nav
6621        /// mode (day-toolkit-material edge-to-edge today; ignored elsewhere). Unmarked pages get the
6622        /// standard opaque bar.
6623        Pushed { title: String, immersive: bool },
6624        /// The top page is about to be removed; present its predecessor.
6625        Popped,
6626        /// Current top-of-stack title changed.
6627        Title(String),
6628        /// The top page has a back guard (`NavStack::on_back`, docs/navigation.md): while `true`,
6629        /// the toolkit must not auto-pop on a native back gesture/button but route it to
6630        /// Day as `Event::NavBack { already_popped: false }` so the app's guard decides. On
6631        /// backends whose back already routes through Day (AppKit/Qt/XAML/web custom headers)
6632        /// this is a no-op; iOS disables the swipe, Android holds its callback, GTK sets the
6633        /// page `can-pop=false`, ArkUI consumes `onBackPressed`.
6634        GuardTop(bool),
6635        /// Re-present the host: the window's size class crossed a breakpoint, or the app wrote a
6636        /// new `presentation`. The page children do not change: the toolkit rebuilds its
6637        /// chrome and re-homes the pages it already has, each one landing by its
6638        /// [`NavPageProps::pane`]. Rebuilding them instead would drop scroll offsets, field
6639        /// focus, and every native animation in flight, which is why this is a patch and not
6640        /// a rebuild.
6641        ///
6642        /// Backends with no split container ignore it and stay stacked.
6643        Presentation(NavPresentation),
6644        /// Show the resident [`Pane::Detail`] page at this index, counting the host's detail
6645        /// children in attach order. The counterpart to [`Self::Pushed`]/[`Self::Popped`] for the
6646        /// presentations where pages are resident rather than stacked
6647        /// ([`NavPresentation::rows_are_chrome`]): a tab bar switches between pages that all stay
6648        /// alive, so there is nothing to push and nothing to pop.
6649        ///
6650        /// Applied without re-emitting [`crate::Event::SelectionChanged`], per the from-native
6651        /// echo rule: this is the programmatic-sync direction.
6652        ///
6653        /// A backend drawing a stacked presentation never receives it; the pieces layer sends
6654        /// push/pop there instead.
6655        Select(usize),
6656        /// Reorder resident detail pages by their previous indices without rebuilding them.
6657        Reorder(Vec<usize>),
6658        /// Show or collapse the content-list pane ([`Pane::List`]), the per-destination
6659        /// visibility switch (`Nav::content_list_for`, docs/navigation.md): a nav host
6660        /// section that spans the whole detail area (a settings page) collapses the pane, and
6661        /// selecting a list-backed section brings it back. Only sent to hosts whose
6662        /// [`NavProps::list_width`] is set. Applied directly, not through an animator proxy:
6663        /// the screenshot step captures the instant the patch returns (the sidebar-toggle rule).
6664        ListVisible(bool),
6665        /// Stacked presentations on a merged-pane backend ([`crate::Cap::NavContentList`]
6666        /// `Emulated`) only: the resident [`Pane::List`] page joins (`true`) or leaves
6667        /// (`false`) the navigation stack directly above the sidebar root. The pieces layer
6668        /// sends it as the selection gains or loses a list-backed destination; the backend
6669        /// realizes the membership change through its platform's navigation APIs (UIKit:
6670        /// `showColumn(.supplementary)` / a pop to the root; never a manual splice, which
6671        /// destroys the split's collapse bookkeeping). Never sent to `Native` backends (their
6672        /// pane persists through every presentation) nor while split.
6673        ListInStack(bool),
6674    }
6675
6676    /// Which pane of a navigation host a page belongs to (docs/navigation.md).
6677    ///
6678    /// A page's pane is a fact about the model, not about how the host currently draws it: a
6679    /// nav host's list page is [`Pane::Sidebar`] whether the toolkit is showing a sidebar beside
6680    /// a detail or stacking the two. What the presentation decides is where each pane lands:
6681    /// its own splitter pane in [`NavPresentation::Split`], the root of the stack in
6682    /// [`NavPresentation::Stack`]. Keeping the two separate is what lets a host re-present on a
6683    /// size-class change (`NavPatch::Presentation`) by re-homing the pages it already has,
6684    /// instead of tearing the tree down and rebuilding it.
6685    #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
6686    pub enum Pane {
6687        /// The list / master pane of a nav host. At most one page per host.
6688        Sidebar,
6689        /// The content-list pane between the sidebar and the detail, Mail's message list
6690        /// (`Nav::content_list`, docs/navigation.md). At most one page per host, and only
6691        /// on hosts whose [`NavProps::list_width`] is set; a backend answering
6692        /// [`crate::Cap::NavContentList`] `Unsupported` never sees one.
6693        List,
6694        /// A destination page. Every page of a `nav_stack` presentation is one of these.
6695        #[default]
6696        Detail,
6697    }
6698
6699    /// One destination's native container.
6700    #[derive(Clone, Debug, Default, PartialEq)]
6701    pub struct NavPageProps {
6702        pub title: String,
6703        pub pane: Pane,
6704    }
6705
6706    /// The largest a modal sheet grows on a desktop, in points: the window less a margin up to
6707    /// this (docs/cover.md "Modal sheet"). AppKit's native sheet and the composed card share it.
6708    pub const SHEET_MAX: crate::Size = crate::Size::new(640.0, 620.0);
6709    /// The largest a [`CoverProps::large`] sheet grows (docs/cover.md "Large sheet").
6710    pub const LARGE_SHEET_MAX: crate::Size = crate::Size::new(1040.0, 880.0);
6711
6712    /// A fullscreen cover's content container (docs/cover.md). Realized detached and hidden;
6713    /// `CoverPatch::Present` shows it over the whole window.
6714    #[derive(Clone, Debug, Default, PartialEq)]
6715    pub struct CoverProps {
6716        /// Prefer a native sheet; toolkits without sheet presentation keep their modal cover.
6717        pub sheet: bool,
6718        /// A half-height sheet rising from the bottom edge, the window content above it
6719        /// staying on show and, where the platform allows, interactive: an inspector over the
6720        /// canvas it describes. Implies `sheet`. The toolkit reports the sheet's own content
6721        /// size through `FrameChanged`, as for any cover (docs/cover.md "Half sheet").
6722        pub half: bool,
6723        /// A large sheet: most of the window, less a margin, for a document or web page that
6724        /// needs the room (docs/cover.md "Large sheet"). Implies `sheet`.
6725        pub large: bool,
6726    }
6727
6728    /// Applied to a `kinds::COVER` node as its bound signal opens and closes it.
6729    #[derive(Clone, Debug, PartialEq)]
6730    pub enum CoverPatch {
6731        /// Present the cover fullscreen (slide up where the platform animates modals).
6732        /// `background` paints the whole surface edge-to-edge (under the status bar / home
6733        /// indicator); the content container is inset to the safe area within it.
6734        /// `dismiss_disabled` = the user must not be able to dismiss it interactively
6735        /// (system back / sheet gestures); programmatic dismissal still works.
6736        Present {
6737            background: Option<Color>,
6738            dismiss_disabled: bool,
6739        },
6740        /// The `interactive_dismiss_disabled` state changed while presented.
6741        DismissDisabled(bool),
6742        /// Dismiss the cover. When the hide transition finishes the backend emits
6743        /// [`crate::Event::CoverHidden`] on the node (trampoline backends send
6744        /// `BridgeKind::CoverHidden`), letting the piece dispose the content only after it
6745        /// left the screen.
6746        Dismiss,
6747    }
6748
6749    /// A `kinds::INSPECTOR` split (docs/inspector.md): content beside a trailing inspector
6750    /// pane. The pane's visibility is Day-owned state (the piece's bound signal), so the
6751    /// props carry the value to draw and [`InspectorPatch::Visible`] keeps it current;
6752    /// a native affordance hiding the pane (a dock close button, a dragged-shut divider)
6753    /// reports back with [`crate::Event::InspectorChanged`].
6754    #[derive(Clone, Debug, PartialEq)]
6755    pub struct InspectorProps {
6756        /// Whether the pane is showing now.
6757        pub visible: bool,
6758        /// The pane's preferred width in points. A backend with a user-draggable divider
6759        /// treats it as the initial width; one without draws it at exactly this.
6760        pub width: f64,
6761        /// Which side of the content the pane sits on. `Trailing` is the classic inspector;
6762        /// `Leading` is a utility pane like a layer panel (docs/tree.md).
6763        pub edge: PaneEdge,
6764    }
6765
6766    /// Which side an inspector pane occupies (docs/inspector.md).
6767    #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
6768    pub enum PaneEdge {
6769        #[default]
6770        Trailing,
6771        Leading,
6772    }
6773
6774    /// Applied to a `kinds::INSPECTOR` node as its bound signal changes.
6775    #[derive(Clone, Debug, PartialEq)]
6776    pub enum InspectorPatch {
6777        /// Show or hide the pane (animated where the platform animates panes). The
6778        /// programmatic-sync direction: applying it must not re-emit
6779        /// [`crate::Event::InspectorChanged`], per the from-native echo rule.
6780        Visible(bool),
6781    }
6782
6783    /// One pane of a `kinds::INSPECTOR` split (docs/inspector.md).
6784    #[derive(Clone, Debug, Default, PartialEq)]
6785    pub struct InspectorPaneProps {
6786        /// `true` for the inspector panel itself, `false` for the content pane.
6787        pub panel: bool,
6788    }
6789
6790    /// How a `kinds::SPLIT` lays its two panes (docs/split.md): beside each other, the divider
6791    /// standing, or stacked, the divider lying. Named by where the panes go, since that is
6792    /// what an app's "layout" toggle means; the divider runs the other way.
6793    #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
6794    pub enum SplitAxis {
6795        /// The panes side by side (first leading), the divider vertical.
6796        #[default]
6797        Horizontal,
6798        /// The panes stacked (first on top), the divider horizontal.
6799        Vertical,
6800    }
6801
6802    /// A `kinds::SPLIT` (docs/split.md): two panes with a divider the user drags. The first
6803    /// pane's share is Day-owned state (the piece's bound signal): the props carry the value
6804    /// to draw, [`SplitPatch::Fraction`] keeps it current, and a divider the user moved
6805    /// reports back as [`crate::Event::ValueChanged`] with the new share, which applying the
6806    /// patch must never re-emit (the from-native echo rule).
6807    #[derive(Clone, Debug, PartialEq)]
6808    pub struct SplitProps {
6809        pub axis: SplitAxis,
6810        /// The first pane's share of the split's length along `axis`, `0.0..=1.0`.
6811        pub fraction: f64,
6812        /// The least length either pane may be dragged to, in points.
6813        pub min_pane: f64,
6814    }
6815
6816    /// Applied to a `kinds::SPLIT` node as its bound signals change.
6817    #[derive(Clone, Debug, PartialEq)]
6818    pub enum SplitPatch {
6819        /// Turn the split the other way, keeping the share.
6820        Axis(SplitAxis),
6821        /// Move the divider so the first pane takes this share. The programmatic-sync
6822        /// direction: applying it must not re-emit [`crate::Event::ValueChanged`].
6823        Fraction(f64),
6824    }
6825
6826    /// One pane of a `kinds::SPLIT` (docs/split.md).
6827    #[derive(Clone, Debug, Default, PartialEq)]
6828    pub struct SplitPaneProps {
6829        /// `false` for the first pane, `true` for the second.
6830        pub second: bool,
6831    }
6832
6833    /// Native navigation item list. `items` are display titles in route order;
6834    /// `selected` highlights the active route (split presentation; None on mobile roots).
6835    /// `icons` (parallel to `items`, `None` = no icon) are bundled image names resolved by each
6836    /// backend via `resource::resolve_image_file`; a backend that can't decorate its rows just
6837    /// ignores them.
6838    #[derive(Clone, Debug, Default, PartialEq)]
6839    pub struct NavMenuProps {
6840        /// Stable document identities, parallel to items; empty for ordinary navigation.
6841        pub document_keys: Vec<String>,
6842        pub items: Vec<String>,
6843        pub icons: Vec<Option<String>>,
6844        /// A trailing accessory per row: an unread count, a status. Rendered right-aligned and
6845        /// de-emphasized, opposite the label. Parallel to `items`; `None` draws nothing.
6846        pub badges: Vec<Option<String>>,
6847        /// A trailing symbol accessory per row, in the same slot as [`Self::badges`] and drawn
6848        /// after it: a bundled image name resolved the way [`Self::icons`] is. This is what a
6849        /// row-level status glyph rides on (a starred page's star) where `badges` carries only
6850        /// text. Parallel to `items`; `None` draws nothing.
6851        pub badge_icons: Vec<Option<String>>,
6852        /// The tint for [`Self::badge_icons`], parallel to `items`. `None` leaves the glyph at
6853        /// the backend's neutral template tint; a status glyph that means something (a yellow
6854        /// star) names its own color here, exactly as [`Self::tints`] does for the leading icon.
6855        pub badge_tints: Vec<Option<Color>>,
6856        /// A per-row icon tint (docs/vectors.md): the row's glyph recolored to this instead of
6857        /// the backend's neutral template tint. Parallel to `items`; `None` keeps the default.
6858        pub tints: Vec<Option<Color>>,
6859        /// A section header introducing the row at the same index. `Some` opens a new group
6860        /// before that row; `None` continues the current one. Parallel to `items`, so adding a
6861        /// header never shifts the selection indices the rows are addressed by.
6862        pub sections: Vec<Option<String>>,
6863        /// A per-row context menu (docs/menus.md): shown on secondary-click / long-press on
6864        /// that row, the same [`crate::MenuItem`] model as everywhere else: items carry
6865        /// registered action ids, so a chosen entry dispatches [`crate::Event::MenuAction`]
6866        /// exactly like a piece context menu. Parallel to `items`; empty = no menu.
6867        pub menus: Vec<Vec<crate::MenuItem>>,
6868        /// Which rows drag to reorder (docs/navigation.md "Reordering sidebar destinations"),
6869        /// parallel to `items`; empty when the sidebar does not reorder. A row moves only
6870        /// within the run of movable rows around it, which a section header or a fixed row
6871        /// ends. A toolkit whose `Cap::NavReorder` is `Native` drags the rows in its own
6872        /// sidebar and reports a drop as [`crate::Event::ListReorder`] in item indices: `from`
6873        /// is the moved row, `to` the row whose position it takes, in the order before the move.
6874        pub movable: Vec<bool>,
6875        /// The sidebar regroups (docs/navigation.md "Moving rows between sections"): a movable
6876        /// row may also cross section headers, into any section whose rows are all movable. A
6877        /// toolkit whose `Cap::NavReorder` is `Native` offers those drops too and reports every
6878        /// drop as [`crate::Event::NavRegroup`] instead of [`crate::Event::ListReorder`]. `false`
6879        /// keeps [`Self::movable`]'s run rule.
6880        pub regroup: bool,
6881        /// Which movable rows keep the app's sorted order within their own section, parallel to
6882        /// `items`; empty when the sidebar does not regroup. Under [`Self::regroup`], a sorted
6883        /// row drops only into another section: no gap in its own section is offered.
6884        pub sorted: Vec<bool>,
6885        pub selected: Option<usize>,
6886    }
6887    #[derive(Clone, Debug, PartialEq)]
6888    // `Items` carries every row array; a patch travels boxed (`Box<dyn Any>`) and lives for one
6889    // update, so the variants' size difference costs nothing worth an indirection.
6890    #[allow(clippy::large_enum_variant)]
6891    pub enum NavMenuPatch {
6892        /// Active icon overlays by row index: None spins, Some(0..=1) fills a circle.
6893        /// Rows absent from this complete snapshot have no overlay. Does not relayout rows.
6894        /// Currently rendered by AppKit/UIKit; other backends may ignore this decoration.
6895        IconProgress(Vec<(usize, Option<f64>)>),
6896        /// Programmatic highlight sync: toolkits apply without re-emitting
6897        /// SelectionChanged (the TextField from_native echo rule).
6898        Selected(Option<usize>),
6899        /// The item set changed (data-driven `nav().items(signal, …)`): rebuild the rows
6900        /// from these labels/icons, then apply `selected` (docs/navigation.md). Applied without
6901        /// re-emitting SelectionChanged.
6902        ///
6903        /// `rows_changed` is `Some` when the rows themselves are the ones already shown (same
6904        /// keys, sections and row menus) and only these rows' title, icon, tint or badge moved:
6905        /// a count ticking, a language change. A backend updates those rows in place (a tab's
6906        /// badge, a menu item's title) rather than rebuilding, which on most platforms re-lays
6907        /// the bar and replays its selection animation; one that cannot rebuilds as for `None`.
6908        Items {
6909            rows_changed: Option<Box<[usize]>>,
6910            document_keys: Box<[String]>,
6911            items: Vec<String>,
6912            icons: Vec<Option<String>>,
6913            badges: Vec<Option<String>>,
6914            badge_icons: Vec<Option<String>>,
6915            badge_tints: Vec<Option<Color>>,
6916            sections: Vec<Option<String>>,
6917            tints: Vec<Option<Color>>,
6918            menus: Vec<Vec<crate::MenuItem>>,
6919            /// [`NavMenuProps::movable`] for the new rows.
6920            movable: Vec<bool>,
6921            /// [`NavMenuProps::sorted`] for the new rows ([`NavMenuProps::regroup`] holds for
6922            /// the sidebar's life).
6923            sorted: Vec<bool>,
6924            selected: Option<usize>,
6925        },
6926    }
6927
6928    /// How a recycling list sizes its rows (docs/list.md).
6929    #[derive(Clone, Copy, Debug, PartialEq, Default)]
6930    pub enum RowHeight {
6931        /// Every row is this tall, a true layout boundary; the fastest path.
6932        Uniform(f64),
6933        /// Rows self-size from their content (host re-measures on change; slower).
6934        #[default]
6935        Automatic,
6936    }
6937
6938    /// Configure a navigation sidebar's native pull-to-refresh control. Not a synthetic pan:
6939    /// supported toolkits own gesture arbitration and the progress indicator. A false state
6940    /// ends a pull, including a request the application declines. Never emits an event.
6941    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
6942    pub struct RefreshPatch {
6943        pub refreshing: bool,
6944    }
6945
6946    /// Native recycling list (docs/list.md). The host owns scrolling + cell reuse; Day supplies
6947    /// row content on demand through the injected `ListSource` (see `Toolkit::attach_list`).
6948    #[derive(Clone, Debug, Default, PartialEq)]
6949    pub struct ListProps {
6950        /// Whether the app handles row activation. Do not claim activation keys when false.
6951        pub activatable: bool,
6952        pub row_height: RowHeight,
6953        /// Whether the native list reports row selection (`Event::SelectionChanged` with the row).
6954        pub selectable: bool,
6955        /// Whether the native list allows selecting several rows at once. Where honored
6956        /// (docs/list.md has the matrix), every selection change reports the full set via
6957        /// `Event::SelectionSet`; single-selection backends keep reporting
6958        /// `Event::SelectionChanged` and treat this as `selectable`.
6959        pub multi_select: bool,
6960        /// Whether rows can be drag-reordered. The toolkit enables its native drag machinery and
6961        /// drives `ListSource::reorder` (validate via `can_move`, commit via `move_row`);
6962        /// probe `Cap::ListReorder` for per-backend support (docs/list.md).
6963        pub reorderable: bool,
6964        /// Whether rows can be deleted by the platform's own delete gesture: a trailing swipe on
6965        /// iOS and ArkUI, an `ItemTouchHelper` swipe on Android. The toolkit drives
6966        /// `ListSource::delete` (offer via `can_delete`, commit via `delete_row`); probe
6967        /// `Cap::ListDelete` for per-backend support (docs/list.md). Desktop toolkits have no such
6968        /// gesture and answer `Unsupported`; an app that must delete everywhere pairs this with an
6969        /// explicit control (a menu item, a button) rather than relying on the swipe.
6970        pub deletable: bool,
6971        /// The label on that affordance, already localized by the app. A toolkit cannot invent
6972        /// translated text (it has no access to the app's catalog), so the string arrives with
6973        /// the props. Empty means "no text": each backend falls back to its platform's own
6974        /// wordless idiom (a trash glyph), which works in every language.
6975        pub delete_label: String,
6976        /// The rows offer edge swipe actions (docs/list.md) through the injected
6977        /// `ListSource::swipe` (offer via `actions_at`, commit via `perform`); probe
6978        /// [`crate::Cap::ListSwipeActions`] for per-backend support. A backend without the
6979        /// affordance never shows one; an app that must offer the command everywhere
6980        /// pairs the swipe with an explicit control, exactly as `deletable` documents.
6981        pub swipe_actions: bool,
6982        /// Row separators, drawn by the host at the row boundary (docs/list.md), so they
6983        /// align with the native selection and ride the platform's own row animations (a
6984        /// macOS/iOS swipe slides the row content past a stationary separator, exactly as
6985        /// Mail's does). `None` keeps each platform's own default (iOS draws them, the
6986        /// desktops don't); `Some(true)`/`Some(false)` forces. A backend without a separator
6987        /// mechanism ignores a force (the matrix in docs/list.md says which); rows there
6988        /// separate by their pitch alone.
6989        pub separators: Option<bool>,
6990        /// The list starts in the platform's editing mode (docs/list.md): delete controls on
6991        /// the rows `deletable` offers, reorder grips on the rows `reorderable` moves, and a
6992        /// tap that still activates. Later changes arrive as [`ListPatch::Editing`]. Probe
6993        /// [`crate::Cap::ListEditing`]; a backend without an editing mode ignores it.
6994        pub editing: bool,
6995        /// The rows fall into sections, each opened by a header row (docs/list.md
6996        /// "Sections"): `ListSource::is_header` says which rows. Probe
6997        /// [`crate::Cap::ListSections`] for whether headers float natively.
6998        pub sections: bool,
6999        /// Draw the rows as the platform's inset grouped list (docs/list.md "Appearance"):
7000        /// rounded groups set in from the edges on a grouped background, as iOS Settings and
7001        /// Safari's History draw them. ios-uikit (`UITableViewStyleInsetGrouped`) and
7002        /// macos-appkit (`NSTableViewStyleInset`); the other toolkits draw their plain list.
7003        pub inset_grouped: bool,
7004    }
7005
7006    /// One row-level result-set change. Indexes are sequential (each delta describes the
7007    /// set as the previous ones left it), so a host applies them one at a time (or falls back
7008    /// to a reload; the source's snapshot already holds the final state either way).
7009    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
7010    pub enum RowDelta {
7011        Insert(usize),
7012        Remove(usize),
7013        Move(usize, usize),
7014    }
7015
7016    /// Immutable-at-realize props of a `kinds::TREE` host (docs/tree.md). Everything that
7017    /// changes after realize flows through [`TreePatch`] or the injected `TreeSource`.
7018    #[derive(Clone, Debug, PartialEq)]
7019    pub struct TreeProps {
7020        /// Two-level sectioned list: root branches are non-selectable headings.
7021        pub section_headers: bool,
7022        pub row_height: RowHeight,
7023        /// Rows highlight and report selection ([`crate::Event::TreeSelection`]).
7024        pub selectable: bool,
7025        /// Several rows may be selected at once; every change reports the full token set.
7026        pub multi_select: bool,
7027        /// Rows drag to a new parent/position through the platform's own mechanism, driving
7028        /// `TreeSource::moves`. Probe [`crate::Cap::TreeMove`] for support.
7029        pub movable: bool,
7030        /// Indentation per depth level, in points. `None` = the platform's default step.
7031        pub indent: Option<f64>,
7032    }
7033
7034    /// Post-realize changes to a `kinds::TREE` host (docs/tree.md). Token-addressed
7035    /// throughout; see [`crate::TreeSource`] for why indices cannot address tree rows.
7036    #[derive(Clone, Debug, PartialEq)]
7037    pub enum TreePatch {
7038        /// The node set changed (count/order/parentage/content): the host re-queries its
7039        /// `TreeSource`. Expansion and selection survive by token (docs/tree.md).
7040        Reload,
7041        /// Programmatically disclose (`true`) or collapse (`false`) one row. Applied without
7042        /// re-emitting [`crate::Event::TreeExpanded`] (the from-native echo rule).
7043        Expand(u64, bool),
7044        /// Programmatic selection sync (tokens; empty = clear), applied without re-emitting
7045        /// [`crate::Event::TreeSelection`].
7046        Selected(Vec<u64>),
7047        /// Scroll this row into view, realizing it if needed. The piece has already expanded
7048        /// the row's ancestors (through the app's expansion signal) before issuing this.
7049        Reveal(u64),
7050    }
7051
7052    #[derive(Clone, Debug, PartialEq)]
7053    pub enum ListPatch {
7054        /// The row set changed (count/order/content): the host re-queries its `ListSource`.
7055        Reload,
7056        /// The row set changed by exactly these deltas: a host that can, animates each row
7057        /// in, out, or across; one that cannot treats this as [`ListPatch::Reload`]. The
7058        /// data source answers with the final state throughout.
7059        Splice(Vec<RowDelta>),
7060        /// An `Automatic`-height row was re-laid at a new height after its first layout (its
7061        /// text changed, a wrapped line appeared, the backend corrected its width): the host
7062        /// gives the row bound to physical cell `cell` (the handle `ListSource::bind_row` got,
7063        /// as `usize`) the new `height`, padding included, the same value
7064        /// `ListSource::cell_height` now answers for it.
7065        ///
7066        /// Sent from inside a day-core layout pass, with the tree borrowed: a host applies it
7067        /// after the pass (posted to its main loop), never by asking the source anything
7068        /// synchronously, which would read a `0.0` height (docs/list.md "Row heights").
7069        RowSizeInvalidated { cell: usize, height: f64 },
7070        /// Imperatively scroll the native list so its last row is fully visible (a chat timeline
7071        /// sticking to the newest message). No-op when the list is empty (docs/list.md).
7072        ScrollToEnd,
7073        /// Imperatively scroll the native list so this row is visible, realizing it if needed
7074        /// (docs/list.md). Clamped to the row count; no-op when the list is empty.
7075        ScrollToRow(usize),
7076        /// Programmatic selection sync (row indices; empty = clear): toolkits apply without
7077        /// re-emitting a selection event, like every other programmatic sync.
7078        Selected(Vec<usize>),
7079        /// Enter (`true`) or leave (`false`) the platform's list editing mode, animated
7080        /// (docs/list.md, [`ListProps::editing`]). Ignored where `Cap::ListEditing` is
7081        /// `Unsupported`.
7082        Editing(bool),
7083    }
7084}
7085
7086// ---------------------------------------------------------------------------
7087// Imperative presentation (docs/dialogs.md)
7088// ---------------------------------------------------------------------------
7089
7090/// Sharing (docs/sharing.md): what [`Toolkit::share`] presents.
7091pub mod share {
7092    use crate::Symbol;
7093
7094    /// A share request: the page or link to share, and the app's own actions to offer beside
7095    /// the system's targets.
7096    #[derive(Clone, Debug, Default, PartialEq)]
7097    pub struct ShareSpec {
7098        /// The URL handed to the chosen target.
7099        pub url: String,
7100        /// Its title: the subject of a mail, the header of the chooser where it shows one.
7101        pub title: String,
7102        /// The app's actions, in order (`Cap::ShareActions`).
7103        pub actions: Vec<ShareAction>,
7104    }
7105
7106    /// One of the app's actions in a share chooser.
7107    #[derive(Clone, Debug, PartialEq)]
7108    pub struct ShareAction {
7109        /// The dispatch id a choice reports, as `Event::MenuAction(id)`.
7110        pub id: u64,
7111        /// The action's name, already localized.
7112        pub title: String,
7113        /// Its glyph, where the chooser draws one.
7114        pub symbol: Option<Symbol>,
7115    }
7116}
7117
7118pub mod present {
7119    /// A dialog button's semantic role: styling + default/cancel placement on each toolkit.
7120    #[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
7121    pub enum ButtonRole {
7122        #[default]
7123        Default,
7124        Cancel,
7125        Destructive,
7126    }
7127
7128    #[derive(Clone, Debug, PartialEq)]
7129    pub struct PresentButton {
7130        pub label: String,
7131        pub role: ButtonRole,
7132    }
7133
7134    /// A named group of file extensions for a file dialog (e.g. "Text" → `["txt", "md"]`).
7135    /// An empty `extensions` list means "all files".
7136    #[derive(Clone, Debug, PartialEq, Default)]
7137    pub struct FileFilter {
7138        pub name: String,
7139        pub extensions: Vec<String>,
7140    }
7141
7142    /// What a backend should present for a `req`. Kept toolkit-agnostic; the pieces layer
7143    /// maps a chosen button index back to a typed payload.
7144    #[derive(Clone, Debug, PartialEq)]
7145    pub enum PresentSpec {
7146        /// Alert / confirmation / action sheet: title + optional message + ordered buttons.
7147        /// `sheet` = present from the bottom on mobile (desktop falls back to an alert).
7148        Dialog {
7149            title: String,
7150            message: Option<String>,
7151            buttons: Vec<PresentButton>,
7152            sheet: bool,
7153        },
7154        /// A dialog with a single text field.
7155        Prompt {
7156            title: String,
7157            message: Option<String>,
7158            placeholder: String,
7159            initial: String,
7160            ok: String,
7161            cancel: String,
7162        },
7163        /// Native "open file" picker (docs/files.md). The backend must answer with
7164        /// `PresentResult::Files` whose entries are **readable local paths**: desktop returns
7165        /// the chosen path directly; iOS/Android copy the selection into app storage first, so
7166        /// the pieces layer can read it with `std::fs` regardless of platform. `multiple` lets
7167        /// the user pick several files at once; the answer then carries every chosen path, in
7168        /// the picker's order. A backend that cannot select more than one file still answers
7169        /// with the single pick.
7170        OpenFile {
7171            title: String,
7172            filters: Vec<FileFilter>,
7173            multiple: bool,
7174        },
7175        /// Native "choose folder" picker (docs/files.md). The backend answers with
7176        /// `PresentResult::Files` holding the one chosen directory path, or `Dismissed`. Only
7177        /// backends answering [`Cap::FolderDialog`](crate::Cap::FolderDialog) as `Native` show a
7178        /// chooser; the others resolve the request as `Dismissed` at once, so the await never hangs.
7179        OpenFolder { title: String },
7180        /// Native "save file" picker (docs/files.md). `src_path` is a Day-written temp file
7181        /// holding the bytes to save; iOS/Android deliver it to the chosen destination natively,
7182        /// and the pieces layer best-effort copies it to a chosen local path otherwise.
7183        SaveFile {
7184            title: String,
7185            suggested_name: String,
7186            src_path: String,
7187            filters: Vec<FileFilter>,
7188        },
7189    }
7190
7191    /// The user's answer to a presentation.
7192    #[derive(Clone, Debug, PartialEq)]
7193    pub enum PresentResult {
7194        /// A dialog button at `index` (in spec order) was chosen.
7195        Button(i64),
7196        /// A prompt was confirmed with `text`.
7197        Text(String),
7198        /// One or more file locators chosen from an open/save picker (docs/files.md). Each is a
7199        /// local filesystem path or, on Android save, a `content://` URI.
7200        Files(Vec<String>),
7201        /// Dismissed without choosing (tap-outside / Esc / cancel gesture).
7202        Dismissed,
7203    }
7204
7205    /// The unit-separator that joins string lists across the C ABI (Qt shim / Android JNI), the
7206    /// same encoding the nav menu, combobox, and dialog-button shims use.
7207    pub const UNIT_SEP: char = '\u{1f}';
7208
7209    std::thread_local! {
7210        /// An app-writable scratch directory. Backends whose OS temp dir isn't app-writable
7211        /// (Android → `getCacheDir()`) set this at startup; elsewhere it stays `None` and callers
7212        /// fall back to `std::env::temp_dir()`.
7213        // False positive, and only when checking an android target: the initializer already is
7214        // the `const` block the lint asks for. Android's TLS model makes the macro expand to a
7215        // form clippy reads as lazy, so the suggestion is unfollowable as well as unneeded.
7216        #[allow(clippy::missing_const_for_thread_local)]
7217        static APP_TEMP_DIR: std::cell::RefCell<Option<std::path::PathBuf>> =
7218            const { std::cell::RefCell::new(None) };
7219    }
7220
7221    /// Record an app-writable scratch directory (see [`app_temp_dir`]). Called by a backend at
7222    /// startup when the OS temp dir isn't writable by the app (Android).
7223    pub fn set_app_temp_dir(dir: impl Into<std::path::PathBuf>) {
7224        APP_TEMP_DIR.with(|d| *d.borrow_mut() = Some(dir.into()));
7225    }
7226
7227    /// An app-writable scratch directory: the backend-supplied one, else `std::env::temp_dir()`.
7228    /// Used by the file-save flow (docs/files.md) to stage bytes before the native save picker.
7229    pub fn app_temp_dir() -> std::path::PathBuf {
7230        APP_TEMP_DIR.with(|d| {
7231            d.borrow().clone().unwrap_or_else(|| {
7232                #[cfg(target_arch = "wasm32")]
7233                {
7234                    // A browser has no filesystem and std's `temp_dir()` panics on wasm. A
7235                    // nominal path keeps join/display plumbing alive; actual reads and writes
7236                    // fail with ordinary io errors the file flows already surface.
7237                    std::path::PathBuf::from("/day-tmp")
7238                }
7239                #[cfg(not(target_arch = "wasm32"))]
7240                std::env::temp_dir()
7241            })
7242        })
7243    }
7244
7245    /// The web build's file bytes (wasm32-unknown-unknown only): a browser has no filesystem,
7246    /// so the open/save flows carry bytes through this per-page store instead of `std::fs`:
7247    /// day-toolkit-dom writes a picked file's bytes here and answers with its virtual path; the pieces
7248    /// layer stages save bytes here for the shim to download. Paths are plain strings under
7249    /// `/day-web/`; lifetimes are one picker round-trip (the flows remove what they stage).
7250    #[cfg(all(target_family = "wasm", target_os = "unknown"))]
7251    pub mod web_files {
7252        std::thread_local! {
7253            static FILES: std::cell::RefCell<std::collections::HashMap<String, Vec<u8>>> =
7254                std::cell::RefCell::new(std::collections::HashMap::new());
7255        }
7256
7257        /// Store `bytes` under `path` (replacing any prior content).
7258        pub fn write(path: &str, bytes: Vec<u8>) {
7259            FILES.with(|f| f.borrow_mut().insert(path.to_string(), bytes));
7260        }
7261
7262        /// The bytes at `path`, if present.
7263        pub fn read(path: &str) -> Option<Vec<u8>> {
7264            FILES.with(|f| f.borrow().get(path).cloned())
7265        }
7266
7267        /// Drop `path`'s bytes.
7268        pub fn remove(path: &str) {
7269            FILES.with(|f| {
7270                f.borrow_mut().remove(path);
7271            });
7272        }
7273    }
7274
7275    impl PresentResult {
7276        /// Flat wire tag for the C ABI (Qt shim / Android JNI): 0 dismissed, 1 button, 2 text,
7277        /// 3 files (`text` is the chosen locators joined by the unit separator).
7278        pub fn decode(tag: i32, index: i64, text: String) -> PresentResult {
7279            match tag {
7280                1 => PresentResult::Button(index),
7281                2 => PresentResult::Text(text),
7282                3 => PresentResult::Files(
7283                    text.split(UNIT_SEP)
7284                        .filter(|s| !s.is_empty())
7285                        .map(str::to_string)
7286                        .collect(),
7287                ),
7288                _ => PresentResult::Dismissed,
7289            }
7290        }
7291    }
7292
7293    impl PresentSpec {
7294        /// Backend-facing flattening for the C ABI: `(title, message, button labels, button
7295        /// roles as ints, sheet-or-prompt fields)`. Pure-Rust backends read the enum directly.
7296        pub fn title(&self) -> &str {
7297            match self {
7298                PresentSpec::Dialog { title, .. }
7299                | PresentSpec::Prompt { title, .. }
7300                | PresentSpec::OpenFile { title, .. }
7301                | PresentSpec::OpenFolder { title }
7302                | PresentSpec::SaveFile { title, .. } => title,
7303            }
7304        }
7305        pub fn message(&self) -> Option<&str> {
7306            match self {
7307                PresentSpec::Dialog { message, .. } | PresentSpec::Prompt { message, .. } => {
7308                    message.as_deref()
7309                }
7310                _ => None,
7311            }
7312        }
7313        /// Button labels joined with [`UNIT_SEP`], the encoding the nav menu and combobox
7314        /// shims already use for string lists.
7315        pub fn buttons_joined(&self) -> String {
7316            match self {
7317                PresentSpec::Dialog { buttons, .. } => buttons
7318                    .iter()
7319                    .map(|b| b.label.as_str())
7320                    .collect::<Vec<_>>()
7321                    .join(&UNIT_SEP.to_string()),
7322                PresentSpec::Prompt { ok, cancel, .. } => format!("{ok}{UNIT_SEP}{cancel}"),
7323                _ => String::new(),
7324            }
7325        }
7326        /// Button roles as ints (0 default, 1 cancel, 2 destructive), joined with commas.
7327        pub fn roles_joined(&self) -> String {
7328            let roles: Vec<i32> = match self {
7329                PresentSpec::Dialog { buttons, .. } => {
7330                    buttons.iter().map(|b| b.role as i32).collect()
7331                }
7332                PresentSpec::Prompt { .. } => {
7333                    vec![ButtonRole::Default as i32, ButtonRole::Cancel as i32]
7334                }
7335                _ => vec![],
7336            };
7337            roles
7338                .iter()
7339                .map(|r| r.to_string())
7340                .collect::<Vec<_>>()
7341                .join(",")
7342        }
7343
7344        // --- file-dialog accessors (docs/files.md) ---
7345
7346        /// The file filters, if this is a file dialog.
7347        pub fn filters(&self) -> &[FileFilter] {
7348            match self {
7349                PresentSpec::OpenFile { filters, .. } | PresentSpec::SaveFile { filters, .. } => {
7350                    filters
7351                }
7352                _ => &[],
7353            }
7354        }
7355        /// Whether an open-file dialog lets the user pick several files (`false` for every
7356        /// other spec).
7357        pub fn multiple(&self) -> bool {
7358            matches!(self, PresentSpec::OpenFile { multiple: true, .. })
7359        }
7360        /// The suggested file name for a save dialog (empty otherwise).
7361        pub fn suggested_name(&self) -> &str {
7362            match self {
7363                PresentSpec::SaveFile { suggested_name, .. } => suggested_name,
7364                _ => "",
7365            }
7366        }
7367        /// The Day-written temp source path for a save dialog (empty otherwise).
7368        pub fn src_path(&self) -> &str {
7369            match self {
7370                PresentSpec::SaveFile { src_path, .. } => src_path,
7371                _ => "",
7372            }
7373        }
7374        /// Filters flattened for the C ABI: each filter is `name|ext1,ext2`, joined by
7375        /// [`UNIT_SEP`]. A trailing `|` (no extensions) means "all files". Empty when unfiltered.
7376        pub fn filters_joined(&self) -> String {
7377            self.filters()
7378                .iter()
7379                .map(|f| format!("{}|{}", f.name, f.extensions.join(",")))
7380                .collect::<Vec<_>>()
7381                .join(&UNIT_SEP.to_string())
7382        }
7383    }
7384}
7385
7386// ---------------------------------------------------------------------------
7387// App directories (docs/fs.md "Where files live")
7388// ---------------------------------------------------------------------------
7389
7390/// Where an app keeps its own files: its data, cache and configuration directories, each a
7391/// folder named after the app id in the place its platform sets aside for that kind of file
7392/// (docs/fs.md "Where files live"). Every Day crate that stores files resolves them here, so an
7393/// app's database, documents, caches, settings file and remembered window frames sit together
7394/// and apart from every other app's.
7395///
7396/// These only resolve paths; nothing is created until something is written. Each is `None` where
7397/// the platform has no such directory: the web, or an Android or HarmonyOS process whose host
7398/// passed none.
7399pub mod storage {
7400    use std::path::PathBuf;
7401
7402    /// The app's id, `[app] id` from Day.toml: `DAY_APP_ID` from `day launch`, else the value
7403    /// `day build` baked in, else the executable's name (a test binary or a bare `cargo run`).
7404    /// Made safe as a single folder name.
7405    pub fn app_id() -> String {
7406        std::env::var("DAY_APP_ID")
7407            .ok()
7408            .filter(|id| !id.is_empty())
7409            .or_else(|| {
7410                option_env!("DAY_APP_ID")
7411                    .filter(|id| !id.is_empty())
7412                    .map(str::to_owned)
7413            })
7414            .or_else(|| {
7415                let exe = std::env::current_exe().ok()?;
7416                exe.file_stem()?.to_str().map(str::to_owned)
7417            })
7418            .map(|id| folder_name(&id))
7419            .unwrap_or_else(|| "day-app".to_owned())
7420    }
7421
7422    /// The app's data directory, for what it cannot recreate: databases, documents, downloads
7423    /// the user kept. Application Support on Apple platforms (inside the container when
7424    /// sandboxed), `%LOCALAPPDATA%` on Windows, `$XDG_DATA_HOME` on Linux, the app's files
7425    /// directory on Android and HarmonyOS. `DAY_DATA_DIR` replaces it.
7426    pub fn data_dir() -> Option<PathBuf> {
7427        resolve(Dir::Data, Os::HOST, &app_id(), &env_path)
7428    }
7429
7430    /// [`data_dir`] for the app `app_id` rather than this process's own: a host that keeps a
7431    /// folder per hosted app (a day-lite superapp, a crash reporter's store), or a tool finding
7432    /// where an app it launched writes. On Android and HarmonyOS, where the host's directory is
7433    /// already the one app's, the id changes nothing.
7434    pub fn data_dir_for(app_id: &str) -> Option<PathBuf> {
7435        resolve(Dir::Data, Os::HOST, &folder_name(app_id), &env_path)
7436    }
7437
7438    /// The app's cache directory, for what it can fetch or compute again: the system may clear
7439    /// it, and backups skip it. Caches on Apple platforms, `%LOCALAPPDATA%\<id>\cache` on
7440    /// Windows, `$XDG_CACHE_HOME` on Linux, the app's cache directory on Android and HarmonyOS.
7441    /// `DAY_CACHE_DIR` replaces it; with only `DAY_DATA_DIR` set it is that directory's `cache`.
7442    pub fn cache_dir() -> Option<PathBuf> {
7443        resolve(Dir::Cache, Os::HOST, &app_id(), &env_path)
7444    }
7445
7446    /// The app's configuration directory, for small settings files: Application Support on
7447    /// Apple platforms (whose preferences proper are the user defaults), the roaming
7448    /// `%APPDATA%` on Windows, `$XDG_CONFIG_HOME` on Linux. With `DAY_DATA_DIR` set (as the
7449    /// Android and HarmonyOS hosts do) it is that directory's `config`.
7450    pub fn config_dir() -> Option<PathBuf> {
7451        resolve(Dir::Config, Os::HOST, &app_id(), &env_path)
7452    }
7453
7454    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
7455    enum Dir {
7456        Data,
7457        Cache,
7458        Config,
7459    }
7460
7461    /// The platform families whose conventions differ.
7462    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
7463    enum Os {
7464        /// macOS and iOS: `~/Library`, which is the app's container when sandboxed.
7465        Apple,
7466        Windows,
7467        /// Android and HarmonyOS: the host passes the app's private directories.
7468        Hosted,
7469        /// Linux and the BSDs: the XDG base directories.
7470        Unix,
7471        Web,
7472    }
7473
7474    impl Os {
7475        const HOST: Os = if cfg!(any(target_os = "macos", target_os = "ios")) {
7476            Os::Apple
7477        } else if cfg!(target_os = "windows") {
7478            Os::Windows
7479        } else if cfg!(any(target_os = "android", target_env = "ohos")) {
7480            Os::Hosted
7481        } else if cfg!(target_family = "wasm") {
7482            Os::Web
7483        } else {
7484            Os::Unix
7485        };
7486    }
7487
7488    /// An environment variable naming a directory: set, non-empty and absolute, else ignored.
7489    fn env_path(name: &str) -> Option<PathBuf> {
7490        let path = PathBuf::from(std::env::var_os(name)?);
7491        path.is_absolute().then_some(path)
7492    }
7493
7494    /// One folder name: no separators, no `.`/`..`, nothing a filesystem rejects.
7495    fn folder_name(id: &str) -> String {
7496        let name: String = id
7497            .chars()
7498            .map(|c| match c {
7499                '/' | '\\' | ':' | '*' | '?' | '"' | '<' | '>' | '|' => '_',
7500                c if c.is_control() => '_',
7501                c => c,
7502            })
7503            .collect();
7504        match name.trim() {
7505            "" | "." | ".." => "day-app".to_owned(),
7506            name => name.to_owned(),
7507        }
7508    }
7509
7510    /// The pure resolution, over a platform and an environment, so every platform's rules are
7511    /// testable on any host.
7512    fn resolve(
7513        dir: Dir,
7514        os: Os,
7515        id: &str,
7516        var: &dyn Fn(&str) -> Option<PathBuf>,
7517    ) -> Option<PathBuf> {
7518        // The explicit overrides: a mobile host's own directories, or a test's scratch root.
7519        if dir == Dir::Cache
7520            && let Some(cache) = var("DAY_CACHE_DIR")
7521        {
7522            return Some(cache);
7523        }
7524        if let Some(data) = var("DAY_DATA_DIR") {
7525            return Some(match dir {
7526                Dir::Data => data,
7527                Dir::Cache => data.join("cache"),
7528                Dir::Config => data.join("config"),
7529            });
7530        }
7531        let home = || var("HOME");
7532        match os {
7533            // One expression serves sandboxed and unsandboxed apps: inside the App Sandbox,
7534            // and always on iOS, `HOME` is the container's Data folder, so the same Library
7535            // path lands inside it. Apple asks for a bundle-id folder within Application
7536            // Support and Caches either way. XDG variables are ignored here: a Finder launch
7537            // never sees a shell's, so honoring them would split one app's data across two
7538            // places depending on how it was started.
7539            Os::Apple => {
7540                let library = home()?.join("Library");
7541                let base = match dir {
7542                    Dir::Data | Dir::Config => library.join("Application Support"),
7543                    Dir::Cache => library.join("Caches"),
7544                };
7545                Some(base.join(id))
7546            }
7547            // Local for data and caches: a database or cache roams badly, and a DPAPI-sealed
7548            // file cannot be read on another machine. Roaming for the small settings files.
7549            Os::Windows => {
7550                let profile = |leaf: &str| Some(var("USERPROFILE")?.join("AppData").join(leaf));
7551                let local = || var("LOCALAPPDATA").or_else(|| profile("Local"));
7552                match dir {
7553                    Dir::Data => Some(local()?.join(id)),
7554                    Dir::Cache => Some(local()?.join(id).join("cache")),
7555                    Dir::Config => Some(var("APPDATA").or_else(|| profile("Roaming"))?.join(id)),
7556                }
7557            }
7558            Os::Unix => {
7559                let (xdg, fallback) = match dir {
7560                    Dir::Data => ("XDG_DATA_HOME", ".local/share"),
7561                    Dir::Cache => ("XDG_CACHE_HOME", ".cache"),
7562                    Dir::Config => ("XDG_CONFIG_HOME", ".config"),
7563                };
7564                Some(var(xdg).or_else(|| Some(home()?.join(fallback)))?.join(id))
7565            }
7566            Os::Hosted | Os::Web => None,
7567        }
7568    }
7569
7570    #[cfg(test)]
7571    mod tests {
7572        use super::*;
7573        use std::collections::HashMap;
7574
7575        /// The resolved path as text. `Path::join` uses the host's separator, so on a Windows host
7576        /// another platform's path comes back with `\` between the joined parts; the expectations
7577        /// are that platform's own, so its separators are compared as `/`.
7578        fn at(os: Os, dir: Dir, vars: &[(&str, &str)]) -> Option<String> {
7579            let vars: HashMap<&str, &str> = vars.iter().copied().collect();
7580            let var = |name: &str| vars.get(name).map(PathBuf::from);
7581            resolve(dir, os, "dev.example.notes", &var).map(|p| {
7582                let text = p.display().to_string();
7583                if os == Os::Windows {
7584                    text
7585                } else {
7586                    text.replace('\\', "/")
7587                }
7588            })
7589        }
7590
7591        #[test]
7592        fn apple_uses_library_folders_named_for_the_app() {
7593            let home = [("HOME", "/Users/ada"), ("XDG_DATA_HOME", "/Users/ada/.xdg")];
7594            let support = "/Users/ada/Library/Application Support/dev.example.notes";
7595            assert_eq!(at(Os::Apple, Dir::Data, &home).as_deref(), Some(support));
7596            assert_eq!(at(Os::Apple, Dir::Config, &home).as_deref(), Some(support));
7597            assert_eq!(
7598                at(Os::Apple, Dir::Cache, &home).as_deref(),
7599                Some("/Users/ada/Library/Caches/dev.example.notes")
7600            );
7601            // A sandboxed app's HOME is its container, so its folders land inside it.
7602            let container = [(
7603                "HOME",
7604                "/Users/ada/Library/Containers/dev.example.notes/Data",
7605            )];
7606            assert_eq!(
7607                at(Os::Apple, Dir::Data, &container).as_deref(),
7608                Some(
7609                    "/Users/ada/Library/Containers/dev.example.notes/Data/Library/Application Support/dev.example.notes"
7610                )
7611            );
7612        }
7613
7614        #[test]
7615        fn windows_keeps_data_local_and_settings_roaming() {
7616            let vars = [
7617                ("LOCALAPPDATA", r"C:\Users\ada\AppData\Local"),
7618                ("APPDATA", r"C:\Users\ada\AppData\Roaming"),
7619            ];
7620            let data = at(Os::Windows, Dir::Data, &vars).unwrap_or_default();
7621            assert!(data.starts_with(r"C:\Users\ada\AppData\Local"), "{data}");
7622            assert!(data.ends_with("dev.example.notes"), "{data}");
7623            let cache = at(Os::Windows, Dir::Cache, &vars).unwrap_or_default();
7624            assert!(cache.ends_with("cache"), "{cache}");
7625            let config = at(Os::Windows, Dir::Config, &vars).unwrap_or_default();
7626            assert!(
7627                config.starts_with(r"C:\Users\ada\AppData\Roaming"),
7628                "{config}"
7629            );
7630        }
7631
7632        #[test]
7633        fn unix_follows_xdg_then_home() {
7634            let xdg = [
7635                ("HOME", "/home/ada"),
7636                ("XDG_DATA_HOME", "/data"),
7637                ("XDG_CACHE_HOME", "/cache"),
7638                ("XDG_CONFIG_HOME", "/config"),
7639            ];
7640            assert_eq!(
7641                at(Os::Unix, Dir::Data, &xdg).as_deref(),
7642                Some("/data/dev.example.notes")
7643            );
7644            assert_eq!(
7645                at(Os::Unix, Dir::Cache, &xdg).as_deref(),
7646                Some("/cache/dev.example.notes")
7647            );
7648            assert_eq!(
7649                at(Os::Unix, Dir::Config, &xdg).as_deref(),
7650                Some("/config/dev.example.notes")
7651            );
7652            let home = [("HOME", "/home/ada")];
7653            assert_eq!(
7654                at(Os::Unix, Dir::Data, &home).as_deref(),
7655                Some("/home/ada/.local/share/dev.example.notes")
7656            );
7657            assert_eq!(
7658                at(Os::Unix, Dir::Cache, &home).as_deref(),
7659                Some("/home/ada/.cache/dev.example.notes")
7660            );
7661            assert_eq!(
7662                at(Os::Unix, Dir::Config, &home).as_deref(),
7663                Some("/home/ada/.config/dev.example.notes")
7664            );
7665        }
7666
7667        #[test]
7668        fn hosts_and_tests_override_every_platform() {
7669            let host = [
7670                ("DAY_DATA_DIR", "/data/user/0/dev.example.notes/files"),
7671                ("DAY_CACHE_DIR", "/data/user/0/dev.example.notes/cache"),
7672            ];
7673            for os in [Os::Hosted, Os::Apple, Os::Windows, Os::Unix] {
7674                assert_eq!(
7675                    at(os, Dir::Data, &host).as_deref(),
7676                    Some("/data/user/0/dev.example.notes/files")
7677                );
7678                assert_eq!(
7679                    at(os, Dir::Cache, &host).as_deref(),
7680                    Some("/data/user/0/dev.example.notes/cache")
7681                );
7682            }
7683            let scratch = [("HOME", "/Users/ada"), ("DAY_DATA_DIR", "/tmp/run")];
7684            assert_eq!(
7685                at(Os::Apple, Dir::Cache, &scratch).as_deref(),
7686                Some("/tmp/run/cache")
7687            );
7688            assert_eq!(
7689                at(Os::Apple, Dir::Config, &scratch).as_deref(),
7690                Some("/tmp/run/config")
7691            );
7692            // Without a host directory there is nowhere to put anything.
7693            assert_eq!(at(Os::Hosted, Dir::Data, &[("HOME", "/")]), None);
7694            assert_eq!(at(Os::Web, Dir::Data, &[("HOME", "/")]), None);
7695        }
7696
7697        #[test]
7698        fn app_ids_become_one_folder_name() {
7699            assert_eq!(folder_name("dev.daybrite.news"), "dev.daybrite.news");
7700            assert_eq!(folder_name("a/b\\c:d"), "a_b_c_d");
7701            assert_eq!(folder_name(".."), "day-app");
7702            assert_eq!(folder_name(""), "day-app");
7703        }
7704    }
7705}
7706
7707// ---------------------------------------------------------------------------
7708// The Toolkit trait (§8.1)
7709// ---------------------------------------------------------------------------
7710
7711/// Timing supplied by a native display scheduler. Seconds on a monotonic clock; its epoch
7712/// is platform-specific. `target_timestamp` is absent when the platform cannot predict presentation.
7713#[derive(Clone, Copy, Debug, PartialEq)]
7714pub struct FrameStamp {
7715    pub timestamp: f64,
7716    pub target_timestamp: Option<f64>,
7717}
7718impl FrameStamp {
7719    pub fn new(timestamp: f64) -> Self {
7720        Self {
7721            timestamp,
7722            target_timestamp: None,
7723        }
7724    }
7725}
7726/// A one-shot native frame callback, always delivered asynchronously on the UI thread.
7727pub type FrameCallback = Box<dyn FnOnce(FrameStamp)>;
7728/// Cancels a pending callback and releases its native registration. UI-thread only, idempotent
7729/// in effect, and safe during/after delivery. Dropping without calling is allowed after delivery.
7730pub type CancelFrame = Box<dyn FnOnce()>;
7731
7732/// The margins and minimum height a native list gives each row ([`Toolkit::list_row_metrics`],
7733/// docs/list.md "Row metrics"): a `UITableView` cell's layout margins, a Material list item's
7734/// 16dp sides and 56dp height.
7735#[derive(Clone, Copy, Debug, Default, PartialEq)]
7736pub struct RowMetrics {
7737    /// Space between the row's edges and its content.
7738    pub insets: Insets,
7739    /// The least height a row takes, margins included; content centers vertically in it.
7740    pub min_height: f64,
7741}
7742
7743/// Platform colors for custom drawing. Native controls keep their own semantic styling.
7744#[derive(Clone, Copy, Debug, PartialEq, Eq)]
7745#[repr(u8)]
7746pub enum SystemColor {
7747    Accent,
7748    Text,
7749    SecondaryText,
7750    Background,
7751    Surface,
7752}
7753
7754impl SystemColor {
7755    /// All roles, in discriminant order, for toolkit palette snapshots.
7756    pub const ALL: [Self; 5] = [
7757        Self::Accent,
7758        Self::Text,
7759        Self::SecondaryText,
7760        Self::Background,
7761        Self::Surface,
7762    ];
7763
7764    /// Day's fallback palette when the toolkit cannot resolve a role.
7765    /// These are fixed sRGB colors, not an approximation of a user-selected system accent.
7766    pub const fn fallback(self, dark: bool) -> Color {
7767        Color::hex(match (self, dark) {
7768            (Self::Accent, false) => 0x0a66ff,
7769            (Self::Accent, true) => 0x3f83ff,
7770            (Self::Text, false) => 0x1d1d1f,
7771            (Self::Text, true) => 0xf5f5f7,
7772            (Self::SecondaryText, false) => 0x6e6e73,
7773            (Self::SecondaryText, true) => 0x98989d,
7774            (Self::Background, false) => 0xffffff,
7775            (Self::Background, true) => 0x1e1e20,
7776            (Self::Surface, false) => 0xf3f2f7,
7777            (Self::Surface, true) => 0x2c2c2e,
7778        })
7779    }
7780}
7781
7782pub trait Toolkit: Sized + 'static {
7783    // `'static` so a handle clone can cross the object-safe TreeOps boundary boxed as `Any`
7784    // (`node_handle_any`, the tweaks door, docs/tweaks.md).
7785    type Handle: Clone + 'static;
7786
7787    /// Request one frame for the window containing `host`. Never call inline. Each native source
7788    /// must stop after delivery unless requested again; no polling timer. Hidden/unmapped windows
7789    /// may defer delivery until visible. Native callbacks must reach the UI thread before calling
7790    /// Rust. The returned closure cancels safely, including when the window has closed.
7791    /// The mock intentionally stays pending: tests inject a manual scheduler in day-core.
7792    fn request_frame(&mut self, _host: &Self::Handle, _cb: FrameCallback) -> CancelFrame {
7793        Box::new(|| {})
7794    }
7795
7796    fn capability(&self, _cap: Cap) -> Support {
7797        Support::Unsupported
7798    }
7799
7800    // node lifecycle
7801    fn realize(&mut self, kind: PieceKind, props: &dyn Any, id: NodeId) -> Self::Handle;
7802    fn update(
7803        &mut self,
7804        h: &Self::Handle,
7805        kind: PieceKind,
7806        patch: &dyn Any,
7807        anim: Option<&AnimSpec>,
7808    );
7809    /// Called from the turn-boundary release queue; backends may defer destruction further.
7810    fn release(&mut self, h: Self::Handle);
7811    /// Give a satellite piece a chance to drop its own per-view state, immediately before
7812    /// [`release`](Toolkit::release) frees `h` (§15.2).
7813    ///
7814    /// A backend that hosts third-party pieces implements this by looking `kind` up in its renderer
7815    /// registry and calling that piece's `release` hook. Defaulted to nothing: a backend with no
7816    /// registry has nothing to dispatch, and one that has not wired this yet leaves piece
7817    /// teardown unrun rather than failing to build.
7818    fn release_piece(&mut self, _kind: PieceKind, _h: &Self::Handle) {}
7819
7820    // tree
7821    fn insert(&mut self, parent: &Self::Handle, child: &Self::Handle, index: usize);
7822    fn remove(&mut self, parent: &Self::Handle, child: &Self::Handle);
7823    /// Put `child` at index `to` among `parent`'s native children: day's z-order resync, which
7824    /// walks the whole sibling row and asks for every position in turn. A child already at `to`
7825    /// must therefore cost nothing: a backend that re-parents unconditionally pays for the
7826    /// untouched siblings too, and where re-parenting means detach-then-add (no ViewGroup move
7827    /// primitive on Android) the detach resigns the focus of everything inside the subtree,
7828    /// which is how a text field being typed into loses the keyboard (docs/focus.md).
7829    fn move_child(&mut self, parent: &Self::Handle, child: &Self::Handle, to: usize);
7830
7831    // geometry (§7): frames are in the nearest realized native ancestor's space, in points.
7832    fn measure(&mut self, h: &Self::Handle, kind: PieceKind, p: Proposal) -> Size;
7833    /// Distance from the top of the widget's frame to its first text baseline, in points, when
7834    /// the widget is `size` (docs/baseline.md). `None` ⇒ it has no text baseline (an image, a
7835    /// slider, a bare container) and a baseline-aligned row falls back to box alignment for it.
7836    ///
7837    /// This is a measurement, not a layout mode: day places every frame itself (§7.1) and never
7838    /// hands a row to a native baseline-aligning container, so what it needs from the toolkit is
7839    /// where the text sits inside the box. Backends that cannot answer keep the default and rows
7840    /// stay centered, which is what every row did before this existed.
7841    fn first_baseline(&mut self, _h: &Self::Handle, _kind: PieceKind, _size: Size) -> Option<f64> {
7842        None
7843    }
7844    fn set_frame(&mut self, h: &Self::Handle, frame: Rect, anim: Option<&AnimSpec>);
7845
7846    // animatable visual channels (§8.4): cheap per-node opacity + transform that don't relayout.
7847    // Defaulted no-ops so backends adopt them incrementally; `anim = Some` ⇒ animate to the value
7848    // on the toolkit's own compositor, `None` ⇒ set instantly.
7849    fn set_opacity(&mut self, _h: &Self::Handle, _opacity: f64, _anim: Option<&AnimSpec>) {}
7850    fn set_transform(
7851        &mut self,
7852        _h: &Self::Handle,
7853        _t: Transform,
7854        _size: Size,
7855        _anim: Option<&AnimSpec>,
7856    ) {
7857    }
7858
7859    // text selection (docs/text.md): make this node's text user-selectable (copy/drag). Applied
7860    // once from the `.selectable()` modifier (day-pieces) to the widget it wraps (a `label`'s
7861    // native text view, most usefully). Unmanaged: Day sets it here and never patches it, so it
7862    // survives text updates. The default no-op means a backend without a selection affordance
7863    // silently leaves the text unselectable.
7864    //
7865    // Returns `Some(replacement)` when the toolkit had to rebuild the widget as a different
7866    // native class to gain a selection affordance (UIKit: `UILabel` has none, so the label
7867    // becomes a read-only `UITextView`); day-core re-points the node's handle at the
7868    // replacement, so later patches and layout reach the widget that is actually on screen.
7869    // Every property-flip backend returns `None`.
7870    fn set_selectable(&mut self, _h: &Self::Handle, _selectable: bool) -> Option<Self::Handle> {
7871        None
7872    }
7873
7874    // text entry (docs/textfield.md): how a `text_field` takes its text: hidden characters,
7875    // read-only, the keyboard and autofill purpose, the action key, the length bound. Called
7876    // once after `realize` when a field asks for anything but the defaults, and again with the
7877    // whole set whenever a reactive member changes, so the setter is idempotent.
7878    //
7879    // Returns `Some(replacement)` when hiding the characters takes a different native class
7880    // (AppKit: `NSSecureTextField`; WinUI: `PasswordBox`), the same contract as
7881    // `set_selectable`: the backend carries the text, the placeholder and its own event wiring
7882    // over, takes the old widget's place in the native tree, and day-core re-points the node's
7883    // handle. Required, with no default: a backend that left this out would show a password in
7884    // the clear. A member the toolkit has no notion of (an action key on a desktop) is ignored.
7885    fn set_input_traits(&mut self, h: &Self::Handle, traits: &InputTraits) -> Option<Self::Handle>;
7886
7887    // pointer shape (docs/cursor.md): the cursor to show while the pointer is over this node
7888    // and its descendants, from the `.cursor()` modifier. Called again whenever a reactive
7889    // cursor changes, so the setter is idempotent and cheap; `Cursor::Default` releases the
7890    // node. The default no-op is a backend with no pointer API to reach (`Cap::Cursor`
7891    // answers `Unsupported` there).
7892    fn set_cursor(&mut self, _h: &Self::Handle, _cursor: Cursor) {}
7893
7894    /// Show or hide a retained subtree, including its input and accessibility participation.
7895    /// The layout and reactive scope stay alive while hidden.
7896    fn set_presented(&mut self, _h: &Self::Handle, _visible: bool) {}
7897
7898    /// Attach overscroll delivery to a refresh host; the caller owns the mounted scope.
7899    fn attach_refresh(&mut self, _h: &Self::Handle, _host: NodeId) {}
7900
7901    // scroll (§7.6)
7902    fn set_scroll_content(&mut self, _h: &Self::Handle, _content: Size) {}
7903    // The room a classic (non-overlay) scroll bar takes out of a scroll view's content area
7904    // while the content overflows along `vertical`'s axis: its width for a vertical scroll, its
7905    // height for a horizontal one (docs/scroll.md). Day lays overflowing content out that much
7906    // narrower, so it fits beside the bar instead of reaching under it. 0 — the default — is
7907    // every backend whose bars overlay the content (AppKit, GTK, UIKit, Android, XAML, DOM).
7908    fn scroll_bar_inset(&mut self, _h: &Self::Handle, _vertical: bool) -> f64 {
7909        0.0
7910    }
7911    // The margins and minimum height the platform's own list gives a row (docs/list.md "Row
7912    // metrics"), asked of list `h` each time day-core lays a row. Day insets the row's content by
7913    // the margins and keeps it at least that tall, so a row reads at the platform's size without
7914    // the app padding it per platform. Zero — the default — leaves the row to its content.
7915    fn list_row_metrics(&mut self, _h: &Self::Handle) -> RowMetrics {
7916        RowMetrics::default()
7917    }
7918    fn scroll_to(&mut self, _h: &Self::Handle, _target: Rect, _animated: bool) {}
7919    /// Scroll a native navigation menu to its top or bottom without changing selection.
7920    /// The widget owns its content extent. Return false when the handle is unsupported.
7921    fn nav_scroll_to_edge(&mut self, _h: &Self::Handle, _bottom: bool) -> bool {
7922        false
7923    }
7924    fn scroll_offset(&mut self, _h: &Self::Handle) -> Point {
7925        Point::ZERO
7926    }
7927
7928    // events: one trampoline, node-id keyed; enqueue-only contract (§8.3).
7929    fn set_event_sink(&mut self, sink: EventSink);
7930
7931    // gestures (docs/shapes.md): attach a native recognizer for `kind` to `h`, emitting
7932    // `Event::Tap/LongPress/Drag` for `node` (enqueue-only). Default no gesture; a piece opts in
7933    // when it has a handler. Idempotent per (handle, kind).
7934    fn enable_gesture(&mut self, _h: &Self::Handle, _node: NodeId, _kind: GestureKind) {}
7935
7936    // focus (docs/focus.md): move native keyboard focus to (or away from) this control.
7937    // `focused = true` requests focus (on mobile this also raises the soft keyboard for text
7938    // inputs); `false` resigns it (dismissing the keyboard; platforms without a "focus nothing"
7939    // state resign to a focusable root). Backends report the resulting state, user- or
7940    // programmatic, with `Event::FocusChanged(bool)` through the sink; a request that cannot
7941    // be honored (unfocusable, unmounted) produces no event. The default no-op means a
7942    // backend without focus support neither moves nor reports focus.
7943    fn focus(&mut self, _h: &Self::Handle, _node: NodeId, _focused: bool) {}
7944
7945    // focusability (docs/focus.md): opt this container into the platform's focus system, the
7946    // canvas contract generalized (`Decorate::focusable`). A focusable container accepts focus,
7947    // takes it on a press (before the press reaches its gesture recognizers), reports both
7948    // directions with `Event::FocusChanged`, and delivers the non-text keys it hears while
7949    // focused as `Event::Key` for `node` (gated on `keys::handled`, like a canvas). The default
7950    // no-op means the piece renders normally but never joins the focus order: `.focused(…)`
7951    // bindings stay quiet and `.on_key(…)` never fires, the same graceful silence unfocusable
7952    // controls already have. Idempotent; only `true` is ever sent today (a piece opts in at
7953    // build, it does not opt back out).
7954    fn set_focusable(&mut self, _h: &Self::Handle, _node: NodeId, _focusable: bool) {}
7955
7956    // recycling list (docs/list.md, §10): day-core hands the `LIST` host its row-pull `source`
7957    // once, right after realize. A recycling backend stores it and calls it from its native
7958    // data-source; the default no-op means a backend without list support renders nothing.
7959    fn attach_list(&mut self, _host: &Self::Handle, _source: ListSource) {}
7960
7961    // hierarchical tree (docs/tree.md): day-core hands the `TREE` host its token-addressed
7962    // row-pull `source` once, right after realize. A backend with a native tree stores it and
7963    // answers its data-source from it; the default no-op means a backend without tree support
7964    // renders nothing (`Cap::Tree` answers `Unsupported`, and apps gate on that).
7965    fn attach_tree(&mut self, _host: &Self::Handle, _source: TreeSource) {}
7966
7967    // routes (docs/navigation.md): day-core reports the app's current route path here whenever
7968    // it changes ("" = everything at its root), so a backend with a native notion of location
7969    // can mirror it: web-dom writes the URL hash (`#controls`), and browser back/forward or a
7970    // hand-edited hash comes back as `Event::RouteRequested`. Default no-op: most toolkits
7971    // have nowhere to put a route.
7972    fn set_route(&mut self, _route: &str) {}
7973
7974    // undo bridge (docs/model.md): mirror the app's undo stack into the platform's own undo
7975    // objects, so the stock Edit menu retitles and enables itself and the platform's gestures
7976    // land: the native front of one Day-owned history. The state flows down whenever it
7977    // changes; the user's invocation comes back up as `Event::Undo`. Default no-op: a backend
7978    // without a native undo system answers `Cap::UndoBridge` `Unsupported`, and the app's own
7979    // affordances (menu items, buttons, accelerators) drive the stack instead.
7980    fn set_undo_state(&mut self, _state: &UndoState) {}
7981
7982    // edit bridge (docs/menus.md): mirror what the app's standard-edit handlers can do, so
7983    // the platform's own menu validation enables Cut/Copy/Paste exactly as it does for text
7984    // widgets; invocations come back up as `Event::Edit`. Default no-op: a backend without
7985    // a native edit-command route answers `Cap::EditBridge` accordingly.
7986    fn set_edit_state(&mut self, _state: &EditState) {}
7987
7988    // ambient modifiers (docs/menus.md): the keyboard modifiers held right now, for
7989    // interactions whose meaning they change (shift-click multi-select). Pull-based: the
7990    // platforms expose exactly this query (NSEvent.modifierFlags, the shim's tracked mask).
7991    // Touch-only backends keep the all-false default.
7992    fn modifiers(&mut self) -> Modifiers {
7993        Modifiers::default()
7994    }
7995
7996    // Dynamic context menu (docs/menus.md): the menu is built when it is summoned. The provider
7997    // is called synchronously from the platform's own menu callback (UI thread, outside any
7998    // day-core borrow) with the location in the node's local coordinates, and its result is
7999    // shown. The static `set_context_menu` below stays the simple path; this one exists for
8000    // surfaces whose menu depends on what is under the pointer (a canvas selection,
8001    // docs/tree.md). Default no-op: a backend without the affordance shows nothing.
8002    fn set_drag_source(&mut self, _h: &Self::Handle, _source: transfer::Source) {}
8003    fn set_drop_target(&mut self, _h: &Self::Handle, _target: transfer::Target) {}
8004
8005    fn set_context_menu_fn(&mut self, _h: &Self::Handle, _node: NodeId, _f: ContextMenuFn) {}
8006
8007    // menus (§ menus): render `items` with the backend's native menu affordance, firing
8008    // `Event::MenuAction(id)` (enqueue-only) for each id'd item; `role` items use the native standard
8009    // command. Default no-op: a toolkit without a menu bar / context menu shows nothing.
8010    /// The application menu (macOS/Windows/Linux menu bar; the app-bar overflow on Android; the
8011    /// UIMenuBuilder main menu on iPadOS/Catalyst). Replaces any previous app menu.
8012    fn set_app_menu(&mut self, _items: &[MenuItem]) {}
8013    /// A context menu for `h`, shown on secondary-click (desktop) or long-press (mobile). Passing an
8014    /// empty slice removes it.
8015    fn set_context_menu(&mut self, _h: &Self::Handle, _node: NodeId, _items: &[MenuItem]) {}
8016    /// Make the button `h` (a [`kinds::BUTTON`] node) a pull-down menu button (docs/menus.md
8017    /// "Menu buttons"): its primary press (a click, a tap, the keyboard's Space or Return, the
8018    /// accessibility press) asks `f` for the menu at that moment and shows it under the button
8019    /// with the toolkit's own menu, instead of reporting [`Event::Pressed`]. `f` is called on
8020    /// the UI thread, outside any day-core borrow, with [`Point::ZERO`] (where on the button
8021    /// the press landed does not change its menu); an empty result shows nothing. Chosen items
8022    /// fire [`Event::MenuAction`] as a context menu's do.
8023    ///
8024    /// A toolkit with no native menu to show reports [`Event::ContextMenu`] for `node` instead,
8025    /// with `window` at the button's bottom-leading corner, and the pieces layer presents the
8026    /// composed menu there. Called once per realized button; the release sweep reclaims `f`.
8027    /// Resolve the press through [`resolve_button_menu`], which re-checks after `f` runs that
8028    /// the button was not released by it. Default no-op: the button stays an inert button.
8029    fn set_button_menu(&mut self, _h: &Self::Handle, _node: NodeId, _f: ContextMenuFn) {}
8030
8031    // toolbars (docs/toolbars.md): a window's native toolbar: NSToolbar, AdwHeaderBar, QToolBar,
8032    // CommandBar. `h` is the window root's handle (the same handle `open_window` returned, or the
8033    // primary root's); the backend walks from it to the window it belongs to. Default no-op: a
8034    // toolkit with no toolbar shows nothing rather than a drawn imitation, and reports
8035    // `Cap::Toolbar` as `Unsupported` so an app can put the command somewhere else.
8036    /// Edit the window's toolbar (docs/toolbars.md): the [`ToolbarOp`]s, removals first, then
8037    /// insertions in ascending position. The bar starts empty, and becomes empty again when every
8038    /// item has been removed, at which point the backend takes it off the window.
8039    ///
8040    /// An item no op names must keep its native widget untouched, which is what keeps a search
8041    /// field focused while the page around it changes. Day sends an edit only when the bar
8042    /// changed, at most once per turn, and an item keeps its [`ToolbarItem::action`] for as long
8043    /// as its window shows an item with that id, so a native item's handler never needs
8044    /// repointing. Keep a [`ToolbarMirror`] and place each new item after
8045    /// [`ToolbarMirror::prev_where`] its group.
8046    ///
8047    /// Returns whether the edit was applied. `false` (the window has no bar to edit yet) makes
8048    /// Day send the whole bar again at the next change rather than assume this one landed.
8049    fn edit_toolbar(&mut self, _h: &Self::Handle, _ops: &[ToolbarOp]) -> bool {
8050        true
8051    }
8052    /// Apply a targeted change to one live toolbar item, the path a bound signal writes through,
8053    /// so syncing a search field does not rebuild the bar. No-op if the item is not present.
8054    fn update_toolbar(&mut self, _h: &Self::Handle, _patch: &ToolbarPatch) {}
8055
8056    // lifecycle (docs/lifecycle.md): does this backend deliver `phase`? The default answers "yes" for
8057    // the universal phases (launch/activation/termination) and "no" for the mobile-only ones. Backends
8058    // that wire up more (the mobile ones) override this; it must agree with the crate's
8059    // `const fn lifecycle_supported`, which drives compile-time guards in `day::require_lifecycle!`.
8060    fn supports_lifecycle(&self, phase: Lifecycle) -> bool {
8061        phase.is_universal()
8062    }
8063
8064    // pillars
8065    /// Apply a node's accessibility annotations (docs/accessibility.md): the label, hint and
8066    /// value the screen reader speaks, an explicit role, whether the node is hidden from
8067    /// assistive technology, and the automation identifier. Called with the node's whole
8068    /// accumulated set each time any of it changes, so every member is written on every call.
8069    /// Only an explicit role is applied: a native control reports its own.
8070    fn set_a11y(&mut self, _h: &Self::Handle, _a11y: &A11yProps) {}
8071    /// Speak `text` through the screen reader without moving its focus (docs/accessibility.md;
8072    /// probe [`Cap::Announce`]). `urgent` interrupts what is being read; otherwise the sentence
8073    /// waits its turn. Nothing happens when no screen reader is running. The default is a
8074    /// backend that reaches no announcement API.
8075    fn announce(&mut self, _text: &str, _urgent: bool) {}
8076    /// Read a widget's native state back from the platform for `a11y_audit` and
8077    /// `assert_native` (§14.2, docs/testing.md) to diff against Day's expectation. Default:
8078    /// nothing read; the audit skips the node and `assert_native` records each field as unread.
8079    fn read_native(&self, _h: &Self::Handle) -> NativeSnapshot {
8080        NativeSnapshot::default()
8081    }
8082    fn replay(&mut self, _h: &Self::Handle, _ops: &[DrawOp], _size: Size) {}
8083
8084    /// Every family this toolkit can draw canvas text in, with the faces each ships
8085    /// (docs/fonts.md; probe [`Cap::FontList`]). Default: none. `day::font_families` calls
8086    /// this once per process and caches the answer: enumeration is slow on every platform
8087    /// (fontconfig, a DirectWrite collection, an XML parse on Android) and the set does not
8088    /// change under a running app.
8089    fn font_families(&mut self) -> Vec<FontFamilyInfo> {
8090        Vec::new()
8091    }
8092
8093    /// Measure one line of canvas text at `size` points in `font`, in the same engine
8094    /// [`Toolkit::replay`] draws [`DrawOp::Text`] with, so a `TextAnchor::LEADING` anchor plus
8095    /// the returned `ascent` lands on the drawn baseline. `None` = cannot measure; the facade
8096    /// then answers [`TextMetrics::approximate`].
8097    fn measure_text(&mut self, _text: &str, _size: f64, _font: &CanvasFont) -> Option<TextMetrics> {
8098        None
8099    }
8100    // --- raster images (docs/images.md) -------------------------------------------------
8101    //
8102    // Request-id shaped rather than blocking, because one backend can never answer
8103    // synchronously: a browser decodes through `createImageBitmap`, which is a promise. Every
8104    // other backend decodes inline and raises the completion before returning, so the shape
8105    // costs them nothing but a line, and the app-facing API can be one thing everywhere
8106    // instead of two (docs/async.md rule 3: a callback and a future, never a runtime).
8107
8108    /// Decode encoded image bytes (PNG/JPEG/…) into a native image, answering `req` with
8109    /// [`Event::ImageDecoded`].
8110    ///
8111    /// The id in that event is minted by the caller (day-core), not the backend: the backend
8112    /// keeps its own side table from that id to whatever it decoded.
8113    ///
8114    /// The default does nothing because a default body cannot reach the event sink
8115    /// (it is installed per backend by [`Toolkit::set_event_sink`], not reachable through this
8116    /// trait), so there is no way for it to answer. day-core asks [`Cap::ImageDecode`] first and
8117    /// resolves the request as [`ImageError::Unsupported`] itself, which is why a backend with
8118    /// no decoder needs no code here at all.
8119    fn decode_image(&mut self, _req: u64, _id: BitmapId, _bytes: &[u8]) {}
8120
8121    /// What a decoded image is: pixel size, scale, format, alpha ([`BitmapInfo`]).
8122    ///
8123    /// Synchronous: every backend that decoded the image already holds these facts. `None` means
8124    /// the id names nothing live.
8125    fn image_info(&mut self, _id: BitmapId) -> Option<BitmapInfo> {
8126        None
8127    }
8128
8129    /// The metadata beyond the pixels: EXIF orientation, DPI, capture time
8130    /// ([`ImageProperties`], probe [`Cap::ImageProperties`]). `None` where the backend has no
8131    /// metadata reader, which is most of them.
8132    fn image_properties(&mut self, _id: BitmapId) -> Option<ImageProperties> {
8133        None
8134    }
8135
8136    /// Encode a decoded image back to bytes per `spec`, answering `req` with
8137    /// [`Event::ImageEncoded`]. A format outside [`Self::encode_formats`] answers
8138    /// [`ImageError::Encode`] rather than silently substituting another one.
8139    ///
8140    /// Defaulted to nothing for the same reason as [`Self::decode_image`]: day-core probes
8141    /// [`Cap::ImageEncode`] and answers `Unsupported` without ever calling this.
8142    fn encode_image(&mut self, _req: u64, _id: BitmapId, _spec: &EncodeSpec) {}
8143
8144    /// Which formats [`Self::encode_image`] can write, the [`Cap::ImageEncode`]
8145    /// counterpart of [`Self::font_families`]/[`Cap::FontList`]. Empty by default.
8146    fn encode_formats(&mut self) -> Vec<ImageFormat> {
8147        Vec::new()
8148    }
8149
8150    /// Drop a decoded image and everything the backend cached for it. Called when the app's
8151    /// last handle to it goes away; an id the backend never saw is a no-op.
8152    fn release_image(&mut self, _id: BitmapId) {}
8153
8154    // --- canvas export (docs/canvas.md "Exporting") --------------------------------------
8155    //
8156    // Request-id shaped like the image duties above, for the same reason: the browser's
8157    // `createImageBitmap` is a promise, and a native toolkit may paint on another thread. A
8158    // backend may also answer inline, before returning. day-core validates sizes, enforces
8159    // the pixel limits and probes the caps first, so a backend sees only requests it can
8160    // attempt.
8161
8162    /// Replay `ops` into a new offscreen bitmap of `size` points at `scale` pixels per point
8163    /// ([`export_pixels`] gives the pixel size), with a transparent background and the
8164    /// canvas's top-left origin. Store it under `id` in the same table [`Self::decode_image`]
8165    /// fills, so `image_info`, `encode_image`, `release_image`, the `image` piece and
8166    /// [`DrawOp::Image`] all take it, then answer `req` with [`Event::BitmapRendered`] (its
8167    /// [`BitmapInfo::scale`] is `scale`).
8168    ///
8169    /// The painter must be the one [`Self::replay`] uses, so text, gradients, clips and stamps
8170    /// match the screen. Where the platform's 2-D API draws into a memory surface from any
8171    /// thread, the paint runs on a thread of [`offscreen`] and the answer is posted back, so
8172    /// a long replay never stalls the UI; the toolkit resolves on the UI thread, before it
8173    /// hands the job over, everything the painter would otherwise read from UI-thread state
8174    /// (the decoded images the ops reference, the fonts their text runs need). The contract
8175    /// holds either way: one answer per request, carrying that request's `req`, raised on the
8176    /// UI thread, and the bitmap in the table before it. Defaulted to nothing: day-core probes
8177    /// [`Cap::CanvasBitmap`] and answers [`ExportError::Unsupported`] itself.
8178    fn render_bitmap(
8179        &mut self,
8180        _req: u64,
8181        _id: BitmapId,
8182        _ops: &[DrawOp],
8183        _size: Size,
8184        _scale: f64,
8185    ) {
8186    }
8187
8188    /// Replay each page into one PDF document and answer `req` with [`Event::PdfRendered`].
8189    /// Units are PDF points, top-left origin; shapes and text stay vector, and images embed at
8190    /// their pixel size. `pages` is never empty. Defaulted to nothing: day-core probes
8191    /// [`Cap::CanvasPdf`] first.
8192    fn render_pdf(&mut self, _req: u64, _pages: &[PdfPage], _info: &PdfInfo) {}
8193
8194    fn snapshot_window(&mut self) -> Result<Vec<u8>, String> {
8195        Err("snapshot unsupported".into())
8196    }
8197    /// Where `root`, the primary window's root container, sits in [`Self::snapshot_window`]'s
8198    /// image, in points from its top-left. A reader of the capture (dayscript `sample_pixel`)
8199    /// maps Day's frames into it with this; it matters where the capture spans more than Day's
8200    /// content on more than one side, as Android's edge-to-edge content does (status bar
8201    /// above, navigation bar below).
8202    ///
8203    /// Defaulted to `None`, which the reader takes as "any rows beyond Day's content are
8204    /// above it", true where the only extra area is a title bar.
8205    fn snapshot_origin(&mut self, _root: &Self::Handle) -> Option<Point> {
8206        None
8207    }
8208    /// Establish a fresh screenshot checkpoint after reactive work and native transitions.
8209    /// `revision` is stable across retries and unique to the request; `host` selects a
8210    /// secondary window, or None for the primary. Never block the UI thread waiting for
8211    /// a frame. Pending requests are retried within the dayscript deadline.
8212    ///
8213    /// Ready means the platform render checkpoint completed, not that a vsync callback
8214    /// proves pixels were displayed. OnCapture delegates freshness to snapshot_window.
8215    fn prepare_snapshot(
8216        &mut self,
8217        _host: Option<&Self::Handle>,
8218        _revision: u32,
8219    ) -> Result<capture::Readiness, String> {
8220        // Compatible with external toolkits predating this hook: their synchronous
8221        // snapshot owns freshness, and no external-capture acknowledgment is fabricated.
8222        Ok(capture::Readiness::OnCapture)
8223    }
8224
8225    /// The same capture with the window's own chrome: title bar, toolbar, whatever the platform
8226    /// draws around the content (docs/window-image.md).
8227    ///
8228    /// Defaulted to [`Self::snapshot_window`]: a backend that cannot separate the two
8229    /// (or has no chrome to speak of, a phone) answers with the content shot rather than an
8230    /// error, so an app asking for chrome degrades to "what there was" instead of failing. The
8231    /// dayscript `screenshot` step never calls this, which is what keeps every captured gallery
8232    /// baseline byte-identical to before it existed.
8233    fn snapshot_window_chrome(&mut self) -> Result<Vec<u8>, String> {
8234        self.snapshot_window()
8235    }
8236    /// Show/hide the sidebar pane of the navigation host `host`, which is what the sidebar
8237    /// affordance a `nav(Sidebar)` contributes for itself drives ([`SIDEBAR_TOGGLE_ID`]).
8238    /// `false` when `host` has no pane to toggle (a stack, a tab bar, no sidebar concept at all).
8239    ///
8240    /// Per host, not per process: a second window's button collapses that window's sidebar
8241    /// and not the first's. The item's own action makes the call, and dayscript's `toolbar:`
8242    /// step presses the item like any other, so a walkthrough drives exactly the path a click
8243    /// takes. Defaulted, so a backend with no sidebar needs no code. docs/toolbars.md,
8244    /// docs/navigation.md.
8245    fn toggle_sidebar(&mut self, _host: &Self::Handle) -> bool {
8246        false
8247    }
8248    /// Press the platform's own back affordance (the navigation bar's back button on iOS,
8249    /// the system back on Android) on the innermost navigation host that has something to
8250    /// pop. What `nav_back()` does not do: that is Day's rail, which pops the model and lets the
8251    /// backend follow, while this runs the native path first (the bar's `shouldPop`, the
8252    /// dispatcher's callbacks, the pop itself) and lets the backend report it to Day as a user
8253    /// back, guard and all. dayscript's `nav_back: { native: true }` drives it, so a walkthrough
8254    /// can cover the code that a real tap runs and Day's rail never reaches. `false` when this
8255    /// toolkit has no native back or nothing is popped by it. Defaulted, so a desktop needs no
8256    /// code. docs/navigation.md.
8257    fn native_back(&mut self) -> bool {
8258        false
8259    }
8260    /// Take (`true`) or release (`false`) the platform's system back for the app's own
8261    /// handlers ([`Decorate::on_system_back`](/api/day_pieces/trait.Decorate.html#method.on_system_back)):
8262    /// day-core arms it while at least one mounted handler is enabled. Armed, a system back that
8263    /// nothing native consumes first (a presented cover, a pushed page, an armed guard) reaches
8264    /// Day as [`Event::NavBack`] on [`WINDOW_NODE`] instead of leaving the app; released, the
8265    /// platform's default runs, predictive-back preview and all. Android registers an
8266    /// `OnBackPressedCallback` beneath its own; HarmonyOS consumes the page's `onBackPress`.
8267    /// Defaulted, so a toolkit with no system back (desktop, iOS, the web) needs no code.
8268    /// docs/navigation.md "Handling the system Back".
8269    fn set_system_back(&mut self, _armed: bool) {}
8270    /// Whether the UI has settled, with no native transition (modal present/dismiss, nav push)
8271    /// still animating. The dayscript `screenshot` step polls this before capturing so shots
8272    /// never catch a half-faded dialog or half-pushed page. Backends without async
8273    /// transitions (or without a way to know) report `true`.
8274    fn ui_idle(&mut self) -> bool {
8275        true
8276    }
8277
8278    // imperative presentation (docs/dialogs.md): show a native modal for request `req`;
8279    // the backend answers by enqueuing `Event::PresentResult { req, .. }`. `dismiss` is
8280    // used only when Day resolves programmatically (dayscript) while the modal is still up.
8281    fn present(&mut self, _req: u64, _spec: &present::PresentSpec) {}
8282    fn dismiss(&mut self, _req: u64) {}
8283
8284    /// Open `url` in the platform's default handler: the system browser for `http(s)`, the mail
8285    /// client for `mailto:`, etc. Backs the [`link`](/api/day_pieces/fn.link.html) piece. Fire and
8286    /// forget: there is no result, and an unopenable URL is ignored. The default no-ops so a
8287    /// backend that hasn't wired it up still compiles.
8288    fn open_url(&mut self, _url: &str) {}
8289
8290    /// Whether a native share chooser is available. Does not probe installed share targets.
8291    fn share_support(&self) -> Support {
8292        Support::Unsupported
8293    }
8294    /// Present the system share chooser for `spec` (docs/sharing.md). True means presentation
8295    /// started, not that sharing completed. Never sends data without the user's choice of a
8296    /// target. Where the chooser can carry the app's own actions (`Cap::ShareActions`), each
8297    /// of `spec.actions` appears with its title and glyph, and choosing one enqueues
8298    /// `Event::MenuAction(action.id)`; elsewhere the actions are left out. `anchor` is the
8299    /// control the chooser points at where it is a popover (iPad, macOS); without one the
8300    /// chooser uses the window's top trailing corner.
8301    fn share(&mut self, _spec: &share::ShareSpec, _anchor: Option<&Self::Handle>) -> bool {
8302        false
8303    }
8304
8305    /// Read current OS associations. Unsupported platforms must not fabricate a default.
8306    fn application_handlers(
8307        &mut self,
8308        _query: &applications::HandlerQuery,
8309    ) -> Result<applications::ApplicationHandlers, applications::ApplicationError> {
8310        Err(applications::ApplicationError::Unsupported)
8311    }
8312
8313    /// Open with an opaque application identifier returned by `application_handlers`.
8314    fn open_url_with_application(
8315        &mut self,
8316        _url: &str,
8317        _application: &str,
8318        completion: applications::OpenApplicationCompletion,
8319    ) {
8320        completion(Err(applications::ApplicationError::Unsupported));
8321    }
8322
8323    /// Ask the OS to require a second swipe for its edge gestures on `edges` (docs/cover.md):
8324    /// the union requested by every mounted `defers_system_gestures` modifier, re-sent whenever
8325    /// that set changes (`Edges::NONE` when the last one unmounts). iOS defers the home
8326    /// indicator / notification edges; Android enters swipe-to-reveal immersive mode while
8327    /// non-empty. The default no-ops (desktop has no system edge gestures).
8328    fn defer_system_gestures(&mut self, _edges: Edges) {}
8329
8330    /// Hide (`true`) or show the system status bar (docs/cover.md): whether any mounted
8331    /// `status_bar_hidden` modifier currently asks for it hidden, re-sent whenever that answer
8332    /// may have changed (`false` when the last request unmounts). iOS answers the root and
8333    /// cover view controllers' `prefersStatusBarHidden`; Android and HarmonyOS hide the status
8334    /// bar through their window inset controls. The default no-ops (desktop and web have no
8335    /// status bar); report `Cap::StatusBarHidden` alongside an implementation.
8336    fn set_status_bar_hidden(&mut self, _hidden: bool) {}
8337
8338    /// Whether the platform is rendering in dark appearance right now. Apps painting
8339    /// custom surfaces (opaque overlay panels, scrims) branch on this so their fills track
8340    /// the theme the default text colors already follow; hardcoding either theme's
8341    /// surface produces dark-on-dark or light-on-light text on the other. Queried at
8342    /// build time (a piece rebuilt after a theme change re-queries). The default honors a
8343    /// `DAY_THEME` launch override and otherwise answers light.
8344    /// Resolve a semantic color for custom artwork. Backends with native palette access
8345    /// override this; the default follows light/dark appearance using Day's fixed palette.
8346    fn system_color(&mut self, role: SystemColor) -> Color {
8347        role.fallback(self.dark_mode())
8348    }
8349
8350    fn dark_mode(&mut self) -> bool {
8351        std::env::var("DAY_THEME").ok().as_deref() == Some("dark")
8352    }
8353    /// Whether the user asked the system for less motion (docs/accessibility.md; probe
8354    /// [`Cap::ReduceMotion`]): macOS and iOS "Reduce Motion", Android "Remove animations" (an
8355    /// animator duration scale of zero), GTK's `gtk-enable-animations` off, Windows "Show
8356    /// animations" off, the web's `prefers-reduced-motion`. Read at launch; a backend that
8357    /// watches the setting calls `day_core::note_motion_changed` when it flips. Day then applies
8358    /// every finite animation at its destination and keeps only indeterminate motion. The default
8359    /// is a backend that reads no such setting.
8360    fn reduce_motion(&mut self) -> bool {
8361        false
8362    }
8363
8364    /// App-level appearance override: `Some(true)` forces dark, `Some(false)` forces light,
8365    /// `None` returns to following the system. Backends restyle their native widgets in
8366    /// place and answer the override from [`dark_mode`](Self::dark_mode); app-painted
8367    /// surfaces pick it up on their next rebuild. `Cap::Appearance` reports whether the
8368    /// backend honors this; the default ignores the call.
8369    fn set_appearance(&mut self, _dark: Option<bool>) {}
8370
8371    /// Put `badge` on the app's icon in the Dock / launcher / home screen (docs/badge.md).
8372    ///
8373    /// Fire-and-forget, like `set_appearance`: a payload this toolkit cannot render is ignored, and
8374    /// the app probes `Cap::AppBadge{Count,Text,Dot}` before choosing one. Never substitute: a
8375    /// backend that turned `Text("beta")` into `Count(1)` would put a wrong number on a user's
8376    /// icon, which is worse than showing nothing. The default ignores every call.
8377    fn set_app_badge(&mut self, _badge: &AppBadge) {}
8378
8379    // app lifecycle (mobile; desktop backends no-op)
8380    fn on_suspend(&mut self) {}
8381    fn on_resume(&mut self) {}
8382    fn on_memory_warning(&mut self) {}
8383
8384    // adoption of foreign native handles (polyglot pieces, §15.3)
8385    fn adopt(&mut self, _raw: RawHandle) -> Self::Handle {
8386        unimplemented!("this toolkit does not adopt foreign handles yet")
8387    }
8388
8389    // secondary windows (docs/windows.md)
8390
8391    /// Open a native OS window per `options` + `kind`: create and show the window, wire its
8392    /// events to `id` (`WindowResized` with the content size in points, `WindowClosed` after
8393    /// the native close, `WindowFocused` on key/active changes), and answer with its content
8394    /// container handle, the same contract as the `ready` root container. Backends whose
8395    /// window creation is asynchronous (a scene, an activity, an ability) answer
8396    /// [`WindowOpenReply::Pending`] and complete later through
8397    /// `day_core::finish_window_open(id, raw, size)`, which goes through [`Toolkit::adopt`].
8398    /// The default answers `Unsupported`; day-core then presents the content as a
8399    /// fullscreen cover in the primary window instead.
8400    fn open_window(
8401        &mut self,
8402        _id: NodeId,
8403        _options: &WindowOptions,
8404        _kind: WindowKind,
8405    ) -> WindowOpenReply<Self::Handle> {
8406        WindowOpenReply::Unsupported
8407    }
8408
8409    /// Close the native window whose content container is `host` (a handle `open_window`
8410    /// produced). Asynchronous: the platform confirms with `Event::WindowClosed` on the
8411    /// window's root node, and only then does day-core tear the subtree down. Idempotent; unknown
8412    /// hosts are ignored. Never called with the primary window's container.
8413    fn close_window(&mut self, _host: &Self::Handle) {}
8414
8415    /// End the application: the last window with [`WindowRole::Primary`] has closed
8416    /// (docs/windows.md). day-core decides when, since it owns the window registry and the role
8417    /// each window carries; the backend supplies only the platform's exit:
8418    /// `NSApplication.terminate`, `QCoreApplication::quit`, `GtkApplication.quit`,
8419    /// `PostQuitMessage`. Everything day-core wanted to happen first (secondary windows
8420    /// disposed, `WillTerminate` delivered) already has by the time this is called.
8421    ///
8422    /// The default does nothing, which is right for the backends whose process lifetime is
8423    /// not theirs to end: a browser tab, an Android activity, an iOS scene.
8424    fn quit_app(&mut self) {}
8425
8426    /// Bring the window whose content container is `host` to front and make it key/active:
8427    /// the focus half of open-or-focus singleton windows. Default no-op.
8428    fn focus_window(&mut self, _host: &Self::Handle) {}
8429
8430    /// Retitle the window whose content container is `host`. Default no-op.
8431    fn set_window_title(&mut self, _host: &Self::Handle, _title: &str) {}
8432
8433    /// Resize the window whose content container is `host` to fit `size` of content, and pin it
8434    /// there: what `WindowOptions::size_to_fit` asks for (docs/windows.md).
8435    ///
8436    /// `size` is the content size Day measured, not the window's outer frame: the backend adds
8437    /// its chrome. A settings panel is the case this exists for, and every desktop platform
8438    /// sizes one to its content rather than to a number the app guessed; a fixed height either
8439    /// clips the last row or leaves a band of empty panel under it, and which one you get depends
8440    /// on the user's text size.
8441    ///
8442    /// Default no-op, so a toolkit that cannot resize a live window keeps the size it was
8443    /// opened at, which is what every backend did before this existed.
8444    fn fit_window(&mut self, _host: &Self::Handle, _size: Size) {}
8445
8446    /// Snapshot the window whose content container is `host` (the dayscript `screenshot`
8447    /// step's `window:` target). The default answers the primary snapshot, so backends that
8448    /// never open windows stay correct without changes.
8449    fn snapshot_window_of(&mut self, _host: &Self::Handle) -> Result<Vec<u8>, String> {
8450        self.snapshot_window()
8451    }
8452
8453    /// Apply one property change to the window whose content container is `host`
8454    /// (docs/windows.md "Window properties"). The primary window arrives with its root container,
8455    /// like [`set_window_title`](Self::set_window_title).
8456    ///
8457    /// Fire-and-forget, like [`set_app_badge`](Self::set_app_badge): a change this toolkit cannot
8458    /// make is ignored, and the app probes the matching `Cap` (named on each [`WindowChange`]
8459    /// variant) before relying on it. A change the platform completes later (a fullscreen
8460    /// transition, a zoom animation) reports its outcome through
8461    /// [`Event::WindowStateChanged`], never by assuming the request took. The default ignores
8462    /// every change.
8463    fn apply_window(&mut self, _host: &Self::Handle, _change: &WindowChange) {}
8464
8465    /// True OS window groups, as distinct from native tab widgets.
8466    fn native_window_tabs(&self) -> bool {
8467        false
8468    }
8469    /// Native in-window document/section tab control; OS grouping is reported separately.
8470    fn native_document_tabs(&self) -> bool {
8471        false
8472    }
8473    /// Join/reorder these windows in an OS tab group. Content remains window-owned.
8474    fn group_windows(&mut self, _hosts: &[Self::Handle]) {}
8475    /// Current native order of the group containing this window, including detached groups.
8476    fn window_tab_order(&self, _host: &Self::Handle) -> Vec<NodeId> {
8477        Vec::new()
8478    }
8479
8480    /// Install the app's Dock menu (docs/menus.md "Dock menu"): the items macOS shows above
8481    /// its own when the user right-clicks the app's Dock icon, built from the app's
8482    /// `[[shortcuts]]` and its `dock_menu(..)` entries. Same item model and dispatch as
8483    /// [`set_app_menu`](Self::set_app_menu); an empty slice removes the menu. `Cap::DockMenu`
8484    /// reports support; the default ignores the call.
8485    fn set_dock_menu(&mut self, _items: &[MenuItem]) {}
8486
8487    /// Make the node at `h` move its window when the user drags it, as a title bar does
8488    /// (`.window_drag_region()`, docs/window-chrome.md): the region's own background starts a
8489    /// native window drag (with the platform's snapping and edge tiling), a double click does
8490    /// what the user's title-bar double-click setting says, and controls inside the region keep
8491    /// receiving their own clicks. `false` releases it. `Cap::DragRegion`; the default ignores
8492    /// the call, so on a phone the region is an ordinary view.
8493    fn set_drag_region(&mut self, _h: &Self::Handle, _drag: bool) {}
8494
8495    /// Show these status items, replacing the previous set (docs/status-item.md): add the
8496    /// ones whose `id` is new, update the ones that changed, remove the ones no longer listed.
8497    /// A click on an item runs its `activate` action or opens its menu; menu choices dispatch
8498    /// [`Event::MenuAction`] like the app menu's. `Cap::StatusItem`; the default ignores the
8499    /// call, which is what a phone and the web do.
8500    fn set_status_items(&mut self, _items: &[StatusItemSpec]) {}
8501
8502    /// Show `progress` on the app's Dock or taskbar icon (docs/status-item.md).
8503    /// `Cap::AppProgress`; the default ignores it.
8504    fn set_app_progress(&mut self, _progress: AppProgress) {}
8505
8506    /// Show or hide the app's Dock icon while it runs: a menu-bar app hides it and lives in its
8507    /// status item (macOS activation policy). `Cap::DockVisibility`; the default ignores it.
8508    fn set_dock_visible(&mut self, _visible: bool) {}
8509
8510    /// Keep the process running when its last window closes (docs/windows.md "Keeping the app
8511    /// running"). When `true`, the backend must not end the app on its own as windows close: it
8512    /// reports every close, the first window's included, as `Event::WindowClosed`, and day-core
8513    /// decides whether to call [`quit_app`](Self::quit_app). When `false`, the backend keeps its
8514    /// platform's own rule. A backend whose process lifetime is not its own (a phone, a browser
8515    /// tab) ignores it, which is the default.
8516    fn set_keep_running(&mut self, _keep: bool) {}
8517
8518    /// The displays attached now (docs/windows.md "Monitors"). `Cap::Monitors`; the default
8519    /// answers none, and day-core then describes the primary window's own size as one display.
8520    fn monitors(&self) -> Vec<Monitor> {
8521        Vec::new()
8522    }
8523
8524    /// The outer frame of the window whose content container is `host`, in points on the
8525    /// desktop's coordinate space (top-left origin), or `None` where the platform does not say
8526    /// (a phone, Wayland's positions). Read when the app asks for it and when day-core saves a
8527    /// remembered frame (`WindowOptions::remember_frame`).
8528    fn window_frame(&self, _host: &Self::Handle) -> Option<Rect> {
8529        None
8530    }
8531
8532    /// Replace the launcher shortcuts the app set while running (docs/deep-links.md "Launcher
8533    /// shortcuts"), shown beside the ones Day.toml declares: iOS Home Screen quick actions,
8534    /// Android dynamic shortcuts, the macOS Dock menu. Each opens its route through the deep-link
8535    /// intake. `Cap::DynamicShortcuts`; the default ignores the call.
8536    fn set_launcher_shortcuts(&mut self, _shortcuts: &[LauncherShortcut]) {}
8537}
8538
8539/// What a secondary window is, so backends can apply platform conventions (docs/windows.md).
8540#[derive(Clone, Copy, PartialEq, Eq, Debug)]
8541pub enum WindowKind {
8542    /// A regular document/tool window: resizable, miniaturizable, platform-default tabbing.
8543    Normal,
8544    /// A settings/preferences window: singleton by convention; macOS disallows window
8545    /// tabbing and drops the resize/minimize chrome, mobile presents it modally. Pairs with
8546    /// day-core's key-singleton reopen (`open_window` with a key).
8547    Preferences,
8548    /// The About window (docs/settings.md): the same fixed, centered, untabbed panel chrome
8549    /// as [`Self::Preferences`] (every desktop treats the two alike), presented modally on
8550    /// mobile. Singleton under day-core's `day.about` key.
8551    About,
8552}
8553
8554impl WindowKind {
8555    /// Whether this is a panel (settings or About) rather than a document window: the kinds
8556    /// every desktop draws fixed-size, centered and out of the Window menu, and mobile presents
8557    /// as a cover.
8558    pub fn is_panel(self) -> bool {
8559        !matches!(self, WindowKind::Normal)
8560    }
8561}
8562
8563/// Whether a window keeps the app alive (docs/windows.md close policy).
8564///
8565/// A separate axis from [`WindowKind`], which describes chrome. They correlate (a
8566/// preferences panel is the archetypal window that should not hold an app open), but they are
8567/// not the same question, and conflating them would leave no way to say "an ordinary-looking
8568/// tool window that shouldn't outlive the documents".
8569///
8570/// Note the word "secondary" is overloaded around windows: elsewhere in day it means "a window
8571/// other than the first one opened". Here it means "does not keep the app alive", which is
8572/// about lifetime, not about order of creation.
8573#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
8574pub enum WindowRole {
8575    /// Closing the last one of these ends the app.
8576    #[default]
8577    Primary,
8578    /// Never keeps the app alive: when the last `Primary` closes, the app exits and takes
8579    /// these with it, however many are open.
8580    Secondary,
8581}
8582
8583impl From<WindowKind> for WindowRole {
8584    /// The default pairing: an ordinary window holds the app open, a preferences panel does
8585    /// not. An app that needs a different answer sets the role itself.
8586    fn from(kind: WindowKind) -> WindowRole {
8587        match kind {
8588            WindowKind::Normal => WindowRole::Primary,
8589            WindowKind::Preferences | WindowKind::About => WindowRole::Secondary,
8590        }
8591    }
8592}
8593
8594/// A backend's answer to [`Toolkit::open_window`] (docs/windows.md).
8595pub enum WindowOpenReply<H> {
8596    /// The window exists now; here is its content container (desktop backends).
8597    Open(H),
8598    /// Native creation started but completes asynchronously (a scene, an activity, an
8599    /// ability); the backend will call `day_core::finish_window_open` when the content
8600    /// container exists. day-core parks the window record until then.
8601    Pending,
8602    /// This toolkit cannot open windows (`Cap::MultiWindow` = `Unsupported`); day-core
8603    /// falls back to presenting the content as a fullscreen cover in the primary window.
8604    Unsupported,
8605}
8606
8607/// How a window is shown (docs/windows.md "Window properties"): what the window's `state()`
8608/// signal holds and what [`WindowChange::State`] asks for.
8609#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
8610pub enum WindowState {
8611    /// On screen at its own size: neither minimized, maximized nor fullscreen.
8612    #[default]
8613    Normal,
8614    /// Minimized to the Dock, taskbar or shelf. `Cap::WindowStates`.
8615    Minimized,
8616    /// Zoomed to fill the screen's work area, keeping its chrome. `Cap::WindowStates`.
8617    Maximized,
8618    /// Covering the whole screen with no window chrome; on a phone, the system bars hidden.
8619    /// `Cap::WindowFullscreen`.
8620    Fullscreen,
8621}
8622
8623impl WindowState {
8624    /// The wire code of [`bridge::BridgeKind::WindowStateChanged`].
8625    pub const fn code(self) -> i32 {
8626        match self {
8627            WindowState::Normal => 0,
8628            WindowState::Minimized => 1,
8629            WindowState::Maximized => 2,
8630            WindowState::Fullscreen => 3,
8631        }
8632    }
8633
8634    /// The state a wire code names; an unknown code reads as `Normal`.
8635    pub const fn from_code(code: i32) -> WindowState {
8636        match code {
8637            1 => WindowState::Minimized,
8638            2 => WindowState::Maximized,
8639            3 => WindowState::Fullscreen,
8640            _ => WindowState::Normal,
8641        }
8642    }
8643}
8644
8645/// How a window stacks against other apps' windows ([`WindowChange::Level`], `Cap::WindowLevel`).
8646#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
8647pub enum WindowLevel {
8648    /// Ordinary stacking: the focused app's windows come forward.
8649    #[default]
8650    Normal,
8651    /// Stays above other apps' ordinary windows: a palette, a timer, a video peek.
8652    Floating,
8653}
8654
8655/// How strongly a window asks for the user's attention ([`WindowChange::RequestAttention`]).
8656#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
8657pub enum Attention {
8658    /// Once: one Dock bounce, a taskbar button that flashes a few times.
8659    #[default]
8660    Informational,
8661    /// Until the user switches to the app.
8662    Critical,
8663}
8664
8665/// One change to one window (docs/windows.md "Window properties"), carried by
8666/// [`Toolkit::apply_window`]. Each variant names the `Cap` that reports whether the running
8667/// toolkit makes it.
8668#[derive(Clone, Debug, PartialEq)]
8669pub enum WindowChange {
8670    /// Minimize, zoom, take fullscreen, or return to normal. `Cap::WindowStates` for the
8671    /// first two, `Cap::WindowFullscreen` for fullscreen. The outcome comes back as
8672    /// [`Event::WindowStateChanged`].
8673    State(WindowState),
8674    /// Keep the window's content out of screenshots, recordings and screen sharing.
8675    /// `Cap::ContentProtection`.
8676    ContentProtected(bool),
8677    /// Move and/or resize. `origin` is the outer frame's top-left corner in points on the
8678    /// desktop's coordinate space (top-left origin, `Cap::WindowPosition`); `size` is the size Day
8679    /// lays the content out at, in points, the same size `WindowResized` reports
8680    /// (`Cap::WindowGeometry`): the backend adds its own chrome around it.
8681    Frame {
8682        origin: Option<Point>,
8683        size: Option<Size>,
8684    },
8685    /// The content size the user can resize the window to. `None` lifts that bound.
8686    /// `Cap::WindowGeometry`.
8687    Limits {
8688        min: Option<Size>,
8689        max: Option<Size>,
8690    },
8691    /// Stacking against other apps' windows. `Cap::WindowLevel`.
8692    Level(WindowLevel),
8693    /// Show the window on every virtual desktop / Space. `Cap::WindowLevel`.
8694    OnAllWorkspaces(bool),
8695    /// Leave the window out of the taskbar and the window switcher. `Cap::WindowLevel`.
8696    SkipTaskbar(bool),
8697    /// Whether the user can resize the window. `Cap::WindowGeometry`.
8698    Resizable(bool),
8699    /// Whether the window offers a minimize control. `Cap::WindowStates`.
8700    Minimizable(bool),
8701    /// Whether the window offers a maximize / zoom control. `Cap::WindowStates`.
8702    Maximizable(bool),
8703    /// Whether the window offers a close control. `Cap::WindowStates`.
8704    Closable(bool),
8705    /// Hide the window without closing it, or show it again. `Cap::WindowStates`.
8706    Visible(bool),
8707    /// This window's light/dark override over the app-wide [`Toolkit::set_appearance`].
8708    /// `Cap::WindowAppearance`.
8709    Appearance(Option<bool>),
8710    /// Bounce the Dock icon, flash the taskbar button. `Cap::RequestAttention`.
8711    RequestAttention(Attention),
8712}
8713
8714/// The frame a window wears (docs/window-chrome.md), set once when it opens.
8715#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
8716pub enum WindowChrome {
8717    /// The platform's title bar and frame.
8718    #[default]
8719    Standard,
8720    /// The content runs to the window's top edge, under the title bar, and the platform's own
8721    /// window controls (close, minimize, zoom) stay where they are. For a custom title bar: the
8722    /// backend reports the bar's height as the window's safe-area top inset (`day::safe_area()`),
8723    /// so the app pads its content by it and paints its background under it. Mark the draggable
8724    /// part with `.window_drag_region()`. `Cap::OverlayTitleBar`; where unsupported the window
8725    /// keeps its standard bar.
8726    Overlay,
8727    /// No title bar and no frame: a splash screen, a heads-up panel, a borderless utility. The
8728    /// window still resizes from its edges when resizable; mark the part that moves it with
8729    /// `.window_drag_region()`. `Cap::FramelessWindow`; where unsupported the window keeps its
8730    /// standard frame.
8731    Frameless,
8732}
8733
8734/// What shows behind a window's content (docs/window-chrome.md).
8735#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
8736pub enum WindowBackground {
8737    /// The platform's window background.
8738    #[default]
8739    Opaque,
8740    /// Nothing: pixels the content leaves unpainted show the desktop through the window. For
8741    /// rounded or shaped splash screens and overlays. `Cap::TransparentWindow`.
8742    Transparent,
8743    /// A translucent system material that blurs what is behind the window.
8744    /// `Cap::WindowMaterial`; where unsupported the window stays opaque.
8745    Material(WindowMaterial),
8746}
8747
8748/// The system materials a window background can use ([`WindowBackground::Material`]).
8749#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
8750pub enum WindowMaterial {
8751    /// The main-window material: macOS's window background, Windows 11's Mica.
8752    Window,
8753    /// A sidebar or source list: macOS's sidebar material, Windows 11's Mica Alt (tabbed).
8754    Sidebar,
8755    /// A transient surface (a popover, a menu-like panel, a heads-up display): macOS's popover
8756    /// material, Windows 11's Acrylic.
8757    Transient,
8758}
8759
8760/// Where a window opens ([`WindowOptions::placement`]).
8761#[derive(Clone, Copy, Debug, Default, PartialEq)]
8762pub enum WindowPlacement {
8763    /// The platform's choice: macOS cascades, Windows and Linux let the window manager decide.
8764    #[default]
8765    Automatic,
8766    /// Centered on the screen with the active window.
8767    Centered,
8768    /// The outer frame's top-left corner at this point, in points on the desktop's coordinate
8769    /// space (top-left origin). Falls back to `Automatic` without `Cap::WindowPosition`.
8770    At(Point),
8771}
8772
8773/// A small runtime RGBA image for a status item: charts, meters, or a grid of results.
8774///
8775/// Rows run top to bottom; samples are tightly packed, non-premultiplied sRGB RGBA8.
8776/// `scale` is pixels per logical point (2 for Retina). This owns its bytes, independent of
8777/// any window or decoded-image registry. Currently rendered by AppKit; other backends use
8778/// [`StatusItemSpec::icon`] as a fallback. See docs/status-item.md.
8779#[derive(Clone, PartialEq)]
8780pub struct StatusImage {
8781    width: u32,
8782    height: u32,
8783    scale: f64,
8784    rgba: std::sync::Arc<[u8]>,
8785}
8786
8787impl StatusImage {
8788    /// Validate a runtime image. Rejects empty/mismatched pixels, invalid scales, and images
8789    /// exceeding 16 MiB or 4096 logical points on either axis. No platform allocation occurs.
8790    pub fn rgba(
8791        width: u32,
8792        height: u32,
8793        scale: f64,
8794        pixels: impl Into<std::sync::Arc<[u8]>>,
8795    ) -> Option<Self> {
8796        let rgba = pixels.into();
8797        let expected = (width as usize)
8798            .checked_mul(height as usize)?
8799            .checked_mul(4)?;
8800        if width == 0
8801            || height == 0
8802            || expected > 16 * 1024 * 1024
8803            || rgba.len() != expected
8804            || !scale.is_finite()
8805            || scale <= 0.0
8806            || f64::from(width) / scale > 4096.0
8807            || f64::from(height) / scale > 4096.0
8808        {
8809            return None;
8810        }
8811        Some(Self {
8812            width,
8813            height,
8814            scale,
8815            rgba,
8816        })
8817    }
8818
8819    pub fn width(&self) -> u32 {
8820        self.width
8821    }
8822    pub fn height(&self) -> u32 {
8823        self.height
8824    }
8825    pub fn scale(&self) -> f64 {
8826        self.scale
8827    }
8828    pub fn pixels(&self) -> &[u8] {
8829        &self.rgba
8830    }
8831    pub fn size(&self) -> Size {
8832        Size::new(
8833            f64::from(self.width) / self.scale,
8834            f64::from(self.height) / self.scale,
8835        )
8836    }
8837}
8838
8839impl std::fmt::Debug for StatusImage {
8840    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
8841        f.debug_struct("StatusImage")
8842            .field("width", &self.width)
8843            .field("height", &self.height)
8844            .field("scale", &self.scale)
8845            .field("bytes", &self.rgba.len())
8846            .finish()
8847    }
8848}
8849
8850#[cfg(test)]
8851mod status_image_tests {
8852    use super::*;
8853
8854    #[test]
8855    fn validates_pixel_layout_and_logical_size() {
8856        let image = StatusImage::rgba(120, 36, 2.0, vec![255; 120 * 36 * 4]).unwrap();
8857        assert_eq!(image.size(), Size::new(60.0, 18.0));
8858        assert_eq!(image.clone(), image);
8859        assert!(StatusImage::rgba(0, 1, 1.0, vec![]).is_none());
8860        assert!(StatusImage::rgba(1, 1, 1.0, vec![0; 3]).is_none());
8861        assert!(StatusImage::rgba(u32::MAX, u32::MAX, 1.0, vec![]).is_none());
8862        for scale in [0.0, -1.0, f64::NAN, f64::INFINITY, 0.00001] {
8863            assert!(StatusImage::rgba(1, 1, scale, vec![0; 4]).is_none());
8864        }
8865    }
8866}
8867
8868/// One status item: an icon in the menu bar (macOS), the notification area (Windows) or a
8869/// StatusNotifierItem host's tray (Linux), with a menu (docs/status-item.md).
8870#[derive(Clone, Debug, PartialEq)]
8871pub struct StatusItemSpec {
8872    /// The app's name for the item, stable across updates: what a backend diffs by.
8873    pub id: String,
8874    /// The glyph. `None` shows the title alone (macOS) or the app's icon (elsewhere).
8875    pub icon: Option<Icon>,
8876    /// A runtime image. AppKit prefers this over `icon`, preserving aspect ratio and point
8877    /// size up to 18pt high; other backends ignore it and show `icon`/`title` as before.
8878    pub raster: Option<StatusImage>,
8879    /// Draw the icon as a template: its shape only, in the menu bar's or panel's own color, so
8880    /// it reads in light and dark. Symbols are always templates.
8881    pub template: bool,
8882    /// Text beside the icon where the platform shows one (the macOS menu bar). Empty: icon only.
8883    pub title: String,
8884    /// The hover text.
8885    pub tooltip: String,
8886    /// The menu the item opens. Same model and dispatch as the app menu.
8887    pub menu: Vec<MenuItem>,
8888    /// A dispatch id (the [`Event::MenuAction`] registry) run when the user clicks the item
8889    /// itself, where the platform separates a click from opening the menu (a left click on macOS
8890    /// and Windows, the host's "activate" on Linux). 0: a click opens the menu.
8891    pub activate: u64,
8892}
8893
8894/// One display (docs/windows.md "Monitors"), in points on the desktop's coordinate space:
8895/// top-left origin at the primary display's top-left corner.
8896#[derive(Clone, Debug, PartialEq)]
8897pub struct Monitor {
8898    /// Stable for the display across launches where the platform offers it (a display UUID, a
8899    /// connector name); an index otherwise.
8900    pub id: String,
8901    /// The display's name, for a picker ("Built-in Retina Display", "DELL U2720Q").
8902    pub name: String,
8903    /// The display's whole area.
8904    pub frame: Rect,
8905    /// The part windows should use: the frame minus the menu bar, Dock, taskbar or panels.
8906    pub work_area: Rect,
8907    /// Device pixels per point.
8908    pub scale: f64,
8909    /// The display the desktop's menu bar or primary taskbar is on.
8910    pub primary: bool,
8911}
8912
8913/// A launcher shortcut the app sets while it runs (docs/deep-links.md "Launcher shortcuts"): a
8914/// route to open and the label the launcher shows, already localized.
8915#[derive(Clone, Debug, PartialEq, Eq)]
8916pub struct LauncherShortcut {
8917    /// The route the shortcut opens, through the deep-link intake.
8918    pub route: String,
8919    /// What the launcher shows.
8920    pub label: String,
8921}
8922
8923/// A progress indicator on the app's Dock or taskbar icon ([`Toolkit::set_app_progress`],
8924/// docs/status-item.md).
8925#[derive(Clone, Copy, Debug, Default, PartialEq)]
8926pub enum AppProgress {
8927    /// No indicator.
8928    #[default]
8929    None,
8930    /// Work of unknown length.
8931    Indeterminate,
8932    /// A fraction done, 0.0 to 1.0.
8933    Value(f64),
8934    /// A fraction done, paused. Platforms without a paused state show `Value`.
8935    Paused(f64),
8936    /// A fraction done when the work failed. Platforms without an error state show `Value`.
8937    Error(f64),
8938}
8939
8940/// Whether and how a window joins macOS window tabs ([`WindowOptions::tabbing`],
8941/// `Cap::WindowTabbing`). Other platforms have no system window tabs and ignore it.
8942#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
8943pub enum WindowTabbing {
8944    /// The platform default for the window's kind: an ordinary window tabs with the app's other
8945    /// ordinary windows when the user's "Prefer tabs" setting says so; preferences never tab.
8946    #[default]
8947    Automatic,
8948    /// Tab only with windows of the same group, following the user's setting. The tab bar's
8949    /// "+" opens the builder registered for this group (`register_new_window_for`).
8950    Group(String),
8951    /// Always open as a tab of an existing window of the same group, whatever the setting.
8952    Preferred(String),
8953    /// Never become a tab.
8954    Disallowed,
8955}
8956
8957/// An app's generated locale catalog: `(DEFAULT, CATALOG)`, exactly what `day-build` emits as
8958/// `res::locales::{DEFAULT, CATALOG}` (§18.5). Carried in [`WindowOptions::locales`] so the
8959/// framework can install it at the one moment that is correct.
8960pub type AppLocales = (&'static str, &'static [(&'static str, &'static str)]);
8961
8962#[derive(Clone, Debug)]
8963pub struct WindowOptions {
8964    pub title: String,
8965    pub size: Size,
8966    pub min_size: Option<Size>,
8967    /// Create and mount the window without showing it or activating the app. Supported on
8968    /// AppKit; other backends currently ignore this option. Defaults to false.
8969    ///
8970    /// Menu-bar apps can keep their initial host hidden and open Preferences on demand.
8971    /// The window still exists and can be shown with `WindowHandle::set_visible(true)`;
8972    /// this does not change the app's keep-running policy.
8973    pub start_hidden: bool,
8974    /// Ask the backend to size this window to its content once it has been built and laid out,
8975    /// rather than keeping [`Self::size`] (docs/windows.md). `size` still decides the width and
8976    /// acts as the height ceiling, so a panel with more content than fits the screen scrolls
8977    /// instead of growing past it.
8978    ///
8979    /// What a preferences panel wants on every desktop. Ignored by backends that cannot resize a
8980    /// live window, and by the ones with no windows at all.
8981    pub size_to_fit: bool,
8982    /// The app's display name for the standard application menu / About (macOS). `None` falls back
8983    /// to `title`; set it when `title` carries extra decoration you don't want in `About <name>`
8984    /// (e.g. the showcase's window title is "Day Showcase (AppKit)" but its app name is "Showcase").
8985    pub app_name: Option<String>,
8986    /// The app's locale catalog, installed by `day::launch` (docs/localization.md).
8987    ///
8988    /// The order is why this is the framework's job: the OS's languages reach day-localization from the
8989    /// live backend, and the catalog has to be registered after that hint and before the first
8990    /// localized string is read. An app that installs it itself (before `launch`, where there
8991    /// is no backend yet) registers against an empty hint list and resolves to `DEFAULT`, so a
8992    /// French device opens an English window.
8993    pub locales: Option<AppLocales>,
8994    /// The title, computed once the catalog above is installed: how a window title comes from
8995    /// the catalog rather than a literal. Takes precedence over [`Self::title`], which stays the
8996    /// fallback for the moment before (and for apps with nothing to translate).
8997    ///
8998    /// A plain `fn` rather than a closure: this struct is `Clone`, and the callers are a
8999    /// non-capturing `|| res::str::app_title().format()`, which coerces.
9000    pub title_fn: Option<fn() -> String>,
9001    /// The app's version, for Day's exit line (`Clean exit for <app> v<version> …`,
9002    /// docs/lifecycle.md): `env!("CARGO_PKG_VERSION")` in the app crate, which the scaffold's
9003    /// `window()` sets. `None` falls back to the `DAY_APP_VERSION` the `day` CLI sets on a launch.
9004    pub version: Option<String>,
9005    /// macOS window tabbing for this window (`Cap::WindowTabbing`); ignored elsewhere.
9006    pub tabbing: WindowTabbing,
9007    /// The window's frame: standard, a title bar the content runs under, or none
9008    /// (docs/window-chrome.md). Desktop only; phones and the web ignore it.
9009    pub chrome: WindowChrome,
9010    /// What shows behind the content: the window background, nothing, or a system material.
9011    pub background: WindowBackground,
9012    /// Whether the window casts the platform's drop shadow. A transparent, shaped window often
9013    /// wants none.
9014    pub shadow: bool,
9015    /// Whether the user can resize the window by its edges.
9016    pub resizable: bool,
9017    /// Where the window opens.
9018    pub placement: WindowPlacement,
9019    /// The largest content size the user can resize the window to (`Cap::WindowGeometry`).
9020    pub max_size: Option<Size>,
9021    /// Remember this window's size, position and maximized state under this key, and reopen it
9022    /// that way next launch (docs/windows.md "Remembered frames"). A position that no attached
9023    /// display shows any more is dropped, so a window never reopens off-screen.
9024    pub remember_frame: Option<String>,
9025    /// The logical window this opens (docs/windows.md): `open_window` focuses an already-open
9026    /// window with the same key instead of opening a second (the preferences pattern). `None`
9027    /// always opens a new one.
9028    pub key: Option<String>,
9029    /// The kind of window: a regular one, a preferences panel, an About panel.
9030    pub kind: WindowKind,
9031}
9032
9033impl WindowOptions {
9034    /// The window title. Replaces a [`title_fn`](Self::title_fn) set earlier (the generated
9035    /// `res::window_options()` sets one), so the last title named wins.
9036    pub fn title(mut self, title: impl Into<String>) -> Self {
9037        self.title = title.into();
9038        self.title_fn = None;
9039        self
9040    }
9041    /// The content size the window opens at (desktop; phones fill the screen).
9042    pub fn size(mut self, width: f64, height: f64) -> Self {
9043        self.size = Size::new(width, height);
9044        self
9045    }
9046    /// The smallest content size the user can resize to.
9047    pub fn min_size(mut self, width: f64, height: f64) -> Self {
9048        self.min_size = Some(Size::new(width, height));
9049        self
9050    }
9051    /// The largest content size the user can resize to (`Cap::WindowGeometry`).
9052    pub fn max_size(mut self, width: f64, height: f64) -> Self {
9053        self.max_size = Some(Size::new(width, height));
9054        self
9055    }
9056    /// Create and mount the window without showing it; see [`Self::start_hidden`].
9057    pub fn start_hidden(mut self) -> Self {
9058        self.start_hidden = true;
9059        self
9060    }
9061    /// Size the window to its content once built; see [`Self::size_to_fit`].
9062    pub fn size_to_fit(mut self) -> Self {
9063        self.size_to_fit = true;
9064        self
9065    }
9066    /// The app's display name for the application menu and About; see [`Self::app_name`].
9067    pub fn app_name(mut self, name: impl Into<String>) -> Self {
9068        self.app_name = Some(name.into());
9069        self
9070    }
9071    /// The app's locale catalog, as `res::locales::{DEFAULT, CATALOG}`; see [`Self::locales`].
9072    pub fn locales(
9073        mut self,
9074        default: &'static str,
9075        catalog: &'static [(&'static str, &'static str)],
9076    ) -> Self {
9077        self.locales = Some((default, catalog));
9078        self
9079    }
9080    /// The title, computed once the catalog is installed; see [`Self::title_fn`].
9081    pub fn title_fn(mut self, f: fn() -> String) -> Self {
9082        self.title_fn = Some(f);
9083        self
9084    }
9085    /// The app's version, for Day's exit line; see [`Self::version`].
9086    pub fn version(mut self, version: impl Into<String>) -> Self {
9087        self.version = Some(version.into());
9088        self
9089    }
9090    /// macOS window tabbing for this window; see [`Self::tabbing`].
9091    pub fn tabbing(mut self, tabbing: WindowTabbing) -> Self {
9092        self.tabbing = tabbing;
9093        self
9094    }
9095    /// The window's frame; see [`Self::chrome`].
9096    pub fn chrome(mut self, chrome: WindowChrome) -> Self {
9097        self.chrome = chrome;
9098        self
9099    }
9100    /// What shows behind the content; see [`Self::background`].
9101    pub fn background(mut self, background: WindowBackground) -> Self {
9102        self.background = background;
9103        self
9104    }
9105    /// No drop shadow, for a transparent or shaped window; see [`Self::shadow`].
9106    pub fn no_shadow(mut self) -> Self {
9107        self.shadow = false;
9108        self
9109    }
9110    /// A window the user cannot resize; see [`Self::resizable`].
9111    pub fn fixed_size(mut self) -> Self {
9112        self.resizable = false;
9113        self
9114    }
9115    /// Where the window opens; see [`Self::placement`].
9116    pub fn placement(mut self, placement: WindowPlacement) -> Self {
9117        self.placement = placement;
9118        self
9119    }
9120    /// Remember and restore this window's frame under `key`; see [`Self::remember_frame`].
9121    pub fn remember_frame(mut self, key: impl Into<String>) -> Self {
9122        self.remember_frame = Some(key.into());
9123        self
9124    }
9125    /// The logical window this opens; see [`Self::key`].
9126    pub fn key(mut self, key: impl Into<String>) -> Self {
9127        self.key = Some(key.into());
9128        self
9129    }
9130    /// The kind of window; see [`Self::kind`].
9131    pub fn kind(mut self, kind: WindowKind) -> Self {
9132        self.kind = kind;
9133        self
9134    }
9135}
9136
9137impl Default for WindowOptions {
9138    fn default() -> Self {
9139        WindowOptions {
9140            title: "Day".into(),
9141            size: Size::new(480.0, 640.0),
9142            min_size: None,
9143            start_hidden: false,
9144            size_to_fit: false,
9145            app_name: None,
9146            locales: None,
9147            title_fn: None,
9148            version: None,
9149            tabbing: WindowTabbing::Automatic,
9150            chrome: WindowChrome::Standard,
9151            background: WindowBackground::Opaque,
9152            shadow: true,
9153            resizable: true,
9154            placement: WindowPlacement::Automatic,
9155            max_size: None,
9156            remember_frame: None,
9157            key: None,
9158            kind: WindowKind::Normal,
9159        }
9160    }
9161}
9162
9163/// A platform backend: owns the native main loop and exactly one window in v1 (§8.1).
9164///
9165/// `run` sets up the native app + window, installs the reactive scheduler + main poster,
9166/// then hands `(self, root_container, content_size)` to `ready` (which mounts the tree and
9167/// takes ownership of the backend), and finally runs the native main loop.
9168pub trait Platform: Toolkit {
9169    /// The process-constant target id, e.g. `"macos-appkit"`.
9170    const TARGET: &'static str;
9171    /// The toolkit half of the target, e.g. `"appkit"`.
9172    const TOOLKIT: &'static str;
9173    /// Whether [`Platform::run`] returning means the app is over. True for a backend that
9174    /// drives the native loop itself until the app quits (GTK, Qt, XAML; AppKit's never
9175    /// returns). False where the host owns the loop and `run` hands back at once, with the
9176    /// app still to come (ArkUI's ability, Android's activity, the web page, the mock's test):
9177    /// their `DidExit` is the host's last callback, not the return (docs/lifecycle.md).
9178    const RUN_ENDS_APP: bool = true;
9179
9180    fn run(self, options: WindowOptions, ready: Box<dyn FnOnce(Self, Self::Handle, Size)>);
9181
9182    /// Post a closure onto the native main loop. Callable from any thread; this is the
9183    /// single door the reactive scheduler and `Setter` deliveries ride (§3.3).
9184    fn post(f: Box<dyn FnOnce() + Send>);
9185
9186    /// Post `f` onto the native main loop after (at least) `ms` milliseconds: the timer
9187    /// door behind `day::sleep` (docs/async.md). Every shipped backend overrides it with the
9188    /// loop's own timer (`dispatch_after`, `Handler.postDelayed`, `g_timeout_add`,
9189    /// `QTimer::singleShot`, `SetTimer`, `setTimeout`), so a sleep costs no thread. The
9190    /// default is the fallback for a backend without one: a helper thread that sleeps the
9191    /// whole delay and rides [`Platform::post`] home. It is correct, but a thread per sleep
9192    /// adds up under a ticking loop, so the first use says so once in the log.
9193    fn post_delayed(ms: u32, f: Box<dyn FnOnce() + Send>) {
9194        static SAID: std::sync::Once = std::sync::Once::new();
9195        SAID.call_once(|| {
9196            log::warn!(
9197                "day: {} has no native timer door; `day::sleep` falls back to a helper thread \
9198                 per delay (implement `Platform::post_delayed`)",
9199                Self::TARGET
9200            );
9201        });
9202        std::thread::spawn(move || {
9203            std::thread::sleep(std::time::Duration::from_millis(u64::from(ms)));
9204            Self::post(f);
9205        });
9206    }
9207
9208    /// Ordered OS locale preference list (BCP-47), for fluent-langneg (§12.2).
9209    fn locale_hints(&self) -> Vec<String> {
9210        Vec::new()
9211    }
9212}
9213
9214// ---------------------------------------------------------------------------
9215// Open renderer registry (§8.2)
9216// ---------------------------------------------------------------------------
9217
9218/// The scale a window snapshot is rendered at, when a scripted run states one
9219/// (`DAY_CAPTURE_SCALE=2`, set by `day launch --script` from Day.toml `[screenshots]`).
9220///
9221/// For the backends that render their own snapshot (GTK, Qt): the capture then measures
9222/// window points times this, whatever display the host has, which is what makes a CI capture
9223/// under a 1x xvfb the same 2560x1600 pixels a HiDPI laptop produces. A backend that reads the
9224/// compositor's pixels back (AppKit, XAML) captures at the display's own scale and ignores it.
9225/// `None` when unset or unparseable: capture at the backend's natural scale.
9226pub fn capture_scale() -> Option<f64> {
9227    std::env::var("DAY_CAPTURE_SCALE")
9228        .ok()
9229        .and_then(|v| v.trim().parse::<f64>().ok())
9230        .filter(|s| s.is_finite() && (0.5..=4.0).contains(s))
9231}
9232
9233/// Seconds on a monotonic clock since the first call: the frame timestamp for a backend that
9234/// does not expose a native timestamp (§8.4). The origin is arbitrary. Not for the web
9235/// build, where `Instant` is unavailable and `requestAnimationFrame` stamps the frame itself.
9236pub fn frame_timestamp() -> f64 {
9237    static ORIGIN: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new();
9238    ORIGIN
9239        .get_or_init(std::time::Instant::now)
9240        .elapsed()
9241        .as_secs_f64()
9242}
9243
9244/// The user's language preference from the POSIX environment, newest-first, as BCP-47 tags.
9245///
9246/// `LANGUAGE` is the GNU multi-language list (`fr:en`); `LC_ALL`, `LC_MESSAGES` and `LANG` each
9247/// carry one locale in POSIX form (`fr_FR.UTF-8`), which becomes `fr-FR`. Shared by the backends
9248/// whose platform has no richer API to ask (§12.2, docs/localization.md).
9249pub fn posix_locale_hints() -> Vec<String> {
9250    let mut out: Vec<String> = Vec::new();
9251    let mut push = |tag: &str| {
9252        // "C" and "POSIX" are the absence of a preference, not a language.
9253        let tag = tag.split('.').next().unwrap_or(tag).replace('_', "-");
9254        if tag.is_empty() || tag == "C" || tag == "POSIX" {
9255            return;
9256        }
9257        if !out.contains(&tag) {
9258            out.push(tag);
9259        }
9260    };
9261    if let Ok(list) = std::env::var("LANGUAGE") {
9262        for tag in list.split(':') {
9263            push(tag);
9264        }
9265    }
9266    for key in ["LC_ALL", "LC_MESSAGES", "LANG"] {
9267        if let Ok(v) = std::env::var(key) {
9268            push(&v);
9269        }
9270    }
9271    out
9272}
9273
9274/// Optional custom measure for a third-party piece (§8.2).
9275pub type MeasureFn<B> = fn(&mut B, &<B as Toolkit>::Handle, Proposal) -> Size;
9276
9277/// A third-party piece's per-toolkit implementation. `make` receives the concrete backend
9278/// (public helper surface) and returns a native handle the backend then owns like any built-in.
9279pub struct Renderer<B: Toolkit> {
9280    pub kind: PieceKind,
9281    pub make: fn(&mut B, &dyn Any, NodeId) -> B::Handle,
9282    pub update: fn(&mut B, &B::Handle, &dyn Any),
9283    pub measure: Option<MeasureFn<B>>,
9284    /// Teardown, run from the release queue just before [`Toolkit::release`] frees the handle.
9285    ///
9286    /// A piece that keeps per-view state (a retained delegate, a session map, a native
9287    /// observer) has no other place to drop it: `make`/`update` are the only other hooks, and a
9288    /// disposed node never calls them again. Without this a piece leaks one entry per realized
9289    /// view, and any map keyed by the handle's address can go on to answer for a later view that
9290    /// the allocator hands the same address.
9291    ///
9292    /// `None` for the pieces that own nothing (most of them).
9293    pub release: Option<fn(&mut B, &B::Handle)>,
9294}
9295
9296pub struct Registry<B: Toolkit> {
9297    map: HashMap<PieceKind, Renderer<B>>,
9298}
9299
9300impl<B: Toolkit> Default for Registry<B> {
9301    fn default() -> Self {
9302        Registry {
9303            map: HashMap::new(),
9304        }
9305    }
9306}
9307
9308impl<B: Toolkit> Registry<B> {
9309    pub fn register(&mut self, r: Renderer<B>) {
9310        let kind = r.kind;
9311        if self.map.insert(kind, r).is_some() {
9312            // Two pieces claiming one kind is last-linked-wins in link order, effectively
9313            // nondeterministic. Fail loudly in debug; in release, say so once at boot rather
9314            // than render the wrong widget silently.
9315            debug_assert!(
9316                false,
9317                "duplicate renderer registered for piece kind {kind:?}"
9318            );
9319            log::warn!("duplicate renderer for piece kind {kind:?} — later registration wins");
9320        }
9321    }
9322    pub fn get(&self, kind: PieceKind) -> Option<&Renderer<B>> {
9323        self.map.get(kind)
9324    }
9325    pub fn kinds(&self) -> impl Iterator<Item = PieceKind> + '_ {
9326        self.map.keys().copied()
9327    }
9328}
9329
9330/// The canvas wire op codes (§11, §15.3): slot 0 of every 9-number record in
9331/// [`encode_ops`]'s output. The numeric values are the frozen wire contract: the JNI, C++,
9332/// and JS decoders each hand-write these as constants, so a value here may never be reused
9333/// or renumbered; new ops append. `ALL` drives the density test that keeps this enum and
9334/// the encoder in step.
9335#[derive(Clone, Copy, Debug, PartialEq, Eq)]
9336#[repr(i32)]
9337pub enum OpCode {
9338    /// Fill a rect (a,b=origin, c,d=size).
9339    FillRect = 0,
9340    /// Stroke a rect (g=width).
9341    StrokeRect = 1,
9342    /// Fill a rounded rect (e=radius).
9343    FillRrect = 2,
9344    /// Fill an ellipse in a rect.
9345    FillEllipse = 3,
9346    /// Stroke an ellipse (g=width).
9347    StrokeEllipse = 4,
9348    /// Stroke an arc (e=start°, f=sweep°, g=width). `Fill(Shape::Arc)` also encodes as
9349    /// this with width 0, the known asymmetry; see [`encode_ops`].
9350    StrokeArc = 5,
9351    /// Line a,b → c,d (g=width).
9352    Line = 6,
9353    /// Text at a,b (e=size, f=anchor: 0 leading / 1 centered); the string rides the texts
9354    /// channel.
9355    Text = 7,
9356    /// Save the graphics state.
9357    Save = 8,
9358    /// Restore the graphics state.
9359    Restore = 9,
9360    /// Concat an affine transform (a..f).
9361    Concat = 10,
9362    /// Fill a polygon; points ride the texts channel as "x,y x,y …" (closed automatically),
9363    /// or the geometry channel of [`encode_ops_with_geometry`] (b = offset, c = count, and
9364    /// the texts entry is empty). `a` = the [`geometry_key`] of those points, or 0 for none.
9365    FillPolygon = 11,
9366    /// Stroke a polygon (g=width); points and key as [`OpCode::FillPolygon`].
9367    StrokePolygon = 12,
9368    /// Stroke a rounded rect (e=radius, g=width).
9369    StrokeRrect = 13,
9370    /// Set a gradient for the next shape record (f=type: 0 linear with a,b=start / c,d=end
9371    /// unit points; 1 radial with a,b=center unit point, c=unit radius; e=stop count).
9372    /// Stops ride the texts channel as "offset,aarrggbb offset,aarrggbb …". Unit geometry
9373    /// resolves against the shape's bounding box.
9374    SetGradient = 14,
9375    /// Fill a path (f=fill rule: 0 non-zero / 1 even-odd); segments ride the texts channel
9376    /// (see [`encode_path`]), or the geometry channel of [`encode_ops_with_geometry`]
9377    /// (b = offset, c = count, see [`path_numbers`]; the texts entry is empty). `a` = the
9378    /// [`geometry_key`] of those segments, or 0 for none.
9379    ///
9380    /// The key is a cache handle, not a payload: a decoder that recognizes it may keep the
9381    /// native geometry it built last time and skip re-parsing the segments, but it must still
9382    /// consume the texts entry either way, because that channel is positional and a skipped
9383    /// entry desynchronizes every record after it.
9384    FillPath = 15,
9385    /// Stroke a path (g=width); segments and key as [`OpCode::FillPath`].
9386    StrokePath = 16,
9387    /// Clip to a shape (f=shape kind: 0 rect / 1 rrect(e=radius) / 2 ellipse / 3 path
9388    /// (e=fill rule) / 4 polygon; a..d=geometry; path/polygon payloads ride the texts
9389    /// channel).
9390    ///
9391    /// For the two payload-bearing kinds (3 and 4) there is no geometry in the slots, so `a`
9392    /// carries the [`geometry_key`] instead, b and c the geometry channel's offset and count
9393    /// when there is one, and d stays 0. The other three kinds put real geometry in a..d and
9394    /// have nothing to cache.
9395    Clip = 17,
9396    /// Stroke style for the next stroke record (a=cap, b=join, c=miter limit, d=dash
9397    /// phase, e=dash count; the dash array rides the texts channel).
9398    StrokeStyle = 18,
9399    /// Font for the next text record (a=CSS weight 100 … 900, 0 = default; b=italic 0/1); the
9400    /// family name rides the texts channel, `""` = the platform's default face. Like
9401    /// [`OpCode::SetGradient`] and [`OpCode::StrokeStyle`] it is consumed by the record that
9402    /// follows and then cleared; a default [`CanvasFont`] emits no record at all, so a drawing
9403    /// without fonts encodes exactly as it did before this op existed.
9404    SetFont = 19,
9405    /// The next shape record is a template, drawn once per stamped position rather than once
9406    /// (docs/canvas.md "Stamping"). `a` = how many positions follow. Like [`OpCode::SetGradient`],
9407    /// [`OpCode::StrokeStyle`] and [`OpCode::SetFont`] it is a prefix, consumed by the record it
9408    /// applies to and then cleared.
9409    ///
9410    /// Between this and that template record come `ceil(a / 4)` [`OpCode::StampPoints`] records
9411    /// carrying the coordinates. A drawing with no stamps encodes exactly as it did before.
9412    Stamp = 20,
9413    /// Four stamped positions, filling the record edge to edge: `[op, x0, y0, x1, y1, x2, y2,
9414    /// x3, y3]`, the one record that uses its last slot for geometry instead of a color, because
9415    /// it carries no color of its own. The final record of a run is padded; the count in the
9416    /// [`OpCode::Stamp`] header says how many of the pairs are real.
9417    StampPoints = 21,
9418    /// Draw a decoded image: `a,b` = origin, `c,d` = size, `e` = the [`BitmapId`], `f` = opacity
9419    /// in `0.0..=1.0` (docs/images.md).
9420    ///
9421    /// The id rides the numeric channel because it is a number, and an `f64` carries a `u64` id
9422    /// exactly up to 2^53; ids are minted from 1 per process, so that ceiling is unreachable.
9423    /// Nothing rides the texts channel for this op.
9424    Image = 22,
9425    /// The source region for the next image record (`a,b` = origin, `c,d` = size, in the
9426    /// bitmap's own pixels): [`DrawOp::Image`]'s `source`. Like [`OpCode::SetFont`] it is a
9427    /// prefix, consumed by the record that follows and then cleared, and a whole-image draw
9428    /// emits none, so a drawing without regions encodes exactly as it did before this op
9429    /// existed. A decoder clamps the region to the bitmap and draws nothing for an empty
9430    /// intersection ([`clamp_image_source`]).
9431    ImageSource = 23,
9432}
9433
9434impl OpCode {
9435    /// Every code, in wire order. The density test iterates this so a new variant that
9436    /// forgets to join fails loudly.
9437    pub const ALL: [OpCode; 24] = [
9438        OpCode::FillRect,
9439        OpCode::StrokeRect,
9440        OpCode::FillRrect,
9441        OpCode::FillEllipse,
9442        OpCode::StrokeEllipse,
9443        OpCode::StrokeArc,
9444        OpCode::Line,
9445        OpCode::Text,
9446        OpCode::Save,
9447        OpCode::Restore,
9448        OpCode::Concat,
9449        OpCode::FillPolygon,
9450        OpCode::StrokePolygon,
9451        OpCode::StrokeRrect,
9452        OpCode::SetGradient,
9453        OpCode::FillPath,
9454        OpCode::StrokePath,
9455        OpCode::Clip,
9456        OpCode::StrokeStyle,
9457        OpCode::SetFont,
9458        OpCode::Stamp,
9459        OpCode::StampPoints,
9460        OpCode::Image,
9461        OpCode::ImageSource,
9462    ];
9463
9464    /// The code back from a wire number (a decoder-side aid and the round-trip test's
9465    /// reference); `None` for anything outside the table.
9466    pub fn from_wire(n: f64) -> Option<OpCode> {
9467        OpCode::ALL.into_iter().find(|c| *c as i32 as f64 == n)
9468    }
9469}
9470
9471/// Flat numeric encoding of a display list for shim/JNI boundaries (§11, §15.3): per op
9472/// 9 numbers [kind, a, b, c, d, e, f, g, rgba-bits]; text payloads ride separately in order.
9473/// The kind slot carries an [`OpCode`]; its doc comments are the per-slot contract.
9474///
9475/// Transports join `texts` with the unit separator U+001F (one entry per text-carrying
9476/// record, in order), so text payloads must not contain U+001F. Known asymmetry:
9477/// `Fill(Shape::Arc)` encodes as [`OpCode::StrokeArc`] with width 0. Filled arcs render
9478/// only on the direct-replay backends (AppKit/UIKit); use a polygon fan if a filled arc
9479/// must be portable.
9480/// Serialize a path for the `texts` side-channel: one space-separated token per segment,
9481/// `M x y` / `L x y` / `Q cx cy x y` / `C c1x c1y c2x c2y x y` / `Z`.
9482///
9483/// Text rather than numbers because that is the channel the encoder already has for
9484/// variable-length payloads, and every decoder (JS, Java, C++) can already split a string. The
9485/// numeric channel is a flat `[f64; 9]`-per-record array with no length prefix, so a path could
9486/// not ride it without changing the record shape for every backend at once.
9487/// A content key for a shape's variable-length geometry: the handle a backend caches decoded
9488/// native geometry under (a `Path2D`, a `QPainterPath`, an `android.graphics.Path`) so an
9489/// unchanged path is rebuilt once instead of re-parsed out of the texts channel every frame.
9490///
9491/// It hashes the geometry, not the op's position or its identity, so that a draw closure that
9492/// rebuilds its `PathBuilder` chain from scratch on every frame (which is what canvas consumers
9493/// do) produces an equal path, hashes the same and hits the same entry. An identity would miss
9494/// every time.
9495///
9496/// Two different paths that collided would draw each other, so the width matters: FNV-1a over the
9497/// IEEE bits, masked to the 53 bits an `f64` wire slot carries exactly. `0.0` is reserved for "no
9498/// key": a decoder seeing it must decode the payload as it always did, which is also what every
9499/// decoder written before this key existed does with the slot.
9500pub fn geometry_key(shape: &Shape) -> f64 {
9501    fn mix(h: &mut u64, v: f64) {
9502        for byte in v.to_bits().to_le_bytes() {
9503            *h ^= u64::from(byte);
9504            *h = h.wrapping_mul(0x0000_0100_0000_01b3);
9505        }
9506    }
9507    fn mix_point(h: &mut u64, p: Point) {
9508        mix(h, p.x);
9509        mix(h, p.y);
9510    }
9511    let mut h: u64 = 0xcbf2_9ce4_8422_2325;
9512    match shape {
9513        Shape::Polygon(pts) => {
9514            // The discriminant joins the hash so a polygon and a path of the same points can
9515            // never share an entry: they decode to different geometry.
9516            mix(&mut h, 11.0);
9517            for p in pts {
9518                mix_point(&mut h, *p);
9519            }
9520        }
9521        Shape::Path(path) => {
9522            mix(&mut h, 15.0);
9523            mix(&mut h, rule_bits(path.rule));
9524            for seg in &path.segs {
9525                match seg {
9526                    PathSeg::Move(a) => {
9527                        mix(&mut h, 0.0);
9528                        mix_point(&mut h, *a);
9529                    }
9530                    PathSeg::Line(a) => {
9531                        mix(&mut h, 1.0);
9532                        mix_point(&mut h, *a);
9533                    }
9534                    PathSeg::Quad(c, a) => {
9535                        mix(&mut h, 2.0);
9536                        mix_point(&mut h, *c);
9537                        mix_point(&mut h, *a);
9538                    }
9539                    PathSeg::Cubic(c1, c2, a) => {
9540                        mix(&mut h, 3.0);
9541                        mix_point(&mut h, *c1);
9542                        mix_point(&mut h, *c2);
9543                        mix_point(&mut h, *a);
9544                    }
9545                    PathSeg::Close => mix(&mut h, 4.0),
9546                }
9547            }
9548        }
9549        // Everything else puts its whole geometry in the record's own slots, so there is nothing
9550        // to parse and nothing worth caching.
9551        _ => return 0.0,
9552    }
9553    let masked = h & ((1u64 << 53) - 1);
9554    // 0 means "no key", so the one hash that lands there borrows its neighbor.
9555    if masked == 0 { 1.0 } else { masked as f64 }
9556}
9557
9558/// Append a coordinate to the texts channel: a plain decimal with up to six fractional digits
9559/// and no trailing zeros (`12`, `-0.5`, `183.472938`), never an exponent.
9560///
9561/// Six decimals of a canvas point is a millionth of a point, far below anything a transform an
9562/// app would draw under can bring to a pixel, and the fixed form costs a tenth of the shortest
9563/// round-trip repr: one integer write instead of a float formatter and a temporary `String` per
9564/// coordinate, which was the larger half of a map tile's export on Android. The decoders parse
9565/// with their platform's general float reader, so a value the fixed form cannot carry (a
9566/// non-finite number, a magnitude past 2^53 millionths) falls back to `Display`.
9567fn push_wire_num(out: &mut String, v: f64) {
9568    use std::fmt::Write as _;
9569    const SCALE: f64 = 1_000_000.0;
9570    let scaled = (v * SCALE).round();
9571    if scaled.is_nan() || scaled.abs() >= 9.0e15 {
9572        let _ = write!(out, "{v}");
9573        return;
9574    }
9575    let mut n = scaled as i64;
9576    if n < 0 {
9577        out.push('-');
9578        n = -n;
9579    }
9580    let whole = n / 1_000_000;
9581    let mut frac = n % 1_000_000;
9582    let _ = write!(out, "{whole}");
9583    if frac != 0 {
9584        let mut digits = 6;
9585        while frac % 10 == 0 {
9586            frac /= 10;
9587            digits -= 1;
9588        }
9589        out.push('.');
9590        let _ = write!(out, "{frac:0digits$}");
9591    }
9592}
9593
9594/// Polygon points for the texts channel: `"x,y x,y …"`, numbers as [`push_wire_num`] writes
9595/// them.
9596fn encode_points(pts: &[Point]) -> String {
9597    let mut out = String::with_capacity(pts.len() * 16);
9598    for p in pts {
9599        if !out.is_empty() {
9600            out.push(' ');
9601        }
9602        push_wire_num(&mut out, p.x);
9603        out.push(',');
9604        push_wire_num(&mut out, p.y);
9605    }
9606    out
9607}
9608
9609/// Path segments for the texts channel: `"M x y L x y Q cx cy x y C … Z"`, one token per
9610/// command or number. Coordinates use up to six decimal places, without trailing zeros;
9611/// non-finite values and magnitudes outside the fixed-point range use their display form.
9612pub fn encode_path(path: &Path) -> String {
9613    let mut out = String::with_capacity(path.segs.len() * 16);
9614    let points = |out: &mut String, cmd: char, pts: &[Point]| {
9615        if !out.is_empty() {
9616            out.push(' ');
9617        }
9618        out.push(cmd);
9619        for p in pts {
9620            out.push(' ');
9621            push_wire_num(out, p.x);
9622            out.push(' ');
9623            push_wire_num(out, p.y);
9624        }
9625    };
9626    for seg in &path.segs {
9627        match seg {
9628            PathSeg::Move(p) => points(&mut out, 'M', &[*p]),
9629            PathSeg::Line(p) => points(&mut out, 'L', &[*p]),
9630            PathSeg::Quad(c, p) => points(&mut out, 'Q', &[*c, *p]),
9631            PathSeg::Cubic(a, b, p) => points(&mut out, 'C', &[*a, *b, *p]),
9632            PathSeg::Close => points(&mut out, 'Z', &[]),
9633        }
9634    }
9635    out
9636}
9637
9638/// Clamp a [`DrawOp::Image`] `source` region to the bitmap it indexes (`pixels` wide and high),
9639/// keeping the region's mapping into `rect`: the answer is the part of the region inside the
9640/// bitmap and the part of `rect` it lands in.
9641///
9642/// The single definition of what an out-of-range region means. The mapping is kept rather than
9643/// the clamped part stretched over the whole of `rect`, because that is what every native
9644/// sub-rect draw does on its own (Qt, the HTML canvas) and what the clip-and-scale fallback
9645/// gives for free, so the backends agree. `None` (an empty region, an empty intersection, or a
9646/// bitmap with no pixels) draws nothing. Every backend that replays in Rust calls this; the
9647/// C++/Java/JS decoders repeat the same arithmetic.
9648pub fn clamp_image_source(source: Rect, rect: Rect, pixels: Size) -> Option<(Rect, Rect)> {
9649    if !(source.size.width > 0.0 && source.size.height > 0.0) {
9650        return None;
9651    }
9652    let x0 = source.origin.x.max(0.0);
9653    let y0 = source.origin.y.max(0.0);
9654    let x1 = (source.origin.x + source.size.width).min(pixels.width);
9655    let y1 = (source.origin.y + source.size.height).min(pixels.height);
9656    if !(x1 > x0 && y1 > y0) {
9657        return None;
9658    }
9659    let kx = rect.size.width / source.size.width;
9660    let ky = rect.size.height / source.size.height;
9661    let dest = Rect::new(
9662        rect.origin.x + (x0 - source.origin.x) * kx,
9663        rect.origin.y + (y0 - source.origin.y) * ky,
9664        (x1 - x0) * kx,
9665        (y1 - y0) * ky,
9666    );
9667    Some((Rect::new(x0, y0, x1 - x0, y1 - y0), dest))
9668}
9669
9670/// `FillRule` as a wire number: 0 non-zero, 1 even-odd.
9671fn rule_bits(rule: FillRule) -> f64 {
9672    match rule {
9673        FillRule::NonZero => 0.0,
9674        FillRule::EvenOdd => 1.0,
9675    }
9676}
9677
9678/// Encode a display list for a decoder written in another language (Java, C++, JS): the
9679/// numbers channel, nine `f64` slots per record (`[kind, a, b, c, d, e, f, g, color]`, kinds
9680/// from [`OpCode`]), and the texts channel, one entry per record that carries text or
9681/// variable-length geometry, in record order.
9682pub fn encode_ops(ops: &[DrawOp]) -> (Vec<f64>, Vec<String>) {
9683    encode_ops_into(ops, None)
9684}
9685
9686/// [`encode_ops`] with a third, geometry channel: the points of every path and polygon (fills,
9687/// strokes, clips) as numbers instead of text. Such a record's slot `b` is its offset into the
9688/// channel and slot `c` its count, and its texts entry is empty, so that channel stays
9689/// positional for a decoder that ignores the third one. Paths are written by
9690/// [`path_numbers`], polygons by [`point_numbers`].
9691///
9692/// Formatting a coordinate and parsing it back were, together, half of what a map tile's export
9693/// cost on Android (docs/canvas.md "Exporting"); a decoder that can take an array of doubles
9694/// across its boundary skips both.
9695pub fn encode_ops_with_geometry(ops: &[DrawOp]) -> (Vec<f64>, Vec<String>, Vec<f64>) {
9696    let mut geometry = Vec::new();
9697    let (nums, texts) = encode_ops_into(ops, Some(&mut geometry));
9698    (nums, texts, geometry)
9699}
9700
9701/// A path's segments for the geometry channel: a command code, then its points — `0` move
9702/// (x y), `1` line (x y), `2` quad (cx cy x y), `3` cubic (x1 y1 x2 y2 x y), `4` close.
9703pub fn path_numbers(path: &Path, out: &mut Vec<f64>) {
9704    for seg in &path.segs {
9705        match seg {
9706            PathSeg::Move(p) => out.extend_from_slice(&[0.0, p.x, p.y]),
9707            PathSeg::Line(p) => out.extend_from_slice(&[1.0, p.x, p.y]),
9708            PathSeg::Quad(c, p) => out.extend_from_slice(&[2.0, c.x, c.y, p.x, p.y]),
9709            PathSeg::Cubic(a, b, p) => out.extend_from_slice(&[3.0, a.x, a.y, b.x, b.y, p.x, p.y]),
9710            PathSeg::Close => out.push(4.0),
9711        }
9712    }
9713}
9714
9715/// A polygon's points for the geometry channel: x then y, per point.
9716pub fn point_numbers(pts: &[Point], out: &mut Vec<f64>) {
9717    for p in pts {
9718        out.push(p.x);
9719        out.push(p.y);
9720    }
9721}
9722
9723/// Put a path's or polygon's points on the wire: on the geometry channel when the caller opened
9724/// one, as `numbers` writes them, answering (offset, count) for slots b and c and leaving an
9725/// empty texts entry; else as `text` on the texts channel, answering (0, 0).
9726fn geometry_payload(
9727    geometry: &mut Option<&mut Vec<f64>>,
9728    texts: &mut Vec<String>,
9729    text: impl FnOnce() -> String,
9730    numbers: impl FnOnce(&mut Vec<f64>),
9731) -> (f64, f64) {
9732    match geometry {
9733        Some(g) => {
9734            let offset = g.len();
9735            numbers(g);
9736            texts.push(String::new());
9737            (offset as f64, (g.len() - offset) as f64)
9738        }
9739        None => {
9740            texts.push(text());
9741            (0.0, 0.0)
9742        }
9743    }
9744}
9745
9746fn encode_ops_into(ops: &[DrawOp], mut geometry: Option<&mut Vec<f64>>) -> (Vec<f64>, Vec<String>) {
9747    fn color_bits(c: Color) -> f64 {
9748        let r = (c.r.clamp(0.0, 1.0) * 255.0) as u32;
9749        let g = (c.g.clamp(0.0, 1.0) * 255.0) as u32;
9750        let b = (c.b.clamp(0.0, 1.0) * 255.0) as u32;
9751        let a = (c.a.clamp(0.0, 1.0) * 255.0) as u32;
9752        ((a << 24) | (r << 16) | (g << 8) | b) as f64
9753    }
9754    #[allow(clippy::too_many_arguments)]
9755    fn push(
9756        k: OpCode,
9757        a: f64,
9758        b: f64,
9759        c: f64,
9760        d: f64,
9761        e: f64,
9762        f: f64,
9763        g: f64,
9764        col: Color,
9765        nums: &mut Vec<f64>,
9766    ) {
9767        nums.extend_from_slice(&[k as i32 as f64, a, b, c, d, e, f, g, color_bits(col)]);
9768    }
9769    /// The kind-18 prefix a non-plain stroke style emits, applying to the next stroke record,
9770    /// the same "modifier record" rule the gradient and font records follow. A plain style emits
9771    /// nothing, so a drawing without dashes or caps encodes exactly as it always did.
9772    fn stroke_style_record(style: &StrokeStyle, nums: &mut Vec<f64>, texts: &mut Vec<String>) {
9773        if style.is_plain() {
9774            return;
9775        }
9776        push(
9777            OpCode::StrokeStyle,
9778            match style.cap {
9779                LineCap::Butt => 0.0,
9780                LineCap::Round => 1.0,
9781                LineCap::Square => 2.0,
9782            },
9783            match style.join {
9784                LineJoin::Miter => 0.0,
9785                LineJoin::Round => 1.0,
9786                LineJoin::Bevel => 2.0,
9787            },
9788            style.miter_limit,
9789            style.dash_phase,
9790            style.dash.len() as f64,
9791            0.0,
9792            0.0,
9793            Color::CLEAR,
9794            nums,
9795        );
9796        texts.push(
9797            style
9798                .dash
9799                .iter()
9800                .map(|d| d.to_string())
9801                .collect::<Vec<_>>()
9802                .join(" "),
9803        );
9804    }
9805
9806    /// One shape record (the fill/stroke kinds shared by both ops).
9807    fn shape_record(
9808        stroke: bool,
9809        shape: &Shape,
9810        w: f64,
9811        col: Color,
9812        nums: &mut Vec<f64>,
9813        texts: &mut Vec<String>,
9814        geometry: &mut Option<&mut Vec<f64>>,
9815    ) {
9816        match shape {
9817            Shape::Rect(r) => push(
9818                if stroke {
9819                    OpCode::StrokeRect
9820                } else {
9821                    OpCode::FillRect
9822                },
9823                r.origin.x,
9824                r.origin.y,
9825                r.size.width,
9826                r.size.height,
9827                0.0,
9828                0.0,
9829                w,
9830                col,
9831                nums,
9832            ),
9833            Shape::RoundedRect(r, rad) => push(
9834                if stroke {
9835                    OpCode::StrokeRrect
9836                } else {
9837                    OpCode::FillRrect
9838                },
9839                r.origin.x,
9840                r.origin.y,
9841                r.size.width,
9842                r.size.height,
9843                *rad,
9844                0.0,
9845                w,
9846                col,
9847                nums,
9848            ),
9849            Shape::Ellipse(r) => push(
9850                if stroke {
9851                    OpCode::StrokeEllipse
9852                } else {
9853                    OpCode::FillEllipse
9854                },
9855                r.origin.x,
9856                r.origin.y,
9857                r.size.width,
9858                r.size.height,
9859                0.0,
9860                0.0,
9861                w,
9862                col,
9863                nums,
9864            ),
9865            Shape::Arc {
9866                rect,
9867                start_deg,
9868                sweep_deg,
9869            } => push(
9870                OpCode::StrokeArc,
9871                rect.origin.x,
9872                rect.origin.y,
9873                rect.size.width,
9874                rect.size.height,
9875                *start_deg,
9876                *sweep_deg,
9877                w,
9878                col,
9879                nums,
9880            ),
9881            Shape::Line(p1, p2) => {
9882                push(OpCode::Line, p1.x, p1.y, p2.x, p2.y, 0.0, 0.0, w, col, nums)
9883            }
9884            Shape::Polygon(pts) => {
9885                // Variable-length points ride the texts side-channel ("x,y x,y …"),
9886                // consumed in record order exactly like text payloads, or the geometry
9887                // channel when there is one (slots b, c).
9888                let (offset, count) = geometry_payload(
9889                    geometry,
9890                    texts,
9891                    || encode_points(pts),
9892                    |g| point_numbers(pts, g),
9893                );
9894                push(
9895                    if stroke {
9896                        OpCode::StrokePolygon
9897                    } else {
9898                        OpCode::FillPolygon
9899                    },
9900                    geometry_key(shape),
9901                    offset,
9902                    count,
9903                    0.0,
9904                    0.0,
9905                    0.0,
9906                    w,
9907                    col,
9908                    nums,
9909                );
9910            }
9911            Shape::Path(path) => {
9912                // Same side-channels as Polygon, one token per segment (see `encode_path`).
9913                // The fill rule rides slot f; stroking ignores it.
9914                let (offset, count) = geometry_payload(
9915                    geometry,
9916                    texts,
9917                    || encode_path(path),
9918                    |g| path_numbers(path, g),
9919                );
9920                push(
9921                    if stroke {
9922                        OpCode::StrokePath
9923                    } else {
9924                        OpCode::FillPath
9925                    },
9926                    geometry_key(shape),
9927                    offset,
9928                    count,
9929                    0.0,
9930                    0.0,
9931                    rule_bits(path.rule),
9932                    w,
9933                    col,
9934                    nums,
9935                );
9936            }
9937        }
9938    }
9939    /// A gradient applies to the next shape record, fill or stroke. Geometry per type rides
9940    /// slots a..d and the type discriminant slot f: one record shape, so every decoder keeps a
9941    /// single gradient code path.
9942    fn gradient_record(
9943        geo: [f64; 4],
9944        kind: f64,
9945        stops: &[(f64, Color)],
9946        nums: &mut Vec<f64>,
9947        texts: &mut Vec<String>,
9948    ) {
9949        push(
9950            OpCode::SetGradient,
9951            geo[0],
9952            geo[1],
9953            geo[2],
9954            geo[3],
9955            stops.len() as f64,
9956            kind,
9957            0.0,
9958            Color::CLEAR,
9959            nums,
9960        );
9961        texts.push(
9962            stops
9963                .iter()
9964                .map(|(o, c)| format!("{o},{:08x}", color_bits(*c) as u32))
9965                .collect::<Vec<_>>()
9966                .join(" "),
9967        );
9968    }
9969    let mut nums = Vec::with_capacity(ops.len() * 9);
9970    let mut texts = Vec::new();
9971    for op in ops {
9972        match op {
9973            DrawOp::Fill(shape, paint) => {
9974                // A gradient emits one kind-14 set-gradient record before its shape record;
9975                // the stops ride the texts channel as "offset,aarrggbb offset,aarrggbb …".
9976                // Geometry per type rides slots a..d, the type discriminant slot f: one
9977                // record shape, so every decoder keeps a single gradient code path.
9978                let col = match paint {
9979                    Paint::Solid(c) => *c,
9980                    Paint::Linear(g) => {
9981                        gradient_record(
9982                            [g.start.x, g.start.y, g.end.x, g.end.y],
9983                            0.0,
9984                            &g.stops,
9985                            &mut nums,
9986                            &mut texts,
9987                        );
9988                        // The gradient replaces the shape record's color, but it must be
9989                        // opaque, not clear: Skia-based decoders (Android Paint, OH_Drawing)
9990                        // modulate a shader by the paint alpha, so a clear slot would render
9991                        // the whole gradient invisible.
9992                        Color::WHITE
9993                    }
9994                    Paint::Radial(g) => {
9995                        gradient_record(
9996                            [g.center.x, g.center.y, g.radius, 0.0],
9997                            1.0,
9998                            &g.stops,
9999                            &mut nums,
10000                            &mut texts,
10001                        );
10002                        Color::WHITE
10003                    }
10004                };
10005                shape_record(false, shape, 0.0, col, &mut nums, &mut texts, &mut geometry);
10006            }
10007            DrawOp::Stamp(st) => {
10008                // No copies means no drawing. Some native decoders use an empty point
10009                // buffer to mean an ordinary (unstamped) template, so omit the entire op.
10010                if st.at.is_empty() {
10011                    continue;
10012                }
10013                // A prefix record, then the coordinates, then the template shape record: the
10014                // "applies to the next record" rule the gradient, stroke style and font records
10015                // already follow, so a decoder needs no new kind of state, only one more slot in
10016                // the state it keeps. The template goes last because a decoder has to hold the
10017                // points before it can draw with them.
10018                //
10019                // The points are numbers on the numeric channel, not the texts channel a
10020                // polygon's points ride: this op exists for tens of thousands of them, and
10021                // formatting that many floats into a string every frame would cost more than
10022                // the individual ops it replaces.
10023                let col = match &st.paint {
10024                    Paint::Solid(c) => *c,
10025                    Paint::Linear(g) => {
10026                        gradient_record(
10027                            [g.start.x, g.start.y, g.end.x, g.end.y],
10028                            0.0,
10029                            &g.stops,
10030                            &mut nums,
10031                            &mut texts,
10032                        );
10033                        Color::WHITE
10034                    }
10035                    Paint::Radial(g) => {
10036                        gradient_record(
10037                            [g.center.x, g.center.y, g.radius, 0.0],
10038                            1.0,
10039                            &g.stops,
10040                            &mut nums,
10041                            &mut texts,
10042                        );
10043                        Color::WHITE
10044                    }
10045                };
10046                push(
10047                    OpCode::Stamp,
10048                    st.at.len() as f64,
10049                    0.0,
10050                    0.0,
10051                    0.0,
10052                    0.0,
10053                    0.0,
10054                    0.0,
10055                    Color::CLEAR,
10056                    &mut nums,
10057                );
10058                for chunk in st.at.chunks(4) {
10059                    // Written directly rather than through `push`: this is the one record whose
10060                    // last slot is a coordinate rather than a color, which is what lets four
10061                    // points fit with nothing wasted.
10062                    let mut rec = [
10063                        OpCode::StampPoints as i32 as f64,
10064                        0.0,
10065                        0.0,
10066                        0.0,
10067                        0.0,
10068                        0.0,
10069                        0.0,
10070                        0.0,
10071                        0.0,
10072                    ];
10073                    for (i, p) in chunk.iter().enumerate() {
10074                        rec[1 + i * 2] = p.x;
10075                        rec[2 + i * 2] = p.y;
10076                    }
10077                    nums.extend_from_slice(&rec);
10078                }
10079                match &st.stroke {
10080                    None => shape_record(
10081                        false,
10082                        &st.shape,
10083                        0.0,
10084                        col,
10085                        &mut nums,
10086                        &mut texts,
10087                        &mut geometry,
10088                    ),
10089                    Some(style) => {
10090                        stroke_style_record(style, &mut nums, &mut texts);
10091                        shape_record(
10092                            true,
10093                            &st.shape,
10094                            style.width,
10095                            col,
10096                            &mut nums,
10097                            &mut texts,
10098                            &mut geometry,
10099                        );
10100                    }
10101                }
10102            }
10103            DrawOp::Stroke(shape, paint, style) => {
10104                // A styled stroke emits one kind-18 record first, applying to the next stroke
10105                // only, the same "modifier record" shape the gradient uses, so decoders keep
10106                // one rule: consume, apply to the next shape record, reset.
10107                stroke_style_record(style, &mut nums, &mut texts);
10108                let col = match paint {
10109                    Paint::Solid(c) => *c,
10110                    Paint::Linear(g) => {
10111                        gradient_record(
10112                            [g.start.x, g.start.y, g.end.x, g.end.y],
10113                            0.0,
10114                            &g.stops,
10115                            &mut nums,
10116                            &mut texts,
10117                        );
10118                        Color::WHITE
10119                    }
10120                    Paint::Radial(g) => {
10121                        gradient_record(
10122                            [g.center.x, g.center.y, g.radius, 0.0],
10123                            1.0,
10124                            &g.stops,
10125                            &mut nums,
10126                            &mut texts,
10127                        );
10128                        Color::WHITE
10129                    }
10130                };
10131                shape_record(
10132                    true,
10133                    shape,
10134                    style.width,
10135                    col,
10136                    &mut nums,
10137                    &mut texts,
10138                    &mut geometry,
10139                );
10140            }
10141            DrawOp::Clip(shape) => {
10142                // One record for every clip shape, with the shape kind in slot f and the
10143                // geometry in a..e; a path or polygon puts its points on the texts channel.
10144                // Encoding clips as a variant of `shape_record` instead would need a third
10145                // kind code per shape, which is five more numbers every decoder must learn.
10146                let (kind, geo, extra, payload): (f64, [f64; 4], f64, Option<String>) = match shape
10147                {
10148                    Shape::Rect(r) => (
10149                        0.0,
10150                        [r.origin.x, r.origin.y, r.size.width, r.size.height],
10151                        0.0,
10152                        None,
10153                    ),
10154                    Shape::RoundedRect(r, rad) => (
10155                        1.0,
10156                        [r.origin.x, r.origin.y, r.size.width, r.size.height],
10157                        *rad,
10158                        None,
10159                    ),
10160                    Shape::Ellipse(r) => (
10161                        2.0,
10162                        [r.origin.x, r.origin.y, r.size.width, r.size.height],
10163                        0.0,
10164                        None,
10165                    ),
10166                    // Slot a carries the geometry key for these two sub-kinds only. The other
10167                    // three put real geometry there, which is why the key rides the same slot
10168                    // the payload-bearing kinds leave empty; b and c are the geometry
10169                    // channel's offset and count when there is one.
10170                    Shape::Path(p) => {
10171                        let (offset, count) = geometry_payload(
10172                            &mut geometry,
10173                            &mut texts,
10174                            || encode_path(p),
10175                            |g| path_numbers(p, g),
10176                        );
10177                        (
10178                            3.0,
10179                            [geometry_key(shape), offset, count, 0.0],
10180                            rule_bits(p.rule),
10181                            None,
10182                        )
10183                    }
10184                    Shape::Polygon(pts) => {
10185                        let (offset, count) = geometry_payload(
10186                            &mut geometry,
10187                            &mut texts,
10188                            || encode_points(pts),
10189                            |g| point_numbers(pts, g),
10190                        );
10191                        (4.0, [geometry_key(shape), offset, count, 0.0], 0.0, None)
10192                    }
10193                    // A clip to a line or an arc has no interior to clip to. Clipping to an
10194                    // empty region would blank everything after it, so clip to the shape's
10195                    // bounds instead: wrong in the same direction as no clip at all.
10196                    Shape::Line(..) | Shape::Arc { .. } => {
10197                        let r = shape.bounds();
10198                        (
10199                            0.0,
10200                            [r.origin.x, r.origin.y, r.size.width, r.size.height],
10201                            0.0,
10202                            None,
10203                        )
10204                    }
10205                };
10206                push(
10207                    OpCode::Clip,
10208                    geo[0],
10209                    geo[1],
10210                    geo[2],
10211                    geo[3],
10212                    extra,
10213                    kind,
10214                    0.0,
10215                    Color::CLEAR,
10216                    &mut nums,
10217                );
10218                if let Some(s) = payload {
10219                    texts.push(s);
10220                }
10221            }
10222            DrawOp::Text {
10223                text,
10224                at,
10225                size,
10226                color,
10227                anchor,
10228                font,
10229            } => {
10230                if *font != CanvasFont::default() {
10231                    push(
10232                        OpCode::SetFont,
10233                        f64::from(font.css_weight()),
10234                        f64::from(u8::from(font.italic)),
10235                        0.0,
10236                        0.0,
10237                        0.0,
10238                        0.0,
10239                        0.0,
10240                        Color::CLEAR,
10241                        &mut nums,
10242                    );
10243                    texts.push(
10244                        font.family_str()
10245                            .replace([FONT_LIST_FIELD, FONT_LIST_FAMILY], " "),
10246                    );
10247                }
10248                push(
10249                    OpCode::Text,
10250                    at.x,
10251                    at.y,
10252                    0.0,
10253                    0.0,
10254                    *size,
10255                    anchor.pack(),
10256                    0.0,
10257                    *color,
10258                    &mut nums,
10259                );
10260                texts.push(text.clone());
10261            }
10262            DrawOp::Image {
10263                image,
10264                rect,
10265                opacity,
10266                source,
10267            } => {
10268                if let Some(src) = source {
10269                    push(
10270                        OpCode::ImageSource,
10271                        src.origin.x,
10272                        src.origin.y,
10273                        src.size.width,
10274                        src.size.height,
10275                        0.0,
10276                        0.0,
10277                        0.0,
10278                        Color::CLEAR,
10279                        &mut nums,
10280                    );
10281                }
10282                push(
10283                    OpCode::Image,
10284                    rect.origin.x,
10285                    rect.origin.y,
10286                    rect.size.width,
10287                    rect.size.height,
10288                    image.0 as f64,
10289                    *opacity,
10290                    0.0,
10291                    Color::CLEAR,
10292                    &mut nums,
10293                );
10294            }
10295            DrawOp::Save => push(
10296                OpCode::Save,
10297                0.0,
10298                0.0,
10299                0.0,
10300                0.0,
10301                0.0,
10302                0.0,
10303                0.0,
10304                Color::CLEAR,
10305                &mut nums,
10306            ),
10307            DrawOp::Restore => push(
10308                OpCode::Restore,
10309                0.0,
10310                0.0,
10311                0.0,
10312                0.0,
10313                0.0,
10314                0.0,
10315                0.0,
10316                Color::CLEAR,
10317                &mut nums,
10318            ),
10319            DrawOp::Concat(m) => push(
10320                OpCode::Concat,
10321                m.a,
10322                m.b,
10323                m.c,
10324                m.d,
10325                m.tx,
10326                m.ty,
10327                0.0,
10328                Color::CLEAR,
10329                &mut nums,
10330            ),
10331        }
10332    }
10333    (nums, texts)
10334}
10335
10336#[cfg(test)]
10337mod font_list_tests {
10338    use super::*;
10339
10340    #[test]
10341    fn css_weights_round_trip_and_snap_to_the_nearest_rung() {
10342        for w in FontWeight::ALL {
10343            assert_eq!(FontWeight::from_css(w.css()), w);
10344        }
10345        assert_eq!(FontWeight::from_css(0), FontWeight::UltraLight);
10346        assert_eq!(FontWeight::from_css(350), FontWeight::Regular); // ties go heavier
10347        assert_eq!(FontWeight::from_css(649), FontWeight::Semibold);
10348        assert_eq!(FontWeight::from_css(1200), FontWeight::Black);
10349    }
10350
10351    fn sans() -> FontFamilyInfo {
10352        FontFamilyInfo {
10353            family: "Day Sans".into(),
10354            faces: vec![
10355                FontFace {
10356                    name: "Regular".into(),
10357                    weight: FontWeight::Regular,
10358                    italic: false,
10359                },
10360                FontFace {
10361                    name: "Bold".into(),
10362                    weight: FontWeight::Bold,
10363                    italic: false,
10364                },
10365                FontFace {
10366                    name: "Light Italic".into(),
10367                    weight: FontWeight::Light,
10368                    italic: true,
10369                },
10370            ],
10371        }
10372    }
10373
10374    #[test]
10375    fn face_for_prefers_the_slant_then_the_nearest_weight() {
10376        let f = sans();
10377        assert!(f.has_bold() && f.has_italic());
10378        assert_eq!(f.face_for(FontWeight::Bold, false).unwrap().name, "Bold");
10379        assert_eq!(
10380            f.face_for(FontWeight::Semibold, false).unwrap().name,
10381            "Bold"
10382        );
10383        assert_eq!(
10384            f.face_for(FontWeight::Medium, false).unwrap().name,
10385            "Regular"
10386        );
10387        let tie = FontFamilyInfo {
10388            family: "Tie".into(),
10389            faces: vec![
10390                FontFace {
10391                    name: "Light".into(),
10392                    weight: FontWeight::Light,
10393                    italic: false,
10394                },
10395                FontFace {
10396                    name: "Bold".into(),
10397                    weight: FontWeight::Bold,
10398                    italic: false,
10399                },
10400            ],
10401        };
10402        // Medium sits 200 from both; the heavier face wins the tie.
10403        assert_eq!(
10404            tie.face_for(FontWeight::Medium, false).unwrap().name,
10405            "Bold"
10406        );
10407        assert_eq!(
10408            f.face_for(FontWeight::Black, true).unwrap().name,
10409            "Light Italic"
10410        );
10411        let none = FontFamilyInfo {
10412            family: "Empty".into(),
10413            faces: vec![],
10414        };
10415        assert!(none.face_for(FontWeight::Regular, false).is_none());
10416        assert!(!none.has_bold());
10417    }
10418
10419    #[test]
10420    fn the_shim_list_format_decodes_tolerantly() {
10421        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\
10422                 \u{1e}\u{1e}Day Mono\u{1f}Regular\u{1f}400\u{1f}0\u{1e}Faceless";
10423        let list = parse_font_list(s);
10424        assert_eq!(list.len(), 3);
10425        assert_eq!(list[0].family, "Day Sans");
10426        assert_eq!(list[0].faces.len(), 2, "the bad weight is skipped");
10427        assert_eq!(list[0].faces[1].name, "Bold Italic"); // synthesized from 700 + italic
10428        assert_eq!(list[1].family, "Day Mono");
10429        assert_eq!(list[2].family, "Faceless");
10430        assert!(list[2].faces.is_empty());
10431    }
10432
10433    #[test]
10434    fn approximate_metrics_scale_with_size_and_length() {
10435        let m = TextMetrics::approximate("abc", 10.0);
10436        assert_eq!((m.width, m.height, m.ascent), (18.0, 12.0, 9.0));
10437        assert_eq!(TextMetrics::approximate("", 10.0).width, 0.0);
10438    }
10439
10440    #[test]
10441    fn a_default_canvas_font_is_the_platform_face() {
10442        let f = CanvasFont::default();
10443        assert_eq!((f.family_str(), f.css_weight(), f.italic), ("", 0, false));
10444    }
10445}
10446
10447#[cfg(test)]
10448mod image_header_tests {
10449    use super::*;
10450
10451    /// A 4×2 PNG: signature, then an IHDR whose width and height are big-endian.
10452    fn png(w: u32, h: u32) -> Vec<u8> {
10453        let mut v = vec![0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a];
10454        v.extend(13u32.to_be_bytes());
10455        v.extend(b"IHDR");
10456        v.extend(w.to_be_bytes());
10457        v.extend(h.to_be_bytes());
10458        v
10459    }
10460
10461    /// A JPEG whose frame header sits behind one other segment, so the walk has to skip it.
10462    fn jpeg(w: u16, h: u16) -> Vec<u8> {
10463        let mut v = vec![0xFF, 0xD8]; // SOI
10464        v.extend([0xFF, 0xE0, 0x00, 0x04, 0x00, 0x00]); // APP0, length 4
10465        v.extend([0xFF, 0xC0, 0x00, 0x11, 0x08]); // SOF0, length 17, precision 8
10466        v.extend(h.to_be_bytes());
10467        v.extend(w.to_be_bytes());
10468        v
10469    }
10470
10471    #[test]
10472    fn a_header_states_the_size_before_anything_decodes() {
10473        assert_eq!(ImageFormat::dimensions(&png(512, 512)), Some((512, 512)));
10474        assert_eq!(ImageFormat::dimensions(&png(1, 65535)), Some((1, 65535)));
10475        // The JPEG walk must step over the APP0 segment to reach the frame header.
10476        assert_eq!(ImageFormat::dimensions(&jpeg(640, 480)), Some((640, 480)));
10477
10478        let mut gif = b"GIF89a".to_vec();
10479        gif.extend(320u16.to_le_bytes());
10480        gif.extend(240u16.to_le_bytes());
10481        assert_eq!(ImageFormat::dimensions(&gif), Some((320, 240)));
10482
10483        // A top-down BMP states its height as a negative number; the size is still positive.
10484        let mut bmp = b"BM".to_vec();
10485        bmp.resize(18, 0);
10486        bmp.extend(64i32.to_le_bytes());
10487        bmp.extend((-32i32).to_le_bytes());
10488        assert_eq!(ImageFormat::dimensions(&bmp), Some((64, 32)));
10489    }
10490
10491    #[test]
10492    fn a_truncated_or_unknown_header_answers_nothing_rather_than_a_guess() {
10493        assert_eq!(ImageFormat::dimensions(&[]), None);
10494        // The signature is there but the IHDR is not.
10495        assert_eq!(ImageFormat::dimensions(&png(8, 8)[..12]), None);
10496        // Not an image at all.
10497        assert_eq!(ImageFormat::dimensions(b"not an image"), None);
10498        // A JPEG that never reaches a frame header must not loop or invent a size.
10499        assert_eq!(
10500            ImageFormat::dimensions(&[0xFF, 0xD8, 0xFF, 0xE0, 0x00, 0x04, 0, 0]),
10501            None
10502        );
10503    }
10504}
10505
10506#[cfg(test)]
10507mod encode_ops_tests {
10508    use super::*;
10509
10510    /// The texts channel carries plain decimals: whole numbers without a point, fractions to
10511    /// six places with the trailing zeros gone, and the general form only past what the fixed
10512    /// one can hold.
10513    #[test]
10514    fn wire_numbers_are_short_plain_decimals() {
10515        let text = |v: f64| {
10516            let mut out = String::new();
10517            push_wire_num(&mut out, v);
10518            out
10519        };
10520        assert_eq!(text(12.0), "12");
10521        assert_eq!(text(-0.5), "-0.5");
10522        assert_eq!(text(183.472_938_472_938_4), "183.472938");
10523        assert_eq!(text(0.1 + 0.2), "0.3");
10524        assert_eq!(text(-0.000_000_1), "0");
10525        assert_eq!(text(2.000_05), "2.00005");
10526        assert_eq!(text(f64::INFINITY), "inf");
10527        assert_eq!(text(1.0e17), "100000000000000000");
10528        let path = Path {
10529            segs: vec![
10530                PathSeg::Move(Point::new(1.5, 2.0)),
10531                PathSeg::Line(Point::new(-3.25, 4.0)),
10532                PathSeg::Close,
10533            ],
10534            rule: FillRule::NonZero,
10535        };
10536        assert_eq!(encode_path(&path), "M 1.5 2 L -3.25 4 Z");
10537        assert_eq!(
10538            encode_points(&[Point::new(0.0, 0.0), Point::new(10.0, 0.125)]),
10539            "0,0 10,0.125"
10540        );
10541    }
10542
10543    /// With the geometry channel open, a path's and a polygon's points leave the texts channel
10544    /// (an empty entry keeps it positional) for the numbers, with offset and count in slots b
10545    /// and c; without it the texts channel carries them exactly as before.
10546    #[test]
10547    fn geometry_channel_carries_points_as_numbers() {
10548        let path = Shape::Path(Path {
10549            segs: vec![
10550                PathSeg::Move(Point::new(1.0, 2.0)),
10551                PathSeg::Quad(Point::new(3.0, 4.0), Point::new(5.0, 6.0)),
10552                PathSeg::Close,
10553            ],
10554            rule: FillRule::EvenOdd,
10555        });
10556        let polygon = Shape::Polygon(vec![Point::new(0.0, 0.0), Point::new(7.0, 8.0)]);
10557        let ops = vec![
10558            DrawOp::Clip(path.clone()),
10559            DrawOp::Fill(path.clone(), Paint::Solid(Color::WHITE)),
10560            DrawOp::Stroke(
10561                polygon.clone(),
10562                Paint::Solid(Color::WHITE),
10563                StrokeStyle::default(),
10564            ),
10565        ];
10566        let (nums, texts, geometry) = encode_ops_with_geometry(&ops);
10567        assert_eq!(texts, vec!["", "", ""]);
10568        assert_eq!(
10569            geometry,
10570            vec![
10571                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,
10572                6.0, 4.0, 0.0, 0.0, 7.0, 8.0
10573            ]
10574        );
10575        // The clip (kind 17, sub-kind 3 in f) and the fill (kind 15) point at the two copies
10576        // of the path, the stroke (kind 12) at the polygon's four numbers.
10577        assert_eq!((nums[0], nums[2], nums[3], nums[6]), (17.0, 0.0, 9.0, 3.0));
10578        assert_eq!(
10579            (nums[9], nums[11], nums[12], nums[15]),
10580            (15.0, 9.0, 9.0, 1.0)
10581        );
10582        assert_eq!((nums[18], nums[20], nums[21]), (12.0, 18.0, 4.0));
10583        let (plain_nums, plain_texts) = encode_ops(&ops);
10584        assert_eq!(plain_texts[1], "M 1 2 Q 3 4 5 6 Z");
10585        assert_eq!(plain_texts[2], "0,0 7,8");
10586        assert_eq!((plain_nums[11], plain_nums[12]), (0.0, 0.0));
10587    }
10588
10589    /// A region outside the bitmap is clamped to it with its mapping into the rect kept, and an
10590    /// empty intersection draws nothing.
10591    #[test]
10592    fn image_source_clamps_to_the_bitmap() {
10593        let px = Size::new(64.0, 32.0);
10594        let dest = Rect::new(100.0, 200.0, 32.0, 32.0); // 2 points per source pixel
10595        assert_eq!(
10596            clamp_image_source(Rect::new(-8.0, -8.0, 16.0, 16.0), dest, px),
10597            Some((
10598                Rect::new(0.0, 0.0, 8.0, 8.0),
10599                Rect::new(116.0, 216.0, 16.0, 16.0)
10600            ))
10601        );
10602        assert_eq!(
10603            clamp_image_source(Rect::new(60.0, 28.0, 16.0, 16.0), dest, px),
10604            Some((
10605                Rect::new(60.0, 28.0, 4.0, 4.0),
10606                Rect::new(100.0, 200.0, 8.0, 8.0)
10607            ))
10608        );
10609        assert_eq!(
10610            clamp_image_source(Rect::new(16.0, 8.0, 16.0, 16.0), dest, px),
10611            Some((Rect::new(16.0, 8.0, 16.0, 16.0), dest))
10612        );
10613        assert_eq!(
10614            clamp_image_source(Rect::new(64.0, 0.0, 8.0, 8.0), dest, px),
10615            None
10616        );
10617        assert_eq!(
10618            clamp_image_source(Rect::new(0.0, 0.0, 0.0, 8.0), dest, px),
10619            None
10620        );
10621        assert_eq!(
10622            clamp_image_source(Rect::new(0.0, 0.0, 8.0, 8.0), dest, Size::new(0.0, 0.0)),
10623            None
10624        );
10625    }
10626
10627    /// The wire codes are a frozen dense table: any gap, duplicate, or variant missing from
10628    /// `ALL` breaks a decoder somewhere, so it must break here first.
10629    #[test]
10630    fn op_codes_are_dense_and_round_trip() {
10631        for (i, code) in OpCode::ALL.into_iter().enumerate() {
10632            assert_eq!(code as i32, i as i32, "{code:?} broke wire density");
10633            assert_eq!(OpCode::from_wire(i as f64), Some(code));
10634        }
10635        assert_eq!(OpCode::from_wire(OpCode::ALL.len() as f64), None);
10636        assert_eq!(OpCode::from_wire(-1.0), None);
10637        assert_eq!(OpCode::from_wire(0.5), None);
10638    }
10639
10640    /// Reference decode of a display list covering every op arm: the record stream must be
10641    /// whole 9-slot records of known codes, and the texts channel must carry exactly one
10642    /// entry per text-carrying record, in order: the contract every shim decoder assumes.
10643    #[test]
10644    fn encode_ops_emits_whole_records_and_matched_text_payloads() {
10645        let r = Rect::new(1.0, 2.0, 3.0, 4.0);
10646        let red = Color::rgb(1.0, 0.0, 0.0);
10647        let ops = vec![
10648            DrawOp::Fill(Shape::Rect(r), Paint::Solid(red)),
10649            DrawOp::Stroke(Shape::Rect(r), Paint::Solid(red), StrokeStyle::round(2.0)),
10650            DrawOp::Fill(Shape::RoundedRect(r, 5.0), Paint::Solid(red)),
10651            DrawOp::Fill(Shape::Ellipse(r), Paint::Solid(red)),
10652            // The documented asymmetry: a filled arc encodes as StrokeArc with width 0.
10653            DrawOp::Fill(
10654                Shape::Arc {
10655                    rect: r,
10656                    start_deg: 0.0,
10657                    sweep_deg: 90.0,
10658                },
10659                Paint::Solid(red),
10660            ),
10661            DrawOp::Stroke(
10662                Shape::Line(Point::new(0.0, 0.0), Point::new(9.0, 9.0)),
10663                Paint::Solid(red),
10664                StrokeStyle::width(1.0),
10665            ),
10666            DrawOp::Fill(
10667                Shape::Polygon(vec![
10668                    Point::new(0.0, 0.0),
10669                    Point::new(4.0, 0.0),
10670                    Point::new(2.0, 3.0),
10671                ]),
10672                Paint::Solid(red),
10673            ),
10674            DrawOp::Fill(
10675                Shape::Path(Path {
10676                    segs: vec![
10677                        PathSeg::Move(Point::new(0.0, 0.0)),
10678                        PathSeg::Line(Point::new(5.0, 5.0)),
10679                        PathSeg::Close,
10680                    ],
10681                    rule: FillRule::EvenOdd,
10682                }),
10683                Paint::Linear(LinearGradient::new(
10684                    UnitPoint::new(0.0, 0.0),
10685                    UnitPoint::new(1.0, 1.0),
10686                    vec![(0.0, red), (1.0, Color::WHITE)],
10687                )),
10688            ),
10689            DrawOp::Clip(Shape::Rect(r)),
10690            DrawOp::Clip(Shape::Polygon(vec![
10691                Point::new(0.0, 0.0),
10692                Point::new(1.0, 0.0),
10693                Point::new(0.0, 1.0),
10694            ])),
10695            DrawOp::Text {
10696                text: "hi".into(),
10697                at: Point::new(7.0, 8.0),
10698                size: 12.0,
10699                color: red,
10700                anchor: TextAnchor::LEADING,
10701                font: CanvasFont::default(),
10702            },
10703            DrawOp::Text {
10704                text: "bold".into(),
10705                at: Point::new(7.0, 8.0),
10706                size: 12.0,
10707                color: red,
10708                anchor: TextAnchor::CENTERED,
10709                font: CanvasFont {
10710                    family: Some("Day Sans".into()),
10711                    weight: Some(FontWeight::Bold),
10712                    italic: true,
10713                },
10714            },
10715            DrawOp::Save,
10716            DrawOp::Concat(Affine::IDENTITY),
10717            DrawOp::Restore,
10718            DrawOp::Image {
10719                image: BitmapId(7),
10720                rect: r,
10721                opacity: 0.5,
10722                source: None,
10723            },
10724            DrawOp::Image {
10725                image: BitmapId(7),
10726                rect: r,
10727                opacity: 1.0,
10728                source: Some(Rect::new(16.0, 32.0, 8.0, 8.0)),
10729            },
10730        ];
10731        let (nums, texts) = encode_ops(&ops);
10732        assert_eq!(nums.len() % 9, 0, "partial record on the wire");
10733
10734        let mut expected_texts = 0usize;
10735        let mut decoded = Vec::new();
10736        for rec in nums.chunks(9) {
10737            let code = OpCode::from_wire(rec[0])
10738                .unwrap_or_else(|| panic!("unknown op code {} on the wire", rec[0]));
10739            decoded.push(code);
10740            expected_texts += match code {
10741                OpCode::Text
10742                | OpCode::FillPolygon
10743                | OpCode::StrokePolygon
10744                | OpCode::SetGradient
10745                | OpCode::FillPath
10746                | OpCode::StrokePath
10747                | OpCode::StrokeStyle
10748                | OpCode::SetFont => 1,
10749                // Clip carries a payload only for its path (3) / polygon (4) sub-kinds.
10750                OpCode::Clip => usize::from(rec[6] == 3.0 || rec[6] == 4.0),
10751                _ => 0,
10752            };
10753        }
10754        assert_eq!(
10755            texts.len(),
10756            expected_texts,
10757            "texts channel out of step with the records that consume it"
10758        );
10759        // No payload may carry the transport separator.
10760        assert!(texts.iter().all(|t| !t.contains('\u{1f}')));
10761
10762        let expected = {
10763            use OpCode::*;
10764            vec![
10765                FillRect,
10766                StrokeStyle, // ::round(2.0) is not plain, so the style modifier precedes
10767                StrokeRect,
10768                FillRrect,
10769                FillEllipse,
10770                StrokeArc, // the filled arc's stroke encoding…
10771                Line,
10772                FillPolygon,
10773                SetGradient, // gradient precedes its shape record
10774                FillPath,
10775                Clip,
10776                Clip,
10777                Text,
10778                SetFont, // a non-default font precedes its text record…
10779                Text,
10780                Save,
10781                Concat,
10782                Restore,
10783                Image,
10784                ImageSource, // a region precedes its image record; a whole-image draw has none
10785                Image,
10786            ]
10787        };
10788        assert_eq!(decoded, expected);
10789        // The bitmap id rides the numeric channel intact (an f64 holds a u64 id exactly well
10790        // past any id this process will mint), and nothing of an image reaches the texts channel.
10791        let img = nums
10792            .chunks(9)
10793            .find(|r| r[0] == OpCode::Image as i32 as f64)
10794            .expect("Image record");
10795        assert_eq!(&img[1..7], &[1.0, 2.0, 3.0, 4.0, 7.0, 0.5]);
10796        // The region rides its own prefix record, in bitmap pixels, with nothing else in it.
10797        let src = nums
10798            .chunks(9)
10799            .find(|r| r[0] == OpCode::ImageSource as i32 as f64)
10800            .expect("ImageSource record");
10801        assert_eq!(&src[1..8], &[16.0, 32.0, 8.0, 8.0, 0.0, 0.0, 0.0]);
10802        // …carrying the CSS weight and the slant, with the family on the texts channel.
10803        let font_rec = nums
10804            .chunks(9)
10805            .find(|r| r[0] == OpCode::SetFont as i32 as f64)
10806            .expect("SetFont record");
10807        assert_eq!(&font_rec[1..3], &[700.0, 1.0]);
10808        assert_eq!(texts.iter().filter(|t| *t == "Day Sans").count(), 1);
10809        // …with width 0, per the documented asymmetry.
10810        let arc = nums
10811            .chunks(9)
10812            .find(|r| r[0] == OpCode::StrokeArc as i32 as f64);
10813        assert_eq!(arc.map(|r| r[7]), Some(0.0));
10814        // A gradient-filled shape's color slot is opaque white, never clear (Skia decoders
10815        // modulate the shader by it).
10816        let path_rec = nums
10817            .chunks(9)
10818            .find(|r| r[0] == OpCode::FillPath as i32 as f64);
10819        assert_eq!(
10820            path_rec.map(|r| r[8] as u32),
10821            Some(0xFFFF_FFFF),
10822            "gradient shape record must carry opaque white"
10823        );
10824    }
10825
10826    #[test]
10827    fn variable_length_geometry_carries_a_content_key() {
10828        let path = |x: f64| {
10829            Shape::Path(Path {
10830                segs: vec![
10831                    PathSeg::Move(Point::new(x, 0.0)),
10832                    PathSeg::Cubic(
10833                        Point::new(1.0, 1.0),
10834                        Point::new(2.0, 2.0),
10835                        Point::new(3.0, 3.0),
10836                    ),
10837                    PathSeg::Close,
10838                ],
10839                rule: FillRule::NonZero,
10840            })
10841        };
10842        let poly = Shape::Polygon(vec![
10843            Point::new(0.0, 0.0),
10844            Point::new(1.0, 0.0),
10845            Point::new(0.0, 1.0),
10846        ]);
10847
10848        // Equal geometry keys equal though the two were built separately. The key exists for
10849        // this: a draw closure rebuilds its paths from scratch on every frame.
10850        assert_eq!(geometry_key(&path(0.0)), geometry_key(&path(0.0)));
10851        assert_ne!(geometry_key(&path(0.0)), geometry_key(&path(1.0)));
10852        // The fill rule decides what the path draws, so it belongs to the key.
10853        let even_odd = Shape::Path(Path {
10854            segs: match path(0.0) {
10855                Shape::Path(p) => p.segs,
10856                _ => unreachable!(),
10857            },
10858            rule: FillRule::EvenOdd,
10859        });
10860        assert_ne!(geometry_key(&path(0.0)), geometry_key(&even_odd));
10861        // A polygon and a path decode to different geometry and never share an entry.
10862        assert_ne!(geometry_key(&poly), geometry_key(&path(0.0)));
10863        // Fixed-size shapes keep 0: their geometry rides the record's own slots.
10864        assert_eq!(
10865            geometry_key(&Shape::Rect(Rect::new(0.0, 0.0, 1.0, 1.0))),
10866            0.0
10867        );
10868        // And a key survives an f64 wire slot exactly, which is what the 53-bit mask buys.
10869        let k = geometry_key(&path(0.0));
10870        assert!(
10871            k > 0.0 && k < (1u64 << 53) as f64 && k.fract() == 0.0,
10872            "{k}"
10873        );
10874
10875        // It reaches the wire in slot a, for exactly the ops whose payload rides the texts
10876        // channel, and never displaces geometry that is already there.
10877        let (nums, _) = encode_ops(&[
10878            DrawOp::Fill(path(0.0), Paint::Solid(Color::WHITE)),
10879            DrawOp::Fill(poly.clone(), Paint::Solid(Color::WHITE)),
10880            DrawOp::Clip(path(0.0)),
10881            DrawOp::Clip(Shape::Rect(Rect::new(1.0, 2.0, 3.0, 4.0))),
10882        ]);
10883        let slot_a = |code: OpCode| {
10884            nums.chunks(9)
10885                .find(|r| r[0] == code as i32 as f64)
10886                .unwrap_or_else(|| panic!("no {code:?} record"))[1]
10887        };
10888        assert_eq!(slot_a(OpCode::FillPath), geometry_key(&path(0.0)));
10889        assert_eq!(slot_a(OpCode::FillPolygon), geometry_key(&poly));
10890        let clips: Vec<&[f64]> = nums
10891            .chunks(9)
10892            .filter(|r| r[0] == OpCode::Clip as i32 as f64)
10893            .collect();
10894        assert_eq!(clips[0][1], geometry_key(&path(0.0)), "path clip keys");
10895        assert_eq!(
10896            &clips[1][1..5],
10897            &[1.0, 2.0, 3.0, 4.0],
10898            "a rect clip still puts its geometry in a..d"
10899        );
10900    }
10901}
10902
10903#[cfg(test)]
10904mod markup_tests {
10905    use super::*;
10906
10907    fn bold(range: std::ops::Range<usize>) -> TextRun {
10908        TextRun::font(
10909            range,
10910            FontSpec {
10911                style: Font::Body,
10912                weight: Some(FontWeight::Bold),
10913                ..Default::default()
10914            },
10915        )
10916    }
10917
10918    #[test]
10919    fn plain_text_is_escaped_in_both_dialects() {
10920        // The case a translated string will find: markup metacharacters in the content.
10921        let text = "5 < 6 & \"quoted\" <b>not bold</b>";
10922        for d in [MarkupDialect::Pango, MarkupDialect::QtHtml] {
10923            let m = runs_to_markup(text, &[], d, 16.0);
10924            assert!(!m.contains("<b>"), "content tag survived into markup: {m}");
10925            assert!(m.contains("&lt;b&gt;"), "{m}");
10926            assert!(m.contains("&amp;"), "{m}");
10927            assert!(m.contains("5 &lt; 6"), "{m}");
10928        }
10929    }
10930
10931    #[test]
10932    fn a_styled_run_is_wrapped_and_its_text_escaped() {
10933        let text = "a <b> c";
10934        let m = runs_to_markup(text, &[bold(2..5)], MarkupDialect::Pango, 16.0);
10935        assert_eq!(m, "a <b>&lt;b&gt;</b> c");
10936    }
10937
10938    #[test]
10939    fn color_and_monospace_differ_per_dialect() {
10940        let text = "code";
10941        let run = TextRun {
10942            range: 0..4,
10943            font: FontSpec {
10944                style: Font::Body,
10945                monospace: true,
10946                ..Default::default()
10947            },
10948            color: Some(Color::rgb(1.0, 0.0, 0.0)),
10949            ..TextRun::default()
10950        };
10951        let pango = runs_to_markup(text, std::slice::from_ref(&run), MarkupDialect::Pango, 16.0);
10952        assert!(pango.contains("foreground=\"#ff0000\""), "{pango}");
10953        assert!(pango.contains("font_family=\"monospace\""), "{pango}");
10954        let qt = runs_to_markup(
10955            text,
10956            std::slice::from_ref(&run),
10957            MarkupDialect::QtHtml,
10958            16.0,
10959        );
10960        assert!(qt.contains("color:#ff0000"), "{qt}");
10961        // Qt takes its fixed face from <code>: a `font-family:monospace` style attribute
10962        // renders proportional (observed on Qt 6.11).
10963        assert!(qt.contains("<code>") && qt.contains("</code>"), "{qt}");
10964    }
10965
10966    #[test]
10967    fn the_new_attributes_reach_both_dialects() {
10968        let run = TextRun {
10969            range: 0..2,
10970            font: FontSpec::default().scaled(1.5),
10971            background: Some(Color::rgb(0.0, 1.0, 0.0)),
10972            underline: Underline::Single,
10973            ..TextRun::default()
10974        };
10975        let pango = runs_to_markup("hi", std::slice::from_ref(&run), MarkupDialect::Pango, 16.0);
10976        assert!(pango.contains("background=\"#00ff00\""), "{pango}");
10977        // Pango takes an absolute size in 1/1024 pt (16 pt base × 1.5 = 24 pt), because the
10978        // relative attributes are Pango 1.50's and an unknown attribute empties the whole label.
10979        assert!(pango.contains("size=\"24576\""), "{pango}");
10980        assert!(pango.contains("<u>hi</u>"), "{pango}");
10981        let qt = runs_to_markup(
10982            "hi",
10983            std::slice::from_ref(&run),
10984            MarkupDialect::QtHtml,
10985            16.0,
10986        );
10987        assert!(qt.contains("background-color:#00ff00"), "{qt}");
10988        // Qt takes points: 16 pt base × 1.5 (observed; its CSS subset ignores a percentage).
10989        assert!(qt.contains("font-size:24pt"), "{qt}");
10990        assert!(qt.contains("<u>hi</u>"), "{qt}");
10991    }
10992
10993    #[test]
10994    fn a_link_target_is_escaped_too() {
10995        // A URL carrying `&` between query parameters is ordinary, and unescaped it truncates
10996        // the attribute and swallows the rest of the label.
10997        let text = "docs";
10998        let run = TextRun {
10999            range: 0..4,
11000            link: Some("https://x.dev/?a=1&b=2".into()),
11001            ..TextRun::default()
11002        };
11003        let m = runs_to_markup(text, &[run], MarkupDialect::Pango, 16.0);
11004        assert!(m.contains("a=1&amp;b=2"), "{m}");
11005    }
11006
11007    #[test]
11008    fn tags_nest_and_close_in_reverse() {
11009        let run = TextRun {
11010            range: 0..2,
11011            font: FontSpec {
11012                style: Font::Body,
11013                weight: Some(FontWeight::Bold),
11014                italic: true,
11015                ..Default::default()
11016            },
11017            strikethrough: true,
11018            link: Some("u".into()),
11019            ..TextRun::default()
11020        };
11021        let m = runs_to_markup("hi", &[run], MarkupDialect::Pango, 16.0);
11022        assert_eq!(m, "<a href=\"u\"><b><i><s>hi</s></i></b></a>");
11023    }
11024
11025    #[test]
11026    fn runs_out_of_bounds_are_skipped_not_panicked() {
11027        // `runs_are_valid` rejects these upstream; this is the belt-and-braces path.
11028        let m = runs_to_markup("hi", &[bold(0..99)], MarkupDialect::Pango, 16.0);
11029        assert_eq!(m, "hi");
11030    }
11031
11032    #[test]
11033    fn validation_catches_the_four_ways_runs_go_wrong() {
11034        let text = "héllo";
11035        assert!(runs_are_valid(text, &[bold(0..1)]).is_ok());
11036        // Overlapping.
11037        assert!(runs_are_valid(text, &[bold(0..3), bold(2..4)]).is_err());
11038        // Past the end.
11039        assert!(runs_are_valid(text, &[bold(0..99)]).is_err());
11040        // Inverted. Built from parts, since a literal `3..1` is a clippy error in its own right.
11041        let (hi, lo) = (3, 1);
11042        assert!(runs_are_valid(text, &[bold(hi..lo)]).is_err());
11043        // Splitting the 2-byte `é`.
11044        assert!(runs_are_valid(text, &[bold(0..2)]).is_err());
11045    }
11046}
11047
11048#[cfg(test)]
11049mod route_of_url_tests {
11050    use super::route_of_url;
11051
11052    #[test]
11053    fn strips_the_scheme_and_keeps_route_and_params() {
11054        assert_eq!(
11055            route_of_url("notes://mail/inbox?hint=x"),
11056            "mail/inbox?hint=x"
11057        );
11058        assert_eq!(route_of_url("notes://home"), "home");
11059        // No scheme: already a route, unchanged.
11060        assert_eq!(route_of_url("mail/inbox"), "mail/inbox");
11061        assert_eq!(route_of_url(""), "");
11062        // Percent-encoding passes through; the route parser decodes, not this mapping.
11063        assert_eq!(route_of_url("n://a/b%2Fc?q=1%202"), "a/b%2Fc?q=1%202");
11064    }
11065}
11066
11067#[cfg(test)]
11068mod builtin_kind_tests {
11069    use super::*;
11070
11071    /// Every built-in round-trips through its wire key, and the keys are unique. Guards the
11072    /// `builtin_kinds!` expansion: a copy-paste slip in the table would alias two kinds.
11073    #[test]
11074    fn keys_round_trip_and_are_unique() {
11075        let mut seen = std::collections::HashSet::new();
11076        for &b in Builtin::ALL {
11077            assert_eq!(Builtin::from_key(b.key()), Some(b), "{b:?} key round-trip");
11078            assert!(seen.insert(b.key()), "duplicate key {:?}", b.key());
11079            assert!(
11080                b.key().starts_with("day."),
11081                "built-in {b:?} must use the reserved `day.` prefix"
11082            );
11083        }
11084    }
11085
11086    /// The `kinds::*` constants are the enum's keys, so the two spellings cannot drift.
11087    #[test]
11088    fn kinds_constants_match_the_enum() {
11089        assert_eq!(kinds::LABEL, Builtin::Label.key());
11090        assert_eq!(kinds::LIST_CELL, Builtin::ListCell.key());
11091        assert_eq!(kinds::COVER, Builtin::Cover.key());
11092        assert_eq!(kinds::INSPECTOR, Builtin::Inspector.key());
11093        assert_eq!(kinds::TREE, Builtin::Tree.key());
11094        // 19 after `Tabs`/`TabsPage` retired (the tab bar is a NAV presentation, not a kind),
11095        // +2 for the inspector split and its panes (docs/inspector.md), +1 for the tree
11096        // (docs/tree.md).
11097        assert_eq!(Builtin::ALL.len(), 25);
11098    }
11099
11100    /// An extension piece's kind is not a built-in.
11101    #[test]
11102    fn extension_kinds_are_not_builtin() {
11103        assert_eq!(Builtin::from_key("acme.combobox"), None);
11104        assert_eq!(Builtin::from_key("day.not_a_real_kind"), None);
11105    }
11106}
11107
11108#[cfg(test)]
11109mod locale_tests {
11110    /// POSIX locale strings are not BCP-47 tags, and "C" is not a language; that difference is
11111    /// the job of `posix_locale_hints` (§12.2).
11112    #[test]
11113    fn posix_hints_parse_and_drop_the_c_locale() {
11114        // The parsing is exercised through the same normalization the function applies.
11115        let normalize = |v: &str| v.split('.').next().unwrap_or(v).replace('_', "-");
11116        assert_eq!(normalize("fr_FR.UTF-8"), "fr-FR");
11117        assert_eq!(normalize("en_US"), "en-US");
11118        assert_eq!(normalize("C"), "C");
11119        // A real read never panics whatever this host's environment holds.
11120        let hints = super::posix_locale_hints();
11121        assert!(
11122            hints
11123                .iter()
11124                .all(|h| !h.is_empty() && h != "C" && h != "POSIX")
11125        );
11126    }
11127}
11128
11129#[cfg(test)]
11130mod sidetable_tests {
11131    use super::sidetable::{SideTable, sweep};
11132    use std::cell::Cell;
11133    use std::rc::Rc;
11134
11135    /// The registry exists so that one `sweep(key)` clears every table without any
11136    /// table needing its own line in a backend's `release()`.
11137    #[test]
11138    fn sweep_clears_every_registered_table_and_runs_teardowns() {
11139        let torn = Rc::new(Cell::new(0u32));
11140        let t2 = torn.clone();
11141        let plain: SideTable<&'static str> = SideTable::new();
11142        let hooked: SideTable<u32> = SideTable::with_teardown(move |_| t2.set(t2.get() + 1));
11143
11144        plain.insert(7, "a");
11145        hooked.insert(7, 1);
11146        hooked.insert(8, 2);
11147        sweep(7);
11148        assert!(!plain.contains(7));
11149        assert!(!hooked.contains(7), "swept from every table");
11150        assert!(hooked.contains(8), "other keys untouched");
11151        assert_eq!(torn.get(), 1, "teardown ran for the swept value");
11152
11153        // remove() runs the teardown too; take() bypasses it for ownership transfer.
11154        hooked.remove(8);
11155        assert_eq!(torn.get(), 2);
11156        hooked.insert(9, 3);
11157        assert_eq!(hooked.take(9), Some(3));
11158        assert_eq!(torn.get(), 2, "take() skips the hook");
11159    }
11160
11161    #[test]
11162    fn contain_returns_default_on_panic() {
11163        let ok = super::ffi_guard::contain(0i32, || 5);
11164        assert_eq!(ok, 5);
11165        let prev = std::panic::take_hook();
11166        std::panic::set_hook(Box::new(|_| {}));
11167        let contained = super::ffi_guard::contain(-1i32, || panic!("boom"));
11168        std::panic::set_hook(prev);
11169        assert_eq!(contained, -1, "the panic must not escape the guard");
11170    }
11171}
11172
11173#[cfg(test)]
11174mod cursor_tests {
11175    use super::Cursor;
11176
11177    /// Every named cursor has a distinct CSS keyword, and `NAMED` lists each exactly once: the
11178    /// gallery and every backend's table key on the keyword.
11179    #[test]
11180    fn named_cursors_have_distinct_css_names() {
11181        let mut seen = std::collections::BTreeSet::new();
11182        for c in Cursor::NAMED.iter() {
11183            assert!(
11184                seen.insert(c.css_name().to_string()),
11185                "duplicate: {}",
11186                c.css_name()
11187            );
11188            assert!(!matches!(c, Cursor::Native(_)));
11189        }
11190        assert_eq!(seen.len(), Cursor::NAMED.len());
11191        assert_eq!(Cursor::native("dragCopy").css_name(), "dragCopy");
11192        assert_eq!(Cursor::default(), Cursor::Default);
11193    }
11194}
11195
11196#[cfg(test)]
11197mod text_anchor_tests {
11198    /// The anchor arithmetic every backend repeats. A drawing whose text lands in the wrong
11199    /// corner is a per-backend bug that only a screenshot catches, so the shared definition is
11200    /// pinned here and each shim is written to match it.
11201    #[test]
11202    fn text_anchor_offsets_place_the_line_box() {
11203        use crate::props::TextAlign;
11204        use crate::{TextAnchor, TextVAlign};
11205        // A 40-wide, 20-tall line box whose baseline sits 16 below its top.
11206        let (w, h, asc) = (40.0, 20.0, 16.0);
11207        let at = |ha, va| TextAnchor { h: ha, v: va }.offset(w, h, asc);
11208
11209        // The default is the drawing origin itself, every backend's native "draw here".
11210        assert_eq!(at(TextAlign::Leading, TextVAlign::Top), (0.0, 0.0));
11211        assert_eq!(TextAnchor::default(), TextAnchor::LEADING);
11212        // Horizontal: the box's leading edge, its middle, its trailing edge.
11213        assert_eq!(at(TextAlign::Center, TextVAlign::Top).0, -20.0);
11214        assert_eq!(at(TextAlign::Trailing, TextVAlign::Top).0, -40.0);
11215        // Vertical: top, middle, the baseline itself, bottom.
11216        assert_eq!(at(TextAlign::Leading, TextVAlign::Middle).1, -10.0);
11217        assert_eq!(at(TextAlign::Leading, TextVAlign::Baseline).1, -16.0);
11218        assert_eq!(at(TextAlign::Leading, TextVAlign::Bottom).1, -20.0);
11219        // The two named placements are the ones the two-variant enum used to have.
11220        assert_eq!(TextAnchor::CENTERED.offset(w, h, asc), (-20.0, -10.0));
11221        assert_eq!(TextAnchor::TRAILING.offset(w, h, asc), (-40.0, 0.0));
11222    }
11223
11224    /// The wire code the serializing backends (qt, xaml, arkui, android, web) decode by hand.
11225    #[test]
11226    fn text_anchor_packs_into_one_slot_and_round_trips() {
11227        use crate::props::TextAlign;
11228        use crate::{TextAnchor, TextVAlign};
11229        let mut seen = std::collections::BTreeSet::new();
11230        for h in [TextAlign::Leading, TextAlign::Center, TextAlign::Trailing] {
11231            for v in [
11232                TextVAlign::Top,
11233                TextVAlign::Middle,
11234                TextVAlign::Baseline,
11235                TextVAlign::Bottom,
11236            ] {
11237                let a = TextAnchor { h, v };
11238                let code = a.pack();
11239                assert!(
11240                    (0.0..=11.0).contains(&code),
11241                    "{code} outside the packed range"
11242                );
11243                assert!(seen.insert(code as u64), "two anchors share code {code}");
11244                assert_eq!(TextAnchor::unpack(code), a);
11245            }
11246        }
11247        assert_eq!(seen.len(), 12);
11248        // The shims decode as `h = code / 4`, `v = code % 4` in integer arithmetic.
11249        assert_eq!(TextAnchor::LEADING.pack(), 0.0);
11250        assert_eq!(TextAnchor::CENTERED.pack(), 5.0);
11251        // Junk answers the default rather than failing inside a native draw callback.
11252        assert_eq!(TextAnchor::unpack(-3.0), TextAnchor::LEADING);
11253        assert_eq!(TextAnchor::unpack(99.0), TextAnchor::unpack(11.0));
11254    }
11255
11256    /// The two shapes a backend's own metrics arrive in. Both land on the same contract: the line
11257    /// box's top-leading corner is the origin, and `ink` is relative to it.
11258    #[test]
11259    fn metrics_convert_from_a_backends_own_shape() {
11260        use crate::{Rect, TextMetrics};
11261        // Baseline-relative, y up-negative; Core Text, Skia and Qt all report like this.
11262        let m = TextMetrics::from_baseline(
11263            40.0,
11264            16.0,
11265            4.0,
11266            11.0,
11267            // Ink starting 1 right of the origin, from 11 above the baseline to 2 below it.
11268            Rect::new(1.0, -11.0, 38.0, 13.0),
11269        );
11270        assert_eq!(
11271            (m.width, m.height, m.ascent, m.cap_height),
11272            (40.0, 20.0, 16.0, 11.0)
11273        );
11274        // Shifted down by the ascent: the ink now starts 5 below the line box's top, which is
11275        // where a cap begins in a slot whose baseline is at 16.
11276        assert_eq!(m.ink, Rect::new(1.0, 5.0, 38.0, 13.0));
11277        assert_eq!(m.ascent - m.cap_height, m.ink.origin.y);
11278
11279        // The eight-slot wire form is already line-box-relative and passes straight through.
11280        let w = TextMetrics::from_slots(&[40.0, 20.0, 16.0, 11.0, 1.0, 5.0, 38.0, 13.0]);
11281        assert_eq!(w, m);
11282    }
11283
11284    /// The fallback must be usable, not merely present: a caller frames text with it on a toolkit
11285    /// that cannot measure, and every relation it relies on has to hold.
11286    #[test]
11287    fn the_approximation_is_internally_consistent() {
11288        use crate::TextMetrics;
11289        let m = TextMetrics::approximate("Agy", 20.0);
11290        assert!(m.ascent < m.height, "the baseline sits inside the line box");
11291        assert!(
11292            m.cap_height < m.ascent,
11293            "caps do not reach above the ascent"
11294        );
11295        // The ink box is the whole line box: a superset, so an overlap test using it can only be
11296        // too cautious. Never a claim to be tighter than it knows.
11297        assert_eq!(m.ink.origin.x, 0.0);
11298        assert_eq!(m.ink.origin.y, 0.0);
11299        assert_eq!(m.ink.size.width, m.width);
11300        assert_eq!(m.ink.size.height, m.height);
11301        // Empty text still answers a usable (zero-width, full-height) slot.
11302        let e = TextMetrics::approximate("", 20.0);
11303        assert_eq!(e.width, 0.0);
11304        assert!(e.height > 0.0);
11305    }
11306}
11307
11308#[cfg(test)]
11309mod cap_list_tests {
11310    use super::Cap;
11311
11312    #[test]
11313    fn every_capability_is_listed_once_in_its_place() {
11314        for (i, cap) in Cap::ALL.iter().enumerate() {
11315            assert_eq!(cap.ordinal(), i, "{cap:?} is out of place in Cap::ALL");
11316        }
11317    }
11318}
11319
11320#[cfg(test)]
11321mod button_menu_tests {
11322    use super::*;
11323    use std::cell::Cell;
11324    use std::rc::Rc;
11325
11326    fn action(label: &str) -> MenuItem {
11327        MenuItem::Action {
11328            id: None,
11329            action: 1,
11330            label: label.into(),
11331            shortcut: None,
11332            enabled: true,
11333            checked: None,
11334            role: None,
11335            icon: None,
11336        }
11337    }
11338
11339    #[test]
11340    fn a_provider_that_releases_its_button_shows_nothing() {
11341        let registered = Rc::new(Cell::new(true));
11342        let r = registered.clone();
11343        // The provider's app code removes the button (here: unregisters it), then still answers.
11344        let provider: ContextMenuFn = Rc::new(move |_| {
11345            r.set(false);
11346            vec![action("Open")]
11347        });
11348        assert!(resolve_button_menu(&provider, || registered.get()).is_none());
11349    }
11350
11351    #[test]
11352    fn a_live_button_shows_its_items_and_an_empty_menu_shows_nothing() {
11353        let provider: ContextMenuFn = Rc::new(|_| vec![action("Open")]);
11354        assert_eq!(
11355            resolve_button_menu(&provider, || true).map(|i| i.len()),
11356            Some(1)
11357        );
11358        let empty: ContextMenuFn = Rc::new(|_| Vec::new());
11359        let mut asked = false;
11360        assert!(
11361            resolve_button_menu(&empty, || {
11362                asked = true;
11363                true
11364            })
11365            .is_none()
11366        );
11367        assert!(!asked, "an empty menu needs no registry check");
11368    }
11369}