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    /// Drop both marks for a node that left the tree (day-core calls it from its removal
605    /// path). Node ids are generational, so a stale id would never match a new node; this
606    /// keeps the registries from growing with every rebuilt canvas.
607    pub fn forget(node: NodeId) {
608        HANDLED.with(|h| h.borrow_mut().remove(&node));
609        TEXT.with(|h| h.borrow_mut().remove(&node));
610    }
611}
612
613/// Raw foreign native handle for polyglot adoption (§15.3).
614pub type RawHandle = *mut std::ffi::c_void;
615
616// ---------------------------------------------------------------------------
617// Events (§8.3)
618// ---------------------------------------------------------------------------
619
620/// The wire table for backends whose native side reaches Rust through one numeric-kind
621/// trampoline (Android's JNI `nativeOnEvent`, ArkUI's `day_arkui_on_event`). This enum
622/// defines those kind numbers; the Java and C++ sides carry mirrored constants that parity
623/// tests check against these discriminants (so a collision or drift fails `cargo test` on the
624/// host instead of silently mis-decoding events on a device). AppKit/UIKit/GTK/Qt emit `Event`
625/// values directly and never use these numbers; XAML uses per-event callbacks with its own
626/// small local codes.
627///
628/// Payload conventions ride `(num: f64, text: String)` per kind, documented on each variant.
629pub mod bridge {
630    /// One numeric event kind. `as i32` is the wire value.
631    #[repr(i32)]
632    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
633    pub enum BridgeKind {
634        /// Click/press. No payload.
635        Pressed = 0,
636        /// `text` = the field's full new text.
637        TextChanged = 1,
638        /// `num` != 0 ⇒ on.
639        ToggleChanged = 2,
640        /// `num` = the new value.
641        ValueChanged = 3,
642        /// `num` = the selected index.
643        SelectionChanged = 4,
644        /// `num` == 1 ⇒ the native side already popped (predictive back / up arrow).
645        NavBack = 5,
646        /// Nav/tab page size report; `text` = `"w,h"` in px (Rust divides by density).
647        FrameChanged = 6,
648        /// Warm deep link; `text` = the route.
649        Deeplink = 7,
650        /// Modal answered with a button; `num` = the button index.
651        PresentButton = 8,
652        /// Modal answered with text; `text` = the entry.
653        PresentText = 9,
654        /// Modal dismissed.
655        PresentDismissed = 10,
656        /// Gesture; `num` = phase (0 tap, 1 began, 2 changed, 3 ended), `text` = `"x,y,tx,ty"` px.
657        Gesture = 11,
658        /// Piece-defined open channel (`Event::Custom` with an empty tag): the piece reads the
659        /// raw `num`/`text` payload.
660        Custom = 12,
661        /// Menu selection; the event's node id is the chosen action's dispatch id.
662        MenuAction = 13,
663        /// App lifecycle; `num` = the phase code (`day_spec::Lifecycle` order).
664        Lifecycle = 14,
665        /// File-picker answer; `text` = chosen locators joined by the unit separator.
666        PresentFile = 15,
667        /// `num` != 0 ⇒ gained keyboard focus.
668        FocusChanged = 16,
669        /// IME action / Return.
670        Submitted = 17,
671        /// Root size change; `text` = `"w,h"` in px. Routed to `WINDOW_NODE` as a window
672        /// resize (the rail rotation, late inset passes, and the soft keyboard ride).
673        WindowResized = 18,
674        /// Safe-area report from an edge-to-edge backend; `text` =
675        /// `"top,bottom,leading,trailing"` in px (Rust divides by density and feeds
676        /// `day_core::set_safe_area`). Node id ignored; no `Event` is emitted.
677        SafeArea = 19,
678        /// A secondary window closed (docs/windows.md); the node id is the window's root.
679        WindowClosed = 20,
680        /// A secondary window's key/active state changed; `num` != 0 ⇒ focused.
681        WindowFocused = 21,
682        /// `num` = the settled value: the drag ended (see `Event::ValueCommitted`). A backend
683        /// that cannot tell a settled value from a moving one sends only `ValueChanged`.
684        ValueCommitted = 22,
685        /// Inline search on a `.searchable()` navigation surface (docs/search.md): the field's
686        /// new text, against the nav host's node. `num` = 1 ⇒ the text was submitted (Return or
687        /// the keyboard's Search key), decoding to [`crate::Event::SearchSubmitted`].
688        SearchChanged = 23,
689        /// The toolkit's own adaptive nav container changed presentation and is reporting it
690        /// (docs/size-classes.md). `num` = 1.0 for split, 0.0 for stacked.
691        NavPresentation = 24,
692        /// The system switched between light and dark appearance. No payload; node id ignored
693        /// and no `Event` is emitted; Rust calls `day_core::note_appearance_changed`, the same
694        /// thing AppKit's and GTK's own scheme observers do.
695        AppearanceChanged = 25,
696        /// A fullscreen cover's hide transition finished (docs/cover.md); no payload, and the
697        /// node id is the cover's. Decodes to [`crate::Event::CoverHidden`].
698        CoverHidden = 26,
699        /// A styled text run's link was tapped (docs/text-runs.md); `text` = the run's target.
700        /// Decodes to [`crate::Event::LinkActivated`].
701        LinkActivated = 27,
702        /// The platform's own undo affordance fired (⌘Z, a three-finger swipe, the Edit menu
703        /// through a native front); `num` != 0 ⇒ redo.
704        UndoInvoked = 28,
705        /// A toolbar item produced a value (docs/toolbars.md): the node id is the item's
706        /// dispatch action; `text` = `"on"` with `num` != 0 ⇒ a toggle turned on, `"on"` with
707        /// 0 ⇒ off, `"sel"` with `num` = the chosen segment, `"text:<query>"` ⇒ a search
708        /// item's new text, `"submit:<query>"` ⇒ that text submitted. Decodes to
709        /// [`crate::Event::ToolbarChanged`]. A plain toolbar button sends `MenuAction`.
710        ToolbarChanged = 30,
711        /// An activated list row; `num` is its current index.
712        ListActivated = 31,
713        /// External document copied into app storage; `text` = its local locator.
714        DocumentOpened = 32,
715        /// The user's reduce-motion setting flipped (docs/accessibility.md). No payload; node
716        /// id ignored and no `Event` is emitted; Rust calls `day_core::note_motion_changed`, as
717        /// the desktop backends' own observers do.
718        ReduceMotionChanged = 33,
719        /// Text committed on the full key route (docs/menus.md "The full route"): `text` =
720        /// what the input method or the key typed, `num` = the modifier mask. Decodes to an
721        /// [`crate::Event::Key`] whose `text` is set; a key that typed nothing rides `Key`.
722        Text = 36,
723        /// A non-text key reached the focused node (docs/menus.md); `text` = the day key name
724        /// (`"ArrowLeft"`, `"5"`, …), `num` = the [`crate::KeyEvent`] modifier mask. Decodes to
725        /// [`crate::Event::Key`].
726        Key = 29,
727        /// A window's display state changed (docs/windows.md): `num` = the
728        /// [`crate::WindowState`] code (0 normal, 1 minimized, 2 maximized, 3 fullscreen), against
729        /// the window's root node, or [`crate::WINDOW_NODE`] for the primary. Decodes to
730        /// [`crate::Event::WindowStateChanged`] through [`crate::WindowState::from_code`].
731        WindowStateChanged = 34,
732        /// Native pull-to-refresh request; no payload.
733        RefreshRequested = 35,
734    }
735
736    impl BridgeKind {
737        /// Every variant, for uniqueness/parity tests and exhaustive dispatch.
738        pub const ALL: [BridgeKind; 36] = [
739            BridgeKind::Pressed,
740            BridgeKind::TextChanged,
741            BridgeKind::ToggleChanged,
742            BridgeKind::ValueChanged,
743            BridgeKind::SelectionChanged,
744            BridgeKind::NavBack,
745            BridgeKind::FrameChanged,
746            BridgeKind::Deeplink,
747            BridgeKind::PresentButton,
748            BridgeKind::PresentText,
749            BridgeKind::PresentDismissed,
750            BridgeKind::Gesture,
751            BridgeKind::Custom,
752            BridgeKind::MenuAction,
753            BridgeKind::Lifecycle,
754            BridgeKind::PresentFile,
755            BridgeKind::FocusChanged,
756            BridgeKind::Submitted,
757            BridgeKind::WindowResized,
758            BridgeKind::SafeArea,
759            BridgeKind::WindowClosed,
760            BridgeKind::WindowFocused,
761            BridgeKind::ValueCommitted,
762            BridgeKind::SearchChanged,
763            BridgeKind::NavPresentation,
764            BridgeKind::AppearanceChanged,
765            BridgeKind::CoverHidden,
766            BridgeKind::LinkActivated,
767            BridgeKind::UndoInvoked,
768            BridgeKind::Key,
769            BridgeKind::ToolbarChanged,
770            BridgeKind::ListActivated,
771            BridgeKind::DocumentOpened,
772            BridgeKind::ReduceMotionChanged,
773            BridgeKind::WindowStateChanged,
774            BridgeKind::RefreshRequested,
775        ];
776    }
777
778    #[cfg(test)]
779    mod tests {
780        use super::BridgeKind;
781
782        /// The kind-15 lesson: two meanings on one number decode silently as the first. Every
783        /// discriminant must be unique, and the table must stay dense enough to spot gaps.
784        #[test]
785        fn discriminants_are_unique() {
786            let mut seen = std::collections::BTreeSet::new();
787            for k in BridgeKind::ALL {
788                assert!(
789                    seen.insert(k as i32),
790                    "duplicate bridge kind number {} ({k:?})",
791                    k as i32
792                );
793            }
794            assert_eq!(seen.len(), BridgeKind::ALL.len());
795        }
796
797        /// `ALL` is what the uniqueness check above sees, so a variant left out of it is a variant
798        /// nothing checks, which is how `SearchChanged` and `NavPresentation` sat outside the
799        /// table. The wire numbers are assigned densely from 0, so demanding the set be exactly
800        /// `0..len` catches both a gap and an omission.
801        #[test]
802        fn table_covers_every_wire_number() {
803            let mut nums: Vec<i32> = BridgeKind::ALL.iter().map(|k| *k as i32).collect();
804            nums.sort_unstable();
805            let dense: Vec<i32> = (0..BridgeKind::ALL.len() as i32).collect();
806            assert_eq!(
807                nums, dense,
808                "bridge kinds must be dense from 0 — a missing entry means a variant no test sees"
809            );
810        }
811    }
812}
813
814#[derive(Clone, Debug, PartialEq)]
815pub enum Event {
816    Pressed,
817    TextChanged(String),
818    Submitted,
819    ToggleChanged(bool),
820    ValueChanged(f64),
821    /// A continuous control's value settled: the drag ended (mouse/touch up), or the value moved
822    /// by a discrete action (a keyboard arrow, a click on the track). Always preceded by the
823    /// `ValueChanged` carrying the same value.
824    ///
825    /// The pair exists because one gesture produces two different facts. `ValueChanged` is the
826    /// live one (bindings follow it so the UI tracks the thumb) and it fires continuously, which
827    /// is why nothing durable should key off it: a drag from 1 to 100 and back to 50 emits every
828    /// value in between. `ValueCommitted` fires once, with the value the user chose, and is what
829    /// a recording, a log, or a refetch should use.
830    ///
831    /// A backend that cannot tell the two apart emits only `ValueChanged`; its sliders then do not
832    /// record (docs/coverage-matrix.md).
833    ValueCommitted(f64),
834    SelectionChanged(i64),
835    /// A list row was activated: desktop double-click/Enter, or a touch tap.
836    /// Separate from selection so keyboard browsing need not open or play the row.
837    ListActivated(usize),
838    /// The platform's own undo affordance fired through a native front (⌘Z on the Edit menu,
839    /// a three-finger swipe, shake-to-undo); `redo` distinguishes the pair. Only backends
840    /// with a native undo system emit it; everywhere else the app's own controls call the
841    /// stack directly and this event never exists (docs/model.md).
842    Undo {
843        redo: bool,
844    },
845    /// The platform's own standard edit command fired through its native route (Edit ▸
846    /// Cut/Copy/Paste, ⌘X/⌘C/⌘V, the browser's `copy`/`paste` DOM events) with no text
847    /// widget claiming it first; the app's edit bridge answers (docs/menus.md). Transport
848    /// is the system clipboard (day-part-clipboard), not the event.
849    Edit(EditOp),
850    /// A multi-select list's selection changed: the full set of selected row indices,
851    /// ascending (empty = nothing selected). Emitted instead of `SelectionChanged` where
852    /// `ListProps::multi_select` is honored (docs/list.md).
853    SelectionSet(Vec<i64>),
854    FocusChanged(bool),
855    Tap(Point),
856    /// A link run inside a label was activated; the payload is [`TextRun::link`] verbatim.
857    LinkActivated(String),
858    LongPress(Point),
859    /// A context-menu summon reported by a toolkit that presents no native menu of its own
860    /// (web-dom): the pieces layer shows the composed menu (docs/menus.md). `local` is the
861    /// point in the node's own coordinates (what the app's provider receives); `window` the
862    /// same point in window coordinates (where the composed panel goes). Toolkits that serve
863    /// context menus natively never emit this.
864    ContextMenu {
865        local: Point,
866        window: Point,
867    },
868    /// A drag/pan gesture (docs/shapes.md). `location` is in the node's local coordinates;
869    /// `translation` is the cumulative movement since `Began`.
870    Drag {
871        phase: DragPhase,
872        location: Point,
873        translation: Point,
874    },
875    /// A pinch/magnify gesture over the node (docs/shapes.md): `scale` is cumulative since
876    /// `Began` (1.0 = unchanged), `location` the gesture's centroid in local coordinates,
877    /// the anchor a zoom keeps stationary. Only nodes that enabled
878    /// [`GestureKind::Pinch`] receive it; a backend with no recognizer emits nothing.
879    Pinch {
880        phase: DragPhase,
881        scale: f64,
882        location: Point,
883    },
884    /// A two-finger rotation over the node (docs/canvas.md "Zoom and pan"): `rotation` is in
885    /// radians, cumulative since `Began`, positive clockwise on screen; `location` the
886    /// gesture's centroid in local coordinates ([`Point::ZERO`] where the platform gives
887    /// none). A trackpad's rotate tick has no gesture session and arrives as a lone `Changed`
888    /// carrying that tick's own angle. Only nodes that enabled [`GestureKind::Rotate`]
889    /// receive it; a backend with no recognizer emits nothing.
890    Rotate {
891        phase: DragPhase,
892        rotation: f64,
893        location: Point,
894    },
895    /// A viewport pan over the node (docs/shapes.md): `delta` is the movement since the
896    /// previous event; incremental, not cumulative, because desktop wheels have no gesture
897    /// session to accumulate over (a discrete wheel tick arrives as a lone `Changed`).
898    /// Two-finger touch pans bracket theirs with `Began`/`Ended`. Distinct from
899    /// [`Event::Drag`], the primary pointer's press-drag.
900    Pan {
901        phase: DragPhase,
902        delta: Point,
903        location: Point,
904    },
905    /// The pointer moved over the node, or left it (docs/canvas.md "Interaction"). `location` is
906    /// in the node's local coordinates. Phases follow the drag vocabulary: `Began` on entry,
907    /// `Changed` for each move, `Ended` on exit, where `location` is the last point seen inside,
908    /// so a handler always knows where the pointer went out.
909    ///
910    /// Only nodes that enabled [`GestureKind::Hover`] receive it, and only on a device with a
911    /// pointer at all.
912    Hover {
913        phase: DragPhase,
914        location: Point,
915    },
916    ScrollChanged(Point),
917    /// A canvas node was re-framed by layout; re-record (§11). Nav pane/page containers
918    /// also report their allocated size with this (docs/navigation.md).
919    FrameChanged(Size),
920    /// Native back navigation (iOS back button/swipe, Android system back or toolbar up).
921    /// `already_popped` = the toolkit already performed the pop natively (iOS); the nav
922    /// host then syncs its stack without re-issuing `NavPatch::Popped`.
923    NavBack {
924        already_popped: bool,
925    },
926    /// A nav host's own adaptive container changed presentation, and Day is being told about it
927    /// after the fact (docs/size-classes.md).
928    ///
929    /// The counterpart to [`props::NavPatch::Presentation`], for the toolkits that answer
930    /// `Cap::NavRepresent = Emulated`: `UISplitViewController` collapsing as a Pro Max iPhone
931    /// rotates into portrait, `SlidingPaneLayout` deciding at measure time that two panes no
932    /// longer fit. Day did not ask for it and must not fight it; the pieces layer only
933    /// reconciles what follows, which is the selection rule (a split presentation cannot draw an
934    /// empty detail pane, so expanding with nothing selected picks the first item).
935    ///
936    /// Emitted on the NAV host node, and only when the presentation actually changed.
937    NavPresentationChanged(props::NavPresentation),
938    Key(KeyEvent),
939    Pointer(PointerEvent),
940    WindowResized(Size),
941    /// The platform asks the app to show a route (docs/navigation.md), a runtime deep link:
942    /// on web-dom, the URL hash changing under the app (hand-edited, or browser back/forward);
943    /// on mobile, a warm scheme link (iOS `application:openURL:`, Android `onNewIntent` via
944    /// `BridgeKind::Deeplink`). Emitted on [`WINDOW_NODE`] (day-core answers with `navigate()`
945    /// when the route differs from the current one) or on the active nav host's node (the nav
946    /// piece answers with `navigate()` itself, docs/deep-links.md). Launch-time deep links use
947    /// `DAY_DEEPLINK`/`set_launch_deeplink` instead; this variant is for changes while the
948    /// app runs.
949    RouteRequested(String),
950    /// A native modal answered request `req` (docs/dialogs.md).
951    PresentResult {
952        req: u64,
953        result: present::PresentResult,
954    },
955    /// A decode started by [`Toolkit::decode_image`] finished (docs/images.md).
956    ///
957    /// Keyed by request id like [`Event::PresentResult`], and for the same reason: the answer
958    /// belongs to a waiting caller, not to a tree node. It never crosses a native boundary
959    /// (every backend raises it from its own Rust arm once the platform decoder answers), so it
960    /// has no [`bridge::BridgeKind`], exactly like the completion events dialogs use in-process.
961    ///
962    /// No bitmap id rides here: day-core minted it and handed it to the backend with the bytes,
963    /// so it already knows which image a request answers for. A backend that stored the image
964    /// under that id has nothing more to say than the facts it read.
965    ImageDecoded {
966        req: u64,
967        result: Result<BitmapInfo, ImageError>,
968    },
969    /// An encode started by [`Toolkit::encode_image`] finished (docs/images.md): the encoded
970    /// bytes, or why they could not be produced.
971    ImageEncoded {
972        req: u64,
973        result: Result<Vec<u8>, ImageError>,
974    },
975    /// A canvas drawing started by [`Toolkit::render_bitmap`] finished rendering
976    /// (docs/canvas.md "Exporting"). Keyed by request id like [`Event::ImageDecoded`], and like
977    /// it carries no bitmap id: day-core minted the id and handed it over with the ops, so the
978    /// answer is only the facts of the image the backend stored under it.
979    BitmapRendered {
980        req: u64,
981        result: Result<BitmapInfo, ExportError>,
982    },
983    /// A PDF started by [`Toolkit::render_pdf`] finished (docs/canvas.md "Exporting"): the
984    /// document's bytes, or why they could not be produced.
985    PdfRendered {
986        req: u64,
987        result: Result<Vec<u8>, ExportError>,
988    },
989    /// An open, piece-defined event (§8.2). `tag` names the event for in-process emitters (a static
990    /// literal); it is empty for events that cross a native boundary (JNI/C-ABI), which carry only the
991    /// primitive `num`/`text` payload. A piece's `cx.on` reads whichever fields it needs. This is the
992    /// escape hatch for events the fixed variants above don't cover (a web view's URL, a picked date, …).
993    Custom {
994        tag: &'static str,
995        num: f64,
996        text: String,
997    },
998    /// A menu item (app menu or context menu) with this action id was activated (§ menus). day-core
999    /// routes it to the app closure registered for the id. Standard-role items don't carry an id
1000    /// (`role` items are handled natively) so they never emit this.
1001    MenuAction(u64),
1002    /// A toolbar item produced a value: a search field's text, a toggle's new state
1003    /// (docs/toolbars.md). `action` is the item's dispatch id, from the same registry
1004    /// [`Event::MenuAction`] uses, and day-core routes it to the closure registered for it.
1005    /// A plain toolbar button has no value and emits `MenuAction` instead.
1006    ToolbarChanged {
1007        action: u64,
1008        value: ToolbarValue,
1009    },
1010    /// A searchable navigation surface's field changed (docs/search.md). Emitted against the nav
1011    /// host's node, not through the toolbar's dispatch registry: search belongs to the surface,
1012    /// so the field can move between the toolbar and the navigation list without the app
1013    /// re-registering anything.
1014    SearchChanged(String),
1015    /// The user picked a different scope. Carries the index into `SearchProps::scopes`.
1016    SearchScopeChanged(usize),
1017    /// The user chose one of `SearchProps::suggestions`, by index. The toolkit has already put
1018    /// that completion in the field and emitted [`Event::SearchChanged`] for it; this says which
1019    /// one, for an app that wants to act on the choice itself.
1020    SearchSuggestionChosen(usize),
1021    /// The user submitted the inline field's text with its Return or Search key. Emitted
1022    /// after the last [`Event::SearchChanged`], with the text as submitted, for a search that
1023    /// runs on demand (a server query) rather than narrowing as the text changes.
1024    SearchSubmitted(String),
1025    /// The app moved through a lifecycle phase (docs/lifecycle.md). Backends emit this from the
1026    /// native app/activity delegate; day-core routes it to the app's `on_lifecycle` handlers.
1027    Lifecycle(Lifecycle),
1028    /// A secondary native window closed (the title-bar close, a platform gesture such as an
1029    /// app-switcher swipe or an activity finish, or `Toolkit::close_window`); emitted on the
1030    /// window's root node after the platform committed the close. day-core disposes the
1031    /// window's subtree on receipt, so native and programmatic closes share one teardown
1032    /// path (docs/windows.md). Never emitted for the primary window (its close terminates
1033    /// the app).
1034    WindowClosed,
1035    /// A secondary window's key/active state changed; emitted on the window's root node.
1036    /// day-core tracks the focused window with it (dialog parenting, dayscript targeting).
1037    WindowFocused(bool),
1038    /// A window's display state changed (docs/windows.md): the user minimized, zoomed or took it
1039    /// fullscreen, or a [`WindowChange::State`] request landed. Emitted on the window's root node
1040    /// (the primary's may arrive on [`WINDOW_NODE`]); day-core feeds the window's `state()`
1041    /// signal with it, so the app reads what the platform did rather than what it asked for.
1042    WindowStateChanged(WindowState),
1043    /// A native list committed a drag-reorder (docs/list.md): row `from` landed at row `to`.
1044    /// Emitted on the `LIST` node by the list piece's commit hook: the reorder driver
1045    /// rotates its snapshot synchronously inside the platform's drop callback, then reports
1046    /// through the event queue so the app's `on_reorder` never runs inside a native animation
1047    /// callstack.
1048    ListReorder {
1049        from: usize,
1050        to: usize,
1051    },
1052    /// A regrouping sidebar committed a drop (`props::NavMenuProps::regroup`, docs/navigation.md
1053    /// "Moving rows between sections"), in item indices into the rows as they were before the
1054    /// move: row `from` now sits in the section whose first row is item `section` (item 0 for
1055    /// rows above the first header), before item `before`, or at that section's end for
1056    /// `None`. `before` is never `from`. Emitted on the `NAV_MENU` node by a toolkit whose
1057    /// `Cap::NavReorder` is `Native`, deferred through the event queue exactly as
1058    /// [`Event::ListReorder`] is; the nav validates it against the app's rules before reporting.
1059    NavRegroup {
1060        from: usize,
1061        section: usize,
1062        before: Option<usize>,
1063    },
1064    /// A native list committed a swipe-delete (docs/list.md): the row at this index is gone.
1065    /// Deferred through the event queue exactly as [`Event::ListReorder`] is.
1066    ListDelete(usize),
1067    /// The native pull-to-refresh control requested an update. The app owns its busy state.
1068    RefreshRequested,
1069    /// A native list activated a swipe action (docs/list.md): the user pressed button `action`
1070    /// (an index into the row's [`ListSwipe::actions_at`] offer for `edge`) on row `index`, or
1071    /// swiped clear across for the edge's first action. Emitted on the `LIST` node by the list
1072    /// piece's commit hook and deferred through the event queue exactly as
1073    /// [`Event::ListReorder`] is, so the app's handler never runs inside a native animation
1074    /// callstack.
1075    ListSwipe {
1076        index: usize,
1077        edge: SwipeEdge,
1078        action: usize,
1079    },
1080    /// A fullscreen cover's hide transition finished (docs/cover.md): the content can now be
1081    /// disposed. Answers [`props::CoverPatch::Dismiss`]; delivery is a hard guarantee, and
1082    /// backends over-report rather than under-report; consumers gate on their own closing
1083    /// flag, so duplicates and belated reports are no-ops.
1084    CoverHidden,
1085    /// The user showed or hid an inspector pane through a native affordance (a dock widget's
1086    /// close button, a divider dragged shut) rather than through Day (docs/inspector.md).
1087    /// Emitted on the `kinds::INSPECTOR` node, and only when the visibility actually changed;
1088    /// the piece writes it back to the bound signal. Applying
1089    /// [`props::InspectorPatch::Visible`] must never re-emit it (the from-native echo rule).
1090    InspectorChanged(bool),
1091    /// The user disclosed or collapsed a tree row through the native affordance (docs/tree.md).
1092    /// Emitted on the `kinds::TREE` node; the piece writes it back to the app's expansion
1093    /// signal. Applying [`props::TreePatch::Expand`] must never re-emit it (the from-native
1094    /// echo rule).
1095    TreeExpanded {
1096        token: u64,
1097        expanded: bool,
1098    },
1099    /// A native tree committed a drag move (docs/tree.md): `token` now sits under `parent`
1100    /// (`None` = the root) at `index` (`None` = dropped onto the parent, an append). Deferred
1101    /// through the event queue exactly as [`Event::ListReorder`] is; the app's `on_move`
1102    /// writes its own data, whose refresh reloads the tree.
1103    TreeMove {
1104        token: u64,
1105        parent: Option<u64>,
1106        index: Option<usize>,
1107    },
1108    /// A tree's selection changed: the full set of selected row tokens (empty = cleared).
1109    /// Token-addressed, since a tree cannot speak row indices: expanding a row renumbers
1110    /// everything below it (docs/tree.md).
1111    TreeSelection(Vec<u64>),
1112}
1113
1114impl Event {
1115    /// Build a text-carrying [`Event::Custom`] (with `num` defaulted to 0), the common case for an
1116    /// in-process piece reporting a value back: `emit(node, Event::custom("webview:url", url))`.
1117    pub fn custom(tag: &'static str, text: impl Into<String>) -> Event {
1118        Event::Custom {
1119            tag,
1120            num: 0.0,
1121            text: text.into(),
1122        }
1123    }
1124}
1125
1126/// An app-lifecycle phase (docs/lifecycle.md). Each backend maps these onto its OS's native app /
1127/// activity delegate. Some phases only exist on some platforms (a mobile app enters the
1128/// background and can be low on memory, a desktop app cannot), so [`Lifecycle::is_universal`]
1129/// marks the ones every backend delivers, and [`Toolkit::supports_lifecycle`] reports per-backend
1130/// truth.
1131///
1132/// Rough native mapping:
1133///
1134/// | phase | AppKit | UIKit | GTK | Qt | Android | XAML |
1135/// |---|---|---|---|---|---|---|
1136/// | `WillLaunch` / `DidLaunch` | `applicationWill/DidFinishLaunching` | same | `startup`/mount | mount | `onCreate` | window create |
1137/// | `DidBecomeActive` | `didBecomeActive` | `didBecomeActive` | `notify::is-active` | `ApplicationActive` | `onResume` | `Activated` |
1138/// | `WillResignActive` | `willResignActive` | `willResignActive` | `notify::is-active` | `ApplicationInactive` | `onPause` | `Deactivated` |
1139/// | `WillEnterForeground` | — | `willEnterForeground` | — | — | `onStart` | — |
1140/// | `DidEnterBackground` | — | `didEnterBackground` | — | — | `onStop` | — |
1141/// | `DidReceiveMemoryWarning` | — | `didReceiveMemoryWarning` | — | — | `onTrimMemory` | — |
1142/// | `WillTerminate` | `willTerminate` | `willTerminate` | `shutdown` | `aboutToQuit` | `onDestroy` | window close |
1143/// | `DidExit` | after `willTerminate` | after `willTerminate` | `run` returned | `exec` returned | after `onDestroy` | loop returned |
1144#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1145pub enum Lifecycle {
1146    /// Before the window and UI are built: the first thing to run. Set up global state here.
1147    WillLaunch,
1148    /// The UI is mounted and the app is about to start running. Kick off startup work here.
1149    DidLaunch,
1150    /// The app came to the foreground and is the active, focused app receiving input.
1151    DidBecomeActive,
1152    /// The app is about to stop being active (an interruption, app switch, or losing focus).
1153    WillResignActive,
1154    /// The app is about to return to the foreground (mobile). Refresh what background invalidated.
1155    WillEnterForeground,
1156    /// The app left the foreground and is no longer visible (mobile). Persist state, release UI work.
1157    DidEnterBackground,
1158    /// The system is low on memory (mobile). Drop caches and non-essential memory now.
1159    DidReceiveMemoryWarning,
1160    /// The app is about to terminate: the last chance to save. Triggered by the Quit command,
1161    /// the platform's quit shortcut, or the OS reclaiming the app.
1162    WillTerminate,
1163    /// The run loop is over and nothing of the app will run after this: the last phase, after
1164    /// every `WillTerminate` handler. Day logs its exit line ("Clean exit for …") once the
1165    /// handlers have run, so a handler here is the app's last word before it.
1166    DidExit,
1167}
1168
1169impl Lifecycle {
1170    /// Every phase, in delivery order (launch → run → quit). Handy for logging/registration sweeps.
1171    pub const ALL: [Lifecycle; 9] = [
1172        Lifecycle::WillLaunch,
1173        Lifecycle::DidLaunch,
1174        Lifecycle::DidBecomeActive,
1175        Lifecycle::WillResignActive,
1176        Lifecycle::WillEnterForeground,
1177        Lifecycle::DidEnterBackground,
1178        Lifecycle::DidReceiveMemoryWarning,
1179        Lifecycle::WillTerminate,
1180        Lifecycle::DidExit,
1181    ];
1182
1183    /// True for phases every backend delivers (launch, activation, termination). The remaining
1184    /// phases (`WillEnterForeground`, `DidEnterBackground`, `DidReceiveMemoryWarning`) are mobile
1185    /// concepts and are only delivered by the mobile backends. `const` so it composes into a
1186    /// backend's `const fn lifecycle_supported` and thus into compile-time guards.
1187    pub const fn is_universal(self) -> bool {
1188        matches!(
1189            self,
1190            Lifecycle::WillLaunch
1191                | Lifecycle::DidLaunch
1192                | Lifecycle::DidBecomeActive
1193                | Lifecycle::WillResignActive
1194                | Lifecycle::WillTerminate
1195                | Lifecycle::DidExit
1196        )
1197    }
1198
1199    /// A stable, human-readable name (for logs/warnings).
1200    pub const fn name(self) -> &'static str {
1201        match self {
1202            Lifecycle::WillLaunch => "WillLaunch",
1203            Lifecycle::DidLaunch => "DidLaunch",
1204            Lifecycle::DidBecomeActive => "DidBecomeActive",
1205            Lifecycle::WillResignActive => "WillResignActive",
1206            Lifecycle::WillEnterForeground => "WillEnterForeground",
1207            Lifecycle::DidEnterBackground => "DidEnterBackground",
1208            Lifecycle::DidReceiveMemoryWarning => "DidReceiveMemoryWarning",
1209            Lifecycle::WillTerminate => "WillTerminate",
1210            Lifecycle::DidExit => "DidExit",
1211        }
1212    }
1213}
1214
1215/// The phase of a drag gesture (docs/shapes.md).
1216#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1217pub enum DragPhase {
1218    Began,
1219    Changed,
1220    Ended,
1221}
1222
1223/// A gesture a node wants delivered. Backends attach the matching native recognizer when day-core
1224/// calls [`Toolkit::enable_gesture`]; the default is no gesture (recognizers cost, so opt-in).
1225#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1226pub enum GestureKind {
1227    Tap,
1228    LongPress,
1229    Drag,
1230    /// The pointer moving over the node without pressing (docs/canvas.md "Interaction"), and
1231    /// leaving it. Delivered only where a pointer exists: every desktop, an iPad with a trackpad
1232    /// or pencil, an Android device with a mouse or stylus. A touch-only device reports none,
1233    /// which is the right answer, not a gap, so anything reachable by hover must also be
1234    /// reachable by a tap.
1235    Hover,
1236    /// Pinch/magnify (docs/shapes.md): trackpad magnification, two-finger touch pinch.
1237    Pinch,
1238    /// Rotation (docs/canvas.md "Zoom and pan"): trackpad rotate, two-finger touch twist.
1239    Rotate,
1240    /// Viewport pan (docs/shapes.md): trackpad two-finger scroll, two-finger touch pan.
1241    /// Distinct from [`GestureKind::Drag`], the primary pointer's press-drag.
1242    Pan,
1243}
1244
1245// ---------------------------------------------------------------------------
1246// Menus (app menu bar + context menus). The model is a toolkit-neutral tree; each backend renders
1247// it with its native affordance (NSMenu / GMenu+GtkPopoverMenu / QMenu / UIMenu / Android
1248// PopupMenu / XAML MenuFlyout) and its own conventions, so day imposes no menu manager of its own.
1249// ---------------------------------------------------------------------------
1250
1251/// A keyboard shortcut for a menu item. `primary` is the platform's command modifier (⌘ on Apple,
1252/// Ctrl on GTK/Qt/XAML) so one declaration reads correctly everywhere. `key` is a single character
1253/// (`"s"`, `"."`) or a named key (`"Return"`, `"Delete"`, `"Left"`, `"F1"`).
1254#[derive(Clone, Debug, PartialEq, Eq, Default)]
1255pub struct Shortcut {
1256    pub key: String,
1257    /// ⌘ (Apple) / Ctrl (elsewhere). The conventional command modifier.
1258    pub primary: bool,
1259    pub shift: bool,
1260    /// ⌥ / Alt.
1261    pub alt: bool,
1262    /// Literal Control (⌃ on Apple). Rare; prefer `primary` for the command modifier.
1263    pub control: bool,
1264}
1265
1266impl Shortcut {
1267    /// `primary`+`key` (⌘S / Ctrl+S), the common case: `Shortcut::primary("s").shift()`.
1268    pub fn primary(key: impl Into<String>) -> Shortcut {
1269        Shortcut {
1270            key: key.into(),
1271            primary: true,
1272            ..Default::default()
1273        }
1274    }
1275    /// `key` with no modifiers (e.g. `F1`, plain `Delete`).
1276    pub fn plain(key: impl Into<String>) -> Shortcut {
1277        Shortcut {
1278            key: key.into(),
1279            ..Default::default()
1280        }
1281    }
1282    pub fn shift(mut self) -> Shortcut {
1283        self.shift = true;
1284        self
1285    }
1286    pub fn alt(mut self) -> Shortcut {
1287        self.alt = true;
1288        self
1289    }
1290    pub fn control(mut self) -> Shortcut {
1291        self.control = true;
1292        self
1293    }
1294}
1295
1296/// A standard/system command. The backend supplies the native item, a selector on AppKit/UIKit
1297/// (`cut:`/`copy:`/`paste:`…) or a stock action on GTK/Qt/XAML, so it targets the focused
1298/// control, gets the platform's default label + shortcut, and enables/disables itself
1299/// automatically. This is how default items (Edit ▸ Cut/Copy/Paste, the app's Quit/About) are
1300/// accommodated without the app re-implementing them.
1301#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1302pub enum MenuRole {
1303    Cut,
1304    Copy,
1305    Paste,
1306    SelectAll,
1307    Undo,
1308    Redo,
1309    Delete,
1310    /// The app's About command (docs/settings.md). With an About registered through
1311    /// `day::register_about` the item lowers to that dispatch action (a Day-rendered About
1312    /// window, or the toolkit's own About dialog where one exists); without one AppKit shows
1313    /// its stock Info.plist panel and the other desktops show the label alone.
1314    About,
1315    Quit,
1316    Preferences,
1317    Minimize,
1318    CloseWindow,
1319    Fullscreen,
1320    /// File ▸ New Window (docs/windows.md): opens another window through the builder the
1321    /// app registered with `day::register_new_window`. No platform has a native selector
1322    /// for it, so the item lowers to the registered dispatch action (disabled when none).
1323    NewWindow,
1324    /// Check for Updates… (docs/settings.md): placed directly under About in the macOS App
1325    /// menu (the Sparkle convention) and in Help elsewhere. Lowers to the action an updater
1326    /// registered with `day::register_check_for_updates`; absent from the bar when none did.
1327    CheckForUpdates,
1328}
1329
1330/// The keyboard modifiers held at an interaction, queryable ambiently
1331/// ([`Toolkit::modifiers`]): `primary` is the platform's command key (⌘ on Apple platforms,
1332/// Ctrl elsewhere, the same convention [`Shortcut::primary`] uses). Touch-only backends
1333/// answer all-false.
1334#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1335pub struct Modifiers {
1336    pub shift: bool,
1337    pub primary: bool,
1338    pub alt: bool,
1339}
1340
1341/// A standard edit command a platform route delivered ([`Event::Edit`]).
1342#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1343pub enum EditOp {
1344    Cut,
1345    Copy,
1346    Paste,
1347    SelectAll,
1348}
1349
1350/// What the app's edit bridge can currently do, mirrored into the toolkit
1351/// ([`Toolkit::set_edit_state`]) so native menu validation enables the stock items.
1352/// `can_paste` is the app's half ("a paste handler is installed"); the toolkit combines it
1353/// with its own clipboard-has-text check where one exists.
1354#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1355pub struct EditState {
1356    pub can_cut: bool,
1357    pub can_copy: bool,
1358    pub can_paste: bool,
1359    pub can_select_all: bool,
1360}
1361
1362/// The undo stack's face, as a native front mirrors it ([`Toolkit::set_undo_state`]): what is
1363/// possible and what the menu titles should say. Labels arrive already localized: a toolkit
1364/// cannot invent translated text, the same rule as every other label in this file.
1365#[derive(Clone, Debug, PartialEq, Default)]
1366pub struct UndoState {
1367    pub can_undo: bool,
1368    pub can_redo: bool,
1369    /// The next undo unit's display label ("Rename"), empty when nothing is undoable. Fronts
1370    /// interpolate it into the platform's own title form ("Undo Rename").
1371    pub undo_label: String,
1372    pub redo_label: String,
1373}
1374
1375/// One entry in a menu (recursive: a `Submenu` nests).
1376#[derive(Clone, Debug, PartialEq)]
1377pub enum MenuItem {
1378    /// A command. `action` (nonzero) dispatches [`Event::MenuAction`] to the app; a `role`-only item
1379    /// uses the native standard command instead (action 0). `label`/`shortcut` override the role's
1380    /// defaults. `icon` is the platform's own glyph beside the title where menus carry one (macOS,
1381    /// Windows, GNOME, KDE, Android); a backend whose menus are text-only ignores it.
1382    ///
1383    /// The `id`/`action` split is [`ToolbarItem`]'s: `id` names the item and `action` is what it
1384    /// runs. They are separate because a label cannot serve as a name (it is localized, and an
1385    /// item that shows its own state changes it), so anything addressing an item from outside
1386    /// (dayscript's `menu: { id: … }`) needs something that does not move.
1387    Action {
1388        /// The app's own name for this item, where it gave one. Stable across locales and across
1389        /// a change of `checked`, and unique within the menu it is installed in.
1390        id: Option<String>,
1391        /// The item's command, as a dispatch id from the same registry [`Event::MenuAction`] uses
1392        /// (0 = no command), so a toolbar button and its menu twin can share one closure.
1393        action: u64,
1394        label: String,
1395        shortcut: Option<Shortcut>,
1396        enabled: bool,
1397        /// On/off state where the item stands for a setting or one of several choices, drawn with
1398        /// the platform's own check mark. `None` is a plain command and reserves no mark; `Some`
1399        /// makes the item checkable and says which way it currently sits.
1400        ///
1401        /// The item still runs its `action` when chosen; a backend never flips this on its own.
1402        /// The app owns the state, and re-installing the menu (`app_menu`, which re-lowers on change) is what moves
1403        /// the mark, so what the menu shows can never disagree with what the app thinks.
1404        checked: Option<bool>,
1405        role: Option<MenuRole>,
1406        icon: Option<Icon>,
1407    },
1408    /// A nested submenu. At the top level of an app menu a `role` claims one of the platform's
1409    /// standard menu-bar slots: the backend then uses this menu instead of its stock one, and
1410    /// places it where the platform expects that menu to sit.
1411    Submenu {
1412        label: String,
1413        items: Vec<MenuItem>,
1414        role: Option<MenuBarRole>,
1415    },
1416    /// A visual separator.
1417    Separator,
1418}
1419
1420/// A standard menu-bar slot (macOS's File/Edit/View/Window/Help, and their counterparts
1421/// elsewhere). A backend that has a house style for the menu bar fills every slot an app did
1422/// not claim with its own stock menu, so an app never has to restate the platform's furniture,
1423/// and can still replace any of it by tagging its own submenu with the matching role.
1424#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1425#[non_exhaustive]
1426pub enum MenuBarRole {
1427    File,
1428    Edit,
1429    View,
1430    /// KDE/Plasma's Settings menu (`Configure <App>`, Configure Shortcuts). No counterpart on
1431    /// macOS, where preferences live in the app menu, or on GNOME/Windows.
1432    Settings,
1433    /// macOS's Window menu. Windows and Linux desktops do not have one.
1434    Window,
1435    Help,
1436}
1437
1438// ---------------------------------------------------------------------------
1439// Window toolbars (docs/toolbars.md)
1440// ---------------------------------------------------------------------------
1441
1442/// A standard icon, named by what it means rather than by how it looks, so each backend can
1443/// draw the platform's own glyph for it: an SF Symbol on macOS, a freedesktop icon name on
1444/// GTK and Qt, a Fluent glyph on Windows. This is the only way an icon looks native on every
1445/// desktop at once; a bundled PNG cannot, because it is one artist's take on all four.
1446///
1447/// The set is kept small: the commands that recur across toolbars. Anything
1448/// app-specific is an [`Icon::Image`].
1449#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1450#[non_exhaustive]
1451pub enum Symbol {
1452    Add,
1453    Remove,
1454    Delete,
1455    Edit,
1456    New,
1457    Open,
1458    Save,
1459    Print,
1460    Refresh,
1461    Search,
1462    Share,
1463    Settings,
1464    Info,
1465    Star,
1466    Bookmark,
1467    Back,
1468    Forward,
1469    Up,
1470    Down,
1471    Home,
1472    /// Show/hide the sidebar, the leading item of most desktop toolbars.
1473    Sidebar,
1474    Filter,
1475    Sort,
1476    /// An overflow affordance (macOS `ellipsis`, GNOME's hamburger, Fluent `More`).
1477    More,
1478    Play,
1479    Pause,
1480    Stop,
1481    /// A photo capture: a screenshot command, a camera control.
1482    Camera,
1483    /// Source code.
1484    Code,
1485    /// Light appearance (a sun). The three below are the vocabulary of a theme chooser, which
1486    /// every platform draws with the same three ideas.
1487    Light,
1488    /// Dark appearance (a moon).
1489    Dark,
1490    /// Follow the system: the half-filled circle every platform uses for "automatic".
1491    Auto,
1492    ZoomIn,
1493    ZoomOut,
1494    /// Back to actual size: the 100% zoom command between [`Symbol::ZoomIn`] and
1495    /// [`Symbol::ZoomOut`].
1496    ZoomReset,
1497    Undo,
1498    Redo,
1499    Copy,
1500    Cut,
1501    Paste,
1502    Mail,
1503    Folder,
1504    Document,
1505    Check,
1506    Close,
1507    Warning,
1508    /// A rectangle: the shape vocabulary a drawing surface needs (docs/shapes.md), and the
1509    /// glyphs every drawing, diagram and annotation tool puts in the same place.
1510    Rectangle,
1511    /// An ellipse.
1512    Oval,
1513    /// An outlined circle: the read/unread vocabulary (a read row, its dot removed), and the
1514    /// generic ring glyph.
1515    Circle,
1516    /// A filled circle: the unread dot itself.
1517    CircleFilled,
1518    /// A straight line segment.
1519    Line,
1520    /// Combine the selection into a group: the drawing-tool command (two stacked squares).
1521    Group,
1522    /// Dissolve a group back into its members (two separated squares).
1523    Ungroup,
1524    /// Text: a line of type as a drawing element (the drawing-tool "T").
1525    Text,
1526    /// The device's own position: a map's "show my location" button (Apple's arrow, the
1527    /// crosshair elsewhere).
1528    Location,
1529}
1530
1531/// The SF Symbol each standard symbol draws as. The system's own glyphs match the user's
1532/// device: weight, optical size, accent color and all. Shared by both Apple backends
1533/// (toolbars on macOS, menus on both).
1534///
1535/// The match is exhaustive so that a new [`Symbol`] must name its glyph here rather than
1536/// silently drawing nothing on Apple. A name this OS release does not know still resolves to
1537/// no image, and the item falls back to its label.
1538pub fn sf_symbol_name(s: Symbol) -> &'static str {
1539    match s {
1540        Symbol::Add => "plus",
1541        Symbol::Remove => "minus",
1542        Symbol::Delete => "trash",
1543        Symbol::Edit => "pencil",
1544        Symbol::New => "square.and.pencil",
1545        Symbol::Open => "folder",
1546        Symbol::Save => "square.and.arrow.down",
1547        Symbol::Print => "printer",
1548        Symbol::Refresh => "arrow.clockwise",
1549        Symbol::Search => "magnifyingglass",
1550        Symbol::Share => "square.and.arrow.up",
1551        Symbol::Settings => "gearshape",
1552        Symbol::Info => "info.circle",
1553        Symbol::Star => "star",
1554        Symbol::Bookmark => "bookmark",
1555        Symbol::Back => "chevron.backward",
1556        Symbol::Forward => "chevron.forward",
1557        Symbol::Up => "chevron.up",
1558        Symbol::Down => "chevron.down",
1559        Symbol::Home => "house",
1560        Symbol::Sidebar => "sidebar.leading",
1561        Symbol::Filter => "line.3.horizontal.decrease",
1562        Symbol::Sort => "arrow.up.arrow.down",
1563        Symbol::More => "ellipsis",
1564        Symbol::Play => "play.fill",
1565        Symbol::Pause => "pause.fill",
1566        Symbol::Stop => "stop.fill",
1567        Symbol::Camera => "camera",
1568        Symbol::Code => "chevron.left.forwardslash.chevron.right",
1569        Symbol::Light => "sun.max",
1570        Symbol::Dark => "moon",
1571        Symbol::Auto => "circle.lefthalf.filled",
1572        Symbol::ZoomIn => "plus.magnifyingglass",
1573        Symbol::ZoomReset => "1.magnifyingglass",
1574        Symbol::ZoomOut => "minus.magnifyingglass",
1575        Symbol::Undo => "arrow.uturn.backward",
1576        Symbol::Redo => "arrow.uturn.forward",
1577        Symbol::Copy => "doc.on.doc",
1578        Symbol::Cut => "scissors",
1579        Symbol::Paste => "doc.on.clipboard",
1580        Symbol::Mail => "envelope",
1581        Symbol::Folder => "folder",
1582        Symbol::Document => "doc",
1583        Symbol::Check => "checkmark",
1584        Symbol::Close => "xmark",
1585        Symbol::Warning => "exclamationmark.triangle",
1586        Symbol::Rectangle => "rectangle",
1587        Symbol::Oval => "oval",
1588        Symbol::Circle => "circle",
1589        Symbol::CircleFilled => "circle.fill",
1590        Symbol::Line => "line.diagonal",
1591        Symbol::Group => "square.on.square",
1592        Symbol::Ungroup => "square.on.square.dashed",
1593        Symbol::Text => "textformat",
1594        Symbol::Location => "location",
1595    }
1596}
1597
1598/// A button or toolbar item's picture: a standard [`Symbol`] (drawn with the platform's own icon set) or
1599/// a bundled image from `resource/images` for something only this app has.
1600#[derive(Clone, Debug, PartialEq)]
1601pub enum Icon {
1602    Symbol(Symbol),
1603    /// A bundled image name, resolved the same way [`ImageName`] is elsewhere.
1604    Image(String),
1605}
1606
1607/// What a toolbar item is. The variants are the vocabulary every desktop toolbar shares; each
1608/// backend realizes one with its native control, never with a drawn imitation.
1609#[derive(Clone, Debug, PartialEq)]
1610pub enum ToolbarItemKind {
1611    /// A push button running the item's `action`.
1612    Button,
1613    /// A two-state button. `on` seeds it; the user flipping it emits
1614    /// [`ToolbarValue::On`], and the app's own writes arrive as [`ToolbarPatch::On`].
1615    Toggle { on: bool },
1616    /// A button that drops a menu: the same [`MenuItem`] model the menu bar uses, so a
1617    /// toolbar menu and its menu-bar twin are one list of commands.
1618    Menu { items: Vec<MenuItem> },
1619    /// A search field. Edits emit [`ToolbarValue::Text`]; the app's own writes arrive as
1620    /// [`ToolbarPatch::Text`].
1621    ///
1622    /// Day creates this item itself, from a `.searchable()` surface whose placement resolved to
1623    /// the toolbar (docs/search.md); apps declare search on the surface, never here.
1624    Search {
1625        text: String,
1626        placeholder: String,
1627        /// Completions for the current text, drawn by the field's own completion affordance
1628        /// where it has one (`AutoSuggestBox`, `QCompleter`, `<datalist>`). Empty = none.
1629        suggestions: Vec<String>,
1630    },
1631    /// A row of mutually exclusive choices drawn as one control: the native segmented control
1632    /// (`NSSegmentedControl`, a linked GTK/Qt button box, a XAML toggle strip, `.day-segmented`
1633    /// on the web).
1634    ///
1635    /// This is what a set of related toolbar toggles should be when exactly one of them is on at
1636    /// a time: three separate toggles say "three independent switches" to the eye and to a screen
1637    /// reader, and leave the app to keep them exclusive. Choosing a segment emits
1638    /// [`ToolbarValue::Selected`]; the app's own writes arrive as [`ToolbarPatch::Selected`].
1639    Segmented {
1640        /// One entry per segment. A segment with an icon draws it in place of its title where
1641        /// the platform does that, and keeps the title as its accessible name.
1642        segments: Vec<ToolbarSegment>,
1643        selected: usize,
1644    },
1645    /// Static text, for a status or a caption.
1646    Label,
1647    /// A divider between neighbors in the same placement bucket, where the platform draws one
1648    /// (macOS toolbars have no separator, so AppKit renders it as a fixed space,
1649    /// docs/toolbars.md). Grouping is all it does: alignment is [`ToolbarPlacement`]'s job.
1650    Separator,
1651}
1652
1653/// One choice inside a [`ToolbarItemKind::Segmented`] control.
1654#[derive(Clone, Debug, PartialEq)]
1655pub struct ToolbarSegment {
1656    /// The segment's name: its label where the platform shows text, its accessible name always.
1657    pub title: String,
1658    pub icon: Option<Icon>,
1659}
1660
1661/// The reserved id of the sidebar affordance a `nav(Sidebar)` supplies for itself
1662/// (docs/toolbars.md). Backends with a system item for the job (AppKit's
1663/// `NSToolbarToggleSidebarItem`) recognize it by this id and draw theirs instead; dayscript
1664/// recognizes it to drive the toolkit's own duty rather than an app closure.
1665pub const SIDEBAR_TOGGLE_ID: &str = "day::sidebar_toggle";
1666
1667/// The reserved id of a `.searchable()` surface's field (docs/search.md): the `ToolbarItem` a
1668/// desktop bar draws for it, and the name dayscript's `toolbar:` step drives it by wherever the
1669/// platform put it — on the bar, or inline on the navigation surface where the bar holds no
1670/// field, in which case day-core resolves the id to that host instead.
1671pub const SEARCH_ITEM_ID: &str = "day::search";
1672
1673/// One item in a window's toolbar (docs/toolbars.md).
1674#[derive(Clone, Debug, PartialEq)]
1675pub struct ToolbarItem {
1676    /// Stable identity: the native item identifier, the dayscript target, and the key a
1677    /// [`ToolbarPatch`] addresses. Unique within a toolbar.
1678    pub id: String,
1679    pub kind: ToolbarItemKind,
1680    /// The item's name. Shown beside or below the icon where the platform does that, and used
1681    /// verbatim in the overflow and customization menus, so it is never optional, even on a
1682    /// toolbar that only shows icons. It is also the item's accessible name.
1683    pub label: String,
1684    /// Hover help. Defaults to `label` where the platform expects a tooltip and none is given.
1685    pub tooltip: Option<String>,
1686    pub icon: Option<Icon>,
1687    pub enabled: bool,
1688    /// The item's command, as a dispatch id from the same registry [`Event::MenuAction`] uses
1689    /// (0 = no command), so a toolbar button and its menu twin can share one closure.
1690    pub action: u64,
1691    /// This item's role on the chrome carrying it (docs/toolbars.md). It never names a surface:
1692    /// Which chrome an item rides is decided by where the app declared it, so this says only
1693    /// where on that chrome it belongs.
1694    pub placement: ToolbarPlacement,
1695    /// Whether the item draws its title, its icon, or both, where the platform can do more than
1696    /// one. An item folded into an overflow menu shows its title whatever this asks for; a menu
1697    /// row with no words is not a menu row.
1698    pub label_style: LabelStyle,
1699    /// Draw this item in the platform's emphasized style (a tinted/filled bar button, a
1700    /// prominent `NSToolbarItem`). For the one action a chrome is really offering.
1701    pub prominent: bool,
1702    /// Which column of a multi-pane window this item came from (docs/toolbars.md), set by Day
1703    /// from the piece that declared it, never by an app.
1704    ///
1705    /// A desktop toolbar spans every column at once, and a three-pane app expects each column's
1706    /// commands to sit over that column: the sidebar's against the first divider, the list's over
1707    /// the list, the rest over the detail. That is what Mail, Notes and Finder do, and it is only
1708    /// expressible because the declaration site already said which pane the command belongs to.
1709    /// Backends that draw one undivided bar ignore it.
1710    pub column: ToolbarColumn,
1711}
1712
1713/// Which pane of a window's navigation a toolbar item was declared in (docs/toolbars.md).
1714#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1715pub enum ToolbarColumn {
1716    /// The window itself, over no particular column. Draws with the detail's items, which is
1717    /// where a command that acts on the whole window belongs when the panes are side by side.
1718    #[default]
1719    Window,
1720    /// The sidebar / master column.
1721    Sidebar,
1722    /// The content-list column between the sidebar and the detail.
1723    List,
1724    /// The detail column.
1725    Detail,
1726}
1727
1728/// Where an item sits on the chrome that carries it (docs/toolbars.md).
1729///
1730/// A placement is a role, never a surface. Which toolbar, navigation bar or column an item
1731/// rides follows from the piece that declared it, so an app never spells that out twice.
1732#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1733pub enum ToolbarPlacement {
1734    /// The natural spot on this chrome: after the leading group on a desktop toolbar, the
1735    /// trailing item group on a navigation bar, an `IF_ROOM` menu action on Android.
1736    #[default]
1737    Automatic,
1738    /// The leading edge: a pane toggle, a control that reveals what is to its left.
1739    Navigation,
1740    /// Centered: a title accessory, a transport, a status readout.
1741    Principal,
1742    /// Trailing, and the last thing a crowded chrome gives up.
1743    Primary,
1744    /// Trailing, and the first thing a crowded chrome folds into its overflow.
1745    Secondary,
1746    /// A bottom bar where the platform has one (iOS `toolbarItems`, an Android bottom app bar);
1747    /// [`ToolbarPlacement::Secondary`] everywhere else.
1748    Bottom,
1749}
1750
1751/// Which halves of an item's label a platform draws, where it can draw more than one.
1752#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1753pub enum LabelStyle {
1754    /// The platform's own convention for this chrome.
1755    #[default]
1756    Automatic,
1757    /// The icon alone (the title stays as the accessible name and the tooltip).
1758    IconOnly,
1759    /// The title alone, even where an icon was given.
1760    TitleOnly,
1761    /// Both, where the chrome has room for both.
1762    TitleAndIcon,
1763}
1764
1765/// A value a toolbar item produced.
1766#[derive(Clone, Debug, PartialEq)]
1767pub enum ToolbarValue {
1768    /// A search item's full new text.
1769    Text(String),
1770    /// A search item's text, submitted with the field's Return or Search key. Sent after the
1771    /// last [`ToolbarValue::Text`]; it changes no state of its own.
1772    Submit(String),
1773    /// A toggle item's new state.
1774    On(bool),
1775    /// A segmented item's newly chosen index.
1776    Selected(usize),
1777}
1778
1779/// A targeted update to one live toolbar item: the path that keeps a bound signal in sync
1780/// without rebuilding the bar (which would drop the search field's focus mid-keystroke).
1781#[derive(Clone, Debug, PartialEq)]
1782pub enum ToolbarPatch {
1783    /// Focus a search control and select its text without changing its value.
1784    Focus { item: String },
1785    /// Replace a search item's text.
1786    Text { item: String, text: String },
1787    /// Set a toggle item's state.
1788    On { item: String, on: bool },
1789    /// Select a segmented item's index.
1790    Selected { item: String, index: usize },
1791    /// Enable or disable any item.
1792    Enabled { item: String, on: bool },
1793    /// Replace a search item's completions (docs/search.md). Targeted rather than a rebuild,
1794    /// because these change on every keystroke and rebuilding the bar would take the field's
1795    /// focus with it.
1796    Suggestions { item: String, list: Vec<String> },
1797    /// Replace an item's words (a language change): its label, which an icon-only item still
1798    /// carries for the overflow menu and assistive technology, and its tooltip. The item keeps
1799    /// its native widget, its action and its place.
1800    Label {
1801        item: String,
1802        label: String,
1803        tooltip: Option<String>,
1804    },
1805    /// Replace a search item's empty-state prompt (docs/search.md), in the live field.
1806    Placeholder { item: String, text: String },
1807}
1808
1809impl ToolbarPatch {
1810    /// The id of the item this patch addresses.
1811    pub fn item(&self) -> &str {
1812        match self {
1813            ToolbarPatch::Focus { item }
1814            | ToolbarPatch::Text { item, .. }
1815            | ToolbarPatch::On { item, .. }
1816            | ToolbarPatch::Selected { item, .. }
1817            | ToolbarPatch::Enabled { item, .. }
1818            | ToolbarPatch::Suggestions { item, .. }
1819            | ToolbarPatch::Label { item, .. }
1820            | ToolbarPatch::Placeholder { item, .. } => item,
1821        }
1822    }
1823
1824    /// Write this patch's value into `items`, the model of a bar. `false` when no item there
1825    /// takes it (an unknown id, or a kind the value does not apply to).
1826    pub fn apply_to(&self, items: &mut [ToolbarItem]) -> bool {
1827        let Some(it) = items.iter_mut().find(|i| i.id == self.item()) else {
1828            return false;
1829        };
1830        match (self, &mut it.kind) {
1831            (ToolbarPatch::Focus { .. }, ToolbarItemKind::Search { .. }) => (),
1832            (ToolbarPatch::Text { text, .. }, ToolbarItemKind::Search { text: t, .. }) => {
1833                *t = text.clone()
1834            }
1835            (
1836                ToolbarPatch::Suggestions { list, .. },
1837                ToolbarItemKind::Search { suggestions, .. },
1838            ) => *suggestions = list.clone(),
1839            (ToolbarPatch::On { on, .. }, ToolbarItemKind::Toggle { on: o }) => *o = *on,
1840            (
1841                ToolbarPatch::Selected { index, .. },
1842                ToolbarItemKind::Segmented { segments, selected },
1843            ) if *index < segments.len() => *selected = *index,
1844            (ToolbarPatch::Enabled { on, .. }, _) => it.enabled = *on,
1845            (ToolbarPatch::Label { label, tooltip, .. }, _) => {
1846                it.label = label.clone();
1847                it.tooltip = tooltip.clone();
1848            }
1849            (
1850                ToolbarPatch::Placeholder { text, .. },
1851                ToolbarItemKind::Search { placeholder, .. },
1852            ) => *placeholder = text.clone(),
1853            _ => return false,
1854        }
1855        true
1856    }
1857}
1858
1859/// One step of an edit to a window's toolbar (docs/toolbars.md).
1860///
1861/// Day hands a backend its bar as edits, never as a whole new model to rebuild, for the same
1862/// reason the view tree arrives as `insert`/`remove` rather than as a fresh tree: an item the
1863/// edit does not name keeps its native widget, and with it the keyboard focus, the caret, a
1864/// menu that is open. A value (search text, a toggle) never travels as an edit; it is a
1865/// [`ToolbarPatch`] on the live item.
1866///
1867/// An edit lists every [`ToolbarOp::Remove`] first, then every [`ToolbarOp::Insert`] in
1868/// ascending `index`, so applying them in order to the bar's current items (a
1869/// [`ToolbarMirror`] does exactly that) produces the new bar. Items keep their relative order
1870/// across an edit: an item that moves arrives as a remove and an insert, like one whose
1871/// presentation changed.
1872#[derive(Clone, Debug, PartialEq)]
1873pub enum ToolbarOp {
1874    /// The item with this id leaves the bar.
1875    Remove { id: String },
1876    /// `item` joins the bar at `index`, its position once this edit is complete.
1877    Insert { index: usize, item: ToolbarItem },
1878}
1879
1880impl ToolbarOp {
1881    /// Apply this op to `items`, a bar's model in order.
1882    pub fn apply_to(&self, items: &mut Vec<ToolbarItem>) {
1883        match self {
1884            ToolbarOp::Remove { id } => items.retain(|i| i.id != *id),
1885            ToolbarOp::Insert { index, item } => {
1886                items.insert((*index).min(items.len()), item.clone())
1887            }
1888        }
1889    }
1890}
1891
1892/// A backend's copy of one window's toolbar, kept in step with the [`ToolbarOp`]s and
1893/// [`ToolbarPatch`]es that reach it, and the one place a backend works out where a new item
1894/// goes (docs/toolbars.md).
1895///
1896/// Every backend lays its bar out as a few groups (the leading and trailing ends of a header
1897/// bar, the columns of a split window, the primary and overflow commands of a command bar) and
1898/// keeps model order within each. So an inserted item always goes right after
1899/// [`ToolbarMirror::prev_where`] its own group, or first in the group when that is `None`, and
1900/// nothing already on the bar moves.
1901#[derive(Clone, Debug, Default)]
1902pub struct ToolbarMirror {
1903    items: Vec<ToolbarItem>,
1904}
1905
1906impl ToolbarMirror {
1907    /// The bar's items, in model order.
1908    pub fn items(&self) -> &[ToolbarItem] {
1909        &self.items
1910    }
1911
1912    pub fn is_empty(&self) -> bool {
1913        self.items.is_empty()
1914    }
1915
1916    /// The item with this id.
1917    pub fn get(&self, id: &str) -> Option<&ToolbarItem> {
1918        self.items.iter().find(|i| i.id == id)
1919    }
1920
1921    /// The item dispatching `action`: how a backend whose native bar reports only an action
1922    /// id (a menu tap) finds what was tapped.
1923    pub fn by_action(&self, action: u64) -> Option<&ToolbarItem> {
1924        self.items
1925            .iter()
1926            .find(|i| i.action == action && action != 0)
1927    }
1928
1929    /// Take the item with `id` out, returning it.
1930    pub fn remove(&mut self, id: &str) -> Option<ToolbarItem> {
1931        let at = self.items.iter().position(|i| i.id == id)?;
1932        Some(self.items.remove(at))
1933    }
1934
1935    /// Put `item` at `index` (clamped to the end).
1936    pub fn insert(&mut self, index: usize, item: ToolbarItem) {
1937        let at = index.min(self.items.len());
1938        self.items.insert(at, item);
1939    }
1940
1941    /// Apply one op to the model: what a backend that repaints its whole native bar from the
1942    /// model (a menu of actions) does with each.
1943    pub fn apply(&mut self, op: &ToolbarOp) {
1944        op.apply_to(&mut self.items);
1945    }
1946
1947    /// Write a value patch into the model. `false` when no item takes it.
1948    pub fn patch(&mut self, patch: &ToolbarPatch) -> bool {
1949        patch.apply_to(&mut self.items)
1950    }
1951
1952    /// The nearest item before `index` that `same_group` accepts: the native item a new one at
1953    /// `index` goes right after, in that group. `None` = it goes first in the group.
1954    pub fn prev_where(
1955        &self,
1956        index: usize,
1957        same_group: impl Fn(&ToolbarItem) -> bool,
1958    ) -> Option<&ToolbarItem> {
1959        self.items[..index.min(self.items.len())]
1960            .iter()
1961            .rev()
1962            .find(|i| same_group(i))
1963    }
1964}
1965
1966#[derive(Clone, Debug, PartialEq)]
1967pub struct KeyEvent {
1968    /// The key's name, in the web `KeyboardEvent.key` vocabulary every platform can map onto:
1969    /// the four arrows ("ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown") and the ten digits
1970    /// ("0" through "9", from the main row or the numeric keypad) everywhere, plus
1971    /// "Delete" and "Backspace" on backends with no menu bar ([`Cap::AppMenu`] unsupported),
1972    /// where no accelerator can own those keys. A focused piece claims every key the route
1973    /// carries, so offering them on a menu-bar platform would let a canvas swallow the Delete
1974    /// its own Edit menu was about to act on (docs/menus.md). The two delete keys keep the
1975    /// names the platform gives the physical keys (a Mac's ⌫ is "Backspace" and its ⌦ is
1976    /// "Delete"), so a handler that means "remove this" takes both. A digit arrives only while
1977    /// neither [`KeyEvent::PRIMARY`] nor [`KeyEvent::ALT`] (nor a Mac's Control) is held: ⌘1
1978    /// and Ctrl+1 are accelerators, and a canvas claiming them would starve the menu. Most
1979    /// backends name the digit the keypress types, so a layout whose number row needs Shift for
1980    /// digits reports "1" with [`KeyEvent::SHIFT`] set; XAML and ArkUI read the physical key.
1981    /// Backends emit `Event::Key` only while no text widget has focus; a field's own editing
1982    /// keys never surface here.
1983    ///
1984    /// A piece that declared `Decorate::keyboard()` takes the full route instead: every key
1985    /// the platform delivers while it is focused. A key that types nothing is named by its
1986    /// web name ([`KeyEvent::NAMED`]: "Enter", "Tab", "Escape", "Backspace", "Delete", "Home",
1987    /// "End", "PageUp", "PageDown", "Insert", the arrows and "F1" through "F12"); a key that
1988    /// types is named by its unmodified character ("a", "A" under Shift, "8", "ü" on a layout
1989    /// that has one), and what it typed rides in [`KeyEvent::text`]. Under Control or Alt the
1990    /// name stays that character ("c" with [`KeyEvent::CONTROL`] set, never the control code
1991    /// it would type). Text an input method commits (a dead-key accent, a Japanese phrase,
1992    /// the soft keyboard's word) arrives with the text alone and an empty name: no single
1993    /// key is behind it. Only the platform's command chords stay out: ⌘ on Apple platforms
1994    /// and the browser's own shortcuts belong to the menu and the browser, so a terminal's
1995    /// ⌘C still copies. [`KeyEvent::typed`] is the question a text consumer asks.
1996    pub key: String,
1997    /// A [`KeyEvent::SHIFT`]/[`KeyEvent::PRIMARY`]/[`KeyEvent::ALT`]/[`KeyEvent::CONTROL`]
1998    /// mask.
1999    pub modifiers: u8,
2000    /// The text this press committed, on the full route: what the key typed ("a", "A", "é"
2001    /// after a dead key, the whole string an input method committed at once), or `None` for
2002    /// a key that typed nothing (a named key, a Control or Alt chord, a composition still in
2003    /// progress). Separate from [`KeyEvent::key`] so that a committed "Enter" is text and the
2004    /// Enter key is a key, whatever the input method sends. Always `None` on the short route.
2005    pub text: Option<String>,
2006}
2007
2008impl KeyEvent {
2009    pub const SHIFT: u8 = 1;
2010    /// The platform's command key: ⌘ on Apple platforms, Ctrl elsewhere (the
2011    /// [`Shortcut::primary`] convention).
2012    pub const PRIMARY: u8 = 2;
2013    pub const ALT: u8 = 4;
2014    /// The Control key itself, wherever it sits: on Apple platforms it is a different key from
2015    /// [`KeyEvent::PRIMARY`] (⌘), elsewhere the same one, so a Ctrl+C on Linux sets both.
2016    /// Carried on the full route only (`Decorate::keyboard`).
2017    pub const CONTROL: u8 = 8;
2018
2019    /// The ten digit key names, indexed by value.
2020    pub const DIGITS: [&'static str; 10] = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"];
2021
2022    /// Every name the full route gives a key that types nothing (the web `KeyboardEvent.key`
2023    /// vocabulary). A key outside this list is named by the text it types.
2024    pub const NAMED: [&'static str; 26] = [
2025        "ArrowLeft",
2026        "ArrowRight",
2027        "ArrowUp",
2028        "ArrowDown",
2029        "Enter",
2030        "Tab",
2031        "Escape",
2032        "Backspace",
2033        "Delete",
2034        "Home",
2035        "End",
2036        "PageUp",
2037        "PageDown",
2038        "Insert",
2039        "F1",
2040        "F2",
2041        "F3",
2042        "F4",
2043        "F5",
2044        "F6",
2045        "F7",
2046        "F8",
2047        "F9",
2048        "F10",
2049        "F11",
2050        "F12",
2051    ];
2052
2053    /// The text this press typed ([`KeyEvent::text`]), or `None` for a key that typed nothing.
2054    pub fn typed(&self) -> Option<&str> {
2055        self.text.as_deref()
2056    }
2057
2058    /// A key that types nothing (one of [`KeyEvent::NAMED`], or a chord's character under
2059    /// Control or Alt), on either route.
2060    pub fn named(key: impl Into<String>, modifiers: u8) -> KeyEvent {
2061        KeyEvent {
2062            key: key.into(),
2063            modifiers,
2064            text: None,
2065        }
2066    }
2067
2068    /// Text a press committed on the full route. The key is named by the text when the text
2069    /// is one character (the press typed it), and left empty for a longer commit, which no
2070    /// single key is behind.
2071    pub fn typed_text(text: impl Into<String>, modifiers: u8) -> KeyEvent {
2072        let text = text.into();
2073        let mut chars = text.chars();
2074        let key = match (chars.next(), chars.next()) {
2075            (Some(_), None) => text.clone(),
2076            _ => String::new(),
2077        };
2078        KeyEvent {
2079            key,
2080            modifiers,
2081            text: Some(text),
2082        }
2083    }
2084
2085    /// Text a press committed on the full route, named by the key that produced it
2086    /// (`key`, in the vocabulary above) when the backend knows it.
2087    pub fn typed_by(key: impl Into<String>, text: impl Into<String>, modifiers: u8) -> KeyEvent {
2088        KeyEvent {
2089            key: key.into(),
2090            modifiers,
2091            text: Some(text.into()),
2092        }
2093    }
2094
2095    /// The web name for the function key `F<n>`, `1..=12`.
2096    pub fn function_name(n: u8) -> Option<&'static str> {
2097        match n {
2098            1..=12 => Some(Self::NAMED[13 + n as usize]),
2099            _ => None,
2100        }
2101    }
2102
2103    /// The key name for a typed character when it is one of the ten digits: what a backend
2104    /// reports for a keypress that types `0`–`9`.
2105    pub fn digit_name(c: char) -> Option<&'static str> {
2106        c.to_digit(10).map(|d| Self::DIGITS[d as usize])
2107    }
2108
2109    /// The value of a digit key, or `None` for every other key.
2110    pub fn digit(&self) -> Option<u8> {
2111        match self.key.as_bytes() {
2112            [d @ b'0'..=b'9'] => Some(d - b'0'),
2113            _ => None,
2114        }
2115    }
2116
2117    pub fn shift(&self) -> bool {
2118        self.modifiers & Self::SHIFT != 0
2119    }
2120    pub fn primary(&self) -> bool {
2121        self.modifiers & Self::PRIMARY != 0
2122    }
2123    pub fn alt(&self) -> bool {
2124        self.modifiers & Self::ALT != 0
2125    }
2126    pub fn control(&self) -> bool {
2127        self.modifiers & Self::CONTROL != 0
2128    }
2129}
2130
2131#[cfg(test)]
2132mod key_event_tests {
2133    use super::KeyEvent;
2134
2135    #[test]
2136    fn digit_names_read_back_as_values() {
2137        for (value, c) in ('0'..='9').enumerate() {
2138            let name = KeyEvent::digit_name(c).expect("an ASCII digit names itself");
2139            let key = KeyEvent::named(name, 0);
2140            assert_eq!(key.digit(), Some(value as u8));
2141        }
2142        // Only the ASCII digits: a letter, an Arabic-Indic three, and a named key are not.
2143        assert_eq!(KeyEvent::digit_name('a'), None);
2144        assert_eq!(KeyEvent::digit_name('٣'), None);
2145        let arrow = KeyEvent::named("ArrowUp", 0);
2146        assert_eq!(arrow.digit(), None);
2147    }
2148
2149    #[test]
2150    fn typed_text_is_told_from_named_keys() {
2151        let a = KeyEvent::typed_text("a", 0);
2152        assert_eq!((a.key.as_str(), a.typed()), ("a", Some("a")));
2153        let space = KeyEvent::typed_text(" ", 0);
2154        assert_eq!((space.key.as_str(), space.typed()), (" ", Some(" ")));
2155        assert_eq!(KeyEvent::typed_text("7", 0).digit(), Some(7));
2156        // A longer commit has no key behind it.
2157        let phrase = KeyEvent::typed_text("こんにちは", 0);
2158        assert_eq!(
2159            (phrase.key.as_str(), phrase.typed()),
2160            ("", Some("こんにちは"))
2161        );
2162        // Text that spells a key name is still text, and the key is still a key.
2163        for name in KeyEvent::NAMED {
2164            assert_eq!(
2165                KeyEvent::named(name, 0).typed(),
2166                None,
2167                "{name} types nothing"
2168            );
2169            assert_eq!(KeyEvent::typed_text(name, 0).typed(), Some(name));
2170        }
2171        let accent = KeyEvent::typed_by("e", "é", 0);
2172        assert_eq!((accent.key.as_str(), accent.typed()), ("e", Some("é")));
2173        assert_eq!(KeyEvent::function_name(1), Some("F1"));
2174        assert_eq!(KeyEvent::function_name(12), Some("F12"));
2175        assert_eq!(KeyEvent::function_name(13), None);
2176        let chord = KeyEvent::named("c", KeyEvent::CONTROL | KeyEvent::SHIFT);
2177        assert!(chord.control() && chord.shift() && !chord.primary());
2178        assert_eq!(chord.typed(), None);
2179    }
2180
2181    #[test]
2182    fn a_declaration_claims_nothing_without_a_handler() {
2183        let node = super::NodeId(0xdead_0001);
2184        super::keys::mark_text(node);
2185        assert!(!super::keys::text(node), "no handler, no claim");
2186        super::keys::mark(node);
2187        assert!(super::keys::text(node) && super::keys::handled(node));
2188        super::keys::forget(node);
2189        assert!(!super::keys::text(node) && !super::keys::handled(node));
2190    }
2191}
2192
2193#[derive(Clone, Copy, Debug, PartialEq)]
2194pub struct PointerEvent {
2195    pub position: Point,
2196    pub down: bool,
2197}
2198
2199/// The event sink: enqueue-only. It may be invoked re-entrantly from inside any Toolkit method;
2200/// day-core drains queued events at safe points, each as a fresh batch (§3.3).
2201pub type EventSink = Box<dyn Fn(NodeId, Event)>;
2202
2203/// The synchronous row-pull closures for recycling lists (docs/list.md, §10). day-core injects one
2204/// per `LIST` host via [`Toolkit::attach_list`]; a recycling backend stores it and calls it from
2205/// its native data-source (on the UI thread, outside any day-core borrow). Each closure re-enters
2206/// day-core, so, unlike [`EventSink`], these run to completion synchronously (`bind_row` even
2207/// flushes + lays out the row before returning, so the host can measure the cell immediately).
2208#[derive(Clone)]
2209pub struct ListSource {
2210    /// Report the first actually visible row (exclude overscan). Enqueue-only; optional,
2211    /// so hosts without a viewport binding incur no app event work.
2212    pub first_visible: Option<std::rc::Rc<dyn Fn(usize)>>,
2213    /// Current row count.
2214    pub len: std::rc::Rc<dyn Fn() -> usize>,
2215    /// Present on a sectioned list (`ListProps::sections`, docs/list.md "Sections"): whether
2216    /// row `index` is a section header. Every row index the host sees counts headers, and
2217    /// day-core translates to the app's items. A header row is not selectable, activatable or
2218    /// swipeable; the host draws it in its platform's group-header style, sized to its content
2219    /// even in a `Uniform` list, and floats it where the platform does (macOS group rows,
2220    /// UIKit plain-table section headers).
2221    pub is_header: Option<std::rc::Rc<dyn Fn(usize) -> bool>>,
2222    /// Stable identity token for the row at `index` (for native diffing / animation).
2223    pub token_at: std::rc::Rc<dyn Fn(usize) -> u64>,
2224    /// Build (first use of this cell) or rebind (recycled cell) row `index` into the native cell.
2225    pub bind_row: std::rc::Rc<dyn Fn(usize, RawHandle)>,
2226    /// A host that emulates `Cap::ListSections` binds the header it pins over the top of the
2227    /// list with this instead of `bind_row` (docs/list.md "Sections"): the same build or
2228    /// rebind, but the copy carries no element ids, so a dayscript or accessibility lookup of a
2229    /// header finds the header row in the list, never its pinned copy.
2230    pub bind_pinned: std::rc::Rc<dyn Fn(usize, RawHandle)>,
2231    /// The native cell left the viewport; Day may drop per-cell bookkeeping (optional).
2232    pub recycle: std::rc::Rc<dyn Fn(RawHandle)>,
2233    /// The native host is done with this cell for good (a `GtkListItemFactory::teardown`, a
2234    /// `UITableViewCell` deallocating): Day disposes the row it built there, its scope, nodes
2235    /// and element ids. Without this a host that discards cells, as every pool does on a far
2236    /// jump, leaves one dead row behind in day-core per discarded cell. Safe inside a day-core
2237    /// borrow (the work is held for the borrow's end) and for a cell Day never saw.
2238    pub release: std::rc::Rc<dyn Fn(RawHandle)>,
2239    /// Re-lay the row bound to this cell at `width`, called from the cell's own native layout
2240    /// pass, the hook [`TreeSource::layout_cell`] already gives trees. day-core lays a row at the
2241    /// `LIST`'s width first, which is right wherever the cell is the row itself; a backend
2242    /// whose native row wraps the cell in chrome (GtkListView's themed `row` node pads it)
2243    /// corrects it here, so the row fits the cell the platform gave it instead of holding the
2244    /// whole list wider than its frame. Skips quietly when called inside a day-core borrow (a
2245    /// snapshot pass).
2246    pub layout_cell: std::rc::Rc<dyn Fn(RawHandle, f64)>,
2247    /// The height day-core last laid the row bound to this cell at: the row's own height,
2248    /// padding included, as `RowHeight` resolves it. A backend whose cell measures itself
2249    /// (GtkListView's `DayCell`) reports it as the cell's height, so a padded row keeps its
2250    /// bottom padding rather than the height of its last child's frame. `0.0` before the row's
2251    /// first layout, or inside a day-core borrow.
2252    pub cell_height: std::rc::Rc<dyn Fn(RawHandle) -> f64>,
2253    /// Drag-to-reorder closures, present when `ListProps::reorderable` (docs/list.md). `None` on
2254    /// non-reorderable lists; backends must not enable their drag machinery without it.
2255    pub reorder: Option<ListReorder>,
2256    /// Swipe-to-delete closures, present when `ListProps::deletable` (docs/list.md). `None` on
2257    /// non-deletable lists; backends must not offer their delete affordance without it.
2258    pub delete: Option<ListDelete>,
2259    /// Swipe-actions closures, present when `ListProps::swipe_actions` (docs/list.md). `None` on
2260    /// lists that declared none; backends must not install their row-action machinery
2261    /// without it.
2262    pub swipe: Option<ListSwipe>,
2263}
2264
2265/// The synchronous drag-to-reorder half of [`ListSource`] (docs/list.md). Both closures follow
2266/// `bind_row`'s discipline: called on the UI thread from inside native drag callbacks, outside
2267/// any day-core borrow, and they run to completion synchronously.
2268#[derive(Clone)]
2269pub struct ListReorder {
2270    /// May row `from` drop at row `to`? Called from the native validate/hover hook so the
2271    /// affordance (gap, insertion mark, forbidden cursor) reflects the app's answer live.
2272    /// Returns the accepted target index: `to` itself to allow, another index to retarget the
2273    /// drop, or `-1` to deny.
2274    pub can_move: std::rc::Rc<dyn Fn(usize, usize) -> i64>,
2275    /// Commit: row `from` dropped at row `to` (an index `can_move` accepted). Rotates Day's row
2276    /// snapshot before returning (so `len`/`token_at`/`bind_row` reflect the new order while the
2277    /// native move animates) and defers the app's own callback to the next event drain.
2278    pub move_row: std::rc::Rc<dyn Fn(usize, usize)>,
2279}
2280
2281/// The synchronous swipe-to-delete half of [`ListSource`] (docs/list.md), shaped exactly like
2282/// [`ListReorder`]: both closures are called on the UI thread from inside native swipe callbacks,
2283/// outside any day-core borrow, and run to completion synchronously.
2284///
2285/// Each platform spells the gesture its own way (a trailing swipe action on iOS, an
2286/// `ItemTouchHelper` swipe on Android, a `ListItem` swipe action on ArkUI), but all three ask the
2287/// same two questions, so this struct is one pair of closures rather than three shapes.
2288#[derive(Clone)]
2289pub struct ListDelete {
2290    /// May row `index` be deleted? Called before the affordance is offered, so a row the app
2291    /// protects shows no delete action at all rather than one that fails on use.
2292    pub can_delete: std::rc::Rc<dyn Fn(usize) -> bool>,
2293    /// Commit: delete row `index`. Removes it from Day's row snapshot before returning (so
2294    /// `len`/`token_at`/`bind_row` already reflect the shorter list while the native row-removal
2295    /// animates) and defers the app's own callback to the next event drain.
2296    pub delete_row: std::rc::Rc<dyn Fn(usize)>,
2297}
2298
2299/// Which edge of a row a swipe action rides (docs/list.md). Semantic, not geometric:
2300/// `Leading` follows the reading direction (the left edge in LTR, the right in RTL), the
2301/// mapping every platform's swipe API already makes.
2302#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2303pub enum SwipeEdge {
2304    Leading,
2305    Trailing,
2306}
2307
2308/// One offered swipe action (docs/list.md): pure data. The pieces layer keeps the handlers;
2309/// the backend answers a tap through [`ListSwipe::perform`] by index into the offer.
2310#[derive(Clone, Debug, PartialEq)]
2311pub struct ListSwipeAction {
2312    /// The word on the button, already localized (a toolkit cannot translate).
2313    pub label: String,
2314    /// Destructive styling: the platform's red.
2315    pub destructive: bool,
2316    /// Explicit button color; `None` = the platform's default for the style.
2317    pub tint: Option<Color>,
2318    /// A glyph for the button where the platform draws one: above the label on macOS, in
2319    /// place of it on iOS (docs/list.md).
2320    pub symbol: Option<Symbol>,
2321}
2322
2323/// The synchronous swipe-actions half of [`ListSource`] (docs/list.md), the generalized
2324/// sibling of [`ListDelete`]: reveal-as-you-swipe buttons on either row edge. The offer is
2325/// pulled per row at gesture time, so labels follow row state ("Mark Read" on an unread row,
2326/// "Mark Unread" on a read one); the commit defers to the event drain like every closure here.
2327#[derive(Clone)]
2328pub struct ListSwipe {
2329    /// The offer: the actions for row `index` on `edge`, called inside the platform's swipe
2330    /// callback, so keep it pure. Empty = no affordance for that row and edge. The first action
2331    /// is the full-swipe action where the platform activates one at the far edge.
2332    pub actions_at: std::rc::Rc<dyn Fn(usize, SwipeEdge) -> Vec<ListSwipeAction>>,
2333    /// The commit: the user activated action `action` (an index into the offer) on row
2334    /// `index`, `edge`. Unlike a delete this never reshapes the row snapshot; the app's
2335    /// handler is deferred to the next event drain, never run inside the native callback.
2336    pub perform: std::rc::Rc<dyn Fn(usize, SwipeEdge, usize)>,
2337}
2338
2339/// The synchronous row-pull closures for hierarchical trees (docs/tree.md): [`ListSource`]'s
2340/// shape, addressed by token instead of row index, because expanding a row renumbers every
2341/// index below it while tokens hold still. day-core injects one per `TREE` host via
2342/// [`Toolkit::attach_tree`]; the backend answers its native data-source from it. The same
2343/// synchronous discipline as [`ListSource`]: UI thread, outside any day-core borrow;
2344/// `bind_row` flushes and lays the row out before returning.
2345#[derive(Clone)]
2346pub struct TreeSource {
2347    /// How many children `parent` has (`None` = the root level).
2348    pub children_len: std::rc::Rc<dyn Fn(Option<u64>) -> usize>,
2349    /// The i-th child of `parent`: the stable token every backend keys its rows by.
2350    pub child_token: std::rc::Rc<dyn Fn(Option<u64>, usize) -> u64>,
2351    /// Whether this token can hold children at all: what draws (or omits) the disclosure.
2352    pub expandable: std::rc::Rc<dyn Fn(u64) -> bool>,
2353    /// Non-selectable section heading, separate from a navigation destination.
2354    pub section_header: std::rc::Rc<dyn Fn(u64) -> bool>,
2355    /// Current desired expansion, including restoration before the first native reload.
2356    pub expanded: std::rc::Rc<dyn Fn(u64) -> bool>,
2357    /// Build (first use of this cell) or rebind (recycled cell) the row for `token` into the
2358    /// native cell.
2359    pub bind_row: std::rc::Rc<dyn Fn(u64, RawHandle)>,
2360    /// The native cell left the viewport; Day may drop per-cell bookkeeping (optional).
2361    pub recycle: std::rc::Rc<dyn Fn(RawHandle)>,
2362    /// Re-lay the row bound to this cell at `width`, called from the cell's own native
2363    /// layout pass. Trees need this where lists don't: indentation makes every cell's
2364    /// content width per-row, so the host-width layout `bind_row` did is only a first
2365    /// approximation. Skips quietly when called inside a day-core borrow (a snapshot pass).
2366    pub layout_cell: std::rc::Rc<dyn Fn(RawHandle, f64)>,
2367    /// Native bounds for controls whose group headers have a different height from leaves.
2368    /// Overrides the initial row-height estimate and preserves the native height on rebind.
2369    pub layout_cell_size: std::rc::Rc<dyn Fn(RawHandle, Size)>,
2370    /// The height day-core last laid this cell's row at (see [`ListSource::cell_height`]).
2371    pub cell_height: std::rc::Rc<dyn Fn(RawHandle) -> f64>,
2372    /// The row's type-ahead string (docs/tree.md): what native type-select matches against.
2373    pub type_select_text: std::rc::Rc<dyn Fn(u64) -> String>,
2374    /// The row's context menu, built when the menu is summoned (docs/menus.md "Dynamic context
2375    /// menus"), called on the UI thread from the platform's own menu callback, outside any
2376    /// day-core borrow, like every closure here. `None` = rows carry no menu; an empty
2377    /// result suppresses the menu for that row.
2378    pub row_menu: Option<std::rc::Rc<dyn Fn(u64) -> Vec<MenuItem>>>,
2379    /// Drag-to-move closures, present when `TreeProps::movable` (docs/tree.md). `None` on
2380    /// immovable trees; backends must not enable their drag machinery without it.
2381    pub moves: Option<TreeMoves>,
2382}
2383
2384/// The synchronous drag half of [`TreeSource`] (docs/tree.md). Both closures follow
2385/// `bind_row`'s discipline: called on the UI thread from inside native drag callbacks.
2386#[derive(Clone)]
2387pub struct TreeMoves {
2388    /// The live verdict, consulted while the drag is over a target: may `token` land under
2389    /// `parent` at `index`? `index: None` means "dropped onto the parent" (append). Pure, since
2390    /// it runs inside the platform's drag-validate callback.
2391    #[allow(clippy::type_complexity)]
2392    pub can_move: std::rc::Rc<dyn Fn(u64, Option<u64>, Option<usize>) -> MoveVerdict>,
2393    /// Commit an accepted drop. Defers the app's `on_move` through the event queue
2394    /// ([`Event::TreeMove`]); the app's own data write drives the reload.
2395    #[allow(clippy::type_complexity)]
2396    pub move_node: std::rc::Rc<dyn Fn(u64, Option<u64>, Option<usize>)>,
2397}
2398
2399/// A summon-time context-menu provider (docs/menus.md): local-point in, menu out.
2400pub type ContextMenuFn = std::rc::Rc<dyn Fn(Point) -> Vec<MenuItem>>;
2401
2402/// A tree move guard's verdict (docs/tree.md). No `Retarget` yet: the drop vocabulary is
2403/// already positional, so a guard that wants a different target denies and the user drops
2404/// where it is allowed.
2405#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2406pub enum MoveVerdict {
2407    Allow,
2408    Deny,
2409}
2410
2411/// One addressable widget within a composite native backing (docs/tree.md,
2412/// docs/tweaks.md), Qt's name for the concept (`QStyle::SubControl`). A `list`'s or
2413/// `tree`'s node handle is its scroller; `Subcontrol::Content` is the widget inside it.
2414/// Backends resolve an unknown subcontrol to `None`, never to the host.
2415#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
2416pub enum Subcontrol {
2417    /// The node's own handle: what every tweak accessor reached before subcontrols existed.
2418    Host,
2419    /// The content widget inside the scroller (`NSOutlineView`, `NSTableView`, …).
2420    Content,
2421    /// The header view, where the widget has one. Day's lists and trees ship headerless, so
2422    /// this answers `None` until a kind grows a header.
2423    Header,
2424}
2425
2426// ---------------------------------------------------------------------------
2427// Capabilities, animation, a11y
2428// ---------------------------------------------------------------------------
2429
2430/// What to show on the app's icon in the Dock, launcher, home screen, or taskbar (docs/badge.md).
2431///
2432/// Distinct from `NavItem::badge`, which annotates a sidebar row inside the window. This one
2433/// decorates the application itself and is drawn by the shell, not by Day.
2434///
2435/// What each payload needs is asked separately (`Cap::AppBadgeCount`, `AppBadgeText`,
2436/// `AppBadgeDot`) because the platforms differ in what they accept more than in whether they have
2437/// a badge at all: macOS takes arbitrary text, iOS and the web take a number, Android takes nothing.
2438#[derive(Clone, Debug, PartialEq, Eq, Default)]
2439pub enum AppBadge {
2440    /// Clear the badge.
2441    #[default]
2442    None,
2443    /// A count. Zero clears it, matching every platform's own convention.
2444    Count(u32),
2445    /// Short arbitrary text (`"99+"`, `"beta"`). Only macOS renders it; probe `Cap::AppBadgeText`.
2446    Text(String),
2447    /// An indicator with no value.
2448    Dot,
2449}
2450
2451/// How wide a window is, in coarse buckets (docs/size-classes.md).
2452///
2453/// The breakpoints are Android's window size classes, in density-independent points, and they are
2454/// used verbatim on every backend rather than per-platform. One table means one answer: a 700pt
2455/// window is [`WidthClass::Medium`] on a Mac, in a browser, and on a tablet, so an app that lays
2456/// out from the class gets the same layout at the same size everywhere. Apple publishes only two
2457/// buckets (compact/regular); those map onto this table rather than replacing it, with
2458/// [`WidthClass::Compact`] the compact one and everything above it regular.
2459#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug, Default)]
2460pub enum WidthClass {
2461    /// `< 600dp`: a phone in portrait. One pane at a time.
2462    #[default]
2463    Compact,
2464    /// `600–839dp`: a tablet in portrait, a narrow desktop window.
2465    Medium,
2466    /// `840–1199dp`: a tablet in landscape, a typical desktop window.
2467    Expanded,
2468    /// `1200–1599dp`: a large desktop window.
2469    Large,
2470    /// `≥ 1600dp`: a maximized window on a big display.
2471    ExtraLarge,
2472}
2473
2474/// How tall a window is (docs/size-classes.md). Consulted far less than [`WidthClass`]: it is
2475/// what tells a phone in landscape (wide enough for two panes, too short for a tall list) that
2476/// it should not grow vertical chrome.
2477#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug, Default)]
2478pub enum HeightClass {
2479    /// `< 480dp`: a phone in landscape.
2480    #[default]
2481    Compact,
2482    /// `480–899dp`: a phone in portrait, a tablet in landscape.
2483    Medium,
2484    /// `≥ 900dp`: a tablet in portrait, most desktop windows.
2485    Expanded,
2486}
2487
2488/// A window's size class (docs/size-classes.md), reported by the backend and read by apps
2489/// through `day::size_class()`.
2490///
2491/// Per-window, not per-app: two windows of one process can sit in different classes at the same
2492/// time (a narrow and a wide window side by side, iPadOS Stage Manager, Android split-screen), and
2493/// an app that keyed off a single global would lay the second window out for the first one's size.
2494#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
2495pub struct SizeClass {
2496    pub width: WidthClass,
2497    pub height: HeightClass,
2498}
2499
2500impl SizeClass {
2501    /// The `Compact`/`Medium` width boundary in dp: the narrowest window where a second
2502    /// pane starts to fit. Backends that hand an adaptive container its pane widths derive
2503    /// them from this (Android's list + minimum-detail widths sum to it), so the platform's
2504    /// measure-time decision and this table agree by construction (docs/size-classes.md).
2505    pub const SPLIT_MIN_WIDTH: f64 = 600.0;
2506
2507    /// Bucket a window's size in points. The one place the breakpoint numbers appear.
2508    pub fn from_size(width: f64, height: f64) -> Self {
2509        SizeClass {
2510            width: match width {
2511                w if w >= 1600.0 => WidthClass::ExtraLarge,
2512                w if w >= 1200.0 => WidthClass::Large,
2513                w if w >= 840.0 => WidthClass::Expanded,
2514                w if w >= Self::SPLIT_MIN_WIDTH => WidthClass::Medium,
2515                _ => WidthClass::Compact,
2516            },
2517            height: match height {
2518                h if h >= 900.0 => HeightClass::Expanded,
2519                h if h >= 480.0 => HeightClass::Medium,
2520                _ => HeightClass::Compact,
2521            },
2522        }
2523    }
2524
2525    /// Whether a two-pane presentation fits. The rule behind an automatic
2526    /// [`props::NavPresentation`]: anything wider than compact gets both panes.
2527    pub fn prefers_split(self) -> bool {
2528        self.width > WidthClass::Compact
2529    }
2530}
2531
2532#[derive(Clone, Copy, PartialEq, Eq, Debug)]
2533pub enum Cap {
2534    /// Standard searchfield control.
2535    SearchField,
2536    /// Standard combobox control.
2537    ComboBox,
2538    /// Standard stepper control.
2539    Stepper,
2540    /// Standard datetime control.
2541    DateTimePicker,
2542    /// Standard colorpicker control.
2543    ColorPicker,
2544    /// Standard pullrefresh control.
2545    PullRefresh,
2546    /// Standard pager control.
2547    Pager,
2548    /// User-driven pull recognition, separate from a refresh indicator.
2549    PullRefreshGesture,
2550
2551    /// Native data-transfer source and destination callbacks.
2552    DragDrop,
2553    /// Transfers between independent native applications (inbound).
2554    DragExternalImport,
2555    /// Transfers to independent native applications, including arbitrary binary MIME data.
2556    DragExternalExport,
2557    /// Lossless ordered items and alternatives between Day applications.
2558    DragMultipleItems,
2559    /// Existing native file references, distinct from promised/generated files.
2560    DragFileReferences,
2561    /// Native result can wait for asynchronous data receipt.
2562    DragDeferredReceipt,
2563    /// Generated files supplied to a destination after dropping.
2564    DragFilePromises,
2565    /// External move acknowledgment safe for source deletion.
2566    DragExternalMove,
2567    ListRecycling,
2568    /// The toolkit fronts the app's undo stack with the platform's own undo system
2569    /// ([`Toolkit::set_undo_state`] + `Event::Undo`): `Native` where one exists
2570    /// (`NSUndoManager` on macOS/iOS, `QUndoStack`), `Unsupported` everywhere else, where
2571    /// Day's menu items and accelerators drive the stack directly and nothing platform-owned
2572    /// needs mirroring (docs/model.md).
2573    UndoBridge,
2574    /// The toolkit routes the platform's standard Cut/Copy/Paste to the app's edit bridge
2575    /// ([`Toolkit::set_edit_state`] + `Event::Edit`): the same menu items, shortcuts, and
2576    /// responder precedence the platform's text editing uses; a focused text widget keeps
2577    /// its own clipboard behavior, everything else reaches the app (docs/menus.md).
2578    /// `Native` where a system route exists (the responder chain, the browser's clipboard
2579    /// events), `Emulated` where Day's own menu items dispatch it, `Unsupported` elsewhere.
2580    EditBridge,
2581    /// The toolkit realizes `ListProps::reorderable` as drag-to-reorder rows: `Native` when the
2582    /// platform's own mechanism drives it (NSTableView drag/drop, UITableView drag delegates,
2583    /// ItemTouchHelper, …), `Emulated` for a pointer-tracked fake (web-dom). `Unsupported` ⇒ the
2584    /// list renders normally but rows cannot be dragged (docs/list.md).
2585    ListReorder,
2586    /// Sidebar destinations can be dragged to reorder (`NavBuilder::reorder_items`) and between
2587    /// sections (`NavBuilder::regroup_items`). `Native` when the toolkit's own sidebar drags them
2588    /// (`NavMenuProps::movable`, and across headers under `NavMenuProps::regroup`); `Emulated`
2589    /// when Day stands a reorderable list in for the sidebar. Independent of `ListReorder`: UIKit
2590    /// supports draggable content lists but retains its native navigation collection for
2591    /// sidebars.
2592    NavReorder,
2593    /// The toolkit realizes `ListProps::deletable` as the platform's delete gesture:
2594    /// `Native` where the platform ships one (UIKit's trailing swipe actions, Android's
2595    /// `ItemTouchHelper`, ArkUI's `ListItem.swipeAction`), `Unsupported` on the desktop toolkits,
2596    /// whose lists have no swipe idiom and where deletion belongs to a menu or a button
2597    /// (docs/list.md).
2598    ListDelete,
2599    /// The toolkit realizes `ListProps::swipe_actions` as edge swipe actions: buttons
2600    /// that reveal as the row tracks the swipe, with the far edge activating the first one
2601    /// (docs/list.md). `Native` where the platform ships the affordance: macos-appkit
2602    /// (`NSTableView` row actions, Mail's own machinery) and ios-uikit
2603    /// (`UISwipeActionsConfiguration`). `Unsupported` everywhere else: the affordance is
2604    /// absent, and the app's command lives in its explicit controls.
2605    ListSwipeActions,
2606    /// The toolkit realizes `ListProps::editing` as the platform's list editing mode: rows
2607    /// show their delete controls and reorder grips while the list is editing (docs/list.md).
2608    /// `Native` on ios-uikit (`UITableView` editing). `Unsupported` everywhere else, where a
2609    /// list has no separate editing mode: its rows already drag, swipe and open menus as they
2610    /// are, and the list renders as if `editing` were off.
2611    ListEditing,
2612    /// The toolkit realizes `kinds::LIST_ITEM` as its own list row content (docs/list.md "List
2613    /// items"): `Native` where the platform has a standard row it draws itself (UIKit's
2614    /// `UIListContentConfiguration`, a Material list item, AppKit's image-and-text table cell,
2615    /// a GTK row box), so the row takes the platform's fonts, icon size, spacing, secondary
2616    /// colors and check mark. `Unsupported` ⇒ the `list_item` piece composes the same content
2617    /// from plain pieces. Apps have no reason to probe this; the piece does.
2618    ListItem,
2619    /// The toolkit realizes `kinds::TREE` as a hierarchical tree view (docs/tree.md):
2620    /// `Native` where a platform tree widget hosts Day-built rows (NSOutlineView, the UIKit
2621    /// sidebar list, GtkListView+TreeListModel, WinUI TreeView, ArkTS TreeView), `Emulated`
2622    /// where Day flattens the tree onto its list machinery, `Unsupported` where neither
2623    /// exists yet. An app gates its tree UI on this answer rather than showing a placeholder.
2624    Tree,
2625    /// The toolkit realizes `TreeProps::movable` as drag-to-reparent/restack rows
2626    /// (docs/tree.md). A strictly smaller set than [`Cap::Tree`]: a backend can render a
2627    /// tree it cannot yet drag within.
2628    TreeMove,
2629    /// Native two-level section headers; general trees may still be composed.
2630    TreeSections,
2631    /// The toolkit answers [`Toolkit::first_baseline`], so rows can align text on its baseline
2632    /// rather than on the middle of its box (docs/baseline.md). `Native` where the platform
2633    /// reports the baseline itself (`NSView.firstBaselineOffsetFromTop`, `View.getBaseline`,
2634    /// `gtk_widget_measure`), `Emulated` where Day derives it from the widget's font metrics,
2635    /// `Unsupported` ⇒ baseline-aligned rows fall back to centering and look exactly as they do
2636    /// today.
2637    BaselineAlignment,
2638    /// The toolkit draws a label's [`TextRun`]s: bold, italic, color or a monospace face within
2639    /// one wrapping paragraph (docs/text-runs.md). `Unsupported` ⇒ the label renders its text
2640    /// uniformly, which reads correctly and loses only the emphasis.
2641    TextRuns,
2642    /// The toolkit makes a run carrying [`TextRun::link`] activatable, emitting
2643    /// [`Event::LinkActivated`]. A strictly smaller set than [`Cap::TextRuns`]: several toolkits
2644    /// draw a link run in link colors but have no way to hit-test it, and one (Android) can do
2645    /// links or selection but not both (docs/text-runs.md).
2646    TextLinks,
2647    Lottie,
2648    NativeSymbols,
2649    /// The toolkit can rasterize its window and hand back the pixels
2650    /// (`Toolkit::snapshot_window`): what the dayscript `screenshot` step captures in-process
2651    /// and what `day::window_image()` offers the app (docs/window-image.md). `Unsupported` where
2652    /// a backend cannot draw itself into a bitmap: web-dom, which would need a rasterizer
2653    /// shipped with it. Probe it before offering a "save a screenshot" affordance, rather than
2654    /// offering one that fails when pressed.
2655    Snapshot,
2656    /// The toolkit can present `nav()` as sidebar+detail split panes, a statement about the
2657    /// toolkit, not about the window it is currently drawing. Whether a given host is split right
2658    /// now follows from its [`SizeClass`]: the pieces layer resolves an automatic
2659    /// [`props::NavPresentation`] against both, and re-resolves on every class change. A backend
2660    /// with no split container answers `Unsupported` and stays stacked at every size.
2661    NavSplit,
2662    /// The toolkit can draw a navigation host's rows as its own chrome: a tab bar
2663    /// ([`props::NavPresentation::Tabs`]) and, where it has one, a rail
2664    /// ([`props::NavPresentation::Rail`]). Like [`Self::NavSplit`] this is a statement about the
2665    /// toolkit, not about the window it is drawing right now.
2666    ///
2667    /// This is what `NavStyle::Automatic` resolves against (docs/navigation.md): a backend
2668    /// answering `Unsupported` gets the sidebar resolver instead (`Split` ↔ `Stack`), which is
2669    /// what every backend did before adaptive navigation existed. So an unimplemented backend
2670    /// degrades to its previous behavior rather than to a hole.
2671    ///
2672    /// `Emulated` means the rows are composed from other widgets rather than drawn by a native
2673    /// tab container (Qt, web-dom). `Native` means a real one (`UITabBarController`, a Material
2674    /// `NavigationBarView`, `NavigationView`).
2675    NavTabs,
2676    /// A narrow window should become a tab bar here, a separate question from [`Self::NavTabs`],
2677    /// which only says the toolkit *can* draw one.
2678    ///
2679    /// The two differ on every desktop. macOS, GNOME, Qt and Windows can all draw a tab bar, and
2680    /// must, because an app is free to pin `NavStyle::Tabs`; but none of them grows one when
2681    /// its window is dragged narrow. A narrow Mail.app hides its sidebar and pushes; it does not
2682    /// sprout a bottom tab bar, and an app that did would look like a port. The phones and the web
2683    /// are the opposite: those are the surfaces whose window size ranges from a phone to a
2684    /// desktop, and a tab bar is what their users expect at the narrow end.
2685    ///
2686    /// So this is a statement about the platform's idiom, not about its widget set:
2687    ///
2688    /// - `Native`/`Emulated`: `NavStyle::Automatic` may resolve to
2689    ///   [`props::NavPresentation::Tabs`] on a compact window (ios-uikit, android-material,
2690    ///   harmony-arkui, web-dom).
2691    /// - `Unsupported`: it may not; a compact window collapses to
2692    ///   [`props::NavPresentation::Stack`] instead, exactly as `NavStyle::Sidebar` has always
2693    ///   done (macos-appkit, linux-gtk, linux-qt, windows-winui).
2694    ///
2695    /// [`props::NavPresentation::Rail`] is not gated by this. A narrow sidebar is an ordinary
2696    /// desktop shape (on Windows it is what `NavigationView` does at that width on its own), so
2697    /// the rail rung stays available everywhere `Cap::NavSplit` is.
2698    NavTabsAdaptive,
2699    /// How a navigation host's presentation follows the window (docs/size-classes.md). All three
2700    /// answers mean something different here, and the difference is who decides:
2701    ///
2702    /// - `Native`: **Day tells the toolkit.** The pieces layer resolves the presentation from
2703    ///   the [`SizeClass`], re-resolves on every change, and sends
2704    ///   [`props::NavPatch::Presentation`]; the toolkit rebuilds its chrome and re-homes the
2705    ///   pages it already has. The desktops and web-dom.
2706    /// - `Emulated`: **the toolkit tells Day.** Its own adaptive container owns the decision
2707    ///   (`UISplitViewController` collapsing as a Pro Max iPhone rotates, `SlidingPaneLayout`
2708    ///   measuring whether both panes fit), so Day must not push a presentation into it: that
2709    ///   would be a second decision racing the platform's own animation. The toolkit
2710    ///   reports what it did with [`Event::NavPresentationChanged`] and Day reconciles.
2711    /// - `Unsupported`: nobody re-presents. The presentation is resolved once, from
2712    ///   [`Cap::NavSplit`] alone, and the window's size never enters into it. A toolkit that
2713    ///   cannot change presentation must not have it decided by something that can, or a window
2714    ///   launched narrow would be stuck stacked with no way back.
2715    NavRepresent,
2716    /// The toolkit places a navigation host's content-list page ([`props::Pane::List`]) in its
2717    /// own pane between the sidebar and the detail, the Mail shape: mailboxes, message list,
2718    /// message (docs/navigation.md). The three answers differ on what happens when the host
2719    /// leaves the split:
2720    ///
2721    /// - `Native`: the pane exists at every presentation. A narrow window collapses the
2722    ///   sidebar but keeps the list beside the detail, exactly as a narrow Mail.app does
2723    ///   (macos-appkit: a `contentList` `NSSplitViewItem`).
2724    /// - `Emulated`: the pane exists while split and merges into the navigation stack when
2725    ///   the host collapses (ios-uikit: `UISplitViewController` triple-column). The pieces
2726    ///   layer then interposes the list between the sidebar root and the detail
2727    ///   ([`props::NavPatch::ListInStack`]) and gates the detail push on the app's
2728    ///   `detail_visible` binding.
2729    /// - `Unsupported`: the backend never sees [`props::Pane::List`] or
2730    ///   [`props::NavProps::list_width`]; the nav piece composes the pane beside (split)
2731    ///   or in place of (stacked) the destination content itself.
2732    NavContentList,
2733    /// The toolkit shows the current destination's title in a native header/bar, so a page
2734    /// needn't repeat it in its own content. `Native` on XAML (the NavigationView header),
2735    /// UIKit (`UINavigationBar`), Android (`MaterialToolbar`), and ArkUI (`NavDestination`
2736    /// title bars). The desktop custom back-headers (AppKit/Qt/web) show a title only in
2737    /// stack mode, so those backends stay `Unsupported` (docs/navigation.md).
2738    NavHeader,
2739    /// The toolkit applies a runtime appearance override (`set_appearance`): native widgets
2740    /// restyle in place and `dark_mode` answers the override. Probe before showing a theme
2741    /// picker; on `Unsupported` backends the call is ignored.
2742    Appearance,
2743    /// The toolkit renders an application menu bar (docs/menus.md), so `app_menu` is visible to
2744    /// the user, and `register_preferences` gets its automatic Settings… item.
2745    ///
2746    /// The question an app asks before deciding where a command lives. Settings is the usual
2747    /// case: on a platform with a menu bar it belongs in the App menu and putting it in the
2748    /// navigation as well is clutter; on one without, the menu is a no-op and a Settings row is
2749    /// the only way in. Distinct from `Cap::Toolbar`: web-dom draws a window toolbar and has no
2750    /// menu bar at all, so keying off the toolbar strands Settings there.
2751    AppMenu,
2752    /// The toolkit can present native alert/confirm/sheet/prompt modals (docs/dialogs.md).
2753    Dialogs,
2754    /// The toolkit can present native open/save file pickers (docs/files.md).
2755    FileDialogs,
2756    /// The toolkit can present a native folder chooser (`PresentSpec::OpenFolder`,
2757    /// docs/files.md). `Native` on the four desktop toolkits (AppKit, GTK, Qt, WinUI); the
2758    /// phone and web backends answer `Unsupported` and resolve the request as `Dismissed`, so
2759    /// an app hides its "Add Folder…" command where this is not `Native`.
2760    FolderDialog,
2761    /// The toolkit runs backend-executed animation for `AnimSpec` intents on
2762    /// `update`/`set_frame`/`set_opacity`/`set_transform` (§8.4). `Unsupported` ⇒ animated calls
2763    /// apply instantly (still correct, just not animated).
2764    Animation,
2765    /// The toolkit presents a `kinds::COVER` node as a native fullscreen modal surface
2766    /// (docs/cover.md). `Unsupported` ⇒ the `cover` piece's content never shows.
2767    Cover,
2768    /// The toolkit presents a `.sheet()` cover as a native modal sheet (AppKit's window sheet,
2769    /// UIKit's page sheet) over the page it covers (docs/cover.md "Modal sheet"). `Unsupported`
2770    /// ⇒ the `cover` piece composes the sheet itself: on a window wider than compact, a card
2771    /// centered over the dimmed page; on a compact one, the full window.
2772    CoverSheet,
2773    /// The toolkit can hide the system status bar while a `status_bar_hidden` subtree is
2774    /// mounted (`Toolkit::set_status_bar_hidden`, docs/cover.md). `Native` on the phone and
2775    /// tablet backends; desktop and web have no status bar, so a setting that offers to hide
2776    /// it should be offered only where this is not `Unsupported`.
2777    StatusBarHidden,
2778    /// The toolkit's `text_area` can be made read-only (`TextAreaProps::editable = false`).
2779    TextEditable,
2780    /// The toolkit's `text_area` selectability can be toggled (`TextAreaProps::selectable`).
2781    /// `Unsupported` where selection is always on (GTK); `Emulated` where the backend
2782    /// collapses native selections itself (XAML, ArkUI).
2783    TextSelectable,
2784    /// The toolkit's `text_area` has built-in spell-check/autocorrect (`TextAreaProps::spellcheck`).
2785    /// `Unsupported` where the toolkit ships none (GTK, Qt, ArkUI).
2786    TextSpellCheck,
2787    /// The toolkit can open additional native OS windows (`Toolkit::open_window`,
2788    /// docs/windows.md). `Native` on the desktop backends and on mobile backends whose
2789    /// platform has a real secondary-window surface (iPad scenes, Android document
2790    /// activities, OHOS multiton abilities). On `Unsupported` backends
2791    /// `day_core::open_window` still works; the content presents as a fullscreen cover in
2792    /// the primary window instead. Probe it to adapt chrome: an `Unsupported` tier has no
2793    /// native title bar or close button, so window content should carry its own close
2794    /// affordance.
2795    MultiWindow,
2796    /// The toolkit can put a count on the app icon (`Toolkit::set_app_badge`, docs/badge.md).
2797    /// `Emulated` where the call is made but the shell may ignore it: desktop Linux, where the
2798    /// Unity launcher protocol is honored by Plasma and Dash-to-Dock but not by stock GNOME.
2799    AppBadgeCount,
2800    /// The toolkit renders `AppBadge::Text` as written. macOS only: `NSDockTile.badgeLabel` is an
2801    /// arbitrary string, while every other platform's badge is a number or nothing.
2802    AppBadgeText,
2803    /// The toolkit can show a valueless indicator (`AppBadge::Dot`).
2804    AppBadgeDot,
2805    /// The toolkit gives a window chrome that persists across pages
2806    /// (`Toolkit::edit_toolbar`, docs/toolbars.md): `Native` on the desktop backends and the
2807    /// phones, `Emulated` on web-dom, `Unsupported` where the only chrome belongs to a page.
2808    ///
2809    /// It no longer decides whether a command can be shown at all: a toolbar item declared on a
2810    /// piece rides that piece's own chrome everywhere. Probe it only for a layout decision that
2811    /// turns on a persistent bar existing.
2812    Toolbar,
2813    /// The window toolbar can hold a search field (docs/search.md): `Native` on the desktop
2814    /// backends, `Emulated` on web-dom. `Unsupported` on the phones, whose bar is a row of actions
2815    /// (an Android app-bar menu, iOS bar buttons, ArkUI title-bar menus): their field goes on the
2816    /// navigation surface instead, so `SearchPlacement::Toolbar` resolves to `Inline` there.
2817    ToolbarSearch,
2818    /// The toolkit realizes `kinds::INSPECTOR` as its own trailing-pane container
2819    /// (docs/inspector.md): an `NSSplitView` inspector pane, a `GtkPaned` with the panel as
2820    /// its end child, a `QDockWidget`, a XAML `SplitView` right pane. `Unsupported` ⇒ the
2821    /// `inspector` piece composes the pane from plain containers instead (same panel, same
2822    /// signal, no native divider), so an unimplemented backend degrades to a drawn pane, not
2823    /// to a hole. Apps normally have no reason to probe this; the piece does.
2824    Inspector,
2825    /// The toolkit realizes `kinds::SPLIT` as its own splitter (docs/split.md): an
2826    /// `NSSplitView`, a `GtkPaned`, a `QSplitter`, each side by side or stacked and with the
2827    /// divider the user drags. `Unsupported` ⇒ the `split` piece composes the two panes and
2828    /// draws and drags the divider itself (the web, the mobile toolkits, XAML), so the piece
2829    /// behaves the same everywhere and only the divider's look is the toolkit's. Apps have no
2830    /// reason to probe this; the piece does.
2831    Split,
2832    /// The toolkit shapes the pointer over a node from the `.cursor()` decorator
2833    /// ([`Toolkit::set_cursor`], docs/cursor.md). `Native` where the platform draws the requested
2834    /// shape from its own set (AppKit, GTK, the DOM, Android's `PointerIcon`), `Emulated` where
2835    /// some shapes map to a nearest neighbor (Qt, XAML) or the platform draws pointer effects
2836    /// rather than shapes (iPadOS), `Unsupported` where nothing changes: a touch-only toolkit,
2837    /// or one whose pointer API Day does not reach yet. Apps ask before offering an affordance
2838    /// that only a cursor reveals, such as a resize handle with no other visual.
2839    Cursor,
2840    /// The toolkit can enumerate the platform's font families with the faces each ships
2841    /// ([`Toolkit::font_families`], docs/fonts.md). `Native` where an OS font database answers
2842    /// (NSFontManager, UIFont, Pango, QFontDatabase, Android's `fonts.xml`,
2843    /// `OH_Drawing_FontMgr`, DirectWrite); `Emulated` where the list is composed rather than
2844    /// read: web-dom answers the CSS generic families plus the bundled `document.fonts`, since
2845    /// a browser exposes no local font list without a permission prompt; `Unsupported` means
2846    /// the list is empty and an app should offer only the default face. Measurement
2847    /// ([`Toolkit::measure_text`]) has no probe: a `None` answer degrades to
2848    /// [`TextMetrics::approximate`]. Probe this before offering a font menu, not before
2849    /// drawing; a [`CanvasFont`] draws everywhere.
2850    FontList,
2851    /// The toolkit reads the user's reduce-motion setting ([`Toolkit::reduce_motion`],
2852    /// docs/accessibility.md) and reports when it changes. `Native` where the platform has the
2853    /// switch and Day reaches it; `Unsupported` where Day reaches none (the app then animates as
2854    /// it would with the setting off, and `DAY_REDUCE_MOTION=1` still forces it on).
2855    ReduceMotion,
2856    /// The toolkit can speak a sentence through the screen reader without moving its focus
2857    /// ([`Toolkit::announce`], docs/accessibility.md): "Saved", "3 results", "Upload failed".
2858    /// `Native` where the platform has an announcement request (`NSAccessibility`'s
2859    /// announcement notification, `UIAccessibility`'s, Android's accessibility event, GTK
2860    /// 4.14's `gtk_accessible_announce`, a WinUI notification event); `Emulated` on the web,
2861    /// where an ARIA live region carries it; `Unsupported` where Day reaches no announcement
2862    /// API yet. An app with a visible status label needs no announcement: screen readers read
2863    /// what changes on screen only when told to, so this is for the change the user cannot
2864    /// otherwise learn about.
2865    Announce,
2866    /// The toolkit can turn encoded image bytes into a native image
2867    /// ([`Toolkit::decode_image`], docs/images.md): what `image(bytes)`, a pasted screenshot and
2868    /// a canvas image all rest on. `Native` wherever the platform decoder takes a buffer;
2869    /// `Unsupported` means only staged asset names draw, so an app should not offer "open an
2870    /// image" at all. Every backend that decodes also answers [`Toolkit::image_info`], so pixel
2871    /// size needs no probe of its own.
2872    ImageDecode,
2873    /// The toolkit can encode a decoded image back to bytes ([`Toolkit::encode_image`]).
2874    /// Which formats it encodes is [`Toolkit::encode_formats`], the same shape as
2875    /// [`Cap::FontList`]/[`Toolkit::font_families`], because "can encode" and "can encode WebP"
2876    /// are different questions and only the second one needs a list.
2877    ImageEncode,
2878    /// The toolkit can read an image's metadata beyond its pixels: EXIF orientation, DPI,
2879    /// capture time ([`Toolkit::image_properties`]). `Native` where a platform metadata reader
2880    /// is already linked (WinRT's `BitmapPropertiesView`, Android's `ExifInterface`);
2881    /// `Unsupported` where reading it would mean shipping a parser or a new framework, which is
2882    /// most places. An app that wants orientation must handle `None`.
2883    ImageProperties,
2884    /// The toolkit can replay a canvas drawing into an offscreen bitmap
2885    /// ([`Toolkit::render_bitmap`], docs/canvas.md "Exporting"): what `Drawing::to_bitmap` and
2886    /// `Drawing::to_png` rest on. `Native` where the toolkit's own canvas painter can target an
2887    /// image surface (a `CGBitmapContext`, a cairo image surface, a `QImage`, an android
2888    /// `Bitmap`, an `OH_Drawing_Bitmap`, a detached `<canvas>`); `Unsupported` where the
2889    /// on-screen canvas has no painter to retarget (WinUI builds XAML shapes instead).
2890    CanvasBitmap,
2891    /// The toolkit can replay canvas drawings into a PDF document ([`Toolkit::render_pdf`],
2892    /// docs/canvas.md "Exporting"), with vector shapes and the platform's own font embedding.
2893    /// `Native` only where the platform ships a PDF writer the canvas painter can draw into
2894    /// (Core Graphics on AppKit and UIKit, cairo on GTK, `QPdfWriter` on Qt, `PdfDocument` on
2895    /// Android); `Unsupported` on ArkUI, the web and WinUI, which have none.
2896    CanvasPdf,
2897    /// The toolkit minimizes, zooms, hides and restores a window on request
2898    /// ([`WindowChange::State`], [`WindowChange::Visible`], docs/windows.md) and reports what the
2899    /// user does through [`Event::WindowStateChanged`]. `Native` on the desktop backends;
2900    /// `Unsupported` on the phones and the web, whose windows the OS sizes.
2901    WindowStates,
2902    /// The toolkit takes a window fullscreen on request and reports when it enters and leaves
2903    /// ([`WindowState::Fullscreen`]). `Native` on the desktops, on Android (system bars hidden
2904    /// through `WindowInsetsController`), on HarmonyOS and on the web (the Fullscreen API, which
2905    /// browsers allow only during a user gesture); `Emulated` on iOS, which hides the status bar
2906    /// and lets the home indicator fade but always keeps the app full-screen anyway.
2907    WindowFullscreen,
2908    /// The toolkit keeps a window out of screenshots, recordings and screen sharing
2909    /// ([`WindowChange::ContentProtected`]). `Native` on macOS (`NSWindowSharingNone`), Windows
2910    /// (`WDA_EXCLUDEFROMCAPTURE`), Android (`FLAG_SECURE`) and HarmonyOS (privacy mode);
2911    /// `Emulated` on iOS, which has no switch for it: Day covers the content while the screen is
2912    /// being recorded or mirrored, but a screenshot still captures it. `Unsupported` on Linux
2913    /// and the web.
2914    ContentProtection,
2915    /// The toolkit honors [`WindowOptions::tabbing`]: macOS window tabs. `Unsupported` everywhere
2916    /// else, where no system window tabs exist.
2917    WindowTabbing,
2918    /// The toolkit shows a Dock menu ([`Toolkit::set_dock_menu`], docs/menus.md): the app's
2919    /// shortcuts and `dock_menu(..)` entries above the system's own items. macOS only.
2920    DockMenu,
2921    /// The toolkit resizes a window and bounds its size on request ([`WindowChange::Frame`]'s
2922    /// size, [`WindowChange::Limits`], [`WindowChange::Resizable`]).
2923    WindowGeometry,
2924    /// The toolkit moves a window to a requested position ([`WindowChange::Frame`]'s origin).
2925    /// `Unsupported` on GTK 4, which removed window positioning, and wherever the compositor owns
2926    /// placement (Wayland).
2927    WindowPosition,
2928    /// The toolkit changes how a window stacks ([`WindowChange::Level`],
2929    /// [`WindowChange::OnAllWorkspaces`], [`WindowChange::SkipTaskbar`]).
2930    WindowLevel,
2931    /// The toolkit gives one window its own light/dark appearance ([`WindowChange::Appearance`]).
2932    /// Where it cannot, the app-wide [`Toolkit::set_appearance`] still applies to every window.
2933    WindowAppearance,
2934    /// The toolkit asks for the user's attention on request ([`WindowChange::RequestAttention`]):
2935    /// a Dock bounce, a flashing taskbar button.
2936    RequestAttention,
2937    /// The toolkit opens a window with no title bar or frame ([`WindowChrome::Frameless`],
2938    /// docs/window-chrome.md). Desktop backends only.
2939    FramelessWindow,
2940    /// The toolkit runs a window's content under its title bar with the window controls kept
2941    /// ([`WindowChrome::Overlay`]) and reports the bar's height as the safe-area top inset.
2942    OverlayTitleBar,
2943    /// The toolkit opens a window whose unpainted pixels show the desktop
2944    /// ([`WindowBackground::Transparent`]).
2945    TransparentWindow,
2946    /// The toolkit puts a translucent system material behind a window
2947    /// ([`WindowBackground::Material`]): macOS's visual-effect materials, Windows 11's Mica and
2948    /// Acrylic. `Emulated` where an approximation stands in.
2949    WindowMaterial,
2950    /// The toolkit lets a piece move its window like a title bar does
2951    /// ([`Toolkit::set_drag_region`], `.window_drag_region()`). `Emulated` on the web, where
2952    /// only an installed app with a window-controls overlay honors it.
2953    DragRegion,
2954    /// The toolkit shows status items ([`Toolkit::set_status_items`], docs/status-item.md): the
2955    /// macOS menu bar, the Windows notification area, a Linux tray. On Linux the answer depends
2956    /// on the desktop: `Native` while a StatusNotifierItem host is running (KDE Plasma, most
2957    /// panels, GNOME with the AppIndicator extension), `Unsupported` without one (stock GNOME),
2958    /// so an app can keep a window instead of vanishing into a tray nobody shows.
2959    StatusItem,
2960    /// The toolkit shows progress on the app's Dock or taskbar icon
2961    /// ([`Toolkit::set_app_progress`]). `Emulated` on Linux, where the Unity launcher protocol is
2962    /// honored by KDE Plasma and Dash to Dock but not by every dock.
2963    AppProgress,
2964    /// The toolkit can hide the app's Dock icon while it runs ([`Toolkit::set_dock_visible`]).
2965    /// macOS only.
2966    DockVisibility,
2967    /// The toolkit lists the displays and their work areas ([`Toolkit::monitors`]). `Emulated`
2968    /// where the one screen the app runs on is reported (a phone, the web).
2969    Monitors,
2970    /// The toolkit shows launcher shortcuts the app sets while it runs
2971    /// ([`Toolkit::set_launcher_shortcuts`]).
2972    DynamicShortcuts,
2973    /// How the toolkit draws a sectioned list's headers (`ListProps::sections`, docs/list.md
2974    /// "Sections"). `Native` where the platform's list has group headers that pin to the top
2975    /// while their section scrolls under them: macos-appkit (`NSTableView` group rows with
2976    /// `floatsGroupRows`) and ios-uikit (plain-style `UITableView` section headers).
2977    /// `Emulated` where the host pins a copy of the current header over the top of the list
2978    /// itself. Headers are unselectable rows on every toolkit, so an app needs this only to
2979    /// describe the difference, never to decide whether to call `.sections`.
2980    ListSections,
2981}
2982
2983impl Cap {
2984    /// Every capability, in declaration order: what a conformance run asks the toolkit about,
2985    /// so the evidence can be held against the declared coverage matrix (docs/testing.md).
2986    pub const ALL: [Cap; 90] = [
2987        Cap::DragDrop,
2988        Cap::DragExternalImport,
2989        Cap::DragExternalExport,
2990        Cap::DragMultipleItems,
2991        Cap::DragFileReferences,
2992        Cap::DragDeferredReceipt,
2993        Cap::DragFilePromises,
2994        Cap::DragExternalMove,
2995        Cap::ListRecycling,
2996        Cap::UndoBridge,
2997        Cap::EditBridge,
2998        Cap::ListReorder,
2999        Cap::NavReorder,
3000        Cap::ListDelete,
3001        Cap::ListSwipeActions,
3002        Cap::Tree,
3003        Cap::TreeMove,
3004        Cap::BaselineAlignment,
3005        Cap::TextRuns,
3006        Cap::TextLinks,
3007        Cap::Lottie,
3008        Cap::NativeSymbols,
3009        Cap::Snapshot,
3010        Cap::NavSplit,
3011        Cap::NavTabs,
3012        Cap::NavTabsAdaptive,
3013        Cap::NavRepresent,
3014        Cap::NavContentList,
3015        Cap::NavHeader,
3016        Cap::Appearance,
3017        Cap::AppMenu,
3018        Cap::Dialogs,
3019        Cap::FileDialogs,
3020        Cap::Animation,
3021        Cap::Cover,
3022        Cap::StatusBarHidden,
3023        Cap::TextEditable,
3024        Cap::TextSelectable,
3025        Cap::TextSpellCheck,
3026        Cap::MultiWindow,
3027        Cap::AppBadgeCount,
3028        Cap::AppBadgeText,
3029        Cap::AppBadgeDot,
3030        Cap::Toolbar,
3031        Cap::ToolbarSearch,
3032        Cap::Inspector,
3033        Cap::Cursor,
3034        Cap::FontList,
3035        Cap::ReduceMotion,
3036        Cap::Announce,
3037        Cap::ImageDecode,
3038        Cap::ImageEncode,
3039        Cap::ImageProperties,
3040        Cap::WindowStates,
3041        Cap::WindowFullscreen,
3042        Cap::ContentProtection,
3043        Cap::WindowTabbing,
3044        Cap::DockMenu,
3045        Cap::WindowGeometry,
3046        Cap::WindowPosition,
3047        Cap::WindowLevel,
3048        Cap::WindowAppearance,
3049        Cap::RequestAttention,
3050        Cap::FramelessWindow,
3051        Cap::OverlayTitleBar,
3052        Cap::TransparentWindow,
3053        Cap::WindowMaterial,
3054        Cap::DragRegion,
3055        Cap::StatusItem,
3056        Cap::AppProgress,
3057        Cap::DockVisibility,
3058        Cap::Monitors,
3059        Cap::DynamicShortcuts,
3060        Cap::Split,
3061        Cap::TreeSections,
3062        Cap::CoverSheet,
3063        Cap::ListEditing,
3064        Cap::ListItem,
3065        Cap::CanvasBitmap,
3066        Cap::CanvasPdf,
3067        Cap::SearchField,
3068        Cap::ComboBox,
3069        Cap::Stepper,
3070        Cap::DateTimePicker,
3071        Cap::ColorPicker,
3072        Cap::PullRefresh,
3073        Cap::Pager,
3074        Cap::PullRefreshGesture,
3075        Cap::FolderDialog,
3076        Cap::ListSections,
3077    ];
3078
3079    /// The capability's place in [`Cap::ALL`]. Exhaustive, so a new variant fails to compile
3080    /// here until it is given one, and the unit test below then holds `ALL` to it.
3081    pub const fn ordinal(self) -> usize {
3082        match self {
3083            Cap::DragDrop => 0,
3084            Cap::DragExternalImport => 1,
3085            Cap::DragExternalExport => 2,
3086            Cap::DragMultipleItems => 3,
3087            Cap::DragFileReferences => 4,
3088            Cap::DragDeferredReceipt => 5,
3089            Cap::DragFilePromises => 6,
3090            Cap::DragExternalMove => 7,
3091            Cap::ListRecycling => 8,
3092            Cap::UndoBridge => 9,
3093            Cap::EditBridge => 10,
3094            Cap::ListReorder => 11,
3095            Cap::NavReorder => 12,
3096            Cap::ListDelete => 13,
3097            Cap::ListSwipeActions => 14,
3098            Cap::Tree => 15,
3099            Cap::TreeMove => 16,
3100            Cap::BaselineAlignment => 17,
3101            Cap::TextRuns => 18,
3102            Cap::TextLinks => 19,
3103            Cap::Lottie => 20,
3104            Cap::NativeSymbols => 21,
3105            Cap::Snapshot => 22,
3106            Cap::NavSplit => 23,
3107            Cap::NavTabs => 24,
3108            Cap::NavTabsAdaptive => 25,
3109            Cap::NavRepresent => 26,
3110            Cap::NavContentList => 27,
3111            Cap::NavHeader => 28,
3112            Cap::Appearance => 29,
3113            Cap::AppMenu => 30,
3114            Cap::Dialogs => 31,
3115            Cap::FileDialogs => 32,
3116            Cap::Animation => 33,
3117            Cap::Cover => 34,
3118            Cap::StatusBarHidden => 35,
3119            Cap::TextEditable => 36,
3120            Cap::TextSelectable => 37,
3121            Cap::TextSpellCheck => 38,
3122            Cap::MultiWindow => 39,
3123            Cap::AppBadgeCount => 40,
3124            Cap::AppBadgeText => 41,
3125            Cap::AppBadgeDot => 42,
3126            Cap::Toolbar => 43,
3127            Cap::ToolbarSearch => 44,
3128            Cap::Inspector => 45,
3129            Cap::Cursor => 46,
3130            Cap::FontList => 47,
3131            Cap::ReduceMotion => 48,
3132            Cap::Announce => 49,
3133            Cap::ImageDecode => 50,
3134            Cap::ImageEncode => 51,
3135            Cap::ImageProperties => 52,
3136            Cap::WindowStates => 53,
3137            Cap::WindowFullscreen => 54,
3138            Cap::ContentProtection => 55,
3139            Cap::WindowTabbing => 56,
3140            Cap::DockMenu => 57,
3141            Cap::WindowGeometry => 58,
3142            Cap::WindowPosition => 59,
3143            Cap::WindowLevel => 60,
3144            Cap::WindowAppearance => 61,
3145            Cap::RequestAttention => 62,
3146            Cap::FramelessWindow => 63,
3147            Cap::OverlayTitleBar => 64,
3148            Cap::TransparentWindow => 65,
3149            Cap::WindowMaterial => 66,
3150            Cap::DragRegion => 67,
3151            Cap::StatusItem => 68,
3152            Cap::AppProgress => 69,
3153            Cap::DockVisibility => 70,
3154            Cap::Monitors => 71,
3155            Cap::DynamicShortcuts => 72,
3156            Cap::Split => 73,
3157            Cap::TreeSections => 74,
3158            Cap::CoverSheet => 75,
3159            Cap::ListEditing => 76,
3160            Cap::ListItem => 77,
3161            Cap::CanvasBitmap => 78,
3162            Cap::CanvasPdf => 79,
3163            Cap::SearchField => 80,
3164            Cap::ComboBox => 81,
3165            Cap::Stepper => 82,
3166            Cap::DateTimePicker => 83,
3167            Cap::ColorPicker => 84,
3168            Cap::PullRefresh => 85,
3169            Cap::Pager => 86,
3170            Cap::PullRefreshGesture => 87,
3171            Cap::FolderDialog => 88,
3172            Cap::ListSections => 89,
3173        }
3174    }
3175}
3176
3177// ---------------------------------------------------------------------------
3178// Raster images (docs/images.md): the currency shared by the `image` piece, the canvas, and
3179// the decode/metadata/encode duties below.
3180// ---------------------------------------------------------------------------
3181
3182/// A decoded image the toolkit holds, addressed by an id day-core mints.
3183///
3184/// Opaque, because what sits behind it is an `NSImage`, a `UIImage`, a `GdkTexture`, a
3185/// `QPixmap`, a `BitmapImage`, an android `Bitmap` or an `ImageBitmap`, and none of those cross
3186/// the boundary. The id is released through [`Toolkit::release_image`] when the app's handle
3187/// drops, so a backend's side table never outlives the app's interest in it.
3188#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
3189pub struct BitmapId(pub u64);
3190
3191/// An encoded image format: what [`BitmapInfo::format`] reports and [`EncodeSpec::format`] asks
3192/// for. Not every backend encodes every one: ask [`Toolkit::encode_formats`] (the
3193/// [`Cap::ImageEncode`] pair of [`Toolkit::font_families`]/[`Cap::FontList`]) rather than
3194/// assuming.
3195#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default)]
3196pub enum ImageFormat {
3197    #[default]
3198    Png,
3199    Jpeg,
3200    Webp,
3201    Gif,
3202    Bmp,
3203    Tiff,
3204    /// HEIF/HEIC, Apple's camera format; decodable on the Apple backends and Android, and
3205    /// encodable almost nowhere.
3206    Heif,
3207    /// Decoded from bytes whose magic numbers [`ImageFormat::sniff`] does not know. A backend may
3208    /// still decode it: the platform decoders read more formats than Day names.
3209    Unknown,
3210}
3211
3212impl ImageFormat {
3213    /// The IANA media type, which is also the string the ArkUI packer, GDI+ and the browser's
3214    /// `toBlob` take. `Unknown` answers `application/octet-stream`.
3215    pub fn mime(self) -> &'static str {
3216        match self {
3217            ImageFormat::Png => "image/png",
3218            ImageFormat::Jpeg => "image/jpeg",
3219            ImageFormat::Webp => "image/webp",
3220            ImageFormat::Gif => "image/gif",
3221            ImageFormat::Bmp => "image/bmp",
3222            ImageFormat::Tiff => "image/tiff",
3223            ImageFormat::Heif => "image/heif",
3224            ImageFormat::Unknown => "application/octet-stream",
3225        }
3226    }
3227
3228    /// The pixel size the encoded bytes declare, read from the container's own header
3229    /// (docs/images.md).
3230    ///
3231    /// Every backend that decodes natively reports its own dimensions; this exists for the one
3232    /// that cannot. The XAML backend's (`windows-winui`) `BitmapImage` learns its size
3233    /// asynchronously, only once the element has been shown, so a synchronous `image_info` there
3234    /// would have nothing to say.
3235    /// Reading the header instead gives the same answer the decoder would, before any decoding.
3236    ///
3237    /// `None` when the header is absent, truncated, or a container this does not parse.
3238    pub fn dimensions(bytes: &[u8]) -> Option<(u32, u32)> {
3239        let be16 = |i: usize| -> Option<u32> {
3240            Some(u32::from(u16::from_be_bytes([
3241                *bytes.get(i)?,
3242                *bytes.get(i + 1)?,
3243            ])))
3244        };
3245        let le16 = |i: usize| -> Option<u32> {
3246            Some(u32::from(u16::from_le_bytes([
3247                *bytes.get(i)?,
3248                *bytes.get(i + 1)?,
3249            ])))
3250        };
3251        let be32 = |i: usize| -> Option<u32> {
3252            Some(u32::from_be_bytes([
3253                *bytes.get(i)?,
3254                *bytes.get(i + 1)?,
3255                *bytes.get(i + 2)?,
3256                *bytes.get(i + 3)?,
3257            ]))
3258        };
3259        let le32 = |i: usize| -> Option<u32> {
3260            Some(u32::from_le_bytes([
3261                *bytes.get(i)?,
3262                *bytes.get(i + 1)?,
3263                *bytes.get(i + 2)?,
3264                *bytes.get(i + 3)?,
3265            ]))
3266        };
3267        match Self::sniff(bytes)? {
3268            // IHDR is always the first chunk: 8-byte signature, 4-byte length, 4-byte type.
3269            ImageFormat::Png => Some((be32(16)?, be32(20)?)),
3270            // The logical screen descriptor follows the 6-byte version stamp, little-endian.
3271            ImageFormat::Gif => Some((le16(6)?, le16(8)?)),
3272            // The DIB header's width/height are signed; a negative height is a top-down bitmap.
3273            ImageFormat::Bmp => Some((
3274                le32(18)?.cast_signed().unsigned_abs(),
3275                le32(22)?.cast_signed().unsigned_abs(),
3276            )),
3277            // Walk the segment chain to the frame header. Every SOF marker carries the size at
3278            // the same offsets; the arithmetic-coded and progressive ones are SOFs too, which is
3279            // why this matches the whole range rather than SOF0 alone. DNL/DHP (0xC4, 0xC8,
3280            // 0xCC) are not frame headers and are skipped like any other segment.
3281            ImageFormat::Jpeg => {
3282                let mut i = 2usize;
3283                // `<=`, not `<`: a frame header that ends the buffer is still a frame header, and
3284                // the size sits in its last four bytes.
3285                while i + 9 <= bytes.len() {
3286                    if bytes[i] != 0xFF {
3287                        i += 1;
3288                        continue;
3289                    }
3290                    let marker = bytes[i + 1];
3291                    // Padding fill bytes and the standalone markers carry no length.
3292                    if marker == 0xFF || (0xD0..=0xD9).contains(&marker) || marker == 0x01 {
3293                        i += 1;
3294                        continue;
3295                    }
3296                    let is_sof = (0xC0..=0xCF).contains(&marker)
3297                        && marker != 0xC4
3298                        && marker != 0xC8
3299                        && marker != 0xCC;
3300                    if is_sof {
3301                        // [marker][len:2][precision:1][height:2][width:2]
3302                        return Some((be16(i + 7)?, be16(i + 5)?));
3303                    }
3304                    i += 2 + be16(i + 2)? as usize;
3305                }
3306                None
3307            }
3308            // RIFF: a 12-byte header, then a chunk id. VP8X states the size minus one in 24-bit
3309            // little-endian; lossy VP8 hides it in the 14 low bits after the start code; lossless
3310            // VP8L packs width-1 and height-1 into 14 bits each across four bytes.
3311            ImageFormat::Webp => match bytes.get(12..16)? {
3312                b"VP8X" => {
3313                    let w = u32::from(*bytes.get(24)?)
3314                        | u32::from(*bytes.get(25)?) << 8
3315                        | u32::from(*bytes.get(26)?) << 16;
3316                    let h = u32::from(*bytes.get(27)?)
3317                        | u32::from(*bytes.get(28)?) << 8
3318                        | u32::from(*bytes.get(29)?) << 16;
3319                    Some((w + 1, h + 1))
3320                }
3321                b"VP8 " => Some((le16(26)? & 0x3FFF, le16(28)? & 0x3FFF)),
3322                b"VP8L" => {
3323                    let bits = le32(21)?;
3324                    Some(((bits & 0x3FFF) + 1, ((bits >> 14) & 0x3FFF) + 1))
3325                }
3326                _ => None,
3327            },
3328            // TIFF's IFD is a pointer chase and HEIF's is a box tree; neither is worth parsing
3329            // here, because every backend that reads them decodes natively and answers for itself.
3330            ImageFormat::Tiff | ImageFormat::Heif | ImageFormat::Unknown => None,
3331        }
3332    }
3333
3334    /// The format `bytes` begins with, by magic number: enough to fill [`BitmapInfo::format`]
3335    /// on every backend, including the ones whose decoder never says what it decoded.
3336    ///
3337    /// Hand-rolled rather than a crate: it is a dozen byte comparisons against fixed prefixes,
3338    /// and the alternative is an image-decoding dependency in the one crate that must stay
3339    /// dependency-free.
3340    pub fn sniff(bytes: &[u8]) -> Option<ImageFormat> {
3341        let starts = |sig: &[u8]| bytes.len() >= sig.len() && &bytes[..sig.len()] == sig;
3342        if starts(&[0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a]) {
3343            return Some(ImageFormat::Png);
3344        }
3345        if starts(&[0xff, 0xd8, 0xff]) {
3346            return Some(ImageFormat::Jpeg);
3347        }
3348        if starts(b"GIF87a") || starts(b"GIF89a") {
3349            return Some(ImageFormat::Gif);
3350        }
3351        if starts(b"BM") {
3352            return Some(ImageFormat::Bmp);
3353        }
3354        if starts(&[0x49, 0x49, 0x2a, 0x00]) || starts(&[0x4d, 0x4d, 0x00, 0x2a]) {
3355            return Some(ImageFormat::Tiff);
3356        }
3357        // RIFF....WEBP and ....ftypheic/heix/mif1 both carry their tag past a 4-byte prefix.
3358        if starts(b"RIFF") && bytes.len() >= 12 && &bytes[8..12] == b"WEBP" {
3359            return Some(ImageFormat::Webp);
3360        }
3361        if bytes.len() >= 12 && &bytes[4..8] == b"ftyp" {
3362            let brand = &bytes[8..12];
3363            if brand == b"heic" || brand == b"heix" || brand == b"mif1" || brand == b"msf1" {
3364                return Some(ImageFormat::Heif);
3365            }
3366        }
3367        None
3368    }
3369}
3370
3371/// What a decoded image is, in the terms every backend can answer
3372/// ([`Toolkit::image_info`], docs/images.md).
3373///
3374/// `pixels` is the image's own pixel size, not the points it draws at: an asset that stages at
3375/// 2× reports twice its point size and a `scale` of 2, so an app sizing a frame divides. Bytes
3376/// carry no density, so a decoded buffer always answers `scale: 1.0`.
3377#[derive(Clone, Copy, Debug, Default, PartialEq)]
3378pub struct BitmapInfo {
3379    pub pixels: Size,
3380    /// Pixels per point (1.0 for decoded bytes; 2 or 3 for a catalog/drawable asset that staged
3381    /// a density variant).
3382    pub scale: f64,
3383    /// The encoded format it came from, where the backend knows or [`ImageFormat::sniff`] said.
3384    pub format: Option<ImageFormat>,
3385    pub has_alpha: bool,
3386}
3387
3388/// What [`Toolkit::encode_image`] should produce (docs/images.md).
3389///
3390/// A struct rather than three positional arguments, per docs/api-style.md: the call site reads
3391/// `EncodeSpec { format: ImageFormat::Jpeg, quality: Some(0.8), ..Default::default() }`.
3392#[derive(Clone, Copy, Debug, PartialEq)]
3393pub struct EncodeSpec {
3394    pub format: ImageFormat,
3395    /// Lossy quality in `0.0..=1.0`. `None` takes the platform's default; a lossless format
3396    /// ignores it.
3397    pub quality: Option<f64>,
3398    /// Scale the longest side down to fit this box first (aspect preserved). `None` encodes at
3399    /// the image's own size.
3400    pub fit: Option<Size>,
3401}
3402
3403impl Default for EncodeSpec {
3404    fn default() -> Self {
3405        EncodeSpec {
3406            format: ImageFormat::Png,
3407            quality: None,
3408            fit: None,
3409        }
3410    }
3411}
3412
3413/// The metadata an image file carries beyond its pixels ([`Toolkit::image_properties`]).
3414///
3415/// Sparse by construction: every field is what the platform's own reader answered, and a
3416/// backend with no metadata reader at all answers `None` to the whole call rather than an empty
3417/// struct. Probe [`Cap::ImageProperties`] before offering an affordance that depends on it.
3418#[derive(Clone, Debug, Default, PartialEq)]
3419pub struct ImageProperties {
3420    /// The EXIF orientation tag (1–8), where one was recorded.
3421    pub orientation: Option<u16>,
3422    /// Pixels per inch, where the file records a resolution.
3423    pub dpi: Option<f64>,
3424    /// The capture timestamp as the file spells it (no parsing: the formats disagree).
3425    pub created: Option<String>,
3426    /// Everything else the platform reader named, in its own vocabulary. Keys are the
3427    /// platform's, so read them defensively.
3428    pub extra: Vec<(String, String)>,
3429}
3430
3431/// Why an image operation could not answer.
3432#[derive(Clone, Copy, Debug, PartialEq, Eq)]
3433pub enum ImageError {
3434    /// The bytes are not an image this platform decodes.
3435    Decode,
3436    /// The image decoded, but this backend cannot encode the format asked for. `encode_formats`
3437    /// says which it can.
3438    Encode,
3439    /// The backend has no path for this at all (probe [`Cap::ImageDecode`] /
3440    /// [`Cap::ImageEncode`]).
3441    Unsupported,
3442    /// The id named no live image: released already, or never decoded.
3443    Gone,
3444}
3445
3446impl std::fmt::Display for ImageError {
3447    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3448        match self {
3449            ImageError::Decode => write!(f, "the bytes are not a decodable image"),
3450            ImageError::Encode => write!(f, "this backend cannot encode that format"),
3451            ImageError::Unsupported => write!(f, "image support is unavailable on this backend"),
3452            ImageError::Gone => write!(f, "the image was released"),
3453        }
3454    }
3455}
3456
3457impl std::error::Error for ImageError {}
3458
3459// ---------------------------------------------------------------------------
3460// Canvas export (docs/canvas.md "Exporting"): a recorded drawing replayed into an offscreen
3461// bitmap or a PDF by the same painter the on-screen canvas uses.
3462// ---------------------------------------------------------------------------
3463
3464/// The largest side, in pixels, a rendered bitmap may have (docs/canvas.md "Exporting").
3465/// day-core answers [`ExportError::TooLarge`] above it before any toolkit allocates.
3466pub const EXPORT_MAX_SIDE: u32 = 16_384;
3467
3468/// The most pixels a rendered bitmap may hold in total: 64 megapixels, 256 MB at four bytes a
3469/// pixel, which is already more than the tightest per-app heap (Android's) comfortably holds.
3470pub const EXPORT_MAX_PIXELS: u64 = 64 * 1024 * 1024;
3471
3472/// The pixel size a drawing of `size` points renders to at `scale` pixels per point: each side
3473/// rounded up, so a drawing never loses its last partial pixel. Shared by day-core's limit
3474/// check and every backend, so the bitmap a backend allocates is the one day-core approved.
3475pub fn export_pixels(size: Size, scale: f64) -> (u32, u32) {
3476    let side = |v: f64| (v * scale).ceil().clamp(0.0, u32::MAX as f64) as u32;
3477    (side(size.width), side(size.height))
3478}
3479
3480/// One page of a PDF [`Toolkit::render_pdf`] writes: the page size in PDF points (1/72 inch,
3481/// the same unit as canvas points) and the ops to replay onto it, origin top-left.
3482#[derive(Clone, Debug, PartialEq)]
3483pub struct PdfPage {
3484    pub size: Size,
3485    pub ops: Vec<DrawOp>,
3486}
3487
3488/// The document information a PDF carries. A backend whose writer has no metadata API (Android's
3489/// `PdfDocument`) ignores it.
3490#[derive(Clone, Debug, Default, PartialEq)]
3491pub struct PdfInfo {
3492    pub title: Option<String>,
3493    pub author: Option<String>,
3494}
3495
3496/// Why a canvas export could not answer (docs/canvas.md "Exporting").
3497#[derive(Clone, Debug, PartialEq)]
3498pub enum ExportError {
3499    /// This toolkit has no path for the export (probe [`Cap::CanvasBitmap`] /
3500    /// [`Cap::CanvasPdf`]).
3501    Unsupported,
3502    /// The bitmap would exceed [`EXPORT_MAX_SIDE`] or [`EXPORT_MAX_PIXELS`]; checked in
3503    /// day-core before the toolkit runs. The size is the one that was refused, in pixels.
3504    TooLarge { width: u32, height: u32 },
3505    /// A zero, negative or non-finite size or scale, or a PDF with no pages.
3506    Invalid,
3507    /// The platform refused (out of memory, a writer error); the text is the platform's.
3508    Failed(String),
3509}
3510
3511impl std::fmt::Display for ExportError {
3512    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3513        match self {
3514            ExportError::Unsupported => write!(f, "this export is unavailable on this backend"),
3515            ExportError::TooLarge { width, height } => {
3516                write!(
3517                    f,
3518                    "a {width} × {height} pixel bitmap is too large to render"
3519                )
3520            }
3521            ExportError::Invalid => write!(f, "the drawing has no size or the PDF has no pages"),
3522            ExportError::Failed(why) => write!(f, "rendering failed: {why}"),
3523        }
3524    }
3525}
3526
3527impl std::error::Error for ExportError {}
3528
3529/// Where a raster image's pixels come from (docs/images.md).
3530///
3531/// One currency for both halves of the same question: `Named` is the staged asset every
3532/// `image(res::images::…)` has always drawn, `Bytes` is an encoded PNG/JPEG the app already
3533/// holds (a download, a file the user picked, a clipboard paste), and `Decoded` names an image
3534/// the toolkit decoded once so several nodes (and the canvas) share it.
3535#[derive(Clone)]
3536pub enum ImageSource {
3537    /// A staged asset name, resolved through the backend's own pipeline (§18.2).
3538    Named(String),
3539    /// Encoded bytes (PNG/JPEG/…) the app owns, decoded by the platform's own decoder. Shared
3540    /// rather than copied: handing over a new buffer is a refcount bump.
3541    Bytes(std::sync::Arc<Vec<u8>>),
3542    /// An image already decoded through [`Toolkit::decode_image`].
3543    Decoded(BitmapId),
3544}
3545
3546impl Default for ImageSource {
3547    fn default() -> Self {
3548        ImageSource::Named(String::new())
3549    }
3550}
3551
3552/// Bytes compare by identity, not content.
3553///
3554/// This is the equality a binding gates on (§4.2), so it runs on every evaluation, and
3555/// comparing two multi-megabyte buffers byte by byte would cost far more than the redundant
3556/// decode it saves. Handing over a distinct buffer holding the same pixels therefore re-decodes,
3557/// which is the same trade `Arc::ptr_eq` makes wherever else Day carries shared buffers.
3558impl PartialEq for ImageSource {
3559    fn eq(&self, other: &Self) -> bool {
3560        match (self, other) {
3561            (ImageSource::Named(a), ImageSource::Named(b)) => a == b,
3562            (ImageSource::Bytes(a), ImageSource::Bytes(b)) => std::sync::Arc::ptr_eq(a, b),
3563            (ImageSource::Decoded(a), ImageSource::Decoded(b)) => a == b,
3564            _ => false,
3565        }
3566    }
3567}
3568
3569/// Logs the buffer's length, never its contents: a `Debug` that dumped a megabyte of pixels
3570/// into a trace line would make the trace useless and slow.
3571impl std::fmt::Debug for ImageSource {
3572    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3573        match self {
3574            ImageSource::Named(n) => f.debug_tuple("Named").field(n).finish(),
3575            ImageSource::Bytes(b) => f.debug_tuple("Bytes").field(&b.len()).finish(),
3576            ImageSource::Decoded(id) => f.debug_tuple("Decoded").field(&id.0).finish(),
3577        }
3578    }
3579}
3580
3581impl From<BitmapId> for ImageSource {
3582    fn from(id: BitmapId) -> Self {
3583        ImageSource::Decoded(id)
3584    }
3585}
3586
3587/// A staged asset name is a source, so `image(res::images::cover)` keeps compiling unchanged.
3588///
3589/// There is no `From<&str>` here, for the same reason [`resource::ImageName`] has none:
3590/// `image("typo")` must stay a compile error rather than a blank view at runtime (resource.rs).
3591/// A path or URL string is not a source either: read the bytes and hand those over.
3592impl From<resource::ImageName> for ImageSource {
3593    fn from(name: resource::ImageName) -> Self {
3594        ImageSource::Named(name.as_str().to_owned())
3595    }
3596}
3597
3598impl From<resource::VectorName> for ImageSource {
3599    fn from(name: resource::VectorName) -> Self {
3600        ImageSource::Named(name.as_str().to_owned())
3601    }
3602}
3603
3604impl From<std::sync::Arc<Vec<u8>>> for ImageSource {
3605    fn from(bytes: std::sync::Arc<Vec<u8>>) -> Self {
3606        ImageSource::Bytes(bytes)
3607    }
3608}
3609
3610/// An owned string is a name, not bytes: the same conversion [`resource::ImageName`] offers for
3611/// a name computed at runtime, and the reason `image(some_string)` keeps compiling. A `&str`
3612/// still converts nowhere, so `image("typo")` stays a compile error (resource.rs).
3613impl From<String> for ImageSource {
3614    fn from(name: String) -> Self {
3615        ImageSource::Named(name)
3616    }
3617}
3618
3619impl From<Vec<u8>> for ImageSource {
3620    fn from(bytes: Vec<u8>) -> Self {
3621        ImageSource::Bytes(std::sync::Arc::new(bytes))
3622    }
3623}
3624
3625#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
3626pub enum Support {
3627    Native,
3628    Emulated,
3629    /// The default: what an unimplemented capability answers everywhere.
3630    #[default]
3631    Unsupported,
3632}
3633
3634/// What a text field collects (`text_field(..).input_purpose(_)`, docs/textfield.md).
3635///
3636/// One word for everything a platform keys off the kind of text: the on-screen keyboard's
3637/// layout, capitalization and correction, and the credential or contact the system offers to
3638/// fill in. A backend applies the parts its toolkit has: a desktop toolkit with no on-screen
3639/// keyboard still takes the autofill and correction half.
3640///
3641/// Purpose is independent of [`InputTraits::secure`]: a numeric PIN is `Number` and secure.
3642#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
3643pub enum InputPurpose {
3644    /// Free text: the default keyboard, with the platform's own capitalization and correction.
3645    #[default]
3646    Text,
3647    /// A person's name: words capitalized, never corrected.
3648    Name,
3649    /// An email address: the `@` keyboard, never capitalized or corrected.
3650    Email,
3651    /// A web address: the URL keyboard, never capitalized or corrected.
3652    Url,
3653    /// A telephone number: the phone pad.
3654    Phone,
3655    /// A whole number: the digit pad.
3656    Number,
3657    /// A number with a fractional part: the digit pad with a decimal separator.
3658    Decimal,
3659    /// An account name: never capitalized or corrected, and offered to the password manager.
3660    Username,
3661    /// An existing password, offered to the password manager for filling.
3662    Password,
3663    /// A password being chosen, so the password manager offers to make and save one.
3664    NewPassword,
3665    /// A code sent by message or mail, which the keyboard offers as it arrives. The keyboard
3666    /// stays the text one, since a code can carry letters.
3667    OneTimeCode,
3668}
3669
3670/// The on-screen keyboard's action key (`text_field(..).submit_label(_)`, docs/textfield.md).
3671///
3672/// The key always fires the field's `on_submit`; this names what it promises. A toolkit with
3673/// no on-screen keyboard ignores it.
3674#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
3675pub enum SubmitLabel {
3676    /// The platform's own key (Return).
3677    #[default]
3678    Return,
3679    Done,
3680    Go,
3681    Next,
3682    Search,
3683    Send,
3684}
3685
3686/// How a text field takes its text (docs/textfield.md): the whole set travels together through
3687/// [`Toolkit::set_input_traits`], so a backend that has to rebuild the widget for one member
3688/// has every other member in hand to dress the replacement.
3689#[derive(Clone, Debug, Default, PartialEq, Eq)]
3690pub struct InputTraits {
3691    /// Hide the characters (a password field).
3692    pub secure: bool,
3693    /// Show and select the text, take no edits.
3694    pub read_only: bool,
3695    pub purpose: InputPurpose,
3696    pub submit_label: SubmitLabel,
3697    /// The most characters (Unicode scalar values) the field takes; `None` is unbounded.
3698    /// day-pieces holds the bound on every backend. A toolkit applies its native limit as well
3699    /// only where that limit counts the same unit (GTK): one that counts UTF-16 units would
3700    /// refuse characters the bound allows.
3701    pub max_length: Option<u32>,
3702}
3703
3704/// The pointer's shape over a piece (the `.cursor()` decorator, docs/cursor.md).
3705///
3706/// The named variants are the CSS cursor vocabulary: the largest set any toolkit accepts as it
3707/// is (GTK and the DOM take the names verbatim), and every other toolkit's set is a subset of it
3708/// or maps onto it. A backend draws its own shape for each name, or the nearest one it has, and
3709/// answers [`Cap::Cursor`] with how faithful that is. [`Cursor::Native`] reaches a shape only one
3710/// toolkit names; the `day::cursor::<toolkit>` modules carry those as constants, gated on that
3711/// toolkit's feature, and every other backend ignores a name it does not know.
3712///
3713/// A cursor applies to the node and its descendants until a descendant sets its own.
3714/// [`Cursor::Default`] hands the shape back to the platform rather than pinning an arrow, so a
3715/// reactive cursor can release what it took.
3716#[derive(Clone, Debug, PartialEq, Eq, Hash, Default)]
3717pub enum Cursor {
3718    /// The platform default (an arrow), and the value that releases a node's cursor.
3719    #[default]
3720    Default,
3721    /// A pointing hand: links and other tap-to-activate content.
3722    Pointer,
3723    /// An I-beam over editable or selectable text.
3724    Text,
3725    /// An I-beam for vertical text.
3726    VerticalText,
3727    Crosshair,
3728    /// Four-way move.
3729    Move,
3730    /// An open hand: content that can be dragged.
3731    Grab,
3732    /// A closed hand: content being dragged.
3733    Grabbing,
3734    NotAllowed,
3735    /// The app is busy and cannot take input.
3736    Wait,
3737    /// The app is busy but still takes input.
3738    Progress,
3739    Help,
3740    ContextMenu,
3741    /// A drop will copy.
3742    Copy,
3743    /// A drop will link.
3744    Alias,
3745    /// A table cell.
3746    Cell,
3747    ZoomIn,
3748    ZoomOut,
3749    /// No pointer at all.
3750    None,
3751    /// Vertical (north–south) resize.
3752    NsResize,
3753    /// Horizontal (east–west) resize.
3754    EwResize,
3755    /// Diagonal resize, north-east to south-west.
3756    NeswResize,
3757    /// Diagonal resize, north-west to south-east.
3758    NwseResize,
3759    ColResize,
3760    RowResize,
3761    /// A toolkit's own named cursor, resolved by that backend's lookup and ignored by every
3762    /// other. Prefer the `day::cursor::<toolkit>` constants, which are gated on the toolkit.
3763    Native(std::borrow::Cow<'static, str>),
3764}
3765
3766impl Cursor {
3767    /// A toolkit-specific cursor by its native name (see [`Cursor::Native`]).
3768    pub const fn native(name: &'static str) -> Self {
3769        Cursor::Native(std::borrow::Cow::Borrowed(name))
3770    }
3771
3772    /// The CSS keyword for a named cursor, which GTK and the DOM take as it is. A native cursor
3773    /// answers its own name, so a backend keyed on CSS names may still recognize it.
3774    pub fn css_name(&self) -> &str {
3775        match self {
3776            Cursor::Default => "default",
3777            Cursor::Pointer => "pointer",
3778            Cursor::Text => "text",
3779            Cursor::VerticalText => "vertical-text",
3780            Cursor::Crosshair => "crosshair",
3781            Cursor::Move => "move",
3782            Cursor::Grab => "grab",
3783            Cursor::Grabbing => "grabbing",
3784            Cursor::NotAllowed => "not-allowed",
3785            Cursor::Wait => "wait",
3786            Cursor::Progress => "progress",
3787            Cursor::Help => "help",
3788            Cursor::ContextMenu => "context-menu",
3789            Cursor::Copy => "copy",
3790            Cursor::Alias => "alias",
3791            Cursor::Cell => "cell",
3792            Cursor::ZoomIn => "zoom-in",
3793            Cursor::ZoomOut => "zoom-out",
3794            Cursor::None => "none",
3795            Cursor::NsResize => "ns-resize",
3796            Cursor::EwResize => "ew-resize",
3797            Cursor::NeswResize => "nesw-resize",
3798            Cursor::NwseResize => "nwse-resize",
3799            Cursor::ColResize => "col-resize",
3800            Cursor::RowResize => "row-resize",
3801            Cursor::Native(name) => name,
3802        }
3803    }
3804
3805    /// Every named cursor, in declaration order, what a gallery or a test walks.
3806    pub const NAMED: [Cursor; 25] = [
3807        Cursor::Default,
3808        Cursor::Pointer,
3809        Cursor::Text,
3810        Cursor::VerticalText,
3811        Cursor::Crosshair,
3812        Cursor::Move,
3813        Cursor::Grab,
3814        Cursor::Grabbing,
3815        Cursor::NotAllowed,
3816        Cursor::Wait,
3817        Cursor::Progress,
3818        Cursor::Help,
3819        Cursor::ContextMenu,
3820        Cursor::Copy,
3821        Cursor::Alias,
3822        Cursor::Cell,
3823        Cursor::ZoomIn,
3824        Cursor::ZoomOut,
3825        Cursor::None,
3826        Cursor::NsResize,
3827        Cursor::EwResize,
3828        Cursor::NeswResize,
3829        Cursor::NwseResize,
3830        Cursor::ColResize,
3831        Cursor::RowResize,
3832    ];
3833}
3834
3835/// A set of screen edges, for the `defers_system_gestures` modifier (docs/cover.md). Mirrors
3836/// SwiftUI's `Edge.Set`: on iOS these map to `UIRectEdge` for
3837/// `preferredScreenEdgesDeferringSystemGestures`; on Android any non-empty set enters
3838/// swipe-to-reveal immersive mode (the closest platform analogue).
3839#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
3840pub struct Edges(pub u8);
3841
3842impl Edges {
3843    pub const NONE: Edges = Edges(0);
3844    pub const TOP: Edges = Edges(1);
3845    pub const BOTTOM: Edges = Edges(2);
3846    pub const LEADING: Edges = Edges(4);
3847    pub const TRAILING: Edges = Edges(8);
3848    pub const ALL: Edges = Edges(15);
3849
3850    pub fn contains(self, other: Edges) -> bool {
3851        self.0 & other.0 == other.0
3852    }
3853    pub fn union(self, other: Edges) -> Edges {
3854        Edges(self.0 | other.0)
3855    }
3856    pub fn is_empty(self) -> bool {
3857        self.0 == 0
3858    }
3859}
3860
3861impl std::ops::BitOr for Edges {
3862    type Output = Edges;
3863    fn bitor(self, rhs: Edges) -> Edges {
3864        self.union(rhs)
3865    }
3866}
3867
3868/// The timing curve of an animation (§8.4). Native backends map each variant onto their own
3869/// easing (`CAMediaTimingFunction`, `QEasingCurve`, ArkUI `ARKUI_CURVE_*`, spring animators); the
3870/// canvas/self-driven path samples it via [`Curve::fraction`]. `Spring` matches SwiftUI's
3871/// `.spring(response:dampingFraction:)`.
3872#[derive(Clone, Copy, Debug, PartialEq)]
3873pub enum Curve {
3874    Linear,
3875    EaseIn,
3876    EaseOut,
3877    EaseInOut,
3878    /// `response` = approximate settling period (seconds); `damping` = damping ratio (1.0 =
3879    /// critically damped, `<1` = bouncy overshoot).
3880    Spring {
3881        response: f64,
3882        damping: f64,
3883    },
3884}
3885
3886impl Curve {
3887    /// Fraction of the transition complete at `elapsed` seconds (0 at start, reaching 1, or
3888    /// overshooting it for an under-damped spring). Easing curves clamp to `duration`; springs
3889    /// evaluate their analytic unit-step response and use `duration` only as a settle cap. Drives
3890    /// the self-driven/canvas path; native backends interpolate on their own compositor instead.
3891    pub fn fraction(self, elapsed: f64, duration: f64) -> f64 {
3892        match self {
3893            Curve::Spring { response, damping } => spring_step(response, damping, elapsed),
3894            _ => {
3895                let t = if duration <= 0.0 {
3896                    1.0
3897                } else {
3898                    (elapsed / duration).clamp(0.0, 1.0)
3899                };
3900                self.ease(t)
3901            }
3902        }
3903    }
3904
3905    /// Eased progress for normalized `t` in `0.0..=1.0` (springs pass through; use [`Self::fraction`]).
3906    #[inline]
3907    pub fn ease(self, t: f64) -> f64 {
3908        match self {
3909            Curve::Linear | Curve::Spring { .. } => t,
3910            Curve::EaseIn => t * t,
3911            Curve::EaseOut => 1.0 - (1.0 - t) * (1.0 - t),
3912            Curve::EaseInOut => t * t * (3.0 - 2.0 * t), // smoothstep
3913        }
3914    }
3915
3916    /// Whether the transition has settled, so the canvas frame clock can stop ticking it.
3917    pub fn is_settled(self, elapsed: f64, duration: f64) -> bool {
3918        match self {
3919            Curve::Spring { response, damping } => {
3920                let cap = response.max(0.0) * 4.0 + 0.2;
3921                if elapsed >= cap {
3922                    return true;
3923                }
3924                (spring_step(response, damping, elapsed) - 1.0).abs() < 0.001
3925                    && elapsed > response * 0.5
3926            }
3927            _ => elapsed >= duration.max(0.0),
3928        }
3929    }
3930}
3931
3932/// Unit-step response of a second-order spring (`response` = period seconds, `damping` = ratio),
3933/// evaluated at `t` seconds. Under-damped rings and overshoots; critically/over-damped eases in.
3934fn spring_step(response: f64, damping: f64, t: f64) -> f64 {
3935    if response <= 0.0 || t <= 0.0 {
3936        return if t <= 0.0 { 0.0 } else { 1.0 };
3937    }
3938    let omega0 = std::f64::consts::TAU / response;
3939    let zeta = damping.max(0.0);
3940    if zeta < 1.0 {
3941        let omega_d = omega0 * (1.0 - zeta * zeta).sqrt();
3942        let e = (-zeta * omega0 * t).exp();
3943        1.0 - e * ((omega_d * t).cos() + (zeta * omega0 / omega_d) * (omega_d * t).sin())
3944    } else {
3945        let e = (-omega0 * t).exp();
3946        1.0 - e * (1.0 + omega0 * t)
3947    }
3948}
3949
3950/// Animation intent (§8.4). Native-widget backends map it onto their own animator (Core Animation,
3951/// `ViewPropertyAnimator`, XAML Composition, `OH_ArkUI_AnimateTo`, …); the canvas/self-driven path
3952/// samples `curve` via [`Curve::fraction`]. Threaded through `Toolkit::update`/`set_frame`/
3953/// `set_opacity`/`set_transform`.
3954#[derive(Clone, Copy, Debug, PartialEq)]
3955pub struct AnimSpec {
3956    pub duration_ms: u32,
3957    pub delay_ms: u32,
3958    pub curve: Curve,
3959    /// Repeat count beyond the first play (`0` = play once); `u32::MAX` = repeat forever.
3960    pub repeat: u32,
3961    pub autoreverse: bool,
3962}
3963
3964impl Default for AnimSpec {
3965    /// The default feel: a smooth spring (SwiftUI's modern default).
3966    fn default() -> Self {
3967        AnimSpec {
3968            duration_ms: 350,
3969            delay_ms: 0,
3970            curve: Curve::Spring {
3971                response: 0.4,
3972                damping: 0.8,
3973            },
3974            repeat: 0,
3975            autoreverse: false,
3976        }
3977    }
3978}
3979
3980impl AnimSpec {
3981    /// A smooth spring: `response` = settling period (s), `damping` = ratio (1.0 = no bounce, `<1`
3982    /// bouncy). `duration_ms` is a nominal cap for backends that need a duration; spring backends
3983    /// use `response`/`damping` directly.
3984    pub fn spring(response: f64, damping: f64) -> Self {
3985        AnimSpec {
3986            // `response` is the animation's duration: every backend maps a spring to a
3987            // fixed-duration overshoot curve over exactly `duration_ms`, so timing is identical
3988            // across toolkits (a physics spring's settle time would vary per platform).
3989            duration_ms: (response * 1000.0).max(50.0) as u32,
3990            delay_ms: 0,
3991            curve: Curve::Spring { response, damping },
3992            repeat: 0,
3993            autoreverse: false,
3994        }
3995    }
3996    pub fn linear(duration_ms: u32) -> Self {
3997        Self::timed(duration_ms, Curve::Linear)
3998    }
3999    pub fn ease_in(duration_ms: u32) -> Self {
4000        Self::timed(duration_ms, Curve::EaseIn)
4001    }
4002    pub fn ease_out(duration_ms: u32) -> Self {
4003        Self::timed(duration_ms, Curve::EaseOut)
4004    }
4005    pub fn ease_in_out(duration_ms: u32) -> Self {
4006        Self::timed(duration_ms, Curve::EaseInOut)
4007    }
4008    fn timed(duration_ms: u32, curve: Curve) -> Self {
4009        AnimSpec {
4010            duration_ms,
4011            delay_ms: 0,
4012            curve,
4013            repeat: 0,
4014            autoreverse: false,
4015        }
4016    }
4017    /// Delay before the animation starts (builder).
4018    pub fn delay(mut self, ms: u32) -> Self {
4019        self.delay_ms = ms;
4020        self
4021    }
4022    /// Repeat `count` extra times (builder); `autoreverse` ping-pongs each cycle.
4023    pub fn repeat(mut self, count: u32, autoreverse: bool) -> Self {
4024        self.repeat = count;
4025        self.autoreverse = autoreverse;
4026        self
4027    }
4028    /// Repeat forever (builder), e.g. a pulsing indicator.
4029    pub fn repeat_forever(mut self, autoreverse: bool) -> Self {
4030        self.repeat = u32::MAX;
4031        self.autoreverse = autoreverse;
4032        self
4033    }
4034    #[inline]
4035    pub fn duration_secs(&self) -> f64 {
4036        self.duration_ms as f64 / 1000.0
4037    }
4038    #[inline]
4039    pub fn delay_secs(&self) -> f64 {
4040        self.delay_ms as f64 / 1000.0
4041    }
4042}
4043
4044#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
4045pub enum Role {
4046    #[default]
4047    None,
4048    Button,
4049    Toggle,
4050    Slider,
4051    TextInput,
4052    Heading(u8),
4053    Image,
4054    Meter,
4055    Group,
4056    /// A hierarchical tree container (docs/tree.md): `role="tree"`, `AXOutline`.
4057    Tree,
4058    /// One row of a tree: `role="treeitem"`, with level/expanded state where the platform
4059    /// carries them (docs/tree.md).
4060    TreeItem,
4061    /// One tab in a strip of peers (`role="tab"`, `AXTabButton`): the composed document
4062    /// strip's title buttons. Pair it with [`A11yProps::selected`] for the current one.
4063    Tab,
4064    /// The strip holding tabs (`role="tablist"`, `AXTabGroup`).
4065    TabList,
4066}
4067
4068impl Role {
4069    /// The a11y role a built-in piece kind reports natively, the audit's *expectation* when the
4070    /// user hasn't set an explicit `.role()`. Native controls already expose these, so Day records
4071    /// them for `a11y_audit` (§14.2) rather than overriding the widget; only canvas/custom pieces
4072    /// need Day to apply a role. Returns `None` for kinds with no inherent control role.
4073    pub fn for_kind(kind: PieceKind) -> Role {
4074        match kind {
4075            kinds::BUTTON => Role::Button,
4076            kinds::TOGGLE => Role::Toggle,
4077            kinds::SLIDER => Role::Slider,
4078            kinds::TEXT_FIELD => Role::TextInput,
4079            kinds::IMAGE => Role::Image,
4080            kinds::PROGRESS => Role::Meter,
4081            kinds::TREE => Role::Tree,
4082            _ => Role::None,
4083        }
4084    }
4085}
4086
4087#[derive(Clone, Debug, Default, PartialEq)]
4088pub struct A11yProps {
4089    pub label: Option<String>,
4090    pub hint: Option<String>,
4091    pub value: Option<String>,
4092    pub role: Role,
4093    pub identifier: Option<String>,
4094    pub hidden: bool,
4095    pub decorative: bool,
4096    /// Whether the element is the selected one among its peers (a tab, a row): the
4097    /// platform's selected state, read aloud as such. `None` leaves the widget's own answer.
4098    pub selected: Option<bool>,
4099}
4100
4101impl A11yProps {
4102    /// Merge another set of annotations onto this one: any field `other` sets (a `Some`, a
4103    /// non-`None` role, or a `true` flag) overrides ours; unset fields are left intact. Lets a
4104    /// node accumulate its `.a11y()`, `.id()`, and piece defaults into one stored result, so
4105    /// each `set_a11y` re-applies the full picture and `a11y_audit` has the complete expectation.
4106    pub fn merge(&mut self, other: &A11yProps) {
4107        if other.label.is_some() {
4108            self.label = other.label.clone();
4109        }
4110        if other.hint.is_some() {
4111            self.hint = other.hint.clone();
4112        }
4113        if other.value.is_some() {
4114            self.value = other.value.clone();
4115        }
4116        if other.role != Role::None {
4117            self.role = other.role;
4118        }
4119        if other.identifier.is_some() {
4120            self.identifier = other.identifier.clone();
4121        }
4122        self.hidden |= other.hidden;
4123        self.decorative |= other.decorative;
4124        if other.selected.is_some() {
4125            self.selected = other.selected;
4126        }
4127    }
4128
4129    /// The role to *expect* for a node of `kind` carrying these annotations: an explicit
4130    /// `.role()` wins, otherwise the kind's native default (`Role::for_kind`).
4131    pub fn resolved_role(&self, kind: PieceKind) -> Role {
4132        if self.role != Role::None {
4133            self.role
4134        } else {
4135            Role::for_kind(kind)
4136        }
4137    }
4138}
4139
4140/// A widget's actual native state, read back from the platform by `Toolkit::read_native`
4141/// (docs/testing.md): what the widget itself shows and reports, independently of Day's tree,
4142/// so `a11y_audit` and `assert_native` (§14.2) can diff it against Day's expectation.
4143///
4144/// Two groups. The accessibility fields (`role`, `label`, `value`, `identifier`) are read
4145/// together and `found` says whether they were: `found = false` means the backend cannot read
4146/// its accessibility tree, and the audit skips the node. Every other field is read on its own,
4147/// and `None` means "not read": the backend cannot read it, or it does not apply to this kind.
4148/// A reader never reports a field it did not take from the widget, so a `None` is a recorded
4149/// gap rather than a pass.
4150#[derive(Clone, Debug, Default, PartialEq)]
4151pub struct NativeSnapshot {
4152    /// The accessibility fields below were read.
4153    pub found: bool,
4154    /// The native role mapped back to Day's `Role` (best-effort).
4155    pub role: Role,
4156    /// The accessibility label the platform reports.
4157    pub label: Option<String>,
4158    /// The accessibility value the platform reports.
4159    pub value: Option<String>,
4160    /// The automation identifier, which Day sets from `.id()`.
4161    pub identifier: Option<String>,
4162    /// The text the widget displays: a label's string, a button's title, a text field's or
4163    /// text area's contents, without markup or mnemonic markers. `None` for a secure field
4164    /// that masks it.
4165    pub text: Option<String>,
4166    /// A slider's or progress indicator's value, in the range Day gave it.
4167    pub number: Option<f64>,
4168    /// A toggle's state, or a button's selected state (`ButtonProps::selected`).
4169    pub checked: Option<bool>,
4170    /// Whether the widget takes input.
4171    pub enabled: Option<bool>,
4172    /// Whether the widget is shown: not hidden itself, nor by an ancestor.
4173    pub visible: Option<bool>,
4174    /// The widget's frame in points, relative to the window's content area, origin top left.
4175    pub frame: Option<Rect>,
4176}
4177
4178// ---------------------------------------------------------------------------
4179// Canvas display list (§11): full op set lands with M8a; the types are v1.
4180// ---------------------------------------------------------------------------
4181
4182#[derive(Clone, Debug, PartialEq)]
4183pub enum Shape {
4184    Rect(Rect),
4185    RoundedRect(Rect, f64),
4186    Ellipse(Rect),
4187    /// Arc within `rect`'s inscribed ellipse; angles in degrees, 0 = +x axis, clockwise.
4188    Arc {
4189        rect: Rect,
4190        start_deg: f64,
4191        sweep_deg: f64,
4192    },
4193    Line(Point, Point),
4194    Polygon(Vec<Point>),
4195    /// An arbitrary path: curves, several contours, and a fill rule (docs/canvas.md).
4196    ///
4197    /// [`Shape::Polygon`] is the straight-line, single-contour special case, kept because it is
4198    /// what most drawing code wants and it encodes far more compactly.
4199    Path(Path),
4200}
4201
4202impl Shape {
4203    /// A rectangle rounded corner by corner (docs/canvas.md "Rounded corners"), as the simplest
4204    /// shape that draws it: a plain [`Shape::Rect`] when every corner is square, a
4205    /// [`Shape::RoundedRect`] (each toolkit's own rounded rectangle) when the corners agree, and a
4206    /// path ([`rounded_rect_segs`]) otherwise. The radii are [fitted](CornerRadii::fitted) first.
4207    ///
4208    /// ```
4209    /// use day_spec::{CornerRadii, Rect, Shape};
4210    ///
4211    /// // A bar standing on its axis: rounded on top, square where it meets the baseline.
4212    /// let bar = Shape::rounded_rect(Rect::new(0.0, 0.0, 20.0, 80.0), CornerRadii::top(6.0));
4213    /// assert!(matches!(bar, Shape::Path(_)));
4214    /// ```
4215    pub fn rounded_rect(rect: Rect, radii: CornerRadii) -> Shape {
4216        let r = radii.fitted(rect.size);
4217        if r.is_zero() || rect.size.width <= 0.0 || rect.size.height <= 0.0 {
4218            Shape::Rect(rect)
4219        } else if r.is_uniform() {
4220            Shape::RoundedRect(rect, r.top_left)
4221        } else {
4222            Shape::Path(Path {
4223                segs: rounded_rect_segs(rect, r),
4224                rule: FillRule::NonZero,
4225            })
4226        }
4227    }
4228
4229    /// The same shape moved by `(dx, dy)`.
4230    ///
4231    /// What a [`Stamp`] means by "the template translated by one point", and the one definition of
4232    /// it: a backend builds each copy of a batch with this rather than reaching for its own
4233    /// platform transform, so every toolkit stamps to the same coordinates.
4234    pub fn translated(&self, dx: f64, dy: f64) -> Shape {
4235        let r = |r: &Rect| {
4236            Rect::new(
4237                r.origin.x + dx,
4238                r.origin.y + dy,
4239                r.size.width,
4240                r.size.height,
4241            )
4242        };
4243        let p = |p: &Point| Point::new(p.x + dx, p.y + dy);
4244        match self {
4245            Shape::Rect(rect) => Shape::Rect(r(rect)),
4246            Shape::RoundedRect(rect, rad) => Shape::RoundedRect(r(rect), *rad),
4247            Shape::Ellipse(rect) => Shape::Ellipse(r(rect)),
4248            Shape::Arc {
4249                rect,
4250                start_deg,
4251                sweep_deg,
4252            } => Shape::Arc {
4253                rect: r(rect),
4254                start_deg: *start_deg,
4255                sweep_deg: *sweep_deg,
4256            },
4257            Shape::Line(a, b) => Shape::Line(p(a), p(b)),
4258            Shape::Polygon(pts) => Shape::Polygon(pts.iter().map(p).collect()),
4259            Shape::Path(path) => Shape::Path(Path {
4260                segs: path
4261                    .segs
4262                    .iter()
4263                    .map(|seg| match seg {
4264                        PathSeg::Move(a) => PathSeg::Move(p(a)),
4265                        PathSeg::Line(a) => PathSeg::Line(p(a)),
4266                        PathSeg::Quad(c, a) => PathSeg::Quad(p(c), p(a)),
4267                        PathSeg::Cubic(c1, c2, a) => PathSeg::Cubic(p(c1), p(c2), p(a)),
4268                        PathSeg::Close => PathSeg::Close,
4269                    })
4270                    .collect(),
4271                rule: path.rule,
4272            }),
4273        }
4274    }
4275
4276    /// The shape's bounding rectangle: the box gradient [`UnitPoint`]s resolve against.
4277    pub fn bounds(&self) -> Rect {
4278        match self {
4279            Shape::Rect(r) | Shape::RoundedRect(r, _) | Shape::Ellipse(r) => *r,
4280            Shape::Arc { rect, .. } => *rect,
4281            Shape::Line(a, b) => points_bounds(&[*a, *b]),
4282            Shape::Polygon(pts) => points_bounds(pts),
4283            Shape::Path(p) => p.bounds(),
4284        }
4285    }
4286}
4287
4288/// One step of a [`Path`]. Points are absolute, in the canvas's coordinate space.
4289#[derive(Clone, Copy, Debug, PartialEq)]
4290pub enum PathSeg {
4291    /// Start a new contour at this point.
4292    Move(Point),
4293    Line(Point),
4294    /// Quadratic bezier: one control point, then the end point.
4295    Quad(Point, Point),
4296    /// Cubic bezier: two control points, then the end point.
4297    Cubic(Point, Point, Point),
4298    /// Close the current contour back to its `Move`.
4299    Close,
4300}
4301
4302/// Which points count as inside when a path's contours overlap (docs/canvas.md).
4303///
4304/// This matters the moment a shape has a hole: the counter of an "o", a washer, a ring chart. It
4305/// is a property of the fill, so stroking ignores it.
4306#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
4307pub enum FillRule {
4308    /// Direction-sensitive: a hole needs its contour wound the opposite way. Every 2-D API's
4309    /// default, and what a font's glyph outlines assume.
4310    #[default]
4311    NonZero,
4312    /// Parity: any contour inside another cuts a hole regardless of winding. What PDF's `f*`
4313    /// operator and SVG's `fill-rule: evenodd` mean.
4314    EvenOdd,
4315}
4316
4317/// An arbitrary 2-D path: any number of contours, straight or curved, with a fill rule.
4318#[derive(Clone, Debug, PartialEq, Default)]
4319pub struct Path {
4320    pub segs: Vec<PathSeg>,
4321    pub rule: FillRule,
4322}
4323
4324impl Path {
4325    /// A conservative bounding box: the hull of every point including control points, which
4326    /// contains the true curve bounds (a bezier stays inside its control hull). Used only to
4327    /// resolve gradient unit points, where being slightly generous costs nothing and computing
4328    /// exact curve extrema would not.
4329    pub fn bounds(&self) -> Rect {
4330        let mut pts: Vec<Point> = Vec::with_capacity(self.segs.len() * 3);
4331        for seg in &self.segs {
4332            match seg {
4333                PathSeg::Move(p) | PathSeg::Line(p) => pts.push(*p),
4334                PathSeg::Quad(c, p) => pts.extend_from_slice(&[*c, *p]),
4335                PathSeg::Cubic(c1, c2, p) => pts.extend_from_slice(&[*c1, *c2, *p]),
4336                PathSeg::Close => {}
4337            }
4338        }
4339        points_bounds(&pts)
4340    }
4341}
4342
4343/// A radius for each corner of a rectangle, clockwise from the top left (docs/canvas.md "Rounded
4344/// corners"). The shape a bar in a chart wants (rounded at its value end, square against its
4345/// axis), a tab (rounded on top), or a card joined to its neighbor.
4346///
4347/// Radii are in points and never negative. [`CornerRadii::fitted`] shrinks them the way CSS
4348/// does when two radii on one side would overlap, which is what a caller animating a radius or
4349/// drawing a short bar needs to not think about.
4350#[derive(Clone, Copy, Debug, PartialEq, Default)]
4351pub struct CornerRadii {
4352    pub top_left: f64,
4353    pub top_right: f64,
4354    pub bottom_right: f64,
4355    pub bottom_left: f64,
4356}
4357
4358impl CornerRadii {
4359    /// The same radius on every corner: what [`Shape::RoundedRect`] draws.
4360    pub fn uniform(r: f64) -> Self {
4361        CornerRadii {
4362            top_left: r,
4363            top_right: r,
4364            bottom_right: r,
4365            bottom_left: r,
4366        }
4367    }
4368    /// Rounded along the top edge, square along the bottom: a bar standing on its axis.
4369    pub fn top(r: f64) -> Self {
4370        CornerRadii {
4371            top_left: r,
4372            top_right: r,
4373            ..Default::default()
4374        }
4375    }
4376    /// Rounded along the bottom edge: a bar hanging below its axis.
4377    pub fn bottom(r: f64) -> Self {
4378        CornerRadii {
4379            bottom_right: r,
4380            bottom_left: r,
4381            ..Default::default()
4382        }
4383    }
4384    /// Rounded along the left edge: a bar growing leftward from its axis.
4385    pub fn left(r: f64) -> Self {
4386        CornerRadii {
4387            top_left: r,
4388            bottom_left: r,
4389            ..Default::default()
4390        }
4391    }
4392    /// Rounded along the right edge: a bar growing rightward from its axis.
4393    pub fn right(r: f64) -> Self {
4394        CornerRadii {
4395            top_right: r,
4396            bottom_right: r,
4397            ..Default::default()
4398        }
4399    }
4400
4401    /// The four radii, clockwise from the top left.
4402    pub fn to_array(self) -> [f64; 4] {
4403        [
4404            self.top_left,
4405            self.top_right,
4406            self.bottom_right,
4407            self.bottom_left,
4408        ]
4409    }
4410
4411    /// Whether every corner is square.
4412    pub fn is_zero(self) -> bool {
4413        self.to_array().iter().all(|r| *r <= 0.0)
4414    }
4415
4416    /// Whether every corner has the same radius, so the rectangle is a [`Shape::RoundedRect`].
4417    pub fn is_uniform(self) -> bool {
4418        let [a, b, c, d] = self.to_array();
4419        a == b && b == c && c == d
4420    }
4421
4422    /// These radii made to fit a `size` rectangle, the rule CSS uses for `border-radius`: a
4423    /// negative or non-finite radius is square, and when the two radii along any side add up to
4424    /// more than that side, every radius is scaled down by the same factor until none overlap.
4425    /// Scaling all four together keeps the corners in proportion, where clamping each one alone
4426    /// would turn a pill into a lopsided shape.
4427    pub fn fitted(self, size: Size) -> Self {
4428        let clean = |r: f64| if r.is_finite() && r > 0.0 { r } else { 0.0 };
4429        let [tl, tr, br, bl] = self.to_array().map(clean);
4430        let (w, h) = (size.width.max(0.0), size.height.max(0.0));
4431        let factor = [(w, tl + tr), (w, bl + br), (h, tl + bl), (h, tr + br)]
4432            .into_iter()
4433            .filter(|(_, sum)| *sum > 0.0)
4434            .map(|(side, sum)| side / sum)
4435            .fold(1.0f64, f64::min);
4436        CornerRadii {
4437            top_left: tl * factor,
4438            top_right: tr * factor,
4439            bottom_right: br * factor,
4440            bottom_left: bl * factor,
4441        }
4442    }
4443}
4444
4445/// The point `angle_deg` round a circle: degrees, `0` = the +x axis, positive clockwise in device
4446/// space (y down), the convention [`Shape::Arc`] and every arc helper here use.
4447pub fn arc_point(center: Point, radius: f64, angle_deg: f64) -> Point {
4448    let a = angle_deg.to_radians();
4449    Point::new(center.x + radius * a.cos(), center.y + radius * a.sin())
4450}
4451
4452/// A circular arc as cubic beziers: `sweep_deg` of a circle of `radius` about `center`, from
4453/// `start_deg` ([`arc_point`]'s convention). The segments start *from* the arc's first point, which
4454/// the caller reaches itself (a move or a line); nothing for a zero or non-finite radius or sweep.
4455///
4456/// The arc is split into quarter turns at most, where a cubic tracks a circle best: the radial
4457/// error peaks at 2.7 × 10⁻⁴ of the radius, a quarter of a pixel on a circle a thousand points
4458/// across (docs/canvas.md "Paths"). The same beziers on every backend mean the same pixels on
4459/// every backend, which an arc op interpreted by nine rasterizers would not.
4460pub fn arc_cubics(center: Point, radius: f64, start_deg: f64, sweep_deg: f64) -> Vec<PathSeg> {
4461    let (start, sweep) = (start_deg.to_radians(), sweep_deg.to_radians());
4462    if !radius.is_finite() || radius <= 0.0 || !sweep.is_finite() || sweep == 0.0 {
4463        return Vec::new();
4464    }
4465    let at = |a: f64| Point::new(center.x + radius * a.cos(), center.y + radius * a.sin());
4466    let steps = (sweep.abs() / std::f64::consts::FRAC_PI_2).ceil() as usize;
4467    let delta = sweep / steps as f64;
4468    // The exact control-handle length for a circular arc of this sweep. Negative for a negative
4469    // sweep, which is what turns the handles around for a counter-clockwise arc.
4470    let k = 4.0 / 3.0 * (delta / 4.0).tan() * radius;
4471    (0..steps)
4472        .map(|i| {
4473            let a = start + delta * i as f64;
4474            let b = a + delta;
4475            let (p0, p1) = (at(a), at(b));
4476            PathSeg::Cubic(
4477                Point::new(p0.x - k * a.sin(), p0.y + k * a.cos()),
4478                Point::new(p1.x + k * b.sin(), p1.y - k * b.cos()),
4479                p1,
4480            )
4481        })
4482        .collect()
4483}
4484
4485/// The closed contour of a rectangle rounded corner by corner, clockwise from the top left, with
4486/// the radii [fitted](CornerRadii::fitted) first. A square corner is a sharp point, not a
4487/// zero-length curve.
4488pub fn rounded_rect_segs(rect: Rect, radii: CornerRadii) -> Vec<PathSeg> {
4489    let r = radii.fitted(rect.size);
4490    let (x0, y0) = (rect.origin.x, rect.origin.y);
4491    let (x1, y1) = (x0 + rect.size.width, y0 + rect.size.height);
4492    // Each corner: the point where its curve starts, then the quarter turn round its center.
4493    let corners = [
4494        (
4495            Point::new(x0 + r.top_left, y0 + r.top_left),
4496            r.top_left,
4497            180.0,
4498        ),
4499        (
4500            Point::new(x1 - r.top_right, y0 + r.top_right),
4501            r.top_right,
4502            270.0,
4503        ),
4504        (
4505            Point::new(x1 - r.bottom_right, y1 - r.bottom_right),
4506            r.bottom_right,
4507            0.0,
4508        ),
4509        (
4510            Point::new(x0 + r.bottom_left, y1 - r.bottom_left),
4511            r.bottom_left,
4512            90.0,
4513        ),
4514    ];
4515    let mut segs = Vec::with_capacity(14);
4516    for (i, (center, radius, start)) in corners.into_iter().enumerate() {
4517        let first = arc_point(center, radius, start);
4518        segs.push(if i == 0 {
4519            PathSeg::Move(first)
4520        } else {
4521            PathSeg::Line(first)
4522        });
4523        segs.extend(arc_cubics(center, radius, start, 90.0));
4524    }
4525    segs.push(PathSeg::Close);
4526    segs
4527}
4528
4529/// How a stroked line ends (docs/canvas.md). Names match PDF's `J`, SVG's `stroke-linecap`, and
4530/// every native 2-D API.
4531#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
4532pub enum LineCap {
4533    #[default]
4534    Butt,
4535    Round,
4536    Square,
4537}
4538
4539/// How two stroked segments meet (docs/canvas.md). Matches PDF's `j` and SVG's
4540/// `stroke-linejoin`.
4541#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
4542pub enum LineJoin {
4543    #[default]
4544    Miter,
4545    Round,
4546    Bevel,
4547}
4548
4549/// Everything about a stroke except its paint.
4550///
4551/// [`StrokeStyle::width`] and `From<f64>` keep the common "just a width" case a single
4552/// argument, so plain `stroke(shape, color, 2.0)` call sites read the same as they always did.
4553#[derive(Clone, Debug, PartialEq)]
4554pub struct StrokeStyle {
4555    pub width: f64,
4556    pub cap: LineCap,
4557    pub join: LineJoin,
4558    /// Ignored unless `join` is [`LineJoin::Miter`]. The 2-D convention: past this ratio of miter
4559    /// length to line width the join falls back to a bevel.
4560    pub miter_limit: f64,
4561    /// On/off run lengths, repeating. Empty means solid.
4562    pub dash: Vec<f64>,
4563    /// How far into the dash pattern the line starts.
4564    pub dash_phase: f64,
4565}
4566
4567impl Default for StrokeStyle {
4568    fn default() -> Self {
4569        // 10.0 is the miter limit PDF, PostScript, SVG and Cairo all default to.
4570        StrokeStyle {
4571            width: 1.0,
4572            cap: LineCap::Butt,
4573            join: LineJoin::Miter,
4574            miter_limit: 10.0,
4575            dash: Vec::new(),
4576            dash_phase: 0.0,
4577        }
4578    }
4579}
4580
4581impl StrokeStyle {
4582    /// A solid stroke of `width`, everything else default.
4583    pub fn width(width: f64) -> Self {
4584        StrokeStyle {
4585            width,
4586            ..Default::default()
4587        }
4588    }
4589    /// A dashed stroke: `dash` is on/off run lengths, repeating.
4590    pub fn dashed(width: f64, dash: Vec<f64>) -> Self {
4591        StrokeStyle {
4592            width,
4593            dash,
4594            ..Default::default()
4595        }
4596    }
4597    /// Rounded ends and joins, the shape a data line usually wants.
4598    pub fn round(width: f64) -> Self {
4599        StrokeStyle {
4600            width,
4601            cap: LineCap::Round,
4602            join: LineJoin::Round,
4603            ..Default::default()
4604        }
4605    }
4606    /// Is this the plain width-only stroke every pre-existing call site asks for? Backends use
4607    /// it to skip setting dash/cap/join state they would only have to set back.
4608    pub fn is_plain(&self) -> bool {
4609        self.cap == LineCap::Butt
4610            && self.join == LineJoin::Miter
4611            && self.dash.is_empty()
4612            && self.miter_limit == 10.0
4613    }
4614}
4615
4616impl From<f64> for StrokeStyle {
4617    fn from(width: f64) -> Self {
4618        StrokeStyle::width(width)
4619    }
4620}
4621
4622fn points_bounds(pts: &[Point]) -> Rect {
4623    let (mut x0, mut y0, mut x1, mut y1) = (f64::MAX, f64::MAX, f64::MIN, f64::MIN);
4624    for p in pts {
4625        x0 = x0.min(p.x);
4626        y0 = y0.min(p.y);
4627        x1 = x1.max(p.x);
4628        y1 = y1.max(p.y);
4629    }
4630    if pts.is_empty() {
4631        return Rect::ZERO;
4632    }
4633    Rect::new(x0, y0, x1 - x0, y1 - y0)
4634}
4635
4636/// A point in the unit space of a shape's bounding box: (0,0) = top-leading, (1,1) =
4637/// bottom-trailing. Gradient geometry is expressed in unit points so one paint value works for
4638/// any shape size (docs/shapes.md §3.2).
4639#[derive(Clone, Copy, Debug, PartialEq)]
4640pub struct UnitPoint {
4641    pub x: f64,
4642    pub y: f64,
4643}
4644
4645impl UnitPoint {
4646    pub const fn new(x: f64, y: f64) -> Self {
4647        UnitPoint { x, y }
4648    }
4649    pub const TOP: UnitPoint = UnitPoint::new(0.5, 0.0);
4650    pub const BOTTOM: UnitPoint = UnitPoint::new(0.5, 1.0);
4651    pub const LEADING: UnitPoint = UnitPoint::new(0.0, 0.5);
4652    pub const TRAILING: UnitPoint = UnitPoint::new(1.0, 0.5);
4653    pub const TOP_LEADING: UnitPoint = UnitPoint::new(0.0, 0.0);
4654    pub const TOP_TRAILING: UnitPoint = UnitPoint::new(1.0, 0.0);
4655    pub const BOTTOM_LEADING: UnitPoint = UnitPoint::new(0.0, 1.0);
4656    pub const BOTTOM_TRAILING: UnitPoint = UnitPoint::new(1.0, 1.0);
4657    pub const CENTER: UnitPoint = UnitPoint::new(0.5, 0.5);
4658
4659    /// Resolve to an absolute point within `rect`.
4660    pub fn resolve(&self, rect: Rect) -> Point {
4661        Point::new(
4662            rect.origin.x + self.x * rect.size.width,
4663            rect.origin.y + self.y * rect.size.height,
4664        )
4665    }
4666}
4667
4668/// A linear gradient (docs/shapes.md §3.2 / §7): color stops along the line from `start` to
4669/// `end`, both in the unit space of the filled shape's bounding box. Stops are
4670/// `(offset 0..=1, color)`, ascending.
4671#[derive(Clone, Debug, PartialEq)]
4672pub struct LinearGradient {
4673    pub start: UnitPoint,
4674    pub end: UnitPoint,
4675    pub stops: Vec<(f64, Color)>,
4676}
4677
4678impl LinearGradient {
4679    pub fn new(start: UnitPoint, end: UnitPoint, stops: Vec<(f64, Color)>) -> Self {
4680        LinearGradient { start, end, stops }
4681    }
4682    /// Top-to-bottom between two colors: the everyday sky/backdrop case.
4683    pub fn vertical(top: Color, bottom: Color) -> Self {
4684        LinearGradient::new(
4685            UnitPoint::TOP,
4686            UnitPoint::BOTTOM,
4687            vec![(0.0, top), (1.0, bottom)],
4688        )
4689    }
4690    /// Leading-to-trailing between two colors.
4691    pub fn horizontal(leading: Color, trailing: Color) -> Self {
4692        LinearGradient::new(
4693            UnitPoint::LEADING,
4694            UnitPoint::TRAILING,
4695            vec![(0.0, leading), (1.0, trailing)],
4696        )
4697    }
4698}
4699
4700/// A radial gradient (docs/shapes.md §3.2 / §7): color stops from `center` outward. Both the
4701/// center and the radius live in the unit space of the filled shape's bounding box, so the
4702/// gradient stretches into an ellipse when the bounds aren't square (the XAML relative-brush
4703/// behavior; the other backends reproduce it with a local matrix on a circular gradient). A
4704/// `radius` of `0.5` from the default center touches the edge midpoints of the bounds.
4705#[derive(Clone, Debug, PartialEq)]
4706pub struct RadialGradient {
4707    pub center: UnitPoint,
4708    pub radius: f64,
4709    pub stops: Vec<(f64, Color)>,
4710}
4711
4712impl RadialGradient {
4713    pub fn new(center: UnitPoint, radius: f64, stops: Vec<(f64, Color)>) -> Self {
4714        RadialGradient {
4715            center,
4716            radius,
4717            stops,
4718        }
4719    }
4720    /// Centered, edge-touching (radius 0.5) between two colors: the everyday glow case.
4721    pub fn centered(inner: Color, outer: Color) -> Self {
4722        RadialGradient::new(UnitPoint::CENTER, 0.5, vec![(0.0, inner), (1.0, outer)])
4723    }
4724}
4725
4726/// The payload of [`DrawOp::Stamp`]: one shape drawn at every position in `at`.
4727///
4728/// A scatter plot is the case this exists for. Drawn as individual ops, fifty thousand points are
4729/// fifty thousand `DrawOp`s, rebuilt, compared and cloned on every frame that re-records, before
4730/// a backend draws anything. As one `Stamp` they are one op and a flat array of coordinates, and
4731/// a backend can put every copy into one path and hand the rasterizer a single fill.
4732///
4733/// Every copy shares the shape, the size and the paint. Varying any of those means more than one
4734/// stamp: group by what varies, which for a chart is usually the series color.
4735#[derive(Clone, Debug, PartialEq)]
4736pub struct Stamp {
4737    /// The template, authored around the origin: each copy is this shape translated by one point.
4738    /// A 6-point dot is `Shape::Ellipse(Rect::new(-3.0, -3.0, 6.0, 6.0))`.
4739    pub shape: Shape,
4740    /// Where the copies go. Order is the drawing order, so later points paint over earlier ones.
4741    pub at: Vec<Point>,
4742    pub paint: Paint,
4743    /// `None` fills each copy; `Some` strokes it with this style.
4744    pub stroke: Option<StrokeStyle>,
4745}
4746
4747/// A fill source: a solid color, or a linear/radial gradient (docs/shapes.md §3.2; angular and
4748/// semantic tokens are later phases). `From<Color>` keeps every existing `fill(shape, color)`
4749/// call site compiling unchanged.
4750#[derive(Clone, Debug, PartialEq)]
4751pub enum Paint {
4752    Solid(Color),
4753    Linear(LinearGradient),
4754    Radial(RadialGradient),
4755}
4756
4757impl From<Color> for Paint {
4758    fn from(c: Color) -> Self {
4759        Paint::Solid(c)
4760    }
4761}
4762
4763impl From<LinearGradient> for Paint {
4764    fn from(g: LinearGradient) -> Self {
4765        Paint::Linear(g)
4766    }
4767}
4768
4769impl From<RadialGradient> for Paint {
4770    fn from(g: RadialGradient) -> Self {
4771        Paint::Radial(g)
4772    }
4773}
4774
4775/// Where `at` sits vertically. `Top`, `Middle` and `Bottom` are edges of the line box (ascent +
4776/// descent at the font's size, the box [`Toolkit::measure_text`] reports); `Baseline` is the
4777/// typographic baseline itself.
4778#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
4779pub enum TextVAlign {
4780    /// `at` is the top of the line box.
4781    #[default]
4782    Top,
4783    /// `at` is the vertical middle of the line box.
4784    Middle,
4785    /// `at` is the baseline itself: what every native 2-D text call takes, and what a run of labels
4786    /// sharing a line should align on rather than their individual boxes.
4787    Baseline,
4788    /// `at` is the bottom of the line box.
4789    Bottom,
4790}
4791
4792/// How canvas text hangs on its `at` point: one placement per axis (docs/canvas.md "Text").
4793///
4794/// Two axes rather than a list of named positions, because that is the shape of the problem and
4795/// of every native API underneath: `NSAttributedString` drawing, Pango extents,
4796/// `QFontMetricsF`, `Paint.Align`, Canvas2D's `textAlign`/`textBaseline`. The alignment is done
4797/// by the backend, which is both cheaper and more accurate than doing it in app code: it already
4798/// has the laid-out metrics, where an app has to ask for them through
4799/// [`Toolkit::measure_text`] first.
4800///
4801/// [`TextAnchor::LEADING`] and [`TextAnchor::CENTERED`] name the two placements that used to be
4802/// this type's only variants.
4803#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
4804pub struct TextAnchor {
4805    /// The horizontal placement: the same three-way leading/center/trailing a wrapped label's
4806    /// lines take ([`props::TextAlign`]), because it is the same question with the same RTL rule.
4807    /// `Trailing` is what an axis label right-aligned against its axis wants, and the reason the
4808    /// horizontal axis is settable at all: emulating it in app code costs a
4809    /// [`Toolkit::measure_text`] call per label, where the backend already holds the width it is
4810    /// about to draw with.
4811    pub h: props::TextAlign,
4812    pub v: TextVAlign,
4813}
4814
4815impl TextAnchor {
4816    /// The top-leading corner of the line box, the default.
4817    pub const LEADING: TextAnchor = TextAnchor {
4818        h: props::TextAlign::Leading,
4819        v: TextVAlign::Top,
4820    };
4821    /// The center of the line box, both ways.
4822    pub const CENTERED: TextAnchor = TextAnchor {
4823        h: props::TextAlign::Center,
4824        v: TextVAlign::Middle,
4825    };
4826    /// The top-trailing corner of the line box.
4827    pub const TRAILING: TextAnchor = TextAnchor {
4828        h: props::TextAlign::Trailing,
4829        v: TextVAlign::Top,
4830    };
4831
4832    /// Where the text's top-leading corner goes, as an offset from `at`, given the line box this
4833    /// text measures to. The single definition of what an anchor means: every backend that draws
4834    /// in Rust calls this, and the C++/Java/JS shims repeat exactly this arithmetic.
4835    ///
4836    /// `height` is the line box (ascent + descent) and `ascent` the baseline's offset from its
4837    /// top, the two numbers [`TextMetrics`] carries.
4838    pub fn offset(self, width: f64, height: f64, ascent: f64) -> (f64, f64) {
4839        let dx = match self.h {
4840            props::TextAlign::Leading => 0.0,
4841            props::TextAlign::Center => -width / 2.0,
4842            props::TextAlign::Trailing => -width,
4843        };
4844        let dy = match self.v {
4845            TextVAlign::Top => 0.0,
4846            TextVAlign::Middle => -height / 2.0,
4847            TextVAlign::Baseline => -ascent,
4848            TextVAlign::Bottom => -height,
4849        };
4850        (dx, dy)
4851    }
4852
4853    /// The anchor as one number, for the numeric op stream the serializing backends share:
4854    /// `h * 4 + v`, so it still occupies the single slot the two-variant enum did.
4855    pub fn pack(self) -> f64 {
4856        (self.h as u8 * 4 + self.v as u8) as f64
4857    }
4858
4859    /// Inverse of [`TextAnchor::pack`]. An unrecognized code answers the default rather than
4860    /// failing: a stream is only ever written by a matching encoder, and a drawing with text in
4861    /// the wrong corner beats one that panics inside a native draw callback.
4862    pub fn unpack(code: f64) -> TextAnchor {
4863        let c = code.round().clamp(0.0, 11.0) as u8;
4864        let h = match c / 4 {
4865            1 => props::TextAlign::Center,
4866            2 => props::TextAlign::Trailing,
4867            _ => props::TextAlign::Leading,
4868        };
4869        let v = match c % 4 {
4870            1 => TextVAlign::Middle,
4871            2 => TextVAlign::Baseline,
4872            3 => TextVAlign::Bottom,
4873            _ => TextVAlign::Top,
4874        };
4875        TextAnchor { h, v }
4876    }
4877}
4878
4879#[derive(Clone, Debug, PartialEq)]
4880pub enum DrawOp {
4881    Fill(Shape, Paint),
4882    /// Stroke `shape`. The paint may be a gradient, and [`StrokeStyle`] carries width, dash, cap
4883    /// and join; `Draw::stroke` builds the plain width-only case.
4884    Stroke(Shape, Paint, StrokeStyle),
4885    /// One line of text. `size` is absolute canvas points (no accessibility scale: canvas
4886    /// text is a label inside a drawing, docs/canvas.md); `font` picks the family, weight and
4887    /// slant, and its default is the platform's own UI face.
4888    Text {
4889        text: String,
4890        at: Point,
4891        size: f64,
4892        color: Color,
4893        anchor: TextAnchor,
4894        font: CanvasFont,
4895    },
4896    /// Draw one shape at many positions, the batched form of [`DrawOp::Fill`]/[`DrawOp::Stroke`]
4897    /// (docs/canvas.md "Stamping").
4898    ///
4899    /// Boxed because the payload is wider than the largest other op, and a bigger `DrawOp` would
4900    /// cost every op in every drawing, the exact thing this variant exists to stop paying.
4901    Stamp(Box<Stamp>),
4902    /// Draw an image into `rect` (docs/images.md).
4903    ///
4904    /// The source is a [`BitmapId`] and never bytes: a canvas re-records on every tracked read,
4905    /// so carrying a buffer here would hand the backend a megabyte to compare, and re-decode, on
4906    /// every frame. The app decodes once with `day::decode_image` and draws the handle.
4907    ///
4908    /// `opacity` multiplies the image's own alpha. A backend that cannot draw a bitmap at all
4909    /// draws nothing rather than a placeholder rectangle, the same way an unknown op is skipped.
4910    ///
4911    /// `source` is the region of the bitmap to draw, in the bitmap's own PIXELS (not points:
4912    /// [`BitmapInfo::scale`] says how many pixels make a point), `None` meaning the whole
4913    /// image. It is what lets one decoded sprite sheet serve every icon on a map: each draw
4914    /// picks its cell and scales it into `rect`. A region reaching outside the bitmap is clamped
4915    /// to it, never an error: the part inside draws where the mapping into `rect` puts it, and
4916    /// an empty intersection draws nothing. A backend without a sub-rect draw clips to `rect`
4917    /// and draws the whole image scaled so the region lands there ([`clamp_image_source`] is
4918    /// the shared arithmetic).
4919    Image {
4920        image: BitmapId,
4921        rect: Rect,
4922        opacity: f64,
4923        source: Option<Rect>,
4924    },
4925    /// Intersect the clip with `shape`; everything drawn afterwards is confined to it.
4926    ///
4927    /// Scoped by [`DrawOp::Save`]/[`DrawOp::Restore`], which is the only way to widen a clip
4928    /// again; every native 2-D context works this way, so there is no "unclip".
4929    Clip(Shape),
4930    /// Push the current transform + clip (§11, shapes). Backends map to save/restore of the
4931    /// native 2-D context; `Concat` multiplies an affine onto the CTM (shape rotate/scale/offset).
4932    Save,
4933    Restore,
4934    Concat(day_geometry::Affine),
4935}
4936
4937// ---------------------------------------------------------------------------
4938// Built-in piece descriptors: full props (realize) + sparse patches (update).
4939// One binding = one attribute = one patch value: sparseness by construction (§8.1).
4940// ---------------------------------------------------------------------------
4941
4942/// A semantic (logical) text style. Each maps to the platform's native text style where the
4943/// toolkit has one: `UIFont`/`NSFont.preferredFont(forTextStyle:)` on Apple (Dynamic Type), the
4944/// `*TextBlockStyle` resources on XAML. A Day app thus matches the OS's own typography and
4945/// inherits its accessibility text scaling with no extra work. Backends without semantic styles
4946/// (GTK/Qt/Android) approximate with sizes that still track the platform's text-scale /
4947/// font-scale accessibility setting.
4948///
4949/// The set mirrors SwiftUI `Font.TextStyle` (largest → smallest).
4950#[derive(Clone, Copy, Debug, PartialEq, Default)]
4951pub enum Font {
4952    LargeTitle,
4953    Title,
4954    Title2,
4955    Title3,
4956    Headline,
4957    Subheadline,
4958    #[default]
4959    Body,
4960    Callout,
4961    Footnote,
4962    Caption,
4963    Caption2,
4964    /// A custom point size. Backends scale it by the platform's accessibility text-scale (iOS via
4965    /// `UIFontMetrics`, Android via `sp`, GTK via text-scaling-factor) so it stays legible.
4966    System(f64),
4967    /// A bundled custom font by **family name**, at a point size (`Font::Custom("Pacifico",
4968    /// 24.0)`). The family must ship in the project's `fonts/` directory; `day build` stages the
4969    /// file into each platform's native font store and the backend registers it at startup
4970    /// (§18.4). The name is the family name baked into the font file (what Font Book /
4971    /// fontconfig report), not the file name. The size scales with the platform accessibility
4972    /// text-scale exactly like [`Font::System`]; weight/italic apply only where the family ships
4973    /// (or the platform synthesizes) such a face. An unknown family falls back to the system font
4974    /// of the same size, with a warning in the log.
4975    Custom(&'static str, f64),
4976}
4977
4978impl Font {
4979    /// A bundled custom font by **typed family**, at a point size, the checked form of
4980    /// [`Font::Custom`]. Pass a generated `res::fonts::…` constant
4981    /// (`Font::custom(res::fonts::pacifico, 24.0)`), which exists only if the family ships in the
4982    /// project's `fonts/` directory, so the font is guaranteed bundled. For a family name known
4983    /// another way, the untyped [`Font::Custom`] variant is the escape hatch.
4984    pub const fn custom(family: FontFamily, size: f64) -> Font {
4985        Font::Custom(family.as_str(), size)
4986    }
4987}
4988
4989/// Font weight, matching `UIFont.Weight` / SwiftUI `Font.Weight` (lightest → heaviest).
4990/// Ordered by heaviness, so backends can e.g. map `>= Semibold` to a synthesized bold face.
4991#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
4992pub enum FontWeight {
4993    UltraLight,
4994    Thin,
4995    Light,
4996    Regular,
4997    Medium,
4998    Semibold,
4999    Bold,
5000    Heavy,
5001    Black,
5002}
5003
5004impl FontWeight {
5005    /// Every rung, lightest first.
5006    pub const ALL: [FontWeight; 9] = [
5007        FontWeight::UltraLight,
5008        FontWeight::Thin,
5009        FontWeight::Light,
5010        FontWeight::Regular,
5011        FontWeight::Medium,
5012        FontWeight::Semibold,
5013        FontWeight::Bold,
5014        FontWeight::Heavy,
5015        FontWeight::Black,
5016    ];
5017
5018    /// The CSS / OpenType numeric weight (100 … 900), the one number every platform font API
5019    /// also speaks (`Typeface.create(base, weight, italic)`, `QFont::Weight`,
5020    /// `DWRITE_FONT_WEIGHT`, `OH_Drawing_FontWeight`), and what the canvas wire carries.
5021    pub const fn css(self) -> u16 {
5022        match self {
5023            FontWeight::UltraLight => 100,
5024            FontWeight::Thin => 200,
5025            FontWeight::Light => 300,
5026            FontWeight::Regular => 400,
5027            FontWeight::Medium => 500,
5028            FontWeight::Semibold => 600,
5029            FontWeight::Bold => 700,
5030            FontWeight::Heavy => 800,
5031            FontWeight::Black => 900,
5032        }
5033    }
5034
5035    /// The nearest rung to a CSS weight (ties round heavier, like CSS font matching); anything
5036    /// outside 100 … 900 clamps.
5037    pub fn from_css(n: u16) -> FontWeight {
5038        let n = n.clamp(100, 900);
5039        let idx = (usize::from(n) + 50) / 100; // 100 → 1 … 900 → 9
5040        FontWeight::ALL[idx.clamp(1, 9) - 1]
5041    }
5042
5043    /// The English face name for a rung ("Semibold"), for platforms whose enumeration names
5044    /// no face (see [`FontFace::synthesized_name`]).
5045    pub const fn name(self) -> &'static str {
5046        match self {
5047            FontWeight::UltraLight => "Ultra Light",
5048            FontWeight::Thin => "Thin",
5049            FontWeight::Light => "Light",
5050            FontWeight::Regular => "Regular",
5051            FontWeight::Medium => "Medium",
5052            FontWeight::Semibold => "Semibold",
5053            FontWeight::Bold => "Bold",
5054            FontWeight::Heavy => "Heavy",
5055            FontWeight::Black => "Black",
5056        }
5057    }
5058}
5059
5060/// One face a font family ships (docs/fonts.md): its display name ("Bold Italic"), weight and
5061/// slant. What [`FontFamilyInfo::faces`] lists and what a font menu's style picker offers.
5062#[derive(Clone, Debug, PartialEq, Eq)]
5063pub struct FontFace {
5064    pub name: String,
5065    pub weight: FontWeight,
5066    pub italic: bool,
5067}
5068
5069impl FontFace {
5070    /// A display name from weight + slant ("Semibold Italic") for platforms whose enumeration
5071    /// API names no face (Android's `fonts.xml`, the CSS generic families).
5072    pub fn synthesized_name(weight: FontWeight, italic: bool) -> String {
5073        if italic {
5074            format!("{} Italic", weight.name())
5075        } else {
5076            weight.name().to_string()
5077        }
5078    }
5079}
5080
5081/// A platform (or bundled) font family and the faces it can draw canvas text in
5082/// ([`Toolkit::font_families`], docs/fonts.md).
5083#[derive(Clone, Debug, PartialEq, Eq)]
5084pub struct FontFamilyInfo {
5085    pub family: String,
5086    pub faces: Vec<FontFace>,
5087}
5088
5089impl FontFamilyInfo {
5090    /// Whether any face is [`FontWeight::Bold`] or heavier.
5091    pub fn has_bold(&self) -> bool {
5092        self.faces.iter().any(|f| f.weight >= FontWeight::Bold)
5093    }
5094    /// Whether any face is italic.
5095    pub fn has_italic(&self) -> bool {
5096        self.faces.iter().any(|f| f.italic)
5097    }
5098    /// The nearest face: an exact slant match preferred, then the smallest weight distance
5099    /// (ties go heavier, like CSS font matching). `None` only when the family lists no faces.
5100    pub fn face_for(&self, weight: FontWeight, italic: bool) -> Option<&FontFace> {
5101        let want = i32::from(weight.css());
5102        self.faces.iter().min_by_key(|f| {
5103            let slant = i32::from(f.italic != italic);
5104            let dist = (i32::from(f.weight.css()) - want).abs();
5105            // Heavier wins a tie: subtracting the bool sorts the heavier face first.
5106            (slant, dist, i32::from(i32::from(f.weight.css()) < want))
5107        })
5108    }
5109}
5110
5111/// Single-line text measurement in canvas points ([`Toolkit::measure_text`], docs/fonts.md).
5112///
5113/// Two boxes, and the difference between them matters. `width`/`height` is the **line box**: the
5114/// typographic slot the text occupies, the same for every string in a face at a size, and what
5115/// [`TextAnchor`] positions. [`ink`](TextMetrics::ink) is the **ink box**: where the glyphs
5116/// put marks. A line of digits leaves the descender space of its line box empty, so the
5117/// two disagree, and which one is wanted depends on the question: laying text out in a column
5118/// wants the line box, and centering it on a rule or keeping it clear of a mark wants the ink.
5119#[derive(Clone, Copy, Debug, PartialEq)]
5120pub struct TextMetrics {
5121    /// The advance width of the whole string.
5122    pub width: f64,
5123    /// The line box: ascent + descent at this size (plus the line gap where the engine reports
5124    /// one), which is the box [`TextAnchor`] positions.
5125    pub height: f64,
5126    /// The baseline's offset from the top of the line box.
5127    pub ascent: f64,
5128    /// The face's cap height at this size: baseline to the top of a capital.
5129    ///
5130    /// A property of the font, not of this string, reported here because it is what optical
5131    /// centering needs and asking for it separately would be a second measurement. Text made of
5132    /// capitals and digits looks centered on a rule when its cap box straddles it, not its line
5133    /// box: the line box reserves descender room that digits never use, so centering by it sits
5134    /// every label a little low. The cap middle is `ascent - cap_height / 2.0` below the line
5135    /// box's top.
5136    pub cap_height: f64,
5137    /// The ink box, the tight bounds of what is drawn, with its origin relative to the line
5138    /// box's top-leading corner, so `ink.origin` is where the marks start inside the slot.
5139    ///
5140    /// Empty (zero-size) for text that draws nothing, a space included. Where a toolkit cannot
5141    /// report ink it answers the whole line box, which is a superset: an overlap test against it
5142    /// can only be too cautious, never wrong.
5143    pub ink: Rect,
5144}
5145
5146impl TextMetrics {
5147    /// The portable guess `day::measure_text` falls back to when a toolkit cannot measure:
5148    /// 0.6 × size per character, 1.2 × size tall, the baseline at 0.9 × size, caps at 0.7 × size.
5149    /// Its ink is the whole line box, the safe direction to be wrong in (see
5150    /// [`ink`](TextMetrics::ink)).
5151    pub fn approximate(text: &str, size: f64) -> TextMetrics {
5152        let (width, height) = (0.6 * size * text.chars().count() as f64, 1.2 * size);
5153        TextMetrics {
5154            width,
5155            height,
5156            ascent: 0.9 * size,
5157            cap_height: 0.7 * size,
5158            ink: Rect::new(0.0, 0.0, width, height),
5159        }
5160    }
5161
5162    /// Read the eight-slot form the serializing backends (qt, xaml, arkui, web) fill across their
5163    /// C ABI: advance, line height, ascent, cap height, then the ink box relative to the line
5164    /// box's top-leading corner. One definition so four shims cannot drift from each other.
5165    pub fn from_slots(out: &[f64; 8]) -> TextMetrics {
5166        TextMetrics {
5167            width: out[0],
5168            height: out[1],
5169            ascent: out[2],
5170            cap_height: out[3],
5171            ink: Rect::new(out[4], out[5], out[6], out[7]),
5172        }
5173    }
5174
5175    /// The line box's top-leading corner, given a baseline-relative measurement, the shape every
5176    /// backend's metrics come in. `ink_*` are relative to the drawing origin on the baseline
5177    /// (`ink_top` negative above it), the convention Skia, Core Text and Qt all report in.
5178    pub fn from_baseline(
5179        width: f64,
5180        ascent: f64,
5181        descent: f64,
5182        cap_height: f64,
5183        ink: Rect,
5184    ) -> TextMetrics {
5185        TextMetrics {
5186            width,
5187            height: ascent + descent,
5188            ascent,
5189            cap_height,
5190            // Baseline-relative to line-box-relative is one shift by the ascent.
5191            ink: Rect::new(
5192                ink.origin.x,
5193                ink.origin.y + ascent,
5194                ink.size.width,
5195                ink.size.height,
5196            ),
5197        }
5198    }
5199}
5200
5201/// What canvas text is drawn with beyond its size (docs/canvas.md "Text"): a family, a weight and
5202/// a slant. The default is the platform's own UI face, regular, upright, which is what every
5203/// backend drew before the field existed, so a default font encodes to nothing on the wire.
5204#[derive(Clone, Debug, PartialEq, Eq, Default)]
5205pub struct CanvasFont {
5206    /// A platform or bundled family name (as [`Toolkit::font_families`] lists it); `None` =
5207    /// the platform's default UI face.
5208    pub family: Option<String>,
5209    /// `None` = Regular.
5210    pub weight: Option<FontWeight>,
5211    pub italic: bool,
5212}
5213
5214impl CanvasFont {
5215    /// The family name to send over the wire, empty for the default.
5216    pub fn family_str(&self) -> &str {
5217        self.family.as_deref().unwrap_or("")
5218    }
5219    /// The CSS weight to send over the wire, 0 for the default.
5220    pub fn css_weight(&self) -> u16 {
5221        self.weight.map(FontWeight::css).unwrap_or(0)
5222    }
5223}
5224
5225/// Field separator inside one family of the shim-side font list ([`parse_font_list`]).
5226pub const FONT_LIST_FIELD: char = '\u{1f}';
5227/// Family separator of the shim-side font list ([`parse_font_list`]).
5228pub const FONT_LIST_FAMILY: char = '\u{1e}';
5229
5230/// Decode the text a non-Rust font enumerator hands back (the Qt, XAML and ArkUI shims, the
5231/// Android bridge, the web shim all produce this one format): families separated by U+001E;
5232/// inside a family, U+001F-separated fields: the family name, then one (name, CSS weight,
5233/// italic `0`/`1`) triple per face. Tolerant: a malformed face or family is skipped, an empty
5234/// face name is synthesized from its weight and slant, and a family with no faces is kept
5235/// with none (the caller decides what a face-less family means).
5236pub fn parse_font_list(s: &str) -> Vec<FontFamilyInfo> {
5237    let mut out = Vec::new();
5238    for fam in s.split(FONT_LIST_FAMILY) {
5239        let mut fields = fam.split(FONT_LIST_FIELD);
5240        let Some(family) = fields.next().map(str::trim).filter(|f| !f.is_empty()) else {
5241            continue;
5242        };
5243        let rest: Vec<&str> = fields.collect();
5244        let mut faces = Vec::new();
5245        for face in rest.chunks(3) {
5246            let [name, weight, italic] = face else {
5247                continue;
5248            };
5249            let Ok(weight) = weight.trim().parse::<u16>() else {
5250                continue;
5251            };
5252            let weight = FontWeight::from_css(weight);
5253            let italic = matches!(italic.trim(), "1" | "true");
5254            let name = name.trim();
5255            let name = if name.is_empty() {
5256                FontFace::synthesized_name(weight, italic)
5257            } else {
5258                name.to_string()
5259            };
5260            if !faces
5261                .iter()
5262                .any(|f: &FontFace| f.weight == weight && f.italic == italic)
5263            {
5264                faces.push(FontFace {
5265                    name,
5266                    weight,
5267                    italic,
5268                });
5269            }
5270        }
5271        out.push(FontFamilyInfo {
5272            family: family.to_string(),
5273            faces,
5274        });
5275    }
5276    out
5277}
5278
5279/// The full font descriptor a label carries: a semantic (or custom) [`Font`] style plus an optional
5280/// weight override, an italic flag, and the tabular-figures request. Backends resolve this to one
5281/// native font.
5282#[derive(Clone, Copy, Debug, PartialEq)]
5283pub struct FontSpec {
5284    pub style: Font,
5285    pub weight: Option<FontWeight>,
5286    pub italic: bool,
5287    /// Ask for tabular (monospaced) figures: every digit takes the same advance, so a number that
5288    /// changes stops changing width.
5289    ///
5290    /// In a proportional system font `1` is narrower than `8`, so a readout beside a slider
5291    /// wobbles as the value changes even when the digit count is fixed. Every platform ships this
5292    /// as a font feature, so Day asks for the platform's own rather than substituting a monospaced
5293    /// family: the text keeps the system face, and only the digits change metrics.
5294    ///
5295    /// Reserving space (`Decorate::reserving`) and tabular figures solve the two halves of the
5296    /// same problem (reservation stops the box resizing, tabular stops the glyphs shifting inside
5297    /// it), and a numeric readout usually wants both.
5298    ///
5299    /// This rides the existing label realize/patch path rather than adding a Toolkit method, so it
5300    /// is not a backend duty and has no duty-matrix row. Every in-tree backend honors it: AppKit
5301    /// and UIKit re-pick the system face (`monospacedDigitSystemFont`), GTK and Qt and ArkUI set
5302    /// the `tnum` OpenType feature, Android `setFontFeatureSettings`, XAML the `Typography`
5303    /// NumeralAlignment property, and web-dom `font-variant-numeric`. A font with no `tnum` table,
5304    /// or an SDK predating the attribute, renders the stock proportional figures.
5305    pub tabular: bool,
5306    /// Ask for the platform's monospaced face at this style's size, what `` `code` `` in a
5307    /// markdown run needs (docs/text-runs.md).
5308    ///
5309    /// A flag rather than a `Font::Monospace(pt)` variant so the run keeps its semantic style:
5310    /// code inside a `Footnote` paragraph must stay footnote-sized and keep tracking the
5311    /// reader's text-size setting, which a fixed point size would throw away.
5312    ///
5313    /// Like [`Self::tabular`], this rides the label realize/patch path and is not a backend duty:
5314    /// every toolkit has a system monospace face (`monospacedSystemFont`, Pango's `monospace`
5315    /// family, `QFontDatabase::FixedFont`, `Typeface.MONOSPACE`, CSS `monospace`).
5316    pub monospace: bool,
5317    /// Multiply the resolved size. `1.0` is the style's own size, `1.6` a heading against a body
5318    /// paragraph, `0.8` a caption inside one.
5319    ///
5320    /// Relative rather than an absolute point size, so that an editor's font-size control can
5321    /// move this while text a person reads for an hour still tracks the platform's
5322    /// accessibility text-scale. `Font::System(pt)` remains the absolute escape hatch, and it
5323    /// is where an imported document's `\fs28` or `font-size: 14px` lands (docs/texteditor.md):
5324    /// faithful to the file, and no longer responsive to the reader, which is the trade that
5325    /// form makes.
5326    ///
5327    /// Three toolkits take it directly (`GtkTextTag::scale`, Android's `RelativeSizeSpan`, CSS
5328    /// `em`); the rest multiply it into the size they already compute.
5329    pub scale: f64,
5330}
5331
5332impl Default for FontSpec {
5333    fn default() -> Self {
5334        FontSpec {
5335            style: Font::Body,
5336            weight: None,
5337            italic: false,
5338            tabular: false,
5339            monospace: false,
5340            scale: 1.0,
5341        }
5342    }
5343}
5344
5345impl From<Font> for FontSpec {
5346    fn from(style: Font) -> Self {
5347        FontSpec {
5348            style,
5349            ..FontSpec::default()
5350        }
5351    }
5352}
5353
5354impl FontSpec {
5355    /// The plain descriptor for a style: no weight override, no italic, scale 1.0.
5356    pub fn new(style: Font) -> Self {
5357        FontSpec::from(style)
5358    }
5359    /// This descriptor at a different relative size (see [`FontSpec::scale`]).
5360    pub fn scaled(mut self, scale: f64) -> Self {
5361        self.scale = scale;
5362        self
5363    }
5364    /// The point size this descriptor resolves to, given the size the platform assigns its
5365    /// semantic style. The one place `scale` is applied, so every backend's font resolver
5366    /// multiplies the same way.
5367    pub fn resolved_points(&self, style_points: f64) -> f64 {
5368        let base = match self.style {
5369            Font::System(pt) | Font::Custom(_, pt) => pt,
5370            _ => style_points,
5371        };
5372        (base * self.scale).max(1.0)
5373    }
5374}
5375
5376/// One styled span of a label's text (docs/text-runs.md).
5377///
5378/// `range` is a byte range into the label's `text`. Bytes, not chars: every backend that takes a
5379/// structured attributed string wants UTF-16 or byte offsets, `str` slicing is byte-based, and a
5380/// char count would have to be converted at every boundary. Ranges must be non-overlapping and
5381/// ascending; a gap between them is unstyled text, drawn with the label's own font.
5382///
5383/// A run says only what differs. `font` is the whole descriptor rather than a delta because a
5384/// bold run inside a Body paragraph is `FontSpec { style: Body, weight: Some(Bold), .. }`. The
5385/// style has to travel with the weight or the run loses its semantic size.
5386#[derive(Clone, Debug, PartialEq)]
5387pub struct TextRun {
5388    pub range: std::ops::Range<usize>,
5389    pub font: FontSpec,
5390    pub color: Option<Color>,
5391    /// A highlight painted behind the glyphs. Every native text editor carries this attribute
5392    /// (docs/texteditor.md), and search hits and review comments are the two things an app is
5393    /// asked for the moment it has styled text at all.
5394    pub background: Option<Color>,
5395    /// A line under the text.
5396    pub underline: Underline,
5397    /// A line through the text. Separate from `FontSpec` because it is a decoration, not a face:
5398    /// no platform expresses it by picking a different font.
5399    pub strikethrough: bool,
5400    /// Makes this run a link to the given target. Rendering it is [`Cap::TextRuns`]; making it
5401    /// activatable is [`Cap::TextLinks`], which is a smaller set (see the docs).
5402    pub link: Option<String>,
5403}
5404
5405impl Default for TextRun {
5406    fn default() -> Self {
5407        TextRun {
5408            range: 0..0,
5409            font: FontSpec::default(),
5410            color: None,
5411            background: None,
5412            underline: Underline::None,
5413            strikethrough: false,
5414            link: None,
5415        }
5416    }
5417}
5418
5419impl TextRun {
5420    /// A run that only changes the font, the common case for emphasis.
5421    pub fn font(range: std::ops::Range<usize>, font: FontSpec) -> Self {
5422        TextRun {
5423            range,
5424            font,
5425            ..TextRun::default()
5426        }
5427    }
5428
5429    /// This run's attributes without its range: what a selection's style is compared against
5430    /// and what an editor's toolbar toggles (docs/texteditor.md).
5431    pub fn style(&self) -> RunStyle {
5432        RunStyle {
5433            font: self.font,
5434            color: self.color,
5435            background: self.background,
5436            underline: self.underline,
5437            strikethrough: self.strikethrough,
5438            link: self.link.clone(),
5439        }
5440    }
5441
5442    /// A run of `style` over `range`.
5443    pub fn styled(range: std::ops::Range<usize>, style: RunStyle) -> Self {
5444        TextRun {
5445            range,
5446            font: style.font,
5447            color: style.color,
5448            background: style.background,
5449            underline: style.underline,
5450            strikethrough: style.strikethrough,
5451            link: style.link,
5452        }
5453    }
5454}
5455
5456/// Serialize a label's text + runs as markup, for the two backends whose text widgets take a
5457/// string in their own dialect rather than a structured attributed string: GTK (Pango markup)
5458/// and Qt (its HTML subset). Shared so the escaping is written and tested once: a translated
5459/// string containing `&` or `<` corrupts the whole label otherwise, and it will be a translated
5460/// string that finds the bug.
5461///
5462/// `dialect` decides the spelling: Pango wants `<span foreground="#rrggbb"
5463/// font_family="monospace">`, Qt wants `<span style="color:#rrggbb">` with `<code>`. Both accept
5464/// `<b>`, `<i>`, `<u>`, `<s>` and `<a href>`, which is why one function can serve them.
5465///
5466/// `base_points` is the size the label itself resolved to. Only a relative-size run
5467/// ([`FontSpec::scale`]) needs it, and only in the Qt dialect: Pango markup takes a percentage
5468/// directly, while Qt's CSS subset understands `pt` and `px` and ignores `%`.
5469pub fn runs_to_markup(
5470    text: &str,
5471    runs: &[TextRun],
5472    dialect: MarkupDialect,
5473    base_points: f64,
5474) -> String {
5475    let mut out = String::with_capacity(text.len() + runs.len() * 24);
5476    let mut at = 0usize;
5477    for r in runs {
5478        // Skip a run whose range does not address this string, without advancing `at`: dropping
5479        // the run loses styling, but advancing past it would drop the rest of the sentence.
5480        // `runs_are_valid` rejects these upstream; this keeps the failure cheap if one slips by.
5481        let Some(styled) = text.get(r.range.clone()) else {
5482            continue;
5483        };
5484        if r.range.start > at
5485            && let Some(plain) = text.get(at..r.range.start)
5486        {
5487            escape_markup_in(plain, &mut out, dialect);
5488        }
5489        open_run(r, dialect, base_points, &mut out);
5490        escape_markup_in(styled, &mut out, dialect);
5491        close_run(r, dialect, &mut out);
5492        at = r.range.end;
5493    }
5494    if let Some(tail) = text.get(at..) {
5495        escape_markup_in(tail, &mut out, dialect);
5496    }
5497    out
5498}
5499
5500impl Symbol {
5501    /// A 24×24 outline path for this symbol, Day's own drawing of it.
5502    ///
5503    /// The platform's icon comes first on every backend that has one (SF Symbols, the freedesktop
5504    /// icon theme, Fluent's glyph font). This is the fallback for when that lookup finds nothing,
5505    /// which is not an edge case: `view-filter-symbolic` exists on a GNOME desktop and nowhere
5506    /// else, so a GTK or Qt app run off that desktop drew a toolbar item with no icon at all.
5507    /// One table here means the same fallback shape everywhere instead of a gap per platform.
5508    ///
5509    /// `None` for a variant with no drawing yet: `Symbol` is `#[non_exhaustive]`, so a new one
5510    /// degrades to a label rather than failing to compile.
5511    pub fn outline_path(self) -> Option<&'static str> {
5512        use Symbol as S;
5513        // The wildcard is unreachable today (every variant is drawn below) and it is here for
5514        // the next one, which should degrade to a label rather than fail to compile.
5515        #[allow(unreachable_patterns)]
5516        Some(match self {
5517            S::Add => "M11 5h2v6h6v2h-6v6h-2v-6H5v-2h6z",
5518            S::Remove => "M5 11h14v2H5z",
5519            S::Delete => "M9 3h6l1 2h4v2H4V5h4zM6 8h12l-1 13H7z",
5520            S::Edit => {
5521                "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"
5522            }
5523            S::New => "M13 2H6v20h12V7h-5zm2 .5L19.5 7H15z",
5524            S::Open => "M2 5h7l2 2h11v12H2z",
5525            S::Save => "M3 3h13l5 5v13H3zm5 0h7v6H8zm-1 11h10v7H7z",
5526            S::Print => "M7 3h10v4H7zM4 8h16v8h-3v6H7v-6H4z",
5527            S::Refresh => "M12 4V1L8 5l4 4V6a6 6 0 1 1-6 6H4a8 8 0 1 0 8-8z",
5528            S::Search => {
5529                "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"
5530            }
5531            S::Share => "M12 3l5 5h-3v7h-4V8H7zM5 17h14v4H5z",
5532            // An eight-tooth gear, round about the center (radius 10 at the teeth, 7.6 at the
5533            // roots) with a 3.2 hole: square in its box, so it sits in a row's 24-point icon
5534            // slot at the same size as its neighbors.
5535            S::Settings => {
5536                "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"
5537            }
5538            S::Info => "M12 2a10 10 0 1 0 0 20 10 10 0 0 0 0-20m-1 5h2v2h-2zm0 4h2v6h-2z",
5539            S::Star => {
5540                "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"
5541            }
5542            S::Bookmark => "M6 2h12v20l-6-4-6 4z",
5543            S::Back => "M15.4 5.4L14 4l-8 8 8 8 1.4-1.4L8.8 12z",
5544            S::Forward => "M8.6 5.4L10 4l8 8-8 8-1.4-1.4L15.2 12z",
5545            S::Up => "M5.4 15.4L4 14l8-8 8 8-1.4 1.4L12 8.8z",
5546            S::Down => "M5.4 8.6L4 10l8 8 8-8-1.4-1.4L12 15.2z",
5547            S::Home => "M12 3l9 8h-3v10h-5v-6h-2v6H6V11H3z",
5548            S::Sidebar => "M3 4h18v16H3zm2 2v12h4V6zm6 0v12h8V6z",
5549            S::Filter => "M3 5h18l-7 8v6l-4 2v-8z",
5550            S::Sort => "M8 4v12H4l4 4 4-4H10V4zM14 6h7v2h-7zm0 4h5v2h-5zm0 4h3v2h-3z",
5551            S::More => {
5552                "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"
5553            }
5554            S::Play => "M8 5l11 7-11 7z",
5555            S::Pause => "M7 5h3v14H7zm7 0h3v14h-3z",
5556            S::Stop => "M6 6h12v12H6z",
5557            S::Camera => {
5558                "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"
5559            }
5560            S::Code => {
5561                "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"
5562            }
5563            S::Light => {
5564                "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"
5565            }
5566            S::Dark => "M12 3a9 9 0 1 0 9 9 7 7 0 0 1-9-9",
5567            // "Automatic": the half-filled circle every platform uses: the left half solid, the
5568            // right half an outline, which `evenodd` below turns into the ring it should be.
5569            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",
5570            S::ZoomIn => {
5571                "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"
5572            }
5573            S::ZoomOut => {
5574                "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"
5575            }
5576            // The ZoomIn lens with a numeral 1 in it, "back to actual size".
5577            S::ZoomReset => {
5578                "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"
5579            }
5580            S::Undo => "M12 5V2L7 7l5 5V9a5 5 0 1 1 0 10H8v2h4a7 7 0 0 0 0-14z",
5581            S::Redo => "M12 5V2l5 5-5 5V9a5 5 0 1 0 0 10h4v2h-4a7 7 0 0 1 0-14z",
5582            S::Copy => "M8 2h10v14H8zM4 6h2v14h12v2H4z",
5583            S::Cut => {
5584                "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"
5585            }
5586            S::Paste => "M9 2h6v2h3v18H6V4h3zm0 2v2h6V4z",
5587            S::Mail => "M2 5h20v14H2zm2 3.2V17h16V8.2l-8 5z",
5588            S::Folder => "M2 5h7l2 2h11v12H2z",
5589            S::Document => "M14 2H6v20h12V6zm.5.8L17.2 6H14.5z",
5590            S::Check => "M9 16.2L4.8 12l-1.4 1.4L9 19 21 7l-1.4-1.4z",
5591            S::Close => {
5592                "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"
5593            }
5594            S::Warning => "M12 2l10 19H2zm-1 7h2v6h-2zm0 8h2v2h-2z",
5595            // Shape outlines, stroked as a 2-unit band (an even-odd ring), so they read as
5596            // outlines at any size rather than filled blocks.
5597            S::Rectangle => "M3 5h18v14H3zm2 2v10h14V7z",
5598            S::Oval => {
5599                "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"
5600            }
5601            // A circular ring (even-odd: outer disc minus inner) and its filled twin.
5602            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",
5603            S::CircleFilled => "M12 4a8 8 0 1 0 0 16 8 8 0 0 0 0-16z",
5604            S::Line => "M4.7 17.9l13.2-13.2 1.4 1.4L6.1 19.3z",
5605            // Group: a solid square stacked on another (the visible L of the back one);
5606            // Ungroup: the same two squares pulled apart.
5607            S::Group => "M8 4h12v12h-4V8H8zM4 8h12v12H4z",
5608            S::Ungroup => "M3 3h8v8H3zM13 13h8v8h-8z",
5609            // A crosshair: a dot in a ring with four ticks, the even-odd fill leaving the gap
5610            // between dot and ring empty.
5611            S::Location => {
5612                "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"
5613            }
5614            // `Symbol` is `#[non_exhaustive]`: a variant added upstream draws nothing here rather
5615            // than failing to compile, and its item keeps its label.
5616            _ => return None,
5617        })
5618    }
5619
5620    /// [`Self::outline_path`] wrapped as a standalone SVG document.
5621    pub fn outline_svg(self) -> Option<String> {
5622        self.outline_path().map(|d| {
5623            format!(
5624                "<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 24 24\">\
5625                 <path fill-rule=\"evenodd\" d=\"{d}\"/></svg>"
5626            )
5627        })
5628    }
5629}
5630
5631/// Which markup dialect [`runs_to_markup`] should emit.
5632#[derive(Clone, Copy, Debug, PartialEq, Eq)]
5633pub enum MarkupDialect {
5634    /// Pango markup (GTK).
5635    Pango,
5636    /// Qt's rich-text HTML subset.
5637    QtHtml,
5638}
5639
5640/// XML-escape a run of plain text into `out`. `&` first, or the escapes escape each other.
5641///
5642/// Newlines are dialect-specific. Pango lays a literal `\n` out as a line break, but Qt's rich
5643/// text is HTML, where any run of whitespace collapses to one space, which silently ran a
5644/// two-paragraph body together into a single block. `<br>` is what says "break here" in HTML, so
5645/// the same string wraps the same way on both.
5646fn escape_markup_in(s: &str, out: &mut String, dialect: MarkupDialect) {
5647    for c in s.chars() {
5648        match c {
5649            '&' => out.push_str("&amp;"),
5650            '<' => out.push_str("&lt;"),
5651            '>' => out.push_str("&gt;"),
5652            '"' => out.push_str("&quot;"),
5653            '\'' => out.push_str("&#39;"),
5654            '\n' if dialect == MarkupDialect::QtHtml => out.push_str("<br>"),
5655            _ => out.push(c),
5656        }
5657    }
5658}
5659
5660/// [`escape_markup_in`] for the URL slot, where a newline cannot appear.
5661fn escape_markup(s: &str, out: &mut String) {
5662    escape_markup_in(s, out, MarkupDialect::Pango);
5663}
5664
5665fn hex(c: Color) -> String {
5666    format!(
5667        "#{:02x}{:02x}{:02x}",
5668        (c.r.clamp(0.0, 1.0) * 255.0) as u8,
5669        (c.g.clamp(0.0, 1.0) * 255.0) as u8,
5670        (c.b.clamp(0.0, 1.0) * 255.0) as u8
5671    )
5672}
5673
5674/// Does this run need a `<span>` in `dialect`, or do the plain tags cover it?
5675fn needs_span(r: &TextRun, dialect: MarkupDialect) -> bool {
5676    let extras = r.color.is_some() || r.background.is_some() || r.font.scale != 1.0;
5677    match dialect {
5678        // Pango expresses the monospace family as a span attribute; Qt cannot (see below).
5679        MarkupDialect::Pango => extras || r.font.monospace,
5680        MarkupDialect::QtHtml => extras,
5681    }
5682}
5683
5684fn open_run(r: &TextRun, dialect: MarkupDialect, base_points: f64, out: &mut String) {
5685    if let Some(url) = r.link.as_deref() {
5686        out.push_str("<a href=\"");
5687        escape_markup(url, out);
5688        out.push_str("\">");
5689    }
5690    // The span carries the attributes that have no tag: colors, relative size, and (on Pango)
5691    // the monospace family. Bold/italic/strike/underline are tags in both dialects, which keeps
5692    // the attribute string short and the escaping trivial.
5693    let color = r.color.map(hex);
5694    let background = r.background.map(hex);
5695    let mono = r.font.monospace;
5696    if needs_span(r, dialect) {
5697        match dialect {
5698            MarkupDialect::Pango => {
5699                out.push_str("<span");
5700                if let Some(c) = &color {
5701                    out.push_str(&format!(" foreground=\"{c}\""));
5702                }
5703                if let Some(c) = &background {
5704                    out.push_str(&format!(" background=\"{c}\""));
5705                }
5706                if mono {
5707                    out.push_str(" font_family=\"monospace\"");
5708                }
5709                if r.font.scale != 1.0 {
5710                    // Absolute, in Pango units (1/1024 pt), not the `font_scale`/`size="N%"`
5711                    // pair: those are Pango 1.50 attributes, and a Pango that does not know an
5712                    // attribute fails the whole markup parse, which renders the label empty
5713                    // rather than merely unscaled. A point size still tracks the desktop's text
5714                    // scaling, since Pango resolves points through the Xft DPI.
5715                    let pts = r.font.resolved_points(base_points);
5716                    out.push_str(&format!(" size=\"{}\"", (pts * 1024.0).round() as i64));
5717                }
5718                out.push('>');
5719            }
5720            MarkupDialect::QtHtml => {
5721                // Color only. Qt's rich text does not resolve the generic `monospace` family
5722                // from a style attribute (it rendered proportional), so the fixed face comes
5723                // from the `<code>` tag below, which Qt maps to its own fixed font.
5724                out.push_str("<span style=\"");
5725                if let Some(c) = &color {
5726                    out.push_str(&format!("color:{c};"));
5727                }
5728                if let Some(c) = &background {
5729                    out.push_str(&format!("background-color:{c};"));
5730                }
5731                if r.font.scale != 1.0 {
5732                    // Points, not a percentage: Qt's rich-text CSS subset understands `pt` and
5733                    // `px` and silently ignores `%`, which is why a scaled run rendered at the
5734                    // base size here while every other backend scaled it.
5735                    let pt = r.font.resolved_points(base_points);
5736                    out.push_str(&format!("font-size:{pt}pt;"));
5737                }
5738                out.push_str("\">");
5739            }
5740        }
5741    }
5742    if dialect == MarkupDialect::QtHtml && mono {
5743        out.push_str("<code>");
5744    }
5745    if r.font.weight.is_some_and(|w| w >= FontWeight::Semibold) {
5746        out.push_str("<b>");
5747    }
5748    if r.font.italic {
5749        out.push_str("<i>");
5750    }
5751    if r.underline.is_on() {
5752        out.push_str("<u>");
5753    }
5754    if r.strikethrough {
5755        out.push_str("<s>");
5756    }
5757}
5758
5759fn close_run(r: &TextRun, dialect: MarkupDialect, out: &mut String) {
5760    if r.strikethrough {
5761        out.push_str("</s>");
5762    }
5763    if r.underline.is_on() {
5764        out.push_str("</u>");
5765    }
5766    if r.font.italic {
5767        out.push_str("</i>");
5768    }
5769    if r.font.weight.is_some_and(|w| w >= FontWeight::Semibold) {
5770        out.push_str("</b>");
5771    }
5772    if dialect == MarkupDialect::QtHtml && r.font.monospace {
5773        out.push_str("</code>");
5774    }
5775    if needs_span(r, dialect) {
5776        out.push_str("</span>");
5777    }
5778    if r.link.is_some() {
5779        out.push_str("</a>");
5780    }
5781}
5782
5783/// Are these runs well formed for `text`: ascending, non-overlapping, inside the string, and on
5784/// character boundaries?
5785///
5786/// Checked once in the pieces layer rather than in eight backends. A backend handed overlapping
5787/// ranges would produce a different wrong answer per platform, and a range splitting a multi-byte
5788/// character would panic on `str` slicing in some and render mojibake in others.
5789pub fn runs_are_valid(text: &str, runs: &[TextRun]) -> Result<(), String> {
5790    let mut prev_end = 0usize;
5791    for (i, r) in runs.iter().enumerate() {
5792        if r.range.start < prev_end {
5793            return Err(format!(
5794                "run {i} starts at {} but the previous run ends at {prev_end} — runs must be \
5795                 ascending and non-overlapping",
5796                r.range.start
5797            ));
5798        }
5799        if r.range.end > text.len() {
5800            return Err(format!(
5801                "run {i} ends at {} but the text is {} bytes",
5802                r.range.end,
5803                text.len()
5804            ));
5805        }
5806        if r.range.start > r.range.end {
5807            return Err(format!("run {i} has an inverted range {:?}", r.range));
5808        }
5809        if !text.is_char_boundary(r.range.start) || !text.is_char_boundary(r.range.end) {
5810            return Err(format!(
5811                "run {i} range {:?} splits a multi-byte character",
5812                r.range
5813            ));
5814        }
5815        prev_end = r.range.end;
5816    }
5817    Ok(())
5818}
5819
5820pub mod props {
5821    use super::*;
5822
5823    #[derive(Clone, Debug, Default, PartialEq)]
5824    pub struct ContainerProps {
5825        pub background: Option<Color>,
5826        pub corner_radius: f64,
5827        pub clips: bool,
5828        /// Semantic, theme-adaptive surface, mapped by each backend to a native material that
5829        /// follows the platform's light/dark appearance automatically (unlike the fixed-RGBA
5830        /// `background`, which it overrides when set).
5831        pub role: Option<super::SurfaceRole>,
5832    }
5833    /// Reactive surface update for a `background(..)` decorator whose color is a signal/closure:
5834    /// the backend re-applies the fill on the container's native backing view. Corner radius and
5835    /// clipping are fixed at realize (the `corner_radius(r)` decorator takes a plain `f64`).
5836    #[derive(Clone, Debug, PartialEq)]
5837    pub enum ContainerPatch {
5838        Background(Option<Color>),
5839    }
5840
5841    /// Realize props for a `scroll` container: which axis it scrolls. Backends create the matching
5842    /// native scroll view (vertical `UIScrollView`/`ScrollView`, horizontal
5843    /// `HorizontalScrollView`, etc.).
5844    #[derive(Clone, Debug, Default, PartialEq)]
5845    pub struct ScrollProps {
5846        pub horizontal: bool,
5847    }
5848
5849    #[derive(Clone, Debug, Default, PartialEq)]
5850    pub struct LabelProps {
5851        pub text: String,
5852        pub font: FontSpec,
5853        pub color: Option<Color>,
5854        /// What the text means, for the color the platform gives it (docs/text.md).
5855        ///
5856        /// Semantic the way [`crate::Font`] is semantic: an app says "this is secondary text"
5857        /// and each platform answers with its own answer: `secondaryLabelColor` on Apple,
5858        /// `?android:textColorSecondary`, GTK's `dim-label`. That is the only way a de-emphasized
5859        /// label stays correct in both appearances, since a literal grey that reads well on white
5860        /// is wrong on black. An explicit [`Self::color`] still wins; a backend that has no such
5861        /// color renders primary, which is legible and correct, just not dimmed.
5862        pub role: TextRole,
5863        pub wraps: bool,
5864        /// Maximum rendered lines; zero is unlimited. Apple and Android plain labels truncate
5865        /// the last line. Other backends may retain their ordinary wrapping behavior.
5866        pub max_lines: u32,
5867        /// How the label's lines sit within its own width. Only observable on a label that
5868        /// wraps or carries explicit newlines: a single line fills its box, so its alignment is
5869        /// the container's business, not the label's.
5870        ///
5871        /// `Leading` is the default and is what running text wants; `Center` is for the short,
5872        /// centered block a welcome screen or an empty state uses. A backend that cannot set
5873        /// it renders leading-aligned, which is legible and correct, just not centered.
5874        pub align: TextAlign,
5875        /// Styled spans within `text` (docs/text-runs.md). Empty is the overwhelmingly common
5876        /// case and means exactly what a label has always meant: one font, one color. A backend
5877        /// that cannot draw runs ignores this and renders `text` uniformly, which is legible and
5878        /// correct, just unstyled.
5879        pub runs: Vec<crate::TextRun>,
5880    }
5881    /// What a label's text means, for the color the platform gives it (`LabelProps::role`).
5882    #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
5883    pub enum TextRole {
5884        /// Ordinary text, in the platform's primary label color.
5885        #[default]
5886        Primary,
5887        /// De-emphasized text: a caption, a hint, the "nothing selected" line an empty detail
5888        /// pane shows. Rendered in the platform's secondary label color.
5889        Secondary,
5890    }
5891
5892    /// How a wrapped label's lines sit within its width (`LabelProps::align`).
5893    ///
5894    /// There is no `Justified` variant because no toolkit in Day's set agrees on how to justify
5895    /// the last line, and the ones that can do it at all need a paragraph style the others have
5896    /// no equivalent for.
5897    #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
5898    pub enum TextAlign {
5899        /// Left in a left-to-right locale, right in an RTL one (docs/localization.md).
5900        #[default]
5901        Leading,
5902        Center,
5903        Trailing,
5904    }
5905
5906    #[derive(Clone, Debug, PartialEq)]
5907    pub enum LabelPatch {
5908        Text(String),
5909        Color(Option<Color>),
5910        Font(FontSpec),
5911        /// New text and its runs together. One patch, not two: a run's byte range is only
5912        /// meaningful against a particular string, so applying them separately would leave the
5913        /// widget briefly holding ranges that point into the wrong text.
5914        Runs(String, Vec<crate::TextRun>),
5915    }
5916
5917    /// A button's native styling tier. `Automatic` is the toolkit's stock look; `Bordered`
5918    /// asks for a visually contained button where the stock look is borderless (iOS's plain
5919    /// system button reads as a link); `Prominent` asks for the platform's accent-filled /
5920    /// default-action affordance. Toolkits whose stock buttons are already contained treat
5921    /// `Bordered` as `Automatic`.
5922    // `Eq` is gone with the `Tinted` color: `Color` holds floats. `PartialEq` is what the
5923    // props diff uses, and that is unaffected.
5924    #[derive(Clone, Copy, Debug, Default, PartialEq)]
5925    pub enum ButtonStyleSpec {
5926        #[default]
5927        Automatic,
5928        Bordered,
5929        Prominent,
5930        /// A filled button in an app-chosen color, still drawn by the native control: the
5931        /// platform keeps its own pressed, hover, focus and disabled rendering, its button role,
5932        /// and its keyboard activation. The label color is not carried; each backend picks the
5933        /// readable one for the fill (see [`ButtonStyleSpec::on_tint`]), the same call the
5934        /// platform's own tinted buttons make.
5935        ///
5936        /// A backend with no way to recolor its button ignores this and draws its ordinary
5937        /// button. That is the trade: a plain button everywhere beats a colored
5938        /// rectangle that is no longer a button on the platforms that cannot.
5939        Tinted(Color),
5940        /// A button no wider than its title asks for (a one-glyph "−" or "+" in a stepper,
5941        /// a "×" on a chip) on toolkits whose stock button carries a minimum width and wide
5942        /// insets (Material's 88 dp button turns a two-button stepper into 240 dp). The native
5943        /// control stays: only its minimum width and horizontal padding are reduced. A toolkit
5944        /// whose buttons already hug their title (AppKit, UIKit's plain button, Qt) draws its
5945        /// ordinary button.
5946        Compact,
5947        /// Borderless native action button; compact horizontal insets on Material.
5948        Plain,
5949    }
5950
5951    impl ButtonStyleSpec {
5952        /// The label color to draw on a [`ButtonStyleSpec::Tinted`] fill: whichever of black or
5953        /// white contrasts better against it, by WCAG's contrast ratio.
5954        ///
5955        /// Comparing the two ratios rather than thresholding the luminance is the difference
5956        /// between right and nearly right. A mid amber (`#F0A64C`) has a relative luminance of
5957        /// 0.44; under a "brighter than half" test it reads as dark and takes white text, at a
5958        /// hopeless 2.2:1. Its contrast against black is 9.7:1. The two ratios cross at a
5959        /// luminance of 0.179, not 0.5, and everything between those two numbers is a button
5960        /// nobody can read.
5961        pub fn on_tint(fill: Color) -> Color {
5962            // WCAG relative luminance: sRGB channels linearized, then weighted by the eye's
5963            // sensitivity to each.
5964            let lin = |c: f64| {
5965                let c = c.clamp(0.0, 1.0);
5966                if c <= 0.04045 {
5967                    c / 12.92
5968                } else {
5969                    ((c + 0.055) / 1.055).powf(2.4)
5970                }
5971            };
5972            let l = 0.2126 * lin(fill.r) + 0.7152 * lin(fill.g) + 0.0722 * lin(fill.b);
5973            // Contrast ratio is (lighter + 0.05) / (darker + 0.05); white is 1.0, black is 0.0.
5974            let against_white = 1.05 / (l + 0.05);
5975            let against_black = (l + 0.05) / 0.05;
5976            if against_black >= against_white {
5977                Color::BLACK
5978            } else {
5979                Color::WHITE
5980            }
5981        }
5982    }
5983
5984    #[derive(Clone, Debug, Default, PartialEq)]
5985    /// The visible content and accessible title of a button with an icon.
5986    pub struct ButtonContent {
5987        /// Also serves as the accessible name when only the icon is visible.
5988        pub title: String,
5989        pub icon: Option<Icon>,
5990        pub icon_only: bool,
5991    }
5992    #[derive(Clone, Debug, Default, PartialEq)]
5993    pub struct ButtonProps {
5994        pub title: String,
5995        pub icon: Option<Icon>,
5996        pub icon_only: bool,
5997        pub enabled: bool,
5998        pub style: ButtonStyleSpec,
5999        /// The button stands for the current choice among its siblings (a document tab, a
6000        /// view switcher): the platform's own checked or selected rendering, which keeps the
6001        /// button enabled, focusable and activatable, and tells assistive tech it is selected.
6002        /// A click never toggles it natively; only the app's next patch changes it.
6003        pub selected: bool,
6004    }
6005    #[derive(Clone, Debug, PartialEq)]
6006    pub enum ButtonPatch {
6007        Title(String),
6008        /// Update an icon button's label and icon together. Plain buttons still use `Title`.
6009        Content(ButtonContent),
6010        Enabled(bool),
6011        /// The selected state (see [`ButtonProps::selected`]).
6012        Selected(bool),
6013        /// A live style change: what a reactive `.tint(…)` sends, so a button can recolor with
6014        /// app state without being torn down and realized again.
6015        Style(ButtonStyleSpec),
6016    }
6017
6018    #[derive(Clone, Debug, Default, PartialEq)]
6019    pub struct ToggleProps {
6020        pub on: bool,
6021        pub enabled: bool,
6022    }
6023    #[derive(Clone, Debug, PartialEq)]
6024    pub enum TogglePatch {
6025        On(bool),
6026        Enabled(bool),
6027    }
6028
6029    #[derive(Clone, Debug, PartialEq)]
6030    pub struct SliderProps {
6031        pub value: f64,
6032        pub min: f64,
6033        pub max: f64,
6034        pub step: Option<f64>,
6035        pub enabled: bool,
6036    }
6037    impl Default for SliderProps {
6038        fn default() -> Self {
6039            SliderProps {
6040                value: 0.0,
6041                min: 0.0,
6042                max: 1.0,
6043                step: None,
6044                enabled: true,
6045            }
6046        }
6047    }
6048    #[derive(Clone, Debug, PartialEq)]
6049    pub enum SliderPatch {
6050        Value(f64),
6051        Enabled(bool),
6052    }
6053
6054    /// SwiftUI's `pickerStyle` analogue (kinds::PICKER). Each maps to a distinct native
6055    /// control per toolkit (docs/picker.md).
6056    #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
6057    pub enum PickerStyle {
6058        /// A dropdown/pop-up menu (NSPopUpButton / GtkDropDown / QComboBox / UIButton+UIMenu / Spinner).
6059        #[default]
6060        Menu,
6061        /// A horizontal segmented control (NSSegmentedControl / UISegmentedControl / linked toggles / …).
6062        Segmented,
6063        /// A vertical radio-button group laid out inline (NSButton radios / GtkCheckButton group / …).
6064        Inline,
6065    }
6066
6067    /// Full picker props (realize). `style` is set once at build; `options`, `selected` and
6068    /// `enabled` patch (via [`PickerPatch`]).
6069    #[derive(Clone, Debug, PartialEq)]
6070    pub struct PickerProps {
6071        /// Decorative boundaries before option indexes (not selectable options). Native menu
6072        /// grouping on AppKit/UIKit; ignored by other backends and non-menu styles.
6073        pub separators_before: Vec<usize>,
6074        pub options: Vec<String>,
6075        pub selected: usize,
6076        pub style: PickerStyle,
6077        /// Whether the picker takes input. Default `true`.
6078        pub enabled: bool,
6079    }
6080    impl Default for PickerProps {
6081        fn default() -> Self {
6082            PickerProps {
6083                separators_before: Vec::new(),
6084                options: Vec::new(),
6085                selected: 0,
6086                style: PickerStyle::default(),
6087                enabled: true,
6088            }
6089        }
6090    }
6091
6092    #[derive(Clone, Debug, PartialEq)]
6093    pub enum PickerPatch {
6094        Selected(usize),
6095        /// New option labels, for a picker whose choices come from data (a document list, a
6096        /// live count). The backend rebuilds its items and keeps the selected index where it
6097        /// still exists, clamping to the last option otherwise; a fresh
6098        /// [`PickerPatch::Selected`] follows whenever the app's own binding disagrees.
6099        Options(Vec<String>),
6100        /// Enable or disable the whole control, every style alike.
6101        Enabled(bool),
6102    }
6103
6104    /// Full text-area props (realize, kinds::TEXT_AREA; docs/textarea.md). `text` seeds the
6105    /// editor; `min_lines`/`max_lines` bound the auto-growing height in text lines
6106    /// (`max_lines == 0` = unbounded). `editable`/`selectable`/`spellcheck` control the native
6107    /// editor attributes (all default `true`); a backend that can't honor one answers
6108    /// `Cap::Text{Editable,Selectable,SpellCheck}` = `Unsupported`. `text` and the three attributes
6109    /// change after build (via [`TextAreaPatch`]); the rest are build-only.
6110    #[derive(Clone, Debug, PartialEq)]
6111    pub struct TextAreaProps {
6112        pub text: String,
6113        pub placeholder: String,
6114        pub min_lines: u32,
6115        pub max_lines: u32,
6116        /// Whether the user can edit the text (`false` = read-only). Default `true`.
6117        pub editable: bool,
6118        /// Whether the text can be selected (and copied). Default `true`.
6119        pub selectable: bool,
6120        /// Whether spell-check / autocorrect highlighting is on. Default `true`.
6121        pub spellcheck: bool,
6122        /// Plain Enter emits `Event::Submitted` instead of inserting a newline (Shift+Enter
6123        /// still inserts one where the platform can distinguish). Chat composers. Default
6124        /// `false`.
6125        pub submit_on_enter: bool,
6126    }
6127
6128    impl Default for TextAreaProps {
6129        fn default() -> Self {
6130            TextAreaProps {
6131                text: String::new(),
6132                placeholder: String::new(),
6133                min_lines: 1,
6134                max_lines: 0,
6135                editable: true,
6136                selectable: true,
6137                spellcheck: true,
6138                submit_on_enter: false,
6139            }
6140        }
6141    }
6142
6143    /// Imperative text-area updates: replace the text (programmatic sync), or flip one of the
6144    /// live attributes.
6145    #[derive(Clone, Debug, PartialEq)]
6146    pub enum TextAreaPatch {
6147        SetText(String),
6148        SetEditable(bool),
6149        SetSelectable(bool),
6150        SetSpellCheck(bool),
6151    }
6152
6153    #[derive(Clone, Debug, Default, PartialEq)]
6154    pub struct TextFieldProps {
6155        pub text: String,
6156        pub placeholder: String,
6157        pub enabled: bool,
6158    }
6159    #[derive(Clone, Debug, PartialEq)]
6160    pub enum TextFieldPatch {
6161        /// Origin-tagged write (§4.4): `from_native` suppresses the echo back into the widget.
6162        Text {
6163            text: String,
6164            from_native: bool,
6165        },
6166        Placeholder(String),
6167        Enabled(bool),
6168    }
6169
6170    /// How an image is scaled to fill its frame (§18.3). Maps to each toolkit's native scaling.
6171    #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
6172    pub enum ContentMode {
6173        /// Scale to fit entirely inside the frame, preserving aspect ratio (letterboxed). The
6174        /// default: an image never stretches unless asked. SwiftUI's `.scaledToFit`.
6175        #[default]
6176        Fit,
6177        /// Scale to fill the frame, preserving aspect ratio and cropping the overflow. SwiftUI's
6178        /// `.scaledToFill`.
6179        Fill,
6180        /// Stretch to fill the frame exactly, ignoring aspect ratio.
6181        Stretch,
6182    }
6183
6184    #[derive(Clone, Debug, Default, PartialEq)]
6185    pub struct ImageProps {
6186        /// Which pixels to draw: a staged asset name, encoded bytes, or an already-decoded
6187        /// image ([`ImageSource`], docs/images.md). A name resolves through the backend's own
6188        /// pipeline (§18.2); bytes and decoded ids need [`Cap::ImageDecode`], and a backend
6189        /// without it draws nothing rather than guessing.
6190        pub source: ImageSource,
6191        pub decorative: bool,
6192        /// How the image scales within its frame (default [`ContentMode::Fit`], no stretching).
6193        pub content_mode: ContentMode,
6194        /// Optional width:height ratio the view is constrained to (e.g. `16.0/9.0`). `None` lets the
6195        /// image take its allocated frame.
6196        pub aspect_ratio: Option<f64>,
6197        /// Monochrome tint for a template/vector glyph (docs/vectors.md): backends that can,
6198        /// recolor natively (template rendering on Apple, drawable tint on Android, pixel
6199        /// recolor on GTK); backends that can't yet ignore it and draw the source colors.
6200        /// `None` (the default, and every raster `image(…)`) means "as authored".
6201        pub tint: Option<Color>,
6202        /// A monochrome template glyph (docs/vectors.md "Template"): with no `tint`, it draws
6203        /// in the foreground of the surface it sits on — the theme's label color on the
6204        /// desktops, the cell's tint on UIKit, `currentColor` on the web — and follows a
6205        /// theme switch. What a sidebar row's untinted icon is: a tinted glyph recolors the
6206        /// same way with or without this, and `false` (the default) draws an untinted glyph as
6207        /// authored. [`ImagePatch::Tint`]`(None)` on a template returns to that foreground,
6208        /// not to the authored colors.
6209        pub template: bool,
6210    }
6211
6212    /// A list row's standard content (`kinds::LIST_ITEM`, docs/list.md "List items"). Empty
6213    /// text means the part is absent.
6214    #[derive(Clone, Debug, Default, PartialEq)]
6215    pub struct ListItemProps {
6216        pub title: String,
6217        /// A second line under the title, in the platform's secondary style.
6218        pub subtitle: String,
6219        /// Trailing text (a count, a value), in the platform's secondary style.
6220        pub detail: String,
6221        /// The leading glyph: a symbol or a bundled image.
6222        pub icon: Option<crate::Icon>,
6223        /// The glyph's color; `None` takes the platform's own (template glyphs follow the
6224        /// foreground, the tint color on UIKit).
6225        pub icon_tint: Option<Color>,
6226        /// A trailing check mark: the platform's selected-option mark (UIKit's checkmark
6227        /// accessory, a Material check icon), announced as checked.
6228        pub checked: bool,
6229    }
6230
6231    /// A live change to a realized list item; every part changes in place.
6232    #[derive(Clone, Debug, PartialEq)]
6233    pub enum ListItemPatch {
6234        Title(String),
6235        Subtitle(String),
6236        Detail(String),
6237        Icon(Option<crate::Icon>),
6238        IconTint(Option<Color>),
6239        Checked(bool),
6240    }
6241
6242    /// A live change to a realized image or vector glyph.
6243    ///
6244    /// `content_mode` and the rest still describe which art this is and how it fills its frame,
6245    /// which a rebuild expresses better than a patch. Two things do want to follow a signal: the
6246    /// tint (a glyph that recolors with the selection or the theme should repaint, not be torn
6247    /// down and realized again, docs/vectors.md "Tint") and the source, now that it can be a
6248    /// buffer the app swaps (a download landing, a new photo picked, docs/images.md). Replacing
6249    /// the pixels of a view that is already on screen is what a patch is for; realizing a second
6250    /// view would flash.
6251    #[derive(Clone, Debug, PartialEq)]
6252    pub enum ImagePatch {
6253        /// Recolor the glyph, or `None` to draw the authored colors again.
6254        Tint(Option<Color>),
6255        /// Draw different pixels in the same view. A backend that cannot decode the new source
6256        /// (bytes where [`Cap::ImageDecode`] is `Unsupported`) leaves what it was drawing.
6257        Source(ImageSource),
6258    }
6259
6260    #[derive(Clone, Debug, Default, PartialEq)]
6261    pub struct CanvasProps {
6262        pub ops: Vec<DrawOp>,
6263    }
6264
6265    /// Progress indicator. `value` is the completed fraction in `0.0..=1.0`; `None` means
6266    /// indeterminate (an animated spinner / busy bar, no known extent). Backends map this to
6267    /// their native determinate/indeterminate widgets (docs/progress.md).
6268    #[derive(Clone, Debug, PartialEq)]
6269    pub struct ProgressProps {
6270        pub value: Option<f64>,
6271        /// Whether an indeterminate indicator animates; ignored for a determinate bar.
6272        pub animating: bool,
6273        /// The platform's large indicator size.
6274        pub large: bool,
6275    }
6276    impl Default for ProgressProps {
6277        fn default() -> Self {
6278            Self {
6279                value: None,
6280                animating: true,
6281                large: false,
6282            }
6283        }
6284    }
6285    #[derive(Clone, Debug, PartialEq)]
6286    pub enum ProgressPatch {
6287        Animating(bool),
6288        /// New completed fraction, or `None` to switch to indeterminate.
6289        Value(Option<f64>),
6290    }
6291
6292    /// A rule between neighbors (`divider()`): a hairline across the width it is offered, or,
6293    /// with `vertical`, down the height it is offered (`divider().vertical()`, between a
6294    /// row's panes). A toolkit measures both the same way, as a horizontal rule, because the
6295    /// pieces layer swaps the axes of a vertical one's proposal and answer; realization is
6296    /// where the orientation matters, for the few widgets that draw a horizontal line
6297    /// regardless of their frame.
6298    #[derive(Clone, Debug, Default, PartialEq)]
6299    pub struct DividerProps {
6300        pub vertical: bool,
6301    }
6302
6303    /// How a navigation host lays its panes out (docs/navigation.md).
6304    ///
6305    /// This is the resolved presentation, what the toolkit must draw right now. The app asks for
6306    /// one through `Nav::presentation`, where leaving it unset means "automatic": the pieces
6307    /// layer resolves it from the window's [`SizeClass`] and the toolkit's `Cap::NavSplit`, and
6308    /// re-resolves it whenever the class changes. There is no `Auto` variant here because a
6309    /// backend can only ever draw a concrete one, so the undecided state stays on the app's side
6310    /// of the boundary where it can still be decided.
6311    #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
6312    pub enum NavPresentation {
6313        /// Sidebar beside detail, both visible (`NSSplitViewController`, nested `GtkPaned`s,
6314        /// a `NavigationView`). The sidebar pane gets its own container.
6315        Split,
6316        /// One page at a time, back-navigable. The sidebar pane becomes the stack's root.
6317        #[default]
6318        Stack,
6319        /// The rows drawn as a tab bar, one page's content beside it, no back stack: what a
6320        /// phone-shaped window wants from a one-of-N surface (`UITabBarController`, a Material
6321        /// `NavigationBarView`, `NavigationView.PaneDisplayMode = Top`). The `Pane::Sidebar` page
6322        /// is not drawn at all: its rows are the chrome.
6323        Tabs,
6324        /// The rows drawn as a narrow icon strip beside the content, the `Medium`-width answer
6325        /// between [`Self::Tabs`] and [`Self::Split`] (a Material `NavigationRailView`,
6326        /// `PaneDisplayMode = LeftCompact`, an ArkUI vertical `Tabs`).
6327        ///
6328        /// A backend with no rail rounds it to a neighbor of its own choosing rather than
6329        /// failing: UIKit answers `Tabs` (which is what iPadOS does at that width), GTK the same.
6330        /// Rounding is expected and correct; this variant is a request, not a contract.
6331        Rail,
6332    }
6333
6334    impl NavPresentation {
6335        /// `true` for [`NavPresentation::Split`], the shape most backend code wants.
6336        pub fn is_split(self) -> bool {
6337            self == NavPresentation::Split
6338        }
6339
6340        /// `true` when the rows are the chrome rather than a drawn page: [`Self::Tabs`] and
6341        /// [`Self::Rail`]. Both hide the `Pane::Sidebar` page and render its rows themselves, so
6342        /// backend code that only cares about that distinction asks this instead of matching both.
6343        pub fn rows_are_chrome(self) -> bool {
6344            matches!(self, NavPresentation::Tabs | NavPresentation::Rail)
6345        }
6346    }
6347
6348    /// Navigation host (docs/navigation.md).
6349    #[derive(Clone, Debug, Default, PartialEq)]
6350    pub struct NavProps {
6351        /// Document-tab chrome, independent of navigation destinations.
6352        pub documents: Option<DocumentTabsConfig>,
6353        pub title: String,
6354        /// The presentation to draw now; re-presented in place by [`NavPatch::Presentation`].
6355        pub presentation: NavPresentation,
6356        /// The app left the presentation automatic (`NavStyle::Automatic`, or a `Sidebar`
6357        /// nav host with no `.presentation(…)` pin), so it is free to follow the window.
6358        ///
6359        /// Only a toolkit answering `Cap::NavRepresent = Emulated` needs this: its own adaptive
6360        /// container owns the morph, and it must know whether the app asked for one at all before
6361        /// building it. With two presentations that bit could be inferred from a lowered `Split`;
6362        /// with four it cannot, so it is carried explicitly rather than encoded.
6363        ///
6364        /// `Native` re-presenters ignore it (they are told each presentation as it is resolved),
6365        /// and so do toolkits that cannot re-present.
6366        pub adaptive: bool,
6367        /// Draw the platform's own show/hide-sidebar affordance on this host's chrome
6368        /// (docs/toolbars.md). `true` for every `nav(Sidebar)` unless the app opted out:
6369        /// the toolkit owns both the button and the behavior
6370        /// (`NSToolbarToggleSidebarItemIdentifier`, the split view's collapse on GTK,
6371        /// `NavigationView.IsPaneOpen` on XAML), so an app that once declared the item by hand
6372        /// now declares nothing. Hosts with no sidebar ignore it.
6373        pub sidebar_toggle: bool,
6374        /// Search over this navigation surface (`Nav::searchable`, docs/search.md).
6375        /// `None` = the surface is not searchable and no field is rendered anywhere.
6376        pub search: Option<SearchProps>,
6377        /// `Some(width)` = this host has a content-list pane ([`Pane::List`]) at this preferred
6378        /// width in points, between the sidebar and the detail (docs/navigation.md). Read at
6379        /// realize, because a backend that builds a different container for a three-pane host
6380        /// (UIKit's triple-column style is init-only) needs to know before it builds. `None` on
6381        /// every host without one, including all of them on backends answering
6382        /// [`crate::Cap::NavContentList`] `Unsupported`: the pieces layer composes there and
6383        /// the prop is never set.
6384        pub list_width: Option<f64>,
6385        /// Whether that pane is showing for the destination the host opens on
6386        /// (`Nav::content_list_for`). Read at realize, like `list_width`, and for a
6387        /// related reason: a backend whose pane is a real split item can only honor a
6388        /// collapsed state reliably by setting it before the item joins the split. Told
6389        /// afterwards (by `NavPatch::ListVisible`, on a window that has not been displayed
6390        /// yet), AppKit reports the item collapsed and then lays it back out from its holding
6391        /// priorities, and the app opens with a list beside a page that does not own one.
6392        /// `true` on every host whose first destination has a list, and on hosts with no pane
6393        /// at all, where it means nothing.
6394        pub list_visible: bool,
6395    }
6396
6397    /// Switch only tab chrome; resident contents must retain their native identity.
6398    #[derive(Clone, Copy, Debug, PartialEq)]
6399    pub struct DocumentTabsPatch {
6400        pub native: bool,
6401    }
6402
6403    /// Localized document-tab chrome. Native callbacks emit stable route keys.
6404    #[derive(Clone, Debug, Default, PartialEq)]
6405    pub struct DocumentTabsConfig {
6406        pub new_label: String,
6407        pub close_label: String,
6408        pub can_add: bool,
6409    }
6410
6411    /// Where a searchable surface's field should be drawn.
6412    ///
6413    /// A preference, not an instruction: a backend that cannot honor the request falls back to
6414    /// whatever its platform does, exactly as SwiftUI's `searchable(placement:)` does ("depending
6415    /// on the containing view hierarchy and platform, the requested placement may not be able to
6416    /// be fulfilled"). `Automatic` is the one to reach for: it is what lets the field live in the
6417    /// window toolbar on a wide window and move into the navigation list on a narrow one.
6418    #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
6419    pub enum SearchPlacement {
6420        /// The platform decides, from the window's size class and its own convention.
6421        #[default]
6422        Automatic,
6423        /// In the window's toolbar (`NSSearchToolbarItem`, an `AdwHeaderBar` entry, a
6424        /// `CommandBar` `AutoSuggestBox`). `Inline` where the toolbar cannot hold a search field
6425        /// (`Cap::ToolbarSearch`).
6426        Toolbar,
6427        /// Attached to the navigation surface itself: above the sidebar list, or in the
6428        /// navigation bar's search drawer on the phones.
6429        Inline,
6430    }
6431
6432    /// Search over a navigation surface (docs/search.md). The query itself stays an app-owned
6433    /// signal; this carries only what the toolkit must draw, so moving the field between
6434    /// placements never moves the state.
6435    #[derive(Clone, Debug, Default, PartialEq)]
6436    pub struct SearchProps {
6437        /// Current text. Two-way: the user typing emits [`Event::SearchChanged`], and the app's
6438        /// own writes arrive as [`SearchPatch::Text`].
6439        pub text: String,
6440        /// Empty-state prompt.
6441        pub prompt: String,
6442        pub placement: SearchPlacement,
6443        /// Opt into native scrolling search/title chrome on mobile. Default false keeps
6444        /// the field pinned. Desktop toolbar search is unchanged.
6445        pub hides_on_scroll: bool,
6446        /// Start the UIKit navigation search drawer collapsed, with a compact toolbar title.
6447        /// Implies scrolling search on UIKit; ignored by other backends. Default false.
6448        pub initially_hidden: bool,
6449        /// Scope titles, empty = no scope bar. One-of-N: a `UISearchBar` scope bar, a Material
6450        /// `ChipGroup` of single-selection filter chips, an ArkUI `SegmentButtonV2`, an
6451        /// `NSSegmentedControl` (docs/search.md has the per-backend table).
6452        pub scopes: Vec<String>,
6453        /// Index into `scopes`; meaningless when `scopes` is empty.
6454        pub scope: usize,
6455        /// Completions offered for the current text. On a navigation surface these complete the
6456        /// field rather than replacing the list: the list is already the result set, so an
6457        /// overlay of results would cover the thing it is filtering.
6458        pub suggestions: Vec<String>,
6459    }
6460
6461    /// A targeted update to a live search field, the path a bound signal writes through, so
6462    /// syncing text never rebuilds (and refocuses) the field mid-word.
6463    #[derive(Clone, Debug, PartialEq)]
6464    pub enum SearchPatch {
6465        Focus,
6466        Text(String),
6467        Scope(usize),
6468        Suggestions(Vec<String>),
6469    }
6470    /// Applied to the nav host after a page child is attached / before it is removed;
6471    /// the toolkit animates its native presentation accordingly.
6472    #[derive(Clone, Debug, PartialEq)]
6473    pub enum NavPatch {
6474        /// The just-attached last page child became the top of the stack. `immersive` marks a
6475        /// page that keeps the floating transparent chrome on backends with an immersive nav
6476        /// mode (day-toolkit-material edge-to-edge today; ignored elsewhere). Unmarked pages get the
6477        /// standard opaque bar.
6478        Pushed { title: String, immersive: bool },
6479        /// The top page is about to be removed; present its predecessor.
6480        Popped,
6481        /// Current top-of-stack title changed.
6482        Title(String),
6483        /// The top page has a back guard (`NavStack::on_back`, docs/navigation.md): while `true`,
6484        /// the toolkit must not auto-pop on a native back gesture/button but route it to
6485        /// Day as `Event::NavBack { already_popped: false }` so the app's guard decides. On
6486        /// backends whose back already routes through Day (AppKit/Qt/XAML/web custom headers)
6487        /// this is a no-op; iOS disables the swipe, Android holds its callback, GTK sets the
6488        /// page `can-pop=false`, ArkUI consumes `onBackPressed`.
6489        GuardTop(bool),
6490        /// Re-present the host: the window's size class crossed a breakpoint, or the app wrote a
6491        /// new `presentation`. The page children do not change: the toolkit rebuilds its
6492        /// chrome and re-homes the pages it already has, each one landing by its
6493        /// [`NavPageProps::pane`]. Rebuilding them instead would drop scroll offsets, field
6494        /// focus, and every native animation in flight, which is why this is a patch and not
6495        /// a rebuild.
6496        ///
6497        /// Backends with no split container ignore it and stay stacked.
6498        Presentation(NavPresentation),
6499        /// Show the resident [`Pane::Detail`] page at this index, counting the host's detail
6500        /// children in attach order. The counterpart to [`Self::Pushed`]/[`Self::Popped`] for the
6501        /// presentations where pages are resident rather than stacked
6502        /// ([`NavPresentation::rows_are_chrome`]): a tab bar switches between pages that all stay
6503        /// alive, so there is nothing to push and nothing to pop.
6504        ///
6505        /// Applied without re-emitting [`crate::Event::SelectionChanged`], per the from-native
6506        /// echo rule: this is the programmatic-sync direction.
6507        ///
6508        /// A backend drawing a stacked presentation never receives it; the pieces layer sends
6509        /// push/pop there instead.
6510        Select(usize),
6511        /// Reorder resident detail pages by their previous indices without rebuilding them.
6512        Reorder(Vec<usize>),
6513        /// Show or collapse the content-list pane ([`Pane::List`]), the per-destination
6514        /// visibility switch (`Nav::content_list_for`, docs/navigation.md): a nav host
6515        /// section that spans the whole detail area (a settings page) collapses the pane, and
6516        /// selecting a list-backed section brings it back. Only sent to hosts whose
6517        /// [`NavProps::list_width`] is set. Applied directly, not through an animator proxy:
6518        /// the screenshot step captures the instant the patch returns (the sidebar-toggle rule).
6519        ListVisible(bool),
6520        /// Stacked presentations on a merged-pane backend ([`crate::Cap::NavContentList`]
6521        /// `Emulated`) only: the resident [`Pane::List`] page joins (`true`) or leaves
6522        /// (`false`) the navigation stack directly above the sidebar root. The pieces layer
6523        /// sends it as the selection gains or loses a list-backed destination; the backend
6524        /// realizes the membership change through its platform's navigation APIs (UIKit:
6525        /// `showColumn(.supplementary)` / a pop to the root; never a manual splice, which
6526        /// destroys the split's collapse bookkeeping). Never sent to `Native` backends (their
6527        /// pane persists through every presentation) nor while split.
6528        ListInStack(bool),
6529    }
6530
6531    /// Which pane of a navigation host a page belongs to (docs/navigation.md).
6532    ///
6533    /// A page's pane is a fact about the model, not about how the host currently draws it: a
6534    /// nav host's list page is [`Pane::Sidebar`] whether the toolkit is showing a sidebar beside
6535    /// a detail or stacking the two. What the presentation decides is where each pane lands:
6536    /// its own splitter pane in [`NavPresentation::Split`], the root of the stack in
6537    /// [`NavPresentation::Stack`]. Keeping the two separate is what lets a host re-present on a
6538    /// size-class change (`NavPatch::Presentation`) by re-homing the pages it already has,
6539    /// instead of tearing the tree down and rebuilding it.
6540    #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
6541    pub enum Pane {
6542        /// The list / master pane of a nav host. At most one page per host.
6543        Sidebar,
6544        /// The content-list pane between the sidebar and the detail, Mail's message list
6545        /// (`Nav::content_list`, docs/navigation.md). At most one page per host, and only
6546        /// on hosts whose [`NavProps::list_width`] is set; a backend answering
6547        /// [`crate::Cap::NavContentList`] `Unsupported` never sees one.
6548        List,
6549        /// A destination page. Every page of a `nav_stack` presentation is one of these.
6550        #[default]
6551        Detail,
6552    }
6553
6554    /// One destination's native container.
6555    #[derive(Clone, Debug, Default, PartialEq)]
6556    pub struct NavPageProps {
6557        pub title: String,
6558        pub pane: Pane,
6559    }
6560
6561    /// The largest a modal sheet grows on a desktop, in points: the window less a margin up to
6562    /// this (docs/cover.md "Modal sheet"). AppKit's native sheet and the composed card share it.
6563    pub const SHEET_MAX: crate::Size = crate::Size::new(640.0, 620.0);
6564    /// The largest a [`CoverProps::large`] sheet grows (docs/cover.md "Large sheet").
6565    pub const LARGE_SHEET_MAX: crate::Size = crate::Size::new(1040.0, 880.0);
6566
6567    /// A fullscreen cover's content container (docs/cover.md). Realized detached and hidden;
6568    /// `CoverPatch::Present` shows it over the whole window.
6569    #[derive(Clone, Debug, Default, PartialEq)]
6570    pub struct CoverProps {
6571        /// Prefer a native sheet; toolkits without sheet presentation keep their modal cover.
6572        pub sheet: bool,
6573        /// A half-height sheet rising from the bottom edge, the window content above it
6574        /// staying on show and, where the platform allows, interactive: an inspector over the
6575        /// canvas it describes. Implies `sheet`. The toolkit reports the sheet's own content
6576        /// size through `FrameChanged`, as for any cover (docs/cover.md "Half sheet").
6577        pub half: bool,
6578        /// A large sheet: most of the window, less a margin, for a document or web page that
6579        /// needs the room (docs/cover.md "Large sheet"). Implies `sheet`.
6580        pub large: bool,
6581    }
6582
6583    /// Applied to a `kinds::COVER` node as its bound signal opens and closes it.
6584    #[derive(Clone, Debug, PartialEq)]
6585    pub enum CoverPatch {
6586        /// Present the cover fullscreen (slide up where the platform animates modals).
6587        /// `background` paints the whole surface edge-to-edge (under the status bar / home
6588        /// indicator); the content container is inset to the safe area within it.
6589        /// `dismiss_disabled` = the user must not be able to dismiss it interactively
6590        /// (system back / sheet gestures); programmatic dismissal still works.
6591        Present {
6592            background: Option<Color>,
6593            dismiss_disabled: bool,
6594        },
6595        /// The `interactive_dismiss_disabled` state changed while presented.
6596        DismissDisabled(bool),
6597        /// Dismiss the cover. When the hide transition finishes the backend emits
6598        /// [`crate::Event::CoverHidden`] on the node (trampoline backends send
6599        /// `BridgeKind::CoverHidden`), letting the piece dispose the content only after it
6600        /// left the screen.
6601        Dismiss,
6602    }
6603
6604    /// A `kinds::INSPECTOR` split (docs/inspector.md): content beside a trailing inspector
6605    /// pane. The pane's visibility is Day-owned state (the piece's bound signal), so the
6606    /// props carry the value to draw and [`InspectorPatch::Visible`] keeps it current;
6607    /// a native affordance hiding the pane (a dock close button, a dragged-shut divider)
6608    /// reports back with [`crate::Event::InspectorChanged`].
6609    #[derive(Clone, Debug, PartialEq)]
6610    pub struct InspectorProps {
6611        /// Whether the pane is showing now.
6612        pub visible: bool,
6613        /// The pane's preferred width in points. A backend with a user-draggable divider
6614        /// treats it as the initial width; one without draws it at exactly this.
6615        pub width: f64,
6616        /// Which side of the content the pane sits on. `Trailing` is the classic inspector;
6617        /// `Leading` is a utility pane like a layer panel (docs/tree.md).
6618        pub edge: PaneEdge,
6619    }
6620
6621    /// Which side an inspector pane occupies (docs/inspector.md).
6622    #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
6623    pub enum PaneEdge {
6624        #[default]
6625        Trailing,
6626        Leading,
6627    }
6628
6629    /// Applied to a `kinds::INSPECTOR` node as its bound signal changes.
6630    #[derive(Clone, Debug, PartialEq)]
6631    pub enum InspectorPatch {
6632        /// Show or hide the pane (animated where the platform animates panes). The
6633        /// programmatic-sync direction: applying it must not re-emit
6634        /// [`crate::Event::InspectorChanged`], per the from-native echo rule.
6635        Visible(bool),
6636    }
6637
6638    /// One pane of a `kinds::INSPECTOR` split (docs/inspector.md).
6639    #[derive(Clone, Debug, Default, PartialEq)]
6640    pub struct InspectorPaneProps {
6641        /// `true` for the inspector panel itself, `false` for the content pane.
6642        pub panel: bool,
6643    }
6644
6645    /// How a `kinds::SPLIT` lays its two panes (docs/split.md): beside each other, the divider
6646    /// standing, or stacked, the divider lying. Named by where the panes go, since that is
6647    /// what an app's "layout" toggle means; the divider runs the other way.
6648    #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
6649    pub enum SplitAxis {
6650        /// The panes side by side (first leading), the divider vertical.
6651        #[default]
6652        Horizontal,
6653        /// The panes stacked (first on top), the divider horizontal.
6654        Vertical,
6655    }
6656
6657    /// A `kinds::SPLIT` (docs/split.md): two panes with a divider the user drags. The first
6658    /// pane's share is Day-owned state (the piece's bound signal): the props carry the value
6659    /// to draw, [`SplitPatch::Fraction`] keeps it current, and a divider the user moved
6660    /// reports back as [`crate::Event::ValueChanged`] with the new share, which applying the
6661    /// patch must never re-emit (the from-native echo rule).
6662    #[derive(Clone, Debug, PartialEq)]
6663    pub struct SplitProps {
6664        pub axis: SplitAxis,
6665        /// The first pane's share of the split's length along `axis`, `0.0..=1.0`.
6666        pub fraction: f64,
6667        /// The least length either pane may be dragged to, in points.
6668        pub min_pane: f64,
6669    }
6670
6671    /// Applied to a `kinds::SPLIT` node as its bound signals change.
6672    #[derive(Clone, Debug, PartialEq)]
6673    pub enum SplitPatch {
6674        /// Turn the split the other way, keeping the share.
6675        Axis(SplitAxis),
6676        /// Move the divider so the first pane takes this share. The programmatic-sync
6677        /// direction: applying it must not re-emit [`crate::Event::ValueChanged`].
6678        Fraction(f64),
6679    }
6680
6681    /// One pane of a `kinds::SPLIT` (docs/split.md).
6682    #[derive(Clone, Debug, Default, PartialEq)]
6683    pub struct SplitPaneProps {
6684        /// `false` for the first pane, `true` for the second.
6685        pub second: bool,
6686    }
6687
6688    /// Native navigation item list. `items` are display titles in route order;
6689    /// `selected` highlights the active route (split presentation; None on mobile roots).
6690    /// `icons` (parallel to `items`, `None` = no icon) are bundled image names resolved by each
6691    /// backend via `resource::resolve_image_file`; a backend that can't decorate its rows just
6692    /// ignores them.
6693    #[derive(Clone, Debug, Default, PartialEq)]
6694    pub struct NavMenuProps {
6695        /// Stable document identities, parallel to items; empty for ordinary navigation.
6696        pub document_keys: Vec<String>,
6697        pub items: Vec<String>,
6698        pub icons: Vec<Option<String>>,
6699        /// A trailing accessory per row: an unread count, a status. Rendered right-aligned and
6700        /// de-emphasized, opposite the label. Parallel to `items`; `None` draws nothing.
6701        pub badges: Vec<Option<String>>,
6702        /// A trailing symbol accessory per row, in the same slot as [`Self::badges`] and drawn
6703        /// after it: a bundled image name resolved the way [`Self::icons`] is. This is what a
6704        /// row-level status glyph rides on (a starred page's star) where `badges` carries only
6705        /// text. Parallel to `items`; `None` draws nothing.
6706        pub badge_icons: Vec<Option<String>>,
6707        /// The tint for [`Self::badge_icons`], parallel to `items`. `None` leaves the glyph at
6708        /// the backend's neutral template tint; a status glyph that means something (a yellow
6709        /// star) names its own color here, exactly as [`Self::tints`] does for the leading icon.
6710        pub badge_tints: Vec<Option<Color>>,
6711        /// A per-row icon tint (docs/vectors.md): the row's glyph recolored to this instead of
6712        /// the backend's neutral template tint. Parallel to `items`; `None` keeps the default.
6713        pub tints: Vec<Option<Color>>,
6714        /// A section header introducing the row at the same index. `Some` opens a new group
6715        /// before that row; `None` continues the current one. Parallel to `items`, so adding a
6716        /// header never shifts the selection indices the rows are addressed by.
6717        pub sections: Vec<Option<String>>,
6718        /// A per-row context menu (docs/menus.md): shown on secondary-click / long-press on
6719        /// that row, the same [`crate::MenuItem`] model as everywhere else: items carry
6720        /// registered action ids, so a chosen entry dispatches [`crate::Event::MenuAction`]
6721        /// exactly like a piece context menu. Parallel to `items`; empty = no menu.
6722        pub menus: Vec<Vec<crate::MenuItem>>,
6723        /// Which rows drag to reorder (docs/navigation.md "Reordering sidebar destinations"),
6724        /// parallel to `items`; empty when the sidebar does not reorder. A row moves only
6725        /// within the run of movable rows around it, which a section header or a fixed row
6726        /// ends. A toolkit whose `Cap::NavReorder` is `Native` drags the rows in its own
6727        /// sidebar and reports a drop as [`crate::Event::ListReorder`] in item indices: `from`
6728        /// is the moved row, `to` the row whose position it takes, in the order before the move.
6729        pub movable: Vec<bool>,
6730        /// The sidebar regroups (docs/navigation.md "Moving rows between sections"): a movable
6731        /// row may also cross section headers, into any section whose rows are all movable. A
6732        /// toolkit whose `Cap::NavReorder` is `Native` offers those drops too and reports every
6733        /// drop as [`crate::Event::NavRegroup`] instead of [`crate::Event::ListReorder`]. `false`
6734        /// keeps [`Self::movable`]'s run rule.
6735        pub regroup: bool,
6736        /// Which movable rows keep the app's sorted order within their own section, parallel to
6737        /// `items`; empty when the sidebar does not regroup. Under [`Self::regroup`], a sorted
6738        /// row drops only into another section: no gap in its own section is offered.
6739        pub sorted: Vec<bool>,
6740        pub selected: Option<usize>,
6741    }
6742    #[derive(Clone, Debug, PartialEq)]
6743    // `Items` carries every row array; a patch travels boxed (`Box<dyn Any>`) and lives for one
6744    // update, so the variants' size difference costs nothing worth an indirection.
6745    #[allow(clippy::large_enum_variant)]
6746    pub enum NavMenuPatch {
6747        /// Active icon overlays by row index: None spins, Some(0..=1) fills a circle.
6748        /// Rows absent from this complete snapshot have no overlay. Does not relayout rows.
6749        /// Currently rendered by AppKit/UIKit; other backends may ignore this decoration.
6750        IconProgress(Vec<(usize, Option<f64>)>),
6751        /// Programmatic highlight sync: toolkits apply without re-emitting
6752        /// SelectionChanged (the TextField from_native echo rule).
6753        Selected(Option<usize>),
6754        /// The item set changed (data-driven `nav().items(signal, …)`): rebuild the rows
6755        /// from these labels/icons, then apply `selected` (docs/navigation.md). Applied without
6756        /// re-emitting SelectionChanged.
6757        ///
6758        /// `rows_changed` is `Some` when the rows themselves are the ones already shown (same
6759        /// keys, sections and row menus) and only these rows' title, icon, tint or badge moved:
6760        /// a count ticking, a language change. A backend updates those rows in place (a tab's
6761        /// badge, a menu item's title) rather than rebuilding, which on most platforms re-lays
6762        /// the bar and replays its selection animation; one that cannot rebuilds as for `None`.
6763        Items {
6764            rows_changed: Option<Box<[usize]>>,
6765            document_keys: Box<[String]>,
6766            items: Vec<String>,
6767            icons: Vec<Option<String>>,
6768            badges: Vec<Option<String>>,
6769            badge_icons: Vec<Option<String>>,
6770            badge_tints: Vec<Option<Color>>,
6771            sections: Vec<Option<String>>,
6772            tints: Vec<Option<Color>>,
6773            menus: Vec<Vec<crate::MenuItem>>,
6774            /// [`NavMenuProps::movable`] for the new rows.
6775            movable: Vec<bool>,
6776            /// [`NavMenuProps::sorted`] for the new rows ([`NavMenuProps::regroup`] holds for
6777            /// the sidebar's life).
6778            sorted: Vec<bool>,
6779            selected: Option<usize>,
6780        },
6781    }
6782
6783    /// How a recycling list sizes its rows (docs/list.md).
6784    #[derive(Clone, Copy, Debug, PartialEq, Default)]
6785    pub enum RowHeight {
6786        /// Every row is this tall, a true layout boundary; the fastest path.
6787        Uniform(f64),
6788        /// Rows self-size from their content (host re-measures on change; slower).
6789        #[default]
6790        Automatic,
6791    }
6792
6793    /// Configure a navigation sidebar's native pull-to-refresh control. Not a synthetic pan:
6794    /// supported toolkits own gesture arbitration and the progress indicator. A false state
6795    /// ends a pull, including a request the application declines. Never emits an event.
6796    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
6797    pub struct RefreshPatch {
6798        pub refreshing: bool,
6799    }
6800
6801    /// Native recycling list (docs/list.md). The host owns scrolling + cell reuse; Day supplies
6802    /// row content on demand through the injected `ListSource` (see `Toolkit::attach_list`).
6803    #[derive(Clone, Debug, Default, PartialEq)]
6804    pub struct ListProps {
6805        /// Whether the app handles row activation. Do not claim activation keys when false.
6806        pub activatable: bool,
6807        pub row_height: RowHeight,
6808        /// Whether the native list reports row selection (`Event::SelectionChanged` with the row).
6809        pub selectable: bool,
6810        /// Whether the native list allows selecting several rows at once. Where honored
6811        /// (docs/list.md has the matrix), every selection change reports the full set via
6812        /// `Event::SelectionSet`; single-selection backends keep reporting
6813        /// `Event::SelectionChanged` and treat this as `selectable`.
6814        pub multi_select: bool,
6815        /// Whether rows can be drag-reordered. The toolkit enables its native drag machinery and
6816        /// drives `ListSource::reorder` (validate via `can_move`, commit via `move_row`);
6817        /// probe `Cap::ListReorder` for per-backend support (docs/list.md).
6818        pub reorderable: bool,
6819        /// Whether rows can be deleted by the platform's own delete gesture: a trailing swipe on
6820        /// iOS and ArkUI, an `ItemTouchHelper` swipe on Android. The toolkit drives
6821        /// `ListSource::delete` (offer via `can_delete`, commit via `delete_row`); probe
6822        /// `Cap::ListDelete` for per-backend support (docs/list.md). Desktop toolkits have no such
6823        /// gesture and answer `Unsupported`; an app that must delete everywhere pairs this with an
6824        /// explicit control (a menu item, a button) rather than relying on the swipe.
6825        pub deletable: bool,
6826        /// The label on that affordance, already localized by the app. A toolkit cannot invent
6827        /// translated text (it has no access to the app's catalog), so the string arrives with
6828        /// the props. Empty means "no text": each backend falls back to its platform's own
6829        /// wordless idiom (a trash glyph), which works in every language.
6830        pub delete_label: String,
6831        /// The rows offer edge swipe actions (docs/list.md) through the injected
6832        /// `ListSource::swipe` (offer via `actions_at`, commit via `perform`); probe
6833        /// [`crate::Cap::ListSwipeActions`] for per-backend support. A backend without the
6834        /// affordance never shows one; an app that must offer the command everywhere
6835        /// pairs the swipe with an explicit control, exactly as `deletable` documents.
6836        pub swipe_actions: bool,
6837        /// Row separators, drawn by the host at the row boundary (docs/list.md), so they
6838        /// align with the native selection and ride the platform's own row animations (a
6839        /// macOS/iOS swipe slides the row content past a stationary separator, exactly as
6840        /// Mail's does). `None` keeps each platform's own default (iOS draws them, the
6841        /// desktops don't); `Some(true)`/`Some(false)` forces. A backend without a separator
6842        /// mechanism ignores a force (the matrix in docs/list.md says which); rows there
6843        /// separate by their pitch alone.
6844        pub separators: Option<bool>,
6845        /// The list starts in the platform's editing mode (docs/list.md): delete controls on
6846        /// the rows `deletable` offers, reorder grips on the rows `reorderable` moves, and a
6847        /// tap that still activates. Later changes arrive as [`ListPatch::Editing`]. Probe
6848        /// [`crate::Cap::ListEditing`]; a backend without an editing mode ignores it.
6849        pub editing: bool,
6850        /// The rows fall into sections, each opened by a header row (docs/list.md
6851        /// "Sections"): `ListSource::is_header` says which rows. Probe
6852        /// [`crate::Cap::ListSections`] for whether headers float natively.
6853        pub sections: bool,
6854    }
6855
6856    /// One row-level result-set change. Indexes are sequential (each delta describes the
6857    /// set as the previous ones left it), so a host applies them one at a time (or falls back
6858    /// to a reload; the source's snapshot already holds the final state either way).
6859    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
6860    pub enum RowDelta {
6861        Insert(usize),
6862        Remove(usize),
6863        Move(usize, usize),
6864    }
6865
6866    /// Immutable-at-realize props of a `kinds::TREE` host (docs/tree.md). Everything that
6867    /// changes after realize flows through [`TreePatch`] or the injected `TreeSource`.
6868    #[derive(Clone, Debug, PartialEq)]
6869    pub struct TreeProps {
6870        /// Two-level sectioned list: root branches are non-selectable headings.
6871        pub section_headers: bool,
6872        pub row_height: RowHeight,
6873        /// Rows highlight and report selection ([`crate::Event::TreeSelection`]).
6874        pub selectable: bool,
6875        /// Several rows may be selected at once; every change reports the full token set.
6876        pub multi_select: bool,
6877        /// Rows drag to a new parent/position through the platform's own mechanism, driving
6878        /// `TreeSource::moves`. Probe [`crate::Cap::TreeMove`] for support.
6879        pub movable: bool,
6880        /// Indentation per depth level, in points. `None` = the platform's default step.
6881        pub indent: Option<f64>,
6882    }
6883
6884    /// Post-realize changes to a `kinds::TREE` host (docs/tree.md). Token-addressed
6885    /// throughout; see [`crate::TreeSource`] for why indices cannot address tree rows.
6886    #[derive(Clone, Debug, PartialEq)]
6887    pub enum TreePatch {
6888        /// The node set changed (count/order/parentage/content): the host re-queries its
6889        /// `TreeSource`. Expansion and selection survive by token (docs/tree.md).
6890        Reload,
6891        /// Programmatically disclose (`true`) or collapse (`false`) one row. Applied without
6892        /// re-emitting [`crate::Event::TreeExpanded`] (the from-native echo rule).
6893        Expand(u64, bool),
6894        /// Programmatic selection sync (tokens; empty = clear), applied without re-emitting
6895        /// [`crate::Event::TreeSelection`].
6896        Selected(Vec<u64>),
6897        /// Scroll this row into view, realizing it if needed. The piece has already expanded
6898        /// the row's ancestors (through the app's expansion signal) before issuing this.
6899        Reveal(u64),
6900    }
6901
6902    #[derive(Clone, Debug, PartialEq)]
6903    pub enum ListPatch {
6904        /// The row set changed (count/order/content): the host re-queries its `ListSource`.
6905        Reload,
6906        /// The row set changed by exactly these deltas: a host that can, animates each row
6907        /// in, out, or across; one that cannot treats this as [`ListPatch::Reload`]. The
6908        /// data source answers with the final state throughout.
6909        Splice(Vec<RowDelta>),
6910        /// An `Automatic`-height row was re-laid at a new height after its first layout (its
6911        /// text changed, a wrapped line appeared, the backend corrected its width): the host
6912        /// gives the row bound to physical cell `cell` (the handle `ListSource::bind_row` got,
6913        /// as `usize`) the new `height`, padding included, the same value
6914        /// `ListSource::cell_height` now answers for it.
6915        ///
6916        /// Sent from inside a day-core layout pass, with the tree borrowed: a host applies it
6917        /// after the pass (posted to its main loop), never by asking the source anything
6918        /// synchronously, which would read a `0.0` height (docs/list.md "Row heights").
6919        RowSizeInvalidated { cell: usize, height: f64 },
6920        /// Imperatively scroll the native list so its last row is fully visible (a chat timeline
6921        /// sticking to the newest message). No-op when the list is empty (docs/list.md).
6922        ScrollToEnd,
6923        /// Imperatively scroll the native list so this row is visible, realizing it if needed
6924        /// (docs/list.md). Clamped to the row count; no-op when the list is empty.
6925        ScrollToRow(usize),
6926        /// Programmatic selection sync (row indices; empty = clear): toolkits apply without
6927        /// re-emitting a selection event, like every other programmatic sync.
6928        Selected(Vec<usize>),
6929        /// Enter (`true`) or leave (`false`) the platform's list editing mode, animated
6930        /// (docs/list.md, [`ListProps::editing`]). Ignored where `Cap::ListEditing` is
6931        /// `Unsupported`.
6932        Editing(bool),
6933    }
6934}
6935
6936// ---------------------------------------------------------------------------
6937// Imperative presentation (docs/dialogs.md)
6938// ---------------------------------------------------------------------------
6939
6940pub mod present {
6941    /// A dialog button's semantic role: styling + default/cancel placement on each toolkit.
6942    #[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
6943    pub enum ButtonRole {
6944        #[default]
6945        Default,
6946        Cancel,
6947        Destructive,
6948    }
6949
6950    #[derive(Clone, Debug, PartialEq)]
6951    pub struct PresentButton {
6952        pub label: String,
6953        pub role: ButtonRole,
6954    }
6955
6956    /// A named group of file extensions for a file dialog (e.g. "Text" → `["txt", "md"]`).
6957    /// An empty `extensions` list means "all files".
6958    #[derive(Clone, Debug, PartialEq, Default)]
6959    pub struct FileFilter {
6960        pub name: String,
6961        pub extensions: Vec<String>,
6962    }
6963
6964    /// What a backend should present for a `req`. Kept toolkit-agnostic; the pieces layer
6965    /// maps a chosen button index back to a typed payload.
6966    #[derive(Clone, Debug, PartialEq)]
6967    pub enum PresentSpec {
6968        /// Alert / confirmation / action sheet: title + optional message + ordered buttons.
6969        /// `sheet` = present from the bottom on mobile (desktop falls back to an alert).
6970        Dialog {
6971            title: String,
6972            message: Option<String>,
6973            buttons: Vec<PresentButton>,
6974            sheet: bool,
6975        },
6976        /// A dialog with a single text field.
6977        Prompt {
6978            title: String,
6979            message: Option<String>,
6980            placeholder: String,
6981            initial: String,
6982            ok: String,
6983            cancel: String,
6984        },
6985        /// Native "open file" picker (docs/files.md). The backend must answer with
6986        /// `PresentResult::Files` whose entries are **readable local paths**: desktop returns
6987        /// the chosen path directly; iOS/Android copy the selection into app storage first, so
6988        /// the pieces layer can read it with `std::fs` regardless of platform. `multiple` lets
6989        /// the user pick several files at once; the answer then carries every chosen path, in
6990        /// the picker's order. A backend that cannot select more than one file still answers
6991        /// with the single pick.
6992        OpenFile {
6993            title: String,
6994            filters: Vec<FileFilter>,
6995            multiple: bool,
6996        },
6997        /// Native "choose folder" picker (docs/files.md). The backend answers with
6998        /// `PresentResult::Files` holding the one chosen directory path, or `Dismissed`. Only
6999        /// backends answering [`Cap::FolderDialog`](crate::Cap::FolderDialog) as `Native` show a
7000        /// chooser; the others resolve the request as `Dismissed` at once, so the await never hangs.
7001        OpenFolder { title: String },
7002        /// Native "save file" picker (docs/files.md). `src_path` is a Day-written temp file
7003        /// holding the bytes to save; iOS/Android deliver it to the chosen destination natively,
7004        /// and the pieces layer best-effort copies it to a chosen local path otherwise.
7005        SaveFile {
7006            title: String,
7007            suggested_name: String,
7008            src_path: String,
7009            filters: Vec<FileFilter>,
7010        },
7011    }
7012
7013    /// The user's answer to a presentation.
7014    #[derive(Clone, Debug, PartialEq)]
7015    pub enum PresentResult {
7016        /// A dialog button at `index` (in spec order) was chosen.
7017        Button(i64),
7018        /// A prompt was confirmed with `text`.
7019        Text(String),
7020        /// One or more file locators chosen from an open/save picker (docs/files.md). Each is a
7021        /// local filesystem path or, on Android save, a `content://` URI.
7022        Files(Vec<String>),
7023        /// Dismissed without choosing (tap-outside / Esc / cancel gesture).
7024        Dismissed,
7025    }
7026
7027    /// The unit-separator that joins string lists across the C ABI (Qt shim / Android JNI), the
7028    /// same encoding the nav menu, combobox, and dialog-button shims use.
7029    pub const UNIT_SEP: char = '\u{1f}';
7030
7031    std::thread_local! {
7032        /// An app-writable scratch directory. Backends whose OS temp dir isn't app-writable
7033        /// (Android → `getCacheDir()`) set this at startup; elsewhere it stays `None` and callers
7034        /// fall back to `std::env::temp_dir()`.
7035        // False positive, and only when checking an android target: the initializer already is
7036        // the `const` block the lint asks for. Android's TLS model makes the macro expand to a
7037        // form clippy reads as lazy, so the suggestion is unfollowable as well as unneeded.
7038        #[allow(clippy::missing_const_for_thread_local)]
7039        static APP_TEMP_DIR: std::cell::RefCell<Option<std::path::PathBuf>> =
7040            const { std::cell::RefCell::new(None) };
7041    }
7042
7043    /// Record an app-writable scratch directory (see [`app_temp_dir`]). Called by a backend at
7044    /// startup when the OS temp dir isn't writable by the app (Android).
7045    pub fn set_app_temp_dir(dir: impl Into<std::path::PathBuf>) {
7046        APP_TEMP_DIR.with(|d| *d.borrow_mut() = Some(dir.into()));
7047    }
7048
7049    /// An app-writable scratch directory: the backend-supplied one, else `std::env::temp_dir()`.
7050    /// Used by the file-save flow (docs/files.md) to stage bytes before the native save picker.
7051    pub fn app_temp_dir() -> std::path::PathBuf {
7052        APP_TEMP_DIR.with(|d| {
7053            d.borrow().clone().unwrap_or_else(|| {
7054                #[cfg(target_arch = "wasm32")]
7055                {
7056                    // A browser has no filesystem and std's `temp_dir()` panics on wasm. A
7057                    // nominal path keeps join/display plumbing alive; actual reads and writes
7058                    // fail with ordinary io errors the file flows already surface.
7059                    std::path::PathBuf::from("/day-tmp")
7060                }
7061                #[cfg(not(target_arch = "wasm32"))]
7062                std::env::temp_dir()
7063            })
7064        })
7065    }
7066
7067    /// The web build's file bytes (wasm32-unknown-unknown only): a browser has no filesystem,
7068    /// so the open/save flows carry bytes through this per-page store instead of `std::fs`:
7069    /// day-toolkit-dom writes a picked file's bytes here and answers with its virtual path; the pieces
7070    /// layer stages save bytes here for the shim to download. Paths are plain strings under
7071    /// `/day-web/`; lifetimes are one picker round-trip (the flows remove what they stage).
7072    #[cfg(all(target_family = "wasm", target_os = "unknown"))]
7073    pub mod web_files {
7074        std::thread_local! {
7075            static FILES: std::cell::RefCell<std::collections::HashMap<String, Vec<u8>>> =
7076                std::cell::RefCell::new(std::collections::HashMap::new());
7077        }
7078
7079        /// Store `bytes` under `path` (replacing any prior content).
7080        pub fn write(path: &str, bytes: Vec<u8>) {
7081            FILES.with(|f| f.borrow_mut().insert(path.to_string(), bytes));
7082        }
7083
7084        /// The bytes at `path`, if present.
7085        pub fn read(path: &str) -> Option<Vec<u8>> {
7086            FILES.with(|f| f.borrow().get(path).cloned())
7087        }
7088
7089        /// Drop `path`'s bytes.
7090        pub fn remove(path: &str) {
7091            FILES.with(|f| {
7092                f.borrow_mut().remove(path);
7093            });
7094        }
7095    }
7096
7097    impl PresentResult {
7098        /// Flat wire tag for the C ABI (Qt shim / Android JNI): 0 dismissed, 1 button, 2 text,
7099        /// 3 files (`text` is the chosen locators joined by the unit separator).
7100        pub fn decode(tag: i32, index: i64, text: String) -> PresentResult {
7101            match tag {
7102                1 => PresentResult::Button(index),
7103                2 => PresentResult::Text(text),
7104                3 => PresentResult::Files(
7105                    text.split(UNIT_SEP)
7106                        .filter(|s| !s.is_empty())
7107                        .map(str::to_string)
7108                        .collect(),
7109                ),
7110                _ => PresentResult::Dismissed,
7111            }
7112        }
7113    }
7114
7115    impl PresentSpec {
7116        /// Backend-facing flattening for the C ABI: `(title, message, button labels, button
7117        /// roles as ints, sheet-or-prompt fields)`. Pure-Rust backends read the enum directly.
7118        pub fn title(&self) -> &str {
7119            match self {
7120                PresentSpec::Dialog { title, .. }
7121                | PresentSpec::Prompt { title, .. }
7122                | PresentSpec::OpenFile { title, .. }
7123                | PresentSpec::OpenFolder { title }
7124                | PresentSpec::SaveFile { title, .. } => title,
7125            }
7126        }
7127        pub fn message(&self) -> Option<&str> {
7128            match self {
7129                PresentSpec::Dialog { message, .. } | PresentSpec::Prompt { message, .. } => {
7130                    message.as_deref()
7131                }
7132                _ => None,
7133            }
7134        }
7135        /// Button labels joined with [`UNIT_SEP`], the encoding the nav menu and combobox
7136        /// shims already use for string lists.
7137        pub fn buttons_joined(&self) -> String {
7138            match self {
7139                PresentSpec::Dialog { buttons, .. } => buttons
7140                    .iter()
7141                    .map(|b| b.label.as_str())
7142                    .collect::<Vec<_>>()
7143                    .join(&UNIT_SEP.to_string()),
7144                PresentSpec::Prompt { ok, cancel, .. } => format!("{ok}{UNIT_SEP}{cancel}"),
7145                _ => String::new(),
7146            }
7147        }
7148        /// Button roles as ints (0 default, 1 cancel, 2 destructive), joined with commas.
7149        pub fn roles_joined(&self) -> String {
7150            let roles: Vec<i32> = match self {
7151                PresentSpec::Dialog { buttons, .. } => {
7152                    buttons.iter().map(|b| b.role as i32).collect()
7153                }
7154                PresentSpec::Prompt { .. } => {
7155                    vec![ButtonRole::Default as i32, ButtonRole::Cancel as i32]
7156                }
7157                _ => vec![],
7158            };
7159            roles
7160                .iter()
7161                .map(|r| r.to_string())
7162                .collect::<Vec<_>>()
7163                .join(",")
7164        }
7165
7166        // --- file-dialog accessors (docs/files.md) ---
7167
7168        /// The file filters, if this is a file dialog.
7169        pub fn filters(&self) -> &[FileFilter] {
7170            match self {
7171                PresentSpec::OpenFile { filters, .. } | PresentSpec::SaveFile { filters, .. } => {
7172                    filters
7173                }
7174                _ => &[],
7175            }
7176        }
7177        /// Whether an open-file dialog lets the user pick several files (`false` for every
7178        /// other spec).
7179        pub fn multiple(&self) -> bool {
7180            matches!(self, PresentSpec::OpenFile { multiple: true, .. })
7181        }
7182        /// The suggested file name for a save dialog (empty otherwise).
7183        pub fn suggested_name(&self) -> &str {
7184            match self {
7185                PresentSpec::SaveFile { suggested_name, .. } => suggested_name,
7186                _ => "",
7187            }
7188        }
7189        /// The Day-written temp source path for a save dialog (empty otherwise).
7190        pub fn src_path(&self) -> &str {
7191            match self {
7192                PresentSpec::SaveFile { src_path, .. } => src_path,
7193                _ => "",
7194            }
7195        }
7196        /// Filters flattened for the C ABI: each filter is `name|ext1,ext2`, joined by
7197        /// [`UNIT_SEP`]. A trailing `|` (no extensions) means "all files". Empty when unfiltered.
7198        pub fn filters_joined(&self) -> String {
7199            self.filters()
7200                .iter()
7201                .map(|f| format!("{}|{}", f.name, f.extensions.join(",")))
7202                .collect::<Vec<_>>()
7203                .join(&UNIT_SEP.to_string())
7204        }
7205    }
7206}
7207
7208// ---------------------------------------------------------------------------
7209// App directories (docs/fs.md "Where files live")
7210// ---------------------------------------------------------------------------
7211
7212/// Where an app keeps its own files: its data, cache and configuration directories, each a
7213/// folder named after the app id in the place its platform sets aside for that kind of file
7214/// (docs/fs.md "Where files live"). Every Day crate that stores files resolves them here, so an
7215/// app's database, documents, caches, settings file and remembered window frames sit together
7216/// and apart from every other app's.
7217///
7218/// These only resolve paths; nothing is created until something is written. Each is `None` where
7219/// the platform has no such directory: the web, or an Android or HarmonyOS process whose host
7220/// passed none.
7221pub mod storage {
7222    use std::path::PathBuf;
7223
7224    /// The app's id, `[app] id` from Day.toml: `DAY_APP_ID` from `day launch`, else the value
7225    /// `day build` baked in, else the executable's name (a test binary or a bare `cargo run`).
7226    /// Made safe as a single folder name.
7227    pub fn app_id() -> String {
7228        std::env::var("DAY_APP_ID")
7229            .ok()
7230            .filter(|id| !id.is_empty())
7231            .or_else(|| {
7232                option_env!("DAY_APP_ID")
7233                    .filter(|id| !id.is_empty())
7234                    .map(str::to_owned)
7235            })
7236            .or_else(|| {
7237                let exe = std::env::current_exe().ok()?;
7238                exe.file_stem()?.to_str().map(str::to_owned)
7239            })
7240            .map(|id| folder_name(&id))
7241            .unwrap_or_else(|| "day-app".to_owned())
7242    }
7243
7244    /// The app's data directory, for what it cannot recreate: databases, documents, downloads
7245    /// the user kept. Application Support on Apple platforms (inside the container when
7246    /// sandboxed), `%LOCALAPPDATA%` on Windows, `$XDG_DATA_HOME` on Linux, the app's files
7247    /// directory on Android and HarmonyOS. `DAY_DATA_DIR` replaces it.
7248    pub fn data_dir() -> Option<PathBuf> {
7249        resolve(Dir::Data, Os::HOST, &app_id(), &env_path)
7250    }
7251
7252    /// [`data_dir`] for the app `app_id` rather than this process's own: a host that keeps a
7253    /// folder per hosted app (a day-lite superapp, a crash reporter's store), or a tool finding
7254    /// where an app it launched writes. On Android and HarmonyOS, where the host's directory is
7255    /// already the one app's, the id changes nothing.
7256    pub fn data_dir_for(app_id: &str) -> Option<PathBuf> {
7257        resolve(Dir::Data, Os::HOST, &folder_name(app_id), &env_path)
7258    }
7259
7260    /// The app's cache directory, for what it can fetch or compute again: the system may clear
7261    /// it, and backups skip it. Caches on Apple platforms, `%LOCALAPPDATA%\<id>\cache` on
7262    /// Windows, `$XDG_CACHE_HOME` on Linux, the app's cache directory on Android and HarmonyOS.
7263    /// `DAY_CACHE_DIR` replaces it; with only `DAY_DATA_DIR` set it is that directory's `cache`.
7264    pub fn cache_dir() -> Option<PathBuf> {
7265        resolve(Dir::Cache, Os::HOST, &app_id(), &env_path)
7266    }
7267
7268    /// The app's configuration directory, for small settings files: Application Support on
7269    /// Apple platforms (whose preferences proper are the user defaults), the roaming
7270    /// `%APPDATA%` on Windows, `$XDG_CONFIG_HOME` on Linux. With `DAY_DATA_DIR` set (as the
7271    /// Android and HarmonyOS hosts do) it is that directory's `config`.
7272    pub fn config_dir() -> Option<PathBuf> {
7273        resolve(Dir::Config, Os::HOST, &app_id(), &env_path)
7274    }
7275
7276    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
7277    enum Dir {
7278        Data,
7279        Cache,
7280        Config,
7281    }
7282
7283    /// The platform families whose conventions differ.
7284    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
7285    enum Os {
7286        /// macOS and iOS: `~/Library`, which is the app's container when sandboxed.
7287        Apple,
7288        Windows,
7289        /// Android and HarmonyOS: the host passes the app's private directories.
7290        Hosted,
7291        /// Linux and the BSDs: the XDG base directories.
7292        Unix,
7293        Web,
7294    }
7295
7296    impl Os {
7297        const HOST: Os = if cfg!(any(target_os = "macos", target_os = "ios")) {
7298            Os::Apple
7299        } else if cfg!(target_os = "windows") {
7300            Os::Windows
7301        } else if cfg!(any(target_os = "android", target_env = "ohos")) {
7302            Os::Hosted
7303        } else if cfg!(target_family = "wasm") {
7304            Os::Web
7305        } else {
7306            Os::Unix
7307        };
7308    }
7309
7310    /// An environment variable naming a directory: set, non-empty and absolute, else ignored.
7311    fn env_path(name: &str) -> Option<PathBuf> {
7312        let path = PathBuf::from(std::env::var_os(name)?);
7313        path.is_absolute().then_some(path)
7314    }
7315
7316    /// One folder name: no separators, no `.`/`..`, nothing a filesystem rejects.
7317    fn folder_name(id: &str) -> String {
7318        let name: String = id
7319            .chars()
7320            .map(|c| match c {
7321                '/' | '\\' | ':' | '*' | '?' | '"' | '<' | '>' | '|' => '_',
7322                c if c.is_control() => '_',
7323                c => c,
7324            })
7325            .collect();
7326        match name.trim() {
7327            "" | "." | ".." => "day-app".to_owned(),
7328            name => name.to_owned(),
7329        }
7330    }
7331
7332    /// The pure resolution, over a platform and an environment, so every platform's rules are
7333    /// testable on any host.
7334    fn resolve(
7335        dir: Dir,
7336        os: Os,
7337        id: &str,
7338        var: &dyn Fn(&str) -> Option<PathBuf>,
7339    ) -> Option<PathBuf> {
7340        // The explicit overrides: a mobile host's own directories, or a test's scratch root.
7341        if dir == Dir::Cache
7342            && let Some(cache) = var("DAY_CACHE_DIR")
7343        {
7344            return Some(cache);
7345        }
7346        if let Some(data) = var("DAY_DATA_DIR") {
7347            return Some(match dir {
7348                Dir::Data => data,
7349                Dir::Cache => data.join("cache"),
7350                Dir::Config => data.join("config"),
7351            });
7352        }
7353        let home = || var("HOME");
7354        match os {
7355            // One expression serves sandboxed and unsandboxed apps: inside the App Sandbox,
7356            // and always on iOS, `HOME` is the container's Data folder, so the same Library
7357            // path lands inside it. Apple asks for a bundle-id folder within Application
7358            // Support and Caches either way. XDG variables are ignored here: a Finder launch
7359            // never sees a shell's, so honoring them would split one app's data across two
7360            // places depending on how it was started.
7361            Os::Apple => {
7362                let library = home()?.join("Library");
7363                let base = match dir {
7364                    Dir::Data | Dir::Config => library.join("Application Support"),
7365                    Dir::Cache => library.join("Caches"),
7366                };
7367                Some(base.join(id))
7368            }
7369            // Local for data and caches: a database or cache roams badly, and a DPAPI-sealed
7370            // file cannot be read on another machine. Roaming for the small settings files.
7371            Os::Windows => {
7372                let profile = |leaf: &str| Some(var("USERPROFILE")?.join("AppData").join(leaf));
7373                let local = || var("LOCALAPPDATA").or_else(|| profile("Local"));
7374                match dir {
7375                    Dir::Data => Some(local()?.join(id)),
7376                    Dir::Cache => Some(local()?.join(id).join("cache")),
7377                    Dir::Config => Some(var("APPDATA").or_else(|| profile("Roaming"))?.join(id)),
7378                }
7379            }
7380            Os::Unix => {
7381                let (xdg, fallback) = match dir {
7382                    Dir::Data => ("XDG_DATA_HOME", ".local/share"),
7383                    Dir::Cache => ("XDG_CACHE_HOME", ".cache"),
7384                    Dir::Config => ("XDG_CONFIG_HOME", ".config"),
7385                };
7386                Some(var(xdg).or_else(|| Some(home()?.join(fallback)))?.join(id))
7387            }
7388            Os::Hosted | Os::Web => None,
7389        }
7390    }
7391
7392    #[cfg(test)]
7393    mod tests {
7394        use super::*;
7395        use std::collections::HashMap;
7396
7397        /// The resolved path as text. `Path::join` uses the host's separator, so on a Windows host
7398        /// another platform's path comes back with `\` between the joined parts; the expectations
7399        /// are that platform's own, so its separators are compared as `/`.
7400        fn at(os: Os, dir: Dir, vars: &[(&str, &str)]) -> Option<String> {
7401            let vars: HashMap<&str, &str> = vars.iter().copied().collect();
7402            let var = |name: &str| vars.get(name).map(PathBuf::from);
7403            resolve(dir, os, "dev.example.notes", &var).map(|p| {
7404                let text = p.display().to_string();
7405                if os == Os::Windows {
7406                    text
7407                } else {
7408                    text.replace('\\', "/")
7409                }
7410            })
7411        }
7412
7413        #[test]
7414        fn apple_uses_library_folders_named_for_the_app() {
7415            let home = [("HOME", "/Users/ada"), ("XDG_DATA_HOME", "/Users/ada/.xdg")];
7416            let support = "/Users/ada/Library/Application Support/dev.example.notes";
7417            assert_eq!(at(Os::Apple, Dir::Data, &home).as_deref(), Some(support));
7418            assert_eq!(at(Os::Apple, Dir::Config, &home).as_deref(), Some(support));
7419            assert_eq!(
7420                at(Os::Apple, Dir::Cache, &home).as_deref(),
7421                Some("/Users/ada/Library/Caches/dev.example.notes")
7422            );
7423            // A sandboxed app's HOME is its container, so its folders land inside it.
7424            let container = [(
7425                "HOME",
7426                "/Users/ada/Library/Containers/dev.example.notes/Data",
7427            )];
7428            assert_eq!(
7429                at(Os::Apple, Dir::Data, &container).as_deref(),
7430                Some(
7431                    "/Users/ada/Library/Containers/dev.example.notes/Data/Library/Application Support/dev.example.notes"
7432                )
7433            );
7434        }
7435
7436        #[test]
7437        fn windows_keeps_data_local_and_settings_roaming() {
7438            let vars = [
7439                ("LOCALAPPDATA", r"C:\Users\ada\AppData\Local"),
7440                ("APPDATA", r"C:\Users\ada\AppData\Roaming"),
7441            ];
7442            let data = at(Os::Windows, Dir::Data, &vars).unwrap_or_default();
7443            assert!(data.starts_with(r"C:\Users\ada\AppData\Local"), "{data}");
7444            assert!(data.ends_with("dev.example.notes"), "{data}");
7445            let cache = at(Os::Windows, Dir::Cache, &vars).unwrap_or_default();
7446            assert!(cache.ends_with("cache"), "{cache}");
7447            let config = at(Os::Windows, Dir::Config, &vars).unwrap_or_default();
7448            assert!(
7449                config.starts_with(r"C:\Users\ada\AppData\Roaming"),
7450                "{config}"
7451            );
7452        }
7453
7454        #[test]
7455        fn unix_follows_xdg_then_home() {
7456            let xdg = [
7457                ("HOME", "/home/ada"),
7458                ("XDG_DATA_HOME", "/data"),
7459                ("XDG_CACHE_HOME", "/cache"),
7460                ("XDG_CONFIG_HOME", "/config"),
7461            ];
7462            assert_eq!(
7463                at(Os::Unix, Dir::Data, &xdg).as_deref(),
7464                Some("/data/dev.example.notes")
7465            );
7466            assert_eq!(
7467                at(Os::Unix, Dir::Cache, &xdg).as_deref(),
7468                Some("/cache/dev.example.notes")
7469            );
7470            assert_eq!(
7471                at(Os::Unix, Dir::Config, &xdg).as_deref(),
7472                Some("/config/dev.example.notes")
7473            );
7474            let home = [("HOME", "/home/ada")];
7475            assert_eq!(
7476                at(Os::Unix, Dir::Data, &home).as_deref(),
7477                Some("/home/ada/.local/share/dev.example.notes")
7478            );
7479            assert_eq!(
7480                at(Os::Unix, Dir::Cache, &home).as_deref(),
7481                Some("/home/ada/.cache/dev.example.notes")
7482            );
7483            assert_eq!(
7484                at(Os::Unix, Dir::Config, &home).as_deref(),
7485                Some("/home/ada/.config/dev.example.notes")
7486            );
7487        }
7488
7489        #[test]
7490        fn hosts_and_tests_override_every_platform() {
7491            let host = [
7492                ("DAY_DATA_DIR", "/data/user/0/dev.example.notes/files"),
7493                ("DAY_CACHE_DIR", "/data/user/0/dev.example.notes/cache"),
7494            ];
7495            for os in [Os::Hosted, Os::Apple, Os::Windows, Os::Unix] {
7496                assert_eq!(
7497                    at(os, Dir::Data, &host).as_deref(),
7498                    Some("/data/user/0/dev.example.notes/files")
7499                );
7500                assert_eq!(
7501                    at(os, Dir::Cache, &host).as_deref(),
7502                    Some("/data/user/0/dev.example.notes/cache")
7503                );
7504            }
7505            let scratch = [("HOME", "/Users/ada"), ("DAY_DATA_DIR", "/tmp/run")];
7506            assert_eq!(
7507                at(Os::Apple, Dir::Cache, &scratch).as_deref(),
7508                Some("/tmp/run/cache")
7509            );
7510            assert_eq!(
7511                at(Os::Apple, Dir::Config, &scratch).as_deref(),
7512                Some("/tmp/run/config")
7513            );
7514            // Without a host directory there is nowhere to put anything.
7515            assert_eq!(at(Os::Hosted, Dir::Data, &[("HOME", "/")]), None);
7516            assert_eq!(at(Os::Web, Dir::Data, &[("HOME", "/")]), None);
7517        }
7518
7519        #[test]
7520        fn app_ids_become_one_folder_name() {
7521            assert_eq!(folder_name("dev.daybrite.news"), "dev.daybrite.news");
7522            assert_eq!(folder_name("a/b\\c:d"), "a_b_c_d");
7523            assert_eq!(folder_name(".."), "day-app");
7524            assert_eq!(folder_name(""), "day-app");
7525        }
7526    }
7527}
7528
7529// ---------------------------------------------------------------------------
7530// The Toolkit trait (§8.1)
7531// ---------------------------------------------------------------------------
7532
7533/// Timing supplied by a native display scheduler. Seconds on a monotonic clock; its epoch
7534/// is platform-specific. `target_timestamp` is absent when the platform cannot predict presentation.
7535#[derive(Clone, Copy, Debug, PartialEq)]
7536pub struct FrameStamp {
7537    pub timestamp: f64,
7538    pub target_timestamp: Option<f64>,
7539}
7540impl FrameStamp {
7541    pub fn new(timestamp: f64) -> Self {
7542        Self {
7543            timestamp,
7544            target_timestamp: None,
7545        }
7546    }
7547}
7548/// A one-shot native frame callback, always delivered asynchronously on the UI thread.
7549pub type FrameCallback = Box<dyn FnOnce(FrameStamp)>;
7550/// Cancels a pending callback and releases its native registration. UI-thread only, idempotent
7551/// in effect, and safe during/after delivery. Dropping without calling is allowed after delivery.
7552pub type CancelFrame = Box<dyn FnOnce()>;
7553
7554/// The margins and minimum height a native list gives each row ([`Toolkit::list_row_metrics`],
7555/// docs/list.md "Row metrics"): a `UITableView` cell's layout margins, a Material list item's
7556/// 16dp sides and 56dp height.
7557#[derive(Clone, Copy, Debug, Default, PartialEq)]
7558pub struct RowMetrics {
7559    /// Space between the row's edges and its content.
7560    pub insets: Insets,
7561    /// The least height a row takes, margins included; content centers vertically in it.
7562    pub min_height: f64,
7563}
7564
7565/// Platform colors for custom drawing. Native controls keep their own semantic styling.
7566#[derive(Clone, Copy, Debug, PartialEq, Eq)]
7567#[repr(u8)]
7568pub enum SystemColor {
7569    Accent,
7570    Text,
7571    SecondaryText,
7572    Background,
7573    Surface,
7574}
7575
7576impl SystemColor {
7577    /// All roles, in discriminant order, for toolkit palette snapshots.
7578    pub const ALL: [Self; 5] = [
7579        Self::Accent,
7580        Self::Text,
7581        Self::SecondaryText,
7582        Self::Background,
7583        Self::Surface,
7584    ];
7585
7586    /// Day's fallback palette when the toolkit cannot resolve a role.
7587    /// These are fixed sRGB colors, not an approximation of a user-selected system accent.
7588    pub const fn fallback(self, dark: bool) -> Color {
7589        Color::hex(match (self, dark) {
7590            (Self::Accent, false) => 0x0a66ff,
7591            (Self::Accent, true) => 0x3f83ff,
7592            (Self::Text, false) => 0x1d1d1f,
7593            (Self::Text, true) => 0xf5f5f7,
7594            (Self::SecondaryText, false) => 0x6e6e73,
7595            (Self::SecondaryText, true) => 0x98989d,
7596            (Self::Background, false) => 0xffffff,
7597            (Self::Background, true) => 0x1e1e20,
7598            (Self::Surface, false) => 0xf3f2f7,
7599            (Self::Surface, true) => 0x2c2c2e,
7600        })
7601    }
7602}
7603
7604pub trait Toolkit: Sized + 'static {
7605    // `'static` so a handle clone can cross the object-safe TreeOps boundary boxed as `Any`
7606    // (`node_handle_any`, the tweaks door, docs/tweaks.md).
7607    type Handle: Clone + 'static;
7608
7609    /// Request one frame for the window containing `host`. Never call inline. Each native source
7610    /// must stop after delivery unless requested again; no polling timer. Hidden/unmapped windows
7611    /// may defer delivery until visible. Native callbacks must reach the UI thread before calling
7612    /// Rust. The returned closure cancels safely, including when the window has closed.
7613    /// The mock intentionally stays pending: tests inject a manual scheduler in day-core.
7614    fn request_frame(&mut self, _host: &Self::Handle, _cb: FrameCallback) -> CancelFrame {
7615        Box::new(|| {})
7616    }
7617
7618    fn capability(&self, _cap: Cap) -> Support {
7619        Support::Unsupported
7620    }
7621
7622    // node lifecycle
7623    fn realize(&mut self, kind: PieceKind, props: &dyn Any, id: NodeId) -> Self::Handle;
7624    fn update(
7625        &mut self,
7626        h: &Self::Handle,
7627        kind: PieceKind,
7628        patch: &dyn Any,
7629        anim: Option<&AnimSpec>,
7630    );
7631    /// Called from the turn-boundary release queue; backends may defer destruction further.
7632    fn release(&mut self, h: Self::Handle);
7633    /// Give a satellite piece a chance to drop its own per-view state, immediately before
7634    /// [`release`](Toolkit::release) frees `h` (§15.2).
7635    ///
7636    /// A backend that hosts third-party pieces implements this by looking `kind` up in its renderer
7637    /// registry and calling that piece's `release` hook. Defaulted to nothing: a backend with no
7638    /// registry has nothing to dispatch, and one that has not wired this yet leaves piece
7639    /// teardown unrun rather than failing to build.
7640    fn release_piece(&mut self, _kind: PieceKind, _h: &Self::Handle) {}
7641
7642    // tree
7643    fn insert(&mut self, parent: &Self::Handle, child: &Self::Handle, index: usize);
7644    fn remove(&mut self, parent: &Self::Handle, child: &Self::Handle);
7645    /// Put `child` at index `to` among `parent`'s native children: day's z-order resync, which
7646    /// walks the whole sibling row and asks for every position in turn. A child already at `to`
7647    /// must therefore cost nothing: a backend that re-parents unconditionally pays for the
7648    /// untouched siblings too, and where re-parenting means detach-then-add (no ViewGroup move
7649    /// primitive on Android) the detach resigns the focus of everything inside the subtree,
7650    /// which is how a text field being typed into loses the keyboard (docs/focus.md).
7651    fn move_child(&mut self, parent: &Self::Handle, child: &Self::Handle, to: usize);
7652
7653    // geometry (§7): frames are in the nearest realized native ancestor's space, in points.
7654    fn measure(&mut self, h: &Self::Handle, kind: PieceKind, p: Proposal) -> Size;
7655    /// Distance from the top of the widget's frame to its first text baseline, in points, when
7656    /// the widget is `size` (docs/baseline.md). `None` ⇒ it has no text baseline (an image, a
7657    /// slider, a bare container) and a baseline-aligned row falls back to box alignment for it.
7658    ///
7659    /// This is a measurement, not a layout mode: day places every frame itself (§7.1) and never
7660    /// hands a row to a native baseline-aligning container, so what it needs from the toolkit is
7661    /// where the text sits inside the box. Backends that cannot answer keep the default and rows
7662    /// stay centered, which is what every row did before this existed.
7663    fn first_baseline(&mut self, _h: &Self::Handle, _kind: PieceKind, _size: Size) -> Option<f64> {
7664        None
7665    }
7666    fn set_frame(&mut self, h: &Self::Handle, frame: Rect, anim: Option<&AnimSpec>);
7667
7668    // animatable visual channels (§8.4): cheap per-node opacity + transform that don't relayout.
7669    // Defaulted no-ops so backends adopt them incrementally; `anim = Some` ⇒ animate to the value
7670    // on the toolkit's own compositor, `None` ⇒ set instantly.
7671    fn set_opacity(&mut self, _h: &Self::Handle, _opacity: f64, _anim: Option<&AnimSpec>) {}
7672    fn set_transform(
7673        &mut self,
7674        _h: &Self::Handle,
7675        _t: Transform,
7676        _size: Size,
7677        _anim: Option<&AnimSpec>,
7678    ) {
7679    }
7680
7681    // text selection (docs/text.md): make this node's text user-selectable (copy/drag). Applied
7682    // once from the `.selectable()` modifier (day-pieces) to the widget it wraps (a `label`'s
7683    // native text view, most usefully). Unmanaged: Day sets it here and never patches it, so it
7684    // survives text updates. The default no-op means a backend without a selection affordance
7685    // silently leaves the text unselectable.
7686    //
7687    // Returns `Some(replacement)` when the toolkit had to rebuild the widget as a different
7688    // native class to gain a selection affordance (UIKit: `UILabel` has none, so the label
7689    // becomes a read-only `UITextView`); day-core re-points the node's handle at the
7690    // replacement, so later patches and layout reach the widget that is actually on screen.
7691    // Every property-flip backend returns `None`.
7692    fn set_selectable(&mut self, _h: &Self::Handle, _selectable: bool) -> Option<Self::Handle> {
7693        None
7694    }
7695
7696    // text entry (docs/textfield.md): how a `text_field` takes its text: hidden characters,
7697    // read-only, the keyboard and autofill purpose, the action key, the length bound. Called
7698    // once after `realize` when a field asks for anything but the defaults, and again with the
7699    // whole set whenever a reactive member changes, so the setter is idempotent.
7700    //
7701    // Returns `Some(replacement)` when hiding the characters takes a different native class
7702    // (AppKit: `NSSecureTextField`; WinUI: `PasswordBox`), the same contract as
7703    // `set_selectable`: the backend carries the text, the placeholder and its own event wiring
7704    // over, takes the old widget's place in the native tree, and day-core re-points the node's
7705    // handle. Required, with no default: a backend that left this out would show a password in
7706    // the clear. A member the toolkit has no notion of (an action key on a desktop) is ignored.
7707    fn set_input_traits(&mut self, h: &Self::Handle, traits: &InputTraits) -> Option<Self::Handle>;
7708
7709    // pointer shape (docs/cursor.md): the cursor to show while the pointer is over this node
7710    // and its descendants, from the `.cursor()` modifier. Called again whenever a reactive
7711    // cursor changes, so the setter is idempotent and cheap; `Cursor::Default` releases the
7712    // node. The default no-op is a backend with no pointer API to reach (`Cap::Cursor`
7713    // answers `Unsupported` there).
7714    fn set_cursor(&mut self, _h: &Self::Handle, _cursor: Cursor) {}
7715
7716    /// Show or hide a retained subtree, including its input and accessibility participation.
7717    /// The layout and reactive scope stay alive while hidden.
7718    fn set_presented(&mut self, _h: &Self::Handle, _visible: bool) {}
7719
7720    /// Attach overscroll delivery to a refresh host; the caller owns the mounted scope.
7721    fn attach_refresh(&mut self, _h: &Self::Handle, _host: NodeId) {}
7722
7723    // scroll (§7.6)
7724    fn set_scroll_content(&mut self, _h: &Self::Handle, _content: Size) {}
7725    // The room a classic (non-overlay) scroll bar takes out of a scroll view's content area
7726    // while the content overflows along `vertical`'s axis: its width for a vertical scroll, its
7727    // height for a horizontal one (docs/scroll.md). Day lays overflowing content out that much
7728    // narrower, so it fits beside the bar instead of reaching under it. 0 — the default — is
7729    // every backend whose bars overlay the content (AppKit, GTK, UIKit, Android, XAML, DOM).
7730    fn scroll_bar_inset(&mut self, _h: &Self::Handle, _vertical: bool) -> f64 {
7731        0.0
7732    }
7733    // The margins and minimum height the platform's own list gives a row (docs/list.md "Row
7734    // metrics"), asked of list `h` each time day-core lays a row. Day insets the row's content by
7735    // the margins and keeps it at least that tall, so a row reads at the platform's size without
7736    // the app padding it per platform. Zero — the default — leaves the row to its content.
7737    fn list_row_metrics(&mut self, _h: &Self::Handle) -> RowMetrics {
7738        RowMetrics::default()
7739    }
7740    fn scroll_to(&mut self, _h: &Self::Handle, _target: Rect, _animated: bool) {}
7741    /// Scroll a native navigation menu to its top or bottom without changing selection.
7742    /// The widget owns its content extent. Return false when the handle is unsupported.
7743    fn nav_scroll_to_edge(&mut self, _h: &Self::Handle, _bottom: bool) -> bool {
7744        false
7745    }
7746    fn scroll_offset(&mut self, _h: &Self::Handle) -> Point {
7747        Point::ZERO
7748    }
7749
7750    // events: one trampoline, node-id keyed; enqueue-only contract (§8.3).
7751    fn set_event_sink(&mut self, sink: EventSink);
7752
7753    // gestures (docs/shapes.md): attach a native recognizer for `kind` to `h`, emitting
7754    // `Event::Tap/LongPress/Drag` for `node` (enqueue-only). Default no gesture; a piece opts in
7755    // when it has a handler. Idempotent per (handle, kind).
7756    fn enable_gesture(&mut self, _h: &Self::Handle, _node: NodeId, _kind: GestureKind) {}
7757
7758    // focus (docs/focus.md): move native keyboard focus to (or away from) this control.
7759    // `focused = true` requests focus (on mobile this also raises the soft keyboard for text
7760    // inputs); `false` resigns it (dismissing the keyboard; platforms without a "focus nothing"
7761    // state resign to a focusable root). Backends report the resulting state, user- or
7762    // programmatic, with `Event::FocusChanged(bool)` through the sink; a request that cannot
7763    // be honored (unfocusable, unmounted) produces no event. The default no-op means a
7764    // backend without focus support neither moves nor reports focus.
7765    fn focus(&mut self, _h: &Self::Handle, _node: NodeId, _focused: bool) {}
7766
7767    // focusability (docs/focus.md): opt this container into the platform's focus system, the
7768    // canvas contract generalized (`Decorate::focusable`). A focusable container accepts focus,
7769    // takes it on a press (before the press reaches its gesture recognizers), reports both
7770    // directions with `Event::FocusChanged`, and delivers the non-text keys it hears while
7771    // focused as `Event::Key` for `node` (gated on `keys::handled`, like a canvas). The default
7772    // no-op means the piece renders normally but never joins the focus order: `.focused(…)`
7773    // bindings stay quiet and `.on_key(…)` never fires, the same graceful silence unfocusable
7774    // controls already have. Idempotent; only `true` is ever sent today (a piece opts in at
7775    // build, it does not opt back out).
7776    fn set_focusable(&mut self, _h: &Self::Handle, _node: NodeId, _focusable: bool) {}
7777
7778    // recycling list (docs/list.md, §10): day-core hands the `LIST` host its row-pull `source`
7779    // once, right after realize. A recycling backend stores it and calls it from its native
7780    // data-source; the default no-op means a backend without list support renders nothing.
7781    fn attach_list(&mut self, _host: &Self::Handle, _source: ListSource) {}
7782
7783    // hierarchical tree (docs/tree.md): day-core hands the `TREE` host its token-addressed
7784    // row-pull `source` once, right after realize. A backend with a native tree stores it and
7785    // answers its data-source from it; the default no-op means a backend without tree support
7786    // renders nothing (`Cap::Tree` answers `Unsupported`, and apps gate on that).
7787    fn attach_tree(&mut self, _host: &Self::Handle, _source: TreeSource) {}
7788
7789    // routes (docs/navigation.md): day-core reports the app's current route path here whenever
7790    // it changes ("" = everything at its root), so a backend with a native notion of location
7791    // can mirror it: web-dom writes the URL hash (`#controls`), and browser back/forward or a
7792    // hand-edited hash comes back as `Event::RouteRequested`. Default no-op: most toolkits
7793    // have nowhere to put a route.
7794    fn set_route(&mut self, _route: &str) {}
7795
7796    // undo bridge (docs/model.md): mirror the app's undo stack into the platform's own undo
7797    // objects, so the stock Edit menu retitles and enables itself and the platform's gestures
7798    // land: the native front of one Day-owned history. The state flows down whenever it
7799    // changes; the user's invocation comes back up as `Event::Undo`. Default no-op: a backend
7800    // without a native undo system answers `Cap::UndoBridge` `Unsupported`, and the app's own
7801    // affordances (menu items, buttons, accelerators) drive the stack instead.
7802    fn set_undo_state(&mut self, _state: &UndoState) {}
7803
7804    // edit bridge (docs/menus.md): mirror what the app's standard-edit handlers can do, so
7805    // the platform's own menu validation enables Cut/Copy/Paste exactly as it does for text
7806    // widgets; invocations come back up as `Event::Edit`. Default no-op: a backend without
7807    // a native edit-command route answers `Cap::EditBridge` accordingly.
7808    fn set_edit_state(&mut self, _state: &EditState) {}
7809
7810    // ambient modifiers (docs/menus.md): the keyboard modifiers held right now, for
7811    // interactions whose meaning they change (shift-click multi-select). Pull-based: the
7812    // platforms expose exactly this query (NSEvent.modifierFlags, the shim's tracked mask).
7813    // Touch-only backends keep the all-false default.
7814    fn modifiers(&mut self) -> Modifiers {
7815        Modifiers::default()
7816    }
7817
7818    // Dynamic context menu (docs/menus.md): the menu is built when it is summoned. The provider
7819    // is called synchronously from the platform's own menu callback (UI thread, outside any
7820    // day-core borrow) with the location in the node's local coordinates, and its result is
7821    // shown. The static `set_context_menu` below stays the simple path; this one exists for
7822    // surfaces whose menu depends on what is under the pointer (a canvas selection,
7823    // docs/tree.md). Default no-op: a backend without the affordance shows nothing.
7824    fn set_drag_source(&mut self, _h: &Self::Handle, _source: transfer::Source) {}
7825    fn set_drop_target(&mut self, _h: &Self::Handle, _target: transfer::Target) {}
7826
7827    fn set_context_menu_fn(&mut self, _h: &Self::Handle, _node: NodeId, _f: ContextMenuFn) {}
7828
7829    // menus (§ menus): render `items` with the backend's native menu affordance, firing
7830    // `Event::MenuAction(id)` (enqueue-only) for each id'd item; `role` items use the native standard
7831    // command. Default no-op: a toolkit without a menu bar / context menu shows nothing.
7832    /// The application menu (macOS/Windows/Linux menu bar; the app-bar overflow on Android; the
7833    /// UIMenuBuilder main menu on iPadOS/Catalyst). Replaces any previous app menu.
7834    fn set_app_menu(&mut self, _items: &[MenuItem]) {}
7835    /// A context menu for `h`, shown on secondary-click (desktop) or long-press (mobile). Passing an
7836    /// empty slice removes it.
7837    fn set_context_menu(&mut self, _h: &Self::Handle, _node: NodeId, _items: &[MenuItem]) {}
7838
7839    // toolbars (docs/toolbars.md): a window's native toolbar: NSToolbar, AdwHeaderBar, QToolBar,
7840    // CommandBar. `h` is the window root's handle (the same handle `open_window` returned, or the
7841    // primary root's); the backend walks from it to the window it belongs to. Default no-op: a
7842    // toolkit with no toolbar shows nothing rather than a drawn imitation, and reports
7843    // `Cap::Toolbar` as `Unsupported` so an app can put the command somewhere else.
7844    /// Edit the window's toolbar (docs/toolbars.md): the [`ToolbarOp`]s, removals first, then
7845    /// insertions in ascending position. The bar starts empty, and becomes empty again when every
7846    /// item has been removed, at which point the backend takes it off the window.
7847    ///
7848    /// An item no op names must keep its native widget untouched, which is what keeps a search
7849    /// field focused while the page around it changes. Day sends an edit only when the bar
7850    /// changed, at most once per turn, and an item keeps its [`ToolbarItem::action`] for as long
7851    /// as its window shows an item with that id, so a native item's handler never needs
7852    /// repointing. Keep a [`ToolbarMirror`] and place each new item after
7853    /// [`ToolbarMirror::prev_where`] its group.
7854    ///
7855    /// Returns whether the edit was applied. `false` (the window has no bar to edit yet) makes
7856    /// Day send the whole bar again at the next change rather than assume this one landed.
7857    fn edit_toolbar(&mut self, _h: &Self::Handle, _ops: &[ToolbarOp]) -> bool {
7858        true
7859    }
7860    /// Apply a targeted change to one live toolbar item, the path a bound signal writes through,
7861    /// so syncing a search field does not rebuild the bar. No-op if the item is not present.
7862    fn update_toolbar(&mut self, _h: &Self::Handle, _patch: &ToolbarPatch) {}
7863
7864    // lifecycle (docs/lifecycle.md): does this backend deliver `phase`? The default answers "yes" for
7865    // the universal phases (launch/activation/termination) and "no" for the mobile-only ones. Backends
7866    // that wire up more (the mobile ones) override this; it must agree with the crate's
7867    // `const fn lifecycle_supported`, which drives compile-time guards in `day::require_lifecycle!`.
7868    fn supports_lifecycle(&self, phase: Lifecycle) -> bool {
7869        phase.is_universal()
7870    }
7871
7872    // pillars
7873    /// Apply a node's accessibility annotations (docs/accessibility.md): the label, hint and
7874    /// value the screen reader speaks, an explicit role, whether the node is hidden from
7875    /// assistive technology, and the automation identifier. Called with the node's whole
7876    /// accumulated set each time any of it changes, so every member is written on every call.
7877    /// Only an explicit role is applied: a native control reports its own.
7878    fn set_a11y(&mut self, _h: &Self::Handle, _a11y: &A11yProps) {}
7879    /// Speak `text` through the screen reader without moving its focus (docs/accessibility.md;
7880    /// probe [`Cap::Announce`]). `urgent` interrupts what is being read; otherwise the sentence
7881    /// waits its turn. Nothing happens when no screen reader is running. The default is a
7882    /// backend that reaches no announcement API.
7883    fn announce(&mut self, _text: &str, _urgent: bool) {}
7884    /// Read a widget's native state back from the platform for `a11y_audit` and
7885    /// `assert_native` (§14.2, docs/testing.md) to diff against Day's expectation. Default:
7886    /// nothing read; the audit skips the node and `assert_native` records each field as unread.
7887    fn read_native(&self, _h: &Self::Handle) -> NativeSnapshot {
7888        NativeSnapshot::default()
7889    }
7890    fn replay(&mut self, _h: &Self::Handle, _ops: &[DrawOp], _size: Size) {}
7891
7892    /// Every family this toolkit can draw canvas text in, with the faces each ships
7893    /// (docs/fonts.md; probe [`Cap::FontList`]). Default: none. `day::font_families` calls
7894    /// this once per process and caches the answer: enumeration is slow on every platform
7895    /// (fontconfig, a DirectWrite collection, an XML parse on Android) and the set does not
7896    /// change under a running app.
7897    fn font_families(&mut self) -> Vec<FontFamilyInfo> {
7898        Vec::new()
7899    }
7900
7901    /// Measure one line of canvas text at `size` points in `font`, in the same engine
7902    /// [`Toolkit::replay`] draws [`DrawOp::Text`] with, so a `TextAnchor::LEADING` anchor plus
7903    /// the returned `ascent` lands on the drawn baseline. `None` = cannot measure; the facade
7904    /// then answers [`TextMetrics::approximate`].
7905    fn measure_text(&mut self, _text: &str, _size: f64, _font: &CanvasFont) -> Option<TextMetrics> {
7906        None
7907    }
7908    // --- raster images (docs/images.md) -------------------------------------------------
7909    //
7910    // Request-id shaped rather than blocking, because one backend can never answer
7911    // synchronously: a browser decodes through `createImageBitmap`, which is a promise. Every
7912    // other backend decodes inline and raises the completion before returning, so the shape
7913    // costs them nothing but a line, and the app-facing API can be one thing everywhere
7914    // instead of two (docs/async.md rule 3: a callback and a future, never a runtime).
7915
7916    /// Decode encoded image bytes (PNG/JPEG/…) into a native image, answering `req` with
7917    /// [`Event::ImageDecoded`].
7918    ///
7919    /// The id in that event is minted by the caller (day-core), not the backend: the backend
7920    /// keeps its own side table from that id to whatever it decoded.
7921    ///
7922    /// The default does nothing because a default body cannot reach the event sink
7923    /// (it is installed per backend by [`Toolkit::set_event_sink`], not reachable through this
7924    /// trait), so there is no way for it to answer. day-core asks [`Cap::ImageDecode`] first and
7925    /// resolves the request as [`ImageError::Unsupported`] itself, which is why a backend with
7926    /// no decoder needs no code here at all.
7927    fn decode_image(&mut self, _req: u64, _id: BitmapId, _bytes: &[u8]) {}
7928
7929    /// What a decoded image is: pixel size, scale, format, alpha ([`BitmapInfo`]).
7930    ///
7931    /// Synchronous: every backend that decoded the image already holds these facts. `None` means
7932    /// the id names nothing live.
7933    fn image_info(&mut self, _id: BitmapId) -> Option<BitmapInfo> {
7934        None
7935    }
7936
7937    /// The metadata beyond the pixels: EXIF orientation, DPI, capture time
7938    /// ([`ImageProperties`], probe [`Cap::ImageProperties`]). `None` where the backend has no
7939    /// metadata reader, which is most of them.
7940    fn image_properties(&mut self, _id: BitmapId) -> Option<ImageProperties> {
7941        None
7942    }
7943
7944    /// Encode a decoded image back to bytes per `spec`, answering `req` with
7945    /// [`Event::ImageEncoded`]. A format outside [`Self::encode_formats`] answers
7946    /// [`ImageError::Encode`] rather than silently substituting another one.
7947    ///
7948    /// Defaulted to nothing for the same reason as [`Self::decode_image`]: day-core probes
7949    /// [`Cap::ImageEncode`] and answers `Unsupported` without ever calling this.
7950    fn encode_image(&mut self, _req: u64, _id: BitmapId, _spec: &EncodeSpec) {}
7951
7952    /// Which formats [`Self::encode_image`] can write, the [`Cap::ImageEncode`]
7953    /// counterpart of [`Self::font_families`]/[`Cap::FontList`]. Empty by default.
7954    fn encode_formats(&mut self) -> Vec<ImageFormat> {
7955        Vec::new()
7956    }
7957
7958    /// Drop a decoded image and everything the backend cached for it. Called when the app's
7959    /// last handle to it goes away; an id the backend never saw is a no-op.
7960    fn release_image(&mut self, _id: BitmapId) {}
7961
7962    // --- canvas export (docs/canvas.md "Exporting") --------------------------------------
7963    //
7964    // Request-id shaped like the image duties above, for the same reason: the browser's
7965    // `createImageBitmap` is a promise, and a native toolkit may paint on another thread. A
7966    // backend may also answer inline, before returning. day-core validates sizes, enforces
7967    // the pixel limits and probes the caps first, so a backend sees only requests it can
7968    // attempt.
7969
7970    /// Replay `ops` into a new offscreen bitmap of `size` points at `scale` pixels per point
7971    /// ([`export_pixels`] gives the pixel size), with a transparent background and the
7972    /// canvas's top-left origin. Store it under `id` in the same table [`Self::decode_image`]
7973    /// fills, so `image_info`, `encode_image`, `release_image`, the `image` piece and
7974    /// [`DrawOp::Image`] all take it, then answer `req` with [`Event::BitmapRendered`] (its
7975    /// [`BitmapInfo::scale`] is `scale`).
7976    ///
7977    /// The painter must be the one [`Self::replay`] uses, so text, gradients, clips and stamps
7978    /// match the screen. Where the platform's 2-D API draws into a memory surface from any
7979    /// thread, the paint runs on a thread of [`offscreen`] and the answer is posted back, so
7980    /// a long replay never stalls the UI; the toolkit resolves on the UI thread, before it
7981    /// hands the job over, everything the painter would otherwise read from UI-thread state
7982    /// (the decoded images the ops reference, the fonts their text runs need). The contract
7983    /// holds either way: one answer per request, carrying that request's `req`, raised on the
7984    /// UI thread, and the bitmap in the table before it. Defaulted to nothing: day-core probes
7985    /// [`Cap::CanvasBitmap`] and answers [`ExportError::Unsupported`] itself.
7986    fn render_bitmap(
7987        &mut self,
7988        _req: u64,
7989        _id: BitmapId,
7990        _ops: &[DrawOp],
7991        _size: Size,
7992        _scale: f64,
7993    ) {
7994    }
7995
7996    /// Replay each page into one PDF document and answer `req` with [`Event::PdfRendered`].
7997    /// Units are PDF points, top-left origin; shapes and text stay vector, and images embed at
7998    /// their pixel size. `pages` is never empty. Defaulted to nothing: day-core probes
7999    /// [`Cap::CanvasPdf`] first.
8000    fn render_pdf(&mut self, _req: u64, _pages: &[PdfPage], _info: &PdfInfo) {}
8001
8002    fn snapshot_window(&mut self) -> Result<Vec<u8>, String> {
8003        Err("snapshot unsupported".into())
8004    }
8005    /// Where `root`, the primary window's root container, sits in [`Self::snapshot_window`]'s
8006    /// image, in points from its top-left. A reader of the capture (dayscript `sample_pixel`)
8007    /// maps Day's frames into it with this; it matters where the capture spans more than Day's
8008    /// content on more than one side, as Android's edge-to-edge content does (status bar
8009    /// above, navigation bar below).
8010    ///
8011    /// Defaulted to `None`, which the reader takes as "any rows beyond Day's content are
8012    /// above it", true where the only extra area is a title bar.
8013    fn snapshot_origin(&mut self, _root: &Self::Handle) -> Option<Point> {
8014        None
8015    }
8016    /// Establish a fresh screenshot checkpoint after reactive work and native transitions.
8017    /// `revision` is stable across retries and unique to the request; `host` selects a
8018    /// secondary window, or None for the primary. Never block the UI thread waiting for
8019    /// a frame. Pending requests are retried within the dayscript deadline.
8020    ///
8021    /// Ready means the platform render checkpoint completed, not that a vsync callback
8022    /// proves pixels were displayed. OnCapture delegates freshness to snapshot_window.
8023    fn prepare_snapshot(
8024        &mut self,
8025        _host: Option<&Self::Handle>,
8026        _revision: u32,
8027    ) -> Result<capture::Readiness, String> {
8028        // Compatible with external toolkits predating this hook: their synchronous
8029        // snapshot owns freshness, and no external-capture acknowledgment is fabricated.
8030        Ok(capture::Readiness::OnCapture)
8031    }
8032
8033    /// The same capture with the window's own chrome: title bar, toolbar, whatever the platform
8034    /// draws around the content (docs/window-image.md).
8035    ///
8036    /// Defaulted to [`Self::snapshot_window`]: a backend that cannot separate the two
8037    /// (or has no chrome to speak of, a phone) answers with the content shot rather than an
8038    /// error, so an app asking for chrome degrades to "what there was" instead of failing. The
8039    /// dayscript `screenshot` step never calls this, which is what keeps every captured gallery
8040    /// baseline byte-identical to before it existed.
8041    fn snapshot_window_chrome(&mut self) -> Result<Vec<u8>, String> {
8042        self.snapshot_window()
8043    }
8044    /// Show/hide the sidebar pane of the navigation host `host`, which is what the sidebar
8045    /// affordance a `nav(Sidebar)` contributes for itself drives ([`SIDEBAR_TOGGLE_ID`]).
8046    /// `false` when `host` has no pane to toggle (a stack, a tab bar, no sidebar concept at all).
8047    ///
8048    /// Per host, not per process: a second window's button collapses that window's sidebar
8049    /// and not the first's. The item's own action makes the call, and dayscript's `toolbar:`
8050    /// step presses the item like any other, so a walkthrough drives exactly the path a click
8051    /// takes. Defaulted, so a backend with no sidebar needs no code. docs/toolbars.md,
8052    /// docs/navigation.md.
8053    fn toggle_sidebar(&mut self, _host: &Self::Handle) -> bool {
8054        false
8055    }
8056    /// Press the platform's own back affordance (the navigation bar's back button on iOS,
8057    /// the system back on Android) on the innermost navigation host that has something to
8058    /// pop. What `nav_back()` does not do: that is Day's rail, which pops the model and lets the
8059    /// backend follow, while this runs the native path first (the bar's `shouldPop`, the
8060    /// dispatcher's callbacks, the pop itself) and lets the backend report it to Day as a user
8061    /// back, guard and all. dayscript's `nav_back: { native: true }` drives it, so a walkthrough
8062    /// can cover the code that a real tap runs and Day's rail never reaches. `false` when this
8063    /// toolkit has no native back or nothing is popped by it. Defaulted, so a desktop needs no
8064    /// code. docs/navigation.md.
8065    fn native_back(&mut self) -> bool {
8066        false
8067    }
8068    /// Whether the UI has settled, with no native transition (modal present/dismiss, nav push)
8069    /// still animating. The dayscript `screenshot` step polls this before capturing so shots
8070    /// never catch a half-faded dialog or half-pushed page. Backends without async
8071    /// transitions (or without a way to know) report `true`.
8072    fn ui_idle(&mut self) -> bool {
8073        true
8074    }
8075
8076    // imperative presentation (docs/dialogs.md): show a native modal for request `req`;
8077    // the backend answers by enqueuing `Event::PresentResult { req, .. }`. `dismiss` is
8078    // used only when Day resolves programmatically (dayscript) while the modal is still up.
8079    fn present(&mut self, _req: u64, _spec: &present::PresentSpec) {}
8080    fn dismiss(&mut self, _req: u64) {}
8081
8082    /// Open `url` in the platform's default handler: the system browser for `http(s)`, the mail
8083    /// client for `mailto:`, etc. Backs the [`link`](/api/day_pieces/fn.link.html) piece. Fire and
8084    /// forget: there is no result, and an unopenable URL is ignored. The default no-ops so a
8085    /// backend that hasn't wired it up still compiles.
8086    fn open_url(&mut self, _url: &str) {}
8087
8088    /// Whether a native share chooser is available. Does not probe installed share targets.
8089    fn share_support(&self) -> Support {
8090        Support::Unsupported
8091    }
8092    /// Present the system share chooser. True means presentation started, not that sharing
8093    /// completed. Never sends data without the user's choice of a target.
8094    fn share_url(&mut self, _url: &str, _title: &str) -> bool {
8095        false
8096    }
8097
8098    /// Read current OS associations. Unsupported platforms must not fabricate a default.
8099    fn application_handlers(
8100        &mut self,
8101        _query: &applications::HandlerQuery,
8102    ) -> Result<applications::ApplicationHandlers, applications::ApplicationError> {
8103        Err(applications::ApplicationError::Unsupported)
8104    }
8105
8106    /// Open with an opaque application identifier returned by `application_handlers`.
8107    fn open_url_with_application(
8108        &mut self,
8109        _url: &str,
8110        _application: &str,
8111        completion: applications::OpenApplicationCompletion,
8112    ) {
8113        completion(Err(applications::ApplicationError::Unsupported));
8114    }
8115
8116    /// Ask the OS to require a second swipe for its edge gestures on `edges` (docs/cover.md):
8117    /// the union requested by every mounted `defers_system_gestures` modifier, re-sent whenever
8118    /// that set changes (`Edges::NONE` when the last one unmounts). iOS defers the home
8119    /// indicator / notification edges; Android enters swipe-to-reveal immersive mode while
8120    /// non-empty. The default no-ops (desktop has no system edge gestures).
8121    fn defer_system_gestures(&mut self, _edges: Edges) {}
8122
8123    /// Hide (`true`) or show the system status bar (docs/cover.md): whether any mounted
8124    /// `status_bar_hidden` modifier currently asks for it hidden, re-sent whenever that answer
8125    /// may have changed (`false` when the last request unmounts). iOS answers the root and
8126    /// cover view controllers' `prefersStatusBarHidden`; Android and HarmonyOS hide the status
8127    /// bar through their window inset controls. The default no-ops (desktop and web have no
8128    /// status bar); report `Cap::StatusBarHidden` alongside an implementation.
8129    fn set_status_bar_hidden(&mut self, _hidden: bool) {}
8130
8131    /// Whether the platform is rendering in dark appearance right now. Apps painting
8132    /// custom surfaces (opaque overlay panels, scrims) branch on this so their fills track
8133    /// the theme the default text colors already follow; hardcoding either theme's
8134    /// surface produces dark-on-dark or light-on-light text on the other. Queried at
8135    /// build time (a piece rebuilt after a theme change re-queries). The default honors a
8136    /// `DAY_THEME` launch override and otherwise answers light.
8137    /// Resolve a semantic color for custom artwork. Backends with native palette access
8138    /// override this; the default follows light/dark appearance using Day's fixed palette.
8139    fn system_color(&mut self, role: SystemColor) -> Color {
8140        role.fallback(self.dark_mode())
8141    }
8142
8143    fn dark_mode(&mut self) -> bool {
8144        std::env::var("DAY_THEME").ok().as_deref() == Some("dark")
8145    }
8146    /// Whether the user asked the system for less motion (docs/accessibility.md; probe
8147    /// [`Cap::ReduceMotion`]): macOS and iOS "Reduce Motion", Android "Remove animations" (an
8148    /// animator duration scale of zero), GTK's `gtk-enable-animations` off, Windows "Show
8149    /// animations" off, the web's `prefers-reduced-motion`. Read at launch; a backend that
8150    /// watches the setting calls `day_core::note_motion_changed` when it flips. Day then applies
8151    /// every finite animation at its destination and keeps only indeterminate motion. The default
8152    /// is a backend that reads no such setting.
8153    fn reduce_motion(&mut self) -> bool {
8154        false
8155    }
8156
8157    /// App-level appearance override: `Some(true)` forces dark, `Some(false)` forces light,
8158    /// `None` returns to following the system. Backends restyle their native widgets in
8159    /// place and answer the override from [`dark_mode`](Self::dark_mode); app-painted
8160    /// surfaces pick it up on their next rebuild. `Cap::Appearance` reports whether the
8161    /// backend honors this; the default ignores the call.
8162    fn set_appearance(&mut self, _dark: Option<bool>) {}
8163
8164    /// Put `badge` on the app's icon in the Dock / launcher / home screen (docs/badge.md).
8165    ///
8166    /// Fire-and-forget, like `set_appearance`: a payload this toolkit cannot render is ignored, and
8167    /// the app probes `Cap::AppBadge{Count,Text,Dot}` before choosing one. Never substitute: a
8168    /// backend that turned `Text("beta")` into `Count(1)` would put a wrong number on a user's
8169    /// icon, which is worse than showing nothing. The default ignores every call.
8170    fn set_app_badge(&mut self, _badge: &AppBadge) {}
8171
8172    // app lifecycle (mobile; desktop backends no-op)
8173    fn on_suspend(&mut self) {}
8174    fn on_resume(&mut self) {}
8175    fn on_memory_warning(&mut self) {}
8176
8177    // adoption of foreign native handles (polyglot pieces, §15.3)
8178    fn adopt(&mut self, _raw: RawHandle) -> Self::Handle {
8179        unimplemented!("this toolkit does not adopt foreign handles yet")
8180    }
8181
8182    // secondary windows (docs/windows.md)
8183
8184    /// Open a native OS window per `options` + `kind`: create and show the window, wire its
8185    /// events to `id` (`WindowResized` with the content size in points, `WindowClosed` after
8186    /// the native close, `WindowFocused` on key/active changes), and answer with its content
8187    /// container handle, the same contract as the `ready` root container. Backends whose
8188    /// window creation is asynchronous (a scene, an activity, an ability) answer
8189    /// [`WindowOpenReply::Pending`] and complete later through
8190    /// `day_core::finish_window_open(id, raw, size)`, which goes through [`Toolkit::adopt`].
8191    /// The default answers `Unsupported`; day-core then presents the content as a
8192    /// fullscreen cover in the primary window instead.
8193    fn open_window(
8194        &mut self,
8195        _id: NodeId,
8196        _options: &WindowOptions,
8197        _kind: WindowKind,
8198    ) -> WindowOpenReply<Self::Handle> {
8199        WindowOpenReply::Unsupported
8200    }
8201
8202    /// Close the native window whose content container is `host` (a handle `open_window`
8203    /// produced). Asynchronous: the platform confirms with `Event::WindowClosed` on the
8204    /// window's root node, and only then does day-core tear the subtree down. Idempotent; unknown
8205    /// hosts are ignored. Never called with the primary window's container.
8206    fn close_window(&mut self, _host: &Self::Handle) {}
8207
8208    /// End the application: the last window with [`WindowRole::Primary`] has closed
8209    /// (docs/windows.md). day-core decides when, since it owns the window registry and the role
8210    /// each window carries; the backend supplies only the platform's exit:
8211    /// `NSApplication.terminate`, `QCoreApplication::quit`, `GtkApplication.quit`,
8212    /// `PostQuitMessage`. Everything day-core wanted to happen first (secondary windows
8213    /// disposed, `WillTerminate` delivered) already has by the time this is called.
8214    ///
8215    /// The default does nothing, which is right for the backends whose process lifetime is
8216    /// not theirs to end: a browser tab, an Android activity, an iOS scene.
8217    fn quit_app(&mut self) {}
8218
8219    /// Bring the window whose content container is `host` to front and make it key/active:
8220    /// the focus half of open-or-focus singleton windows. Default no-op.
8221    fn focus_window(&mut self, _host: &Self::Handle) {}
8222
8223    /// Retitle the window whose content container is `host`. Default no-op.
8224    fn set_window_title(&mut self, _host: &Self::Handle, _title: &str) {}
8225
8226    /// Resize the window whose content container is `host` to fit `size` of content, and pin it
8227    /// there: what `WindowOptions::size_to_fit` asks for (docs/windows.md).
8228    ///
8229    /// `size` is the content size Day measured, not the window's outer frame: the backend adds
8230    /// its chrome. A settings panel is the case this exists for, and every desktop platform
8231    /// sizes one to its content rather than to a number the app guessed; a fixed height either
8232    /// clips the last row or leaves a band of empty panel under it, and which one you get depends
8233    /// on the user's text size.
8234    ///
8235    /// Default no-op, so a toolkit that cannot resize a live window keeps the size it was
8236    /// opened at, which is what every backend did before this existed.
8237    fn fit_window(&mut self, _host: &Self::Handle, _size: Size) {}
8238
8239    /// Snapshot the window whose content container is `host` (the dayscript `screenshot`
8240    /// step's `window:` target). The default answers the primary snapshot, so backends that
8241    /// never open windows stay correct without changes.
8242    fn snapshot_window_of(&mut self, _host: &Self::Handle) -> Result<Vec<u8>, String> {
8243        self.snapshot_window()
8244    }
8245
8246    /// Apply one property change to the window whose content container is `host`
8247    /// (docs/windows.md "Window properties"). The primary window arrives with its root container,
8248    /// like [`set_window_title`](Self::set_window_title).
8249    ///
8250    /// Fire-and-forget, like [`set_app_badge`](Self::set_app_badge): a change this toolkit cannot
8251    /// make is ignored, and the app probes the matching `Cap` (named on each [`WindowChange`]
8252    /// variant) before relying on it. A change the platform completes later (a fullscreen
8253    /// transition, a zoom animation) reports its outcome through
8254    /// [`Event::WindowStateChanged`], never by assuming the request took. The default ignores
8255    /// every change.
8256    fn apply_window(&mut self, _host: &Self::Handle, _change: &WindowChange) {}
8257
8258    /// True OS window groups, as distinct from native tab widgets.
8259    fn native_window_tabs(&self) -> bool {
8260        false
8261    }
8262    /// Native in-window document/section tab control; OS grouping is reported separately.
8263    fn native_document_tabs(&self) -> bool {
8264        false
8265    }
8266    /// Join/reorder these windows in an OS tab group. Content remains window-owned.
8267    fn group_windows(&mut self, _hosts: &[Self::Handle]) {}
8268    /// Current native order of the group containing this window, including detached groups.
8269    fn window_tab_order(&self, _host: &Self::Handle) -> Vec<NodeId> {
8270        Vec::new()
8271    }
8272
8273    /// Install the app's Dock menu (docs/menus.md "Dock menu"): the items macOS shows above
8274    /// its own when the user right-clicks the app's Dock icon, built from the app's
8275    /// `[[shortcuts]]` and its `dock_menu(..)` entries. Same item model and dispatch as
8276    /// [`set_app_menu`](Self::set_app_menu); an empty slice removes the menu. `Cap::DockMenu`
8277    /// reports support; the default ignores the call.
8278    fn set_dock_menu(&mut self, _items: &[MenuItem]) {}
8279
8280    /// Make the node at `h` move its window when the user drags it, as a title bar does
8281    /// (`.window_drag_region()`, docs/window-chrome.md): the region's own background starts a
8282    /// native window drag (with the platform's snapping and edge tiling), a double click does
8283    /// what the user's title-bar double-click setting says, and controls inside the region keep
8284    /// receiving their own clicks. `false` releases it. `Cap::DragRegion`; the default ignores
8285    /// the call, so on a phone the region is an ordinary view.
8286    fn set_drag_region(&mut self, _h: &Self::Handle, _drag: bool) {}
8287
8288    /// Show these status items, replacing the previous set (docs/status-item.md): add the
8289    /// ones whose `id` is new, update the ones that changed, remove the ones no longer listed.
8290    /// A click on an item runs its `activate` action or opens its menu; menu choices dispatch
8291    /// [`Event::MenuAction`] like the app menu's. `Cap::StatusItem`; the default ignores the
8292    /// call, which is what a phone and the web do.
8293    fn set_status_items(&mut self, _items: &[StatusItemSpec]) {}
8294
8295    /// Show `progress` on the app's Dock or taskbar icon (docs/status-item.md).
8296    /// `Cap::AppProgress`; the default ignores it.
8297    fn set_app_progress(&mut self, _progress: AppProgress) {}
8298
8299    /// Show or hide the app's Dock icon while it runs: a menu-bar app hides it and lives in its
8300    /// status item (macOS activation policy). `Cap::DockVisibility`; the default ignores it.
8301    fn set_dock_visible(&mut self, _visible: bool) {}
8302
8303    /// Keep the process running when its last window closes (docs/windows.md "Keeping the app
8304    /// running"). When `true`, the backend must not end the app on its own as windows close: it
8305    /// reports every close, the first window's included, as `Event::WindowClosed`, and day-core
8306    /// decides whether to call [`quit_app`](Self::quit_app). When `false`, the backend keeps its
8307    /// platform's own rule. A backend whose process lifetime is not its own (a phone, a browser
8308    /// tab) ignores it, which is the default.
8309    fn set_keep_running(&mut self, _keep: bool) {}
8310
8311    /// The displays attached now (docs/windows.md "Monitors"). `Cap::Monitors`; the default
8312    /// answers none, and day-core then describes the primary window's own size as one display.
8313    fn monitors(&self) -> Vec<Monitor> {
8314        Vec::new()
8315    }
8316
8317    /// The outer frame of the window whose content container is `host`, in points on the
8318    /// desktop's coordinate space (top-left origin), or `None` where the platform does not say
8319    /// (a phone, Wayland's positions). Read when the app asks for it and when day-core saves a
8320    /// remembered frame (`WindowOptions::remember_frame`).
8321    fn window_frame(&self, _host: &Self::Handle) -> Option<Rect> {
8322        None
8323    }
8324
8325    /// Replace the launcher shortcuts the app set while running (docs/deep-links.md "Launcher
8326    /// shortcuts"), shown beside the ones Day.toml declares: iOS Home Screen quick actions,
8327    /// Android dynamic shortcuts, the macOS Dock menu. Each opens its route through the deep-link
8328    /// intake. `Cap::DynamicShortcuts`; the default ignores the call.
8329    fn set_launcher_shortcuts(&mut self, _shortcuts: &[LauncherShortcut]) {}
8330}
8331
8332/// What a secondary window is, so backends can apply platform conventions (docs/windows.md).
8333#[derive(Clone, Copy, PartialEq, Eq, Debug)]
8334pub enum WindowKind {
8335    /// A regular document/tool window: resizable, miniaturizable, platform-default tabbing.
8336    Normal,
8337    /// A settings/preferences window: singleton by convention; macOS disallows window
8338    /// tabbing and drops the resize/minimize chrome, mobile presents it modally. Pairs with
8339    /// day-core's key-singleton reopen (`open_window` with a key).
8340    Preferences,
8341    /// The About window (docs/settings.md): the same fixed, centered, untabbed panel chrome
8342    /// as [`Self::Preferences`] (every desktop treats the two alike), presented modally on
8343    /// mobile. Singleton under day-core's `day.about` key.
8344    About,
8345}
8346
8347impl WindowKind {
8348    /// Whether this is a panel (settings or About) rather than a document window: the kinds
8349    /// every desktop draws fixed-size, centered and out of the Window menu, and mobile presents
8350    /// as a cover.
8351    pub fn is_panel(self) -> bool {
8352        !matches!(self, WindowKind::Normal)
8353    }
8354}
8355
8356/// Whether a window keeps the app alive (docs/windows.md close policy).
8357///
8358/// A separate axis from [`WindowKind`], which describes chrome. They correlate (a
8359/// preferences panel is the archetypal window that should not hold an app open), but they are
8360/// not the same question, and conflating them would leave no way to say "an ordinary-looking
8361/// tool window that shouldn't outlive the documents".
8362///
8363/// Note the word "secondary" is overloaded around windows: elsewhere in day it means "a window
8364/// other than the first one opened". Here it means "does not keep the app alive", which is
8365/// about lifetime, not about order of creation.
8366#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
8367pub enum WindowRole {
8368    /// Closing the last one of these ends the app.
8369    #[default]
8370    Primary,
8371    /// Never keeps the app alive: when the last `Primary` closes, the app exits and takes
8372    /// these with it, however many are open.
8373    Secondary,
8374}
8375
8376impl From<WindowKind> for WindowRole {
8377    /// The default pairing: an ordinary window holds the app open, a preferences panel does
8378    /// not. An app that needs a different answer sets the role itself.
8379    fn from(kind: WindowKind) -> WindowRole {
8380        match kind {
8381            WindowKind::Normal => WindowRole::Primary,
8382            WindowKind::Preferences | WindowKind::About => WindowRole::Secondary,
8383        }
8384    }
8385}
8386
8387/// A backend's answer to [`Toolkit::open_window`] (docs/windows.md).
8388pub enum WindowOpenReply<H> {
8389    /// The window exists now; here is its content container (desktop backends).
8390    Open(H),
8391    /// Native creation started but completes asynchronously (a scene, an activity, an
8392    /// ability); the backend will call `day_core::finish_window_open` when the content
8393    /// container exists. day-core parks the window record until then.
8394    Pending,
8395    /// This toolkit cannot open windows (`Cap::MultiWindow` = `Unsupported`); day-core
8396    /// falls back to presenting the content as a fullscreen cover in the primary window.
8397    Unsupported,
8398}
8399
8400/// How a window is shown (docs/windows.md "Window properties"): what the window's `state()`
8401/// signal holds and what [`WindowChange::State`] asks for.
8402#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
8403pub enum WindowState {
8404    /// On screen at its own size: neither minimized, maximized nor fullscreen.
8405    #[default]
8406    Normal,
8407    /// Minimized to the Dock, taskbar or shelf. `Cap::WindowStates`.
8408    Minimized,
8409    /// Zoomed to fill the screen's work area, keeping its chrome. `Cap::WindowStates`.
8410    Maximized,
8411    /// Covering the whole screen with no window chrome; on a phone, the system bars hidden.
8412    /// `Cap::WindowFullscreen`.
8413    Fullscreen,
8414}
8415
8416impl WindowState {
8417    /// The wire code of [`bridge::BridgeKind::WindowStateChanged`].
8418    pub const fn code(self) -> i32 {
8419        match self {
8420            WindowState::Normal => 0,
8421            WindowState::Minimized => 1,
8422            WindowState::Maximized => 2,
8423            WindowState::Fullscreen => 3,
8424        }
8425    }
8426
8427    /// The state a wire code names; an unknown code reads as `Normal`.
8428    pub const fn from_code(code: i32) -> WindowState {
8429        match code {
8430            1 => WindowState::Minimized,
8431            2 => WindowState::Maximized,
8432            3 => WindowState::Fullscreen,
8433            _ => WindowState::Normal,
8434        }
8435    }
8436}
8437
8438/// How a window stacks against other apps' windows ([`WindowChange::Level`], `Cap::WindowLevel`).
8439#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
8440pub enum WindowLevel {
8441    /// Ordinary stacking: the focused app's windows come forward.
8442    #[default]
8443    Normal,
8444    /// Stays above other apps' ordinary windows: a palette, a timer, a video peek.
8445    Floating,
8446}
8447
8448/// How strongly a window asks for the user's attention ([`WindowChange::RequestAttention`]).
8449#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
8450pub enum Attention {
8451    /// Once: one Dock bounce, a taskbar button that flashes a few times.
8452    #[default]
8453    Informational,
8454    /// Until the user switches to the app.
8455    Critical,
8456}
8457
8458/// One change to one window (docs/windows.md "Window properties"), carried by
8459/// [`Toolkit::apply_window`]. Each variant names the `Cap` that reports whether the running
8460/// toolkit makes it.
8461#[derive(Clone, Debug, PartialEq)]
8462pub enum WindowChange {
8463    /// Minimize, zoom, take fullscreen, or return to normal. `Cap::WindowStates` for the
8464    /// first two, `Cap::WindowFullscreen` for fullscreen. The outcome comes back as
8465    /// [`Event::WindowStateChanged`].
8466    State(WindowState),
8467    /// Keep the window's content out of screenshots, recordings and screen sharing.
8468    /// `Cap::ContentProtection`.
8469    ContentProtected(bool),
8470    /// Move and/or resize. `origin` is the outer frame's top-left corner in points on the
8471    /// desktop's coordinate space (top-left origin, `Cap::WindowPosition`); `size` is the size Day
8472    /// lays the content out at, in points, the same size `WindowResized` reports
8473    /// (`Cap::WindowGeometry`): the backend adds its own chrome around it.
8474    Frame {
8475        origin: Option<Point>,
8476        size: Option<Size>,
8477    },
8478    /// The content size the user can resize the window to. `None` lifts that bound.
8479    /// `Cap::WindowGeometry`.
8480    Limits {
8481        min: Option<Size>,
8482        max: Option<Size>,
8483    },
8484    /// Stacking against other apps' windows. `Cap::WindowLevel`.
8485    Level(WindowLevel),
8486    /// Show the window on every virtual desktop / Space. `Cap::WindowLevel`.
8487    OnAllWorkspaces(bool),
8488    /// Leave the window out of the taskbar and the window switcher. `Cap::WindowLevel`.
8489    SkipTaskbar(bool),
8490    /// Whether the user can resize the window. `Cap::WindowGeometry`.
8491    Resizable(bool),
8492    /// Whether the window offers a minimize control. `Cap::WindowStates`.
8493    Minimizable(bool),
8494    /// Whether the window offers a maximize / zoom control. `Cap::WindowStates`.
8495    Maximizable(bool),
8496    /// Whether the window offers a close control. `Cap::WindowStates`.
8497    Closable(bool),
8498    /// Hide the window without closing it, or show it again. `Cap::WindowStates`.
8499    Visible(bool),
8500    /// This window's light/dark override over the app-wide [`Toolkit::set_appearance`].
8501    /// `Cap::WindowAppearance`.
8502    Appearance(Option<bool>),
8503    /// Bounce the Dock icon, flash the taskbar button. `Cap::RequestAttention`.
8504    RequestAttention(Attention),
8505}
8506
8507/// The frame a window wears (docs/window-chrome.md), set once when it opens.
8508#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
8509pub enum WindowChrome {
8510    /// The platform's title bar and frame.
8511    #[default]
8512    Standard,
8513    /// The content runs to the window's top edge, under the title bar, and the platform's own
8514    /// window controls (close, minimize, zoom) stay where they are. For a custom title bar: the
8515    /// backend reports the bar's height as the window's safe-area top inset (`day::safe_area()`),
8516    /// so the app pads its content by it and paints its background under it. Mark the draggable
8517    /// part with `.window_drag_region()`. `Cap::OverlayTitleBar`; where unsupported the window
8518    /// keeps its standard bar.
8519    Overlay,
8520    /// No title bar and no frame: a splash screen, a heads-up panel, a borderless utility. The
8521    /// window still resizes from its edges when resizable; mark the part that moves it with
8522    /// `.window_drag_region()`. `Cap::FramelessWindow`; where unsupported the window keeps its
8523    /// standard frame.
8524    Frameless,
8525}
8526
8527/// What shows behind a window's content (docs/window-chrome.md).
8528#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
8529pub enum WindowBackground {
8530    /// The platform's window background.
8531    #[default]
8532    Opaque,
8533    /// Nothing: pixels the content leaves unpainted show the desktop through the window. For
8534    /// rounded or shaped splash screens and overlays. `Cap::TransparentWindow`.
8535    Transparent,
8536    /// A translucent system material that blurs what is behind the window.
8537    /// `Cap::WindowMaterial`; where unsupported the window stays opaque.
8538    Material(WindowMaterial),
8539}
8540
8541/// The system materials a window background can use ([`WindowBackground::Material`]).
8542#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
8543pub enum WindowMaterial {
8544    /// The main-window material: macOS's window background, Windows 11's Mica.
8545    Window,
8546    /// A sidebar or source list: macOS's sidebar material, Windows 11's Mica Alt (tabbed).
8547    Sidebar,
8548    /// A transient surface (a popover, a menu-like panel, a heads-up display): macOS's popover
8549    /// material, Windows 11's Acrylic.
8550    Transient,
8551}
8552
8553/// Where a window opens ([`WindowOptions::placement`]).
8554#[derive(Clone, Copy, Debug, Default, PartialEq)]
8555pub enum WindowPlacement {
8556    /// The platform's choice: macOS cascades, Windows and Linux let the window manager decide.
8557    #[default]
8558    Automatic,
8559    /// Centered on the screen with the active window.
8560    Centered,
8561    /// The outer frame's top-left corner at this point, in points on the desktop's coordinate
8562    /// space (top-left origin). Falls back to `Automatic` without `Cap::WindowPosition`.
8563    At(Point),
8564}
8565
8566/// A small runtime RGBA image for a status item: charts, meters, or a grid of results.
8567///
8568/// Rows run top to bottom; samples are tightly packed, non-premultiplied sRGB RGBA8.
8569/// `scale` is pixels per logical point (2 for Retina). This owns its bytes, independent of
8570/// any window or decoded-image registry. Currently rendered by AppKit; other backends use
8571/// [`StatusItemSpec::icon`] as a fallback. See docs/status-item.md.
8572#[derive(Clone, PartialEq)]
8573pub struct StatusImage {
8574    width: u32,
8575    height: u32,
8576    scale: f64,
8577    rgba: std::sync::Arc<[u8]>,
8578}
8579
8580impl StatusImage {
8581    /// Validate a runtime image. Rejects empty/mismatched pixels, invalid scales, and images
8582    /// exceeding 16 MiB or 4096 logical points on either axis. No platform allocation occurs.
8583    pub fn rgba(
8584        width: u32,
8585        height: u32,
8586        scale: f64,
8587        pixels: impl Into<std::sync::Arc<[u8]>>,
8588    ) -> Option<Self> {
8589        let rgba = pixels.into();
8590        let expected = (width as usize)
8591            .checked_mul(height as usize)?
8592            .checked_mul(4)?;
8593        if width == 0
8594            || height == 0
8595            || expected > 16 * 1024 * 1024
8596            || rgba.len() != expected
8597            || !scale.is_finite()
8598            || scale <= 0.0
8599            || f64::from(width) / scale > 4096.0
8600            || f64::from(height) / scale > 4096.0
8601        {
8602            return None;
8603        }
8604        Some(Self {
8605            width,
8606            height,
8607            scale,
8608            rgba,
8609        })
8610    }
8611
8612    pub fn width(&self) -> u32 {
8613        self.width
8614    }
8615    pub fn height(&self) -> u32 {
8616        self.height
8617    }
8618    pub fn scale(&self) -> f64 {
8619        self.scale
8620    }
8621    pub fn pixels(&self) -> &[u8] {
8622        &self.rgba
8623    }
8624    pub fn size(&self) -> Size {
8625        Size::new(
8626            f64::from(self.width) / self.scale,
8627            f64::from(self.height) / self.scale,
8628        )
8629    }
8630}
8631
8632impl std::fmt::Debug for StatusImage {
8633    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
8634        f.debug_struct("StatusImage")
8635            .field("width", &self.width)
8636            .field("height", &self.height)
8637            .field("scale", &self.scale)
8638            .field("bytes", &self.rgba.len())
8639            .finish()
8640    }
8641}
8642
8643#[cfg(test)]
8644mod status_image_tests {
8645    use super::*;
8646
8647    #[test]
8648    fn validates_pixel_layout_and_logical_size() {
8649        let image = StatusImage::rgba(120, 36, 2.0, vec![255; 120 * 36 * 4]).unwrap();
8650        assert_eq!(image.size(), Size::new(60.0, 18.0));
8651        assert_eq!(image.clone(), image);
8652        assert!(StatusImage::rgba(0, 1, 1.0, vec![]).is_none());
8653        assert!(StatusImage::rgba(1, 1, 1.0, vec![0; 3]).is_none());
8654        assert!(StatusImage::rgba(u32::MAX, u32::MAX, 1.0, vec![]).is_none());
8655        for scale in [0.0, -1.0, f64::NAN, f64::INFINITY, 0.00001] {
8656            assert!(StatusImage::rgba(1, 1, scale, vec![0; 4]).is_none());
8657        }
8658    }
8659}
8660
8661/// One status item: an icon in the menu bar (macOS), the notification area (Windows) or a
8662/// StatusNotifierItem host's tray (Linux), with a menu (docs/status-item.md).
8663#[derive(Clone, Debug, PartialEq)]
8664pub struct StatusItemSpec {
8665    /// The app's name for the item, stable across updates: what a backend diffs by.
8666    pub id: String,
8667    /// The glyph. `None` shows the title alone (macOS) or the app's icon (elsewhere).
8668    pub icon: Option<Icon>,
8669    /// A runtime image. AppKit prefers this over `icon`, preserving aspect ratio and point
8670    /// size up to 18pt high; other backends ignore it and show `icon`/`title` as before.
8671    pub raster: Option<StatusImage>,
8672    /// Draw the icon as a template: its shape only, in the menu bar's or panel's own color, so
8673    /// it reads in light and dark. Symbols are always templates.
8674    pub template: bool,
8675    /// Text beside the icon where the platform shows one (the macOS menu bar). Empty: icon only.
8676    pub title: String,
8677    /// The hover text.
8678    pub tooltip: String,
8679    /// The menu the item opens. Same model and dispatch as the app menu.
8680    pub menu: Vec<MenuItem>,
8681    /// A dispatch id (the [`Event::MenuAction`] registry) run when the user clicks the item
8682    /// itself, where the platform separates a click from opening the menu (a left click on macOS
8683    /// and Windows, the host's "activate" on Linux). 0: a click opens the menu.
8684    pub activate: u64,
8685}
8686
8687/// One display (docs/windows.md "Monitors"), in points on the desktop's coordinate space:
8688/// top-left origin at the primary display's top-left corner.
8689#[derive(Clone, Debug, PartialEq)]
8690pub struct Monitor {
8691    /// Stable for the display across launches where the platform offers it (a display UUID, a
8692    /// connector name); an index otherwise.
8693    pub id: String,
8694    /// The display's name, for a picker ("Built-in Retina Display", "DELL U2720Q").
8695    pub name: String,
8696    /// The display's whole area.
8697    pub frame: Rect,
8698    /// The part windows should use: the frame minus the menu bar, Dock, taskbar or panels.
8699    pub work_area: Rect,
8700    /// Device pixels per point.
8701    pub scale: f64,
8702    /// The display the desktop's menu bar or primary taskbar is on.
8703    pub primary: bool,
8704}
8705
8706/// A launcher shortcut the app sets while it runs (docs/deep-links.md "Launcher shortcuts"): a
8707/// route to open and the label the launcher shows, already localized.
8708#[derive(Clone, Debug, PartialEq, Eq)]
8709pub struct LauncherShortcut {
8710    /// The route the shortcut opens, through the deep-link intake.
8711    pub route: String,
8712    /// What the launcher shows.
8713    pub label: String,
8714}
8715
8716/// A progress indicator on the app's Dock or taskbar icon ([`Toolkit::set_app_progress`],
8717/// docs/status-item.md).
8718#[derive(Clone, Copy, Debug, Default, PartialEq)]
8719pub enum AppProgress {
8720    /// No indicator.
8721    #[default]
8722    None,
8723    /// Work of unknown length.
8724    Indeterminate,
8725    /// A fraction done, 0.0 to 1.0.
8726    Value(f64),
8727    /// A fraction done, paused. Platforms without a paused state show `Value`.
8728    Paused(f64),
8729    /// A fraction done when the work failed. Platforms without an error state show `Value`.
8730    Error(f64),
8731}
8732
8733/// Whether and how a window joins macOS window tabs ([`WindowOptions::tabbing`],
8734/// `Cap::WindowTabbing`). Other platforms have no system window tabs and ignore it.
8735#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
8736pub enum WindowTabbing {
8737    /// The platform default for the window's kind: an ordinary window tabs with the app's other
8738    /// ordinary windows when the user's "Prefer tabs" setting says so; preferences never tab.
8739    #[default]
8740    Automatic,
8741    /// Tab only with windows of the same group, following the user's setting. The tab bar's
8742    /// "+" opens the builder registered for this group (`register_new_window_for`).
8743    Group(String),
8744    /// Always open as a tab of an existing window of the same group, whatever the setting.
8745    Preferred(String),
8746    /// Never become a tab.
8747    Disallowed,
8748}
8749
8750/// An app's generated locale catalog: `(DEFAULT, CATALOG)`, exactly what `day-build` emits as
8751/// `res::locales::{DEFAULT, CATALOG}` (§18.5). Carried in [`WindowOptions::locales`] so the
8752/// framework can install it at the one moment that is correct.
8753pub type AppLocales = (&'static str, &'static [(&'static str, &'static str)]);
8754
8755#[derive(Clone, Debug)]
8756pub struct WindowOptions {
8757    pub title: String,
8758    pub size: Size,
8759    pub min_size: Option<Size>,
8760    /// Create and mount the window without showing it or activating the app. Supported on
8761    /// AppKit; other backends currently ignore this option. Defaults to false.
8762    ///
8763    /// Menu-bar apps can keep their initial host hidden and open Preferences on demand.
8764    /// The window still exists and can be shown with `WindowHandle::set_visible(true)`;
8765    /// this does not change the app's keep-running policy.
8766    pub start_hidden: bool,
8767    /// Ask the backend to size this window to its content once it has been built and laid out,
8768    /// rather than keeping [`Self::size`] (docs/windows.md). `size` still decides the width and
8769    /// acts as the height ceiling, so a panel with more content than fits the screen scrolls
8770    /// instead of growing past it.
8771    ///
8772    /// What a preferences panel wants on every desktop. Ignored by backends that cannot resize a
8773    /// live window, and by the ones with no windows at all.
8774    pub size_to_fit: bool,
8775    /// The app's display name for the standard application menu / About (macOS). `None` falls back
8776    /// to `title`; set it when `title` carries extra decoration you don't want in `About <name>`
8777    /// (e.g. the showcase's window title is "Day Showcase (AppKit)" but its app name is "Showcase").
8778    pub app_name: Option<String>,
8779    /// The app's locale catalog, installed by `day::launch` (docs/localization.md).
8780    ///
8781    /// The order is why this is the framework's job: the OS's languages reach day-localization from the
8782    /// live backend, and the catalog has to be registered after that hint and before the first
8783    /// localized string is read. An app that installs it itself (before `launch`, where there
8784    /// is no backend yet) registers against an empty hint list and resolves to `DEFAULT`, so a
8785    /// French device opens an English window.
8786    pub locales: Option<AppLocales>,
8787    /// The title, computed once the catalog above is installed: how a window title comes from
8788    /// the catalog rather than a literal. Takes precedence over [`Self::title`], which stays the
8789    /// fallback for the moment before (and for apps with nothing to translate).
8790    ///
8791    /// A plain `fn` rather than a closure: this struct is `Clone`, and the callers are a
8792    /// non-capturing `|| res::str::app_title().format()`, which coerces.
8793    pub title_fn: Option<fn() -> String>,
8794    /// The app's version, for Day's exit line (`Clean exit for <app> v<version> …`,
8795    /// docs/lifecycle.md): `env!("CARGO_PKG_VERSION")` in the app crate, which the scaffold's
8796    /// `window()` sets. `None` falls back to the `DAY_APP_VERSION` the `day` CLI sets on a launch.
8797    pub version: Option<String>,
8798    /// macOS window tabbing for this window (`Cap::WindowTabbing`); ignored elsewhere.
8799    pub tabbing: WindowTabbing,
8800    /// The window's frame: standard, a title bar the content runs under, or none
8801    /// (docs/window-chrome.md). Desktop only; phones and the web ignore it.
8802    pub chrome: WindowChrome,
8803    /// What shows behind the content: the window background, nothing, or a system material.
8804    pub background: WindowBackground,
8805    /// Whether the window casts the platform's drop shadow. A transparent, shaped window often
8806    /// wants none.
8807    pub shadow: bool,
8808    /// Whether the user can resize the window by its edges.
8809    pub resizable: bool,
8810    /// Where the window opens.
8811    pub placement: WindowPlacement,
8812    /// The largest content size the user can resize the window to (`Cap::WindowGeometry`).
8813    pub max_size: Option<Size>,
8814    /// Remember this window's size, position and maximized state under this key, and reopen it
8815    /// that way next launch (docs/windows.md "Remembered frames"). A position that no attached
8816    /// display shows any more is dropped, so a window never reopens off-screen.
8817    pub remember_frame: Option<String>,
8818    /// The logical window this opens (docs/windows.md): `open_window` focuses an already-open
8819    /// window with the same key instead of opening a second (the preferences pattern). `None`
8820    /// always opens a new one.
8821    pub key: Option<String>,
8822    /// The kind of window: a regular one, a preferences panel, an About panel.
8823    pub kind: WindowKind,
8824}
8825
8826impl WindowOptions {
8827    /// The window title. Replaces a [`title_fn`](Self::title_fn) set earlier (the generated
8828    /// `res::window_options()` sets one), so the last title named wins.
8829    pub fn title(mut self, title: impl Into<String>) -> Self {
8830        self.title = title.into();
8831        self.title_fn = None;
8832        self
8833    }
8834    /// The content size the window opens at (desktop; phones fill the screen).
8835    pub fn size(mut self, width: f64, height: f64) -> Self {
8836        self.size = Size::new(width, height);
8837        self
8838    }
8839    /// The smallest content size the user can resize to.
8840    pub fn min_size(mut self, width: f64, height: f64) -> Self {
8841        self.min_size = Some(Size::new(width, height));
8842        self
8843    }
8844    /// The largest content size the user can resize to (`Cap::WindowGeometry`).
8845    pub fn max_size(mut self, width: f64, height: f64) -> Self {
8846        self.max_size = Some(Size::new(width, height));
8847        self
8848    }
8849    /// Create and mount the window without showing it; see [`Self::start_hidden`].
8850    pub fn start_hidden(mut self) -> Self {
8851        self.start_hidden = true;
8852        self
8853    }
8854    /// Size the window to its content once built; see [`Self::size_to_fit`].
8855    pub fn size_to_fit(mut self) -> Self {
8856        self.size_to_fit = true;
8857        self
8858    }
8859    /// The app's display name for the application menu and About; see [`Self::app_name`].
8860    pub fn app_name(mut self, name: impl Into<String>) -> Self {
8861        self.app_name = Some(name.into());
8862        self
8863    }
8864    /// The app's locale catalog, as `res::locales::{DEFAULT, CATALOG}`; see [`Self::locales`].
8865    pub fn locales(
8866        mut self,
8867        default: &'static str,
8868        catalog: &'static [(&'static str, &'static str)],
8869    ) -> Self {
8870        self.locales = Some((default, catalog));
8871        self
8872    }
8873    /// The title, computed once the catalog is installed; see [`Self::title_fn`].
8874    pub fn title_fn(mut self, f: fn() -> String) -> Self {
8875        self.title_fn = Some(f);
8876        self
8877    }
8878    /// The app's version, for Day's exit line; see [`Self::version`].
8879    pub fn version(mut self, version: impl Into<String>) -> Self {
8880        self.version = Some(version.into());
8881        self
8882    }
8883    /// macOS window tabbing for this window; see [`Self::tabbing`].
8884    pub fn tabbing(mut self, tabbing: WindowTabbing) -> Self {
8885        self.tabbing = tabbing;
8886        self
8887    }
8888    /// The window's frame; see [`Self::chrome`].
8889    pub fn chrome(mut self, chrome: WindowChrome) -> Self {
8890        self.chrome = chrome;
8891        self
8892    }
8893    /// What shows behind the content; see [`Self::background`].
8894    pub fn background(mut self, background: WindowBackground) -> Self {
8895        self.background = background;
8896        self
8897    }
8898    /// No drop shadow, for a transparent or shaped window; see [`Self::shadow`].
8899    pub fn no_shadow(mut self) -> Self {
8900        self.shadow = false;
8901        self
8902    }
8903    /// A window the user cannot resize; see [`Self::resizable`].
8904    pub fn fixed_size(mut self) -> Self {
8905        self.resizable = false;
8906        self
8907    }
8908    /// Where the window opens; see [`Self::placement`].
8909    pub fn placement(mut self, placement: WindowPlacement) -> Self {
8910        self.placement = placement;
8911        self
8912    }
8913    /// Remember and restore this window's frame under `key`; see [`Self::remember_frame`].
8914    pub fn remember_frame(mut self, key: impl Into<String>) -> Self {
8915        self.remember_frame = Some(key.into());
8916        self
8917    }
8918    /// The logical window this opens; see [`Self::key`].
8919    pub fn key(mut self, key: impl Into<String>) -> Self {
8920        self.key = Some(key.into());
8921        self
8922    }
8923    /// The kind of window; see [`Self::kind`].
8924    pub fn kind(mut self, kind: WindowKind) -> Self {
8925        self.kind = kind;
8926        self
8927    }
8928}
8929
8930impl Default for WindowOptions {
8931    fn default() -> Self {
8932        WindowOptions {
8933            title: "Day".into(),
8934            size: Size::new(480.0, 640.0),
8935            min_size: None,
8936            start_hidden: false,
8937            size_to_fit: false,
8938            app_name: None,
8939            locales: None,
8940            title_fn: None,
8941            version: None,
8942            tabbing: WindowTabbing::Automatic,
8943            chrome: WindowChrome::Standard,
8944            background: WindowBackground::Opaque,
8945            shadow: true,
8946            resizable: true,
8947            placement: WindowPlacement::Automatic,
8948            max_size: None,
8949            remember_frame: None,
8950            key: None,
8951            kind: WindowKind::Normal,
8952        }
8953    }
8954}
8955
8956/// A platform backend: owns the native main loop and exactly one window in v1 (§8.1).
8957///
8958/// `run` sets up the native app + window, installs the reactive scheduler + main poster,
8959/// then hands `(self, root_container, content_size)` to `ready` (which mounts the tree and
8960/// takes ownership of the backend), and finally runs the native main loop.
8961pub trait Platform: Toolkit {
8962    /// The process-constant target id, e.g. `"macos-appkit"`.
8963    const TARGET: &'static str;
8964    /// The toolkit half of the target, e.g. `"appkit"`.
8965    const TOOLKIT: &'static str;
8966    /// Whether [`Platform::run`] returning means the app is over. True for a backend that
8967    /// drives the native loop itself until the app quits (GTK, Qt, XAML; AppKit's never
8968    /// returns). False where the host owns the loop and `run` hands back at once, with the
8969    /// app still to come (ArkUI's ability, Android's activity, the web page, the mock's test):
8970    /// their `DidExit` is the host's last callback, not the return (docs/lifecycle.md).
8971    const RUN_ENDS_APP: bool = true;
8972
8973    fn run(self, options: WindowOptions, ready: Box<dyn FnOnce(Self, Self::Handle, Size)>);
8974
8975    /// Post a closure onto the native main loop. Callable from any thread; this is the
8976    /// single door the reactive scheduler and `Setter` deliveries ride (§3.3).
8977    fn post(f: Box<dyn FnOnce() + Send>);
8978
8979    /// Post `f` onto the native main loop after (at least) `ms` milliseconds: the timer
8980    /// door behind `day::sleep` (docs/async.md). Every shipped backend overrides it with the
8981    /// loop's own timer (`dispatch_after`, `Handler.postDelayed`, `g_timeout_add`,
8982    /// `QTimer::singleShot`, `SetTimer`, `setTimeout`), so a sleep costs no thread. The
8983    /// default is the fallback for a backend without one: a helper thread that sleeps the
8984    /// whole delay and rides [`Platform::post`] home. It is correct, but a thread per sleep
8985    /// adds up under a ticking loop, so the first use says so once in the log.
8986    fn post_delayed(ms: u32, f: Box<dyn FnOnce() + Send>) {
8987        static SAID: std::sync::Once = std::sync::Once::new();
8988        SAID.call_once(|| {
8989            log::warn!(
8990                "day: {} has no native timer door; `day::sleep` falls back to a helper thread \
8991                 per delay (implement `Platform::post_delayed`)",
8992                Self::TARGET
8993            );
8994        });
8995        std::thread::spawn(move || {
8996            std::thread::sleep(std::time::Duration::from_millis(u64::from(ms)));
8997            Self::post(f);
8998        });
8999    }
9000
9001    /// Ordered OS locale preference list (BCP-47), for fluent-langneg (§12.2).
9002    fn locale_hints(&self) -> Vec<String> {
9003        Vec::new()
9004    }
9005}
9006
9007// ---------------------------------------------------------------------------
9008// Open renderer registry (§8.2)
9009// ---------------------------------------------------------------------------
9010
9011/// The scale a window snapshot is rendered at, when a scripted run states one
9012/// (`DAY_CAPTURE_SCALE=2`, set by `day launch --script` from Day.toml `[screenshots]`).
9013///
9014/// For the backends that render their own snapshot (GTK, Qt): the capture then measures
9015/// window points times this, whatever display the host has, which is what makes a CI capture
9016/// under a 1x xvfb the same 2560x1600 pixels a HiDPI laptop produces. A backend that reads the
9017/// compositor's pixels back (AppKit, XAML) captures at the display's own scale and ignores it.
9018/// `None` when unset or unparseable: capture at the backend's natural scale.
9019pub fn capture_scale() -> Option<f64> {
9020    std::env::var("DAY_CAPTURE_SCALE")
9021        .ok()
9022        .and_then(|v| v.trim().parse::<f64>().ok())
9023        .filter(|s| s.is_finite() && (0.5..=4.0).contains(s))
9024}
9025
9026/// Seconds on a monotonic clock since the first call: the frame timestamp for a backend that
9027/// does not expose a native timestamp (§8.4). The origin is arbitrary. Not for the web
9028/// build, where `Instant` is unavailable and `requestAnimationFrame` stamps the frame itself.
9029pub fn frame_timestamp() -> f64 {
9030    static ORIGIN: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new();
9031    ORIGIN
9032        .get_or_init(std::time::Instant::now)
9033        .elapsed()
9034        .as_secs_f64()
9035}
9036
9037/// The user's language preference from the POSIX environment, newest-first, as BCP-47 tags.
9038///
9039/// `LANGUAGE` is the GNU multi-language list (`fr:en`); `LC_ALL`, `LC_MESSAGES` and `LANG` each
9040/// carry one locale in POSIX form (`fr_FR.UTF-8`), which becomes `fr-FR`. Shared by the backends
9041/// whose platform has no richer API to ask (§12.2, docs/localization.md).
9042pub fn posix_locale_hints() -> Vec<String> {
9043    let mut out: Vec<String> = Vec::new();
9044    let mut push = |tag: &str| {
9045        // "C" and "POSIX" are the absence of a preference, not a language.
9046        let tag = tag.split('.').next().unwrap_or(tag).replace('_', "-");
9047        if tag.is_empty() || tag == "C" || tag == "POSIX" {
9048            return;
9049        }
9050        if !out.contains(&tag) {
9051            out.push(tag);
9052        }
9053    };
9054    if let Ok(list) = std::env::var("LANGUAGE") {
9055        for tag in list.split(':') {
9056            push(tag);
9057        }
9058    }
9059    for key in ["LC_ALL", "LC_MESSAGES", "LANG"] {
9060        if let Ok(v) = std::env::var(key) {
9061            push(&v);
9062        }
9063    }
9064    out
9065}
9066
9067/// Optional custom measure for a third-party piece (§8.2).
9068pub type MeasureFn<B> = fn(&mut B, &<B as Toolkit>::Handle, Proposal) -> Size;
9069
9070/// A third-party piece's per-toolkit implementation. `make` receives the concrete backend
9071/// (public helper surface) and returns a native handle the backend then owns like any built-in.
9072pub struct Renderer<B: Toolkit> {
9073    pub kind: PieceKind,
9074    pub make: fn(&mut B, &dyn Any, NodeId) -> B::Handle,
9075    pub update: fn(&mut B, &B::Handle, &dyn Any),
9076    pub measure: Option<MeasureFn<B>>,
9077    /// Teardown, run from the release queue just before [`Toolkit::release`] frees the handle.
9078    ///
9079    /// A piece that keeps per-view state (a retained delegate, a session map, a native
9080    /// observer) has no other place to drop it: `make`/`update` are the only other hooks, and a
9081    /// disposed node never calls them again. Without this a piece leaks one entry per realized
9082    /// view, and any map keyed by the handle's address can go on to answer for a later view that
9083    /// the allocator hands the same address.
9084    ///
9085    /// `None` for the pieces that own nothing (most of them).
9086    pub release: Option<fn(&mut B, &B::Handle)>,
9087}
9088
9089pub struct Registry<B: Toolkit> {
9090    map: HashMap<PieceKind, Renderer<B>>,
9091}
9092
9093impl<B: Toolkit> Default for Registry<B> {
9094    fn default() -> Self {
9095        Registry {
9096            map: HashMap::new(),
9097        }
9098    }
9099}
9100
9101impl<B: Toolkit> Registry<B> {
9102    pub fn register(&mut self, r: Renderer<B>) {
9103        let kind = r.kind;
9104        if self.map.insert(kind, r).is_some() {
9105            // Two pieces claiming one kind is last-linked-wins in link order, effectively
9106            // nondeterministic. Fail loudly in debug; in release, say so once at boot rather
9107            // than render the wrong widget silently.
9108            debug_assert!(
9109                false,
9110                "duplicate renderer registered for piece kind {kind:?}"
9111            );
9112            log::warn!("duplicate renderer for piece kind {kind:?} — later registration wins");
9113        }
9114    }
9115    pub fn get(&self, kind: PieceKind) -> Option<&Renderer<B>> {
9116        self.map.get(kind)
9117    }
9118    pub fn kinds(&self) -> impl Iterator<Item = PieceKind> + '_ {
9119        self.map.keys().copied()
9120    }
9121}
9122
9123/// The canvas wire op codes (§11, §15.3): slot 0 of every 9-number record in
9124/// [`encode_ops`]'s output. The numeric values are the frozen wire contract: the JNI, C++,
9125/// and JS decoders each hand-write these as constants, so a value here may never be reused
9126/// or renumbered; new ops append. `ALL` drives the density test that keeps this enum and
9127/// the encoder in step.
9128#[derive(Clone, Copy, Debug, PartialEq, Eq)]
9129#[repr(i32)]
9130pub enum OpCode {
9131    /// Fill a rect (a,b=origin, c,d=size).
9132    FillRect = 0,
9133    /// Stroke a rect (g=width).
9134    StrokeRect = 1,
9135    /// Fill a rounded rect (e=radius).
9136    FillRrect = 2,
9137    /// Fill an ellipse in a rect.
9138    FillEllipse = 3,
9139    /// Stroke an ellipse (g=width).
9140    StrokeEllipse = 4,
9141    /// Stroke an arc (e=start°, f=sweep°, g=width). `Fill(Shape::Arc)` also encodes as
9142    /// this with width 0, the known asymmetry; see [`encode_ops`].
9143    StrokeArc = 5,
9144    /// Line a,b → c,d (g=width).
9145    Line = 6,
9146    /// Text at a,b (e=size, f=anchor: 0 leading / 1 centered); the string rides the texts
9147    /// channel.
9148    Text = 7,
9149    /// Save the graphics state.
9150    Save = 8,
9151    /// Restore the graphics state.
9152    Restore = 9,
9153    /// Concat an affine transform (a..f).
9154    Concat = 10,
9155    /// Fill a polygon; points ride the texts channel as "x,y x,y …" (closed automatically),
9156    /// or the geometry channel of [`encode_ops_with_geometry`] (b = offset, c = count, and
9157    /// the texts entry is empty). `a` = the [`geometry_key`] of those points, or 0 for none.
9158    FillPolygon = 11,
9159    /// Stroke a polygon (g=width); points and key as [`OpCode::FillPolygon`].
9160    StrokePolygon = 12,
9161    /// Stroke a rounded rect (e=radius, g=width).
9162    StrokeRrect = 13,
9163    /// Set a gradient for the next shape record (f=type: 0 linear with a,b=start / c,d=end
9164    /// unit points; 1 radial with a,b=center unit point, c=unit radius; e=stop count).
9165    /// Stops ride the texts channel as "offset,aarrggbb offset,aarrggbb …". Unit geometry
9166    /// resolves against the shape's bounding box.
9167    SetGradient = 14,
9168    /// Fill a path (f=fill rule: 0 non-zero / 1 even-odd); segments ride the texts channel
9169    /// (see [`encode_path`]), or the geometry channel of [`encode_ops_with_geometry`]
9170    /// (b = offset, c = count, see [`path_numbers`]; the texts entry is empty). `a` = the
9171    /// [`geometry_key`] of those segments, or 0 for none.
9172    ///
9173    /// The key is a cache handle, not a payload: a decoder that recognizes it may keep the
9174    /// native geometry it built last time and skip re-parsing the segments, but it must still
9175    /// consume the texts entry either way, because that channel is positional and a skipped
9176    /// entry desynchronizes every record after it.
9177    FillPath = 15,
9178    /// Stroke a path (g=width); segments and key as [`OpCode::FillPath`].
9179    StrokePath = 16,
9180    /// Clip to a shape (f=shape kind: 0 rect / 1 rrect(e=radius) / 2 ellipse / 3 path
9181    /// (e=fill rule) / 4 polygon; a..d=geometry; path/polygon payloads ride the texts
9182    /// channel).
9183    ///
9184    /// For the two payload-bearing kinds (3 and 4) there is no geometry in the slots, so `a`
9185    /// carries the [`geometry_key`] instead, b and c the geometry channel's offset and count
9186    /// when there is one, and d stays 0. The other three kinds put real geometry in a..d and
9187    /// have nothing to cache.
9188    Clip = 17,
9189    /// Stroke style for the next stroke record (a=cap, b=join, c=miter limit, d=dash
9190    /// phase, e=dash count; the dash array rides the texts channel).
9191    StrokeStyle = 18,
9192    /// Font for the next text record (a=CSS weight 100 … 900, 0 = default; b=italic 0/1); the
9193    /// family name rides the texts channel, `""` = the platform's default face. Like
9194    /// [`OpCode::SetGradient`] and [`OpCode::StrokeStyle`] it is consumed by the record that
9195    /// follows and then cleared; a default [`CanvasFont`] emits no record at all, so a drawing
9196    /// without fonts encodes exactly as it did before this op existed.
9197    SetFont = 19,
9198    /// The next shape record is a template, drawn once per stamped position rather than once
9199    /// (docs/canvas.md "Stamping"). `a` = how many positions follow. Like [`OpCode::SetGradient`],
9200    /// [`OpCode::StrokeStyle`] and [`OpCode::SetFont`] it is a prefix, consumed by the record it
9201    /// applies to and then cleared.
9202    ///
9203    /// Between this and that template record come `ceil(a / 4)` [`OpCode::StampPoints`] records
9204    /// carrying the coordinates. A drawing with no stamps encodes exactly as it did before.
9205    Stamp = 20,
9206    /// Four stamped positions, filling the record edge to edge: `[op, x0, y0, x1, y1, x2, y2,
9207    /// x3, y3]`, the one record that uses its last slot for geometry instead of a color, because
9208    /// it carries no color of its own. The final record of a run is padded; the count in the
9209    /// [`OpCode::Stamp`] header says how many of the pairs are real.
9210    StampPoints = 21,
9211    /// Draw a decoded image: `a,b` = origin, `c,d` = size, `e` = the [`BitmapId`], `f` = opacity
9212    /// in `0.0..=1.0` (docs/images.md).
9213    ///
9214    /// The id rides the numeric channel because it is a number, and an `f64` carries a `u64` id
9215    /// exactly up to 2^53; ids are minted from 1 per process, so that ceiling is unreachable.
9216    /// Nothing rides the texts channel for this op.
9217    Image = 22,
9218    /// The source region for the next image record (`a,b` = origin, `c,d` = size, in the
9219    /// bitmap's own pixels): [`DrawOp::Image`]'s `source`. Like [`OpCode::SetFont`] it is a
9220    /// prefix, consumed by the record that follows and then cleared, and a whole-image draw
9221    /// emits none, so a drawing without regions encodes exactly as it did before this op
9222    /// existed. A decoder clamps the region to the bitmap and draws nothing for an empty
9223    /// intersection ([`clamp_image_source`]).
9224    ImageSource = 23,
9225}
9226
9227impl OpCode {
9228    /// Every code, in wire order. The density test iterates this so a new variant that
9229    /// forgets to join fails loudly.
9230    pub const ALL: [OpCode; 24] = [
9231        OpCode::FillRect,
9232        OpCode::StrokeRect,
9233        OpCode::FillRrect,
9234        OpCode::FillEllipse,
9235        OpCode::StrokeEllipse,
9236        OpCode::StrokeArc,
9237        OpCode::Line,
9238        OpCode::Text,
9239        OpCode::Save,
9240        OpCode::Restore,
9241        OpCode::Concat,
9242        OpCode::FillPolygon,
9243        OpCode::StrokePolygon,
9244        OpCode::StrokeRrect,
9245        OpCode::SetGradient,
9246        OpCode::FillPath,
9247        OpCode::StrokePath,
9248        OpCode::Clip,
9249        OpCode::StrokeStyle,
9250        OpCode::SetFont,
9251        OpCode::Stamp,
9252        OpCode::StampPoints,
9253        OpCode::Image,
9254        OpCode::ImageSource,
9255    ];
9256
9257    /// The code back from a wire number (a decoder-side aid and the round-trip test's
9258    /// reference); `None` for anything outside the table.
9259    pub fn from_wire(n: f64) -> Option<OpCode> {
9260        OpCode::ALL.into_iter().find(|c| *c as i32 as f64 == n)
9261    }
9262}
9263
9264/// Flat numeric encoding of a display list for shim/JNI boundaries (§11, §15.3): per op
9265/// 9 numbers [kind, a, b, c, d, e, f, g, rgba-bits]; text payloads ride separately in order.
9266/// The kind slot carries an [`OpCode`]; its doc comments are the per-slot contract.
9267///
9268/// Transports join `texts` with the unit separator U+001F (one entry per text-carrying
9269/// record, in order), so text payloads must not contain U+001F. Known asymmetry:
9270/// `Fill(Shape::Arc)` encodes as [`OpCode::StrokeArc`] with width 0. Filled arcs render
9271/// only on the direct-replay backends (AppKit/UIKit); use a polygon fan if a filled arc
9272/// must be portable.
9273/// Serialize a path for the `texts` side-channel: one space-separated token per segment,
9274/// `M x y` / `L x y` / `Q cx cy x y` / `C c1x c1y c2x c2y x y` / `Z`.
9275///
9276/// Text rather than numbers because that is the channel the encoder already has for
9277/// variable-length payloads, and every decoder (JS, Java, C++) can already split a string. The
9278/// numeric channel is a flat `[f64; 9]`-per-record array with no length prefix, so a path could
9279/// not ride it without changing the record shape for every backend at once.
9280/// A content key for a shape's variable-length geometry: the handle a backend caches decoded
9281/// native geometry under (a `Path2D`, a `QPainterPath`, an `android.graphics.Path`) so an
9282/// unchanged path is rebuilt once instead of re-parsed out of the texts channel every frame.
9283///
9284/// It hashes the geometry, not the op's position or its identity, so that a draw closure that
9285/// rebuilds its `PathBuilder` chain from scratch on every frame (which is what canvas consumers
9286/// do) produces an equal path, hashes the same and hits the same entry. An identity would miss
9287/// every time.
9288///
9289/// Two different paths that collided would draw each other, so the width matters: FNV-1a over the
9290/// IEEE bits, masked to the 53 bits an `f64` wire slot carries exactly. `0.0` is reserved for "no
9291/// key": a decoder seeing it must decode the payload as it always did, which is also what every
9292/// decoder written before this key existed does with the slot.
9293pub fn geometry_key(shape: &Shape) -> f64 {
9294    fn mix(h: &mut u64, v: f64) {
9295        for byte in v.to_bits().to_le_bytes() {
9296            *h ^= u64::from(byte);
9297            *h = h.wrapping_mul(0x0000_0100_0000_01b3);
9298        }
9299    }
9300    fn mix_point(h: &mut u64, p: Point) {
9301        mix(h, p.x);
9302        mix(h, p.y);
9303    }
9304    let mut h: u64 = 0xcbf2_9ce4_8422_2325;
9305    match shape {
9306        Shape::Polygon(pts) => {
9307            // The discriminant joins the hash so a polygon and a path of the same points can
9308            // never share an entry: they decode to different geometry.
9309            mix(&mut h, 11.0);
9310            for p in pts {
9311                mix_point(&mut h, *p);
9312            }
9313        }
9314        Shape::Path(path) => {
9315            mix(&mut h, 15.0);
9316            mix(&mut h, rule_bits(path.rule));
9317            for seg in &path.segs {
9318                match seg {
9319                    PathSeg::Move(a) => {
9320                        mix(&mut h, 0.0);
9321                        mix_point(&mut h, *a);
9322                    }
9323                    PathSeg::Line(a) => {
9324                        mix(&mut h, 1.0);
9325                        mix_point(&mut h, *a);
9326                    }
9327                    PathSeg::Quad(c, a) => {
9328                        mix(&mut h, 2.0);
9329                        mix_point(&mut h, *c);
9330                        mix_point(&mut h, *a);
9331                    }
9332                    PathSeg::Cubic(c1, c2, a) => {
9333                        mix(&mut h, 3.0);
9334                        mix_point(&mut h, *c1);
9335                        mix_point(&mut h, *c2);
9336                        mix_point(&mut h, *a);
9337                    }
9338                    PathSeg::Close => mix(&mut h, 4.0),
9339                }
9340            }
9341        }
9342        // Everything else puts its whole geometry in the record's own slots, so there is nothing
9343        // to parse and nothing worth caching.
9344        _ => return 0.0,
9345    }
9346    let masked = h & ((1u64 << 53) - 1);
9347    // 0 means "no key", so the one hash that lands there borrows its neighbor.
9348    if masked == 0 { 1.0 } else { masked as f64 }
9349}
9350
9351/// Append a coordinate to the texts channel: a plain decimal with up to six fractional digits
9352/// and no trailing zeros (`12`, `-0.5`, `183.472938`), never an exponent.
9353///
9354/// Six decimals of a canvas point is a millionth of a point, far below anything a transform an
9355/// app would draw under can bring to a pixel, and the fixed form costs a tenth of the shortest
9356/// round-trip repr: one integer write instead of a float formatter and a temporary `String` per
9357/// coordinate, which was the larger half of a map tile's export on Android. The decoders parse
9358/// with their platform's general float reader, so a value the fixed form cannot carry (a
9359/// non-finite number, a magnitude past 2^53 millionths) falls back to `Display`.
9360fn push_wire_num(out: &mut String, v: f64) {
9361    use std::fmt::Write as _;
9362    const SCALE: f64 = 1_000_000.0;
9363    let scaled = (v * SCALE).round();
9364    if scaled.is_nan() || scaled.abs() >= 9.0e15 {
9365        let _ = write!(out, "{v}");
9366        return;
9367    }
9368    let mut n = scaled as i64;
9369    if n < 0 {
9370        out.push('-');
9371        n = -n;
9372    }
9373    let whole = n / 1_000_000;
9374    let mut frac = n % 1_000_000;
9375    let _ = write!(out, "{whole}");
9376    if frac != 0 {
9377        let mut digits = 6;
9378        while frac % 10 == 0 {
9379            frac /= 10;
9380            digits -= 1;
9381        }
9382        out.push('.');
9383        let _ = write!(out, "{frac:0digits$}");
9384    }
9385}
9386
9387/// Polygon points for the texts channel: `"x,y x,y …"`, numbers as [`push_wire_num`] writes
9388/// them.
9389fn encode_points(pts: &[Point]) -> String {
9390    let mut out = String::with_capacity(pts.len() * 16);
9391    for p in pts {
9392        if !out.is_empty() {
9393            out.push(' ');
9394        }
9395        push_wire_num(&mut out, p.x);
9396        out.push(',');
9397        push_wire_num(&mut out, p.y);
9398    }
9399    out
9400}
9401
9402/// Path segments for the texts channel: `"M x y L x y Q cx cy x y C … Z"`, one token per
9403/// command or number. Coordinates use up to six decimal places, without trailing zeros;
9404/// non-finite values and magnitudes outside the fixed-point range use their display form.
9405pub fn encode_path(path: &Path) -> String {
9406    let mut out = String::with_capacity(path.segs.len() * 16);
9407    let points = |out: &mut String, cmd: char, pts: &[Point]| {
9408        if !out.is_empty() {
9409            out.push(' ');
9410        }
9411        out.push(cmd);
9412        for p in pts {
9413            out.push(' ');
9414            push_wire_num(out, p.x);
9415            out.push(' ');
9416            push_wire_num(out, p.y);
9417        }
9418    };
9419    for seg in &path.segs {
9420        match seg {
9421            PathSeg::Move(p) => points(&mut out, 'M', &[*p]),
9422            PathSeg::Line(p) => points(&mut out, 'L', &[*p]),
9423            PathSeg::Quad(c, p) => points(&mut out, 'Q', &[*c, *p]),
9424            PathSeg::Cubic(a, b, p) => points(&mut out, 'C', &[*a, *b, *p]),
9425            PathSeg::Close => points(&mut out, 'Z', &[]),
9426        }
9427    }
9428    out
9429}
9430
9431/// Clamp a [`DrawOp::Image`] `source` region to the bitmap it indexes (`pixels` wide and high),
9432/// keeping the region's mapping into `rect`: the answer is the part of the region inside the
9433/// bitmap and the part of `rect` it lands in.
9434///
9435/// The single definition of what an out-of-range region means. The mapping is kept rather than
9436/// the clamped part stretched over the whole of `rect`, because that is what every native
9437/// sub-rect draw does on its own (Qt, the HTML canvas) and what the clip-and-scale fallback
9438/// gives for free, so the backends agree. `None` (an empty region, an empty intersection, or a
9439/// bitmap with no pixels) draws nothing. Every backend that replays in Rust calls this; the
9440/// C++/Java/JS decoders repeat the same arithmetic.
9441pub fn clamp_image_source(source: Rect, rect: Rect, pixels: Size) -> Option<(Rect, Rect)> {
9442    if !(source.size.width > 0.0 && source.size.height > 0.0) {
9443        return None;
9444    }
9445    let x0 = source.origin.x.max(0.0);
9446    let y0 = source.origin.y.max(0.0);
9447    let x1 = (source.origin.x + source.size.width).min(pixels.width);
9448    let y1 = (source.origin.y + source.size.height).min(pixels.height);
9449    if !(x1 > x0 && y1 > y0) {
9450        return None;
9451    }
9452    let kx = rect.size.width / source.size.width;
9453    let ky = rect.size.height / source.size.height;
9454    let dest = Rect::new(
9455        rect.origin.x + (x0 - source.origin.x) * kx,
9456        rect.origin.y + (y0 - source.origin.y) * ky,
9457        (x1 - x0) * kx,
9458        (y1 - y0) * ky,
9459    );
9460    Some((Rect::new(x0, y0, x1 - x0, y1 - y0), dest))
9461}
9462
9463/// `FillRule` as a wire number: 0 non-zero, 1 even-odd.
9464fn rule_bits(rule: FillRule) -> f64 {
9465    match rule {
9466        FillRule::NonZero => 0.0,
9467        FillRule::EvenOdd => 1.0,
9468    }
9469}
9470
9471/// Encode a display list for a decoder written in another language (Java, C++, JS): the
9472/// numbers channel, nine `f64` slots per record (`[kind, a, b, c, d, e, f, g, color]`, kinds
9473/// from [`OpCode`]), and the texts channel, one entry per record that carries text or
9474/// variable-length geometry, in record order.
9475pub fn encode_ops(ops: &[DrawOp]) -> (Vec<f64>, Vec<String>) {
9476    encode_ops_into(ops, None)
9477}
9478
9479/// [`encode_ops`] with a third, geometry channel: the points of every path and polygon (fills,
9480/// strokes, clips) as numbers instead of text. Such a record's slot `b` is its offset into the
9481/// channel and slot `c` its count, and its texts entry is empty, so that channel stays
9482/// positional for a decoder that ignores the third one. Paths are written by
9483/// [`path_numbers`], polygons by [`point_numbers`].
9484///
9485/// Formatting a coordinate and parsing it back were, together, half of what a map tile's export
9486/// cost on Android (docs/canvas.md "Exporting"); a decoder that can take an array of doubles
9487/// across its boundary skips both.
9488pub fn encode_ops_with_geometry(ops: &[DrawOp]) -> (Vec<f64>, Vec<String>, Vec<f64>) {
9489    let mut geometry = Vec::new();
9490    let (nums, texts) = encode_ops_into(ops, Some(&mut geometry));
9491    (nums, texts, geometry)
9492}
9493
9494/// A path's segments for the geometry channel: a command code, then its points — `0` move
9495/// (x y), `1` line (x y), `2` quad (cx cy x y), `3` cubic (x1 y1 x2 y2 x y), `4` close.
9496pub fn path_numbers(path: &Path, out: &mut Vec<f64>) {
9497    for seg in &path.segs {
9498        match seg {
9499            PathSeg::Move(p) => out.extend_from_slice(&[0.0, p.x, p.y]),
9500            PathSeg::Line(p) => out.extend_from_slice(&[1.0, p.x, p.y]),
9501            PathSeg::Quad(c, p) => out.extend_from_slice(&[2.0, c.x, c.y, p.x, p.y]),
9502            PathSeg::Cubic(a, b, p) => out.extend_from_slice(&[3.0, a.x, a.y, b.x, b.y, p.x, p.y]),
9503            PathSeg::Close => out.push(4.0),
9504        }
9505    }
9506}
9507
9508/// A polygon's points for the geometry channel: x then y, per point.
9509pub fn point_numbers(pts: &[Point], out: &mut Vec<f64>) {
9510    for p in pts {
9511        out.push(p.x);
9512        out.push(p.y);
9513    }
9514}
9515
9516/// Put a path's or polygon's points on the wire: on the geometry channel when the caller opened
9517/// one, as `numbers` writes them, answering (offset, count) for slots b and c and leaving an
9518/// empty texts entry; else as `text` on the texts channel, answering (0, 0).
9519fn geometry_payload(
9520    geometry: &mut Option<&mut Vec<f64>>,
9521    texts: &mut Vec<String>,
9522    text: impl FnOnce() -> String,
9523    numbers: impl FnOnce(&mut Vec<f64>),
9524) -> (f64, f64) {
9525    match geometry {
9526        Some(g) => {
9527            let offset = g.len();
9528            numbers(g);
9529            texts.push(String::new());
9530            (offset as f64, (g.len() - offset) as f64)
9531        }
9532        None => {
9533            texts.push(text());
9534            (0.0, 0.0)
9535        }
9536    }
9537}
9538
9539fn encode_ops_into(ops: &[DrawOp], mut geometry: Option<&mut Vec<f64>>) -> (Vec<f64>, Vec<String>) {
9540    fn color_bits(c: Color) -> f64 {
9541        let r = (c.r.clamp(0.0, 1.0) * 255.0) as u32;
9542        let g = (c.g.clamp(0.0, 1.0) * 255.0) as u32;
9543        let b = (c.b.clamp(0.0, 1.0) * 255.0) as u32;
9544        let a = (c.a.clamp(0.0, 1.0) * 255.0) as u32;
9545        ((a << 24) | (r << 16) | (g << 8) | b) as f64
9546    }
9547    #[allow(clippy::too_many_arguments)]
9548    fn push(
9549        k: OpCode,
9550        a: f64,
9551        b: f64,
9552        c: f64,
9553        d: f64,
9554        e: f64,
9555        f: f64,
9556        g: f64,
9557        col: Color,
9558        nums: &mut Vec<f64>,
9559    ) {
9560        nums.extend_from_slice(&[k as i32 as f64, a, b, c, d, e, f, g, color_bits(col)]);
9561    }
9562    /// The kind-18 prefix a non-plain stroke style emits, applying to the next stroke record,
9563    /// the same "modifier record" rule the gradient and font records follow. A plain style emits
9564    /// nothing, so a drawing without dashes or caps encodes exactly as it always did.
9565    fn stroke_style_record(style: &StrokeStyle, nums: &mut Vec<f64>, texts: &mut Vec<String>) {
9566        if style.is_plain() {
9567            return;
9568        }
9569        push(
9570            OpCode::StrokeStyle,
9571            match style.cap {
9572                LineCap::Butt => 0.0,
9573                LineCap::Round => 1.0,
9574                LineCap::Square => 2.0,
9575            },
9576            match style.join {
9577                LineJoin::Miter => 0.0,
9578                LineJoin::Round => 1.0,
9579                LineJoin::Bevel => 2.0,
9580            },
9581            style.miter_limit,
9582            style.dash_phase,
9583            style.dash.len() as f64,
9584            0.0,
9585            0.0,
9586            Color::CLEAR,
9587            nums,
9588        );
9589        texts.push(
9590            style
9591                .dash
9592                .iter()
9593                .map(|d| d.to_string())
9594                .collect::<Vec<_>>()
9595                .join(" "),
9596        );
9597    }
9598
9599    /// One shape record (the fill/stroke kinds shared by both ops).
9600    fn shape_record(
9601        stroke: bool,
9602        shape: &Shape,
9603        w: f64,
9604        col: Color,
9605        nums: &mut Vec<f64>,
9606        texts: &mut Vec<String>,
9607        geometry: &mut Option<&mut Vec<f64>>,
9608    ) {
9609        match shape {
9610            Shape::Rect(r) => push(
9611                if stroke {
9612                    OpCode::StrokeRect
9613                } else {
9614                    OpCode::FillRect
9615                },
9616                r.origin.x,
9617                r.origin.y,
9618                r.size.width,
9619                r.size.height,
9620                0.0,
9621                0.0,
9622                w,
9623                col,
9624                nums,
9625            ),
9626            Shape::RoundedRect(r, rad) => push(
9627                if stroke {
9628                    OpCode::StrokeRrect
9629                } else {
9630                    OpCode::FillRrect
9631                },
9632                r.origin.x,
9633                r.origin.y,
9634                r.size.width,
9635                r.size.height,
9636                *rad,
9637                0.0,
9638                w,
9639                col,
9640                nums,
9641            ),
9642            Shape::Ellipse(r) => push(
9643                if stroke {
9644                    OpCode::StrokeEllipse
9645                } else {
9646                    OpCode::FillEllipse
9647                },
9648                r.origin.x,
9649                r.origin.y,
9650                r.size.width,
9651                r.size.height,
9652                0.0,
9653                0.0,
9654                w,
9655                col,
9656                nums,
9657            ),
9658            Shape::Arc {
9659                rect,
9660                start_deg,
9661                sweep_deg,
9662            } => push(
9663                OpCode::StrokeArc,
9664                rect.origin.x,
9665                rect.origin.y,
9666                rect.size.width,
9667                rect.size.height,
9668                *start_deg,
9669                *sweep_deg,
9670                w,
9671                col,
9672                nums,
9673            ),
9674            Shape::Line(p1, p2) => {
9675                push(OpCode::Line, p1.x, p1.y, p2.x, p2.y, 0.0, 0.0, w, col, nums)
9676            }
9677            Shape::Polygon(pts) => {
9678                // Variable-length points ride the texts side-channel ("x,y x,y …"),
9679                // consumed in record order exactly like text payloads, or the geometry
9680                // channel when there is one (slots b, c).
9681                let (offset, count) = geometry_payload(
9682                    geometry,
9683                    texts,
9684                    || encode_points(pts),
9685                    |g| point_numbers(pts, g),
9686                );
9687                push(
9688                    if stroke {
9689                        OpCode::StrokePolygon
9690                    } else {
9691                        OpCode::FillPolygon
9692                    },
9693                    geometry_key(shape),
9694                    offset,
9695                    count,
9696                    0.0,
9697                    0.0,
9698                    0.0,
9699                    w,
9700                    col,
9701                    nums,
9702                );
9703            }
9704            Shape::Path(path) => {
9705                // Same side-channels as Polygon, one token per segment (see `encode_path`).
9706                // The fill rule rides slot f; stroking ignores it.
9707                let (offset, count) = geometry_payload(
9708                    geometry,
9709                    texts,
9710                    || encode_path(path),
9711                    |g| path_numbers(path, g),
9712                );
9713                push(
9714                    if stroke {
9715                        OpCode::StrokePath
9716                    } else {
9717                        OpCode::FillPath
9718                    },
9719                    geometry_key(shape),
9720                    offset,
9721                    count,
9722                    0.0,
9723                    0.0,
9724                    rule_bits(path.rule),
9725                    w,
9726                    col,
9727                    nums,
9728                );
9729            }
9730        }
9731    }
9732    /// A gradient applies to the next shape record, fill or stroke. Geometry per type rides
9733    /// slots a..d and the type discriminant slot f: one record shape, so every decoder keeps a
9734    /// single gradient code path.
9735    fn gradient_record(
9736        geo: [f64; 4],
9737        kind: f64,
9738        stops: &[(f64, Color)],
9739        nums: &mut Vec<f64>,
9740        texts: &mut Vec<String>,
9741    ) {
9742        push(
9743            OpCode::SetGradient,
9744            geo[0],
9745            geo[1],
9746            geo[2],
9747            geo[3],
9748            stops.len() as f64,
9749            kind,
9750            0.0,
9751            Color::CLEAR,
9752            nums,
9753        );
9754        texts.push(
9755            stops
9756                .iter()
9757                .map(|(o, c)| format!("{o},{:08x}", color_bits(*c) as u32))
9758                .collect::<Vec<_>>()
9759                .join(" "),
9760        );
9761    }
9762    let mut nums = Vec::with_capacity(ops.len() * 9);
9763    let mut texts = Vec::new();
9764    for op in ops {
9765        match op {
9766            DrawOp::Fill(shape, paint) => {
9767                // A gradient emits one kind-14 set-gradient record before its shape record;
9768                // the stops ride the texts channel as "offset,aarrggbb offset,aarrggbb …".
9769                // Geometry per type rides slots a..d, the type discriminant slot f: one
9770                // record shape, so every decoder keeps a single gradient code path.
9771                let col = match paint {
9772                    Paint::Solid(c) => *c,
9773                    Paint::Linear(g) => {
9774                        gradient_record(
9775                            [g.start.x, g.start.y, g.end.x, g.end.y],
9776                            0.0,
9777                            &g.stops,
9778                            &mut nums,
9779                            &mut texts,
9780                        );
9781                        // The gradient replaces the shape record's color, but it must be
9782                        // opaque, not clear: Skia-based decoders (Android Paint, OH_Drawing)
9783                        // modulate a shader by the paint alpha, so a clear slot would render
9784                        // the whole gradient invisible.
9785                        Color::WHITE
9786                    }
9787                    Paint::Radial(g) => {
9788                        gradient_record(
9789                            [g.center.x, g.center.y, g.radius, 0.0],
9790                            1.0,
9791                            &g.stops,
9792                            &mut nums,
9793                            &mut texts,
9794                        );
9795                        Color::WHITE
9796                    }
9797                };
9798                shape_record(false, shape, 0.0, col, &mut nums, &mut texts, &mut geometry);
9799            }
9800            DrawOp::Stamp(st) => {
9801                // No copies means no drawing. Some native decoders use an empty point
9802                // buffer to mean an ordinary (unstamped) template, so omit the entire op.
9803                if st.at.is_empty() {
9804                    continue;
9805                }
9806                // A prefix record, then the coordinates, then the template shape record: the
9807                // "applies to the next record" rule the gradient, stroke style and font records
9808                // already follow, so a decoder needs no new kind of state, only one more slot in
9809                // the state it keeps. The template goes last because a decoder has to hold the
9810                // points before it can draw with them.
9811                //
9812                // The points are numbers on the numeric channel, not the texts channel a
9813                // polygon's points ride: this op exists for tens of thousands of them, and
9814                // formatting that many floats into a string every frame would cost more than
9815                // the individual ops it replaces.
9816                let col = match &st.paint {
9817                    Paint::Solid(c) => *c,
9818                    Paint::Linear(g) => {
9819                        gradient_record(
9820                            [g.start.x, g.start.y, g.end.x, g.end.y],
9821                            0.0,
9822                            &g.stops,
9823                            &mut nums,
9824                            &mut texts,
9825                        );
9826                        Color::WHITE
9827                    }
9828                    Paint::Radial(g) => {
9829                        gradient_record(
9830                            [g.center.x, g.center.y, g.radius, 0.0],
9831                            1.0,
9832                            &g.stops,
9833                            &mut nums,
9834                            &mut texts,
9835                        );
9836                        Color::WHITE
9837                    }
9838                };
9839                push(
9840                    OpCode::Stamp,
9841                    st.at.len() as f64,
9842                    0.0,
9843                    0.0,
9844                    0.0,
9845                    0.0,
9846                    0.0,
9847                    0.0,
9848                    Color::CLEAR,
9849                    &mut nums,
9850                );
9851                for chunk in st.at.chunks(4) {
9852                    // Written directly rather than through `push`: this is the one record whose
9853                    // last slot is a coordinate rather than a color, which is what lets four
9854                    // points fit with nothing wasted.
9855                    let mut rec = [
9856                        OpCode::StampPoints as i32 as f64,
9857                        0.0,
9858                        0.0,
9859                        0.0,
9860                        0.0,
9861                        0.0,
9862                        0.0,
9863                        0.0,
9864                        0.0,
9865                    ];
9866                    for (i, p) in chunk.iter().enumerate() {
9867                        rec[1 + i * 2] = p.x;
9868                        rec[2 + i * 2] = p.y;
9869                    }
9870                    nums.extend_from_slice(&rec);
9871                }
9872                match &st.stroke {
9873                    None => shape_record(
9874                        false,
9875                        &st.shape,
9876                        0.0,
9877                        col,
9878                        &mut nums,
9879                        &mut texts,
9880                        &mut geometry,
9881                    ),
9882                    Some(style) => {
9883                        stroke_style_record(style, &mut nums, &mut texts);
9884                        shape_record(
9885                            true,
9886                            &st.shape,
9887                            style.width,
9888                            col,
9889                            &mut nums,
9890                            &mut texts,
9891                            &mut geometry,
9892                        );
9893                    }
9894                }
9895            }
9896            DrawOp::Stroke(shape, paint, style) => {
9897                // A styled stroke emits one kind-18 record first, applying to the next stroke
9898                // only, the same "modifier record" shape the gradient uses, so decoders keep
9899                // one rule: consume, apply to the next shape record, reset.
9900                stroke_style_record(style, &mut nums, &mut texts);
9901                let col = match paint {
9902                    Paint::Solid(c) => *c,
9903                    Paint::Linear(g) => {
9904                        gradient_record(
9905                            [g.start.x, g.start.y, g.end.x, g.end.y],
9906                            0.0,
9907                            &g.stops,
9908                            &mut nums,
9909                            &mut texts,
9910                        );
9911                        Color::WHITE
9912                    }
9913                    Paint::Radial(g) => {
9914                        gradient_record(
9915                            [g.center.x, g.center.y, g.radius, 0.0],
9916                            1.0,
9917                            &g.stops,
9918                            &mut nums,
9919                            &mut texts,
9920                        );
9921                        Color::WHITE
9922                    }
9923                };
9924                shape_record(
9925                    true,
9926                    shape,
9927                    style.width,
9928                    col,
9929                    &mut nums,
9930                    &mut texts,
9931                    &mut geometry,
9932                );
9933            }
9934            DrawOp::Clip(shape) => {
9935                // One record for every clip shape, with the shape kind in slot f and the
9936                // geometry in a..e; a path or polygon puts its points on the texts channel.
9937                // Encoding clips as a variant of `shape_record` instead would need a third
9938                // kind code per shape, which is five more numbers every decoder must learn.
9939                let (kind, geo, extra, payload): (f64, [f64; 4], f64, Option<String>) = match shape
9940                {
9941                    Shape::Rect(r) => (
9942                        0.0,
9943                        [r.origin.x, r.origin.y, r.size.width, r.size.height],
9944                        0.0,
9945                        None,
9946                    ),
9947                    Shape::RoundedRect(r, rad) => (
9948                        1.0,
9949                        [r.origin.x, r.origin.y, r.size.width, r.size.height],
9950                        *rad,
9951                        None,
9952                    ),
9953                    Shape::Ellipse(r) => (
9954                        2.0,
9955                        [r.origin.x, r.origin.y, r.size.width, r.size.height],
9956                        0.0,
9957                        None,
9958                    ),
9959                    // Slot a carries the geometry key for these two sub-kinds only. The other
9960                    // three put real geometry there, which is why the key rides the same slot
9961                    // the payload-bearing kinds leave empty; b and c are the geometry
9962                    // channel's offset and count when there is one.
9963                    Shape::Path(p) => {
9964                        let (offset, count) = geometry_payload(
9965                            &mut geometry,
9966                            &mut texts,
9967                            || encode_path(p),
9968                            |g| path_numbers(p, g),
9969                        );
9970                        (
9971                            3.0,
9972                            [geometry_key(shape), offset, count, 0.0],
9973                            rule_bits(p.rule),
9974                            None,
9975                        )
9976                    }
9977                    Shape::Polygon(pts) => {
9978                        let (offset, count) = geometry_payload(
9979                            &mut geometry,
9980                            &mut texts,
9981                            || encode_points(pts),
9982                            |g| point_numbers(pts, g),
9983                        );
9984                        (4.0, [geometry_key(shape), offset, count, 0.0], 0.0, None)
9985                    }
9986                    // A clip to a line or an arc has no interior to clip to. Clipping to an
9987                    // empty region would blank everything after it, so clip to the shape's
9988                    // bounds instead: wrong in the same direction as no clip at all.
9989                    Shape::Line(..) | Shape::Arc { .. } => {
9990                        let r = shape.bounds();
9991                        (
9992                            0.0,
9993                            [r.origin.x, r.origin.y, r.size.width, r.size.height],
9994                            0.0,
9995                            None,
9996                        )
9997                    }
9998                };
9999                push(
10000                    OpCode::Clip,
10001                    geo[0],
10002                    geo[1],
10003                    geo[2],
10004                    geo[3],
10005                    extra,
10006                    kind,
10007                    0.0,
10008                    Color::CLEAR,
10009                    &mut nums,
10010                );
10011                if let Some(s) = payload {
10012                    texts.push(s);
10013                }
10014            }
10015            DrawOp::Text {
10016                text,
10017                at,
10018                size,
10019                color,
10020                anchor,
10021                font,
10022            } => {
10023                if *font != CanvasFont::default() {
10024                    push(
10025                        OpCode::SetFont,
10026                        f64::from(font.css_weight()),
10027                        f64::from(u8::from(font.italic)),
10028                        0.0,
10029                        0.0,
10030                        0.0,
10031                        0.0,
10032                        0.0,
10033                        Color::CLEAR,
10034                        &mut nums,
10035                    );
10036                    texts.push(
10037                        font.family_str()
10038                            .replace([FONT_LIST_FIELD, FONT_LIST_FAMILY], " "),
10039                    );
10040                }
10041                push(
10042                    OpCode::Text,
10043                    at.x,
10044                    at.y,
10045                    0.0,
10046                    0.0,
10047                    *size,
10048                    anchor.pack(),
10049                    0.0,
10050                    *color,
10051                    &mut nums,
10052                );
10053                texts.push(text.clone());
10054            }
10055            DrawOp::Image {
10056                image,
10057                rect,
10058                opacity,
10059                source,
10060            } => {
10061                if let Some(src) = source {
10062                    push(
10063                        OpCode::ImageSource,
10064                        src.origin.x,
10065                        src.origin.y,
10066                        src.size.width,
10067                        src.size.height,
10068                        0.0,
10069                        0.0,
10070                        0.0,
10071                        Color::CLEAR,
10072                        &mut nums,
10073                    );
10074                }
10075                push(
10076                    OpCode::Image,
10077                    rect.origin.x,
10078                    rect.origin.y,
10079                    rect.size.width,
10080                    rect.size.height,
10081                    image.0 as f64,
10082                    *opacity,
10083                    0.0,
10084                    Color::CLEAR,
10085                    &mut nums,
10086                );
10087            }
10088            DrawOp::Save => push(
10089                OpCode::Save,
10090                0.0,
10091                0.0,
10092                0.0,
10093                0.0,
10094                0.0,
10095                0.0,
10096                0.0,
10097                Color::CLEAR,
10098                &mut nums,
10099            ),
10100            DrawOp::Restore => push(
10101                OpCode::Restore,
10102                0.0,
10103                0.0,
10104                0.0,
10105                0.0,
10106                0.0,
10107                0.0,
10108                0.0,
10109                Color::CLEAR,
10110                &mut nums,
10111            ),
10112            DrawOp::Concat(m) => push(
10113                OpCode::Concat,
10114                m.a,
10115                m.b,
10116                m.c,
10117                m.d,
10118                m.tx,
10119                m.ty,
10120                0.0,
10121                Color::CLEAR,
10122                &mut nums,
10123            ),
10124        }
10125    }
10126    (nums, texts)
10127}
10128
10129#[cfg(test)]
10130mod font_list_tests {
10131    use super::*;
10132
10133    #[test]
10134    fn css_weights_round_trip_and_snap_to_the_nearest_rung() {
10135        for w in FontWeight::ALL {
10136            assert_eq!(FontWeight::from_css(w.css()), w);
10137        }
10138        assert_eq!(FontWeight::from_css(0), FontWeight::UltraLight);
10139        assert_eq!(FontWeight::from_css(350), FontWeight::Regular); // ties go heavier
10140        assert_eq!(FontWeight::from_css(649), FontWeight::Semibold);
10141        assert_eq!(FontWeight::from_css(1200), FontWeight::Black);
10142    }
10143
10144    fn sans() -> FontFamilyInfo {
10145        FontFamilyInfo {
10146            family: "Day Sans".into(),
10147            faces: vec![
10148                FontFace {
10149                    name: "Regular".into(),
10150                    weight: FontWeight::Regular,
10151                    italic: false,
10152                },
10153                FontFace {
10154                    name: "Bold".into(),
10155                    weight: FontWeight::Bold,
10156                    italic: false,
10157                },
10158                FontFace {
10159                    name: "Light Italic".into(),
10160                    weight: FontWeight::Light,
10161                    italic: true,
10162                },
10163            ],
10164        }
10165    }
10166
10167    #[test]
10168    fn face_for_prefers_the_slant_then_the_nearest_weight() {
10169        let f = sans();
10170        assert!(f.has_bold() && f.has_italic());
10171        assert_eq!(f.face_for(FontWeight::Bold, false).unwrap().name, "Bold");
10172        assert_eq!(
10173            f.face_for(FontWeight::Semibold, false).unwrap().name,
10174            "Bold"
10175        );
10176        assert_eq!(
10177            f.face_for(FontWeight::Medium, false).unwrap().name,
10178            "Regular"
10179        );
10180        let tie = FontFamilyInfo {
10181            family: "Tie".into(),
10182            faces: vec![
10183                FontFace {
10184                    name: "Light".into(),
10185                    weight: FontWeight::Light,
10186                    italic: false,
10187                },
10188                FontFace {
10189                    name: "Bold".into(),
10190                    weight: FontWeight::Bold,
10191                    italic: false,
10192                },
10193            ],
10194        };
10195        // Medium sits 200 from both; the heavier face wins the tie.
10196        assert_eq!(
10197            tie.face_for(FontWeight::Medium, false).unwrap().name,
10198            "Bold"
10199        );
10200        assert_eq!(
10201            f.face_for(FontWeight::Black, true).unwrap().name,
10202            "Light Italic"
10203        );
10204        let none = FontFamilyInfo {
10205            family: "Empty".into(),
10206            faces: vec![],
10207        };
10208        assert!(none.face_for(FontWeight::Regular, false).is_none());
10209        assert!(!none.has_bold());
10210    }
10211
10212    #[test]
10213    fn the_shim_list_format_decodes_tolerantly() {
10214        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\
10215                 \u{1e}\u{1e}Day Mono\u{1f}Regular\u{1f}400\u{1f}0\u{1e}Faceless";
10216        let list = parse_font_list(s);
10217        assert_eq!(list.len(), 3);
10218        assert_eq!(list[0].family, "Day Sans");
10219        assert_eq!(list[0].faces.len(), 2, "the bad weight is skipped");
10220        assert_eq!(list[0].faces[1].name, "Bold Italic"); // synthesized from 700 + italic
10221        assert_eq!(list[1].family, "Day Mono");
10222        assert_eq!(list[2].family, "Faceless");
10223        assert!(list[2].faces.is_empty());
10224    }
10225
10226    #[test]
10227    fn approximate_metrics_scale_with_size_and_length() {
10228        let m = TextMetrics::approximate("abc", 10.0);
10229        assert_eq!((m.width, m.height, m.ascent), (18.0, 12.0, 9.0));
10230        assert_eq!(TextMetrics::approximate("", 10.0).width, 0.0);
10231    }
10232
10233    #[test]
10234    fn a_default_canvas_font_is_the_platform_face() {
10235        let f = CanvasFont::default();
10236        assert_eq!((f.family_str(), f.css_weight(), f.italic), ("", 0, false));
10237    }
10238}
10239
10240#[cfg(test)]
10241mod image_header_tests {
10242    use super::*;
10243
10244    /// A 4×2 PNG: signature, then an IHDR whose width and height are big-endian.
10245    fn png(w: u32, h: u32) -> Vec<u8> {
10246        let mut v = vec![0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a];
10247        v.extend(13u32.to_be_bytes());
10248        v.extend(b"IHDR");
10249        v.extend(w.to_be_bytes());
10250        v.extend(h.to_be_bytes());
10251        v
10252    }
10253
10254    /// A JPEG whose frame header sits behind one other segment, so the walk has to skip it.
10255    fn jpeg(w: u16, h: u16) -> Vec<u8> {
10256        let mut v = vec![0xFF, 0xD8]; // SOI
10257        v.extend([0xFF, 0xE0, 0x00, 0x04, 0x00, 0x00]); // APP0, length 4
10258        v.extend([0xFF, 0xC0, 0x00, 0x11, 0x08]); // SOF0, length 17, precision 8
10259        v.extend(h.to_be_bytes());
10260        v.extend(w.to_be_bytes());
10261        v
10262    }
10263
10264    #[test]
10265    fn a_header_states_the_size_before_anything_decodes() {
10266        assert_eq!(ImageFormat::dimensions(&png(512, 512)), Some((512, 512)));
10267        assert_eq!(ImageFormat::dimensions(&png(1, 65535)), Some((1, 65535)));
10268        // The JPEG walk must step over the APP0 segment to reach the frame header.
10269        assert_eq!(ImageFormat::dimensions(&jpeg(640, 480)), Some((640, 480)));
10270
10271        let mut gif = b"GIF89a".to_vec();
10272        gif.extend(320u16.to_le_bytes());
10273        gif.extend(240u16.to_le_bytes());
10274        assert_eq!(ImageFormat::dimensions(&gif), Some((320, 240)));
10275
10276        // A top-down BMP states its height as a negative number; the size is still positive.
10277        let mut bmp = b"BM".to_vec();
10278        bmp.resize(18, 0);
10279        bmp.extend(64i32.to_le_bytes());
10280        bmp.extend((-32i32).to_le_bytes());
10281        assert_eq!(ImageFormat::dimensions(&bmp), Some((64, 32)));
10282    }
10283
10284    #[test]
10285    fn a_truncated_or_unknown_header_answers_nothing_rather_than_a_guess() {
10286        assert_eq!(ImageFormat::dimensions(&[]), None);
10287        // The signature is there but the IHDR is not.
10288        assert_eq!(ImageFormat::dimensions(&png(8, 8)[..12]), None);
10289        // Not an image at all.
10290        assert_eq!(ImageFormat::dimensions(b"not an image"), None);
10291        // A JPEG that never reaches a frame header must not loop or invent a size.
10292        assert_eq!(
10293            ImageFormat::dimensions(&[0xFF, 0xD8, 0xFF, 0xE0, 0x00, 0x04, 0, 0]),
10294            None
10295        );
10296    }
10297}
10298
10299#[cfg(test)]
10300mod encode_ops_tests {
10301    use super::*;
10302
10303    /// The texts channel carries plain decimals: whole numbers without a point, fractions to
10304    /// six places with the trailing zeros gone, and the general form only past what the fixed
10305    /// one can hold.
10306    #[test]
10307    fn wire_numbers_are_short_plain_decimals() {
10308        let text = |v: f64| {
10309            let mut out = String::new();
10310            push_wire_num(&mut out, v);
10311            out
10312        };
10313        assert_eq!(text(12.0), "12");
10314        assert_eq!(text(-0.5), "-0.5");
10315        assert_eq!(text(183.472_938_472_938_4), "183.472938");
10316        assert_eq!(text(0.1 + 0.2), "0.3");
10317        assert_eq!(text(-0.000_000_1), "0");
10318        assert_eq!(text(2.000_05), "2.00005");
10319        assert_eq!(text(f64::INFINITY), "inf");
10320        assert_eq!(text(1.0e17), "100000000000000000");
10321        let path = Path {
10322            segs: vec![
10323                PathSeg::Move(Point::new(1.5, 2.0)),
10324                PathSeg::Line(Point::new(-3.25, 4.0)),
10325                PathSeg::Close,
10326            ],
10327            rule: FillRule::NonZero,
10328        };
10329        assert_eq!(encode_path(&path), "M 1.5 2 L -3.25 4 Z");
10330        assert_eq!(
10331            encode_points(&[Point::new(0.0, 0.0), Point::new(10.0, 0.125)]),
10332            "0,0 10,0.125"
10333        );
10334    }
10335
10336    /// With the geometry channel open, a path's and a polygon's points leave the texts channel
10337    /// (an empty entry keeps it positional) for the numbers, with offset and count in slots b
10338    /// and c; without it the texts channel carries them exactly as before.
10339    #[test]
10340    fn geometry_channel_carries_points_as_numbers() {
10341        let path = Shape::Path(Path {
10342            segs: vec![
10343                PathSeg::Move(Point::new(1.0, 2.0)),
10344                PathSeg::Quad(Point::new(3.0, 4.0), Point::new(5.0, 6.0)),
10345                PathSeg::Close,
10346            ],
10347            rule: FillRule::EvenOdd,
10348        });
10349        let polygon = Shape::Polygon(vec![Point::new(0.0, 0.0), Point::new(7.0, 8.0)]);
10350        let ops = vec![
10351            DrawOp::Clip(path.clone()),
10352            DrawOp::Fill(path.clone(), Paint::Solid(Color::WHITE)),
10353            DrawOp::Stroke(
10354                polygon.clone(),
10355                Paint::Solid(Color::WHITE),
10356                StrokeStyle::default(),
10357            ),
10358        ];
10359        let (nums, texts, geometry) = encode_ops_with_geometry(&ops);
10360        assert_eq!(texts, vec!["", "", ""]);
10361        assert_eq!(
10362            geometry,
10363            vec![
10364                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,
10365                6.0, 4.0, 0.0, 0.0, 7.0, 8.0
10366            ]
10367        );
10368        // The clip (kind 17, sub-kind 3 in f) and the fill (kind 15) point at the two copies
10369        // of the path, the stroke (kind 12) at the polygon's four numbers.
10370        assert_eq!((nums[0], nums[2], nums[3], nums[6]), (17.0, 0.0, 9.0, 3.0));
10371        assert_eq!(
10372            (nums[9], nums[11], nums[12], nums[15]),
10373            (15.0, 9.0, 9.0, 1.0)
10374        );
10375        assert_eq!((nums[18], nums[20], nums[21]), (12.0, 18.0, 4.0));
10376        let (plain_nums, plain_texts) = encode_ops(&ops);
10377        assert_eq!(plain_texts[1], "M 1 2 Q 3 4 5 6 Z");
10378        assert_eq!(plain_texts[2], "0,0 7,8");
10379        assert_eq!((plain_nums[11], plain_nums[12]), (0.0, 0.0));
10380    }
10381
10382    /// A region outside the bitmap is clamped to it with its mapping into the rect kept, and an
10383    /// empty intersection draws nothing.
10384    #[test]
10385    fn image_source_clamps_to_the_bitmap() {
10386        let px = Size::new(64.0, 32.0);
10387        let dest = Rect::new(100.0, 200.0, 32.0, 32.0); // 2 points per source pixel
10388        assert_eq!(
10389            clamp_image_source(Rect::new(-8.0, -8.0, 16.0, 16.0), dest, px),
10390            Some((
10391                Rect::new(0.0, 0.0, 8.0, 8.0),
10392                Rect::new(116.0, 216.0, 16.0, 16.0)
10393            ))
10394        );
10395        assert_eq!(
10396            clamp_image_source(Rect::new(60.0, 28.0, 16.0, 16.0), dest, px),
10397            Some((
10398                Rect::new(60.0, 28.0, 4.0, 4.0),
10399                Rect::new(100.0, 200.0, 8.0, 8.0)
10400            ))
10401        );
10402        assert_eq!(
10403            clamp_image_source(Rect::new(16.0, 8.0, 16.0, 16.0), dest, px),
10404            Some((Rect::new(16.0, 8.0, 16.0, 16.0), dest))
10405        );
10406        assert_eq!(
10407            clamp_image_source(Rect::new(64.0, 0.0, 8.0, 8.0), dest, px),
10408            None
10409        );
10410        assert_eq!(
10411            clamp_image_source(Rect::new(0.0, 0.0, 0.0, 8.0), dest, px),
10412            None
10413        );
10414        assert_eq!(
10415            clamp_image_source(Rect::new(0.0, 0.0, 8.0, 8.0), dest, Size::new(0.0, 0.0)),
10416            None
10417        );
10418    }
10419
10420    /// The wire codes are a frozen dense table: any gap, duplicate, or variant missing from
10421    /// `ALL` breaks a decoder somewhere, so it must break here first.
10422    #[test]
10423    fn op_codes_are_dense_and_round_trip() {
10424        for (i, code) in OpCode::ALL.into_iter().enumerate() {
10425            assert_eq!(code as i32, i as i32, "{code:?} broke wire density");
10426            assert_eq!(OpCode::from_wire(i as f64), Some(code));
10427        }
10428        assert_eq!(OpCode::from_wire(OpCode::ALL.len() as f64), None);
10429        assert_eq!(OpCode::from_wire(-1.0), None);
10430        assert_eq!(OpCode::from_wire(0.5), None);
10431    }
10432
10433    /// Reference decode of a display list covering every op arm: the record stream must be
10434    /// whole 9-slot records of known codes, and the texts channel must carry exactly one
10435    /// entry per text-carrying record, in order: the contract every shim decoder assumes.
10436    #[test]
10437    fn encode_ops_emits_whole_records_and_matched_text_payloads() {
10438        let r = Rect::new(1.0, 2.0, 3.0, 4.0);
10439        let red = Color::rgb(1.0, 0.0, 0.0);
10440        let ops = vec![
10441            DrawOp::Fill(Shape::Rect(r), Paint::Solid(red)),
10442            DrawOp::Stroke(Shape::Rect(r), Paint::Solid(red), StrokeStyle::round(2.0)),
10443            DrawOp::Fill(Shape::RoundedRect(r, 5.0), Paint::Solid(red)),
10444            DrawOp::Fill(Shape::Ellipse(r), Paint::Solid(red)),
10445            // The documented asymmetry: a filled arc encodes as StrokeArc with width 0.
10446            DrawOp::Fill(
10447                Shape::Arc {
10448                    rect: r,
10449                    start_deg: 0.0,
10450                    sweep_deg: 90.0,
10451                },
10452                Paint::Solid(red),
10453            ),
10454            DrawOp::Stroke(
10455                Shape::Line(Point::new(0.0, 0.0), Point::new(9.0, 9.0)),
10456                Paint::Solid(red),
10457                StrokeStyle::width(1.0),
10458            ),
10459            DrawOp::Fill(
10460                Shape::Polygon(vec![
10461                    Point::new(0.0, 0.0),
10462                    Point::new(4.0, 0.0),
10463                    Point::new(2.0, 3.0),
10464                ]),
10465                Paint::Solid(red),
10466            ),
10467            DrawOp::Fill(
10468                Shape::Path(Path {
10469                    segs: vec![
10470                        PathSeg::Move(Point::new(0.0, 0.0)),
10471                        PathSeg::Line(Point::new(5.0, 5.0)),
10472                        PathSeg::Close,
10473                    ],
10474                    rule: FillRule::EvenOdd,
10475                }),
10476                Paint::Linear(LinearGradient::new(
10477                    UnitPoint::new(0.0, 0.0),
10478                    UnitPoint::new(1.0, 1.0),
10479                    vec![(0.0, red), (1.0, Color::WHITE)],
10480                )),
10481            ),
10482            DrawOp::Clip(Shape::Rect(r)),
10483            DrawOp::Clip(Shape::Polygon(vec![
10484                Point::new(0.0, 0.0),
10485                Point::new(1.0, 0.0),
10486                Point::new(0.0, 1.0),
10487            ])),
10488            DrawOp::Text {
10489                text: "hi".into(),
10490                at: Point::new(7.0, 8.0),
10491                size: 12.0,
10492                color: red,
10493                anchor: TextAnchor::LEADING,
10494                font: CanvasFont::default(),
10495            },
10496            DrawOp::Text {
10497                text: "bold".into(),
10498                at: Point::new(7.0, 8.0),
10499                size: 12.0,
10500                color: red,
10501                anchor: TextAnchor::CENTERED,
10502                font: CanvasFont {
10503                    family: Some("Day Sans".into()),
10504                    weight: Some(FontWeight::Bold),
10505                    italic: true,
10506                },
10507            },
10508            DrawOp::Save,
10509            DrawOp::Concat(Affine::IDENTITY),
10510            DrawOp::Restore,
10511            DrawOp::Image {
10512                image: BitmapId(7),
10513                rect: r,
10514                opacity: 0.5,
10515                source: None,
10516            },
10517            DrawOp::Image {
10518                image: BitmapId(7),
10519                rect: r,
10520                opacity: 1.0,
10521                source: Some(Rect::new(16.0, 32.0, 8.0, 8.0)),
10522            },
10523        ];
10524        let (nums, texts) = encode_ops(&ops);
10525        assert_eq!(nums.len() % 9, 0, "partial record on the wire");
10526
10527        let mut expected_texts = 0usize;
10528        let mut decoded = Vec::new();
10529        for rec in nums.chunks(9) {
10530            let code = OpCode::from_wire(rec[0])
10531                .unwrap_or_else(|| panic!("unknown op code {} on the wire", rec[0]));
10532            decoded.push(code);
10533            expected_texts += match code {
10534                OpCode::Text
10535                | OpCode::FillPolygon
10536                | OpCode::StrokePolygon
10537                | OpCode::SetGradient
10538                | OpCode::FillPath
10539                | OpCode::StrokePath
10540                | OpCode::StrokeStyle
10541                | OpCode::SetFont => 1,
10542                // Clip carries a payload only for its path (3) / polygon (4) sub-kinds.
10543                OpCode::Clip => usize::from(rec[6] == 3.0 || rec[6] == 4.0),
10544                _ => 0,
10545            };
10546        }
10547        assert_eq!(
10548            texts.len(),
10549            expected_texts,
10550            "texts channel out of step with the records that consume it"
10551        );
10552        // No payload may carry the transport separator.
10553        assert!(texts.iter().all(|t| !t.contains('\u{1f}')));
10554
10555        let expected = {
10556            use OpCode::*;
10557            vec![
10558                FillRect,
10559                StrokeStyle, // ::round(2.0) is not plain, so the style modifier precedes
10560                StrokeRect,
10561                FillRrect,
10562                FillEllipse,
10563                StrokeArc, // the filled arc's stroke encoding…
10564                Line,
10565                FillPolygon,
10566                SetGradient, // gradient precedes its shape record
10567                FillPath,
10568                Clip,
10569                Clip,
10570                Text,
10571                SetFont, // a non-default font precedes its text record…
10572                Text,
10573                Save,
10574                Concat,
10575                Restore,
10576                Image,
10577                ImageSource, // a region precedes its image record; a whole-image draw has none
10578                Image,
10579            ]
10580        };
10581        assert_eq!(decoded, expected);
10582        // The bitmap id rides the numeric channel intact (an f64 holds a u64 id exactly well
10583        // past any id this process will mint), and nothing of an image reaches the texts channel.
10584        let img = nums
10585            .chunks(9)
10586            .find(|r| r[0] == OpCode::Image as i32 as f64)
10587            .expect("Image record");
10588        assert_eq!(&img[1..7], &[1.0, 2.0, 3.0, 4.0, 7.0, 0.5]);
10589        // The region rides its own prefix record, in bitmap pixels, with nothing else in it.
10590        let src = nums
10591            .chunks(9)
10592            .find(|r| r[0] == OpCode::ImageSource as i32 as f64)
10593            .expect("ImageSource record");
10594        assert_eq!(&src[1..8], &[16.0, 32.0, 8.0, 8.0, 0.0, 0.0, 0.0]);
10595        // …carrying the CSS weight and the slant, with the family on the texts channel.
10596        let font_rec = nums
10597            .chunks(9)
10598            .find(|r| r[0] == OpCode::SetFont as i32 as f64)
10599            .expect("SetFont record");
10600        assert_eq!(&font_rec[1..3], &[700.0, 1.0]);
10601        assert_eq!(texts.iter().filter(|t| *t == "Day Sans").count(), 1);
10602        // …with width 0, per the documented asymmetry.
10603        let arc = nums
10604            .chunks(9)
10605            .find(|r| r[0] == OpCode::StrokeArc as i32 as f64);
10606        assert_eq!(arc.map(|r| r[7]), Some(0.0));
10607        // A gradient-filled shape's color slot is opaque white, never clear (Skia decoders
10608        // modulate the shader by it).
10609        let path_rec = nums
10610            .chunks(9)
10611            .find(|r| r[0] == OpCode::FillPath as i32 as f64);
10612        assert_eq!(
10613            path_rec.map(|r| r[8] as u32),
10614            Some(0xFFFF_FFFF),
10615            "gradient shape record must carry opaque white"
10616        );
10617    }
10618
10619    #[test]
10620    fn variable_length_geometry_carries_a_content_key() {
10621        let path = |x: f64| {
10622            Shape::Path(Path {
10623                segs: vec![
10624                    PathSeg::Move(Point::new(x, 0.0)),
10625                    PathSeg::Cubic(
10626                        Point::new(1.0, 1.0),
10627                        Point::new(2.0, 2.0),
10628                        Point::new(3.0, 3.0),
10629                    ),
10630                    PathSeg::Close,
10631                ],
10632                rule: FillRule::NonZero,
10633            })
10634        };
10635        let poly = Shape::Polygon(vec![
10636            Point::new(0.0, 0.0),
10637            Point::new(1.0, 0.0),
10638            Point::new(0.0, 1.0),
10639        ]);
10640
10641        // Equal geometry keys equal though the two were built separately. The key exists for
10642        // this: a draw closure rebuilds its paths from scratch on every frame.
10643        assert_eq!(geometry_key(&path(0.0)), geometry_key(&path(0.0)));
10644        assert_ne!(geometry_key(&path(0.0)), geometry_key(&path(1.0)));
10645        // The fill rule decides what the path draws, so it belongs to the key.
10646        let even_odd = Shape::Path(Path {
10647            segs: match path(0.0) {
10648                Shape::Path(p) => p.segs,
10649                _ => unreachable!(),
10650            },
10651            rule: FillRule::EvenOdd,
10652        });
10653        assert_ne!(geometry_key(&path(0.0)), geometry_key(&even_odd));
10654        // A polygon and a path decode to different geometry and never share an entry.
10655        assert_ne!(geometry_key(&poly), geometry_key(&path(0.0)));
10656        // Fixed-size shapes keep 0: their geometry rides the record's own slots.
10657        assert_eq!(
10658            geometry_key(&Shape::Rect(Rect::new(0.0, 0.0, 1.0, 1.0))),
10659            0.0
10660        );
10661        // And a key survives an f64 wire slot exactly, which is what the 53-bit mask buys.
10662        let k = geometry_key(&path(0.0));
10663        assert!(
10664            k > 0.0 && k < (1u64 << 53) as f64 && k.fract() == 0.0,
10665            "{k}"
10666        );
10667
10668        // It reaches the wire in slot a, for exactly the ops whose payload rides the texts
10669        // channel, and never displaces geometry that is already there.
10670        let (nums, _) = encode_ops(&[
10671            DrawOp::Fill(path(0.0), Paint::Solid(Color::WHITE)),
10672            DrawOp::Fill(poly.clone(), Paint::Solid(Color::WHITE)),
10673            DrawOp::Clip(path(0.0)),
10674            DrawOp::Clip(Shape::Rect(Rect::new(1.0, 2.0, 3.0, 4.0))),
10675        ]);
10676        let slot_a = |code: OpCode| {
10677            nums.chunks(9)
10678                .find(|r| r[0] == code as i32 as f64)
10679                .unwrap_or_else(|| panic!("no {code:?} record"))[1]
10680        };
10681        assert_eq!(slot_a(OpCode::FillPath), geometry_key(&path(0.0)));
10682        assert_eq!(slot_a(OpCode::FillPolygon), geometry_key(&poly));
10683        let clips: Vec<&[f64]> = nums
10684            .chunks(9)
10685            .filter(|r| r[0] == OpCode::Clip as i32 as f64)
10686            .collect();
10687        assert_eq!(clips[0][1], geometry_key(&path(0.0)), "path clip keys");
10688        assert_eq!(
10689            &clips[1][1..5],
10690            &[1.0, 2.0, 3.0, 4.0],
10691            "a rect clip still puts its geometry in a..d"
10692        );
10693    }
10694}
10695
10696#[cfg(test)]
10697mod markup_tests {
10698    use super::*;
10699
10700    fn bold(range: std::ops::Range<usize>) -> TextRun {
10701        TextRun::font(
10702            range,
10703            FontSpec {
10704                style: Font::Body,
10705                weight: Some(FontWeight::Bold),
10706                ..Default::default()
10707            },
10708        )
10709    }
10710
10711    #[test]
10712    fn plain_text_is_escaped_in_both_dialects() {
10713        // The case a translated string will find: markup metacharacters in the content.
10714        let text = "5 < 6 & \"quoted\" <b>not bold</b>";
10715        for d in [MarkupDialect::Pango, MarkupDialect::QtHtml] {
10716            let m = runs_to_markup(text, &[], d, 16.0);
10717            assert!(!m.contains("<b>"), "content tag survived into markup: {m}");
10718            assert!(m.contains("&lt;b&gt;"), "{m}");
10719            assert!(m.contains("&amp;"), "{m}");
10720            assert!(m.contains("5 &lt; 6"), "{m}");
10721        }
10722    }
10723
10724    #[test]
10725    fn a_styled_run_is_wrapped_and_its_text_escaped() {
10726        let text = "a <b> c";
10727        let m = runs_to_markup(text, &[bold(2..5)], MarkupDialect::Pango, 16.0);
10728        assert_eq!(m, "a <b>&lt;b&gt;</b> c");
10729    }
10730
10731    #[test]
10732    fn color_and_monospace_differ_per_dialect() {
10733        let text = "code";
10734        let run = TextRun {
10735            range: 0..4,
10736            font: FontSpec {
10737                style: Font::Body,
10738                monospace: true,
10739                ..Default::default()
10740            },
10741            color: Some(Color::rgb(1.0, 0.0, 0.0)),
10742            ..TextRun::default()
10743        };
10744        let pango = runs_to_markup(text, std::slice::from_ref(&run), MarkupDialect::Pango, 16.0);
10745        assert!(pango.contains("foreground=\"#ff0000\""), "{pango}");
10746        assert!(pango.contains("font_family=\"monospace\""), "{pango}");
10747        let qt = runs_to_markup(
10748            text,
10749            std::slice::from_ref(&run),
10750            MarkupDialect::QtHtml,
10751            16.0,
10752        );
10753        assert!(qt.contains("color:#ff0000"), "{qt}");
10754        // Qt takes its fixed face from <code>: a `font-family:monospace` style attribute
10755        // renders proportional (observed on Qt 6.11).
10756        assert!(qt.contains("<code>") && qt.contains("</code>"), "{qt}");
10757    }
10758
10759    #[test]
10760    fn the_new_attributes_reach_both_dialects() {
10761        let run = TextRun {
10762            range: 0..2,
10763            font: FontSpec::default().scaled(1.5),
10764            background: Some(Color::rgb(0.0, 1.0, 0.0)),
10765            underline: Underline::Single,
10766            ..TextRun::default()
10767        };
10768        let pango = runs_to_markup("hi", std::slice::from_ref(&run), MarkupDialect::Pango, 16.0);
10769        assert!(pango.contains("background=\"#00ff00\""), "{pango}");
10770        // Pango takes an absolute size in 1/1024 pt (16 pt base × 1.5 = 24 pt), because the
10771        // relative attributes are Pango 1.50's and an unknown attribute empties the whole label.
10772        assert!(pango.contains("size=\"24576\""), "{pango}");
10773        assert!(pango.contains("<u>hi</u>"), "{pango}");
10774        let qt = runs_to_markup(
10775            "hi",
10776            std::slice::from_ref(&run),
10777            MarkupDialect::QtHtml,
10778            16.0,
10779        );
10780        assert!(qt.contains("background-color:#00ff00"), "{qt}");
10781        // Qt takes points: 16 pt base × 1.5 (observed; its CSS subset ignores a percentage).
10782        assert!(qt.contains("font-size:24pt"), "{qt}");
10783        assert!(qt.contains("<u>hi</u>"), "{qt}");
10784    }
10785
10786    #[test]
10787    fn a_link_target_is_escaped_too() {
10788        // A URL carrying `&` between query parameters is ordinary, and unescaped it truncates
10789        // the attribute and swallows the rest of the label.
10790        let text = "docs";
10791        let run = TextRun {
10792            range: 0..4,
10793            link: Some("https://x.dev/?a=1&b=2".into()),
10794            ..TextRun::default()
10795        };
10796        let m = runs_to_markup(text, &[run], MarkupDialect::Pango, 16.0);
10797        assert!(m.contains("a=1&amp;b=2"), "{m}");
10798    }
10799
10800    #[test]
10801    fn tags_nest_and_close_in_reverse() {
10802        let run = TextRun {
10803            range: 0..2,
10804            font: FontSpec {
10805                style: Font::Body,
10806                weight: Some(FontWeight::Bold),
10807                italic: true,
10808                ..Default::default()
10809            },
10810            strikethrough: true,
10811            link: Some("u".into()),
10812            ..TextRun::default()
10813        };
10814        let m = runs_to_markup("hi", &[run], MarkupDialect::Pango, 16.0);
10815        assert_eq!(m, "<a href=\"u\"><b><i><s>hi</s></i></b></a>");
10816    }
10817
10818    #[test]
10819    fn runs_out_of_bounds_are_skipped_not_panicked() {
10820        // `runs_are_valid` rejects these upstream; this is the belt-and-braces path.
10821        let m = runs_to_markup("hi", &[bold(0..99)], MarkupDialect::Pango, 16.0);
10822        assert_eq!(m, "hi");
10823    }
10824
10825    #[test]
10826    fn validation_catches_the_four_ways_runs_go_wrong() {
10827        let text = "héllo";
10828        assert!(runs_are_valid(text, &[bold(0..1)]).is_ok());
10829        // Overlapping.
10830        assert!(runs_are_valid(text, &[bold(0..3), bold(2..4)]).is_err());
10831        // Past the end.
10832        assert!(runs_are_valid(text, &[bold(0..99)]).is_err());
10833        // Inverted. Built from parts, since a literal `3..1` is a clippy error in its own right.
10834        let (hi, lo) = (3, 1);
10835        assert!(runs_are_valid(text, &[bold(hi..lo)]).is_err());
10836        // Splitting the 2-byte `é`.
10837        assert!(runs_are_valid(text, &[bold(0..2)]).is_err());
10838    }
10839}
10840
10841#[cfg(test)]
10842mod route_of_url_tests {
10843    use super::route_of_url;
10844
10845    #[test]
10846    fn strips_the_scheme_and_keeps_route_and_params() {
10847        assert_eq!(
10848            route_of_url("notes://mail/inbox?hint=x"),
10849            "mail/inbox?hint=x"
10850        );
10851        assert_eq!(route_of_url("notes://home"), "home");
10852        // No scheme: already a route, unchanged.
10853        assert_eq!(route_of_url("mail/inbox"), "mail/inbox");
10854        assert_eq!(route_of_url(""), "");
10855        // Percent-encoding passes through; the route parser decodes, not this mapping.
10856        assert_eq!(route_of_url("n://a/b%2Fc?q=1%202"), "a/b%2Fc?q=1%202");
10857    }
10858}
10859
10860#[cfg(test)]
10861mod builtin_kind_tests {
10862    use super::*;
10863
10864    /// Every built-in round-trips through its wire key, and the keys are unique. Guards the
10865    /// `builtin_kinds!` expansion: a copy-paste slip in the table would alias two kinds.
10866    #[test]
10867    fn keys_round_trip_and_are_unique() {
10868        let mut seen = std::collections::HashSet::new();
10869        for &b in Builtin::ALL {
10870            assert_eq!(Builtin::from_key(b.key()), Some(b), "{b:?} key round-trip");
10871            assert!(seen.insert(b.key()), "duplicate key {:?}", b.key());
10872            assert!(
10873                b.key().starts_with("day."),
10874                "built-in {b:?} must use the reserved `day.` prefix"
10875            );
10876        }
10877    }
10878
10879    /// The `kinds::*` constants are the enum's keys, so the two spellings cannot drift.
10880    #[test]
10881    fn kinds_constants_match_the_enum() {
10882        assert_eq!(kinds::LABEL, Builtin::Label.key());
10883        assert_eq!(kinds::LIST_CELL, Builtin::ListCell.key());
10884        assert_eq!(kinds::COVER, Builtin::Cover.key());
10885        assert_eq!(kinds::INSPECTOR, Builtin::Inspector.key());
10886        assert_eq!(kinds::TREE, Builtin::Tree.key());
10887        // 19 after `Tabs`/`TabsPage` retired (the tab bar is a NAV presentation, not a kind),
10888        // +2 for the inspector split and its panes (docs/inspector.md), +1 for the tree
10889        // (docs/tree.md).
10890        assert_eq!(Builtin::ALL.len(), 25);
10891    }
10892
10893    /// An extension piece's kind is not a built-in.
10894    #[test]
10895    fn extension_kinds_are_not_builtin() {
10896        assert_eq!(Builtin::from_key("acme.combobox"), None);
10897        assert_eq!(Builtin::from_key("day.not_a_real_kind"), None);
10898    }
10899}
10900
10901#[cfg(test)]
10902mod locale_tests {
10903    /// POSIX locale strings are not BCP-47 tags, and "C" is not a language; that difference is
10904    /// the job of `posix_locale_hints` (§12.2).
10905    #[test]
10906    fn posix_hints_parse_and_drop_the_c_locale() {
10907        // The parsing is exercised through the same normalization the function applies.
10908        let normalize = |v: &str| v.split('.').next().unwrap_or(v).replace('_', "-");
10909        assert_eq!(normalize("fr_FR.UTF-8"), "fr-FR");
10910        assert_eq!(normalize("en_US"), "en-US");
10911        assert_eq!(normalize("C"), "C");
10912        // A real read never panics whatever this host's environment holds.
10913        let hints = super::posix_locale_hints();
10914        assert!(
10915            hints
10916                .iter()
10917                .all(|h| !h.is_empty() && h != "C" && h != "POSIX")
10918        );
10919    }
10920}
10921
10922#[cfg(test)]
10923mod sidetable_tests {
10924    use super::sidetable::{SideTable, sweep};
10925    use std::cell::Cell;
10926    use std::rc::Rc;
10927
10928    /// The registry exists so that one `sweep(key)` clears every table without any
10929    /// table needing its own line in a backend's `release()`.
10930    #[test]
10931    fn sweep_clears_every_registered_table_and_runs_teardowns() {
10932        let torn = Rc::new(Cell::new(0u32));
10933        let t2 = torn.clone();
10934        let plain: SideTable<&'static str> = SideTable::new();
10935        let hooked: SideTable<u32> = SideTable::with_teardown(move |_| t2.set(t2.get() + 1));
10936
10937        plain.insert(7, "a");
10938        hooked.insert(7, 1);
10939        hooked.insert(8, 2);
10940        sweep(7);
10941        assert!(!plain.contains(7));
10942        assert!(!hooked.contains(7), "swept from every table");
10943        assert!(hooked.contains(8), "other keys untouched");
10944        assert_eq!(torn.get(), 1, "teardown ran for the swept value");
10945
10946        // remove() runs the teardown too; take() bypasses it for ownership transfer.
10947        hooked.remove(8);
10948        assert_eq!(torn.get(), 2);
10949        hooked.insert(9, 3);
10950        assert_eq!(hooked.take(9), Some(3));
10951        assert_eq!(torn.get(), 2, "take() skips the hook");
10952    }
10953
10954    #[test]
10955    fn contain_returns_default_on_panic() {
10956        let ok = super::ffi_guard::contain(0i32, || 5);
10957        assert_eq!(ok, 5);
10958        let prev = std::panic::take_hook();
10959        std::panic::set_hook(Box::new(|_| {}));
10960        let contained = super::ffi_guard::contain(-1i32, || panic!("boom"));
10961        std::panic::set_hook(prev);
10962        assert_eq!(contained, -1, "the panic must not escape the guard");
10963    }
10964}
10965
10966#[cfg(test)]
10967mod cursor_tests {
10968    use super::Cursor;
10969
10970    /// Every named cursor has a distinct CSS keyword, and `NAMED` lists each exactly once: the
10971    /// gallery and every backend's table key on the keyword.
10972    #[test]
10973    fn named_cursors_have_distinct_css_names() {
10974        let mut seen = std::collections::BTreeSet::new();
10975        for c in Cursor::NAMED.iter() {
10976            assert!(
10977                seen.insert(c.css_name().to_string()),
10978                "duplicate: {}",
10979                c.css_name()
10980            );
10981            assert!(!matches!(c, Cursor::Native(_)));
10982        }
10983        assert_eq!(seen.len(), Cursor::NAMED.len());
10984        assert_eq!(Cursor::native("dragCopy").css_name(), "dragCopy");
10985        assert_eq!(Cursor::default(), Cursor::Default);
10986    }
10987}
10988
10989#[cfg(test)]
10990mod text_anchor_tests {
10991    /// The anchor arithmetic every backend repeats. A drawing whose text lands in the wrong
10992    /// corner is a per-backend bug that only a screenshot catches, so the shared definition is
10993    /// pinned here and each shim is written to match it.
10994    #[test]
10995    fn text_anchor_offsets_place_the_line_box() {
10996        use crate::props::TextAlign;
10997        use crate::{TextAnchor, TextVAlign};
10998        // A 40-wide, 20-tall line box whose baseline sits 16 below its top.
10999        let (w, h, asc) = (40.0, 20.0, 16.0);
11000        let at = |ha, va| TextAnchor { h: ha, v: va }.offset(w, h, asc);
11001
11002        // The default is the drawing origin itself, every backend's native "draw here".
11003        assert_eq!(at(TextAlign::Leading, TextVAlign::Top), (0.0, 0.0));
11004        assert_eq!(TextAnchor::default(), TextAnchor::LEADING);
11005        // Horizontal: the box's leading edge, its middle, its trailing edge.
11006        assert_eq!(at(TextAlign::Center, TextVAlign::Top).0, -20.0);
11007        assert_eq!(at(TextAlign::Trailing, TextVAlign::Top).0, -40.0);
11008        // Vertical: top, middle, the baseline itself, bottom.
11009        assert_eq!(at(TextAlign::Leading, TextVAlign::Middle).1, -10.0);
11010        assert_eq!(at(TextAlign::Leading, TextVAlign::Baseline).1, -16.0);
11011        assert_eq!(at(TextAlign::Leading, TextVAlign::Bottom).1, -20.0);
11012        // The two named placements are the ones the two-variant enum used to have.
11013        assert_eq!(TextAnchor::CENTERED.offset(w, h, asc), (-20.0, -10.0));
11014        assert_eq!(TextAnchor::TRAILING.offset(w, h, asc), (-40.0, 0.0));
11015    }
11016
11017    /// The wire code the serializing backends (qt, xaml, arkui, android, web) decode by hand.
11018    #[test]
11019    fn text_anchor_packs_into_one_slot_and_round_trips() {
11020        use crate::props::TextAlign;
11021        use crate::{TextAnchor, TextVAlign};
11022        let mut seen = std::collections::BTreeSet::new();
11023        for h in [TextAlign::Leading, TextAlign::Center, TextAlign::Trailing] {
11024            for v in [
11025                TextVAlign::Top,
11026                TextVAlign::Middle,
11027                TextVAlign::Baseline,
11028                TextVAlign::Bottom,
11029            ] {
11030                let a = TextAnchor { h, v };
11031                let code = a.pack();
11032                assert!(
11033                    (0.0..=11.0).contains(&code),
11034                    "{code} outside the packed range"
11035                );
11036                assert!(seen.insert(code as u64), "two anchors share code {code}");
11037                assert_eq!(TextAnchor::unpack(code), a);
11038            }
11039        }
11040        assert_eq!(seen.len(), 12);
11041        // The shims decode as `h = code / 4`, `v = code % 4` in integer arithmetic.
11042        assert_eq!(TextAnchor::LEADING.pack(), 0.0);
11043        assert_eq!(TextAnchor::CENTERED.pack(), 5.0);
11044        // Junk answers the default rather than failing inside a native draw callback.
11045        assert_eq!(TextAnchor::unpack(-3.0), TextAnchor::LEADING);
11046        assert_eq!(TextAnchor::unpack(99.0), TextAnchor::unpack(11.0));
11047    }
11048
11049    /// The two shapes a backend's own metrics arrive in. Both land on the same contract: the line
11050    /// box's top-leading corner is the origin, and `ink` is relative to it.
11051    #[test]
11052    fn metrics_convert_from_a_backends_own_shape() {
11053        use crate::{Rect, TextMetrics};
11054        // Baseline-relative, y up-negative; Core Text, Skia and Qt all report like this.
11055        let m = TextMetrics::from_baseline(
11056            40.0,
11057            16.0,
11058            4.0,
11059            11.0,
11060            // Ink starting 1 right of the origin, from 11 above the baseline to 2 below it.
11061            Rect::new(1.0, -11.0, 38.0, 13.0),
11062        );
11063        assert_eq!(
11064            (m.width, m.height, m.ascent, m.cap_height),
11065            (40.0, 20.0, 16.0, 11.0)
11066        );
11067        // Shifted down by the ascent: the ink now starts 5 below the line box's top, which is
11068        // where a cap begins in a slot whose baseline is at 16.
11069        assert_eq!(m.ink, Rect::new(1.0, 5.0, 38.0, 13.0));
11070        assert_eq!(m.ascent - m.cap_height, m.ink.origin.y);
11071
11072        // The eight-slot wire form is already line-box-relative and passes straight through.
11073        let w = TextMetrics::from_slots(&[40.0, 20.0, 16.0, 11.0, 1.0, 5.0, 38.0, 13.0]);
11074        assert_eq!(w, m);
11075    }
11076
11077    /// The fallback must be usable, not merely present: a caller frames text with it on a toolkit
11078    /// that cannot measure, and every relation it relies on has to hold.
11079    #[test]
11080    fn the_approximation_is_internally_consistent() {
11081        use crate::TextMetrics;
11082        let m = TextMetrics::approximate("Agy", 20.0);
11083        assert!(m.ascent < m.height, "the baseline sits inside the line box");
11084        assert!(
11085            m.cap_height < m.ascent,
11086            "caps do not reach above the ascent"
11087        );
11088        // The ink box is the whole line box: a superset, so an overlap test using it can only be
11089        // too cautious. Never a claim to be tighter than it knows.
11090        assert_eq!(m.ink.origin.x, 0.0);
11091        assert_eq!(m.ink.origin.y, 0.0);
11092        assert_eq!(m.ink.size.width, m.width);
11093        assert_eq!(m.ink.size.height, m.height);
11094        // Empty text still answers a usable (zero-width, full-height) slot.
11095        let e = TextMetrics::approximate("", 20.0);
11096        assert_eq!(e.width, 0.0);
11097        assert!(e.height > 0.0);
11098    }
11099}
11100
11101#[cfg(test)]
11102mod cap_list_tests {
11103    use super::Cap;
11104
11105    #[test]
11106    fn every_capability_is_listed_once_in_its_place() {
11107        for (i, cap) in Cap::ALL.iter().enumerate() {
11108            assert_eq!(cap.ordinal(), i, "{cap:?} is out of place in Cap::ALL");
11109        }
11110    }
11111}