day_spec/lib.rs
1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3
4//! day-spec: the toolkit specification (DESIGN.md §8).
5//!
6//! Backends depend only on this crate (never on day-core). One backend is linked per binary;
7//! `day-core` is monomorphized over the concrete [`Toolkit`].
8
9use std::any::Any;
10use std::collections::HashMap;
11
12pub use day_geometry::*;
13// `Support` is in `Toolkit`'s signatures and every backend trampoline runs through the guard, so
14// a backend reaches both from the contract crate it already depends on. day-process owns them.
15pub use day_process::{Support, ffi_guard};
16// The link-time registry crate `renderer!` expands to, so a renderer needs no dependency on it.
17pub use day_process::linkme;
18
19pub mod controls;
20pub use controls::datetime::{DayDate, DayTime, now_epoch_millis, now_epoch_secs};
21
22pub mod applications;
23pub mod capture;
24pub mod ink;
25/// Markdown: inline text to styled runs (docs/text-runs.md) and documents to blocks
26/// (docs/markdown-view.md). Lives here rather than in day-pieces because it produces
27/// `TextRun`s, and every format codec beside it reads the same model.
28pub mod markdown;
29pub use ink::{Ink, Palette, SystemColor, resolved_stops};
30pub mod render;
31pub use render::fill_measure;
32/// Bundled-resource random-access API + the per-backend `ResourceOpener` hook (§18.3).
33pub mod resource;
34/// Styled text: the document model `label().runs(…)` renders and `day-piece-text-editor` edits,
35/// with the Markdown / HTML / RTF codecs over it (docs/texteditor.md).
36pub mod styled;
37/// Import and export for [`StyledText`]: Markdown, HTML and RTF (docs/texteditor.md).
38pub mod styled_codec;
39pub mod transfer;
40
41pub use resource::{
42 AssetDir, AssetName, FontFamily, ImageName, Resource, ResourceOpener, VectorName,
43 resolve_asset_dir, resolve_image_file, resource, set_resource_opener,
44};
45pub use styled::{
46 Decoration, DecorationStyle, ListStyle, ParagraphRun, ParagraphStyle, RunStyle, StyledText,
47 coalesce_runs, paragraph_bounds, paragraphs_are_valid,
48};
49pub use styled_codec::{
50 DocStyle, html_to_styled, markdown_to_styled, rtf_to_styled, styled_to_html,
51 styled_to_markdown, styled_to_rtf,
52};
53
54/// Bundled custom fonts: name-table parsing, runtime font directory, family → file resolution
55/// (§18.4). Shared by the CLI stagers and the backends' startup registration. Lives in the leaf
56/// `day-fonts` crate (pure std, no `day-geometry`), re-exported here so `day_spec::fonts::…` is
57/// unchanged for the backends while the CLI can depend on `day-fonts` alone.
58pub use day_fonts as fonts;
59
60/// The route inside a deep-link URL (docs/deep-links.md): everything after `scheme://`,
61/// query included (`notes://mail/inbox?hint=x` ⇒ `mail/inbox?hint=x`). A string with no
62/// scheme passes through unchanged (it is already a route). One definition, shared by every
63/// platform's intake and the dayscript `deep_link` step, so a URL maps to the same route
64/// bytes everywhere; percent-decoding stays with the route parser (docs/navigation.md).
65#[must_use]
66pub fn route_of_url(url: &str) -> String {
67 match url.split_once("://") {
68 Some((_, rest)) => rest.to_string(),
69 None => url.to_string(),
70 }
71}
72
73// ---------------------------------------------------------------------------
74// Identity
75// ---------------------------------------------------------------------------
76
77/// Interned piece-kind key, e.g. `"day.label"` or `"acme.combobox"`.
78pub type PieceKind = &'static str;
79
80/// Declare the built-in piece vocabulary once: the [`Builtin`] enum, its string keys, and the
81/// `kinds::*` constants are all generated from this list, so they can never drift apart.
82///
83/// Adding a variant here is a breaking change for backends: every `Toolkit` must decide how
84/// to realize the new kind, and the exhaustive `match Builtin` in each backend's `realize`
85/// turns that decision into a compile error rather than a runtime placeholder.
86macro_rules! builtin_kinds {
87 ($( $(#[$meta:meta])* $variant:ident = $konst:ident => $key:literal ),+ $(,)?) => {
88 /// Every piece kind Day itself defines (§5.3). Backends match on this exhaustively in
89 /// `realize`; anything outside it is an extension piece resolved through the
90 /// [`Registry`] by its string [`PieceKind`].
91 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
92 pub enum Builtin {
93 $( $(#[$meta])* $variant, )+
94 }
95
96 impl Builtin {
97 /// This kind's wire key: the same string as the matching `kinds::*` constant.
98 pub const fn key(self) -> PieceKind {
99 match self { $( Builtin::$variant => $key, )+ }
100 }
101
102 /// The built-in this key names, or `None` for an extension piece's kind.
103 pub fn from_key(kind: PieceKind) -> Option<Builtin> {
104 match kind {
105 $( $key => Some(Builtin::$variant), )+
106 _ => None,
107 }
108 }
109
110 /// Every built-in, in declaration order (conformance tests iterate it).
111 pub const ALL: &'static [Builtin] = &[ $( Builtin::$variant, )+ ];
112 }
113
114 /// The built-in piece keys as plain strings, for the registry and the `PieceKind` API.
115 pub mod kinds {
116 $( $(#[$meta])* pub const $konst: super::PieceKind = super::Builtin::$variant.key(); )+
117 }
118 };
119}
120
121builtin_kinds! {
122 /// A dumb native panel (the column/row/stack backing).
123 Container = CONTAINER => "day.container",
124 Label = LABEL => "day.label",
125 Button = BUTTON => "day.button",
126 Toggle = TOGGLE => "day.toggle",
127 Slider = SLIDER => "day.slider",
128 TextField = TEXT_FIELD => "day.text_field",
129 /// A native multi-line text editor (docs/textarea.md). Built-in since 2026-07 (previously
130 /// the satellite `day-piece-textarea`).
131 TextArea = TEXT_AREA => "day.text_area",
132 /// A native option picker with menu/segmented/inline stylings (docs/picker.md). Built-in
133 /// since 2026-07 (previously the satellite `day-piece-picker`).
134 Picker = PICKER => "day.picker",
135 Divider = DIVIDER => "day.divider",
136 Scroll = SCROLL => "day.scroll",
137 Image = IMAGE => "day.image",
138 /// Progress indicator: determinate bar (fraction) or indeterminate spinner.
139 Progress = PROGRESS => "day.progress",
140 Canvas = CANVAS => "day.canvas",
141 /// Navigation host (docs/navigation.md): stack on mobile, split panes on desktop.
142 Nav = NAV => "day.nav",
143 /// One destination's native container inside a NAV host.
144 NavPage = NAV_PAGE => "day.nav_page",
145 /// Native navigation item list (docs/navigation.md): `NSOutlineView` source list /
146 /// `GtkListBox` navigation-sidebar / `QListWidget` / `UITableView` rows with chevrons.
147 NavMenu = NAV_MENU => "day.nav_menu",
148 /// Native recycling list (docs/list.md): `NSTableView` / `UITableView` / `RecyclerView` /
149 /// `GtkListView` / `QListView`. Owns scrolling + cell reuse; Day binds row content on demand.
150 List = LIST => "day.list",
151 /// A recycled row's content anchor inside a `LIST`; Day adopts the native cell as its handle.
152 /// Adopted, never realized: `Toolkit::adopt` wraps the native cell, so backends' `realize`
153 /// never sees this kind.
154 ListCell = LIST_CELL => "day.list_cell",
155 /// Native hierarchical tree (docs/tree.md): `NSOutlineView` / sidebar collection list /
156 /// `GtkListView`+`TreeListModel` / WinUI `TreeView` / ArkTS `TreeView`. Rows nest, disclose, and
157 /// drag-to-reparent; Day binds row content on demand through `Toolkit::attach_tree`.
158 /// Row cells are adopted (the same `LIST_CELL` anchor path as `List`).
159 Tree = TREE => "day.tree",
160 /// A fullscreen cover (docs/cover.md): a modal surface presented over the whole window,
161 /// edge-to-edge, driven by `CoverPatch::{Present,Dismiss}`. The handle is the cover's
162 /// content container; its frame is native-owned while presented (the backend sizes it to
163 /// the safe area and reports it via `Event::FrameChanged`).
164 Cover = COVER => "day.cover",
165 /// Content beside a trailing inspector pane (docs/inspector.md): the native split whose
166 /// second pane is a show/hidable properties panel. Exactly two `INSPECTOR_PANE` children:
167 /// the content, then the panel (`InspectorPaneProps::panel`). Only realized where
168 /// `Cap::Inspector` answers `Native`; everywhere else the `inspector` piece composes the
169 /// pane from plain containers and this kind never reaches the backend.
170 Inspector = INSPECTOR => "day.inspector",
171 /// One pane's container inside an `INSPECTOR` host: the `NAV_PAGE` of the inspector split.
172 /// Its frame is native-owned (the splitter/dock sizes it), reported via
173 /// `Event::FrameChanged` on this node; Day lays the pane's content out inside it.
174 InspectorPane = INSPECTOR_PANE => "day.inspector_pane",
175 /// Two panes with a divider the user drags (docs/split.md): the toolkit's own splitter,
176 /// side by side or stacked (`SplitProps::axis`), the first pane's share bound to the app
177 /// (`SplitProps::fraction`, reported back as `Event::ValueChanged`). Exactly two
178 /// `SPLIT_PANE` children, first then second. Only realized where `Cap::Split` answers
179 /// `Native`; everywhere else the `split` piece composes the panes and draws the divider
180 /// itself, and this kind never reaches the backend.
181 Split = SPLIT => "day.split",
182 /// One pane's container inside a `SPLIT` host: native-owned frame (the splitter sizes it),
183 /// reported via `Event::FrameChanged` on this node, like an `INSPECTOR_PANE`.
184 SplitPane = SPLIT_PANE => "day.split_pane",
185 /// A list row's standard content (docs/list.md "List items"): a leading icon, a title, an
186 /// optional subtitle and trailing detail, and a check mark, drawn the way the platform
187 /// draws its own list rows: a `UIListContentView` with the cell's default content
188 /// configuration, a Material list item, an `NSTableCellView`'s image and text, a GTK row
189 /// box. Only realized where `Cap::ListItem` answers `Native`; everywhere else the
190 /// `list_item` piece composes the same content and this kind never reaches the backend.
191 ListItem = LIST_ITEM => "day.list_item",
192}
193
194/// Whether a kind is worth asking [`Toolkit::first_baseline`] about (docs/baseline.md).
195///
196/// A blocklist, not an allowlist: the structural and graphic kinds below have no text of their
197/// own, and everything else (including extension pieces like the date/time pickers, whose kinds
198/// day-spec has never heard of) is assumed to be worth asking. An extension piece that turns
199/// out to have no baseline answers `None`, which costs one query; an allowlist would instead
200/// silently leave every extension piece centered, which is the bug this shape avoids.
201#[must_use]
202pub fn kind_has_baseline(kind: PieceKind) -> bool {
203 !matches!(
204 Builtin::from_key(kind),
205 Some(
206 Builtin::Container
207 | Builtin::Scroll
208 | Builtin::Divider
209 | Builtin::Image
210 | Builtin::Canvas
211 | Builtin::Slider
212 | Builtin::Toggle
213 | Builtin::Progress
214 | Builtin::Nav
215 | Builtin::NavPage
216 | Builtin::NavMenu
217 | Builtin::Split
218 | Builtin::SplitPane
219 | Builtin::List
220 | Builtin::ListCell
221 | Builtin::Cover
222 | Builtin::Inspector
223 | Builtin::InspectorPane
224 )
225 )
226}
227
228/// Placeholder leaves: the one hole in Day's rendering that is invisible to a screenshot.
229///
230/// When a backend has no renderer for a kind it realizes a visible `⟨kind⟩` label rather than
231/// failing. That is the right runtime behavior, but it means a missing renderer looks like a
232/// rendered app: the walkthrough passes, and the gallery's validator (which counts distinct
233/// colors) sees nothing wrong. That is how a stale `skip_on:` survived in the showcase
234/// walkthrough after the renderer it skipped had landed.
235///
236/// So every backend reports here instead of keeping its own warn-once set. The table is process-
237/// wide and append-only, which gives dayscript's `assert_no_placeholders` something to assert on
238/// (`crates/day-script`): a placeholder becomes a test failure instead of a silent gap.
239pub mod placeholder {
240 use super::PieceKind;
241 use std::collections::BTreeSet;
242 use std::sync::{Mutex, OnceLock};
243
244 fn table() -> &'static Mutex<BTreeSet<PieceKind>> {
245 static TABLE: OnceLock<Mutex<BTreeSet<PieceKind>>> = OnceLock::new();
246 TABLE.get_or_init(|| Mutex::new(BTreeSet::new()))
247 }
248
249 /// Record that `toolkit` had no renderer for `kind` and warn, once per kind, however many
250 /// nodes of it are realized. Call from a backend's `realize` fallback arm.
251 pub fn report(kind: PieceKind, toolkit: &str) {
252 let Ok(mut seen) = table().lock() else { return };
253 if seen.insert(kind) {
254 log::warn!(
255 "no renderer for piece kind \"{kind}\" on {toolkit} — is the piece's \
256 {toolkit} feature enabled? (rendering a placeholder)"
257 );
258 }
259 }
260
261 /// Every kind that has rendered a placeholder in this process, sorted. Empty is the goal.
262 #[must_use]
263 pub fn seen() -> Vec<PieceKind> {
264 table()
265 .lock()
266 .map_or_default(|s| s.iter().copied().collect())
267 }
268}
269
270/// Downcast a realize/update payload to the props/patch type a backend arm expects,
271/// warning (once per kind, via [`placeholder::report`]) instead of panicking on a
272/// mismatch. A mismatch means a piece registered under a builtin key or a day-core
273/// regression; degrade to the placeholder path, never abort: most backend arms run
274/// inside native up-calls, where a panic is a process kill.
275pub fn props_of<'a, T: 'static>(
276 kind: PieceKind,
277 toolkit: &str,
278 any: &'a dyn std::any::Any,
279) -> Option<&'a T> {
280 let p = any.downcast_ref::<T>();
281 if p.is_none() {
282 placeholder::report(kind, toolkit);
283 }
284 p
285}
286
287/// Pointer-keyed per-view side tables with an automatic release sweep.
288///
289/// Backends keep auxiliary per-view state in thread-local maps keyed by the native
290/// handle's address. Historically each map needed its own line in `release()`, a
291/// checklist that drifted repeatedly (missed entries have produced both leaks and
292/// stale-pointer CI segfaults, since a freed address gets recycled). A [`crate::sidetable::SideTable`]
293/// registers itself with a per-thread sweeper list at construction, so a backend's
294/// `release()` calls [`crate::sidetable::sweep`] once and every table, present and future, drops its
295/// entry for that handle, running its teardown hook if one was given.
296pub mod sidetable {
297 use std::cell::RefCell;
298 use std::collections::HashMap;
299 use std::rc::Rc;
300
301 /// One table's "remove this key" hook, registered at construction.
302 type Sweeper = Rc<dyn Fn(usize)>;
303
304 thread_local! {
305 static SWEEPERS: RefCell<Vec<Sweeper>> = const { RefCell::new(Vec::new()) };
306 }
307
308 /// A pointer-keyed map swept automatically by [`crate::sidetable::sweep`]. Construct inside a
309 /// `thread_local!` initializer; the optional teardown hook runs for each removed
310 /// value (release a retained native object, dispose an owned child, …), both on sweep
311 /// and on plain [`SideTable::remove`], so teardown cannot be bypassed by accident.
312 pub struct SideTable<V: 'static> {
313 map: Rc<RefCell<HashMap<usize, V>>>,
314 teardown: Option<Rc<dyn Fn(V)>>,
315 }
316
317 impl<V> Default for SideTable<V> {
318 fn default() -> Self {
319 Self::new()
320 }
321 }
322
323 impl<V> SideTable<V> {
324 #[must_use]
325 pub fn new() -> Self {
326 Self::build(None)
327 }
328
329 /// A table whose values need active teardown when their view goes away.
330 pub fn with_teardown(teardown: impl Fn(V) + 'static) -> Self {
331 Self::build(Some(Rc::new(teardown)))
332 }
333
334 fn build(teardown: Option<Rc<dyn Fn(V)>>) -> Self {
335 let map: Rc<RefCell<HashMap<usize, V>>> = Rc::default();
336 let (m, t) = (map.clone(), teardown.clone());
337 SWEEPERS.with(|s| {
338 s.borrow_mut().push(Rc::new(move |key| {
339 // Remove under the borrow, tear down outside it: hooks may re-enter
340 // toolkit code that reads other tables.
341 let v = m.borrow_mut().remove(&key);
342 if let (Some(v), Some(t)) = (v, &t) {
343 t(v);
344 }
345 }));
346 });
347 SideTable { map, teardown }
348 }
349
350 pub fn insert(&self, key: usize, value: V) -> Option<V> {
351 self.map.borrow_mut().insert(key, value)
352 }
353
354 /// Remove and tear down the entry (returns `None` always when a teardown hook
355 /// exists, because the value is consumed by it; use [`SideTable::take`] to skip it).
356 #[must_use]
357 pub fn remove(&self, key: usize) -> Option<V> {
358 let v = self.map.borrow_mut().remove(&key)?;
359 match &self.teardown {
360 Some(t) => {
361 t(v);
362 None
363 }
364 None => Some(v),
365 }
366 }
367
368 /// Remove without running the teardown hook (the caller takes ownership).
369 #[must_use]
370 pub fn take(&self, key: usize) -> Option<V> {
371 self.map.borrow_mut().remove(&key)
372 }
373
374 #[must_use]
375 pub fn contains(&self, key: usize) -> bool {
376 self.map.borrow().contains_key(&key)
377 }
378
379 #[must_use]
380 pub fn get(&self, key: usize) -> Option<V>
381 where
382 V: Clone,
383 {
384 self.map.borrow().get(&key).cloned()
385 }
386
387 /// Run `f` on the value in place (returns `None` if absent).
388 pub fn with<R>(&self, key: usize, f: impl FnOnce(&mut V) -> R) -> Option<R> {
389 self.map.borrow_mut().get_mut(&key).map(f)
390 }
391
392 /// Run `f` over every `(key, value)` (immutable; do not re-enter this table).
393 pub fn for_each(&self, mut f: impl FnMut(usize, &V)) {
394 for (k, v) in self.map.borrow().iter() {
395 f(*k, v);
396 }
397 }
398 }
399
400 /// Remove `key` from every table registered on this thread, running teardowns.
401 /// Call once from a backend's `release()` (and once per auxiliary native object a
402 /// release frees, e.g. an owned content container).
403 pub fn sweep(key: usize) {
404 // Clone the sweeper list first: a teardown may construct a new SideTable
405 // (registering a sweeper) without deadlocking on the borrow.
406 let sweepers: Vec<Sweeper> = SWEEPERS.with(|s| s.borrow().clone());
407 for f in sweepers {
408 f(key);
409 }
410 }
411}
412
413/// The painting threads behind the offscreen exports (docs/canvas.md "Exporting").
414///
415/// `Toolkit::render_bitmap` answers with an event, so a toolkit whose 2-D API can draw into a
416/// memory surface from any thread paints there and posts the answer back to the UI thread. The
417/// pool is shared by every toolkit in the process: a few threads, one short of the cores and
418/// never more than four, so a screenful of requests cannot starve the UI thread or the app's
419/// own work. Jobs run in the order they were queued.
420///
421/// Not built for the web: a browser's `createImageBitmap` is already asynchronous, and
422/// `wasm32-unknown-unknown` has no threads to spawn.
423#[cfg(not(target_arch = "wasm32"))]
424pub mod offscreen {
425 use std::sync::atomic::{AtomicUsize, Ordering};
426 use std::sync::{Arc, Mutex, OnceLock, mpsc};
427
428 type Job = Box<dyn FnOnce() + Send + 'static>;
429
430 static QUEUE: OnceLock<Mutex<mpsc::Sender<Job>>> = OnceLock::new();
431 /// How many painting threads started; zero means every job runs where it was queued.
432 static WORKERS: AtomicUsize = AtomicUsize::new(0);
433
434 /// Run `job` on a painting thread, or inline when none could be started. A panic inside
435 /// `job` is contained ([`crate::ffi_guard::contain`]) so one bad replay cannot take the
436 /// thread, and with it every later export, down; the job itself should answer its request
437 /// in that case, which is why toolkits wrap the paint and not the post.
438 pub fn spawn(job: impl FnOnce() + Send + 'static) {
439 let queue = QUEUE.get_or_init(start);
440 if WORKERS.load(Ordering::Acquire) == 0 {
441 crate::ffi_guard::contain((), job);
442 return;
443 }
444 let job: Job = Box::new(job);
445 // The receivers live as long as the process, so a refused send means every worker left
446 // its loop; the job still runs, inline, rather than a request going unanswered.
447 let refused = match queue.lock() {
448 Ok(sender) => sender.send(job).err().map(|e| e.0),
449 Err(_) => Some(job),
450 };
451 if let Some(job) = refused {
452 crate::ffi_guard::contain((), job);
453 }
454 }
455
456 fn start() -> Mutex<mpsc::Sender<Job>> {
457 let (tx, rx) = mpsc::channel::<Job>();
458 let rx = Arc::new(Mutex::new(rx));
459 let want = std::thread::available_parallelism()
460 .map_or(2, std::num::NonZero::get)
461 .saturating_sub(1)
462 .clamp(1, 4);
463 let mut started = 0;
464 for i in 0..want {
465 let rx = Arc::clone(&rx);
466 let spawned = std::thread::Builder::new()
467 .name(format!("day-paint-{i}"))
468 .spawn(move || {
469 loop {
470 // The lock is held only while waiting for the next job, never while
471 // running one, so the other workers queue behind it fairly.
472 let next = match rx.lock() {
473 Ok(guard) => guard.recv(),
474 Err(_) => return,
475 };
476 match next {
477 Ok(job) => crate::ffi_guard::contain((), job),
478 Err(_) => return,
479 }
480 }
481 });
482 match spawned {
483 Ok(_) => started += 1,
484 Err(e) => log::error!("day-spec: could not start a painting thread: {e}"),
485 }
486 }
487 WORKERS.store(started, Ordering::Release);
488 Mutex::new(tx)
489 }
490}
491
492/// Realized-node identity as seen by backends (day-core's slotmap key, FFI-encoded).
493#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
494pub struct NodeId(pub u64);
495
496/// Default navigation sidebar width (split presentation) until the pane reports its size.
497/// Semantic container surfaces (see `ContainerProps::role`): each backend maps a role to its
498/// own theme-adaptive material so the fill tracks light/dark mode without app code.
499#[derive(Clone, Copy, Debug, PartialEq, Eq)]
500pub enum SurfaceRole {
501 /// A form `section` card, the platform's grouped-content background: AppKit quaternary
502 /// system fill, libadwaita `.card`, Qt `palette(alternate-base)`, UIKit tertiary system
503 /// fill, Material surface-container, XAML card background brush.
504 SectionCard,
505 /// The window's own background, the surface a page sits on: what an opaque cover paints
506 /// by default, and the card of a composed modal sheet (docs/cover.md "Modal sheet").
507 Window,
508 /// The layer between a composed modal sheet and the page under it, which says the page is
509 /// out of reach until the sheet goes. The container's `background` is the plain dimming a
510 /// backend draws when it has no material of its own; the web frosts the page instead.
511 Scrim,
512}
513
514pub const NAV_SIDEBAR_WIDTH: f64 = 240.0;
515
516/// Drag limits for a navigation host's sidebar pane, around [`NAV_SIDEBAR_WIDTH`]. Shared by the
517/// desktops whose divider the user can drag (docs/navigation.md): AppKit enforces both through
518/// its `NSSplitViewItem`; Qt honors the minimum through the pane's own minimum size and leaves
519/// the maximum to the user.
520pub const NAV_SIDEBAR_MIN_W: f64 = 160.0;
521pub const NAV_SIDEBAR_MAX_W: f64 = 400.0;
522
523/// Default preferred width of a navigation host's content-list pane
524/// (`props::NavProps::list_width`, docs/navigation.md), Mail's message-list proportion.
525pub const NAV_LIST_WIDTH: f64 = 300.0;
526
527/// Drag limits for the content-list pane, around the app's preferred width; the same split of
528/// duties as the sidebar's.
529pub const NAV_LIST_MIN_W: f64 = 220.0;
530pub const NAV_LIST_MAX_W: f64 = 560.0;
531
532/// Reserved id for window-level events (resize, lifecycle): day-core routes it to the root.
533pub const WINDOW_NODE: NodeId = NodeId(u64::MAX);
534
535/// Which nodes handle the non-text keys (docs/menus.md). Keys follow focus (the focused piece
536/// hears them and nobody else), so a backend whose focused view would have to claim a key from
537/// the platform's own dispatch (AppKit's responder chain, the DOM's default action) has to know
538/// whether the app wants it before swallowing it. An unclaimed arrow has to keep traveling, or
539/// a canvas inside a scroll view would silently eat the keys that scroll it.
540///
541/// It lives here, in day-spec, rather than in day-core: `day-toolkit-dom` depends on day-spec alone,
542/// and this is a fact about a node that both sides need.
543pub mod keys {
544 use super::NodeId;
545 use std::cell::RefCell;
546 use std::collections::HashSet;
547
548 thread_local! {
549 static HANDLED: RefCell<HashSet<NodeId>> = RefCell::new(HashSet::new());
550 }
551
552 /// Declare that `node` has a key handler (what `Decorate::on_key` records at build).
553 pub fn mark(node: NodeId) {
554 HANDLED.with(|h| h.borrow_mut().insert(node));
555 }
556
557 /// Whether `node` has one.
558 #[must_use]
559 pub fn handled(node: NodeId) -> bool {
560 HANDLED.with(|h| h.borrow().contains(&node))
561 }
562
563 thread_local! {
564 static TEXT: RefCell<HashSet<NodeId>> = RefCell::new(HashSet::new());
565 }
566
567 /// Declare that `node` takes the whole keyboard while focused (what `Decorate::keyboard`
568 /// records at build): every key the platform delivers reaches its handler, named the way
569 /// [`super::KeyEvent`] describes for the full route, and a touch platform raises its soft
570 /// keyboard for it.
571 pub fn mark_text(node: NodeId) {
572 TEXT.with(|h| h.borrow_mut().insert(node));
573 }
574
575 /// Whether `node` takes the whole keyboard: it declared so AND it [`handled`]s keys. A
576 /// declaration with no `.on_key` behind it claims nothing, so every backend asks this one
577 /// question before it raises a soft keyboard, names a letter or claims a Tab.
578 #[must_use]
579 pub fn text(node: NodeId) -> bool {
580 TEXT.with(|h| h.borrow().contains(&node)) && handled(node)
581 }
582
583 /// The keys a focused single-line text field hands to its key handler instead of acting
584 /// on them itself (docs/textfield.md "Keys"): what an address bar needs to walk a
585 /// suggestion list and to cancel an edit. Return stays the field's submit, Tab its focus
586 /// walk, and every other key its editing.
587 pub const FIELD_KEYS: [&str; 3] = ["ArrowUp", "ArrowDown", "Escape"];
588
589 /// Whether a focused text field at `node` claims the key named `key` (web name, see
590 /// [`super::Key::from_name`]) pressed with `modifiers`: one of [`FIELD_KEYS`], no modifier
591 /// held, and a handler declared for the field. A backend that answers yes reports
592 /// `Event::Key` for `node` and keeps the key from the native field.
593 #[must_use]
594 pub fn field_claims(node: NodeId, key: &str, modifiers: impl Into<super::Modifiers>) -> bool {
595 modifiers.into().is_empty() && FIELD_KEYS.contains(&key) && handled(node)
596 }
597
598 /// Drop both marks for a node that left the tree (day-core calls it from its removal
599 /// path). Node ids are generational, so a stale id would never match a new node; this
600 /// keeps the registries from growing with every rebuilt canvas.
601 pub fn forget(node: NodeId) {
602 HANDLED.with(|h| h.borrow_mut().remove(&node));
603 TEXT.with(|h| h.borrow_mut().remove(&node));
604 }
605}
606
607/// Raw foreign native handle for polyglot adoption (§15.3).
608pub type RawHandle = *mut std::ffi::c_void;
609
610// ---------------------------------------------------------------------------
611// Events (§8.3)
612// ---------------------------------------------------------------------------
613
614/// The wire table for backends whose native side reaches Rust through one numeric-kind
615/// trampoline (Android's JNI `nativeOnEvent`, ArkUI's `day_arkui_on_event`). This enum
616/// defines those kind numbers; the Java and C++ sides carry mirrored constants that parity
617/// tests check against these discriminants (so a collision or drift fails `cargo test` on the
618/// host instead of silently mis-decoding events on a device). AppKit/UIKit/GTK/Qt emit `Event`
619/// values directly and never use these numbers; XAML uses per-event callbacks with its own
620/// small local codes.
621///
622/// Payload conventions ride `(num: f64, text: String)` per kind, documented on each variant.
623pub mod bridge {
624 /// One numeric event kind. `as i32` is the wire value.
625 #[repr(i32)]
626 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
627 pub enum BridgeKind {
628 /// Click/press. No payload.
629 Pressed = 0,
630 /// `text` = the field's full new text.
631 TextChanged = 1,
632 /// `num` != 0 ⇒ on.
633 ToggleChanged = 2,
634 /// `num` = the new value.
635 ValueChanged = 3,
636 /// `num` = the selected index.
637 SelectionChanged = 4,
638 /// `num` == 1 ⇒ the native side already popped (predictive back / up arrow).
639 NavBack = 5,
640 /// Nav/tab page size report; `text` = `"w,h"` in px (Rust divides by density).
641 FrameChanged = 6,
642 /// Warm deep link; `text` = the route.
643 Deeplink = 7,
644 /// Modal answered with a button; `num` = the button index.
645 PresentButton = 8,
646 /// Modal answered with text; `text` = the entry.
647 PresentText = 9,
648 /// Modal dismissed.
649 PresentDismissed = 10,
650 /// Gesture; `num` = the code, `text` = the payload in px (Rust divides by density).
651 /// Codes 0 to 3 are a tap and a drag's three phases (0 tap, 1 began, 2 changed,
652 /// 3 ended) with `text` = `"x,y,tx,ty"`. The rest are the [`gesture`] constants:
653 /// long press, double tap, press in and out (`"x,y"`), a drag's or a pan's release
654 /// velocity (`"vx,vy"` in px per second), a touch list ([`gesture::TOUCHES`]) and the
655 /// pointer kind (`text` = [`crate::PointerKind::name`]).
656 Gesture = 11,
657 /// Piece-defined open channel (`Event::Custom` with an empty tag): the piece reads the
658 /// raw `num`/`text` payload.
659 Custom = 12,
660 /// Menu selection; the event's node id is the chosen action's dispatch id.
661 MenuAction = 13,
662 /// App lifecycle; `num` = the phase code (`day_spec::Lifecycle` order).
663 Lifecycle = 14,
664 /// File-picker answer; `text` = chosen locators joined by the unit separator.
665 PresentFile = 15,
666 /// `num` != 0 ⇒ gained keyboard focus.
667 FocusChanged = 16,
668 /// IME action / Return.
669 Submitted = 17,
670 /// Root size change; `text` = `"w,h"` in px. Routed to `WINDOW_NODE` as a window
671 /// resize (the rail rotation, late inset passes, and the soft keyboard ride).
672 WindowResized = 18,
673 /// Safe-area report from an edge-to-edge backend; `text` =
674 /// `"top,bottom,leading,trailing"` in px (Rust divides by density and feeds
675 /// `day_core::set_safe_area`). Node id ignored; no `Event` is emitted.
676 SafeArea = 19,
677 /// A secondary window closed (docs/windows.md); the node id is the window's root.
678 WindowClosed = 20,
679 /// A secondary window's key/active state changed; `num` != 0 ⇒ focused.
680 WindowFocused = 21,
681 /// `num` = the settled value: the drag ended (see `Event::ValueCommitted`). A backend
682 /// that cannot tell a settled value from a moving one sends only `ValueChanged`.
683 ValueCommitted = 22,
684 /// Inline search on a `.searchable()` navigation surface (docs/search.md): the field's
685 /// new text, against the nav host's node. `num` = 1 ⇒ the text was submitted (Return or
686 /// the keyboard's Search key), decoding to [`crate::Event::SearchSubmitted`].
687 SearchChanged = 23,
688 /// The toolkit's own adaptive nav container changed presentation and is reporting it
689 /// (docs/size-classes.md). `num` = 1.0 for split, 0.0 for stacked.
690 NavPresentation = 24,
691 /// The system switched between light and dark appearance. No payload; node id ignored
692 /// and no `Event` is emitted; Rust calls `day_core::note_appearance_changed`, the same
693 /// thing AppKit's and GTK's own scheme observers do.
694 AppearanceChanged = 25,
695 /// A fullscreen cover's hide transition finished (docs/cover.md); no payload, and the
696 /// node id is the cover's. Decodes to [`crate::Event::CoverHidden`].
697 CoverHidden = 26,
698 /// A styled text run's link was tapped (docs/text-runs.md); `text` = the run's target.
699 /// Decodes to [`crate::Event::LinkActivated`].
700 LinkActivated = 27,
701 /// The platform's own undo affordance fired (⌘Z, a three-finger swipe, the Edit menu
702 /// through a native front); `num` != 0 ⇒ redo.
703 UndoInvoked = 28,
704 /// A toolbar item produced a value (docs/toolbars.md): the node id is the item's
705 /// dispatch action; `text` = `"on"` with `num` != 0 ⇒ a toggle turned on, `"on"` with
706 /// 0 ⇒ off, `"sel"` with `num` = the chosen segment, `"text:<query>"` ⇒ a search
707 /// item's new text, `"submit:<query>"` ⇒ that text submitted. Decodes to
708 /// [`crate::Event::ToolbarChanged`]. A plain toolbar button sends `MenuAction`.
709 ToolbarChanged = 30,
710 /// An activated list row; `num` is its current index.
711 ListActivated = 31,
712 /// External document copied into app storage; `text` = its local locator.
713 DocumentOpened = 32,
714 /// The user's reduce-motion setting flipped (docs/accessibility.md). No payload; node
715 /// id ignored and no `Event` is emitted; Rust calls `day_core::note_motion_changed`, as
716 /// the desktop backends' own observers do.
717 ReduceMotionChanged = 33,
718 /// Text committed on the full key route (docs/menus.md "The full route"): `text` =
719 /// what the input method or the key typed, `num` = the modifier mask. Decodes to an
720 /// [`crate::Event::Key`] whose `text` is set; a key that typed nothing rides `Key`.
721 Text = 36,
722 /// A non-text key reached the focused node (docs/menus.md); `text` = the key's web name
723 /// (`"ArrowLeft"`, `"5"`, …, read by [`crate::Key::from_name`]), `num` = the
724 /// [`crate::Modifiers::bits`] mask in its low byte and the phase above it (bit 8 set ⇒
725 /// a repeat, bit 9 set ⇒ a release; [`crate::KeyPhase::from_wire`]). Decodes to
726 /// [`crate::Event::Key`].
727 Key = 29,
728 /// A window's display state changed (docs/windows.md): `num` = the
729 /// [`crate::WindowState`] code (0 normal, 1 minimized, 2 maximized, 3 fullscreen), against
730 /// the window's root node, or [`crate::WINDOW_NODE`] for the primary. Decodes to
731 /// [`crate::Event::WindowStateChanged`] through [`crate::WindowState::from_code`].
732 WindowStateChanged = 34,
733 /// Native pull-to-refresh request; no payload.
734 RefreshRequested = 35,
735 /// Text shared to the app from the system share sheet (Day.toml `share_target`,
736 /// docs/deep-links.md): `text` = the shared text, then the unit separator and the
737 /// subject when one came with it. Node id ignored and no `Event` is emitted; Rust calls
738 /// `day_core::request_shared_text`, which sends a web link in it to `on_open_url`.
739 SharedText = 37,
740 }
741
742 /// The [`BridgeKind::Gesture`] codes above the tap and drag phases (0 to 3), mirrored by the
743 /// Java and C++ sides like the kind numbers.
744 pub mod gesture {
745 /// `Event::LongPress`; `text` = `"x,y"`.
746 pub const LONG_PRESS: i32 = 4;
747 /// `Event::DoubleTap`; `text` = `"x,y"`.
748 pub const DOUBLE_TAP: i32 = 5;
749 /// `Event::Press` with `pressed: true`; `text` = `"x,y"`.
750 pub const PRESS_IN: i32 = 6;
751 /// `Event::Press` with `pressed: false`; `text` = `"x,y"`.
752 pub const PRESS_OUT: i32 = 7;
753 /// `Event::Touches`; `text` = one `"id,phase,x,y,pressure,kind"` per contact, joined
754 /// by `;` (phase 0 began, 1 moved, 2 stationary, 3 ended, 4 cancelled; kind 0 touch,
755 /// 1 mouse, 2 stylus; pressure 0 to 1).
756 pub const TOUCHES: i32 = 8;
757 /// `Event::GestureVelocity` for a drag; `text` = `"vx,vy"`.
758 pub const DRAG_VELOCITY: i32 = 9;
759 /// `Event::GestureVelocity` for a pan; `text` = `"vx,vy"`.
760 pub const PAN_VELOCITY: i32 = 10;
761 /// `Event::PointerKindChanged`; `text` = the kind's name. Node id ignored.
762 pub const POINTER_KIND: i32 = 11;
763 }
764
765 impl BridgeKind {
766 /// Every variant, for uniqueness/parity tests and exhaustive dispatch.
767 pub const ALL: [BridgeKind; 38] = [
768 BridgeKind::Pressed,
769 BridgeKind::TextChanged,
770 BridgeKind::ToggleChanged,
771 BridgeKind::ValueChanged,
772 BridgeKind::SelectionChanged,
773 BridgeKind::NavBack,
774 BridgeKind::FrameChanged,
775 BridgeKind::Deeplink,
776 BridgeKind::PresentButton,
777 BridgeKind::PresentText,
778 BridgeKind::PresentDismissed,
779 BridgeKind::Gesture,
780 BridgeKind::Custom,
781 BridgeKind::MenuAction,
782 BridgeKind::Lifecycle,
783 BridgeKind::PresentFile,
784 BridgeKind::FocusChanged,
785 BridgeKind::Submitted,
786 BridgeKind::WindowResized,
787 BridgeKind::SafeArea,
788 BridgeKind::WindowClosed,
789 BridgeKind::WindowFocused,
790 BridgeKind::ValueCommitted,
791 BridgeKind::SearchChanged,
792 BridgeKind::NavPresentation,
793 BridgeKind::AppearanceChanged,
794 BridgeKind::CoverHidden,
795 BridgeKind::LinkActivated,
796 BridgeKind::UndoInvoked,
797 BridgeKind::Key,
798 BridgeKind::ToolbarChanged,
799 BridgeKind::ListActivated,
800 BridgeKind::DocumentOpened,
801 BridgeKind::ReduceMotionChanged,
802 BridgeKind::WindowStateChanged,
803 BridgeKind::RefreshRequested,
804 BridgeKind::Text,
805 BridgeKind::SharedText,
806 ];
807 }
808
809 #[cfg(test)]
810 mod tests {
811 use super::BridgeKind;
812
813 /// The kind-15 lesson: two meanings on one number decode silently as the first. Every
814 /// discriminant must be unique, and the table must stay dense enough to spot gaps.
815 #[test]
816 fn discriminants_are_unique() {
817 let mut seen = std::collections::BTreeSet::new();
818 for k in BridgeKind::ALL {
819 assert!(
820 seen.insert(k as i32),
821 "duplicate bridge kind number {} ({k:?})",
822 k as i32
823 );
824 }
825 assert_eq!(seen.len(), BridgeKind::ALL.len());
826 }
827
828 /// `ALL` is what the uniqueness check above sees, so a variant left out of it is a variant
829 /// nothing checks, which is how `SearchChanged` and `NavPresentation` sat outside the
830 /// table. The wire numbers are assigned densely from 0, so demanding the set be exactly
831 /// `0..len` catches both a gap and an omission.
832 #[test]
833 fn table_covers_every_wire_number() {
834 let mut nums: Vec<i32> = BridgeKind::ALL.iter().map(|k| *k as i32).collect();
835 nums.sort_unstable();
836 let dense: Vec<i32> = (0..BridgeKind::ALL.len() as i32).collect();
837 assert_eq!(
838 nums, dense,
839 "bridge kinds must be dense from 0 — a missing entry means a variant no test sees"
840 );
841 }
842 }
843}
844
845#[derive(Clone, Debug, PartialEq)]
846pub enum Event {
847 Pressed,
848 TextChanged(String),
849 Submitted,
850 ToggleChanged(bool),
851 ValueChanged(f64),
852 /// A continuous control's value settled: the drag ended (mouse/touch up), or the value moved
853 /// by a discrete action (a keyboard arrow, a click on the track). Always preceded by the
854 /// `ValueChanged` carrying the same value.
855 ///
856 /// The pair exists because one gesture produces two different facts. `ValueChanged` is the
857 /// live one (bindings follow it so the UI tracks the thumb) and it fires continuously, which
858 /// is why nothing durable should key off it: a drag from 1 to 100 and back to 50 emits every
859 /// value in between. `ValueCommitted` fires once, with the value the user chose, and is what
860 /// a recording, a log, or a refetch should use.
861 ///
862 /// A backend that cannot tell the two apart emits only `ValueChanged`; its sliders then do not
863 /// record (docs/coverage-matrix.md).
864 ValueCommitted(f64),
865 SelectionChanged(i64),
866 /// A list row was activated: desktop double-click/Enter, or a touch tap.
867 /// Separate from selection so keyboard browsing need not open or play the row.
868 ListActivated(usize),
869 /// The platform's own undo affordance fired through a native front (⌘Z on the Edit menu,
870 /// a three-finger swipe, shake-to-undo); `redo` distinguishes the pair. Only backends
871 /// with a native undo system emit it; everywhere else the app's own controls call the
872 /// stack directly and this event never exists (docs/model.md).
873 Undo {
874 redo: bool,
875 },
876 /// The platform's own standard edit command fired through its native route (Edit ▸
877 /// Cut/Copy/Paste, ⌘X/⌘C/⌘V, the browser's `copy`/`paste` DOM events) with no text
878 /// widget claiming it first; the app's edit bridge answers (docs/menus.md). Transport
879 /// is the system clipboard (day-part-clipboard), not the event.
880 Edit(EditOp),
881 /// A multi-select list's selection changed: the full set of selected row indices,
882 /// ascending (empty = nothing selected). Emitted instead of `SelectionChanged` where
883 /// `ListProps::multi_select` is honored (docs/list.md).
884 SelectionSet(Vec<i64>),
885 FocusChanged(bool),
886 Tap(Point),
887 /// A link run inside a label was activated; the payload is [`TextRun::link`] verbatim.
888 LinkActivated(String),
889 /// The reader's selection in a selectable label changed ([`Cap::LabelSelection`]): byte
890 /// offsets into the text the label displays, `start <= end`, both on character
891 /// boundaries. `start == end` means nothing is selected any more. Emitted only by labels
892 /// realized with `LabelProps::reports_selection`.
893 TextSelected {
894 start: usize,
895 end: usize,
896 },
897 /// A press held still on the node (docs/gestures.md "Long press"), at the press point in the
898 /// node's coordinates. Fires once, while the pointer is still down; the release that
899 /// follows is not a tap. Only nodes that enabled [`GestureKind::LongPress`] receive it.
900 LongPress(Point),
901 /// Two taps in quick succession on the node (docs/gestures.md "Double tap"), at the second
902 /// tap's point. A node that enabled both [`GestureKind::Tap`] and
903 /// [`GestureKind::DoubleTap`] receives either this or one `Tap`, never both: the single
904 /// tap waits out the double-tap interval. With `DoubleTap` alone enabled nothing waits.
905 DoubleTap(Point),
906 /// The pointer went down on the node (`pressed: true`) or the press ended
907 /// (`pressed: false`): the release, the pointer leaving the node's hit area, or the
908 /// platform taking the gesture away (docs/gestures.md "Press"). Every `true` is followed by
909 /// exactly one `false`. Reported at the pointer-down itself, before any tap or drag is
910 /// recognized, and it never delays or cancels another gesture. Only nodes that enabled
911 /// [`GestureKind::Press`] receive it.
912 Press {
913 pressed: bool,
914 location: Point,
915 },
916 /// The contacts on the node changed (docs/gestures.md "Touches"): every contact that is
917 /// down, plus the ones that ended or were cancelled in this event. Only nodes that
918 /// enabled [`GestureKind::Touches`] receive it.
919 Touches(Vec<Touch>),
920 /// The release velocity of the node's drag or pan as the platform's own recognizer
921 /// measured it, in points per second along the node's axes. Sent immediately before the
922 /// gesture's `Ended` event, by a backend whose recognizer has one; day-core prefers it to
923 /// its own estimate from the event samples (docs/gestures.md "Velocity"). `kind` is
924 /// [`GestureKind::Drag`] or [`GestureKind::Pan`].
925 GestureVelocity {
926 kind: GestureKind,
927 velocity: Point,
928 },
929 /// The kind of device behind the latest pointer input changed (docs/gestures.md "Input
930 /// kind"). Emitted on [`WINDOW_NODE`], only on a change; day-core publishes it as
931 /// `day::primary_pointer()`.
932 PointerKindChanged(PointerKind),
933 /// A context-menu summon reported by a toolkit that presents no native menu of its own
934 /// (web-dom): the pieces layer shows the composed menu (docs/menus.md). `local` is the
935 /// point in the node's own coordinates (what the app's provider receives); `window` the
936 /// same point in window coordinates (where the composed panel goes). Toolkits that serve
937 /// context menus natively never emit this.
938 ContextMenu {
939 local: Point,
940 window: Point,
941 },
942 /// A drag/pan gesture (docs/shapes.md). `location` is in the node's local coordinates;
943 /// `translation` is the cumulative movement since `Began`. Once `Began` is sent the
944 /// gesture belongs to the node until `Ended`: an enclosing scroll view must not take it
945 /// over (docs/gestures.md "Gestures inside a scroll view").
946 Drag {
947 phase: DragPhase,
948 location: Point,
949 translation: Point,
950 },
951 /// A pinch/magnify gesture over the node (docs/shapes.md): `scale` is cumulative since
952 /// `Began` (1.0 = unchanged), `location` the gesture's centroid in local coordinates,
953 /// the anchor a zoom keeps stationary. Only nodes that enabled
954 /// [`GestureKind::Pinch`] receive it; a backend with no recognizer emits nothing.
955 Pinch {
956 phase: DragPhase,
957 scale: f64,
958 location: Point,
959 },
960 /// A two-finger rotation over the node (docs/canvas.md "Zoom and pan"): `rotation` is in
961 /// radians, cumulative since `Began`, positive clockwise on screen; `location` the
962 /// gesture's centroid in local coordinates ([`Point::ZERO`] where the platform gives
963 /// none). A trackpad's rotate tick has no gesture session and arrives as a lone `Changed`
964 /// carrying that tick's own angle. Only nodes that enabled [`GestureKind::Rotate`]
965 /// receive it; a backend with no recognizer emits nothing.
966 Rotate {
967 phase: DragPhase,
968 rotation: f64,
969 location: Point,
970 },
971 /// A viewport pan over the node (docs/shapes.md): `delta` is the movement since the
972 /// previous event; incremental, not cumulative, because desktop wheels have no gesture
973 /// session to accumulate over (a discrete wheel tick arrives as a lone `Changed`).
974 /// Two-finger touch pans bracket theirs with `Began`/`Ended`. Distinct from
975 /// [`Event::Drag`], the primary pointer's press-drag.
976 Pan {
977 phase: DragPhase,
978 delta: Point,
979 location: Point,
980 },
981 /// The pointer moved over the node, or left it (docs/canvas.md "Interaction"). `location` is
982 /// in the node's local coordinates. Phases follow the drag vocabulary: `Began` on entry,
983 /// `Changed` for each move, `Ended` on exit, where `location` is the last point seen inside,
984 /// so a handler always knows where the pointer went out.
985 ///
986 /// Only nodes that enabled [`GestureKind::Hover`] receive it, and only on a device with a
987 /// pointer at all.
988 Hover {
989 phase: DragPhase,
990 location: Point,
991 },
992 /// A scroll view's content offset changed, in points from the content's top-left corner
993 /// (docs/scroll.md "Offset and phase"). Sent only by a scroll realized with
994 /// [`props::ScrollProps::track_offset`], whatever moved it (a finger, a wheel, momentum, a
995 /// programmatic scroll), at most once per display frame, and always once more with the
996 /// offset the view came to rest at.
997 ScrollChanged(Point),
998 /// A scroll view's user-driven scrolling changed phase (docs/scroll.md "Offset and phase").
999 /// Sent only by a scroll realized with [`props::ScrollProps::track_phase`], and only on a
1000 /// change. A programmatic scroll moves the offset and leaves the phase alone.
1001 ScrollPhase(ScrollPhase),
1002 /// A zooming scroll view's scale changed ([`props::ScrollProps::zoom`], docs/scroll.md
1003 /// "Zoom"): the user pinched, or an animated [`props::ScrollPatch::Zoom`] moved it. `1.0`
1004 /// is the content's natural size.
1005 ScrollZoomed(f64),
1006 /// What a recycling list shows changed (docs/list.md "Visible rows"): day-core raises this
1007 /// from the host's [`ListSource::viewport`] reports, deduplicated. Toolkits never send it
1008 /// themselves. `rows` is the visible items as a half-open range of item indices (empty
1009 /// when no item is in view); `end_distance` is [`ListViewport::end_distance`], or `None`
1010 /// from a host that reports only its first visible row.
1011 ListViewport {
1012 rows: std::ops::Range<usize>,
1013 end_distance: Option<f64>,
1014 },
1015 /// The reader started moving a list themselves (docs/list.md "Following the end"):
1016 /// day-core sends it from the host's [`ListSource::reader_scroll`] report. Toolkits never
1017 /// send it themselves.
1018 ListReaderScrolled,
1019 /// A canvas node was re-framed by layout; re-record (§11). Nav pane/page containers
1020 /// also report their allocated size with this (docs/navigation.md).
1021 FrameChanged(Size),
1022 /// Native back navigation (iOS back button/swipe, Android system back or toolbar up).
1023 /// `already_popped` = the toolkit already performed the pop natively (iOS); the nav
1024 /// host then syncs its stack without re-issuing `NavPatch::Popped`.
1025 NavBack {
1026 already_popped: bool,
1027 },
1028 /// A nav host's own adaptive container changed presentation, and Day is being told about it
1029 /// after the fact (docs/size-classes.md).
1030 ///
1031 /// The counterpart to [`props::NavPatch::Presentation`], for the toolkits that answer
1032 /// `Cap::NavRepresent = Emulated`: `UISplitViewController` collapsing as a Pro Max iPhone
1033 /// rotates into portrait, `SlidingPaneLayout` deciding at measure time that two panes no
1034 /// longer fit. Day did not ask for it and must not fight it; the pieces layer only
1035 /// reconciles what follows, which is the selection rule (a split presentation cannot draw an
1036 /// empty detail pane, so expanding with nothing selected picks the first item).
1037 ///
1038 /// Emitted on the NAV host node, and only when the presentation actually changed.
1039 NavPresentationChanged(props::NavPresentation),
1040 Key(KeyEvent),
1041 WindowResized(Size),
1042 /// The platform asks the app to show a route (docs/navigation.md), a runtime deep link:
1043 /// on web-dom, the URL hash changing under the app (hand-edited, or browser back/forward);
1044 /// on mobile, a warm scheme link (iOS `application:openURL:`, Android `onNewIntent` via
1045 /// `BridgeKind::Deeplink`). Emitted on [`WINDOW_NODE`] (day-core answers with `navigate()`
1046 /// when the route differs from the current one) or on the active nav host's node (the nav
1047 /// piece answers with `navigate()` itself, docs/deep-links.md). Launch-time deep links use
1048 /// `DAY_DEEPLINK`/`set_launch_deeplink` instead; this variant is for changes while the
1049 /// app runs.
1050 RouteRequested(String),
1051 /// A native modal answered request `req` (docs/dialogs.md).
1052 PresentResult {
1053 req: u64,
1054 result: present::PresentResult,
1055 },
1056 /// A decode started by [`Toolkit::decode_image`] finished (docs/images.md).
1057 ///
1058 /// Keyed by request id like [`Event::PresentResult`], and for the same reason: the answer
1059 /// belongs to a waiting caller, not to a tree node. It never crosses a native boundary
1060 /// (every backend raises it from its own Rust arm once the platform decoder answers), so it
1061 /// has no [`bridge::BridgeKind`], exactly like the completion events dialogs use in-process.
1062 ///
1063 /// No bitmap id rides here: day-core minted it and handed it to the backend with the bytes,
1064 /// so it already knows which image a request answers for. A backend that stored the image
1065 /// under that id has nothing more to say than the facts it read.
1066 ImageDecoded {
1067 req: u64,
1068 result: Result<BitmapInfo, ImageError>,
1069 },
1070 /// An encode started by [`Toolkit::encode_image`] finished (docs/images.md): the encoded
1071 /// bytes, or why they could not be produced.
1072 ImageEncoded {
1073 req: u64,
1074 result: Result<Vec<u8>, ImageError>,
1075 },
1076 /// A canvas drawing started by [`Toolkit::render_bitmap`] finished rendering
1077 /// (docs/canvas.md "Exporting"). Keyed by request id like [`Event::ImageDecoded`], and like
1078 /// it carries no bitmap id: day-core minted the id and handed it over with the ops, so the
1079 /// answer is only the facts of the image the backend stored under it.
1080 BitmapRendered {
1081 req: u64,
1082 result: Result<BitmapInfo, ExportError>,
1083 },
1084 /// A PDF started by [`Toolkit::render_pdf`] finished (docs/canvas.md "Exporting"): the
1085 /// document's bytes, or why they could not be produced.
1086 PdfRendered {
1087 req: u64,
1088 result: Result<Vec<u8>, ExportError>,
1089 },
1090 /// An open, piece-defined event (§8.2). `tag` names the event for in-process emitters (a static
1091 /// literal); it is empty for events that cross a native boundary (JNI/C-ABI), which carry only the
1092 /// primitive `num`/`text` payload. A piece's `cx.on` reads whichever fields it needs. This is the
1093 /// escape hatch for events the fixed variants above don't cover (a web view's URL, a picked date, …).
1094 Custom {
1095 tag: &'static str,
1096 num: f64,
1097 text: String,
1098 },
1099 /// A menu item (app menu or context menu) with this action id was activated (§ menus). day-core
1100 /// routes it to the app closure registered for the id. Standard-role items don't carry an id
1101 /// (`role` items are handled natively) so they never emit this.
1102 MenuAction(u64),
1103 /// A toolbar item produced a value: a search field's text, a toggle's new state
1104 /// (docs/toolbars.md). `action` is the item's dispatch id, from the same registry
1105 /// [`Event::MenuAction`] uses, and day-core routes it to the closure registered for it.
1106 /// A plain toolbar button has no value and emits `MenuAction` instead.
1107 ToolbarChanged {
1108 action: u64,
1109 value: ToolbarValue,
1110 },
1111 /// A searchable navigation surface's field changed (docs/search.md). Emitted against the nav
1112 /// host's node, not through the toolbar's dispatch registry: search belongs to the surface,
1113 /// so the field can move between the toolbar and the navigation list without the app
1114 /// re-registering anything.
1115 SearchChanged(String),
1116 /// The user picked a different scope. Carries the index into `SearchProps::scopes`.
1117 SearchScopeChanged(usize),
1118 /// The user chose one of `SearchProps::suggestions`, by index. The toolkit has already put
1119 /// that completion in the field and emitted [`Event::SearchChanged`] for it; this says which
1120 /// one, for an app that wants to act on the choice itself.
1121 SearchSuggestionChosen(usize),
1122 /// The user submitted the inline field's text with its Return or Search key. Emitted
1123 /// after the last [`Event::SearchChanged`], with the text as submitted, for a search that
1124 /// runs on demand (a server query) rather than narrowing as the text changes.
1125 SearchSubmitted(String),
1126 /// The app moved through a lifecycle phase (docs/lifecycle.md). Backends emit this from the
1127 /// native app/activity delegate; day-core routes it to the app's `on_lifecycle` handlers.
1128 Lifecycle(Lifecycle),
1129 /// A secondary native window closed (the title-bar close, a platform gesture such as an
1130 /// app-switcher swipe or an activity finish, or `Toolkit::close_window`); emitted on the
1131 /// window's root node after the platform committed the close. day-core disposes the
1132 /// window's subtree on receipt, so native and programmatic closes share one teardown
1133 /// path (docs/windows.md). Never emitted for the primary window (its close terminates
1134 /// the app).
1135 WindowClosed,
1136 /// A secondary window's key/active state changed; emitted on the window's root node.
1137 /// day-core tracks the focused window with it (dialog parenting, dayscript targeting).
1138 WindowFocused(bool),
1139 /// A window's display state changed (docs/windows.md): the user minimized, zoomed or took it
1140 /// fullscreen, or a [`WindowChange::State`] request landed. Emitted on the window's root node
1141 /// (the primary's may arrive on [`WINDOW_NODE`]); day-core feeds the window's `state()`
1142 /// signal with it, so the app reads what the platform did rather than what it asked for.
1143 WindowStateChanged(WindowState),
1144 /// A native list committed a drag-reorder (docs/list.md): row `from` landed at row `to`.
1145 /// Emitted on the `LIST` node by the list piece's commit hook: the reorder driver
1146 /// rotates its snapshot synchronously inside the platform's drop callback, then reports
1147 /// through the event queue so the app's `on_reorder` never runs inside a native animation
1148 /// callstack.
1149 ListReorder {
1150 from: usize,
1151 to: usize,
1152 },
1153 /// A regrouping sidebar committed a drop (`props::NavMenuProps::regroup`, docs/navigation.md
1154 /// "Moving rows between sections"), in item indices into the rows as they were before the
1155 /// move: row `from` now sits in the section whose first row is item `section` (item 0 for
1156 /// rows above the first header), before item `before`, or at that section's end for
1157 /// `None`. `before` is never `from`. Emitted on the `NAV_MENU` node by a toolkit whose
1158 /// `Cap::NavReorder` is `Native`, deferred through the event queue exactly as
1159 /// [`Event::ListReorder`] is; the nav validates it against the app's rules before reporting.
1160 NavRegroup {
1161 from: usize,
1162 section: usize,
1163 before: Option<usize>,
1164 },
1165 /// A native list committed a swipe-delete (docs/list.md): the row at this index is gone.
1166 /// Deferred through the event queue exactly as [`Event::ListReorder`] is.
1167 ListDelete(usize),
1168 /// The native pull-to-refresh control requested an update. The app owns its busy state.
1169 RefreshRequested,
1170 /// A native list activated a swipe action (docs/list.md): the user pressed button `action`
1171 /// (an index into the row's [`ListSwipe::actions_at`] offer for `edge`) on row `index`, or
1172 /// swiped clear across for the edge's first action. Emitted on the `LIST` node by the list
1173 /// piece's commit hook and deferred through the event queue exactly as
1174 /// [`Event::ListReorder`] is, so the app's handler never runs inside a native animation
1175 /// callstack.
1176 ListSwipe {
1177 index: usize,
1178 edge: SwipeEdge,
1179 action: usize,
1180 },
1181 /// A fullscreen cover's hide transition finished (docs/cover.md): the content can now be
1182 /// disposed. Answers [`props::CoverPatch::Dismiss`]; delivery is a hard guarantee, and
1183 /// backends over-report rather than under-report; consumers gate on their own closing
1184 /// flag, so duplicates and belated reports are no-ops.
1185 CoverHidden,
1186 /// The user showed or hid an inspector pane through a native affordance (a dock widget's
1187 /// close button, a divider dragged shut) rather than through Day (docs/inspector.md).
1188 /// Emitted on the `kinds::INSPECTOR` node, and only when the visibility actually changed;
1189 /// the piece writes it back to the bound signal. Applying
1190 /// [`props::InspectorPatch::Visible`] must never re-emit it (the from-native echo rule).
1191 InspectorChanged(bool),
1192 /// The user disclosed or collapsed a tree row through the native affordance (docs/tree.md).
1193 /// Emitted on the `kinds::TREE` node; the piece writes it back to the app's expansion
1194 /// signal. Applying [`props::TreePatch::Expand`] must never re-emit it (the from-native
1195 /// echo rule).
1196 TreeExpanded {
1197 token: u64,
1198 expanded: bool,
1199 },
1200 /// A native tree committed a drag move (docs/tree.md): `token` now sits under `parent`
1201 /// (`None` = the root) at `index` (`None` = dropped onto the parent, an append). Deferred
1202 /// through the event queue exactly as [`Event::ListReorder`] is; the app's `on_move`
1203 /// writes its own data, whose refresh reloads the tree.
1204 TreeMove {
1205 token: u64,
1206 parent: Option<u64>,
1207 index: Option<usize>,
1208 },
1209 /// A tree's selection changed: the full set of selected row tokens (empty = cleared).
1210 /// Token-addressed, since a tree cannot speak row indices: expanding a row renumbers
1211 /// everything below it (docs/tree.md).
1212 TreeSelection(Vec<u64>),
1213}
1214
1215impl Event {
1216 /// Build a text-carrying [`Event::Custom`] (with `num` defaulted to 0), the common case for an
1217 /// in-process piece reporting a value back: `emit(node, Event::custom("webview:url", url))`.
1218 pub fn custom(tag: &'static str, text: impl Into<String>) -> Event {
1219 Event::Custom {
1220 tag,
1221 num: 0.0,
1222 text: text.into(),
1223 }
1224 }
1225}
1226
1227/// An app-lifecycle phase (docs/lifecycle.md). Each backend maps these onto its OS's native app /
1228/// activity delegate. Some phases only exist on some platforms (a mobile app enters the
1229/// background and can be low on memory, a desktop app cannot), so [`Lifecycle::is_universal`]
1230/// marks the ones every backend delivers, and [`Toolkit::supports_lifecycle`] reports per-backend
1231/// truth.
1232///
1233/// Rough native mapping:
1234///
1235/// | phase | AppKit | UIKit | GTK | Qt | Android | XAML |
1236/// |---|---|---|---|---|---|---|
1237/// | `WillLaunch` / `DidLaunch` | `applicationWill/DidFinishLaunching` | same | `startup`/mount | mount | `onCreate` | window create |
1238/// | `DidBecomeActive` | `didBecomeActive` | `didBecomeActive` | `notify::is-active` | `ApplicationActive` | `onResume` | `Activated` |
1239/// | `WillResignActive` | `willResignActive` | `willResignActive` | `notify::is-active` | `ApplicationInactive` | `onPause` | `Deactivated` |
1240/// | `WillEnterForeground` | — | `willEnterForeground` | — | — | `onStart` | — |
1241/// | `DidEnterBackground` | — | `didEnterBackground` | — | — | `onStop` | — |
1242/// | `DidReceiveMemoryWarning` | — | `didReceiveMemoryWarning` | — | — | `onTrimMemory` | — |
1243/// | `WillTerminate` | `willTerminate` | `willTerminate` | `shutdown` | `aboutToQuit` | `onDestroy` | window close |
1244/// | `DidExit` | after `willTerminate` | after `willTerminate` | `run` returned | `exec` returned | after `onDestroy` | loop returned |
1245#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1246pub enum Lifecycle {
1247 /// Before the window and UI are built: the first thing to run. Set up global state here.
1248 WillLaunch,
1249 /// The UI is mounted and the app is about to start running. Kick off startup work here.
1250 DidLaunch,
1251 /// The app came to the foreground and is the active, focused app receiving input.
1252 DidBecomeActive,
1253 /// The app is about to stop being active (an interruption, app switch, or losing focus).
1254 WillResignActive,
1255 /// The app is about to return to the foreground (mobile). Refresh what background invalidated.
1256 WillEnterForeground,
1257 /// The app left the foreground and is no longer visible (mobile). Persist state, release UI work.
1258 DidEnterBackground,
1259 /// The system is low on memory (mobile). Drop caches and non-essential memory now.
1260 DidReceiveMemoryWarning,
1261 /// The app is about to terminate: the last chance to save. Triggered by the Quit command,
1262 /// the platform's quit shortcut, or the OS reclaiming the app.
1263 WillTerminate,
1264 /// The run loop is over and nothing of the app will run after this: the last phase, after
1265 /// every `WillTerminate` handler. Day logs its exit line ("Clean exit for …") once the
1266 /// handlers have run, so a handler here is the app's last word before it.
1267 DidExit,
1268}
1269
1270impl Lifecycle {
1271 /// Every phase, in delivery order (launch → run → quit). Handy for logging/registration sweeps.
1272 pub const ALL: [Lifecycle; 9] = [
1273 Lifecycle::WillLaunch,
1274 Lifecycle::DidLaunch,
1275 Lifecycle::DidBecomeActive,
1276 Lifecycle::WillResignActive,
1277 Lifecycle::WillEnterForeground,
1278 Lifecycle::DidEnterBackground,
1279 Lifecycle::DidReceiveMemoryWarning,
1280 Lifecycle::WillTerminate,
1281 Lifecycle::DidExit,
1282 ];
1283
1284 /// True for phases every backend delivers (launch, activation, termination). The remaining
1285 /// phases (`WillEnterForeground`, `DidEnterBackground`, `DidReceiveMemoryWarning`) are mobile
1286 /// concepts and are only delivered by the mobile backends. `const` so it composes into a
1287 /// backend's `const fn lifecycle_supported` and thus into compile-time guards.
1288 #[must_use]
1289 pub const fn is_universal(self) -> bool {
1290 matches!(
1291 self,
1292 Lifecycle::WillLaunch
1293 | Lifecycle::DidLaunch
1294 | Lifecycle::DidBecomeActive
1295 | Lifecycle::WillResignActive
1296 | Lifecycle::WillTerminate
1297 | Lifecycle::DidExit
1298 )
1299 }
1300
1301 /// A stable, human-readable name (for logs/warnings).
1302 #[must_use]
1303 pub const fn name(self) -> &'static str {
1304 match self {
1305 Lifecycle::WillLaunch => "WillLaunch",
1306 Lifecycle::DidLaunch => "DidLaunch",
1307 Lifecycle::DidBecomeActive => "DidBecomeActive",
1308 Lifecycle::WillResignActive => "WillResignActive",
1309 Lifecycle::WillEnterForeground => "WillEnterForeground",
1310 Lifecycle::DidEnterBackground => "DidEnterBackground",
1311 Lifecycle::DidReceiveMemoryWarning => "DidReceiveMemoryWarning",
1312 Lifecycle::WillTerminate => "WillTerminate",
1313 Lifecycle::DidExit => "DidExit",
1314 }
1315 }
1316}
1317
1318/// The phase of a drag gesture (docs/shapes.md).
1319#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1320pub enum DragPhase {
1321 Began,
1322 Changed,
1323 Ended,
1324}
1325
1326/// The one axis a drag follows (`Decorate::on_drag_along`, [`Toolkit::set_drag_axis`]).
1327#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1328pub enum DragAxis {
1329 Horizontal,
1330 Vertical,
1331}
1332
1333impl DragAxis {
1334 /// Whether a movement of `translation` runs along this axis more than across it.
1335 #[must_use]
1336 pub fn leads(self, translation: Point) -> bool {
1337 match self {
1338 DragAxis::Horizontal => translation.x.abs() >= translation.y.abs(),
1339 DragAxis::Vertical => translation.y.abs() >= translation.x.abs(),
1340 }
1341 }
1342}
1343
1344/// A gesture a node wants delivered. Backends attach the matching native recognizer when day-core
1345/// calls [`Toolkit::enable_gesture`]; the default is no gesture (recognizers cost, so opt-in).
1346#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1347pub enum GestureKind {
1348 Tap,
1349 /// A press held still (`Event::LongPress`).
1350 LongPress,
1351 /// Two taps in quick succession (`Event::DoubleTap`).
1352 DoubleTap,
1353 /// Press-in and press-out (`Event::Press`), reported at the pointer-down itself.
1354 Press,
1355 /// The raw contacts on the node (`Event::Touches`).
1356 Touches,
1357 Drag,
1358 /// The pointer moving over the node without pressing (docs/canvas.md "Interaction"), and
1359 /// leaving it. Delivered only where a pointer exists: every desktop, an iPad with a trackpad
1360 /// or pencil, an Android device with a mouse or stylus. A touch-only device reports none,
1361 /// which is the right answer, not a gap, so anything reachable by hover must also be
1362 /// reachable by a tap.
1363 Hover,
1364 /// Pinch/magnify (docs/shapes.md): trackpad magnification, two-finger touch pinch.
1365 Pinch,
1366 /// Rotation (docs/canvas.md "Zoom and pan"): trackpad rotate, two-finger touch twist.
1367 Rotate,
1368 /// Viewport pan (docs/shapes.md): trackpad two-finger scroll, two-finger touch pan.
1369 /// Distinct from [`GestureKind::Drag`], the primary pointer's press-drag.
1370 Pan,
1371}
1372
1373// ---------------------------------------------------------------------------
1374// Menus (app menu bar + context menus). The model is a toolkit-neutral tree; each backend renders
1375// it with its native affordance (NSMenu / GMenu+GtkPopoverMenu / QMenu / UIMenu / Android
1376// PopupMenu / XAML MenuFlyout) and its own conventions, so day imposes no menu manager of its own.
1377// ---------------------------------------------------------------------------
1378
1379/// A keyboard shortcut for a menu item. `primary` is the platform's command modifier (⌘ on Apple,
1380/// Ctrl on GTK/Qt/XAML) so one declaration reads correctly everywhere. `key` is a single character
1381/// (`"s"`, `"."`) or a named key (`"Return"`, `"Delete"`, `"Left"`, `"F1"`).
1382#[derive(Clone, Debug, PartialEq, Eq, Default)]
1383pub struct Shortcut {
1384 pub key: String,
1385 /// ⌘ (Apple) / Ctrl (elsewhere). The conventional command modifier.
1386 pub primary: bool,
1387 pub shift: bool,
1388 /// ⌥ / Alt.
1389 pub alt: bool,
1390 /// Literal Control (⌃ on Apple). Rare; prefer `primary` for the command modifier.
1391 pub control: bool,
1392}
1393
1394/// The key of a [`Shortcut`], in the menu vocabulary its `key` field holds. Converts from a
1395/// typed [`Key`] (`Key::Enter` is `"Return"`), a `char`, or a name already in that vocabulary
1396/// (`"s"`, `"Return"`, `"Left"`, `"F1"`).
1397#[derive(Clone, Debug, PartialEq, Eq)]
1398pub struct ShortcutKey(pub String);
1399
1400impl From<Key> for ShortcutKey {
1401 fn from(key: Key) -> ShortcutKey {
1402 ShortcutKey(key.shortcut_name())
1403 }
1404}
1405impl From<char> for ShortcutKey {
1406 fn from(c: char) -> ShortcutKey {
1407 ShortcutKey(c.to_string())
1408 }
1409}
1410impl From<&str> for ShortcutKey {
1411 fn from(name: &str) -> ShortcutKey {
1412 ShortcutKey(name.to_owned())
1413 }
1414}
1415impl From<String> for ShortcutKey {
1416 fn from(name: String) -> ShortcutKey {
1417 ShortcutKey(name)
1418 }
1419}
1420
1421impl Shortcut {
1422 /// `primary`+`key` (⌘S / Ctrl+S), the common case: `Shortcut::primary('s').shift()`,
1423 /// `Shortcut::primary(Key::Enter)`.
1424 pub fn primary(key: impl Into<ShortcutKey>) -> Shortcut {
1425 Shortcut {
1426 key: key.into().0,
1427 primary: true,
1428 ..Default::default()
1429 }
1430 }
1431 /// `key` with no modifiers (`Shortcut::plain(Key::F(1))`, plain `Key::Delete`).
1432 pub fn plain(key: impl Into<ShortcutKey>) -> Shortcut {
1433 Shortcut {
1434 key: key.into().0,
1435 ..Default::default()
1436 }
1437 }
1438 /// The shortcut's modifiers as a set, for code that compares it with a [`KeyEvent`].
1439 #[must_use]
1440 pub fn modifiers(&self) -> Modifiers {
1441 Modifiers::NONE
1442 .with(Modifiers::PRIMARY, self.primary)
1443 .with(Modifiers::SHIFT, self.shift)
1444 .with(Modifiers::ALT, self.alt)
1445 .with(Modifiers::CONTROL, self.control)
1446 }
1447 /// Whether a key event is this shortcut: the same key (letters compare without case, as
1448 /// accelerators do) with exactly these modifiers held.
1449 #[must_use]
1450 pub fn matches(&self, event: &KeyEvent) -> bool {
1451 let mut mods = event.modifiers;
1452 // Off Apple platforms Control IS the primary key, and a backend sets both bits.
1453 if self.primary && !self.control && !cfg!(target_vendor = "apple") {
1454 mods = Modifiers::from_bits(mods.bits() & !Modifiers::CONTROL.bits());
1455 }
1456 mods == self.modifiers() && event.key.shortcut_name().eq_ignore_ascii_case(&self.key)
1457 }
1458 #[must_use]
1459 pub fn shift(mut self) -> Shortcut {
1460 self.shift = true;
1461 self
1462 }
1463 #[must_use]
1464 pub fn alt(mut self) -> Shortcut {
1465 self.alt = true;
1466 self
1467 }
1468 #[must_use]
1469 pub fn control(mut self) -> Shortcut {
1470 self.control = true;
1471 self
1472 }
1473}
1474
1475/// A standard/system command. The backend supplies the native item, a selector on AppKit/UIKit
1476/// (`cut:`/`copy:`/`paste:`…) or a stock action on GTK/Qt/XAML, so it targets the focused
1477/// control, gets the platform's default label + shortcut, and enables/disables itself
1478/// automatically. This is how default items (Edit ▸ Cut/Copy/Paste, the app's Quit/About) are
1479/// accommodated without the app re-implementing them.
1480#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1481pub enum MenuRole {
1482 Cut,
1483 Copy,
1484 Paste,
1485 SelectAll,
1486 Undo,
1487 Redo,
1488 Delete,
1489 /// The app's About command (docs/settings.md). With an About registered through
1490 /// `day::register_about` the item lowers to that dispatch action (a Day-rendered About
1491 /// window, or the toolkit's own About dialog where one exists); without one AppKit shows
1492 /// its stock Info.plist panel and the other desktops show the label alone.
1493 About,
1494 Quit,
1495 Preferences,
1496 Minimize,
1497 CloseWindow,
1498 Fullscreen,
1499 /// File ▸ New Window (docs/windows.md): opens another window through the builder the
1500 /// app registered with `day::register_new_window`. No platform has a native selector
1501 /// for it, so the item lowers to the registered dispatch action (disabled when none).
1502 NewWindow,
1503 /// Check for Updates… (docs/settings.md): placed directly under About in the macOS App
1504 /// menu (the Sparkle convention) and in Help elsewhere. Lowers to the action an updater
1505 /// registered with `day::register_check_for_updates`; absent from the bar when none did.
1506 CheckForUpdates,
1507}
1508
1509/// The keyboard modifiers held at an interaction: what a [`KeyEvent`] carries and what
1510/// `day::modifiers()` answers ambiently ([`Toolkit::modifiers`]). A small set with a method
1511/// per key: `event.modifiers.shift()`, `Modifiers::PRIMARY | Modifiers::SHIFT`.
1512/// Touch-only backends answer [`Modifiers::NONE`].
1513///
1514/// [`Modifiers::bits`] is the mask a backend's numeric wire carries
1515/// ([`bridge::BridgeKind::Key`]), and [`Modifiers::from_bits`] reads it back.
1516#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
1517pub struct Modifiers(u8);
1518
1519impl Modifiers {
1520 /// No modifier held.
1521 pub const NONE: Modifiers = Modifiers(0);
1522 /// Shift.
1523 pub const SHIFT: Modifiers = Modifiers(1);
1524 /// The platform's command key: ⌘ on Apple platforms, Ctrl elsewhere (the
1525 /// [`Shortcut::primary`] convention).
1526 pub const PRIMARY: Modifiers = Modifiers(2);
1527 /// Alt (Option on Apple platforms).
1528 pub const ALT: Modifiers = Modifiers(4);
1529 /// The Control key itself, wherever it sits: on Apple platforms it is a different key
1530 /// from [`Modifiers::PRIMARY`] (⌘), elsewhere the same one, so a Ctrl+C on Linux sets
1531 /// both. Carried by key events on the full route (`Decorate::keyboard`).
1532 pub const CONTROL: Modifiers = Modifiers(8);
1533
1534 const ALL_BITS: u8 = 15;
1535
1536 /// The wire mask: one bit per modifier, in declaration order from bit 0.
1537 #[must_use]
1538 pub const fn bits(self) -> u8 {
1539 self.0
1540 }
1541 /// The set a wire mask spells; bits above the four modifiers are ignored.
1542 #[must_use]
1543 pub const fn from_bits(bits: u8) -> Modifiers {
1544 Modifiers(bits & Self::ALL_BITS)
1545 }
1546 /// Whether no modifier is held.
1547 #[must_use]
1548 pub const fn is_empty(self) -> bool {
1549 self.0 == 0
1550 }
1551 /// Whether every modifier in `other` is held.
1552 #[must_use]
1553 pub const fn contains(self, other: Modifiers) -> bool {
1554 self.0 & other.0 == other.0
1555 }
1556 /// This set with `other` added when `held`: how a backend builds the set from the
1557 /// platform's own flags (`Modifiers::NONE.with(Modifiers::SHIFT, flags.shift)`).
1558 #[must_use]
1559 pub const fn with(self, other: Modifiers, held: bool) -> Modifiers {
1560 if held {
1561 Modifiers(self.0 | other.0)
1562 } else {
1563 self
1564 }
1565 }
1566 /// Whether Shift is held.
1567 #[must_use]
1568 pub const fn shift(self) -> bool {
1569 self.contains(Modifiers::SHIFT)
1570 }
1571 /// Whether the platform's command key is held.
1572 #[must_use]
1573 pub const fn primary(self) -> bool {
1574 self.contains(Modifiers::PRIMARY)
1575 }
1576 /// Whether Alt (Option) is held.
1577 #[must_use]
1578 pub const fn alt(self) -> bool {
1579 self.contains(Modifiers::ALT)
1580 }
1581 /// Whether the Control key itself is held.
1582 #[must_use]
1583 pub const fn control(self) -> bool {
1584 self.contains(Modifiers::CONTROL)
1585 }
1586}
1587
1588impl std::ops::BitOr for Modifiers {
1589 type Output = Modifiers;
1590 fn bitor(self, rhs: Modifiers) -> Modifiers {
1591 Modifiers(self.0 | rhs.0)
1592 }
1593}
1594
1595impl std::ops::BitOrAssign for Modifiers {
1596 fn bitor_assign(&mut self, rhs: Modifiers) {
1597 self.0 |= rhs.0;
1598 }
1599}
1600
1601/// A wire mask ([`Modifiers::from_bits`]): what a backend's key trampoline holds.
1602impl From<u8> for Modifiers {
1603 fn from(bits: u8) -> Modifiers {
1604 Modifiers::from_bits(bits)
1605 }
1606}
1607
1608/// A standard edit command a platform route delivered ([`Event::Edit`]).
1609#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1610pub enum EditOp {
1611 Cut,
1612 Copy,
1613 Paste,
1614 SelectAll,
1615}
1616
1617/// What the app's edit bridge can currently do, mirrored into the toolkit
1618/// ([`Toolkit::set_edit_state`]) so native menu validation enables the stock items.
1619/// `can_paste` is the app's half ("a paste handler is installed"); the toolkit combines it
1620/// with its own clipboard-has-text check where one exists.
1621#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1622pub struct EditState {
1623 pub can_cut: bool,
1624 pub can_copy: bool,
1625 pub can_paste: bool,
1626 pub can_select_all: bool,
1627}
1628
1629/// The undo stack's face, as a native front mirrors it ([`Toolkit::set_undo_state`]): what is
1630/// possible and what the menu titles should say. Labels arrive already localized: a toolkit
1631/// cannot invent translated text, the same rule as every other label in this file.
1632#[derive(Clone, Debug, PartialEq, Default)]
1633pub struct UndoState {
1634 pub can_undo: bool,
1635 pub can_redo: bool,
1636 /// The next undo unit's display label ("Rename"), empty when nothing is undoable. Fronts
1637 /// interpolate it into the platform's own title form ("Undo Rename").
1638 pub undo_label: String,
1639 pub redo_label: String,
1640}
1641
1642/// One entry in a menu (recursive: a `Submenu` nests).
1643#[derive(Clone, Debug, PartialEq)]
1644pub enum MenuItem {
1645 /// A command. `action` (nonzero) dispatches [`Event::MenuAction`] to the app; a `role`-only item
1646 /// uses the native standard command instead (action 0). `label`/`shortcut` override the role's
1647 /// defaults. `icon` is the platform's own glyph beside the title where menus carry one (macOS,
1648 /// Windows, GNOME, KDE, Android); a backend whose menus are text-only ignores it.
1649 ///
1650 /// The `id`/`action` split is [`ToolbarItem`]'s: `id` names the item and `action` is what it
1651 /// runs. They are separate because a label cannot serve as a name (it is localized, and an
1652 /// item that shows its own state changes it), so anything addressing an item from outside
1653 /// (dayscript's `menu: { id: … }`) needs something that does not move.
1654 Action {
1655 /// The app's own name for this item, where it gave one. Stable across locales and across
1656 /// a change of `checked`, and unique within the menu it is installed in.
1657 id: Option<String>,
1658 /// The item's command, as a dispatch id from the same registry [`Event::MenuAction`] uses
1659 /// (0 = no command), so a toolbar button and its menu twin can share one closure.
1660 action: u64,
1661 label: String,
1662 shortcut: Option<Shortcut>,
1663 enabled: bool,
1664 /// On/off state where the item stands for a setting or one of several choices, drawn with
1665 /// the platform's own check mark. `None` is a plain command and reserves no mark; `Some`
1666 /// makes the item checkable and says which way it currently sits.
1667 ///
1668 /// The item still runs its `action` when chosen; a backend never flips this on its own.
1669 /// The app owns the state, and re-installing the menu (`app_menu`, which re-lowers on change) is what moves
1670 /// the mark, so what the menu shows can never disagree with what the app thinks.
1671 checked: Option<bool>,
1672 role: Option<MenuRole>,
1673 icon: Option<Icon>,
1674 },
1675 /// A nested submenu. At the top level of an app menu a `role` claims one of the platform's
1676 /// standard menu-bar slots: the backend then uses this menu instead of its stock one, and
1677 /// places it where the platform expects that menu to sit.
1678 Submenu {
1679 label: String,
1680 items: Vec<MenuItem>,
1681 role: Option<MenuBarRole>,
1682 },
1683 /// A visual separator.
1684 Separator,
1685}
1686
1687/// A standard menu-bar slot (macOS's File/Edit/View/Window/Help, and their counterparts
1688/// elsewhere). A backend that has a house style for the menu bar fills every slot an app did
1689/// not claim with its own stock menu, so an app never has to restate the platform's furniture,
1690/// and can still replace any of it by tagging its own submenu with the matching role.
1691#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1692#[non_exhaustive]
1693pub enum MenuBarRole {
1694 File,
1695 Edit,
1696 View,
1697 /// KDE/Plasma's Settings menu (`Configure <App>`, Configure Shortcuts). No counterpart on
1698 /// macOS, where preferences live in the app menu, or on GNOME/Windows.
1699 Settings,
1700 /// macOS's Window menu. Windows and Linux desktops do not have one.
1701 Window,
1702 Help,
1703}
1704
1705// ---------------------------------------------------------------------------
1706// Window toolbars (docs/toolbars.md)
1707// ---------------------------------------------------------------------------
1708
1709/// A standard icon, named by what it means rather than by how it looks, so each backend can
1710/// draw the platform's own glyph for it: an SF Symbol on macOS, a freedesktop icon name on
1711/// GTK and Qt, a Fluent glyph on Windows. This is the only way an icon looks native on every
1712/// desktop at once; a bundled PNG cannot, because it is one artist's take on all four.
1713///
1714/// The set is kept small: the commands that recur across toolbars. Anything
1715/// app-specific is an [`Icon::Image`].
1716#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1717#[non_exhaustive]
1718pub enum Symbol {
1719 Add,
1720 Remove,
1721 Delete,
1722 Edit,
1723 New,
1724 Open,
1725 Save,
1726 Print,
1727 Refresh,
1728 Search,
1729 Share,
1730 Settings,
1731 Info,
1732 Star,
1733 Bookmark,
1734 Back,
1735 Forward,
1736 Up,
1737 Down,
1738 Home,
1739 /// Show/hide the sidebar, the leading item of most desktop toolbars.
1740 Sidebar,
1741 Filter,
1742 Sort,
1743 /// An overflow affordance (macOS `ellipsis`, Android's vertical `more_vert`, GNOME's hamburger,
1744 /// Fluent `More`).
1745 More,
1746 Play,
1747 Pause,
1748 Stop,
1749 /// A photo capture: a screenshot command, a camera control.
1750 Camera,
1751 /// Source code.
1752 Code,
1753 /// Light appearance (a sun). The three below are the vocabulary of a theme chooser, which
1754 /// every platform draws with the same three ideas.
1755 Light,
1756 /// Dark appearance (a moon).
1757 Dark,
1758 /// Follow the system: the half-filled circle every platform uses for "automatic".
1759 Auto,
1760 ZoomIn,
1761 ZoomOut,
1762 /// Back to actual size: the 100% zoom command between [`Symbol::ZoomIn`] and
1763 /// [`Symbol::ZoomOut`].
1764 ZoomReset,
1765 Undo,
1766 Redo,
1767 Copy,
1768 Cut,
1769 Paste,
1770 Mail,
1771 Folder,
1772 Document,
1773 Check,
1774 Close,
1775 Warning,
1776 /// A rectangle: the shape vocabulary a drawing surface needs (docs/shapes.md), and the
1777 /// glyphs every drawing, diagram and annotation tool puts in the same place.
1778 Rectangle,
1779 /// An ellipse.
1780 Oval,
1781 /// An outlined circle: the read/unread vocabulary (a read row, its dot removed), and the
1782 /// generic ring glyph.
1783 Circle,
1784 /// A filled circle: the unread dot itself.
1785 CircleFilled,
1786 /// A straight line segment.
1787 Line,
1788 /// Combine the selection into a group: the drawing-tool command (two stacked squares).
1789 Group,
1790 /// Dissolve a group back into its members (two separated squares).
1791 Ungroup,
1792 /// Text: a line of type as a drawing element (the drawing-tool "T").
1793 Text,
1794 /// The device's own position: a map's "show my location" button (Apple's arrow, the
1795 /// crosshair elsewhere).
1796 Location,
1797 /// The open tabs or windows: a browser's tab switcher (two overlapping squares).
1798 Tabs,
1799 /// A book: a library of bookmarks or saved reading (Safari's bookmarks button).
1800 Book,
1801 /// Past activity: a history list (a clock with a turning arrow).
1802 History,
1803}
1804
1805/// The SF Symbol each standard symbol draws as. The system's own glyphs match the user's
1806/// device: weight, optical size, accent color and all. Shared by both Apple backends
1807/// (toolbars on macOS, menus on both).
1808///
1809/// The match is exhaustive so that a new [`Symbol`] must name its glyph here rather than
1810/// silently drawing nothing on Apple. A name this OS release does not know still resolves to
1811/// no image, and the item falls back to its label.
1812#[must_use]
1813pub fn sf_symbol_name(s: Symbol) -> &'static str {
1814 match s {
1815 Symbol::Add => "plus",
1816 Symbol::Remove => "minus",
1817 Symbol::Delete => "trash",
1818 Symbol::Edit => "pencil",
1819 Symbol::New => "square.and.pencil",
1820 Symbol::Open | Symbol::Folder => "folder",
1821 Symbol::Save => "square.and.arrow.down",
1822 Symbol::Print => "printer",
1823 Symbol::Refresh => "arrow.clockwise",
1824 Symbol::Search => "magnifyingglass",
1825 Symbol::Share => "square.and.arrow.up",
1826 Symbol::Settings => "gearshape",
1827 Symbol::Info => "info.circle",
1828 Symbol::Star => "star",
1829 Symbol::Bookmark => "bookmark",
1830 Symbol::Back => "chevron.backward",
1831 Symbol::Forward => "chevron.forward",
1832 Symbol::Up => "chevron.up",
1833 Symbol::Down => "chevron.down",
1834 Symbol::Home => "house",
1835 Symbol::Sidebar => "sidebar.leading",
1836 Symbol::Filter => "line.3.horizontal.decrease",
1837 Symbol::Sort => "arrow.up.arrow.down",
1838 Symbol::More => "ellipsis",
1839 Symbol::Play => "play.fill",
1840 Symbol::Pause => "pause.fill",
1841 Symbol::Stop => "stop.fill",
1842 Symbol::Camera => "camera",
1843 Symbol::Code => "chevron.left.forwardslash.chevron.right",
1844 Symbol::Light => "sun.max",
1845 Symbol::Dark => "moon",
1846 Symbol::Auto => "circle.lefthalf.filled",
1847 Symbol::ZoomIn => "plus.magnifyingglass",
1848 Symbol::ZoomReset => "1.magnifyingglass",
1849 Symbol::ZoomOut => "minus.magnifyingglass",
1850 Symbol::Undo => "arrow.uturn.backward",
1851 Symbol::Redo => "arrow.uturn.forward",
1852 Symbol::Copy => "doc.on.doc",
1853 Symbol::Cut => "scissors",
1854 Symbol::Paste => "doc.on.clipboard",
1855 Symbol::Mail => "envelope",
1856 Symbol::Document => "doc",
1857 Symbol::Check => "checkmark",
1858 Symbol::Close => "xmark",
1859 Symbol::Warning => "exclamationmark.triangle",
1860 Symbol::Rectangle => "rectangle",
1861 Symbol::Oval => "oval",
1862 Symbol::Circle => "circle",
1863 Symbol::CircleFilled => "circle.fill",
1864 Symbol::Line => "line.diagonal",
1865 Symbol::Group | Symbol::Tabs => "square.on.square",
1866 Symbol::Ungroup => "square.on.square.dashed",
1867 Symbol::Text => "textformat",
1868 Symbol::Location => "location",
1869 Symbol::Book => "book",
1870 Symbol::History => "clock.arrow.circlepath",
1871 }
1872}
1873
1874/// A button or toolbar item's picture: a standard [`Symbol`] (drawn with the platform's own icon set) or
1875/// a bundled image from `resource/images` for something only this app has.
1876#[derive(Clone, Debug, PartialEq)]
1877pub enum Icon {
1878 Symbol(Symbol),
1879 /// A bundled image name, resolved the same way [`ImageName`] is elsewhere.
1880 Image(String),
1881}
1882
1883/// What a toolbar item is. The variants are the vocabulary every desktop toolbar shares; each
1884/// backend realizes one with its native control, never with a drawn imitation.
1885#[derive(Clone, Debug, PartialEq)]
1886pub enum ToolbarItemKind {
1887 /// A push button running the item's `action`.
1888 Button,
1889 /// A two-state button. `on` seeds it; the user flipping it emits
1890 /// [`ToolbarValue::On`], and the app's own writes arrive as [`ToolbarPatch::On`].
1891 Toggle { on: bool },
1892 /// A button that drops a menu: the same [`MenuItem`] model the menu bar uses, so a
1893 /// toolbar menu and its menu-bar twin are one list of commands.
1894 Menu { items: Vec<MenuItem> },
1895 /// A search field. Edits emit [`ToolbarValue::Text`]; the app's own writes arrive as
1896 /// [`ToolbarPatch::Text`].
1897 ///
1898 /// Day creates this item itself, from a `.searchable()` surface whose placement resolved to
1899 /// the toolbar (docs/search.md); apps declare search on the surface, never here.
1900 Search {
1901 text: String,
1902 placeholder: String,
1903 /// Completions for the current text, drawn by the field's own completion affordance
1904 /// where it has one (`AutoSuggestBox`, `QCompleter`, `<datalist>`). Empty = none.
1905 suggestions: Vec<String>,
1906 },
1907 /// A row of mutually exclusive choices drawn as one control: the native segmented control
1908 /// (`NSSegmentedControl`, a linked GTK/Qt button box, a XAML toggle strip, `.day-segmented`
1909 /// on the web).
1910 ///
1911 /// This is what a set of related toolbar toggles should be when exactly one of them is on at
1912 /// a time: three separate toggles say "three independent switches" to the eye and to a screen
1913 /// reader, and leave the app to keep them exclusive. Choosing a segment emits
1914 /// [`ToolbarValue::Selected`]; the app's own writes arrive as [`ToolbarPatch::Selected`].
1915 Segmented {
1916 /// One entry per segment. A segment with an icon draws it in place of its title where
1917 /// the platform does that, and keeps the title as its accessible name.
1918 segments: Vec<ToolbarSegment>,
1919 selected: usize,
1920 },
1921 /// Static text, for a status or a caption.
1922 Label,
1923 /// A divider between neighbors in the same placement bucket, where the platform draws one
1924 /// (macOS toolbars have no separator, so AppKit renders it as a fixed space,
1925 /// docs/toolbars.md). Grouping is all it does: alignment is [`ToolbarPlacement`]'s job.
1926 Separator,
1927}
1928
1929/// One choice inside a [`ToolbarItemKind::Segmented`] control.
1930#[derive(Clone, Debug, PartialEq)]
1931pub struct ToolbarSegment {
1932 /// The segment's name: its label where the platform shows text, its accessible name always.
1933 pub title: String,
1934 pub icon: Option<Icon>,
1935}
1936
1937/// The reserved id of the sidebar affordance a `nav(Sidebar)` supplies for itself
1938/// (docs/toolbars.md). Backends with a system item for the job (AppKit's
1939/// `NSToolbarToggleSidebarItem`) recognize it by this id and draw theirs instead; dayscript
1940/// recognizes it to drive the toolkit's own duty rather than an app closure.
1941pub const SIDEBAR_TOGGLE_ID: &str = "day::sidebar_toggle";
1942
1943/// The reserved id of a `.searchable()` surface's field (docs/search.md): the `ToolbarItem` a
1944/// desktop bar draws for it, and the name dayscript's `toolbar:` step drives it by wherever the
1945/// platform put it — on the bar, or inline on the navigation surface where the bar holds no
1946/// field, in which case day-core resolves the id to that host instead.
1947pub const SEARCH_ITEM_ID: &str = "day::search";
1948
1949/// One item in a window's toolbar (docs/toolbars.md).
1950#[derive(Clone, Debug, PartialEq)]
1951pub struct ToolbarItem {
1952 /// Stable identity: the native item identifier, the dayscript target, and the key a
1953 /// [`ToolbarPatch`] addresses. Unique within a toolbar.
1954 pub id: String,
1955 pub kind: ToolbarItemKind,
1956 /// The item's name. Shown beside or below the icon where the platform does that, and used
1957 /// verbatim in the overflow and customization menus, so it is never optional, even on a
1958 /// toolbar that only shows icons. It is also the item's accessible name.
1959 pub label: String,
1960 /// Hover help. Defaults to `label` where the platform expects a tooltip and none is given.
1961 pub tooltip: Option<String>,
1962 pub icon: Option<Icon>,
1963 pub enabled: bool,
1964 /// The item's command, as a dispatch id from the same registry [`Event::MenuAction`] uses
1965 /// (0 = no command), so a toolbar button and its menu twin can share one closure.
1966 pub action: u64,
1967 /// This item's role on the chrome carrying it (docs/toolbars.md). It never names a surface:
1968 /// Which chrome an item rides is decided by where the app declared it, so this says only
1969 /// where on that chrome it belongs.
1970 pub placement: ToolbarPlacement,
1971 /// Whether the item draws its title, its icon, or both, where the platform can do more than
1972 /// one. An item folded into an overflow menu shows its title whatever this asks for; a menu
1973 /// row with no words is not a menu row.
1974 pub label_style: LabelStyle,
1975 /// Draw this item in the platform's emphasized style (a tinted/filled bar button, a
1976 /// prominent `NSToolbarItem`). For the one action a chrome is really offering.
1977 pub prominent: bool,
1978 /// Which column of a multi-pane window this item came from (docs/toolbars.md), set by Day
1979 /// from the piece that declared it, never by an app.
1980 ///
1981 /// A desktop toolbar spans every column at once, and a three-pane app expects each column's
1982 /// commands to sit over that column: the sidebar's against the first divider, the list's over
1983 /// the list, the rest over the detail. That is what Mail, Notes and Finder do, and it is only
1984 /// expressible because the declaration site already said which pane the command belongs to.
1985 /// Backends that draw one undivided bar ignore it.
1986 pub column: ToolbarColumn,
1987}
1988
1989/// Which pane of a window's navigation a toolbar item was declared in (docs/toolbars.md).
1990#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1991pub enum ToolbarColumn {
1992 /// The window itself, over no particular column. Draws with the detail's items, which is
1993 /// where a command that acts on the whole window belongs when the panes are side by side.
1994 #[default]
1995 Window,
1996 /// The sidebar / master column.
1997 Sidebar,
1998 /// The content-list column between the sidebar and the detail.
1999 List,
2000 /// The detail column.
2001 Detail,
2002}
2003
2004/// Where an item sits on the chrome that carries it (docs/toolbars.md).
2005///
2006/// A placement is a role, never a surface. Which toolbar, navigation bar or column an item
2007/// rides follows from the piece that declared it, so an app never spells that out twice.
2008#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
2009pub enum ToolbarPlacement {
2010 /// The natural spot on this chrome: after the leading group on a desktop toolbar, the
2011 /// trailing item group on a navigation bar, an `IF_ROOM` menu action on Android.
2012 #[default]
2013 Automatic,
2014 /// The leading edge: a pane toggle, a control that reveals what is to its left.
2015 Navigation,
2016 /// Centered: a title accessory, a transport, a status readout.
2017 Principal,
2018 /// Trailing, and the last thing a crowded chrome gives up.
2019 Primary,
2020 /// Trailing, and the first thing a crowded chrome folds into its overflow.
2021 Secondary,
2022 /// A bottom bar where the platform has one (iOS `toolbarItems`, an Android bottom app bar);
2023 /// [`ToolbarPlacement::Secondary`] everywhere else.
2024 Bottom,
2025}
2026
2027/// Which halves of an item's label a platform draws, where it can draw more than one.
2028#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
2029pub enum LabelStyle {
2030 /// The platform's own convention for this chrome.
2031 #[default]
2032 Automatic,
2033 /// The icon alone (the title stays as the accessible name and the tooltip).
2034 IconOnly,
2035 /// The title alone, even where an icon was given.
2036 TitleOnly,
2037 /// Both, where the chrome has room for both.
2038 TitleAndIcon,
2039}
2040
2041/// A value a toolbar item produced.
2042#[derive(Clone, Debug, PartialEq)]
2043pub enum ToolbarValue {
2044 /// A search item's full new text.
2045 Text(String),
2046 /// A search item's text, submitted with the field's Return or Search key. Sent after the
2047 /// last [`ToolbarValue::Text`]; it changes no state of its own.
2048 Submit(String),
2049 /// A toggle item's new state.
2050 On(bool),
2051 /// A segmented item's newly chosen index.
2052 Selected(usize),
2053}
2054
2055/// A targeted update to one live toolbar item: the path that keeps a bound signal in sync
2056/// without rebuilding the bar (which would drop the search field's focus mid-keystroke).
2057#[derive(Clone, Debug, PartialEq)]
2058pub enum ToolbarPatch {
2059 /// Focus a search control and select its text without changing its value.
2060 Focus { item: String },
2061 /// Replace a search item's text.
2062 Text { item: String, text: String },
2063 /// Set a toggle item's state.
2064 On { item: String, on: bool },
2065 /// Select a segmented item's index.
2066 Selected { item: String, index: usize },
2067 /// Enable or disable any item.
2068 Enabled { item: String, on: bool },
2069 /// Replace a search item's completions (docs/search.md). Targeted rather than a rebuild,
2070 /// because these change on every keystroke and rebuilding the bar would take the field's
2071 /// focus with it.
2072 Suggestions { item: String, list: Vec<String> },
2073 /// Replace an item's words (a language change): its label, which an icon-only item still
2074 /// carries for the overflow menu and assistive technology, and its tooltip. The item keeps
2075 /// its native widget, its action and its place.
2076 Label {
2077 item: String,
2078 label: String,
2079 tooltip: Option<String>,
2080 },
2081 /// Replace a search item's empty-state prompt (docs/search.md), in the live field.
2082 Placeholder { item: String, text: String },
2083}
2084
2085impl ToolbarPatch {
2086 /// The id of the item this patch addresses.
2087 #[must_use]
2088 pub fn item(&self) -> &str {
2089 match self {
2090 ToolbarPatch::Focus { item }
2091 | ToolbarPatch::Text { item, .. }
2092 | ToolbarPatch::On { item, .. }
2093 | ToolbarPatch::Selected { item, .. }
2094 | ToolbarPatch::Enabled { item, .. }
2095 | ToolbarPatch::Suggestions { item, .. }
2096 | ToolbarPatch::Label { item, .. }
2097 | ToolbarPatch::Placeholder { item, .. } => item,
2098 }
2099 }
2100
2101 /// Write this patch's value into `items`, the model of a bar. `false` when no item there
2102 /// takes it (an unknown id, or a kind the value does not apply to).
2103 pub fn apply_to(&self, items: &mut [ToolbarItem]) -> bool {
2104 let Some(it) = items.iter_mut().find(|i| i.id == self.item()) else {
2105 return false;
2106 };
2107 match (self, &mut it.kind) {
2108 (ToolbarPatch::Focus { .. }, ToolbarItemKind::Search { .. }) => (),
2109 (ToolbarPatch::Text { text, .. }, ToolbarItemKind::Search { text: t, .. }) => {
2110 t.clone_from(text);
2111 }
2112 (
2113 ToolbarPatch::Suggestions { list, .. },
2114 ToolbarItemKind::Search { suggestions, .. },
2115 ) => suggestions.clone_from(list),
2116 (ToolbarPatch::On { on, .. }, ToolbarItemKind::Toggle { on: o }) => *o = *on,
2117 (
2118 ToolbarPatch::Selected { index, .. },
2119 ToolbarItemKind::Segmented { segments, selected },
2120 ) if *index < segments.len() => *selected = *index,
2121 (ToolbarPatch::Enabled { on, .. }, _) => it.enabled = *on,
2122 (ToolbarPatch::Label { label, tooltip, .. }, _) => {
2123 it.label = label.clone();
2124 it.tooltip = tooltip.clone();
2125 }
2126 (
2127 ToolbarPatch::Placeholder { text, .. },
2128 ToolbarItemKind::Search { placeholder, .. },
2129 ) => placeholder.clone_from(text),
2130 _ => return false,
2131 }
2132 true
2133 }
2134}
2135
2136/// One step of an edit to a window's toolbar (docs/toolbars.md).
2137///
2138/// Day hands a backend its bar as edits, never as a whole new model to rebuild, for the same
2139/// reason the view tree arrives as `insert`/`remove` rather than as a fresh tree: an item the
2140/// edit does not name keeps its native widget, and with it the keyboard focus, the caret, a
2141/// menu that is open. A value (search text, a toggle) never travels as an edit; it is a
2142/// [`ToolbarPatch`] on the live item.
2143///
2144/// An edit lists every [`ToolbarOp::Remove`] first, then every [`ToolbarOp::Insert`] in
2145/// ascending `index`, so applying them in order to the bar's current items (a
2146/// [`ToolbarMirror`] does exactly that) produces the new bar. Items keep their relative order
2147/// across an edit: an item that moves arrives as a remove and an insert, like one whose
2148/// presentation changed.
2149#[derive(Clone, Debug, PartialEq)]
2150pub enum ToolbarOp {
2151 /// The item with this id leaves the bar.
2152 Remove { id: String },
2153 /// `item` joins the bar at `index`, its position once this edit is complete.
2154 Insert { index: usize, item: ToolbarItem },
2155}
2156
2157impl ToolbarOp {
2158 /// Apply this op to `items`, a bar's model in order.
2159 pub fn apply_to(&self, items: &mut Vec<ToolbarItem>) {
2160 match self {
2161 ToolbarOp::Remove { id } => items.retain(|i| i.id != *id),
2162 ToolbarOp::Insert { index, item } => {
2163 items.insert((*index).min(items.len()), item.clone());
2164 }
2165 }
2166 }
2167}
2168
2169/// A backend's copy of one window's toolbar, kept in step with the [`ToolbarOp`]s and
2170/// [`ToolbarPatch`]es that reach it, and the one place a backend works out where a new item
2171/// goes (docs/toolbars.md).
2172///
2173/// Every backend lays its bar out as a few groups (the leading and trailing ends of a header
2174/// bar, the columns of a split window, the primary and overflow commands of a command bar) and
2175/// keeps model order within each. So an inserted item always goes right after
2176/// [`ToolbarMirror::prev_where`] its own group, or first in the group when that is `None`, and
2177/// nothing already on the bar moves.
2178#[derive(Clone, Debug, Default)]
2179pub struct ToolbarMirror {
2180 items: Vec<ToolbarItem>,
2181}
2182
2183impl ToolbarMirror {
2184 /// The bar's items, in model order.
2185 #[must_use]
2186 pub fn items(&self) -> &[ToolbarItem] {
2187 &self.items
2188 }
2189
2190 #[must_use]
2191 pub fn is_empty(&self) -> bool {
2192 self.items.is_empty()
2193 }
2194
2195 /// The item with this id.
2196 #[must_use]
2197 pub fn get(&self, id: &str) -> Option<&ToolbarItem> {
2198 self.items.iter().find(|i| i.id == id)
2199 }
2200
2201 /// The item dispatching `action`: how a backend whose native bar reports only an action
2202 /// id (a menu tap) finds what was tapped.
2203 #[must_use]
2204 pub fn by_action(&self, action: u64) -> Option<&ToolbarItem> {
2205 self.items
2206 .iter()
2207 .find(|i| i.action == action && action != 0)
2208 }
2209
2210 /// Take the item with `id` out, returning it.
2211 pub fn remove(&mut self, id: &str) -> Option<ToolbarItem> {
2212 let at = self.items.iter().position(|i| i.id == id)?;
2213 Some(self.items.remove(at))
2214 }
2215
2216 /// Put `item` at `index` (clamped to the end).
2217 pub fn insert(&mut self, index: usize, item: ToolbarItem) {
2218 let at = index.min(self.items.len());
2219 self.items.insert(at, item);
2220 }
2221
2222 /// Apply one op to the model: what a backend that repaints its whole native bar from the
2223 /// model (a menu of actions) does with each.
2224 pub fn apply(&mut self, op: &ToolbarOp) {
2225 op.apply_to(&mut self.items);
2226 }
2227
2228 /// Write a value patch into the model. `false` when no item takes it.
2229 pub fn patch(&mut self, patch: &ToolbarPatch) -> bool {
2230 patch.apply_to(&mut self.items)
2231 }
2232
2233 /// The nearest item before `index` that `same_group` accepts: the native item a new one at
2234 /// `index` goes right after, in that group. `None` = it goes first in the group.
2235 pub fn prev_where(
2236 &self,
2237 index: usize,
2238 same_group: impl Fn(&ToolbarItem) -> bool,
2239 ) -> Option<&ToolbarItem> {
2240 self.items[..index.min(self.items.len())]
2241 .iter()
2242 .rev()
2243 .find(|i| same_group(i))
2244 }
2245}
2246
2247/// A key on the keyboard, as [`KeyEvent::key`] names it (docs/menus.md "Keys").
2248///
2249/// A key that types is [`Key::Character`] with its unmodified character (`'a'`, `'A'` under
2250/// Shift, `'8'`, `'ü'` on a layout that has one, `' '` for the space bar); a key that types
2251/// nothing is one of the named variants. [`Key::Unidentified`] stands for text with no single
2252/// key behind it (an input method's commit) and for a key outside this vocabulary.
2253///
2254/// At the boundaries that stay text (a backend's wire, a dayscript `key:` step, a menu
2255/// [`Shortcut`]) a key is spelled by its web `KeyboardEvent.key` name: [`Key::from_name`]
2256/// reads one and [`Key::name`] writes it.
2257#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
2258#[non_exhaustive]
2259pub enum Key {
2260 /// A key that types, named by its unmodified character.
2261 Character(char),
2262 ArrowLeft,
2263 ArrowRight,
2264 ArrowUp,
2265 ArrowDown,
2266 Enter,
2267 Tab,
2268 Escape,
2269 Backspace,
2270 Delete,
2271 Home,
2272 End,
2273 PageUp,
2274 PageDown,
2275 Insert,
2276 /// A function key, `F(1)` through `F(12)`.
2277 F(u8),
2278 /// No single key: text an input method committed, or a key this vocabulary does not name.
2279 Unidentified,
2280}
2281
2282impl Key {
2283 /// The key a web `KeyboardEvent.key` name spells: a named key, `"F1"` through `"F12"`, a
2284 /// single character, or `"Space"` for the space bar. Anything else is
2285 /// [`Key::Unidentified`].
2286 #[must_use]
2287 pub fn from_name(name: &str) -> Key {
2288 match name {
2289 "ArrowLeft" => Key::ArrowLeft,
2290 "ArrowRight" => Key::ArrowRight,
2291 "ArrowUp" => Key::ArrowUp,
2292 "ArrowDown" => Key::ArrowDown,
2293 "Enter" => Key::Enter,
2294 "Tab" => Key::Tab,
2295 "Escape" => Key::Escape,
2296 "Backspace" => Key::Backspace,
2297 "Delete" => Key::Delete,
2298 "Home" => Key::Home,
2299 "End" => Key::End,
2300 "PageUp" => Key::PageUp,
2301 "PageDown" => Key::PageDown,
2302 "Insert" => Key::Insert,
2303 "Space" => Key::Character(' '),
2304 _ => {
2305 if let Some(n) = name.strip_prefix('F').and_then(|n| n.parse::<u8>().ok())
2306 && (1..=12).contains(&n)
2307 {
2308 return Key::F(n);
2309 }
2310 let mut chars = name.chars();
2311 match (chars.next(), chars.next()) {
2312 (Some(c), None) => Key::Character(c),
2313 _ => Key::Unidentified,
2314 }
2315 }
2316 }
2317 }
2318
2319 /// The web `KeyboardEvent.key` name of this key: `"ArrowLeft"`, `"F5"`, `"a"`, and the
2320 /// empty string for [`Key::Unidentified`]. The inverse of [`Key::from_name`].
2321 #[must_use]
2322 pub fn name(self) -> String {
2323 match self {
2324 Key::Character(c) => c.to_string(),
2325 Key::F(n) => format!("F{n}"),
2326 Key::Unidentified => String::new(),
2327 Key::ArrowLeft => "ArrowLeft".into(),
2328 Key::ArrowRight => "ArrowRight".into(),
2329 Key::ArrowUp => "ArrowUp".into(),
2330 Key::ArrowDown => "ArrowDown".into(),
2331 Key::Enter => "Enter".into(),
2332 Key::Tab => "Tab".into(),
2333 Key::Escape => "Escape".into(),
2334 Key::Backspace => "Backspace".into(),
2335 Key::Delete => "Delete".into(),
2336 Key::Home => "Home".into(),
2337 Key::End => "End".into(),
2338 Key::PageUp => "PageUp".into(),
2339 Key::PageDown => "PageDown".into(),
2340 Key::Insert => "Insert".into(),
2341 }
2342 }
2343
2344 /// The character of a key that types, or `None` for a named key.
2345 #[must_use]
2346 pub fn character(self) -> Option<char> {
2347 match self {
2348 Key::Character(c) => Some(c),
2349 _ => None,
2350 }
2351 }
2352
2353 /// The value of a digit key (`'0'` through `'9'`), or `None` for every other key.
2354 #[must_use]
2355 pub fn digit(self) -> Option<u8> {
2356 match self {
2357 Key::Character(c @ '0'..='9') => Some(c as u8 - b'0'),
2358 _ => None,
2359 }
2360 }
2361
2362 /// Whether this is one of the four arrow keys.
2363 #[must_use]
2364 pub fn is_arrow(self) -> bool {
2365 matches!(
2366 self,
2367 Key::ArrowLeft | Key::ArrowRight | Key::ArrowUp | Key::ArrowDown
2368 )
2369 }
2370
2371 /// The name a menu [`Shortcut`] spells this key with (`"Return"`, `"Left"`, `"F1"`,
2372 /// `"s"`): the menu vocabulary every backend's accelerator table reads, which differs
2373 /// from the web names for Enter and the arrows.
2374 #[must_use]
2375 pub fn shortcut_name(self) -> String {
2376 match self {
2377 Key::Enter => "Return".into(),
2378 Key::ArrowLeft => "Left".into(),
2379 Key::ArrowRight => "Right".into(),
2380 Key::ArrowUp => "Up".into(),
2381 Key::ArrowDown => "Down".into(),
2382 other => other.name(),
2383 }
2384 }
2385}
2386
2387impl std::fmt::Display for Key {
2388 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2389 f.write_str(&self.name())
2390 }
2391}
2392
2393impl From<char> for Key {
2394 fn from(c: char) -> Key {
2395 Key::Character(c)
2396 }
2397}
2398
2399/// A key by its web name ([`Key::from_name`]): what a backend's key table and a scripted
2400/// step hold.
2401impl From<&str> for Key {
2402 fn from(name: &str) -> Key {
2403 Key::from_name(name)
2404 }
2405}
2406
2407impl From<String> for Key {
2408 fn from(name: String) -> Key {
2409 Key::from_name(&name)
2410 }
2411}
2412
2413impl From<&String> for Key {
2414 fn from(name: &String) -> Key {
2415 Key::from_name(name)
2416 }
2417}
2418
2419impl From<std::borrow::Cow<'_, str>> for Key {
2420 fn from(name: std::borrow::Cow<'_, str>) -> Key {
2421 Key::from_name(&name)
2422 }
2423}
2424
2425/// Where a key is in its press (docs/menus.md "Keys").
2426#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
2427pub enum KeyPhase {
2428 /// The key went down.
2429 #[default]
2430 Down,
2431 /// The key is held and the platform repeated it. A handler that acts once per press
2432 /// ignores this phase; one that moves while a key is held treats it like `Down`.
2433 Repeat,
2434 /// The key came up. Reported where [`Cap::KeyPhases`] is supported.
2435 Up,
2436}
2437
2438impl KeyPhase {
2439 /// The phase a backend's numeric wire carries beside the modifier mask
2440 /// ([`bridge::BridgeKind::Key`]): bits 8 and 9 of `num` (0 down, 1 repeat, 2 up).
2441 #[must_use]
2442 pub fn from_wire(num: f64) -> KeyPhase {
2443 match (num as u32 >> 8) & 3 {
2444 1 => KeyPhase::Repeat,
2445 2 => KeyPhase::Up,
2446 _ => KeyPhase::Down,
2447 }
2448 }
2449}
2450
2451/// One key event for the focused piece (`Decorate::on_key`, `Decorate::on_key_up`).
2452///
2453/// Build one with [`KeyEvent::new`], [`KeyEvent::named`], [`KeyEvent::typed_text`] or
2454/// [`KeyEvent::typed_by`], then [`KeyEvent::with_phase`] for a repeat or a release.
2455#[derive(Clone, Debug, PartialEq)]
2456#[non_exhaustive]
2457pub struct KeyEvent {
2458 /// The key. On the short route (a focusable piece or a canvas) the four arrows and the ten
2459 /// digits (from the main row or the numeric keypad) arrive everywhere, plus
2460 /// [`Key::Delete`] and [`Key::Backspace`] on backends with no menu bar ([`Cap::AppMenu`]
2461 /// unsupported), where no accelerator can own those keys. A focused piece claims every key
2462 /// the route carries, so offering them on a menu-bar platform would let a canvas swallow
2463 /// the Delete its own Edit menu was about to act on (docs/menus.md). The two delete keys
2464 /// keep the names the platform gives the physical keys (a Mac's ⌫ is `Backspace` and its ⌦
2465 /// is `Delete`), so a handler that means "remove this" takes both. A digit arrives only
2466 /// while neither Primary nor Alt (nor a Mac's Control) is held: ⌘1 and Ctrl+1 are
2467 /// accelerators, and a canvas claiming them would starve the menu. Most backends name the
2468 /// digit the keypress types, so a layout whose number row needs Shift for digits reports
2469 /// `'1'` with Shift set; XAML and ArkUI read the physical key. Backends emit `Event::Key`
2470 /// only while no text widget has focus; a field's own editing keys never surface here.
2471 /// The one exception is a single-line text field with a key handler ([`keys::handled`] for
2472 /// its node): it hands [`Key::ArrowUp`], [`Key::ArrowDown`] and [`Key::Escape`], pressed
2473 /// with no modifier, to that handler instead of acting on them itself, so an address bar
2474 /// can walk a suggestion list (docs/textfield.md "Keys").
2475 ///
2476 /// A piece that declared `Decorate::keyboard()` takes the full route instead: every key
2477 /// the platform delivers while it is focused. A key that types nothing is a named variant
2478 /// ([`KeyEvent::NAMED`] lists their web names); a key that types is [`Key::Character`]
2479 /// with its unmodified character (`'a'`, `'A'` under Shift, `'8'`, `'ü'` on a layout that
2480 /// has one), and what it typed rides in [`KeyEvent::text`]. Under Control or Alt the key
2481 /// stays that character (`'c'` with Control set, never the control code it would type).
2482 /// Text an input method commits (a dead-key accent, a Japanese phrase, the soft
2483 /// keyboard's word) arrives with the text alone and [`Key::Unidentified`]: no single key
2484 /// is behind it. Only the platform's command chords stay out: ⌘ on Apple platforms and
2485 /// the browser's own shortcuts belong to the menu and the browser, so a terminal's ⌘C
2486 /// still copies. [`KeyEvent::typed`] is the question a text consumer asks.
2487 pub key: Key,
2488 /// The modifiers held with the key.
2489 pub modifiers: Modifiers,
2490 /// The text this press committed, on the full route: what the key typed ("a", "A", "é"
2491 /// after a dead key, the whole string an input method committed at once), or `None` for
2492 /// a key that typed nothing (a named key, a Control or Alt chord, a composition still in
2493 /// progress). Separate from [`KeyEvent::key`] so that a committed "Enter" is text and the
2494 /// Enter key is a key, whatever the input method sends. Always `None` on the short route
2495 /// and on a release.
2496 pub text: Option<String>,
2497 /// Whether the key went down, repeated while held, or came up. `Decorate::on_key`
2498 /// receives `Down` and `Repeat`; `Decorate::on_key_up` receives `Up`.
2499 pub phase: KeyPhase,
2500}
2501
2502impl KeyEvent {
2503 /// The ten digit key names, indexed by value: a backend's key-code table.
2504 pub const DIGITS: [&'static str; 10] = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"];
2505
2506 /// The web `KeyboardEvent.key` name of every key that types nothing, as a backend's wire
2507 /// and a dayscript `key:` step spell them. A name outside this list is the text it types.
2508 pub const NAMED: [&'static str; 26] = [
2509 "ArrowLeft",
2510 "ArrowRight",
2511 "ArrowUp",
2512 "ArrowDown",
2513 "Enter",
2514 "Tab",
2515 "Escape",
2516 "Backspace",
2517 "Delete",
2518 "Home",
2519 "End",
2520 "PageUp",
2521 "PageDown",
2522 "Insert",
2523 "F1",
2524 "F2",
2525 "F3",
2526 "F4",
2527 "F5",
2528 "F6",
2529 "F7",
2530 "F8",
2531 "F9",
2532 "F10",
2533 "F11",
2534 "F12",
2535 ];
2536
2537 /// A press of `key` with `modifiers` held that typed nothing.
2538 #[must_use]
2539 pub fn new(key: Key, modifiers: Modifiers) -> KeyEvent {
2540 KeyEvent {
2541 key,
2542 modifiers,
2543 text: None,
2544 phase: KeyPhase::Down,
2545 }
2546 }
2547
2548 /// This event in another phase: `KeyEvent::new(Key::ArrowLeft, Modifiers::NONE)`
2549 /// `.with_phase(KeyPhase::Up)` is the release. A release carries no text.
2550 #[must_use]
2551 pub fn with_phase(mut self, phase: KeyPhase) -> KeyEvent {
2552 self.phase = phase;
2553 if phase == KeyPhase::Up {
2554 self.text = None;
2555 }
2556 self
2557 }
2558
2559 /// The text this press typed ([`KeyEvent::text`]), or `None` for a key that typed nothing.
2560 #[must_use]
2561 pub fn typed(&self) -> Option<&str> {
2562 self.text.as_deref()
2563 }
2564
2565 /// A key that types nothing (a named key, or a chord's character under Control or Alt),
2566 /// on either route. A backend passes the key's web name and its wire modifier mask; both
2567 /// convert ([`Key::from_name`], [`Modifiers::from_bits`]).
2568 pub fn named(key: impl Into<Key>, modifiers: impl Into<Modifiers>) -> KeyEvent {
2569 KeyEvent::new(key.into(), modifiers.into())
2570 }
2571
2572 /// Text a press committed on the full route. The key is the text's character when the
2573 /// text is one character (the press typed it), and [`Key::Unidentified`] for a longer
2574 /// commit, which no single key is behind.
2575 pub fn typed_text(text: impl Into<String>, modifiers: impl Into<Modifiers>) -> KeyEvent {
2576 let text = text.into();
2577 let mut chars = text.chars();
2578 let key = match (chars.next(), chars.next()) {
2579 (Some(c), None) => Key::Character(c),
2580 _ => Key::Unidentified,
2581 };
2582 KeyEvent {
2583 key,
2584 modifiers: modifiers.into(),
2585 text: Some(text),
2586 phase: KeyPhase::Down,
2587 }
2588 }
2589
2590 /// Text a press committed on the full route, with the key that produced it when the
2591 /// backend knows it.
2592 pub fn typed_by(
2593 key: impl Into<Key>,
2594 text: impl Into<String>,
2595 modifiers: impl Into<Modifiers>,
2596 ) -> KeyEvent {
2597 KeyEvent {
2598 key: key.into(),
2599 modifiers: modifiers.into(),
2600 text: Some(text.into()),
2601 phase: KeyPhase::Down,
2602 }
2603 }
2604
2605 /// The web name for the function key `F<n>`, `1..=12`.
2606 #[must_use]
2607 pub fn function_name(n: u8) -> Option<&'static str> {
2608 match n {
2609 1..=12 => Some(Self::NAMED[13 + n as usize]),
2610 _ => None,
2611 }
2612 }
2613
2614 /// The key name for a typed character when it is one of the ten digits: what a backend
2615 /// reports for a keypress that types `0`–`9`.
2616 #[must_use]
2617 pub fn digit_name(c: char) -> Option<&'static str> {
2618 c.to_digit(10).map(|d| Self::DIGITS[d as usize])
2619 }
2620
2621 /// The value of a digit key, or `None` for every other key.
2622 #[must_use]
2623 pub fn digit(&self) -> Option<u8> {
2624 self.key.digit()
2625 }
2626
2627 /// Whether Shift is held.
2628 #[must_use]
2629 pub fn shift(&self) -> bool {
2630 self.modifiers.shift()
2631 }
2632 /// Whether the platform's command key is held ([`Modifiers::PRIMARY`]).
2633 #[must_use]
2634 pub fn primary(&self) -> bool {
2635 self.modifiers.primary()
2636 }
2637 /// Whether Alt (Option) is held.
2638 #[must_use]
2639 pub fn alt(&self) -> bool {
2640 self.modifiers.alt()
2641 }
2642 /// Whether the Control key itself is held ([`Modifiers::CONTROL`]).
2643 #[must_use]
2644 pub fn control(&self) -> bool {
2645 self.modifiers.control()
2646 }
2647 /// Whether the key went down or repeated: what `Decorate::on_key` delivers.
2648 #[must_use]
2649 pub fn is_press(&self) -> bool {
2650 self.phase != KeyPhase::Up
2651 }
2652 /// Whether this is the platform repeating a held key.
2653 #[must_use]
2654 pub fn is_repeat(&self) -> bool {
2655 self.phase == KeyPhase::Repeat
2656 }
2657 /// Whether the key came up.
2658 #[must_use]
2659 pub fn is_release(&self) -> bool {
2660 self.phase == KeyPhase::Up
2661 }
2662}
2663
2664#[cfg(test)]
2665mod key_event_tests {
2666 use super::{Key, KeyEvent, KeyPhase, Modifiers};
2667
2668 #[test]
2669 fn digit_names_read_back_as_values() {
2670 for (value, c) in ('0'..='9').enumerate() {
2671 let name = KeyEvent::digit_name(c).expect("an ASCII digit names itself");
2672 let key = KeyEvent::named(name, 0);
2673 assert_eq!(key.digit(), Some(value as u8));
2674 }
2675 // Only the ASCII digits: a letter, an Arabic-Indic three, and a named key are not.
2676 assert_eq!(KeyEvent::digit_name('a'), None);
2677 assert_eq!(KeyEvent::digit_name('٣'), None);
2678 let arrow = KeyEvent::named("ArrowUp", 0);
2679 assert_eq!(arrow.digit(), None);
2680 assert_eq!(arrow.key, Key::ArrowUp);
2681 }
2682
2683 #[test]
2684 fn typed_text_is_told_from_named_keys() {
2685 let a = KeyEvent::typed_text("a", 0);
2686 assert_eq!((a.key, a.typed()), (Key::Character('a'), Some("a")));
2687 let space = KeyEvent::typed_text(" ", 0);
2688 assert_eq!((space.key, space.typed()), (Key::Character(' '), Some(" ")));
2689 assert_eq!(KeyEvent::typed_text("7", 0).digit(), Some(7));
2690 // A longer commit has no key behind it.
2691 let phrase = KeyEvent::typed_text("こんにちは", 0);
2692 assert_eq!(
2693 (phrase.key, phrase.typed()),
2694 (Key::Unidentified, Some("こんにちは"))
2695 );
2696 // Text that spells a key name is still text, and the key is still a key.
2697 for name in KeyEvent::NAMED {
2698 let key = KeyEvent::named(name, 0);
2699 assert_eq!(key.typed(), None, "{name} types nothing");
2700 assert_ne!(key.key, Key::Unidentified, "{name} is in the vocabulary");
2701 assert_eq!(key.key.name(), name, "{name} round-trips");
2702 assert_eq!(KeyEvent::typed_text(name, 0).typed(), Some(name));
2703 }
2704 let accent = KeyEvent::typed_by("e", "é", 0);
2705 assert_eq!(
2706 (accent.key, accent.typed()),
2707 (Key::Character('e'), Some("é"))
2708 );
2709 assert_eq!(KeyEvent::function_name(1), Some("F1"));
2710 assert_eq!(KeyEvent::function_name(12), Some("F12"));
2711 assert_eq!(KeyEvent::function_name(13), None);
2712 let chord = KeyEvent::named("c", Modifiers::CONTROL | Modifiers::SHIFT);
2713 assert!(chord.control() && chord.shift() && !chord.primary());
2714 assert_eq!(chord.typed(), None);
2715 }
2716
2717 #[test]
2718 fn names_modifiers_and_phases_convert_at_the_wire() {
2719 assert_eq!(Key::from_name("Space"), Key::Character(' '));
2720 assert_eq!(Key::from_name("F12"), Key::F(12));
2721 assert_eq!(Key::from_name("F13"), Key::Unidentified);
2722 assert_eq!(Key::from_name(""), Key::Unidentified);
2723 assert_eq!(Key::Enter.shortcut_name(), "Return");
2724 assert_eq!(Key::ArrowLeft.shortcut_name(), "Left");
2725 assert_eq!(Key::Character('s').shortcut_name(), "s");
2726 let mask = Modifiers::SHIFT.bits() | Modifiers::ALT.bits();
2727 let mods = Modifiers::from_bits(mask);
2728 assert!(mods.shift() && mods.alt() && !mods.primary() && !mods.control());
2729 assert!(mods.contains(Modifiers::SHIFT) && !mods.contains(Modifiers::PRIMARY));
2730 assert!(Modifiers::NONE.is_empty() && !mods.is_empty());
2731 // The phase rides above the mask on the numeric wire.
2732 assert_eq!(KeyPhase::from_wire(f64::from(mask)), KeyPhase::Down);
2733 assert_eq!(
2734 KeyPhase::from_wire(f64::from(u16::from(mask) | 1 << 8)),
2735 KeyPhase::Repeat
2736 );
2737 assert_eq!(
2738 KeyPhase::from_wire(f64::from(u16::from(mask) | 2 << 8)),
2739 KeyPhase::Up
2740 );
2741 let up = KeyEvent::typed_text("a", 0).with_phase(KeyPhase::Up);
2742 assert!(up.is_release() && !up.is_press() && up.typed().is_none());
2743 assert!(
2744 KeyEvent::new(Key::Tab, Modifiers::NONE)
2745 .with_phase(KeyPhase::Repeat)
2746 .is_repeat()
2747 );
2748 }
2749
2750 #[test]
2751 fn a_declaration_claims_nothing_without_a_handler() {
2752 let node = super::NodeId(0xdead_0001);
2753 super::keys::mark_text(node);
2754 assert!(!super::keys::text(node), "no handler, no claim");
2755 super::keys::mark(node);
2756 assert!(super::keys::text(node) && super::keys::handled(node));
2757 super::keys::forget(node);
2758 assert!(!super::keys::text(node) && !super::keys::handled(node));
2759 }
2760}
2761
2762/// The kind of device behind a pointer (docs/gestures.md "Input kind"): what
2763/// `day::primary_pointer()` tracks and a [`Touch`] carries.
2764#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
2765pub enum PointerKind {
2766 /// A finger on a touch screen.
2767 Touch,
2768 /// A mouse or a trackpad: a pointer that hovers.
2769 #[default]
2770 Mouse,
2771 /// A stylus or pencil.
2772 Stylus,
2773}
2774
2775impl PointerKind {
2776 /// The kind a platform's users reach for first, before any input arrives: touch on a
2777 /// phone or tablet OS, a mouse elsewhere. [`Toolkit::primary_pointer`] starts from it.
2778 #[must_use]
2779 pub fn platform_default() -> PointerKind {
2780 if cfg!(any(
2781 target_os = "ios",
2782 target_os = "android",
2783 target_env = "ohos"
2784 )) {
2785 PointerKind::Touch
2786 } else {
2787 PointerKind::Mouse
2788 }
2789 }
2790
2791 /// Whether this pointer hovers (a mouse, a trackpad, or a stylus that reports proximity).
2792 #[must_use]
2793 pub fn hovers(self) -> bool {
2794 self != PointerKind::Touch
2795 }
2796
2797 /// The name a backend's wire and a dayscript step spell this kind with.
2798 #[must_use]
2799 pub fn name(self) -> &'static str {
2800 match self {
2801 PointerKind::Touch => "touch",
2802 PointerKind::Mouse => "mouse",
2803 PointerKind::Stylus => "stylus",
2804 }
2805 }
2806
2807 /// The kind `name` spells ([`PointerKind::name`]), or `None`.
2808 #[must_use]
2809 pub fn from_name(name: &str) -> Option<PointerKind> {
2810 match name {
2811 "touch" => Some(PointerKind::Touch),
2812 "mouse" => Some(PointerKind::Mouse),
2813 "stylus" => Some(PointerKind::Stylus),
2814 _ => None,
2815 }
2816 }
2817}
2818
2819/// Where one contact of a multi-touch sequence is ([`Touch::phase`]).
2820#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
2821pub enum TouchPhase {
2822 /// The contact went down.
2823 Began,
2824 /// The contact moved.
2825 Moved,
2826 /// The contact is down and did not move in this event.
2827 Stationary,
2828 /// The contact lifted.
2829 Ended,
2830 /// The platform took the contact away (a system gesture, an enclosing scroll view).
2831 Cancelled,
2832}
2833
2834/// One contact of a raw multi-touch event (`Decorate::on_touches`, docs/gestures.md "Touches").
2835///
2836/// Build one with [`Touch::new`], then [`Touch::with_pressure`] and [`Touch::with_kind`].
2837#[derive(Clone, Copy, Debug, PartialEq)]
2838#[non_exhaustive]
2839pub struct Touch {
2840 /// Stable for the life of the contact, from `Began` to `Ended` or `Cancelled`; reused
2841 /// afterwards.
2842 pub id: u64,
2843 pub phase: TouchPhase,
2844 /// In the piece's own coordinates, in points.
2845 pub location: Point,
2846 /// Contact force from 0 to 1; 1 where the device reports none.
2847 pub pressure: f64,
2848 /// The device behind the contact.
2849 pub kind: PointerKind,
2850}
2851
2852impl Touch {
2853 /// A finger contact at full pressure.
2854 #[must_use]
2855 pub fn new(id: u64, phase: TouchPhase, location: Point) -> Touch {
2856 Touch {
2857 id,
2858 phase,
2859 location,
2860 pressure: 1.0,
2861 kind: PointerKind::Touch,
2862 }
2863 }
2864
2865 /// This contact with a reported force (clamped to 0 through 1).
2866 #[must_use]
2867 pub fn with_pressure(mut self, pressure: f64) -> Touch {
2868 self.pressure = pressure.clamp(0.0, 1.0);
2869 self
2870 }
2871
2872 /// This contact from another kind of device.
2873 #[must_use]
2874 pub fn with_kind(mut self, kind: PointerKind) -> Touch {
2875 self.kind = kind;
2876 self
2877 }
2878
2879 /// Whether the contact is on the surface after this event.
2880 #[must_use]
2881 pub fn is_down(&self) -> bool {
2882 !matches!(self.phase, TouchPhase::Ended | TouchPhase::Cancelled)
2883 }
2884}
2885
2886/// Where user-driven scrolling stands ([`Event::ScrollPhase`], docs/scroll.md "Offset and
2887/// phase").
2888#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
2889pub enum ScrollPhase {
2890 /// Nothing the user did is moving the content.
2891 #[default]
2892 Idle,
2893 /// The user is moving the content: a finger is down and dragging, or a wheel or trackpad
2894 /// gesture is in progress.
2895 Dragging,
2896 /// The user let go and the content is still moving: momentum, a bounce settling, or a snap
2897 /// to a page. A toolkit that cannot tell this from [`ScrollPhase::Dragging`] never sends it.
2898 Coasting,
2899}
2900
2901/// What a recycling list shows, as its host reports it through [`ListSource::viewport`]
2902/// (docs/list.md "Visible rows"); day-core passes it on as [`Event::ListViewport`].
2903///
2904/// The host counts the rows [`ListSource::len`] counts (headers and supplementary rows
2905/// included); day-core translates to the app's items before the piece sees the report.
2906#[derive(Clone, Copy, Debug, PartialEq)]
2907pub struct ListViewport {
2908 /// The first row with any part inside the viewport, overscan excluded.
2909 pub first: usize,
2910 /// The last row with any part inside the viewport, overscan excluded. Never less than
2911 /// `first`.
2912 pub last: usize,
2913 /// How far the viewport's end is from the end of the content, in points: `0.0` when the
2914 /// list is scrolled all the way to its end or its rows fit the viewport, never negative
2915 /// (an overscroll bounce reports `0.0`). A host that estimates the heights of rows it has
2916 /// not laid out reports the estimate.
2917 pub end_distance: f64,
2918}
2919
2920/// Where a row lands in the viewport when a list scrolls to it ([`ListScroll::align`]).
2921#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
2922pub enum RowAlign {
2923 /// The least movement that makes the whole row visible; a row already in view stays put.
2924 #[default]
2925 Nearest,
2926 /// The row's top edge at the top of the viewport.
2927 Start,
2928 /// The row centered in the viewport.
2929 Center,
2930 /// The row's bottom edge at the bottom of the viewport.
2931 End,
2932}
2933
2934/// One programmatic scroll of a recycling list ([`Toolkit::list_scroll`], docs/list.md
2935/// "Programmatic scrolling").
2936#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2937pub struct ListScroll {
2938 /// The row to bring into view, counted as [`ListSource::len`] counts rows and already
2939 /// clamped to it; `None` scrolls to the very end of the content.
2940 pub row: Option<usize>,
2941 /// Where the row lands. Ignored for `row: None`.
2942 pub align: RowAlign,
2943 /// Scroll with the platform's standard scroll animation, or jump.
2944 pub animated: bool,
2945}
2946
2947/// The event sink: enqueue-only. It may be invoked re-entrantly from inside any Toolkit method;
2948/// day-core drains queued events at safe points, each as a fresh batch (§3.3).
2949pub type EventSink = Box<dyn Fn(NodeId, Event)>;
2950
2951/// The synchronous row-pull closures for recycling lists (docs/list.md, §10). day-core injects one
2952/// per `LIST` host via [`Toolkit::attach_list`]; a recycling backend stores it and calls it from
2953/// its native data-source (on the UI thread, outside any day-core borrow). Each closure re-enters
2954/// day-core, so, unlike [`EventSink`], these run to completion synchronously (`bind_row` even
2955/// flushes + lays out the row before returning, so the host can measure the cell immediately).
2956#[derive(Clone)]
2957pub struct ListSource {
2958 /// Report the first actually visible row (exclude overscan). Enqueue-only; optional,
2959 /// so hosts without a viewport binding incur no app event work.
2960 pub first_visible: Option<std::rc::Rc<dyn Fn(usize)>>,
2961 /// Report what the list shows (docs/list.md "Visible rows"): the first and last visible
2962 /// rows and the distance from the viewport's end to the content's end. Present when the
2963 /// piece observes the viewport (`visible_rows`, `follow_end`, `on_end_reached`); a host
2964 /// calls it whenever any of the three values may have changed: after a scroll (the
2965 /// user's or a programmatic one), after the list is resized, and after a reload or a
2966 /// splice has been laid out. Enqueue-only and deduplicated by day-core, so a host may
2967 /// call it on every scroll callback. It supersedes `first_visible`: a host that calls
2968 /// this one need not call the other.
2969 pub viewport: Option<std::rc::Rc<dyn Fn(ListViewport)>>,
2970 /// Report that the reader started moving the list themselves (docs/list.md "Following
2971 /// the end"): a drag, a wheel or trackpad scroll, the scroll bar, or a key that scrolls.
2972 /// Never a scroll the reader did not start: [`Toolkit::list_scroll`], a reload or splice,
2973 /// a resize, or the momentum of a scroll the app asked for. Present when the piece follows
2974 /// the end (`follow_end`); a host that answers [`Cap::ListReaderScroll`] calls it as each
2975 /// such scroll begins (more calls during one are harmless). Enqueue-only.
2976 pub reader_scroll: Option<std::rc::Rc<dyn Fn()>>,
2977 /// Present when the list has rows that are neither items nor section headers
2978 /// (docs/list.md "Header, footer and empty state"): whether row `index` is such a
2979 /// supplementary row (the list's header, footer, empty state, or content padding). The
2980 /// host sizes it to its content even in a `Uniform` list (`cell_height` answers it),
2981 /// draws no separator, selection or swipe affordance on it, never drags it, never pins
2982 /// it, and gives it no group-header styling: it is plain content that scrolls with the
2983 /// rows. `is_header` answers `false` for it.
2984 pub is_supplement: Option<std::rc::Rc<dyn Fn(usize) -> bool>>,
2985 /// Current row count.
2986 pub len: std::rc::Rc<dyn Fn() -> usize>,
2987 /// Present on a sectioned list (`ListProps::sections`, docs/list.md "Sections"): whether
2988 /// row `index` is a section header. Every row index the host sees counts headers, and
2989 /// day-core translates to the app's items. A header row is not selectable, activatable or
2990 /// swipeable; the host draws it in its platform's group-header style, sized to its content
2991 /// even in a `Uniform` list, and floats it where the platform does (macOS group rows,
2992 /// UIKit plain-table section headers).
2993 pub is_header: Option<std::rc::Rc<dyn Fn(usize) -> bool>>,
2994 /// Stable identity token for the row at `index` (for native diffing / animation).
2995 pub token_at: std::rc::Rc<dyn Fn(usize) -> u64>,
2996 /// Build (first use of this cell) or rebind (recycled cell) row `index` into the native cell.
2997 pub bind_row: std::rc::Rc<dyn Fn(usize, RawHandle)>,
2998 /// A host that emulates `Cap::ListSections` binds the header it pins over the top of the
2999 /// list with this instead of `bind_row` (docs/list.md "Sections"): the same build or
3000 /// rebind, but the copy carries no element ids, so a dayscript or accessibility lookup of a
3001 /// header finds the header row in the list, never its pinned copy.
3002 pub bind_pinned: std::rc::Rc<dyn Fn(usize, RawHandle)>,
3003 /// The native cell left the viewport; Day may drop per-cell bookkeeping (optional).
3004 pub recycle: std::rc::Rc<dyn Fn(RawHandle)>,
3005 /// The native host is done with this cell for good (a `GtkListItemFactory::teardown`, a
3006 /// `UITableViewCell` deallocating): Day disposes the row it built there, its scope, nodes
3007 /// and element ids. Without this a host that discards cells, as every pool does on a far
3008 /// jump, leaves one dead row behind in day-core per discarded cell. Safe inside a day-core
3009 /// borrow (the work is held for the borrow's end) and for a cell Day never saw.
3010 pub release: std::rc::Rc<dyn Fn(RawHandle)>,
3011 /// Re-lay the row bound to this cell at `width`, called from the cell's own native layout
3012 /// pass, the hook [`TreeSource::layout_cell`] already gives trees. day-core lays a row at the
3013 /// `LIST`'s width first, which is right wherever the cell is the row itself; a backend
3014 /// whose native row wraps the cell in chrome (`GtkListView`'s themed `row` node pads it)
3015 /// corrects it here, so the row fits the cell the platform gave it instead of holding the
3016 /// whole list wider than its frame. Skips quietly when called inside a day-core borrow (a
3017 /// snapshot pass).
3018 pub layout_cell: std::rc::Rc<dyn Fn(RawHandle, f64)>,
3019 /// The height day-core last laid the row bound to this cell at: the row's own height,
3020 /// padding included, as `RowHeight` resolves it. A backend whose cell measures itself
3021 /// (`GtkListView`'s `DayCell`) reports it as the cell's height, so a padded row keeps its
3022 /// bottom padding rather than the height of its last child's frame. `0.0` before the row's
3023 /// first layout, or inside a day-core borrow.
3024 pub cell_height: std::rc::Rc<dyn Fn(RawHandle) -> f64>,
3025 /// Drag-to-reorder closures, present when `ListProps::reorderable` (docs/list.md). `None` on
3026 /// non-reorderable lists; backends must not enable their drag machinery without it.
3027 pub reorder: Option<ListReorder>,
3028 /// Swipe-to-delete closures, present when `ListProps::deletable` (docs/list.md). `None` on
3029 /// non-deletable lists; backends must not offer their delete affordance without it.
3030 pub delete: Option<ListDelete>,
3031 /// Swipe-actions closures, present when `ListProps::swipe_actions` (docs/list.md). `None` on
3032 /// lists that declared none; backends must not install their row-action machinery
3033 /// without it.
3034 pub swipe: Option<ListSwipe>,
3035}
3036
3037/// The synchronous drag-to-reorder half of [`ListSource`] (docs/list.md). Both closures follow
3038/// `bind_row`'s discipline: called on the UI thread from inside native drag callbacks, outside
3039/// any day-core borrow, and they run to completion synchronously.
3040#[derive(Clone)]
3041pub struct ListReorder {
3042 /// May row `from` drop at row `to`? Called from the native validate/hover hook so the
3043 /// affordance (gap, insertion mark, forbidden cursor) reflects the app's answer live.
3044 /// Returns the accepted target index: `to` itself to allow, another index to retarget the
3045 /// drop, or `-1` to deny.
3046 pub can_move: std::rc::Rc<dyn Fn(usize, usize) -> i64>,
3047 /// Commit: row `from` dropped at row `to` (an index `can_move` accepted). Rotates Day's row
3048 /// snapshot before returning (so `len`/`token_at`/`bind_row` reflect the new order while the
3049 /// native move animates) and defers the app's own callback to the next event drain.
3050 pub move_row: std::rc::Rc<dyn Fn(usize, usize)>,
3051}
3052
3053/// The synchronous swipe-to-delete half of [`ListSource`] (docs/list.md), shaped exactly like
3054/// [`ListReorder`]: both closures are called on the UI thread from inside native swipe callbacks,
3055/// outside any day-core borrow, and run to completion synchronously.
3056///
3057/// Each platform spells the gesture its own way (a trailing swipe action on iOS, an
3058/// `ItemTouchHelper` swipe on Android, a `ListItem` swipe action on ArkUI), but all three ask the
3059/// same two questions, so this struct is one pair of closures rather than three shapes.
3060#[derive(Clone)]
3061pub struct ListDelete {
3062 /// May row `index` be deleted? Called before the affordance is offered, so a row the app
3063 /// protects shows no delete action at all rather than one that fails on use.
3064 pub can_delete: std::rc::Rc<dyn Fn(usize) -> bool>,
3065 /// Commit: delete row `index`. Removes it from Day's row snapshot before returning (so
3066 /// `len`/`token_at`/`bind_row` already reflect the shorter list while the native row-removal
3067 /// animates) and defers the app's own callback to the next event drain.
3068 pub delete_row: std::rc::Rc<dyn Fn(usize)>,
3069}
3070
3071/// Which edge of a row a swipe action rides (docs/list.md). Semantic, not geometric:
3072/// `Leading` follows the reading direction (the left edge in LTR, the right in RTL), the
3073/// mapping every platform's swipe API already makes.
3074#[derive(Clone, Copy, Debug, PartialEq, Eq)]
3075pub enum SwipeEdge {
3076 Leading,
3077 Trailing,
3078}
3079
3080/// One offered swipe action (docs/list.md): pure data. The pieces layer keeps the handlers;
3081/// the backend answers a tap through [`ListSwipe::perform`] by index into the offer.
3082#[derive(Clone, Debug, PartialEq)]
3083pub struct ListSwipeAction {
3084 /// The word on the button, already localized (a toolkit cannot translate).
3085 pub label: String,
3086 /// Destructive styling: the platform's red.
3087 pub destructive: bool,
3088 /// Explicit button color; `None` = the platform's default for the style.
3089 pub tint: Option<Ink>,
3090 /// A glyph for the button where the platform draws one: above the label on macOS, in
3091 /// place of it on iOS (docs/list.md).
3092 pub symbol: Option<Symbol>,
3093}
3094
3095/// The synchronous swipe-actions half of [`ListSource`] (docs/list.md), the generalized
3096/// sibling of [`ListDelete`]: reveal-as-you-swipe buttons on either row edge. The offer is
3097/// pulled per row at gesture time, so labels follow row state ("Mark Read" on an unread row,
3098/// "Mark Unread" on a read one); the commit defers to the event drain like every closure here.
3099#[derive(Clone)]
3100pub struct ListSwipe {
3101 /// The offer: the actions for row `index` on `edge`, called inside the platform's swipe
3102 /// callback, so keep it pure. Empty = no affordance for that row and edge. The first action
3103 /// is the full-swipe action where the platform activates one at the far edge.
3104 pub actions_at: std::rc::Rc<dyn Fn(usize, SwipeEdge) -> Vec<ListSwipeAction>>,
3105 /// The commit: the user activated action `action` (an index into the offer) on row
3106 /// `index`, `edge`. Unlike a delete this never reshapes the row snapshot; the app's
3107 /// handler is deferred to the next event drain, never run inside the native callback.
3108 pub perform: std::rc::Rc<dyn Fn(usize, SwipeEdge, usize)>,
3109}
3110
3111/// The synchronous row-pull closures for hierarchical trees (docs/tree.md): [`ListSource`]'s
3112/// shape, addressed by token instead of row index, because expanding a row renumbers every
3113/// index below it while tokens hold still. day-core injects one per `TREE` host via
3114/// [`Toolkit::attach_tree`]; the backend answers its native data-source from it. The same
3115/// synchronous discipline as [`ListSource`]: UI thread, outside any day-core borrow;
3116/// `bind_row` flushes and lays the row out before returning.
3117#[derive(Clone)]
3118pub struct TreeSource {
3119 /// How many children `parent` has (`None` = the root level).
3120 pub children_len: std::rc::Rc<dyn Fn(Option<u64>) -> usize>,
3121 /// The i-th child of `parent`: the stable token every backend keys its rows by.
3122 pub child_token: std::rc::Rc<dyn Fn(Option<u64>, usize) -> u64>,
3123 /// Whether this token can hold children at all: what draws (or omits) the disclosure.
3124 pub expandable: std::rc::Rc<dyn Fn(u64) -> bool>,
3125 /// Non-selectable section heading, separate from a navigation destination.
3126 pub section_header: std::rc::Rc<dyn Fn(u64) -> bool>,
3127 /// Current desired expansion, including restoration before the first native reload.
3128 pub expanded: std::rc::Rc<dyn Fn(u64) -> bool>,
3129 /// Build (first use of this cell) or rebind (recycled cell) the row for `token` into the
3130 /// native cell.
3131 pub bind_row: std::rc::Rc<dyn Fn(u64, RawHandle)>,
3132 /// The native cell left the viewport; Day may drop per-cell bookkeeping (optional).
3133 pub recycle: std::rc::Rc<dyn Fn(RawHandle)>,
3134 /// Re-lay the row bound to this cell at `width`, called from the cell's own native
3135 /// layout pass. Trees need this where lists don't: indentation makes every cell's
3136 /// content width per-row, so the host-width layout `bind_row` did is only a first
3137 /// approximation. Skips quietly when called inside a day-core borrow (a snapshot pass).
3138 pub layout_cell: std::rc::Rc<dyn Fn(RawHandle, f64)>,
3139 /// Native bounds for controls whose group headers have a different height from leaves.
3140 /// Overrides the initial row-height estimate and preserves the native height on rebind.
3141 pub layout_cell_size: std::rc::Rc<dyn Fn(RawHandle, Size)>,
3142 /// The height day-core last laid this cell's row at (see [`ListSource::cell_height`]).
3143 pub cell_height: std::rc::Rc<dyn Fn(RawHandle) -> f64>,
3144 /// The row's type-ahead string (docs/tree.md): what native type-select matches against.
3145 pub type_select_text: std::rc::Rc<dyn Fn(u64) -> String>,
3146 /// The row's context menu, built when the menu is summoned (docs/menus.md "Dynamic context
3147 /// menus"), called on the UI thread from the platform's own menu callback, outside any
3148 /// day-core borrow, like every closure here. `None` = rows carry no menu; an empty
3149 /// result suppresses the menu for that row.
3150 pub row_menu: Option<std::rc::Rc<dyn Fn(u64) -> Vec<MenuItem>>>,
3151 /// Drag-to-move closures, present when `TreeProps::movable` (docs/tree.md). `None` on
3152 /// immovable trees; backends must not enable their drag machinery without it.
3153 pub moves: Option<TreeMoves>,
3154}
3155
3156/// The synchronous drag half of [`TreeSource`] (docs/tree.md). Both closures follow
3157/// `bind_row`'s discipline: called on the UI thread from inside native drag callbacks.
3158#[derive(Clone)]
3159pub struct TreeMoves {
3160 /// The live verdict, consulted while the drag is over a target: may `token` land under
3161 /// `parent` at `index`? `index: None` means "dropped onto the parent" (append). Pure, since
3162 /// it runs inside the platform's drag-validate callback.
3163 #[allow(clippy::type_complexity)]
3164 pub can_move: std::rc::Rc<dyn Fn(u64, Option<u64>, Option<usize>) -> MoveVerdict>,
3165 /// Commit an accepted drop. Defers the app's `on_move` through the event queue
3166 /// ([`Event::TreeMove`]); the app's own data write drives the reload.
3167 #[allow(clippy::type_complexity)]
3168 pub move_node: std::rc::Rc<dyn Fn(u64, Option<u64>, Option<usize>)>,
3169}
3170
3171/// A summon-time context-menu provider (docs/menus.md): local-point in, menu out.
3172pub type ContextMenuFn = std::rc::Rc<dyn Fn(Point) -> Vec<MenuItem>>;
3173
3174/// Ask a menu button's provider for its menu at press time ([`Toolkit::set_button_menu`]), and
3175/// answer the items to show, or `None` to show nothing: an empty menu, or a provider that
3176/// removed its own button. The provider is app code; a signal it writes can rebuild the tree
3177/// synchronously and release the very button being pressed. `still_registered` asks the
3178/// toolkit's own registry, AFTER the provider has returned, whether the button is still the one
3179/// registered for this press; a toolkit holding a raw native handle must not touch it otherwise.
3180pub fn resolve_button_menu(
3181 provider: &ContextMenuFn,
3182 still_registered: impl FnOnce() -> bool,
3183) -> Option<Vec<MenuItem>> {
3184 let items = provider(Point::ZERO);
3185 if items.is_empty() || !still_registered() {
3186 return None;
3187 }
3188 Some(items)
3189}
3190
3191/// A tree move guard's verdict (docs/tree.md). No `Retarget` yet: the drop vocabulary is
3192/// already positional, so a guard that wants a different target denies and the user drops
3193/// where it is allowed.
3194#[derive(Clone, Copy, Debug, PartialEq, Eq)]
3195pub enum MoveVerdict {
3196 Allow,
3197 Deny,
3198}
3199
3200/// One addressable widget within a composite native backing (docs/tree.md,
3201/// docs/tweaks.md), Qt's name for the concept (`QStyle::SubControl`). A `list`'s or
3202/// `tree`'s node handle is its scroller; `Subcontrol::Content` is the widget inside it.
3203/// Backends resolve an unknown subcontrol to `None`, never to the host.
3204#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
3205pub enum Subcontrol {
3206 /// The node's own handle: what every tweak accessor reached before subcontrols existed.
3207 Host,
3208 /// The content widget inside the scroller (`NSOutlineView`, `NSTableView`, …).
3209 Content,
3210 /// The header view, where the widget has one. Day's lists and trees ship headerless, so
3211 /// this answers `None` until a kind grows a header.
3212 Header,
3213}
3214
3215// ---------------------------------------------------------------------------
3216// Capabilities, animation, a11y
3217// ---------------------------------------------------------------------------
3218
3219/// What to show on the app's icon in the Dock, launcher, home screen, or taskbar (docs/badge.md).
3220///
3221/// Distinct from `NavItem::badge`, which annotates a sidebar row inside the window. This one
3222/// decorates the application itself and is drawn by the shell, not by Day.
3223///
3224/// What each payload needs is asked separately (`Cap::AppBadgeCount`, `AppBadgeText`,
3225/// `AppBadgeDot`) because the platforms differ in what they accept more than in whether they have
3226/// a badge at all: macOS takes arbitrary text, iOS and the web take a number, Android takes nothing.
3227#[derive(Clone, Debug, PartialEq, Eq, Default)]
3228pub enum AppBadge {
3229 /// Clear the badge.
3230 #[default]
3231 None,
3232 /// A count. Zero clears it, matching every platform's own convention.
3233 Count(u32),
3234 /// Short arbitrary text (`"99+"`, `"beta"`). Only macOS renders it; probe `Cap::AppBadgeText`.
3235 Text(String),
3236 /// An indicator with no value.
3237 Dot,
3238}
3239
3240/// How wide a window is, in coarse buckets (docs/size-classes.md).
3241///
3242/// The breakpoints are Android's window size classes, in density-independent points, and they are
3243/// used verbatim on every backend rather than per-platform. One table means one answer: a 700pt
3244/// window is [`WidthClass::Medium`] on a Mac, in a browser, and on a tablet, so an app that lays
3245/// out from the class gets the same layout at the same size everywhere. Apple publishes only two
3246/// buckets (compact/regular); those map onto this table rather than replacing it, with
3247/// [`WidthClass::Compact`] the compact one and everything above it regular.
3248#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug, Default)]
3249pub enum WidthClass {
3250 /// `< 600dp`: a phone in portrait. One pane at a time.
3251 #[default]
3252 Compact,
3253 /// `600–839dp`: a tablet in portrait, a narrow desktop window.
3254 Medium,
3255 /// `840–1199dp`: a tablet in landscape, a typical desktop window.
3256 Expanded,
3257 /// `1200–1599dp`: a large desktop window.
3258 Large,
3259 /// `≥ 1600dp`: a maximized window on a big display.
3260 ExtraLarge,
3261}
3262
3263/// How tall a window is (docs/size-classes.md). Consulted far less than [`WidthClass`]: it is
3264/// what tells a phone in landscape (wide enough for two panes, too short for a tall list) that
3265/// it should not grow vertical chrome.
3266#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug, Default)]
3267pub enum HeightClass {
3268 /// `< 480dp`: a phone in landscape.
3269 #[default]
3270 Compact,
3271 /// `480–899dp`: a phone in portrait, a tablet in landscape.
3272 Medium,
3273 /// `≥ 900dp`: a tablet in portrait, most desktop windows.
3274 Expanded,
3275}
3276
3277/// A window's size class (docs/size-classes.md), reported by the backend and read by apps
3278/// through `day::size_class()`.
3279///
3280/// Per-window, not per-app: two windows of one process can sit in different classes at the same
3281/// time (a narrow and a wide window side by side, iPadOS Stage Manager, Android split-screen), and
3282/// an app that keyed off a single global would lay the second window out for the first one's size.
3283#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
3284pub struct SizeClass {
3285 pub width: WidthClass,
3286 pub height: HeightClass,
3287}
3288
3289impl SizeClass {
3290 /// The `Compact`/`Medium` width boundary in dp: the narrowest window where a second
3291 /// pane starts to fit. Backends that hand an adaptive container its pane widths derive
3292 /// them from this (Android's list + minimum-detail widths sum to it), so the platform's
3293 /// measure-time decision and this table agree by construction (docs/size-classes.md).
3294 pub const SPLIT_MIN_WIDTH: f64 = 600.0;
3295
3296 /// Bucket a window's size in points. The one place the breakpoint numbers appear.
3297 #[must_use]
3298 pub fn from_size(width: f64, height: f64) -> Self {
3299 SizeClass {
3300 width: match width {
3301 w if w >= 1600.0 => WidthClass::ExtraLarge,
3302 w if w >= 1200.0 => WidthClass::Large,
3303 w if w >= 840.0 => WidthClass::Expanded,
3304 w if w >= Self::SPLIT_MIN_WIDTH => WidthClass::Medium,
3305 _ => WidthClass::Compact,
3306 },
3307 height: match height {
3308 h if h >= 900.0 => HeightClass::Expanded,
3309 h if h >= 480.0 => HeightClass::Medium,
3310 _ => HeightClass::Compact,
3311 },
3312 }
3313 }
3314
3315 /// Whether a two-pane presentation fits. The rule behind an automatic
3316 /// [`props::NavPresentation`]: anything wider than compact gets both panes.
3317 #[must_use]
3318 pub fn prefers_split(self) -> bool {
3319 self.width > WidthClass::Compact
3320 }
3321}
3322
3323#[derive(Clone, Copy, PartialEq, Eq, Debug)]
3324pub enum Cap {
3325 /// Standard searchfield control.
3326 SearchField,
3327 /// Standard combobox control.
3328 ComboBox,
3329 /// Standard stepper control.
3330 Stepper,
3331 /// Standard datetime control.
3332 DateTimePicker,
3333 /// Standard colorpicker control.
3334 ColorPicker,
3335 /// Standard pullrefresh control.
3336 PullRefresh,
3337 /// Standard pager control.
3338 Pager,
3339 /// User-driven pull recognition, separate from a refresh indicator.
3340 PullRefreshGesture,
3341
3342 /// Native data-transfer source and destination callbacks.
3343 DragDrop,
3344 /// Transfers between independent native applications (inbound).
3345 DragExternalImport,
3346 /// Transfers to independent native applications, including arbitrary binary MIME data.
3347 DragExternalExport,
3348 /// Lossless ordered items and alternatives between Day applications.
3349 DragMultipleItems,
3350 /// Existing native file references, distinct from promised/generated files.
3351 DragFileReferences,
3352 /// Native result can wait for asynchronous data receipt.
3353 DragDeferredReceipt,
3354 /// Generated files supplied to a destination after dropping.
3355 DragFilePromises,
3356 /// External move acknowledgment safe for source deletion.
3357 DragExternalMove,
3358 ListRecycling,
3359 /// The toolkit fronts the app's undo stack with the platform's own undo system
3360 /// ([`Toolkit::set_undo_state`] + `Event::Undo`): `Native` where one exists
3361 /// (`NSUndoManager` on macOS/iOS, `QUndoStack`), `Unsupported` everywhere else, where
3362 /// Day's menu items and accelerators drive the stack directly and nothing platform-owned
3363 /// needs mirroring (docs/model.md).
3364 UndoBridge,
3365 /// The toolkit routes the platform's standard Cut/Copy/Paste to the app's edit bridge
3366 /// ([`Toolkit::set_edit_state`] + `Event::Edit`): the same menu items, shortcuts, and
3367 /// responder precedence the platform's text editing uses; a focused text widget keeps
3368 /// its own clipboard behavior, everything else reaches the app (docs/menus.md).
3369 /// `Native` where a system route exists (the responder chain, the browser's clipboard
3370 /// events), `Emulated` where Day's own menu items dispatch it, `Unsupported` elsewhere.
3371 EditBridge,
3372 /// The toolkit realizes `ListProps::reorderable` as drag-to-reorder rows: `Native` when the
3373 /// platform's own mechanism drives it (`NSTableView` drag/drop, `UITableView` drag delegates,
3374 /// `ItemTouchHelper`, …), `Emulated` for a pointer-tracked fake (web-dom). `Unsupported` ⇒ the
3375 /// list renders normally but rows cannot be dragged (docs/list.md).
3376 ListReorder,
3377 /// Sidebar destinations can be dragged to reorder (`NavBuilder::reorder_items`) and between
3378 /// sections (`NavBuilder::regroup_items`). `Native` when the toolkit's own sidebar drags them
3379 /// (`NavMenuProps::movable`, and across headers under `NavMenuProps::regroup`); `Emulated`
3380 /// when Day stands a reorderable list in for the sidebar. Independent of `ListReorder`: UIKit
3381 /// supports draggable content lists but retains its native navigation collection for
3382 /// sidebars.
3383 NavReorder,
3384 /// The toolkit realizes `ListProps::deletable` as the platform's delete gesture:
3385 /// `Native` where the platform ships one (UIKit's trailing swipe actions, Android's
3386 /// `ItemTouchHelper`, ArkUI's `ListItem.swipeAction`), `Unsupported` on the desktop toolkits,
3387 /// whose lists have no swipe idiom and where deletion belongs to a menu or a button
3388 /// (docs/list.md).
3389 ListDelete,
3390 /// The toolkit realizes `ListProps::swipe_actions` as edge swipe actions: buttons
3391 /// that reveal as the row tracks the swipe, with the far edge activating the first one
3392 /// (docs/list.md). `Native` where the platform ships the affordance: macos-appkit
3393 /// (`NSTableView` row actions, Mail's own machinery) and ios-uikit
3394 /// (`UISwipeActionsConfiguration`). `Unsupported` everywhere else: the affordance is
3395 /// absent, and the app's command lives in its explicit controls.
3396 ListSwipeActions,
3397 /// The toolkit realizes `ListProps::editing` as the platform's list editing mode: rows
3398 /// show their delete controls and reorder grips while the list is editing (docs/list.md).
3399 /// `Native` on ios-uikit (`UITableView` editing). `Unsupported` everywhere else, where a
3400 /// list has no separate editing mode: its rows already drag, swipe and open menus as they
3401 /// are, and the list renders as if `editing` were off.
3402 ListEditing,
3403 /// The toolkit realizes `kinds::LIST_ITEM` as its own list row content (docs/list.md "List
3404 /// items"): `Native` where the platform has a standard row it draws itself (UIKit's
3405 /// `UIListContentConfiguration`, a Material list item, AppKit's image-and-text table cell,
3406 /// a GTK row box), so the row takes the platform's fonts, icon size, spacing, secondary
3407 /// colors and check mark. `Unsupported` ⇒ the `list_item` piece composes the same content
3408 /// from plain pieces. Apps have no reason to probe this; the piece does.
3409 ListItem,
3410 /// The toolkit realizes `kinds::TREE` as a hierarchical tree view (docs/tree.md):
3411 /// `Native` where a platform tree widget hosts Day-built rows (`NSOutlineView`, the UIKit
3412 /// sidebar list, GtkListView+TreeListModel, WinUI `TreeView`, ArkTS `TreeView`), `Emulated`
3413 /// where Day flattens the tree onto its list machinery, `Unsupported` where neither
3414 /// exists yet. An app gates its tree UI on this answer rather than showing a placeholder.
3415 Tree,
3416 /// The toolkit realizes `TreeProps::movable` as drag-to-reparent/restack rows
3417 /// (docs/tree.md). A strictly smaller set than [`Cap::Tree`]: a backend can render a
3418 /// tree it cannot yet drag within.
3419 TreeMove,
3420 /// Native two-level section headers; general trees may still be composed.
3421 TreeSections,
3422 /// The toolkit answers [`Toolkit::first_baseline`], so rows can align text on its baseline
3423 /// rather than on the middle of its box (docs/baseline.md). `Native` where the platform
3424 /// reports the baseline itself (`NSView.firstBaselineOffsetFromTop`, `View.getBaseline`,
3425 /// `gtk_widget_measure`), `Emulated` where Day derives it from the widget's font metrics,
3426 /// `Unsupported` ⇒ baseline-aligned rows fall back to centering and look exactly as they do
3427 /// today.
3428 BaselineAlignment,
3429 /// The toolkit draws a label's [`TextRun`]s: bold, italic, color or a monospace face within
3430 /// one wrapping paragraph (docs/text-runs.md). `Unsupported` ⇒ the label renders its text
3431 /// uniformly, which reads correctly and loses only the emphasis.
3432 TextRuns,
3433 /// The toolkit makes a run carrying [`TextRun::link`] activatable, emitting
3434 /// [`Event::LinkActivated`]. A strictly smaller set than [`Cap::TextRuns`]: several toolkits
3435 /// draw a link run in link colors but have no way to hit-test it, and one (Android) can do
3436 /// links or selection but not both (docs/text-runs.md).
3437 TextLinks,
3438 Lottie,
3439 NativeSymbols,
3440 /// The toolkit can rasterize its window and hand back the pixels
3441 /// (`Toolkit::snapshot_window`): what the dayscript `screenshot` step captures in-process
3442 /// and what `day::window_image()` offers the app (docs/window-image.md). `Unsupported` where
3443 /// a backend cannot draw itself into a bitmap: web-dom, which would need a rasterizer
3444 /// shipped with it. Probe it before offering a "save a screenshot" affordance, rather than
3445 /// offering one that fails when pressed.
3446 Snapshot,
3447 /// The toolkit can present `nav()` as sidebar+detail split panes, a statement about the
3448 /// toolkit, not about the window it is currently drawing. Whether a given host is split right
3449 /// now follows from its [`SizeClass`]: the pieces layer resolves an automatic
3450 /// [`props::NavPresentation`] against both, and re-resolves on every class change. A backend
3451 /// with no split container answers `Unsupported` and stays stacked at every size.
3452 NavSplit,
3453 /// The toolkit can draw a navigation host's rows as its own chrome: a tab bar
3454 /// ([`props::NavPresentation::Tabs`]) and, where it has one, a rail
3455 /// ([`props::NavPresentation::Rail`]). Like [`Self::NavSplit`] this is a statement about the
3456 /// toolkit, not about the window it is drawing right now.
3457 ///
3458 /// This is what `NavStyle::Automatic` resolves against (docs/navigation.md): a backend
3459 /// answering `Unsupported` gets the sidebar resolver instead (`Split` ↔ `Stack`), which is
3460 /// what every backend did before adaptive navigation existed. So an unimplemented backend
3461 /// degrades to its previous behavior rather than to a hole.
3462 ///
3463 /// `Emulated` means the rows are composed from other widgets rather than drawn by a native
3464 /// tab container (Qt, web-dom). `Native` means a real one (`UITabBarController`, a Material
3465 /// `NavigationBarView`, `NavigationView`).
3466 NavTabs,
3467 /// A narrow window should become a tab bar here, a separate question from [`Self::NavTabs`],
3468 /// which only says the toolkit *can* draw one.
3469 ///
3470 /// The two differ on every desktop. macOS, GNOME, Qt and Windows can all draw a tab bar, and
3471 /// must, because an app is free to pin `NavStyle::Tabs`; but none of them grows one when
3472 /// its window is dragged narrow. A narrow Mail.app hides its sidebar and pushes; it does not
3473 /// sprout a bottom tab bar, and an app that did would look like a port. The phones and the web
3474 /// are the opposite: those are the surfaces whose window size ranges from a phone to a
3475 /// desktop, and a tab bar is what their users expect at the narrow end.
3476 ///
3477 /// So this is a statement about the platform's idiom, not about its widget set:
3478 ///
3479 /// - `Native`/`Emulated`: `NavStyle::Automatic` may resolve to
3480 /// [`props::NavPresentation::Tabs`] on a compact window (ios-uikit, android-material,
3481 /// harmony-arkui, web-dom).
3482 /// - `Unsupported`: it may not; a compact window collapses to
3483 /// [`props::NavPresentation::Stack`] instead, exactly as `NavStyle::Sidebar` has always
3484 /// done (macos-appkit, linux-gtk, linux-qt, windows-winui).
3485 ///
3486 /// [`props::NavPresentation::Rail`] is not gated by this. A narrow sidebar is an ordinary
3487 /// desktop shape (on Windows it is what `NavigationView` does at that width on its own), so
3488 /// the rail rung stays available everywhere `Cap::NavSplit` is.
3489 NavTabsAdaptive,
3490 /// How a navigation host's presentation follows the window (docs/size-classes.md). All three
3491 /// answers mean something different here, and the difference is who decides:
3492 ///
3493 /// - `Native`: **Day tells the toolkit.** The pieces layer resolves the presentation from
3494 /// the [`SizeClass`], re-resolves on every change, and sends
3495 /// [`props::NavPatch::Presentation`]; the toolkit rebuilds its chrome and re-homes the
3496 /// pages it already has. The desktops and web-dom.
3497 /// - `Emulated`: **the toolkit tells Day.** Its own adaptive container owns the decision
3498 /// (`UISplitViewController` collapsing as a Pro Max iPhone rotates, `SlidingPaneLayout`
3499 /// measuring whether both panes fit), so Day must not push a presentation into it: that
3500 /// would be a second decision racing the platform's own animation. The toolkit
3501 /// reports what it did with [`Event::NavPresentationChanged`] and Day reconciles.
3502 /// - `Unsupported`: nobody re-presents. The presentation is resolved once, from
3503 /// [`Cap::NavSplit`] alone, and the window's size never enters into it. A toolkit that
3504 /// cannot change presentation must not have it decided by something that can, or a window
3505 /// launched narrow would be stuck stacked with no way back.
3506 NavRepresent,
3507 /// The toolkit places a navigation host's content-list page ([`props::Pane::List`]) in its
3508 /// own pane between the sidebar and the detail, the Mail shape: mailboxes, message list,
3509 /// message (docs/navigation.md). The three answers differ on what happens when the host
3510 /// leaves the split:
3511 ///
3512 /// - `Native`: the pane exists at every presentation. A narrow window collapses the
3513 /// sidebar but keeps the list beside the detail, exactly as a narrow Mail.app does
3514 /// (macos-appkit: a `contentList` `NSSplitViewItem`).
3515 /// - `Emulated`: the pane exists while split and merges into the navigation stack when
3516 /// the host collapses (ios-uikit: `UISplitViewController` triple-column). The pieces
3517 /// layer then interposes the list between the sidebar root and the detail
3518 /// ([`props::NavPatch::ListInStack`]) and gates the detail push on the app's
3519 /// `detail_visible` binding.
3520 /// - `Unsupported`: the backend never sees [`props::Pane::List`] or
3521 /// [`props::NavProps::list_width`]; the nav piece composes the pane beside (split)
3522 /// or in place of (stacked) the destination content itself.
3523 NavContentList,
3524 /// The toolkit shows the current destination's title in a native header/bar, so a page
3525 /// needn't repeat it in its own content. `Native` on XAML (the `NavigationView` header),
3526 /// UIKit (`UINavigationBar`), Android (`MaterialToolbar`), and ArkUI (`NavDestination`
3527 /// title bars). The desktop custom back-headers (AppKit/Qt/web) show a title only in
3528 /// stack mode, so those backends stay `Unsupported` (docs/navigation.md).
3529 NavHeader,
3530 /// The toolkit applies a runtime appearance override (`set_appearance`): native widgets
3531 /// restyle in place and `dark_mode` answers the override. Probe before showing a theme
3532 /// picker; on `Unsupported` backends the call is ignored.
3533 Appearance,
3534 /// The toolkit renders an application menu bar (docs/menus.md), so `app_menu` is visible to
3535 /// the user, and `register_preferences` gets its automatic Settings… item.
3536 ///
3537 /// The question an app asks before deciding where a command lives. Settings is the usual
3538 /// case: on a platform with a menu bar it belongs in the App menu and putting it in the
3539 /// navigation as well is clutter; on one without, the menu is a no-op and a Settings row is
3540 /// the only way in. Distinct from `Cap::Toolbar`: web-dom draws a window toolbar and has no
3541 /// menu bar at all, so keying off the toolbar strands Settings there.
3542 AppMenu,
3543 /// The toolkit can present native alert/confirm/sheet/prompt modals (docs/dialogs.md).
3544 Dialogs,
3545 /// The toolkit can present native open/save file pickers (docs/files.md).
3546 FileDialogs,
3547 /// The toolkit can present a native folder chooser (`PresentSpec::OpenFolder`,
3548 /// docs/files.md). `Native` on the four desktop toolkits (AppKit, GTK, Qt, WinUI); the
3549 /// phone and web backends answer `Unsupported` and resolve the request as `Dismissed`, so
3550 /// an app hides its "Add Folder…" command where this is not `Native`.
3551 FolderDialog,
3552 /// The toolkit plays `AnimSpec` intents on `update`/`set_frame`/`set_opacity`/
3553 /// `set_transform` on its own animator, keeping the whole contract documented on
3554 /// [`AnimSpec`]: delay, repeat, autoreverse, physical springs, retargeting, and an animated
3555 /// container background (§8.4). `Unsupported` ⇒ animated calls apply instantly (still
3556 /// correct, just not animated).
3557 Animation,
3558 /// The toolkit presents a `kinds::COVER` node as a native fullscreen modal surface
3559 /// (docs/cover.md). `Unsupported` ⇒ the `cover` piece's content never shows.
3560 Cover,
3561 /// The toolkit presents a `.sheet()` cover as a native modal sheet (AppKit's window sheet,
3562 /// UIKit's page sheet) over the page it covers (docs/cover.md "Modal sheet"). `Unsupported`
3563 /// ⇒ the `cover` piece composes the sheet itself: on a window wider than compact, a card
3564 /// centered over the dimmed page; on a compact one, the full window.
3565 CoverSheet,
3566 /// The toolkit can hide the system status bar while a `status_bar_hidden` subtree is
3567 /// mounted (`Toolkit::set_status_bar_hidden`, docs/cover.md). `Native` on the phone and
3568 /// tablet backends; desktop and web have no status bar, so a setting that offers to hide
3569 /// it should be offered only where this is not `Unsupported`.
3570 StatusBarHidden,
3571 /// The toolkit's `text_area` can be made read-only (`TextAreaProps::editable = false`).
3572 TextEditable,
3573 /// The toolkit's `text_area` selectability can be toggled (`TextAreaProps::selectable`).
3574 /// `Unsupported` where selection is always on (GTK); `Emulated` where the backend
3575 /// collapses native selections itself (XAML, ArkUI).
3576 TextSelectable,
3577 /// The toolkit reports a selectable label's selection as it changes
3578 /// ([`Event::TextSelected`], `Label::on_selection`). `Unsupported` where the platform's
3579 /// label has no selection notification: the label is still selectable and the callback
3580 /// never runs.
3581 LabelSelection,
3582 /// The toolkit's `text_area` has built-in spell-check/autocorrect (`TextAreaProps::spellcheck`).
3583 /// `Unsupported` where the toolkit ships none (GTK, Qt, ArkUI).
3584 TextSpellCheck,
3585 /// The toolkit can open additional native OS windows (`Toolkit::open_window`,
3586 /// docs/windows.md). `Native` on the desktop backends and on mobile backends whose
3587 /// platform has a real secondary-window surface (iPad scenes, Android document
3588 /// activities, OHOS multiton abilities). On `Unsupported` backends
3589 /// `day_core::open_window` still works; the content presents as a fullscreen cover in
3590 /// the primary window instead. Probe it to adapt chrome: an `Unsupported` tier has no
3591 /// native title bar or close button, so window content should carry its own close
3592 /// affordance.
3593 MultiWindow,
3594 /// The toolkit can put a count on the app icon (`Toolkit::set_app_badge`, docs/badge.md).
3595 /// `Emulated` where the call is made but the shell may ignore it: desktop Linux, where the
3596 /// Unity launcher protocol is honored by Plasma and Dash-to-Dock but not by stock GNOME.
3597 AppBadgeCount,
3598 /// The toolkit renders `AppBadge::Text` as written. macOS only: `NSDockTile.badgeLabel` is an
3599 /// arbitrary string, while every other platform's badge is a number or nothing.
3600 AppBadgeText,
3601 /// The toolkit can show a valueless indicator (`AppBadge::Dot`).
3602 AppBadgeDot,
3603 /// The toolkit gives a window chrome that persists across pages
3604 /// (`Toolkit::edit_toolbar`, docs/toolbars.md): `Native` on the desktop backends and the
3605 /// phones, `Emulated` on web-dom, `Unsupported` where the only chrome belongs to a page.
3606 ///
3607 /// It no longer decides whether a command can be shown at all: a toolbar item declared on a
3608 /// piece rides that piece's own chrome everywhere. Probe it only for a layout decision that
3609 /// turns on a persistent bar existing.
3610 Toolbar,
3611 /// The window toolbar can hold a search field (docs/search.md): `Native` on the desktop
3612 /// backends, `Emulated` on web-dom. `Unsupported` on the phones, whose bar is a row of actions
3613 /// (an Android app-bar menu, iOS bar buttons, ArkUI title-bar menus): their field goes on the
3614 /// navigation surface instead, so `SearchPlacement::Toolbar` resolves to `Inline` there.
3615 ToolbarSearch,
3616 /// The toolkit realizes `kinds::INSPECTOR` as its own trailing-pane container
3617 /// (docs/inspector.md): an `NSSplitView` inspector pane, a `GtkPaned` with the panel as
3618 /// its end child, a `QDockWidget`, a XAML `SplitView` right pane. `Unsupported` ⇒ the
3619 /// `inspector` piece composes the pane from plain containers instead (same panel, same
3620 /// signal, no native divider), so an unimplemented backend degrades to a drawn pane, not
3621 /// to a hole. Apps normally have no reason to probe this; the piece does.
3622 Inspector,
3623 /// The toolkit realizes `kinds::SPLIT` as its own splitter (docs/split.md): an
3624 /// `NSSplitView`, a `GtkPaned`, a `QSplitter`, each side by side or stacked and with the
3625 /// divider the user drags. `Unsupported` ⇒ the `split` piece composes the two panes and
3626 /// draws and drags the divider itself (the web, the mobile toolkits, XAML), so the piece
3627 /// behaves the same everywhere and only the divider's look is the toolkit's. Apps have no
3628 /// reason to probe this; the piece does.
3629 Split,
3630 /// The toolkit shapes the pointer over a node from the `.cursor()` decorator
3631 /// ([`Toolkit::set_cursor`], docs/cursor.md). `Native` where the platform draws the requested
3632 /// shape from its own set (AppKit, GTK, the DOM, Android's `PointerIcon`), `Emulated` where
3633 /// some shapes map to a nearest neighbor (Qt, XAML) or the platform draws pointer effects
3634 /// rather than shapes (iPadOS), `Unsupported` where nothing changes: a touch-only toolkit,
3635 /// or one whose pointer API Day does not reach yet. Apps ask before offering an affordance
3636 /// that only a cursor reveals, such as a resize handle with no other visual.
3637 Cursor,
3638 /// The toolkit can enumerate the platform's font families with the faces each ships
3639 /// ([`Toolkit::font_families`], docs/fonts.md). `Native` where an OS font database answers
3640 /// (`NSFontManager`, `UIFont`, Pango, `QFontDatabase`, Android's `fonts.xml`,
3641 /// `OH_Drawing_FontMgr`, DirectWrite); `Emulated` where the list is composed rather than
3642 /// read: web-dom answers the CSS generic families plus the bundled `document.fonts`, since
3643 /// a browser exposes no local font list without a permission prompt; `Unsupported` means
3644 /// the list is empty and an app should offer only the default face. Measurement
3645 /// ([`Toolkit::measure_text`]) has no probe: a `None` answer degrades to
3646 /// [`TextMetrics::approximate`]. Probe this before offering a font menu, not before
3647 /// drawing; a [`CanvasFont`] draws everywhere.
3648 FontList,
3649 /// The toolkit reads the user's reduce-motion setting ([`Toolkit::reduce_motion`],
3650 /// docs/accessibility.md) and reports when it changes. `Native` where the platform has the
3651 /// switch and Day reaches it; `Unsupported` where Day reaches none (the app then animates as
3652 /// it would with the setting off, and `DAY_REDUCE_MOTION=1` still forces it on).
3653 ReduceMotion,
3654 /// The toolkit can speak a sentence through the screen reader without moving its focus
3655 /// ([`Toolkit::announce`], docs/accessibility.md): "Saved", "3 results", "Upload failed".
3656 /// `Native` where the platform has an announcement request (`NSAccessibility`'s
3657 /// announcement notification, `UIAccessibility`'s, Android's accessibility event, GTK
3658 /// 4.14's `gtk_accessible_announce`, a WinUI notification event); `Emulated` on the web,
3659 /// where an ARIA live region carries it; `Unsupported` where Day reaches no announcement
3660 /// API yet. An app with a visible status label needs no announcement: screen readers read
3661 /// what changes on screen only when told to, so this is for the change the user cannot
3662 /// otherwise learn about.
3663 Announce,
3664 /// The toolkit can turn encoded image bytes into a native image
3665 /// ([`Toolkit::decode_image`], docs/images.md): what `image(bytes)`, a pasted screenshot and
3666 /// a canvas image all rest on. `Native` wherever the platform decoder takes a buffer;
3667 /// `Unsupported` means only staged asset names draw, so an app should not offer "open an
3668 /// image" at all. Every backend that decodes also answers [`Toolkit::image_info`], so pixel
3669 /// size needs no probe of its own.
3670 ImageDecode,
3671 /// The toolkit can encode a decoded image back to bytes ([`Toolkit::encode_image`]).
3672 /// Which formats it encodes is [`Toolkit::encode_formats`], the same shape as
3673 /// [`Cap::FontList`]/[`Toolkit::font_families`], because "can encode" and "can encode WebP"
3674 /// are different questions and only the second one needs a list.
3675 ImageEncode,
3676 /// The toolkit can read an image's metadata beyond its pixels: EXIF orientation, DPI,
3677 /// capture time ([`Toolkit::image_properties`]). `Native` where a platform metadata reader
3678 /// is already linked (WinRT's `BitmapPropertiesView`, Android's `ExifInterface`);
3679 /// `Unsupported` where reading it would mean shipping a parser or a new framework, which is
3680 /// most places. An app that wants orientation must handle `None`.
3681 ImageProperties,
3682 /// The toolkit can replay a canvas drawing into an offscreen bitmap
3683 /// ([`Toolkit::render_bitmap`], docs/canvas.md "Exporting"): what `Drawing::to_bitmap` and
3684 /// `Drawing::to_png` rest on. `Native` where the toolkit's own canvas painter can target an
3685 /// image surface (a `CGBitmapContext`, a cairo image surface, a `QImage`, an android
3686 /// `Bitmap`, an `OH_Drawing_Bitmap`, a detached `<canvas>`); `Unsupported` where the
3687 /// on-screen canvas has no painter to retarget (WinUI builds XAML shapes instead).
3688 CanvasBitmap,
3689 /// The toolkit can replay canvas drawings into a PDF document ([`Toolkit::render_pdf`],
3690 /// docs/canvas.md "Exporting"), with vector shapes and the platform's own font embedding.
3691 /// `Native` only where the platform ships a PDF writer the canvas painter can draw into
3692 /// (Core Graphics on AppKit and UIKit, cairo on GTK, `QPdfWriter` on Qt, `PdfDocument` on
3693 /// Android); `Unsupported` on ArkUI, the web and WinUI, which have none.
3694 CanvasPdf,
3695 /// The toolkit minimizes, zooms, hides and restores a window on request
3696 /// ([`WindowChange::State`], [`WindowChange::Visible`], docs/windows.md) and reports what the
3697 /// user does through [`Event::WindowStateChanged`]. `Native` on the desktop backends;
3698 /// `Unsupported` on the phones and the web, whose windows the OS sizes.
3699 WindowStates,
3700 /// The toolkit takes a window fullscreen on request and reports when it enters and leaves
3701 /// ([`WindowState::Fullscreen`]). `Native` on the desktops, on Android (system bars hidden
3702 /// through `WindowInsetsController`), on HarmonyOS and on the web (the Fullscreen API, which
3703 /// browsers allow only during a user gesture); `Emulated` on iOS, which hides the status bar
3704 /// and lets the home indicator fade but always keeps the app full-screen anyway.
3705 WindowFullscreen,
3706 /// The toolkit keeps a window out of screenshots, recordings and screen sharing
3707 /// ([`WindowChange::ContentProtected`]). `Native` on macOS (`NSWindowSharingNone`), Windows
3708 /// (`WDA_EXCLUDEFROMCAPTURE`), Android (`FLAG_SECURE`) and HarmonyOS (privacy mode);
3709 /// `Emulated` on iOS, which has no switch for it: Day covers the content while the screen is
3710 /// being recorded or mirrored, but a screenshot still captures it. `Unsupported` on Linux
3711 /// and the web.
3712 ContentProtection,
3713 /// The toolkit honors [`WindowOptions::tabbing`]: macOS window tabs. `Unsupported` everywhere
3714 /// else, where no system window tabs exist.
3715 WindowTabbing,
3716 /// The toolkit shows a Dock menu ([`Toolkit::set_dock_menu`], docs/menus.md): the app's
3717 /// shortcuts and `dock_menu(..)` entries above the system's own items. macOS only.
3718 DockMenu,
3719 /// The toolkit resizes a window and bounds its size on request ([`WindowChange::Frame`]'s
3720 /// size, [`WindowChange::Limits`], [`WindowChange::Resizable`]).
3721 WindowGeometry,
3722 /// The toolkit moves a window to a requested position ([`WindowChange::Frame`]'s origin).
3723 /// `Unsupported` on GTK 4, which removed window positioning, and wherever the compositor owns
3724 /// placement (Wayland).
3725 WindowPosition,
3726 /// The toolkit changes how a window stacks ([`WindowChange::Level`],
3727 /// [`WindowChange::OnAllWorkspaces`], [`WindowChange::SkipTaskbar`]).
3728 WindowLevel,
3729 /// The toolkit gives one window its own light/dark appearance ([`WindowChange::Appearance`]).
3730 /// Where it cannot, the app-wide [`Toolkit::set_appearance`] still applies to every window.
3731 WindowAppearance,
3732 /// The toolkit asks for the user's attention on request ([`WindowChange::RequestAttention`]):
3733 /// a Dock bounce, a flashing taskbar button.
3734 RequestAttention,
3735 /// The toolkit opens a window with no title bar or frame ([`WindowChrome::Frameless`],
3736 /// docs/window-chrome.md). Desktop backends only.
3737 FramelessWindow,
3738 /// The toolkit runs a window's content under its title bar with the window controls kept
3739 /// ([`WindowChrome::Overlay`]) and reports the bar's height as the safe-area top inset.
3740 OverlayTitleBar,
3741 /// The toolkit opens a window whose unpainted pixels show the desktop
3742 /// ([`WindowBackground::Transparent`]).
3743 TransparentWindow,
3744 /// The toolkit puts a translucent system material behind a window
3745 /// ([`WindowBackground::Material`]): macOS's visual-effect materials, Windows 11's Mica and
3746 /// Acrylic. `Emulated` where an approximation stands in.
3747 WindowMaterial,
3748 /// The toolkit lets a piece move its window like a title bar does
3749 /// ([`Toolkit::set_drag_region`], `.window_drag_region()`). `Emulated` on the web, where
3750 /// only an installed app with a window-controls overlay honors it.
3751 DragRegion,
3752 /// The toolkit shows status items ([`Toolkit::set_status_items`], docs/status-item.md): the
3753 /// macOS menu bar, the Windows notification area, a Linux tray. On Linux the answer depends
3754 /// on the desktop: `Native` while a `StatusNotifierItem` host is running (KDE Plasma, most
3755 /// panels, GNOME with the AppIndicator extension), `Unsupported` without one (stock GNOME),
3756 /// so an app can keep a window instead of vanishing into a tray nobody shows.
3757 StatusItem,
3758 /// The toolkit shows progress on the app's Dock or taskbar icon
3759 /// ([`Toolkit::set_app_progress`]). `Emulated` on Linux, where the Unity launcher protocol is
3760 /// honored by KDE Plasma and Dash to Dock but not by every dock.
3761 AppProgress,
3762 /// The toolkit can hide the app's Dock icon while it runs ([`Toolkit::set_dock_visible`]).
3763 /// macOS only.
3764 DockVisibility,
3765 /// The toolkit lists the displays and their work areas ([`Toolkit::monitors`]). `Emulated`
3766 /// where the one screen the app runs on is reported (a phone, the web).
3767 Monitors,
3768 /// The toolkit shows launcher shortcuts the app sets while it runs
3769 /// ([`Toolkit::set_launcher_shortcuts`]).
3770 DynamicShortcuts,
3771 /// How the toolkit draws a sectioned list's headers (`ListProps::sections`, docs/list.md
3772 /// "Sections"). `Native` where the platform's list has group headers that pin to the top
3773 /// while their section scrolls under them: macos-appkit (`NSTableView` group rows with
3774 /// `floatsGroupRows`) and ios-uikit (plain-style `UITableView` section headers).
3775 /// `Emulated` where the host pins a copy of the current header over the top of the list
3776 /// itself. Headers are unselectable rows on every toolkit, so an app needs this only to
3777 /// describe the difference, never to decide whether to call `.sections`.
3778 ListSections,
3779 /// The toolkit's share chooser carries the app's own actions ([`share::ShareSpec::actions`],
3780 /// docs/sharing.md): Add Bookmark or Find on Page beside the system's targets, each with
3781 /// its title and glyph. `Native` on ios-uikit (a `UIActivity` per action), macos-appkit (an
3782 /// `NSSharingService` per action, offered by the picker's delegate) and android-material
3783 /// on Android 14 and later (`ChooserAction`). `Unsupported` everywhere else: the chooser
3784 /// shows the system's targets only, and the app offers its actions in its own menu.
3785 ShareActions,
3786 /// A `scroll` reports its content offset as it moves (`ScrollProps::track_offset`,
3787 /// [`Event::ScrollChanged`], docs/scroll.md "Offset and phase"). `Unsupported`: the bound
3788 /// offset never changes, so a collapsing header stays expanded.
3789 ScrollOffset,
3790 /// A `scroll` reports the phases of user-driven scrolling (`ScrollProps::track_phase`,
3791 /// [`Event::ScrollPhase`]). `Native` where the platform says when a drag begins, when the
3792 /// finger lifts and when momentum ends; anything else and day-core derives `Dragging` and
3793 /// `Idle` from the offset reports (never `Coasting`), which needs [`Cap::ScrollOffset`].
3794 ScrollPhases,
3795 /// A `scroll` comes to rest on page or interval boundaries (`ScrollProps::snap`).
3796 /// `Unsupported`: the view scrolls freely.
3797 ScrollSnap,
3798 /// A `scroll` zooms its content by pinch and by [`props::ScrollPatch::Zoom`]
3799 /// (`ScrollProps::zoom`, docs/scroll.md "Zoom"). `Unsupported`: the content stays at its
3800 /// natural size and the bound scale stays `1.0`.
3801 ScrollZoom,
3802 /// A `scroll` dismisses the software keyboard as its props ask
3803 /// (`ScrollProps::keyboard_dismiss`, `ScrollProps::keyboard_taps`). `Native` where the
3804 /// platform's scroll view does it; `Emulated` where day-core resigns focus when a drag
3805 /// begins (no interactive tracking, and taps are always delivered); `Unsupported` where
3806 /// there is no software keyboard to dismiss.
3807 ScrollKeyboardDismiss,
3808 /// A native `pager` reports a continuous position while a page is dragged (docs/pager.md
3809 /// "Progress"). Anything else and the bound progress steps from page to page.
3810 PagerProgress,
3811 /// The list host reports its viewport through [`ListSource::viewport`] (docs/list.md
3812 /// "Visible rows"): what `visible_rows`, `follow_end` and `on_end_reached` are derived
3813 /// from. `Unsupported`: `visible_rows` follows only `first_visible` reports, `follow_end`
3814 /// follows every change, and `on_end_reached` never fires.
3815 ListViewport,
3816 /// The list host tells a scroll the reader started from one the app asked for, through
3817 /// [`ListSource::reader_scroll`] (docs/list.md "Following the end"). `Unsupported`:
3818 /// `follow_end` learns that the reader left only from the viewport reports, so a reader who
3819 /// interrupts a followed scroll before it reaches the end can be taken back to the end by
3820 /// the next row.
3821 ListReaderScroll,
3822 /// The list host honors [`ListScroll::align`] and [`ListScroll::animated`]
3823 /// ([`Toolkit::list_scroll`]). `Unsupported`: a row scroll reveals the row where the
3824 /// platform's own "scroll to row" puts it.
3825 ListScrollAlign,
3826 /// `Decorate::focusable` is honored ([`Toolkit::set_focusable`], docs/focus.md): a
3827 /// composed piece joins the focus order, takes focus on a press, reports
3828 /// `Event::FocusChanged` and hears `Event::Key` while focused. `Unsupported` ⇒ the piece
3829 /// renders and never takes the keyboard; offer the same commands through buttons or a
3830 /// menu there.
3831 Focusable,
3832 /// Key events carry every phase (docs/menus.md "Keys"): `Native` when the backend reports
3833 /// the release (`KeyPhase::Up`) and marks auto-repeat (`KeyPhase::Repeat`). `Unsupported`
3834 /// ⇒ only presses arrive, each as `KeyPhase::Down`, so held-key movement has no end to
3835 /// wait for and should step per press instead.
3836 KeyPhases,
3837 /// `Decorate::hit_slop` grows the piece's input area ([`Toolkit::set_hit_slop`],
3838 /// docs/gestures.md "Hit slop"). `Unsupported` ⇒ the piece is hit inside its own bounds.
3839 HitSlop,
3840}
3841
3842impl Cap {
3843 /// Every capability, in declaration order: what a conformance run asks the toolkit about,
3844 /// so the evidence can be held against the declared coverage matrix (docs/testing.md).
3845 pub const ALL: [Cap; 104] = [
3846 Cap::DragDrop,
3847 Cap::DragExternalImport,
3848 Cap::DragExternalExport,
3849 Cap::DragMultipleItems,
3850 Cap::DragFileReferences,
3851 Cap::DragDeferredReceipt,
3852 Cap::DragFilePromises,
3853 Cap::DragExternalMove,
3854 Cap::ListRecycling,
3855 Cap::UndoBridge,
3856 Cap::EditBridge,
3857 Cap::ListReorder,
3858 Cap::NavReorder,
3859 Cap::ListDelete,
3860 Cap::ListSwipeActions,
3861 Cap::Tree,
3862 Cap::TreeMove,
3863 Cap::BaselineAlignment,
3864 Cap::TextRuns,
3865 Cap::TextLinks,
3866 Cap::Lottie,
3867 Cap::NativeSymbols,
3868 Cap::Snapshot,
3869 Cap::NavSplit,
3870 Cap::NavTabs,
3871 Cap::NavTabsAdaptive,
3872 Cap::NavRepresent,
3873 Cap::NavContentList,
3874 Cap::NavHeader,
3875 Cap::Appearance,
3876 Cap::AppMenu,
3877 Cap::Dialogs,
3878 Cap::FileDialogs,
3879 Cap::Animation,
3880 Cap::Cover,
3881 Cap::StatusBarHidden,
3882 Cap::TextEditable,
3883 Cap::TextSelectable,
3884 Cap::TextSpellCheck,
3885 Cap::MultiWindow,
3886 Cap::AppBadgeCount,
3887 Cap::AppBadgeText,
3888 Cap::AppBadgeDot,
3889 Cap::Toolbar,
3890 Cap::ToolbarSearch,
3891 Cap::Inspector,
3892 Cap::Cursor,
3893 Cap::FontList,
3894 Cap::ReduceMotion,
3895 Cap::Announce,
3896 Cap::ImageDecode,
3897 Cap::ImageEncode,
3898 Cap::ImageProperties,
3899 Cap::WindowStates,
3900 Cap::WindowFullscreen,
3901 Cap::ContentProtection,
3902 Cap::WindowTabbing,
3903 Cap::DockMenu,
3904 Cap::WindowGeometry,
3905 Cap::WindowPosition,
3906 Cap::WindowLevel,
3907 Cap::WindowAppearance,
3908 Cap::RequestAttention,
3909 Cap::FramelessWindow,
3910 Cap::OverlayTitleBar,
3911 Cap::TransparentWindow,
3912 Cap::WindowMaterial,
3913 Cap::DragRegion,
3914 Cap::StatusItem,
3915 Cap::AppProgress,
3916 Cap::DockVisibility,
3917 Cap::Monitors,
3918 Cap::DynamicShortcuts,
3919 Cap::Split,
3920 Cap::TreeSections,
3921 Cap::CoverSheet,
3922 Cap::ListEditing,
3923 Cap::ListItem,
3924 Cap::CanvasBitmap,
3925 Cap::CanvasPdf,
3926 Cap::SearchField,
3927 Cap::ComboBox,
3928 Cap::Stepper,
3929 Cap::DateTimePicker,
3930 Cap::ColorPicker,
3931 Cap::PullRefresh,
3932 Cap::Pager,
3933 Cap::PullRefreshGesture,
3934 Cap::FolderDialog,
3935 Cap::ListSections,
3936 Cap::ShareActions,
3937 Cap::ScrollOffset,
3938 Cap::ScrollPhases,
3939 Cap::ScrollSnap,
3940 Cap::ScrollZoom,
3941 Cap::ScrollKeyboardDismiss,
3942 Cap::PagerProgress,
3943 Cap::ListViewport,
3944 Cap::ListScrollAlign,
3945 Cap::Focusable,
3946 Cap::KeyPhases,
3947 Cap::HitSlop,
3948 Cap::LabelSelection,
3949 Cap::ListReaderScroll,
3950 ];
3951
3952 /// The capability's place in [`Cap::ALL`]. Exhaustive, so a new variant fails to compile
3953 /// here until it is given one, and the unit test below then holds `ALL` to it.
3954 #[must_use]
3955 pub const fn ordinal(self) -> usize {
3956 match self {
3957 Cap::DragDrop => 0,
3958 Cap::DragExternalImport => 1,
3959 Cap::DragExternalExport => 2,
3960 Cap::DragMultipleItems => 3,
3961 Cap::DragFileReferences => 4,
3962 Cap::DragDeferredReceipt => 5,
3963 Cap::DragFilePromises => 6,
3964 Cap::DragExternalMove => 7,
3965 Cap::ListRecycling => 8,
3966 Cap::UndoBridge => 9,
3967 Cap::EditBridge => 10,
3968 Cap::ListReorder => 11,
3969 Cap::NavReorder => 12,
3970 Cap::ListDelete => 13,
3971 Cap::ListSwipeActions => 14,
3972 Cap::Tree => 15,
3973 Cap::TreeMove => 16,
3974 Cap::BaselineAlignment => 17,
3975 Cap::TextRuns => 18,
3976 Cap::TextLinks => 19,
3977 Cap::Lottie => 20,
3978 Cap::NativeSymbols => 21,
3979 Cap::Snapshot => 22,
3980 Cap::NavSplit => 23,
3981 Cap::NavTabs => 24,
3982 Cap::NavTabsAdaptive => 25,
3983 Cap::NavRepresent => 26,
3984 Cap::NavContentList => 27,
3985 Cap::NavHeader => 28,
3986 Cap::Appearance => 29,
3987 Cap::AppMenu => 30,
3988 Cap::Dialogs => 31,
3989 Cap::FileDialogs => 32,
3990 Cap::Animation => 33,
3991 Cap::Cover => 34,
3992 Cap::StatusBarHidden => 35,
3993 Cap::TextEditable => 36,
3994 Cap::TextSelectable => 37,
3995 Cap::TextSpellCheck => 38,
3996 Cap::MultiWindow => 39,
3997 Cap::AppBadgeCount => 40,
3998 Cap::AppBadgeText => 41,
3999 Cap::AppBadgeDot => 42,
4000 Cap::Toolbar => 43,
4001 Cap::ToolbarSearch => 44,
4002 Cap::Inspector => 45,
4003 Cap::Cursor => 46,
4004 Cap::FontList => 47,
4005 Cap::ReduceMotion => 48,
4006 Cap::Announce => 49,
4007 Cap::ImageDecode => 50,
4008 Cap::ImageEncode => 51,
4009 Cap::ImageProperties => 52,
4010 Cap::WindowStates => 53,
4011 Cap::WindowFullscreen => 54,
4012 Cap::ContentProtection => 55,
4013 Cap::WindowTabbing => 56,
4014 Cap::DockMenu => 57,
4015 Cap::WindowGeometry => 58,
4016 Cap::WindowPosition => 59,
4017 Cap::WindowLevel => 60,
4018 Cap::WindowAppearance => 61,
4019 Cap::RequestAttention => 62,
4020 Cap::FramelessWindow => 63,
4021 Cap::OverlayTitleBar => 64,
4022 Cap::TransparentWindow => 65,
4023 Cap::WindowMaterial => 66,
4024 Cap::DragRegion => 67,
4025 Cap::StatusItem => 68,
4026 Cap::AppProgress => 69,
4027 Cap::DockVisibility => 70,
4028 Cap::Monitors => 71,
4029 Cap::DynamicShortcuts => 72,
4030 Cap::Split => 73,
4031 Cap::TreeSections => 74,
4032 Cap::CoverSheet => 75,
4033 Cap::ListEditing => 76,
4034 Cap::ListItem => 77,
4035 Cap::CanvasBitmap => 78,
4036 Cap::CanvasPdf => 79,
4037 Cap::SearchField => 80,
4038 Cap::ComboBox => 81,
4039 Cap::Stepper => 82,
4040 Cap::DateTimePicker => 83,
4041 Cap::ColorPicker => 84,
4042 Cap::PullRefresh => 85,
4043 Cap::Pager => 86,
4044 Cap::PullRefreshGesture => 87,
4045 Cap::FolderDialog => 88,
4046 Cap::ListSections => 89,
4047 Cap::ShareActions => 90,
4048 Cap::ScrollOffset => 91,
4049 Cap::ScrollPhases => 92,
4050 Cap::ScrollSnap => 93,
4051 Cap::ScrollZoom => 94,
4052 Cap::ScrollKeyboardDismiss => 95,
4053 Cap::PagerProgress => 96,
4054 Cap::ListViewport => 97,
4055 Cap::ListScrollAlign => 98,
4056 Cap::Focusable => 99,
4057 Cap::KeyPhases => 100,
4058 Cap::HitSlop => 101,
4059 Cap::LabelSelection => 102,
4060 Cap::ListReaderScroll => 103,
4061 }
4062 }
4063}
4064
4065// ---------------------------------------------------------------------------
4066// Raster images (docs/images.md): the currency shared by the `image` piece, the canvas, and
4067// the decode/metadata/encode duties below.
4068// ---------------------------------------------------------------------------
4069
4070/// A decoded image the toolkit holds, addressed by an id day-core mints.
4071///
4072/// Opaque, because what sits behind it is an `NSImage`, a `UIImage`, a `GdkTexture`, a
4073/// `QPixmap`, a `BitmapImage`, an android `Bitmap` or an `ImageBitmap`, and none of those cross
4074/// the boundary. The id is released through [`Toolkit::release_image`] when the app's handle
4075/// drops, so a backend's side table never outlives the app's interest in it.
4076#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
4077pub struct BitmapId(pub u64);
4078
4079/// An encoded image format: what [`BitmapInfo::format`] reports and [`EncodeSpec::format`] asks
4080/// for. Not every backend encodes every one: ask [`Toolkit::encode_formats`] (the
4081/// [`Cap::ImageEncode`] pair of [`Toolkit::font_families`]/[`Cap::FontList`]) rather than
4082/// assuming.
4083#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default)]
4084pub enum ImageFormat {
4085 #[default]
4086 Png,
4087 Jpeg,
4088 Webp,
4089 Gif,
4090 Bmp,
4091 Tiff,
4092 /// HEIF/HEIC, Apple's camera format; decodable on the Apple backends and Android, and
4093 /// encodable almost nowhere.
4094 Heif,
4095 /// Decoded from bytes whose magic numbers [`ImageFormat::sniff`] does not know. A backend may
4096 /// still decode it: the platform decoders read more formats than Day names.
4097 Unknown,
4098}
4099
4100impl ImageFormat {
4101 /// The IANA media type, which is also the string the ArkUI packer, GDI+ and the browser's
4102 /// `toBlob` take. `Unknown` answers `application/octet-stream`.
4103 #[must_use]
4104 pub fn mime(self) -> &'static str {
4105 match self {
4106 ImageFormat::Png => "image/png",
4107 ImageFormat::Jpeg => "image/jpeg",
4108 ImageFormat::Webp => "image/webp",
4109 ImageFormat::Gif => "image/gif",
4110 ImageFormat::Bmp => "image/bmp",
4111 ImageFormat::Tiff => "image/tiff",
4112 ImageFormat::Heif => "image/heif",
4113 ImageFormat::Unknown => "application/octet-stream",
4114 }
4115 }
4116
4117 /// The pixel size the encoded bytes declare, read from the container's own header
4118 /// (docs/images.md).
4119 ///
4120 /// Every backend that decodes natively reports its own dimensions; this exists for the one
4121 /// that cannot. The XAML backend's (`windows-winui`) `BitmapImage` learns its size
4122 /// asynchronously, only once the element has been shown, so a synchronous `image_info` there
4123 /// would have nothing to say.
4124 /// Reading the header instead gives the same answer the decoder would, before any decoding.
4125 ///
4126 /// `None` when the header is absent, truncated, or a container this does not parse.
4127 #[must_use]
4128 pub fn dimensions(bytes: &[u8]) -> Option<(u32, u32)> {
4129 let be16 = |i: usize| -> Option<u32> {
4130 Some(u32::from(u16::from_be_bytes([
4131 *bytes.get(i)?,
4132 *bytes.get(i + 1)?,
4133 ])))
4134 };
4135 let le16 = |i: usize| -> Option<u32> {
4136 Some(u32::from(u16::from_le_bytes([
4137 *bytes.get(i)?,
4138 *bytes.get(i + 1)?,
4139 ])))
4140 };
4141 let be32 = |i: usize| -> Option<u32> {
4142 Some(u32::from_be_bytes([
4143 *bytes.get(i)?,
4144 *bytes.get(i + 1)?,
4145 *bytes.get(i + 2)?,
4146 *bytes.get(i + 3)?,
4147 ]))
4148 };
4149 let le32 = |i: usize| -> Option<u32> {
4150 Some(u32::from_le_bytes([
4151 *bytes.get(i)?,
4152 *bytes.get(i + 1)?,
4153 *bytes.get(i + 2)?,
4154 *bytes.get(i + 3)?,
4155 ]))
4156 };
4157 match Self::sniff(bytes)? {
4158 // IHDR is always the first chunk: 8-byte signature, 4-byte length, 4-byte type.
4159 ImageFormat::Png => Some((be32(16)?, be32(20)?)),
4160 // The logical screen descriptor follows the 6-byte version stamp, little-endian.
4161 ImageFormat::Gif => Some((le16(6)?, le16(8)?)),
4162 // The DIB header's width/height are signed; a negative height is a top-down bitmap.
4163 ImageFormat::Bmp => Some((
4164 le32(18)?.cast_signed().unsigned_abs(),
4165 le32(22)?.cast_signed().unsigned_abs(),
4166 )),
4167 // Walk the segment chain to the frame header. Every SOF marker carries the size at
4168 // the same offsets; the arithmetic-coded and progressive ones are SOFs too, which is
4169 // why this matches the whole range rather than SOF0 alone. DNL/DHP (0xC4, 0xC8,
4170 // 0xCC) are not frame headers and are skipped like any other segment.
4171 ImageFormat::Jpeg => {
4172 let mut i = 2usize;
4173 // `<=`, not `<`: a frame header that ends the buffer is still a frame header, and
4174 // the size sits in its last four bytes.
4175 while i + 9 <= bytes.len() {
4176 if bytes[i] != 0xFF {
4177 i += 1;
4178 continue;
4179 }
4180 let marker = bytes[i + 1];
4181 // Padding fill bytes and the standalone markers carry no length.
4182 if marker == 0xFF || (0xD0..=0xD9).contains(&marker) || marker == 0x01 {
4183 i += 1;
4184 continue;
4185 }
4186 let is_sof = (0xC0..=0xCF).contains(&marker)
4187 && marker != 0xC4
4188 && marker != 0xC8
4189 && marker != 0xCC;
4190 if is_sof {
4191 // [marker][len:2][precision:1][height:2][width:2]
4192 return Some((be16(i + 7)?, be16(i + 5)?));
4193 }
4194 i += 2 + be16(i + 2)? as usize;
4195 }
4196 None
4197 }
4198 // RIFF: a 12-byte header, then a chunk id. VP8X states the size minus one in 24-bit
4199 // little-endian; lossy VP8 hides it in the 14 low bits after the start code; lossless
4200 // VP8L packs width-1 and height-1 into 14 bits each across four bytes.
4201 ImageFormat::Webp => match bytes.get(12..16)? {
4202 b"VP8X" => {
4203 let w = u32::from(*bytes.get(24)?)
4204 | u32::from(*bytes.get(25)?) << 8
4205 | u32::from(*bytes.get(26)?) << 16;
4206 let h = u32::from(*bytes.get(27)?)
4207 | u32::from(*bytes.get(28)?) << 8
4208 | u32::from(*bytes.get(29)?) << 16;
4209 Some((w + 1, h + 1))
4210 }
4211 b"VP8 " => Some((le16(26)? & 0x3FFF, le16(28)? & 0x3FFF)),
4212 b"VP8L" => {
4213 let bits = le32(21)?;
4214 Some(((bits & 0x3FFF) + 1, ((bits >> 14) & 0x3FFF) + 1))
4215 }
4216 _ => None,
4217 },
4218 // TIFF's IFD is a pointer chase and HEIF's is a box tree; neither is worth parsing
4219 // here, because every backend that reads them decodes natively and answers for itself.
4220 ImageFormat::Tiff | ImageFormat::Heif | ImageFormat::Unknown => None,
4221 }
4222 }
4223
4224 /// The format `bytes` begins with, by magic number: enough to fill [`BitmapInfo::format`]
4225 /// on every backend, including the ones whose decoder never says what it decoded.
4226 ///
4227 /// Hand-rolled rather than a crate: it is a dozen byte comparisons against fixed prefixes,
4228 /// and the alternative is an image-decoding dependency in the one crate that must stay
4229 /// dependency-free.
4230 #[must_use]
4231 pub fn sniff(bytes: &[u8]) -> Option<ImageFormat> {
4232 let starts = |sig: &[u8]| bytes.len() >= sig.len() && &bytes[..sig.len()] == sig;
4233 if starts(&[0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a]) {
4234 return Some(ImageFormat::Png);
4235 }
4236 if starts(&[0xff, 0xd8, 0xff]) {
4237 return Some(ImageFormat::Jpeg);
4238 }
4239 if starts(b"GIF87a") || starts(b"GIF89a") {
4240 return Some(ImageFormat::Gif);
4241 }
4242 if starts(b"BM") {
4243 return Some(ImageFormat::Bmp);
4244 }
4245 if starts(&[0x49, 0x49, 0x2a, 0x00]) || starts(&[0x4d, 0x4d, 0x00, 0x2a]) {
4246 return Some(ImageFormat::Tiff);
4247 }
4248 // RIFF....WEBP and ....ftypheic/heix/mif1 both carry their tag past a 4-byte prefix.
4249 if starts(b"RIFF") && bytes.len() >= 12 && &bytes[8..12] == b"WEBP" {
4250 return Some(ImageFormat::Webp);
4251 }
4252 if bytes.len() >= 12 && &bytes[4..8] == b"ftyp" {
4253 let brand = &bytes[8..12];
4254 if brand == b"heic" || brand == b"heix" || brand == b"mif1" || brand == b"msf1" {
4255 return Some(ImageFormat::Heif);
4256 }
4257 }
4258 None
4259 }
4260}
4261
4262/// What a decoded image is, in the terms every backend can answer
4263/// ([`Toolkit::image_info`], docs/images.md).
4264///
4265/// `pixels` is the image's own pixel size, not the points it draws at: an asset that stages at
4266/// 2× reports twice its point size and a `scale` of 2, so an app sizing a frame divides. Bytes
4267/// carry no density, so a decoded buffer always answers `scale: 1.0`.
4268#[derive(Clone, Copy, Debug, Default, PartialEq)]
4269pub struct BitmapInfo {
4270 pub pixels: Size,
4271 /// Pixels per point (1.0 for decoded bytes; 2 or 3 for a catalog/drawable asset that staged
4272 /// a density variant).
4273 pub scale: f64,
4274 /// The encoded format it came from, where the backend knows or [`ImageFormat::sniff`] said.
4275 pub format: Option<ImageFormat>,
4276 pub has_alpha: bool,
4277}
4278
4279/// What [`Toolkit::encode_image`] should produce (docs/images.md).
4280///
4281/// A struct rather than three positional arguments, per docs/api-style.md: the call site reads
4282/// `EncodeSpec { format: ImageFormat::Jpeg, quality: Some(0.8), ..Default::default() }`.
4283#[derive(Clone, Copy, Debug, PartialEq)]
4284pub struct EncodeSpec {
4285 pub format: ImageFormat,
4286 /// Lossy quality in `0.0..=1.0`. `None` takes the platform's default; a lossless format
4287 /// ignores it.
4288 pub quality: Option<f64>,
4289 /// Scale the longest side down to fit this box first (aspect preserved). `None` encodes at
4290 /// the image's own size.
4291 pub fit: Option<Size>,
4292}
4293
4294impl Default for EncodeSpec {
4295 fn default() -> Self {
4296 EncodeSpec {
4297 format: ImageFormat::Png,
4298 quality: None,
4299 fit: None,
4300 }
4301 }
4302}
4303
4304/// The metadata an image file carries beyond its pixels ([`Toolkit::image_properties`]).
4305///
4306/// Sparse by construction: every field is what the platform's own reader answered, and a
4307/// backend with no metadata reader at all answers `None` to the whole call rather than an empty
4308/// struct. Probe [`Cap::ImageProperties`] before offering an affordance that depends on it.
4309#[derive(Clone, Debug, Default, PartialEq)]
4310pub struct ImageProperties {
4311 /// The EXIF orientation tag (1–8), where one was recorded.
4312 pub orientation: Option<u16>,
4313 /// Pixels per inch, where the file records a resolution.
4314 pub dpi: Option<f64>,
4315 /// The capture timestamp as the file spells it (no parsing: the formats disagree).
4316 pub created: Option<String>,
4317 /// Everything else the platform reader named, in its own vocabulary. Keys are the
4318 /// platform's, so read them defensively.
4319 pub extra: Vec<(String, String)>,
4320}
4321
4322/// Why an image operation could not answer.
4323#[derive(Clone, Copy, Debug, PartialEq, Eq)]
4324pub enum ImageError {
4325 /// The bytes are not an image this platform decodes.
4326 Decode,
4327 /// The image decoded, but this backend cannot encode the format asked for. `encode_formats`
4328 /// says which it can.
4329 Encode,
4330 /// The backend has no path for this at all (probe [`Cap::ImageDecode`] /
4331 /// [`Cap::ImageEncode`]).
4332 Unsupported,
4333 /// The id named no live image: released already, or never decoded.
4334 Gone,
4335}
4336
4337impl std::fmt::Display for ImageError {
4338 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
4339 match self {
4340 ImageError::Decode => write!(f, "the bytes are not a decodable image"),
4341 ImageError::Encode => write!(f, "this backend cannot encode that format"),
4342 ImageError::Unsupported => write!(f, "image support is unavailable on this backend"),
4343 ImageError::Gone => write!(f, "the image was released"),
4344 }
4345 }
4346}
4347
4348impl std::error::Error for ImageError {}
4349
4350// ---------------------------------------------------------------------------
4351// Canvas export (docs/canvas.md "Exporting"): a recorded drawing replayed into an offscreen
4352// bitmap or a PDF by the same painter the on-screen canvas uses.
4353// ---------------------------------------------------------------------------
4354
4355/// The largest side, in pixels, a rendered bitmap may have (docs/canvas.md "Exporting").
4356/// day-core answers [`ExportError::TooLarge`] above it before any toolkit allocates.
4357pub const EXPORT_MAX_SIDE: u32 = 16_384;
4358
4359/// The most pixels a rendered bitmap may hold in total: 64 megapixels, 256 MB at four bytes a
4360/// pixel, which is already more than the tightest per-app heap (Android's) comfortably holds.
4361pub const EXPORT_MAX_PIXELS: u64 = 64 * 1024 * 1024;
4362
4363/// The pixel size a drawing of `size` points renders to at `scale` pixels per point: each side
4364/// rounded up, so a drawing never loses its last partial pixel. Shared by day-core's limit
4365/// check and every backend, so the bitmap a backend allocates is the one day-core approved.
4366#[must_use]
4367pub fn export_pixels(size: Size, scale: f64) -> (u32, u32) {
4368 let side = |v: f64| (v * scale).ceil().clamp(0.0, f64::from(u32::MAX)) as u32;
4369 (side(size.width), side(size.height))
4370}
4371
4372/// One page of a PDF [`Toolkit::render_pdf`] writes: the page size in PDF points (1/72 inch,
4373/// the same unit as canvas points) and the ops to replay onto it, origin top-left.
4374#[derive(Clone, Debug, PartialEq)]
4375pub struct PdfPage {
4376 pub size: Size,
4377 pub ops: Vec<DrawOp>,
4378}
4379
4380/// The document information a PDF carries. A backend whose writer has no metadata API (Android's
4381/// `PdfDocument`) ignores it.
4382#[derive(Clone, Debug, Default, PartialEq)]
4383pub struct PdfInfo {
4384 pub title: Option<String>,
4385 pub author: Option<String>,
4386}
4387
4388/// Why a canvas export could not answer (docs/canvas.md "Exporting").
4389#[derive(Clone, Debug, PartialEq)]
4390pub enum ExportError {
4391 /// This toolkit has no path for the export (probe [`Cap::CanvasBitmap`] /
4392 /// [`Cap::CanvasPdf`]).
4393 Unsupported,
4394 /// The bitmap would exceed [`EXPORT_MAX_SIDE`] or [`EXPORT_MAX_PIXELS`]; checked in
4395 /// day-core before the toolkit runs. The size is the one that was refused, in pixels.
4396 TooLarge { width: u32, height: u32 },
4397 /// A zero, negative or non-finite size or scale, or a PDF with no pages.
4398 Invalid,
4399 /// The platform refused (out of memory, a writer error); the text is the platform's.
4400 Failed(String),
4401}
4402
4403impl std::fmt::Display for ExportError {
4404 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
4405 match self {
4406 ExportError::Unsupported => write!(f, "this export is unavailable on this backend"),
4407 ExportError::TooLarge { width, height } => {
4408 write!(
4409 f,
4410 "a {width} × {height} pixel bitmap is too large to render"
4411 )
4412 }
4413 ExportError::Invalid => write!(f, "the drawing has no size or the PDF has no pages"),
4414 ExportError::Failed(why) => write!(f, "rendering failed: {why}"),
4415 }
4416 }
4417}
4418
4419impl std::error::Error for ExportError {}
4420
4421/// Where a raster image's pixels come from (docs/images.md).
4422///
4423/// One currency for both halves of the same question: `Named` is the staged asset every
4424/// `image(res::images::…)` has always drawn, `Bytes` is an encoded PNG/JPEG the app already
4425/// holds (a download, a file the user picked, a clipboard paste), and `Decoded` names an image
4426/// the toolkit decoded once so several nodes (and the canvas) share it.
4427#[derive(Clone)]
4428pub enum ImageSource {
4429 /// A staged asset name, resolved through the backend's own pipeline (§18.2).
4430 Named(String),
4431 /// Encoded bytes (PNG/JPEG/…) the app owns, decoded by the platform's own decoder. Shared
4432 /// rather than copied: handing over a new buffer is a refcount bump.
4433 Bytes(std::sync::Arc<Vec<u8>>),
4434 /// An image already decoded through [`Toolkit::decode_image`].
4435 Decoded(BitmapId),
4436}
4437
4438impl Default for ImageSource {
4439 fn default() -> Self {
4440 ImageSource::Named(String::new())
4441 }
4442}
4443
4444/// Bytes compare by identity, not content.
4445///
4446/// This is the equality a binding gates on (§4.2), so it runs on every evaluation, and
4447/// comparing two multi-megabyte buffers byte by byte would cost far more than the redundant
4448/// decode it saves. Handing over a distinct buffer holding the same pixels therefore re-decodes,
4449/// which is the same trade `Arc::ptr_eq` makes wherever else Day carries shared buffers.
4450impl PartialEq for ImageSource {
4451 fn eq(&self, other: &Self) -> bool {
4452 match (self, other) {
4453 (ImageSource::Named(a), ImageSource::Named(b)) => a == b,
4454 (ImageSource::Bytes(a), ImageSource::Bytes(b)) => std::sync::Arc::ptr_eq(a, b),
4455 (ImageSource::Decoded(a), ImageSource::Decoded(b)) => a == b,
4456 _ => false,
4457 }
4458 }
4459}
4460
4461/// Logs the buffer's length, never its contents: a `Debug` that dumped a megabyte of pixels
4462/// into a trace line would make the trace useless and slow.
4463impl std::fmt::Debug for ImageSource {
4464 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
4465 match self {
4466 ImageSource::Named(n) => f.debug_tuple("Named").field(n).finish(),
4467 ImageSource::Bytes(b) => f.debug_tuple("Bytes").field(&b.len()).finish(),
4468 ImageSource::Decoded(id) => f.debug_tuple("Decoded").field(&id.0).finish(),
4469 }
4470 }
4471}
4472
4473impl From<BitmapId> for ImageSource {
4474 fn from(id: BitmapId) -> Self {
4475 ImageSource::Decoded(id)
4476 }
4477}
4478
4479/// A staged asset name is a source, so `image(res::images::cover)` keeps compiling unchanged.
4480///
4481/// There is no `From<&str>` here, for the same reason [`resource::ImageName`] has none:
4482/// `image("typo")` must stay a compile error rather than a blank view at runtime (resource.rs).
4483/// A path or URL string is not a source either: read the bytes and hand those over.
4484impl From<resource::ImageName> for ImageSource {
4485 fn from(name: resource::ImageName) -> Self {
4486 ImageSource::Named(name.as_str().to_owned())
4487 }
4488}
4489
4490impl From<resource::VectorName> for ImageSource {
4491 fn from(name: resource::VectorName) -> Self {
4492 ImageSource::Named(name.as_str().to_owned())
4493 }
4494}
4495
4496impl From<std::sync::Arc<Vec<u8>>> for ImageSource {
4497 fn from(bytes: std::sync::Arc<Vec<u8>>) -> Self {
4498 ImageSource::Bytes(bytes)
4499 }
4500}
4501
4502/// An owned string is a name, not bytes: the same conversion [`resource::ImageName`] offers for
4503/// a name computed at runtime, and the reason `image(some_string)` keeps compiling. A `&str`
4504/// still converts nowhere, so `image("typo")` stays a compile error (resource.rs).
4505impl From<String> for ImageSource {
4506 fn from(name: String) -> Self {
4507 ImageSource::Named(name)
4508 }
4509}
4510
4511impl From<Vec<u8>> for ImageSource {
4512 fn from(bytes: Vec<u8>) -> Self {
4513 ImageSource::Bytes(std::sync::Arc::new(bytes))
4514 }
4515}
4516
4517/// What a text field collects (`text_field(..).input_purpose(_)`, docs/textfield.md).
4518///
4519/// One word for everything a platform keys off the kind of text: the on-screen keyboard's
4520/// layout, capitalization and correction, and the credential or contact the system offers to
4521/// fill in. A backend applies the parts its toolkit has: a desktop toolkit with no on-screen
4522/// keyboard still takes the autofill and correction half.
4523///
4524/// Purpose is independent of [`InputTraits::secure`]: a numeric PIN is `Number` and secure.
4525#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
4526pub enum InputPurpose {
4527 /// Free text: the default keyboard, with the platform's own capitalization and correction.
4528 #[default]
4529 Text,
4530 /// A person's name: words capitalized, never corrected.
4531 Name,
4532 /// An email address: the `@` keyboard, never capitalized or corrected.
4533 Email,
4534 /// A web address: the URL keyboard, never capitalized or corrected.
4535 Url,
4536 /// A telephone number: the phone pad.
4537 Phone,
4538 /// A whole number: the digit pad.
4539 Number,
4540 /// A number with a fractional part: the digit pad with a decimal separator.
4541 Decimal,
4542 /// An account name: never capitalized or corrected, and offered to the password manager.
4543 Username,
4544 /// An existing password, offered to the password manager for filling.
4545 Password,
4546 /// A password being chosen, so the password manager offers to make and save one.
4547 NewPassword,
4548 /// A code sent by message or mail, which the keyboard offers as it arrives. The keyboard
4549 /// stays the text one, since a code can carry letters.
4550 OneTimeCode,
4551}
4552
4553/// The on-screen keyboard's action key (`text_field(..).submit_label(_)`, docs/textfield.md).
4554///
4555/// The key always fires the field's `on_submit`; this names what it promises. A toolkit with
4556/// no on-screen keyboard ignores it.
4557#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
4558pub enum SubmitLabel {
4559 /// The platform's own key (Return).
4560 #[default]
4561 Return,
4562 Done,
4563 Go,
4564 Next,
4565 Search,
4566 Send,
4567}
4568
4569/// How a text field takes its text (docs/textfield.md): the whole set travels together through
4570/// [`Toolkit::set_input_traits`], so a backend that has to rebuild the widget for one member
4571/// has every other member in hand to dress the replacement.
4572#[derive(Clone, Debug, Default, PartialEq, Eq)]
4573pub struct InputTraits {
4574 /// Hide the characters (a password field).
4575 pub secure: bool,
4576 /// Show and select the text, take no edits.
4577 pub read_only: bool,
4578 pub purpose: InputPurpose,
4579 pub submit_label: SubmitLabel,
4580 /// The most characters (Unicode scalar values) the field takes; `None` is unbounded.
4581 /// day-pieces holds the bound on every backend. A toolkit applies its native limit as well
4582 /// only where that limit counts the same unit (GTK): one that counts UTF-16 units would
4583 /// refuse characters the bound allows.
4584 pub max_length: Option<u32>,
4585}
4586
4587/// The pointer's shape over a piece (the `.cursor()` decorator, docs/cursor.md).
4588///
4589/// The named variants are the CSS cursor vocabulary: the largest set any toolkit accepts as it
4590/// is (GTK and the DOM take the names verbatim), and every other toolkit's set is a subset of it
4591/// or maps onto it. A backend draws its own shape for each name, or the nearest one it has, and
4592/// answers [`Cap::Cursor`] with how faithful that is. [`Cursor::Native`] reaches a shape only one
4593/// toolkit names; the `day::cursor::<toolkit>` modules carry those as constants, gated on that
4594/// toolkit's feature, and every other backend ignores a name it does not know.
4595///
4596/// A cursor applies to the node and its descendants until a descendant sets its own.
4597/// [`Cursor::Default`] hands the shape back to the platform rather than pinning an arrow, so a
4598/// reactive cursor can release what it took.
4599#[derive(Clone, Debug, PartialEq, Eq, Hash, Default)]
4600pub enum Cursor {
4601 /// The platform default (an arrow), and the value that releases a node's cursor.
4602 #[default]
4603 Default,
4604 /// A pointing hand: links and other tap-to-activate content.
4605 Pointer,
4606 /// An I-beam over editable or selectable text.
4607 Text,
4608 /// An I-beam for vertical text.
4609 VerticalText,
4610 Crosshair,
4611 /// Four-way move.
4612 Move,
4613 /// An open hand: content that can be dragged.
4614 Grab,
4615 /// A closed hand: content being dragged.
4616 Grabbing,
4617 NotAllowed,
4618 /// The app is busy and cannot take input.
4619 Wait,
4620 /// The app is busy but still takes input.
4621 Progress,
4622 Help,
4623 ContextMenu,
4624 /// A drop will copy.
4625 Copy,
4626 /// A drop will link.
4627 Alias,
4628 /// A table cell.
4629 Cell,
4630 ZoomIn,
4631 ZoomOut,
4632 /// No pointer at all.
4633 None,
4634 /// Vertical (north–south) resize.
4635 NsResize,
4636 /// Horizontal (east–west) resize.
4637 EwResize,
4638 /// Diagonal resize, north-east to south-west.
4639 NeswResize,
4640 /// Diagonal resize, north-west to south-east.
4641 NwseResize,
4642 ColResize,
4643 RowResize,
4644 /// A toolkit's own named cursor, resolved by that backend's lookup and ignored by every
4645 /// other. Prefer the `day::cursor::<toolkit>` constants, which are gated on the toolkit.
4646 Native(std::borrow::Cow<'static, str>),
4647}
4648
4649impl Cursor {
4650 /// A toolkit-specific cursor by its native name (see [`Cursor::Native`]).
4651 #[must_use]
4652 pub const fn native(name: &'static str) -> Self {
4653 Cursor::Native(std::borrow::Cow::Borrowed(name))
4654 }
4655
4656 /// The CSS keyword for a named cursor, which GTK and the DOM take as it is. A native cursor
4657 /// answers its own name, so a backend keyed on CSS names may still recognize it.
4658 #[must_use]
4659 pub fn css_name(&self) -> &str {
4660 match self {
4661 Cursor::Default => "default",
4662 Cursor::Pointer => "pointer",
4663 Cursor::Text => "text",
4664 Cursor::VerticalText => "vertical-text",
4665 Cursor::Crosshair => "crosshair",
4666 Cursor::Move => "move",
4667 Cursor::Grab => "grab",
4668 Cursor::Grabbing => "grabbing",
4669 Cursor::NotAllowed => "not-allowed",
4670 Cursor::Wait => "wait",
4671 Cursor::Progress => "progress",
4672 Cursor::Help => "help",
4673 Cursor::ContextMenu => "context-menu",
4674 Cursor::Copy => "copy",
4675 Cursor::Alias => "alias",
4676 Cursor::Cell => "cell",
4677 Cursor::ZoomIn => "zoom-in",
4678 Cursor::ZoomOut => "zoom-out",
4679 Cursor::None => "none",
4680 Cursor::NsResize => "ns-resize",
4681 Cursor::EwResize => "ew-resize",
4682 Cursor::NeswResize => "nesw-resize",
4683 Cursor::NwseResize => "nwse-resize",
4684 Cursor::ColResize => "col-resize",
4685 Cursor::RowResize => "row-resize",
4686 Cursor::Native(name) => name,
4687 }
4688 }
4689
4690 /// Every named cursor, in declaration order, what a gallery or a test walks.
4691 pub const NAMED: [Cursor; 25] = [
4692 Cursor::Default,
4693 Cursor::Pointer,
4694 Cursor::Text,
4695 Cursor::VerticalText,
4696 Cursor::Crosshair,
4697 Cursor::Move,
4698 Cursor::Grab,
4699 Cursor::Grabbing,
4700 Cursor::NotAllowed,
4701 Cursor::Wait,
4702 Cursor::Progress,
4703 Cursor::Help,
4704 Cursor::ContextMenu,
4705 Cursor::Copy,
4706 Cursor::Alias,
4707 Cursor::Cell,
4708 Cursor::ZoomIn,
4709 Cursor::ZoomOut,
4710 Cursor::None,
4711 Cursor::NsResize,
4712 Cursor::EwResize,
4713 Cursor::NeswResize,
4714 Cursor::NwseResize,
4715 Cursor::ColResize,
4716 Cursor::RowResize,
4717 ];
4718}
4719
4720/// A set of screen edges, for the `defers_system_gestures` modifier (docs/cover.md). Mirrors
4721/// SwiftUI's `Edge.Set`: on iOS these map to `UIRectEdge` for
4722/// `preferredScreenEdgesDeferringSystemGestures`; on Android any non-empty set enters
4723/// swipe-to-reveal immersive mode (the closest platform analogue).
4724#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
4725pub struct Edges(pub u8);
4726
4727impl Edges {
4728 pub const NONE: Edges = Edges(0);
4729 pub const TOP: Edges = Edges(1);
4730 pub const BOTTOM: Edges = Edges(2);
4731 pub const LEADING: Edges = Edges(4);
4732 pub const TRAILING: Edges = Edges(8);
4733 pub const ALL: Edges = Edges(15);
4734
4735 #[must_use]
4736 pub fn contains(self, other: Edges) -> bool {
4737 self.0 & other.0 == other.0
4738 }
4739 #[must_use]
4740 pub fn union(self, other: Edges) -> Edges {
4741 Edges(self.0 | other.0)
4742 }
4743 #[must_use]
4744 pub fn is_empty(self) -> bool {
4745 self.0 == 0
4746 }
4747}
4748
4749impl std::ops::BitOr for Edges {
4750 type Output = Edges;
4751 fn bitor(self, rhs: Edges) -> Edges {
4752 self.union(rhs)
4753 }
4754}
4755
4756/// The timing curve of one cycle of an animation (§8.4, docs/tween.md "The animation
4757/// contract"): progress as a function of the time since the cycle started.
4758///
4759/// The four easing curves are defined by [`Curve::ease`], so every toolkit and the frame-driven
4760/// path draw the same shape: `Linear` is `t`, `EaseIn` is `t²`, `EaseOut` is `1 - (1 - t)²` and
4761/// `EaseInOut` is the smoothstep `t²(3 - 2t)`. A toolkit whose native easing differs (Core
4762/// Animation's `easeInEaseOut` is a different cubic) may use its own curve of the same name:
4763/// the conformance cases allow that much difference and no more.
4764///
4765/// `Spring` is a physical spring, not an overshoot curve stretched over a duration. Its
4766/// position is the closed-form unit-step response [`Curve::fraction`] evaluates, the response
4767/// of SwiftUI's `.spring(response:dampingFraction:)`. A toolkit with a spring animator hands
4768/// it [`Curve::spring_constants`]; every other toolkit plays [`AnimSpec::keyframes`], which
4769/// samples the same function.
4770#[derive(Clone, Copy, Debug, PartialEq)]
4771pub enum Curve {
4772 /// Constant speed.
4773 Linear,
4774 /// Slow at the start: `t²`.
4775 EaseIn,
4776 /// Slow at the end: `1 - (1 - t)²`.
4777 EaseOut,
4778 /// Slow at both ends: `t²(3 - 2t)`.
4779 EaseInOut,
4780 /// A damped spring released at rest one unit from its target.
4781 Spring {
4782 /// The period of the undamped oscillation, in seconds: the natural frequency is
4783 /// `2π / response` radians per second. Lower is faster.
4784 response: f64,
4785 /// The damping ratio: `1.0` is critically damped (the fastest approach with no
4786 /// overshoot), below `1.0` overshoots and rings, above `1.0` creeps in.
4787 damping: f64,
4788 },
4789}
4790
4791/// How close to its target a spring has to stay to count as settled: a thousandth of the
4792/// distance it travels.
4793const SPRING_REST: f64 = 0.001;
4794
4795impl Curve {
4796 /// Fraction of the transition complete at `elapsed` seconds into a cycle of `duration`
4797 /// seconds (0 at the start, reaching 1, or overshooting it for an under-damped spring).
4798 /// Easing curves clamp to `duration`; a spring evaluates its closed-form unit-step response
4799 /// at `elapsed` and does not read `duration`.
4800 #[must_use]
4801 pub fn fraction(self, elapsed: f64, duration: f64) -> f64 {
4802 if let Curve::Spring { response, damping } = self {
4803 spring_step(response, damping, elapsed)
4804 } else {
4805 let t = if duration <= 0.0 {
4806 1.0
4807 } else {
4808 (elapsed / duration).clamp(0.0, 1.0)
4809 };
4810 self.ease(t)
4811 }
4812 }
4813
4814 /// Eased progress for normalized `t` in `0.0..=1.0` (springs pass through; use [`Self::fraction`]).
4815 #[inline]
4816 #[must_use]
4817 pub fn ease(self, t: f64) -> f64 {
4818 match self {
4819 Curve::Linear | Curve::Spring { .. } => t,
4820 Curve::EaseIn => t * t,
4821 Curve::EaseOut => 1.0 - (1.0 - t) * (1.0 - t),
4822 Curve::EaseInOut => t * t * (3.0 - 2.0 * t), // smoothstep
4823 }
4824 }
4825
4826 /// Whether the transition has settled, so the canvas frame clock can stop ticking it.
4827 #[must_use]
4828 pub fn is_settled(self, elapsed: f64, duration: f64) -> bool {
4829 match self {
4830 Curve::Spring { .. } => elapsed >= self.settle_secs().unwrap_or(0.0),
4831 _ => elapsed >= duration.max(0.0),
4832 }
4833 }
4834
4835 /// How long a spring takes to settle, in seconds: the time after which it stays within a
4836 /// thousandth of its travel from the target. `None` for the easing curves, whose length is
4837 /// the spec's `duration_ms`. [`AnimSpec::spring`] uses it as the cycle's duration, so a
4838 /// spring's cycle ends where the eye can no longer see it move. Capped at thirty periods
4839 /// for a spring with next to no damping.
4840 #[must_use]
4841 pub fn settle_secs(self) -> Option<f64> {
4842 let Curve::Spring { response, damping } = self else {
4843 return None;
4844 };
4845 if response <= 0.0 {
4846 return Some(0.0);
4847 }
4848 let omega0 = std::f64::consts::TAU / response;
4849 let zeta = damping.max(0.0);
4850 let rest = (1.0 / SPRING_REST).ln();
4851 let secs = if (zeta - 1.0).abs() < 1e-3 {
4852 // (1 + ω₀t)·e^(-ω₀t) = 0.001 at ω₀t ≈ 9.233.
4853 9.233 / omega0
4854 } else if zeta < 1.0 {
4855 // The envelope e^(-ζω₀t) / √(1 - ζ²) falls below the rest distance.
4856 let root = (1.0 - zeta * zeta).sqrt();
4857 (rest - root.ln()) / (zeta.max(1e-3) * omega0)
4858 } else {
4859 // The slow root dominates: r₂/(r₂ - r₁)·e^(r₁t).
4860 let root = (zeta * zeta - 1.0).sqrt();
4861 let (slow, fast) = (omega0 * (zeta - root), omega0 * (zeta + root));
4862 (rest + (fast / (fast - slow)).ln()) / slow
4863 };
4864 Some(secs.min(response * 30.0))
4865 }
4866
4867 /// A spring's physical constants for a mass of 1, as `(stiffness, damping)`: what
4868 /// `CASpringAnimation`, `SpringAnimation`/`SpringForce`, `SpringScalarNaturalMotionAnimation`
4869 /// and `day::motion::Spring` take. `stiffness = (2π / response)²` and the damping
4870 /// coefficient is `2 · ratio · 2π / response`. `None` for the easing curves.
4871 #[must_use]
4872 pub fn spring_constants(self) -> Option<(f64, f64)> {
4873 let Curve::Spring { response, damping } = self else {
4874 return None;
4875 };
4876 let omega0 = std::f64::consts::TAU / response.max(1e-6);
4877 Some((omega0 * omega0, 2.0 * damping.max(0.0) * omega0))
4878 }
4879}
4880
4881/// Unit-step response of a second-order spring (`response` = period seconds, `damping` = ratio),
4882/// evaluated at `t` seconds. Under-damped rings and overshoots; critically damped and
4883/// over-damped approach without crossing.
4884fn spring_step(response: f64, damping: f64, t: f64) -> f64 {
4885 if response <= 0.0 || t <= 0.0 {
4886 return if t <= 0.0 { 0.0 } else { 1.0 };
4887 }
4888 let omega0 = std::f64::consts::TAU / response;
4889 let zeta = damping.max(0.0);
4890 if (zeta - 1.0).abs() < 1e-3 {
4891 let e = (-omega0 * t).exp();
4892 1.0 - e * (1.0 + omega0 * t)
4893 } else if zeta < 1.0 {
4894 let omega_d = omega0 * (1.0 - zeta * zeta).sqrt();
4895 let e = (-zeta * omega0 * t).exp();
4896 1.0 - e * ((omega_d * t).cos() + (zeta * omega0 / omega_d) * (omega_d * t).sin())
4897 } else {
4898 let root = (zeta * zeta - 1.0).sqrt();
4899 let (slow, fast) = (-omega0 * (zeta - root), -omega0 * (zeta + root));
4900 1.0 - (fast * (slow * t).exp() - slow * (fast * t).exp()) / (fast - slow)
4901 }
4902}
4903
4904/// Where an [`AnimSpec`] is at one moment: what [`AnimSpec::sample`] answers.
4905#[derive(Clone, Copy, Debug, PartialEq)]
4906pub struct AnimSample {
4907 /// `0` at the start value, `1` at the target. A spring may pass `1` on the way. Once
4908 /// `done`, it is where the last cycle ended: `1`, or `0` when an autoreversed run ended on
4909 /// a backward cycle.
4910 pub progress: f64,
4911 /// Whether the run is over. Always `false` for a spec that repeats forever.
4912 pub done: bool,
4913}
4914
4915/// One point of a cycle's curve: what [`AnimSpec::keyframes`] yields.
4916#[derive(Clone, Copy, Debug, PartialEq)]
4917pub struct Keyframe {
4918 /// When, as a fraction of the cycle: `0.0` at its start, `1.0` at its end.
4919 pub offset: f64,
4920 /// The progress there: `0` is the start value, `1` the target. Outside `0..=1` where a
4921 /// spring overshoots.
4922 pub progress: f64,
4923}
4924
4925/// Animation intent (§8.4): how a change to a native property is to be played. Threaded through
4926/// `Toolkit::update`/`set_frame`/`set_opacity`/`set_transform`; the toolkit plays it on its own
4927/// animator, and the frame-driven path (`day::motion`) samples the same function.
4928///
4929/// # The contract every toolkit keeps
4930///
4931/// A change from the value on screen (the *start*) to the new value (the *target*) plays as
4932/// follows, and [`AnimSpec::sample`] is that timeline as a function, so a toolkit with no
4933/// matching native feature drives the property from it and a test compares against it.
4934///
4935/// 1. **Delay.** For `delay_ms` the property keeps showing the start value. The delay is
4936/// served once, before the first cycle, never between repeats.
4937/// 2. **Cycle.** One cycle lasts `duration_ms` and follows `curve` from the start to the
4938/// target. A zero duration applies the target at once (after the delay).
4939/// 3. **Repeat.** The cycle plays `repeat + 1` times; `u32::MAX` repeats until the property
4940/// is next changed. Without `autoreverse` every cycle starts again from the start value.
4941/// 4. **Autoreverse.** With `autoreverse` every second cycle (the 2nd, 4th, …) plays the curve
4942/// backwards, from the target to the start.
4943/// 5. **Rest.** When a finite run ends the property rests on the target, whatever the last
4944/// cycle did. A run that ends on a backward cycle (autoreverse with an odd `repeat`) is
4945/// therefore followed by a jump to the target; use an even `repeat` to end on a forward one.
4946/// 6. **Spring.** A `Curve::Spring` cycle is the spring's closed-form response
4947/// ([`Curve::fraction`]) for `duration_ms`, which [`AnimSpec::spring`] sets to the spring's
4948/// settle time, and it ends exactly on the cycle's end value.
4949/// 7. **Retarget.** A new change to a property in flight starts from the value on screen. A
4950/// change with no animation cancels the run and applies at once.
4951///
4952/// What animates: frame, opacity, transform, and a container's background color
4953/// (`ContainerPatch::Background`), whose in-between colors lie between the two ends in every
4954/// channel.
4955#[derive(Clone, Copy, Debug, PartialEq)]
4956pub struct AnimSpec {
4957 /// The length of one cycle, in milliseconds.
4958 pub duration_ms: u32,
4959 /// How long the start value is held before the first cycle, in milliseconds.
4960 pub delay_ms: u32,
4961 /// The shape of one cycle.
4962 pub curve: Curve,
4963 /// Cycles beyond the first (`0` = play once); `u32::MAX` = repeat forever.
4964 pub repeat: u32,
4965 /// Whether every second cycle plays backwards.
4966 pub autoreverse: bool,
4967}
4968
4969impl Default for AnimSpec {
4970 /// The default feel: a smooth spring (SwiftUI's modern default).
4971 fn default() -> Self {
4972 AnimSpec::spring(0.4, 0.8)
4973 }
4974}
4975
4976impl AnimSpec {
4977 /// How many keyframes [`AnimSpec::keyframes`] yields per second of cycle.
4978 pub const KEYFRAMES_PER_SECOND: f64 = 60.0;
4979
4980 /// A spring: `response` is the period of its undamped oscillation in seconds, `damping`
4981 /// its damping ratio (`1.0` = no bounce, below `1.0` bouncy). `duration_ms` is the spring's
4982 /// settle time ([`Curve::settle_secs`]), so the cycle ends once the motion is too small to
4983 /// see and a repeat or an autoreverse has a definite length.
4984 #[must_use]
4985 pub fn spring(response: f64, damping: f64) -> Self {
4986 let curve = Curve::Spring { response, damping };
4987 AnimSpec {
4988 duration_ms: (curve.settle_secs().unwrap_or(0.0) * 1000.0)
4989 .ceil()
4990 .max(50.0) as u32,
4991 delay_ms: 0,
4992 curve,
4993 repeat: 0,
4994 autoreverse: false,
4995 }
4996 }
4997 /// Constant speed over `duration_ms`.
4998 #[must_use]
4999 pub fn linear(duration_ms: u32) -> Self {
5000 Self::timed(duration_ms, Curve::Linear)
5001 }
5002 /// Slow at the start, over `duration_ms`.
5003 #[must_use]
5004 pub fn ease_in(duration_ms: u32) -> Self {
5005 Self::timed(duration_ms, Curve::EaseIn)
5006 }
5007 /// Slow at the end, over `duration_ms`.
5008 #[must_use]
5009 pub fn ease_out(duration_ms: u32) -> Self {
5010 Self::timed(duration_ms, Curve::EaseOut)
5011 }
5012 /// Slow at both ends, over `duration_ms`.
5013 #[must_use]
5014 pub fn ease_in_out(duration_ms: u32) -> Self {
5015 Self::timed(duration_ms, Curve::EaseInOut)
5016 }
5017 fn timed(duration_ms: u32, curve: Curve) -> Self {
5018 AnimSpec {
5019 duration_ms,
5020 delay_ms: 0,
5021 curve,
5022 repeat: 0,
5023 autoreverse: false,
5024 }
5025 }
5026 /// Delay before the animation starts (builder).
5027 #[must_use]
5028 pub fn delay(mut self, ms: u32) -> Self {
5029 self.delay_ms = ms;
5030 self
5031 }
5032 /// Repeat `count` extra times (builder); `autoreverse` ping-pongs each cycle.
5033 #[must_use]
5034 pub fn repeat(mut self, count: u32, autoreverse: bool) -> Self {
5035 self.repeat = count;
5036 self.autoreverse = autoreverse;
5037 self
5038 }
5039 /// Repeat forever (builder), e.g. a pulsing indicator.
5040 #[must_use]
5041 pub fn repeat_forever(mut self, autoreverse: bool) -> Self {
5042 self.repeat = u32::MAX;
5043 self.autoreverse = autoreverse;
5044 self
5045 }
5046 /// One cycle, in seconds.
5047 #[inline]
5048 #[must_use]
5049 pub fn duration_secs(&self) -> f64 {
5050 f64::from(self.duration_ms) / 1000.0
5051 }
5052 /// The delay, in seconds.
5053 #[inline]
5054 #[must_use]
5055 pub fn delay_secs(&self) -> f64 {
5056 f64::from(self.delay_ms) / 1000.0
5057 }
5058 /// Whether the spec repeats until the property is next changed.
5059 #[inline]
5060 #[must_use]
5061 pub fn repeats_forever(&self) -> bool {
5062 self.repeat == u32::MAX
5063 }
5064 /// How many cycles play, or `None` for a spec that repeats forever.
5065 #[must_use]
5066 pub fn cycles(&self) -> Option<u32> {
5067 (!self.repeats_forever()).then(|| self.repeat + 1)
5068 }
5069 /// The whole run including the delay, in seconds, or `None` for a spec that repeats forever.
5070 #[must_use]
5071 pub fn total_secs(&self) -> Option<f64> {
5072 self.cycles()
5073 .map(|cycles| self.delay_secs() + self.duration_secs() * f64::from(cycles))
5074 }
5075 /// Whether a finite run's last cycle plays backwards, ending on the start value before the
5076 /// property rests on its target (contract rule 5).
5077 #[must_use]
5078 pub fn ends_reversed(&self) -> bool {
5079 self.autoreverse && self.cycles().is_some_and(|cycles| cycles.is_multiple_of(2))
5080 }
5081
5082 /// Where the run is `elapsed` seconds after the change was made: the contract above as a
5083 /// function. During the delay the progress is `0`; inside a cycle it is the curve, read
5084 /// backwards on an autoreversed cycle; after the last cycle `done` is set and the progress
5085 /// is where that cycle ended. The property itself rests on its target once `done`.
5086 #[must_use]
5087 pub fn sample(&self, elapsed: f64) -> AnimSample {
5088 let t = elapsed - self.delay_secs();
5089 if t < 0.0 || !t.is_finite() {
5090 return AnimSample {
5091 progress: 0.0,
5092 done: false,
5093 };
5094 }
5095 let one = self.duration_secs();
5096 if one <= 0.0 {
5097 return AnimSample {
5098 progress: 1.0,
5099 done: true,
5100 };
5101 }
5102 let index = (t / one).floor();
5103 if let Some(cycles) = self.cycles()
5104 && index >= f64::from(cycles)
5105 {
5106 return AnimSample {
5107 progress: if self.ends_reversed() { 0.0 } else { 1.0 },
5108 done: true,
5109 };
5110 }
5111 let mut local = t - index * one;
5112 if self.autoreverse && (index as u64) % 2 == 1 {
5113 local = one - local;
5114 }
5115 AnimSample {
5116 progress: self.cycle_progress(local / one),
5117 done: false,
5118 }
5119 }
5120
5121 /// The progress at `offset` (`0.0..=1.0`) of one forward cycle. The cycle's last point is
5122 /// exactly `1`, so a spring ends on its target instead of a residue away from it.
5123 #[must_use]
5124 pub fn cycle_progress(&self, offset: f64) -> f64 {
5125 if offset >= 1.0 {
5126 return 1.0;
5127 }
5128 let one = self.duration_secs();
5129 self.curve.fraction(offset.max(0.0) * one, one)
5130 }
5131
5132 /// One forward cycle as evenly spaced keyframes, [`Self::KEYFRAMES_PER_SECOND`] of them per
5133 /// second of cycle and never fewer than two: the first at offset 0 and progress 0, the last
5134 /// at offset 1 and progress exactly 1. A toolkit without a spring animator plays these
5135 /// through its keyframe animation or its custom interpolator with linear interpolation
5136 /// between neighbors, which makes every toolkit draw the same spring. They serve the easing
5137 /// curves equally, for a toolkit whose native curve of that name has another shape.
5138 #[must_use]
5139 pub fn keyframes(&self) -> Vec<Keyframe> {
5140 let steps = ((self.duration_secs() * Self::KEYFRAMES_PER_SECOND).ceil() as usize).max(1);
5141 (0..=steps)
5142 .map(|i| {
5143 let offset = i as f64 / steps as f64;
5144 Keyframe {
5145 offset,
5146 progress: self.cycle_progress(offset),
5147 }
5148 })
5149 .collect()
5150 }
5151}
5152
5153/// What a widget shows right now, an animation's in-between state included: what
5154/// [`Toolkit::read_displayed`] answers and the `assert_displayed` step checks (docs/testing.md).
5155///
5156/// [`NativeSnapshot`] reports the state a widget was given; this reports what is on screen
5157/// while the toolkit's animator is still on its way there (Core Animation's presentation
5158/// layer, a `View`'s animated properties, a computed style). Each field is read on its own and
5159/// `None` means "not read": the toolkit cannot observe that property mid-flight.
5160#[derive(Clone, Copy, Debug, Default, PartialEq)]
5161pub struct Displayed {
5162 /// The opacity shown, `0.0..=1.0`.
5163 pub opacity: Option<f64>,
5164 /// The frame shown, in points, in the space [`NativeSnapshot::frame`] uses, before any
5165 /// transform.
5166 pub frame: Option<Rect>,
5167 /// The translation shown, in points: the transform's `tx`/`ty`. A toolkit that animates a
5168 /// transform animates its translation, scale and rotation as one, so this one component
5169 /// stands for the channel.
5170 pub translation: Option<Point>,
5171 /// The background color shown, for a container with one.
5172 pub background: Option<Color>,
5173}
5174
5175#[cfg(test)]
5176mod anim_tests {
5177 use super::*;
5178
5179 fn near(a: f64, b: f64) -> bool {
5180 (a - b).abs() < 1e-9
5181 }
5182
5183 #[test]
5184 fn a_linear_run_lasts_its_duration_then_is_done() {
5185 let spec = AnimSpec::linear(200);
5186 assert!(near(spec.sample(0.0).progress, 0.0));
5187 assert!(near(spec.sample(0.1).progress, 0.5));
5188 assert!(!spec.sample(0.199).done);
5189 let end = spec.sample(0.2);
5190 assert!(end.done && near(end.progress, 1.0));
5191 assert_eq!(spec.total_secs(), Some(0.2));
5192 assert_eq!(spec.cycles(), Some(1));
5193 }
5194
5195 #[test]
5196 fn the_delay_is_served_once_and_cycles_repeat_or_reverse() {
5197 let restart = AnimSpec::linear(100).delay(100).repeat(2, false);
5198 assert!(near(restart.sample(0.05).progress, 0.0));
5199 assert!(near(restart.sample(0.15).progress, 0.5));
5200 // The second and third cycles start from the beginning again, with no second delay.
5201 assert!(near(restart.sample(0.225).progress, 0.25));
5202 assert!(near(restart.sample(0.375).progress, 0.75));
5203 assert!(restart.sample(0.4).done && !restart.ends_reversed());
5204 assert!(near(restart.total_secs().unwrap(), 0.4));
5205
5206 let back = AnimSpec::linear(100).delay(100).repeat(1, true);
5207 assert!(near(back.sample(0.15).progress, 0.5)); // forward
5208 assert!(near(back.sample(0.275).progress, 0.25)); // back
5209 let end = back.sample(0.31);
5210 assert!(end.done && near(end.progress, 0.0) && back.ends_reversed());
5211 assert!(!AnimSpec::linear(100).repeat(2, true).ends_reversed());
5212
5213 let forever = AnimSpec::linear(100).repeat_forever(true);
5214 assert!(!forever.sample(1000.0).done);
5215 assert_eq!(forever.total_secs(), None);
5216 assert_eq!(forever.cycles(), None);
5217
5218 let instant = AnimSpec::linear(0).delay(50);
5219 assert!(!instant.sample(0.01).done);
5220 assert!(instant.sample(0.05).done && near(instant.sample(0.05).progress, 1.0));
5221 }
5222
5223 #[test]
5224 fn a_spring_cycle_is_the_closed_form_and_ends_on_its_target() {
5225 let spec = AnimSpec::spring(0.5, 0.4);
5226 let Curve::Spring { response, damping } = spec.curve else {
5227 panic!("a spring spec has a spring curve");
5228 };
5229 assert!(near(response, 0.5) && near(damping, 0.4));
5230 // The cycle lasts the settle time, well past the response.
5231 let settle = spec.curve.settle_secs().unwrap();
5232 assert!(settle > 1.0 && settle < 2.0, "{settle}");
5233 assert!((spec.duration_secs() - settle).abs() < 0.002);
5234 let peak = (1..100)
5235 .map(|i| spec.sample(f64::from(i) * 0.01).progress)
5236 .fold(0.0, f64::max);
5237 assert!(peak > 1.2, "an under-damped spring overshoots: {peak}");
5238 // Within a thousandth from the settle time on, and exactly 1 at the end.
5239 let late = spec.curve.fraction(settle, 0.0);
5240 assert!((late - 1.0).abs() <= 0.001_5, "{late}");
5241 let end = spec.sample(spec.duration_secs());
5242 assert!(end.done && near(end.progress, 1.0));
5243
5244 // Critically damped and over-damped springs never pass the target.
5245 for ratio in [1.0, 1.6] {
5246 let curve = Curve::Spring {
5247 response: 0.4,
5248 damping: ratio,
5249 };
5250 assert!((1..200).all(|i| curve.fraction(f64::from(i) * 0.01, 0.0) <= 1.000_001));
5251 let settle = curve.settle_secs().unwrap();
5252 assert!(
5253 (curve.fraction(settle, 0.0) - 1.0).abs() <= 0.001_5,
5254 "{ratio}"
5255 );
5256 assert!(curve.is_settled(settle, 0.0) && !curve.is_settled(0.0, 0.0));
5257 }
5258 // The physical constants of a mass of 1.
5259 let (stiffness, damping) = spec.curve.spring_constants().unwrap();
5260 let omega0 = std::f64::consts::TAU / 0.5;
5261 assert!(near(stiffness, omega0 * omega0) && near(damping, 2.0 * 0.4 * omega0));
5262 assert_eq!(Curve::Linear.spring_constants(), None);
5263 assert_eq!(Curve::EaseIn.settle_secs(), None);
5264 }
5265
5266 #[test]
5267 fn keyframes_sample_one_cycle_end_to_end() {
5268 let spring = AnimSpec::spring(0.4, 0.5);
5269 let frames = spring.keyframes();
5270 assert!(frames.len() >= 30, "{}", frames.len());
5271 let (first, last) = (frames[0], frames[frames.len() - 1]);
5272 assert!(near(first.offset, 0.0) && near(first.progress, 0.0));
5273 assert!(near(last.offset, 1.0) && near(last.progress, 1.0));
5274 assert!(frames.windows(2).all(|w| w[1].offset > w[0].offset));
5275 assert!(
5276 frames.iter().any(|k| k.progress > 1.05),
5277 "the overshoot is in the samples"
5278 );
5279 // Each keyframe is the timeline's own value at that moment.
5280 for k in &frames[1..frames.len() - 1] {
5281 let at = spring.sample(k.offset * spring.duration_secs()).progress;
5282 assert!((at - k.progress).abs() < 1e-6);
5283 }
5284 // An easing curve samples the same way; an instant spec is its two ends.
5285 let ease = AnimSpec::ease_in(100).keyframes();
5286 assert_eq!(ease.len(), 7);
5287 assert!(near(ease[3].progress, 0.25));
5288 assert_eq!(AnimSpec::linear(0).keyframes().len(), 2);
5289 }
5290}
5291
5292#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
5293pub enum Role {
5294 #[default]
5295 None,
5296 Button,
5297 Toggle,
5298 Slider,
5299 TextInput,
5300 Heading(u8),
5301 Image,
5302 Meter,
5303 Group,
5304 /// A hierarchical tree container (docs/tree.md): `role="tree"`, `AXOutline`.
5305 Tree,
5306 /// One row of a tree: `role="treeitem"`, with level/expanded state where the platform
5307 /// carries them (docs/tree.md).
5308 TreeItem,
5309 /// One tab in a strip of peers (`role="tab"`, `AXTabButton`): the composed document
5310 /// strip's title buttons. Pair it with [`A11yProps::selected`] for the current one.
5311 Tab,
5312 /// The strip holding tabs (`role="tablist"`, `AXTabGroup`).
5313 TabList,
5314}
5315
5316impl Role {
5317 /// The a11y role a built-in piece kind reports natively, the audit's *expectation* when the
5318 /// user hasn't set an explicit `.role()`. Native controls already expose these, so Day records
5319 /// them for `a11y_audit` (§14.2) rather than overriding the widget; only canvas/custom pieces
5320 /// need Day to apply a role. Returns `None` for kinds with no inherent control role.
5321 #[must_use]
5322 pub fn for_kind(kind: PieceKind) -> Role {
5323 match kind {
5324 kinds::BUTTON => Role::Button,
5325 kinds::TOGGLE => Role::Toggle,
5326 kinds::SLIDER => Role::Slider,
5327 kinds::TEXT_FIELD => Role::TextInput,
5328 kinds::IMAGE => Role::Image,
5329 kinds::PROGRESS => Role::Meter,
5330 kinds::TREE => Role::Tree,
5331 _ => Role::None,
5332 }
5333 }
5334}
5335
5336#[derive(Clone, Debug, Default, PartialEq)]
5337pub struct A11yProps {
5338 pub label: Option<String>,
5339 pub hint: Option<String>,
5340 pub value: Option<String>,
5341 pub role: Role,
5342 pub identifier: Option<String>,
5343 pub hidden: bool,
5344 pub decorative: bool,
5345 /// Whether the element is the selected one among its peers (a tab, a row): the
5346 /// platform's selected state, read aloud as such. `None` leaves the widget's own answer.
5347 pub selected: Option<bool>,
5348}
5349
5350impl A11yProps {
5351 /// Merge another set of annotations onto this one: any field `other` sets (a `Some`, a
5352 /// non-`None` role, or a `true` flag) overrides ours; unset fields are left intact. Lets a
5353 /// node accumulate its `.a11y()`, `.id()`, and piece defaults into one stored result, so
5354 /// each `set_a11y` re-applies the full picture and `a11y_audit` has the complete expectation.
5355 pub fn merge(&mut self, other: &A11yProps) {
5356 if other.label.is_some() {
5357 self.label.clone_from(&other.label);
5358 }
5359 if other.hint.is_some() {
5360 self.hint.clone_from(&other.hint);
5361 }
5362 if other.value.is_some() {
5363 self.value.clone_from(&other.value);
5364 }
5365 if other.role != Role::None {
5366 self.role = other.role;
5367 }
5368 if other.identifier.is_some() {
5369 self.identifier.clone_from(&other.identifier);
5370 }
5371 self.hidden |= other.hidden;
5372 self.decorative |= other.decorative;
5373 if other.selected.is_some() {
5374 self.selected = other.selected;
5375 }
5376 }
5377
5378 /// The role to *expect* for a node of `kind` carrying these annotations: an explicit
5379 /// `.role()` wins, otherwise the kind's native default (`Role::for_kind`).
5380 #[must_use]
5381 pub fn resolved_role(&self, kind: PieceKind) -> Role {
5382 if self.role == Role::None {
5383 Role::for_kind(kind)
5384 } else {
5385 self.role
5386 }
5387 }
5388}
5389
5390/// A widget's actual native state, read back from the platform by `Toolkit::read_native`
5391/// (docs/testing.md): what the widget itself shows and reports, independently of Day's tree,
5392/// so `a11y_audit` and `assert_native` (§14.2) can diff it against Day's expectation.
5393///
5394/// Two groups. The accessibility fields (`role`, `label`, `value`, `identifier`) are read
5395/// together and `found` says whether they were: `found = false` means the backend cannot read
5396/// its accessibility tree, and the audit skips the node. Every other field is read on its own,
5397/// and `None` means "not read": the backend cannot read it, or it does not apply to this kind.
5398/// A reader never reports a field it did not take from the widget, so a `None` is a recorded
5399/// gap rather than a pass.
5400#[derive(Clone, Debug, Default, PartialEq)]
5401pub struct NativeSnapshot {
5402 /// The accessibility fields below were read.
5403 pub found: bool,
5404 /// The native role mapped back to Day's `Role` (best-effort).
5405 pub role: Role,
5406 /// The accessibility label the platform reports.
5407 pub label: Option<String>,
5408 /// The accessibility value the platform reports.
5409 pub value: Option<String>,
5410 /// The automation identifier, which Day sets from `.id()`.
5411 pub identifier: Option<String>,
5412 /// The text the widget displays: a label's string, a button's title, a text field's or
5413 /// text area's contents, without markup or mnemonic markers. `None` for a secure field
5414 /// that masks it.
5415 pub text: Option<String>,
5416 /// A slider's or progress indicator's value, in the range Day gave it.
5417 pub number: Option<f64>,
5418 /// A toggle's state, or a button's selected state (`ButtonProps::selected`).
5419 pub checked: Option<bool>,
5420 /// Whether the widget takes input.
5421 pub enabled: Option<bool>,
5422 /// Whether the widget is shown: not hidden itself, nor by an ancestor.
5423 pub visible: Option<bool>,
5424 /// The widget's frame in points, relative to the window's content area, origin top left.
5425 pub frame: Option<Rect>,
5426}
5427
5428// ---------------------------------------------------------------------------
5429// Canvas display list (§11): full op set lands with M8a; the types are v1.
5430// ---------------------------------------------------------------------------
5431
5432#[derive(Clone, Debug, PartialEq)]
5433pub enum Shape {
5434 Rect(Rect),
5435 RoundedRect(Rect, f64),
5436 Ellipse(Rect),
5437 /// Arc within `rect`'s inscribed ellipse; `start` from the +x axis and `sweep`, both
5438 /// positive clockwise on screen.
5439 Arc {
5440 rect: Rect,
5441 start: Angle,
5442 sweep: Angle,
5443 },
5444 Line(Point, Point),
5445 Polygon(Vec<Point>),
5446 /// An arbitrary path: curves, several contours, and a fill rule (docs/canvas.md).
5447 ///
5448 /// [`Shape::Polygon`] is the straight-line, single-contour special case, kept because it is
5449 /// what most drawing code wants and it encodes far more compactly.
5450 Path(Path),
5451}
5452
5453impl Shape {
5454 /// A rectangle rounded corner by corner (docs/canvas.md "Rounded corners"), as the simplest
5455 /// shape that draws it: a plain [`Shape::Rect`] when every corner is square, a
5456 /// [`Shape::RoundedRect`] (each toolkit's own rounded rectangle) when the corners agree, and a
5457 /// path ([`rounded_rect_segs`]) otherwise. The radii are [fitted](CornerRadii::fitted) first.
5458 ///
5459 /// ```
5460 /// use day_spec::{CornerRadii, Rect, Shape};
5461 ///
5462 /// // A bar standing on its axis: rounded on top, square where it meets the baseline.
5463 /// let bar = Shape::rounded_rect(Rect::new(0.0, 0.0, 20.0, 80.0), CornerRadii::top(6.0));
5464 /// std::assert_matches!(bar, Shape::Path(_));
5465 /// ```
5466 pub fn rounded_rect(rect: Rect, radii: CornerRadii) -> Shape {
5467 let r = radii.fitted(rect.size);
5468 if r.is_zero() || rect.size.width <= 0.0 || rect.size.height <= 0.0 {
5469 Shape::Rect(rect)
5470 } else if r.is_uniform() {
5471 Shape::RoundedRect(rect, r.top_left)
5472 } else {
5473 Shape::Path(Path {
5474 segs: rounded_rect_segs(rect, r),
5475 rule: FillRule::NonZero,
5476 })
5477 }
5478 }
5479
5480 /// The same shape moved by `(dx, dy)`.
5481 ///
5482 /// What a [`Stamp`] means by "the template translated by one point", and the one definition of
5483 /// it: a backend builds each copy of a batch with this rather than reaching for its own
5484 /// platform transform, so every toolkit stamps to the same coordinates.
5485 #[must_use]
5486 pub fn translated(&self, dx: f64, dy: f64) -> Shape {
5487 let r = |r: &Rect| {
5488 Rect::new(
5489 r.origin.x + dx,
5490 r.origin.y + dy,
5491 r.size.width,
5492 r.size.height,
5493 )
5494 };
5495 let p = |p: &Point| Point::new(p.x + dx, p.y + dy);
5496 match self {
5497 Shape::Rect(rect) => Shape::Rect(r(rect)),
5498 Shape::RoundedRect(rect, rad) => Shape::RoundedRect(r(rect), *rad),
5499 Shape::Ellipse(rect) => Shape::Ellipse(r(rect)),
5500 Shape::Arc { rect, start, sweep } => Shape::Arc {
5501 rect: r(rect),
5502 start: *start,
5503 sweep: *sweep,
5504 },
5505 Shape::Line(a, b) => Shape::Line(p(a), p(b)),
5506 Shape::Polygon(pts) => Shape::Polygon(pts.iter().map(p).collect()),
5507 Shape::Path(path) => Shape::Path(Path {
5508 segs: path
5509 .segs
5510 .iter()
5511 .map(|seg| match seg {
5512 PathSeg::Move(a) => PathSeg::Move(p(a)),
5513 PathSeg::Line(a) => PathSeg::Line(p(a)),
5514 PathSeg::Quad(c, a) => PathSeg::Quad(p(c), p(a)),
5515 PathSeg::Cubic(c1, c2, a) => PathSeg::Cubic(p(c1), p(c2), p(a)),
5516 PathSeg::Close => PathSeg::Close,
5517 })
5518 .collect(),
5519 rule: path.rule,
5520 }),
5521 }
5522 }
5523
5524 /// The shape's bounding rectangle: the box gradient [`UnitPoint`]s resolve against.
5525 pub fn bounds(&self) -> Rect {
5526 match self {
5527 Shape::Rect(r) | Shape::RoundedRect(r, _) | Shape::Ellipse(r) => *r,
5528 Shape::Arc { rect, .. } => *rect,
5529 Shape::Line(a, b) => points_bounds(&[*a, *b]),
5530 Shape::Polygon(pts) => points_bounds(pts),
5531 Shape::Path(p) => p.bounds(),
5532 }
5533 }
5534}
5535
5536/// One step of a [`Path`]. Points are absolute, in the canvas's coordinate space.
5537#[derive(Clone, Copy, Debug, PartialEq)]
5538pub enum PathSeg {
5539 /// Start a new contour at this point.
5540 Move(Point),
5541 Line(Point),
5542 /// Quadratic bezier: one control point, then the end point.
5543 Quad(Point, Point),
5544 /// Cubic bezier: two control points, then the end point.
5545 Cubic(Point, Point, Point),
5546 /// Close the current contour back to its `Move`.
5547 Close,
5548}
5549
5550/// Which points count as inside when a path's contours overlap (docs/canvas.md).
5551///
5552/// This matters the moment a shape has a hole: the counter of an "o", a washer, a ring chart. It
5553/// is a property of the fill, so stroking ignores it.
5554#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
5555pub enum FillRule {
5556 /// Direction-sensitive: a hole needs its contour wound the opposite way. Every 2-D API's
5557 /// default, and what a font's glyph outlines assume.
5558 #[default]
5559 NonZero,
5560 /// Parity: any contour inside another cuts a hole regardless of winding. What PDF's `f*`
5561 /// operator and SVG's `fill-rule: evenodd` mean.
5562 EvenOdd,
5563}
5564
5565/// An arbitrary 2-D path: any number of contours, straight or curved, with a fill rule.
5566#[derive(Clone, Debug, PartialEq, Default)]
5567pub struct Path {
5568 pub segs: Vec<PathSeg>,
5569 pub rule: FillRule,
5570}
5571
5572impl Path {
5573 /// A conservative bounding box: the hull of every point including control points, which
5574 /// contains the true curve bounds (a bezier stays inside its control hull). Used only to
5575 /// resolve gradient unit points, where being slightly generous costs nothing and computing
5576 /// exact curve extrema would not.
5577 pub fn bounds(&self) -> Rect {
5578 let mut pts: Vec<Point> = Vec::with_capacity(self.segs.len() * 3);
5579 for seg in &self.segs {
5580 match seg {
5581 PathSeg::Move(p) | PathSeg::Line(p) => pts.push(*p),
5582 PathSeg::Quad(c, p) => pts.extend_from_slice(&[*c, *p]),
5583 PathSeg::Cubic(c1, c2, p) => pts.extend_from_slice(&[*c1, *c2, *p]),
5584 PathSeg::Close => {}
5585 }
5586 }
5587 points_bounds(&pts)
5588 }
5589}
5590
5591/// A radius for each corner of a rectangle, clockwise from the top left (docs/canvas.md "Rounded
5592/// corners"). The shape a bar in a chart wants (rounded at its value end, square against its
5593/// axis), a tab (rounded on top), or a card joined to its neighbor.
5594///
5595/// Radii are in points and never negative. [`CornerRadii::fitted`] shrinks them the way CSS
5596/// does when two radii on one side would overlap, which is what a caller animating a radius or
5597/// drawing a short bar needs to not think about.
5598#[derive(Clone, Copy, Debug, PartialEq, Default)]
5599pub struct CornerRadii {
5600 pub top_left: f64,
5601 pub top_right: f64,
5602 pub bottom_right: f64,
5603 pub bottom_left: f64,
5604}
5605
5606impl CornerRadii {
5607 /// The same radius on every corner: what [`Shape::RoundedRect`] draws.
5608 pub fn uniform(r: f64) -> Self {
5609 CornerRadii {
5610 top_left: r,
5611 top_right: r,
5612 bottom_right: r,
5613 bottom_left: r,
5614 }
5615 }
5616 /// Rounded along the top edge, square along the bottom: a bar standing on its axis.
5617 pub fn top(r: f64) -> Self {
5618 CornerRadii {
5619 top_left: r,
5620 top_right: r,
5621 ..Default::default()
5622 }
5623 }
5624 /// Rounded along the bottom edge: a bar hanging below its axis.
5625 pub fn bottom(r: f64) -> Self {
5626 CornerRadii {
5627 bottom_right: r,
5628 bottom_left: r,
5629 ..Default::default()
5630 }
5631 }
5632 /// Rounded along the left edge: a bar growing leftward from its axis.
5633 pub fn left(r: f64) -> Self {
5634 CornerRadii {
5635 top_left: r,
5636 bottom_left: r,
5637 ..Default::default()
5638 }
5639 }
5640 /// Rounded along the right edge: a bar growing rightward from its axis.
5641 pub fn right(r: f64) -> Self {
5642 CornerRadii {
5643 top_right: r,
5644 bottom_right: r,
5645 ..Default::default()
5646 }
5647 }
5648
5649 /// The four radii, clockwise from the top left.
5650 #[must_use]
5651 pub fn to_array(self) -> [f64; 4] {
5652 [
5653 self.top_left,
5654 self.top_right,
5655 self.bottom_right,
5656 self.bottom_left,
5657 ]
5658 }
5659
5660 /// Whether every corner is square.
5661 #[must_use]
5662 pub fn is_zero(self) -> bool {
5663 self.to_array().iter().all(|r| *r <= 0.0)
5664 }
5665
5666 /// Whether every corner has the same radius, so the rectangle is a [`Shape::RoundedRect`].
5667 #[must_use]
5668 #[expect(
5669 clippy::float_cmp,
5670 reason = "uniform means the four stored radii are exactly equal"
5671 )]
5672 pub fn is_uniform(self) -> bool {
5673 let [a, b, c, d] = self.to_array();
5674 a == b && b == c && c == d
5675 }
5676
5677 /// These radii made to fit a `size` rectangle, the rule CSS uses for `border-radius`: a
5678 /// negative or non-finite radius is square, and when the two radii along any side add up to
5679 /// more than that side, every radius is scaled down by the same factor until none overlap.
5680 /// Scaling all four together keeps the corners in proportion, where clamping each one alone
5681 /// would turn a pill into a lopsided shape.
5682 #[must_use]
5683 pub fn fitted(self, size: Size) -> Self {
5684 let clean = |r: f64| if r.is_finite() && r > 0.0 { r } else { 0.0 };
5685 let [tl, tr, br, bl] = self.to_array().map(clean);
5686 let (w, h) = (size.width.max(0.0), size.height.max(0.0));
5687 let factor = [(w, tl + tr), (w, bl + br), (h, tl + bl), (h, tr + br)]
5688 .into_iter()
5689 .filter(|(_, sum)| *sum > 0.0)
5690 .map(|(side, sum)| side / sum)
5691 .fold(1.0f64, f64::min);
5692 CornerRadii {
5693 top_left: tl * factor,
5694 top_right: tr * factor,
5695 bottom_right: br * factor,
5696 bottom_left: bl * factor,
5697 }
5698 }
5699}
5700
5701/// The point at `angle` round a circle: `0` = the +x axis, positive clockwise in device space
5702/// (y down), the convention [`Shape::Arc`] and every arc helper here use.
5703#[must_use]
5704pub fn arc_point(center: Point, radius: f64, angle: Angle) -> Point {
5705 let (sin, cos) = angle.sin_cos();
5706 Point::new(center.x + radius * cos, center.y + radius * sin)
5707}
5708
5709/// A circular arc as cubic beziers: `sweep` of a circle of `radius` about `center`, from
5710/// `start` ([`arc_point`]'s convention). The segments start *from* the arc's first point, which
5711/// the caller reaches itself (a move or a line); nothing for a zero or non-finite radius or sweep.
5712///
5713/// The arc is split into quarter turns at most, where a cubic tracks a circle best: the radial
5714/// error peaks at 2.7 × 10⁻⁴ of the radius, a quarter of a pixel on a circle a thousand points
5715/// across (docs/canvas.md "Paths"). The same beziers on every backend mean the same pixels on
5716/// every backend, which an arc op interpreted by nine rasterizers would not.
5717#[must_use]
5718pub fn arc_cubics(center: Point, radius: f64, start: Angle, sweep: Angle) -> Vec<PathSeg> {
5719 let (start, sweep) = (start.radians(), sweep.radians());
5720 if !radius.is_finite() || radius <= 0.0 || !sweep.is_finite() || sweep == 0.0 {
5721 return Vec::new();
5722 }
5723 let at = |a: f64| Point::new(center.x + radius * a.cos(), center.y + radius * a.sin());
5724 let steps = (sweep.abs() / std::f64::consts::FRAC_PI_2).ceil() as usize;
5725 let delta = sweep / steps as f64;
5726 // The exact control-handle length for a circular arc of this sweep. Negative for a negative
5727 // sweep, which is what turns the handles around for a counter-clockwise arc.
5728 let k = 4.0 / 3.0 * (delta / 4.0).tan() * radius;
5729 (0..steps)
5730 .map(|i| {
5731 let a = start + delta * i as f64;
5732 let b = a + delta;
5733 let (p0, p1) = (at(a), at(b));
5734 PathSeg::Cubic(
5735 Point::new(p0.x - k * a.sin(), p0.y + k * a.cos()),
5736 Point::new(p1.x + k * b.sin(), p1.y - k * b.cos()),
5737 p1,
5738 )
5739 })
5740 .collect()
5741}
5742
5743/// The closed contour of a rectangle rounded corner by corner, clockwise from the top left, with
5744/// the radii [fitted](CornerRadii::fitted) first. A square corner is a sharp point, not a
5745/// zero-length curve.
5746#[must_use]
5747pub fn rounded_rect_segs(rect: Rect, radii: CornerRadii) -> Vec<PathSeg> {
5748 let r = radii.fitted(rect.size);
5749 let (x0, y0) = (rect.origin.x, rect.origin.y);
5750 let (x1, y1) = (x0 + rect.size.width, y0 + rect.size.height);
5751 // Each corner: the point where its curve starts, then the quarter turn round its center.
5752 let corners = [
5753 (
5754 Point::new(x0 + r.top_left, y0 + r.top_left),
5755 r.top_left,
5756 Angle::HALF,
5757 ),
5758 (
5759 Point::new(x1 - r.top_right, y0 + r.top_right),
5760 r.top_right,
5761 Angle::deg(270.0),
5762 ),
5763 (
5764 Point::new(x1 - r.bottom_right, y1 - r.bottom_right),
5765 r.bottom_right,
5766 Angle::ZERO,
5767 ),
5768 (
5769 Point::new(x0 + r.bottom_left, y1 - r.bottom_left),
5770 r.bottom_left,
5771 Angle::QUARTER,
5772 ),
5773 ];
5774 let mut segs = Vec::with_capacity(14);
5775 for (i, (center, radius, start)) in corners.into_iter().enumerate() {
5776 let first = arc_point(center, radius, start);
5777 segs.push(if i == 0 {
5778 PathSeg::Move(first)
5779 } else {
5780 PathSeg::Line(first)
5781 });
5782 segs.extend(arc_cubics(center, radius, start, Angle::QUARTER));
5783 }
5784 segs.push(PathSeg::Close);
5785 segs
5786}
5787
5788/// How a stroked line ends (docs/canvas.md). Names match PDF's `J`, SVG's `stroke-linecap`, and
5789/// every native 2-D API.
5790#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
5791pub enum LineCap {
5792 #[default]
5793 Butt,
5794 Round,
5795 Square,
5796}
5797
5798/// How two stroked segments meet (docs/canvas.md). Matches PDF's `j` and SVG's
5799/// `stroke-linejoin`.
5800#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
5801pub enum LineJoin {
5802 #[default]
5803 Miter,
5804 Round,
5805 Bevel,
5806}
5807
5808/// Everything about a stroke except its paint.
5809///
5810/// [`StrokeStyle::width`] and `From<f64>` keep the common "just a width" case a single
5811/// argument, so plain `stroke(shape, color, 2.0)` call sites read the same as they always did.
5812#[derive(Clone, Debug, PartialEq)]
5813pub struct StrokeStyle {
5814 pub width: f64,
5815 pub cap: LineCap,
5816 pub join: LineJoin,
5817 /// Ignored unless `join` is [`LineJoin::Miter`]. The 2-D convention: past this ratio of miter
5818 /// length to line width the join falls back to a bevel.
5819 pub miter_limit: f64,
5820 /// On/off run lengths, repeating. Empty means solid.
5821 pub dash: Vec<f64>,
5822 /// How far into the dash pattern the line starts.
5823 pub dash_phase: f64,
5824}
5825
5826impl Default for StrokeStyle {
5827 fn default() -> Self {
5828 // 10.0 is the miter limit PDF, PostScript, SVG and Cairo all default to.
5829 StrokeStyle {
5830 width: 1.0,
5831 cap: LineCap::Butt,
5832 join: LineJoin::Miter,
5833 miter_limit: 10.0,
5834 dash: Vec::new(),
5835 dash_phase: 0.0,
5836 }
5837 }
5838}
5839
5840impl StrokeStyle {
5841 /// A solid stroke of `width`, everything else default.
5842 #[must_use]
5843 pub fn width(width: f64) -> Self {
5844 StrokeStyle {
5845 width,
5846 ..Default::default()
5847 }
5848 }
5849 /// A dashed stroke: `dash` is on/off run lengths, repeating.
5850 #[must_use]
5851 pub fn dashed(width: f64, dash: Vec<f64>) -> Self {
5852 StrokeStyle {
5853 width,
5854 dash,
5855 ..Default::default()
5856 }
5857 }
5858 /// Rounded ends and joins, the shape a data line usually wants.
5859 #[must_use]
5860 pub fn round(width: f64) -> Self {
5861 StrokeStyle {
5862 width,
5863 cap: LineCap::Round,
5864 join: LineJoin::Round,
5865 ..Default::default()
5866 }
5867 }
5868 /// Is this the plain width-only stroke every pre-existing call site asks for? Backends use
5869 /// it to skip setting dash/cap/join state they would only have to set back.
5870 #[must_use]
5871 #[expect(
5872 clippy::float_cmp,
5873 reason = "10.0 is the stored default miter limit, compared as a sentinel"
5874 )]
5875 pub fn is_plain(&self) -> bool {
5876 self.cap == LineCap::Butt
5877 && self.join == LineJoin::Miter
5878 && self.dash.is_empty()
5879 && self.miter_limit == 10.0
5880 }
5881}
5882
5883impl From<f64> for StrokeStyle {
5884 fn from(width: f64) -> Self {
5885 StrokeStyle::width(width)
5886 }
5887}
5888
5889fn points_bounds(pts: &[Point]) -> Rect {
5890 let (mut x0, mut y0, mut x1, mut y1) = (f64::MAX, f64::MAX, f64::MIN, f64::MIN);
5891 for p in pts {
5892 x0 = x0.min(p.x);
5893 y0 = y0.min(p.y);
5894 x1 = x1.max(p.x);
5895 y1 = y1.max(p.y);
5896 }
5897 if pts.is_empty() {
5898 return Rect::ZERO;
5899 }
5900 Rect::new(x0, y0, x1 - x0, y1 - y0)
5901}
5902
5903/// A point in the unit space of a shape's bounding box: (0,0) = top-leading, (1,1) =
5904/// bottom-trailing. Gradient geometry is expressed in unit points so one paint value works for
5905/// any shape size (docs/shapes.md §3.2).
5906#[derive(Clone, Copy, Debug, PartialEq)]
5907pub struct UnitPoint {
5908 pub x: f64,
5909 pub y: f64,
5910}
5911
5912impl UnitPoint {
5913 #[must_use]
5914 pub const fn new(x: f64, y: f64) -> Self {
5915 UnitPoint { x, y }
5916 }
5917 pub const TOP: UnitPoint = UnitPoint::new(0.5, 0.0);
5918 pub const BOTTOM: UnitPoint = UnitPoint::new(0.5, 1.0);
5919 pub const LEADING: UnitPoint = UnitPoint::new(0.0, 0.5);
5920 pub const TRAILING: UnitPoint = UnitPoint::new(1.0, 0.5);
5921 pub const TOP_LEADING: UnitPoint = UnitPoint::new(0.0, 0.0);
5922 pub const TOP_TRAILING: UnitPoint = UnitPoint::new(1.0, 0.0);
5923 pub const BOTTOM_LEADING: UnitPoint = UnitPoint::new(0.0, 1.0);
5924 pub const BOTTOM_TRAILING: UnitPoint = UnitPoint::new(1.0, 1.0);
5925 pub const CENTER: UnitPoint = UnitPoint::new(0.5, 0.5);
5926
5927 /// Resolve to an absolute point within `rect`.
5928 pub fn resolve(&self, rect: Rect) -> Point {
5929 Point::new(
5930 rect.origin.x + self.x * rect.size.width,
5931 rect.origin.y + self.y * rect.size.height,
5932 )
5933 }
5934}
5935
5936/// A linear gradient (docs/shapes.md §3.2 / §7): color stops along the line from `start` to
5937/// `end`, both in the unit space of the filled shape's bounding box. Stops are
5938/// `(offset 0..=1, ink)`, ascending; a stop takes any [`Ink`], so a gradient can follow the
5939/// appearance like a solid fill.
5940#[derive(Clone, Debug, PartialEq)]
5941pub struct LinearGradient {
5942 pub start: UnitPoint,
5943 pub end: UnitPoint,
5944 pub stops: Vec<(f64, Ink)>,
5945}
5946
5947/// Collect `(offset, color)` stops into the ink stops a gradient keeps.
5948fn ink_stops<C: Into<Ink>>(stops: impl IntoIterator<Item = (f64, C)>) -> Vec<(f64, Ink)> {
5949 stops.into_iter().map(|(at, c)| (at, c.into())).collect()
5950}
5951
5952/// Every stop resolved against `palette`, as fixed inks.
5953fn resolve_stops(stops: &[(f64, Ink)], palette: &Palette) -> Vec<(f64, Ink)> {
5954 stops
5955 .iter()
5956 .map(|(at, ink)| (*at, Ink::Fixed(ink.resolve(palette))))
5957 .collect()
5958}
5959
5960impl LinearGradient {
5961 #[must_use]
5962 pub fn new<C: Into<Ink>>(
5963 start: UnitPoint,
5964 end: UnitPoint,
5965 stops: impl IntoIterator<Item = (f64, C)>,
5966 ) -> Self {
5967 LinearGradient {
5968 start,
5969 end,
5970 stops: ink_stops(stops),
5971 }
5972 }
5973 /// Top-to-bottom between two colors: the everyday sky/backdrop case.
5974 #[must_use]
5975 pub fn vertical(top: impl Into<Ink>, bottom: impl Into<Ink>) -> Self {
5976 LinearGradient::new(
5977 UnitPoint::TOP,
5978 UnitPoint::BOTTOM,
5979 [(0.0, top.into()), (1.0, bottom.into())],
5980 )
5981 }
5982 /// Leading-to-trailing between two colors.
5983 #[must_use]
5984 pub fn horizontal(leading: impl Into<Ink>, trailing: impl Into<Ink>) -> Self {
5985 LinearGradient::new(
5986 UnitPoint::LEADING,
5987 UnitPoint::TRAILING,
5988 [(0.0, leading.into()), (1.0, trailing.into())],
5989 )
5990 }
5991}
5992
5993/// A radial gradient (docs/shapes.md §3.2 / §7): color stops from `center` outward. Both the
5994/// center and the radius live in the unit space of the filled shape's bounding box, so the
5995/// gradient stretches into an ellipse when the bounds aren't square (the XAML relative-brush
5996/// behavior; the other backends reproduce it with a local matrix on a circular gradient). A
5997/// `radius` of `0.5` from the default center touches the edge midpoints of the bounds.
5998#[derive(Clone, Debug, PartialEq)]
5999pub struct RadialGradient {
6000 pub center: UnitPoint,
6001 pub radius: f64,
6002 pub stops: Vec<(f64, Ink)>,
6003}
6004
6005impl RadialGradient {
6006 #[must_use]
6007 pub fn new<C: Into<Ink>>(
6008 center: UnitPoint,
6009 radius: f64,
6010 stops: impl IntoIterator<Item = (f64, C)>,
6011 ) -> Self {
6012 RadialGradient {
6013 center,
6014 radius,
6015 stops: ink_stops(stops),
6016 }
6017 }
6018 /// Centered, edge-touching (radius 0.5) between two colors: the everyday glow case.
6019 #[must_use]
6020 pub fn centered(inner: impl Into<Ink>, outer: impl Into<Ink>) -> Self {
6021 RadialGradient::new(
6022 UnitPoint::CENTER,
6023 0.5,
6024 [(0.0, inner.into()), (1.0, outer.into())],
6025 )
6026 }
6027}
6028
6029/// A conic (sweep) gradient: color stops around `center`, the way a color wheel or a gauge's
6030/// ring is painted. The center is in the unit space of the filled shape's bounding box; the
6031/// angle is in canvas space, `0` = the +x axis and positive sweeping clockwise, the
6032/// convention [`Shape::Arc`] uses. Stops are `(offset 0..=1, ink)`, ascending, where the
6033/// offset is the fraction of a full turn from `start`.
6034///
6035/// The colors meet at `start`: for a seamless wheel make the first and last stops the same
6036/// color. Native on Core Graphics (where the OS has it), Android, Qt, `OH_Drawing` and the HTML
6037/// canvas; drawn as a fan of thin wedges on the backends with no such gradient, which reads the
6038/// same at any size a UI draws.
6039#[derive(Clone, Debug, PartialEq)]
6040pub struct ConicGradient {
6041 pub center: UnitPoint,
6042 pub start: Angle,
6043 pub stops: Vec<(f64, Ink)>,
6044}
6045
6046impl ConicGradient {
6047 #[must_use]
6048 pub fn new<C: Into<Ink>>(
6049 center: UnitPoint,
6050 start: Angle,
6051 stops: impl IntoIterator<Item = (f64, C)>,
6052 ) -> Self {
6053 ConicGradient {
6054 center,
6055 start,
6056 stops: ink_stops(stops),
6057 }
6058 }
6059 /// Around the middle of the shape, starting at `start`.
6060 #[must_use]
6061 pub fn centered<C: Into<Ink>>(start: Angle, stops: impl IntoIterator<Item = (f64, C)>) -> Self {
6062 ConicGradient::new(UnitPoint::CENTER, start, stops)
6063 }
6064 /// The color at `angle` (canvas space, any value) in the current appearance: what a
6065 /// backend that draws the gradient as wedges fills each wedge with. Colors interpolate
6066 /// linearly between stops, channel by channel, and hold flat before the first stop and
6067 /// after the last.
6068 #[must_use]
6069 pub fn color_at(&self, angle: Angle) -> Color {
6070 let t = ((angle - self.start).degrees() / 360.0).rem_euclid(1.0);
6071 let Some(first) = self.stops.first() else {
6072 return Color::CLEAR;
6073 };
6074 if t <= first.0 {
6075 return first.1.resolved();
6076 }
6077 for pair in self.stops.windows(2) {
6078 let ((a_at, a), (b_at, b)) = (pair[0], pair[1]);
6079 let (a, b) = (a.resolved(), b.resolved());
6080 if t <= b_at {
6081 let k = if b_at > a_at {
6082 (t - a_at) / (b_at - a_at)
6083 } else {
6084 1.0
6085 };
6086 return Color::rgba(
6087 a.r + (b.r - a.r) * k,
6088 a.g + (b.g - a.g) * k,
6089 a.b + (b.b - a.b) * k,
6090 a.a + (b.a - a.a) * k,
6091 );
6092 }
6093 }
6094 self.stops.last().map_or(Color::CLEAR, |s| s.1.resolved())
6095 }
6096}
6097
6098/// A drop shadow: the silhouette of what is drawn, blurred, tinted `color` and moved by
6099/// (`dx`, `dy`) points (docs/canvas.md "Shadows", docs/surfaces.md).
6100///
6101/// `blur` is the CSS `box-shadow` blur radius: the width of the soft edge, twice the standard
6102/// deviation of the Gaussian that makes it. `0` is a hard-edged copy. The offset and the blur
6103/// are in points and are not scaled or rotated by a canvas's current transform, the rule Core
6104/// Graphics and the HTML canvas share.
6105///
6106/// On a canvas ([`DrawOp::Shadow`]) every fill, stroke, text and image drawn while it is set
6107/// casts its own. On a surface ([`props::ContainerProps::shadow`]) it is the shadow of the
6108/// surface's rounded rectangle, drawn outside its frame without taking any room in layout.
6109#[derive(Clone, Copy, Debug, PartialEq)]
6110pub struct Shadow {
6111 pub color: Ink,
6112 pub blur: f64,
6113 pub dx: f64,
6114 pub dy: f64,
6115}
6116
6117impl Shadow {
6118 /// A shadow directly under the shape: `color` feathered over `blur` points.
6119 #[must_use]
6120 pub fn new(color: impl Into<Ink>, blur: f64) -> Self {
6121 Shadow {
6122 color: color.into(),
6123 blur,
6124 dx: 0.0,
6125 dy: 0.0,
6126 }
6127 }
6128 /// Move the shadow by (`dx`, `dy`) points; positive `dy` is down.
6129 #[must_use]
6130 pub const fn offset(mut self, dx: f64, dy: f64) -> Self {
6131 self.dx = dx;
6132 self.dy = dy;
6133 self
6134 }
6135}
6136
6137/// How what a canvas draws next combines with what it has drawn so far ([`DrawOp::Blend`],
6138/// docs/canvas.md "Blend modes").
6139///
6140/// The backdrop is the canvas's own drawing, never the views behind it: a canvas is its own
6141/// compositing group. Where nothing has been drawn yet the modes other than `Erase` leave the
6142/// source as it is.
6143///
6144/// The set is the one every 2-D context under Day has: the separable modes below are W3C
6145/// compositing's, and `Add` and `Erase` are Porter-Duff's "plus" and "destination-out".
6146#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
6147pub enum BlendMode {
6148 /// Source over: the new drawing covers the old by its alpha.
6149 #[default]
6150 Normal,
6151 /// Multiplies the colors: always darker, white changes nothing. Ink on paper.
6152 Multiply,
6153 /// The inverse of multiply: always lighter, black changes nothing. Light on a screen.
6154 Screen,
6155 /// Multiplies dark backdrops and screens light ones: contrast.
6156 Overlay,
6157 /// The darker of the two, per channel.
6158 Darken,
6159 /// The lighter of the two, per channel.
6160 Lighten,
6161 /// Adds the colors, clamped: overlapping light sources.
6162 Add,
6163 /// Removes what has been drawn, by the new drawing's alpha, leaving the canvas transparent
6164 /// there so whatever is behind the canvas shows through: a hole punched in a ticket. The
6165 /// new drawing's color is ignored.
6166 Erase,
6167}
6168
6169impl BlendMode {
6170 /// Every mode, in wire order.
6171 pub const ALL: [BlendMode; 8] = [
6172 BlendMode::Normal,
6173 BlendMode::Multiply,
6174 BlendMode::Screen,
6175 BlendMode::Overlay,
6176 BlendMode::Darken,
6177 BlendMode::Lighten,
6178 BlendMode::Add,
6179 BlendMode::Erase,
6180 ];
6181
6182 /// The mode as its wire number (slot `a` of [`OpCode::SetBlend`]): the position in
6183 /// [`BlendMode::ALL`].
6184 #[must_use]
6185 pub const fn wire(self) -> i32 {
6186 self as i32
6187 }
6188}
6189
6190/// A line around a surface's edge ([`props::ContainerProps::border`]): `width` points of
6191/// `color`, drawn inside the frame, following its rounded corners, and over the surface's
6192/// content: a child that reaches the edge never covers the border (docs/surfaces.md).
6193#[derive(Clone, Copy, Debug, PartialEq)]
6194pub struct Border {
6195 pub color: Ink,
6196 pub width: f64,
6197}
6198
6199impl Border {
6200 #[must_use]
6201 pub fn new(color: impl Into<Ink>, width: f64) -> Self {
6202 Border {
6203 color: color.into(),
6204 width,
6205 }
6206 }
6207}
6208
6209/// Which corners of a surface its corner radius rounds ([`props::ContainerProps::corners`]).
6210/// The others stay square: a sheet rounded on top, a tab, the first and last rows of a group.
6211///
6212/// Physical corners, like [`CornerRadii`]: `TOP_LEFT` is the top-left in both layout
6213/// directions. Combine with `|`.
6214#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
6215pub struct Corners(u8);
6216
6217impl Corners {
6218 pub const NONE: Corners = Corners(0);
6219 pub const TOP_LEFT: Corners = Corners(1);
6220 pub const TOP_RIGHT: Corners = Corners(2);
6221 pub const BOTTOM_RIGHT: Corners = Corners(4);
6222 pub const BOTTOM_LEFT: Corners = Corners(8);
6223 pub const TOP: Corners = Corners(1 | 2);
6224 pub const BOTTOM: Corners = Corners(4 | 8);
6225 pub const LEFT: Corners = Corners(1 | 8);
6226 pub const RIGHT: Corners = Corners(2 | 4);
6227 pub const ALL: Corners = Corners(15);
6228
6229 /// Whether every corner in `other` is in this set.
6230 #[must_use]
6231 pub const fn contains(self, other: Corners) -> bool {
6232 self.0 & other.0 == other.0
6233 }
6234 /// The set as four bits: 1 top-left, 2 top-right, 4 bottom-right, 8 bottom-left. What a
6235 /// backend hands a decoder in another language.
6236 #[must_use]
6237 pub const fn bits(self) -> u8 {
6238 self.0
6239 }
6240 /// `radius` on the corners in this set and `0` on the rest, as the per-corner radii a
6241 /// path-drawing backend wants.
6242 #[must_use]
6243 pub fn radii(self, radius: f64) -> CornerRadii {
6244 let on = |c: Corners| if self.contains(c) { radius } else { 0.0 };
6245 CornerRadii {
6246 top_left: on(Corners::TOP_LEFT),
6247 top_right: on(Corners::TOP_RIGHT),
6248 bottom_right: on(Corners::BOTTOM_RIGHT),
6249 bottom_left: on(Corners::BOTTOM_LEFT),
6250 }
6251 }
6252}
6253
6254impl Default for Corners {
6255 /// Every corner: what a plain `corner_radius` rounds.
6256 fn default() -> Self {
6257 Corners::ALL
6258 }
6259}
6260
6261impl std::ops::BitOr for Corners {
6262 type Output = Corners;
6263 fn bitor(self, rhs: Corners) -> Corners {
6264 Corners(self.0 | rhs.0)
6265 }
6266}
6267
6268/// The payload of [`DrawOp::Stamp`]: one shape drawn at every position in `at`.
6269///
6270/// A scatter plot is the case this exists for. Drawn as individual ops, fifty thousand points are
6271/// fifty thousand `DrawOp`s, rebuilt, compared and cloned on every frame that re-records, before
6272/// a backend draws anything. As one `Stamp` they are one op and a flat array of coordinates, and
6273/// a backend can put every copy into one path and hand the rasterizer a single fill.
6274///
6275/// Every copy shares the shape, the size and the paint. Varying any of those means more than one
6276/// stamp: group by what varies, which for a chart is usually the series color.
6277#[derive(Clone, Debug, PartialEq)]
6278pub struct Stamp {
6279 /// The template, authored around the origin: each copy is this shape translated by one point.
6280 /// A 6-point dot is `Shape::Ellipse(Rect::new(-3.0, -3.0, 6.0, 6.0))`.
6281 pub shape: Shape,
6282 /// Where the copies go. Order is the drawing order, so later points paint over earlier ones.
6283 pub at: Vec<Point>,
6284 pub paint: Paint,
6285 /// `None` fills each copy; `Some` strokes it with this style.
6286 pub stroke: Option<StrokeStyle>,
6287}
6288
6289/// What fills an area: a solid [`Ink`], or a linear, radial or conic gradient (docs/color.md).
6290/// One vocabulary for every fill: a shape's `.fill(..)`, a surface's `.fill(..)`,
6291/// `.background(..)` and a canvas's `d.fill(..)` all take `impl Into<Paint>`, so a
6292/// [`Color`], a [`SystemColor`], an [`Ink`] or a gradient goes into any of them.
6293#[derive(Clone, Debug, PartialEq)]
6294pub enum Paint {
6295 Solid(Ink),
6296 Linear(LinearGradient),
6297 Radial(RadialGradient),
6298 Conic(ConicGradient),
6299}
6300
6301impl Paint {
6302 /// The same paint with every ink resolved against `palette`: what a canvas records, so the
6303 /// display list a backend draws holds fixed colors only.
6304 #[must_use]
6305 pub fn resolve(&self, palette: &Palette) -> Paint {
6306 match self {
6307 Paint::Solid(ink) => Paint::Solid(Ink::Fixed(ink.resolve(palette))),
6308 Paint::Linear(g) => Paint::Linear(LinearGradient {
6309 stops: resolve_stops(&g.stops, palette),
6310 ..g.clone()
6311 }),
6312 Paint::Radial(g) => Paint::Radial(RadialGradient {
6313 stops: resolve_stops(&g.stops, palette),
6314 ..g.clone()
6315 }),
6316 Paint::Conic(g) => Paint::Conic(ConicGradient {
6317 stops: resolve_stops(&g.stops, palette),
6318 ..g.clone()
6319 }),
6320 }
6321 }
6322
6323 /// Whether any ink in the paint depends on the appearance or the platform.
6324 #[must_use]
6325 pub fn is_dynamic(&self) -> bool {
6326 let stops = |s: &[(f64, Ink)]| s.iter().any(|(_, ink)| ink.is_dynamic());
6327 match self {
6328 Paint::Solid(ink) => ink.is_dynamic(),
6329 Paint::Linear(g) => stops(&g.stops),
6330 Paint::Radial(g) => stops(&g.stops),
6331 Paint::Conic(g) => stops(&g.stops),
6332 }
6333 }
6334}
6335
6336impl From<Ink> for Paint {
6337 fn from(ink: Ink) -> Self {
6338 Paint::Solid(ink)
6339 }
6340}
6341
6342impl From<SystemColor> for Paint {
6343 fn from(role: SystemColor) -> Self {
6344 Paint::Solid(role.into())
6345 }
6346}
6347
6348impl From<ConicGradient> for Paint {
6349 fn from(g: ConicGradient) -> Self {
6350 Paint::Conic(g)
6351 }
6352}
6353
6354impl From<Color> for Paint {
6355 fn from(c: Color) -> Self {
6356 Paint::Solid(c.into())
6357 }
6358}
6359
6360impl From<LinearGradient> for Paint {
6361 fn from(g: LinearGradient) -> Self {
6362 Paint::Linear(g)
6363 }
6364}
6365
6366impl From<RadialGradient> for Paint {
6367 fn from(g: RadialGradient) -> Self {
6368 Paint::Radial(g)
6369 }
6370}
6371
6372/// Where `at` sits vertically. `Top`, `Middle` and `Bottom` are edges of the line box (ascent +
6373/// descent at the font's size, the box [`Toolkit::measure_text`] reports); `Baseline` is the
6374/// typographic baseline itself.
6375#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
6376pub enum TextVAlign {
6377 /// `at` is the top of the line box.
6378 #[default]
6379 Top,
6380 /// `at` is the vertical middle of the line box.
6381 Middle,
6382 /// `at` is the baseline itself: what every native 2-D text call takes, and what a run of labels
6383 /// sharing a line should align on rather than their individual boxes.
6384 Baseline,
6385 /// `at` is the bottom of the line box.
6386 Bottom,
6387}
6388
6389/// How canvas text hangs on its `at` point: one placement per axis (docs/canvas.md "Text").
6390///
6391/// Two axes rather than a list of named positions, because that is the shape of the problem and
6392/// of every native API underneath: `NSAttributedString` drawing, Pango extents,
6393/// `QFontMetricsF`, `Paint.Align`, `Canvas2D`'s `textAlign`/`textBaseline`. The alignment is done
6394/// by the backend, which is both cheaper and more accurate than doing it in app code: it already
6395/// has the laid-out metrics, where an app has to ask for them through
6396/// [`Toolkit::measure_text`] first.
6397///
6398/// [`TextAnchor::LEADING`] and [`TextAnchor::CENTERED`] name the two placements that used to be
6399/// this type's only variants.
6400#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
6401pub struct TextAnchor {
6402 /// The horizontal placement: the same three-way leading/center/trailing a wrapped label's
6403 /// lines take ([`props::TextAlign`]), because it is the same question with the same RTL rule.
6404 /// `Trailing` is what an axis label right-aligned against its axis wants, and the reason the
6405 /// horizontal axis is settable at all: emulating it in app code costs a
6406 /// [`Toolkit::measure_text`] call per label, where the backend already holds the width it is
6407 /// about to draw with.
6408 pub h: props::TextAlign,
6409 pub v: TextVAlign,
6410}
6411
6412impl TextAnchor {
6413 /// The top-leading corner of the line box, the default.
6414 pub const LEADING: TextAnchor = TextAnchor {
6415 h: props::TextAlign::Leading,
6416 v: TextVAlign::Top,
6417 };
6418 /// The center of the line box, both ways.
6419 pub const CENTERED: TextAnchor = TextAnchor {
6420 h: props::TextAlign::Center,
6421 v: TextVAlign::Middle,
6422 };
6423 /// The top-trailing corner of the line box.
6424 pub const TRAILING: TextAnchor = TextAnchor {
6425 h: props::TextAlign::Trailing,
6426 v: TextVAlign::Top,
6427 };
6428
6429 /// Where the text's top-leading corner goes, as an offset from `at`, given the line box this
6430 /// text measures to. The single definition of what an anchor means: every backend that draws
6431 /// in Rust calls this, and the C++/Java/JS shims repeat exactly this arithmetic.
6432 ///
6433 /// `height` is the line box (ascent + descent) and `ascent` the baseline's offset from its
6434 /// top, the two numbers [`TextMetrics`] carries.
6435 #[must_use]
6436 pub fn offset(self, width: f64, height: f64, ascent: f64) -> (f64, f64) {
6437 let dx = match self.h {
6438 props::TextAlign::Leading | props::TextAlign::Justified => 0.0,
6439 props::TextAlign::Center => -width / 2.0,
6440 props::TextAlign::Trailing => -width,
6441 };
6442 let dy = match self.v {
6443 TextVAlign::Top => 0.0,
6444 TextVAlign::Middle => -height / 2.0,
6445 TextVAlign::Baseline => -ascent,
6446 TextVAlign::Bottom => -height,
6447 };
6448 (dx, dy)
6449 }
6450
6451 /// The anchor as one number, for the numeric op stream the serializing backends share:
6452 /// `h * 4 + v`, so it still occupies the single slot the two-variant enum did.
6453 #[must_use]
6454 pub fn pack(self) -> f64 {
6455 f64::from(self.h as u8 * 4 + self.v as u8)
6456 }
6457
6458 /// Inverse of [`TextAnchor::pack`]. An unrecognized code answers the default rather than
6459 /// failing: a stream is only ever written by a matching encoder, and a drawing with text in
6460 /// the wrong corner beats one that panics inside a native draw callback.
6461 #[must_use]
6462 pub fn unpack(code: f64) -> TextAnchor {
6463 let c = code.round().clamp(0.0, 11.0) as u8;
6464 let h = match c / 4 {
6465 1 => props::TextAlign::Center,
6466 2 => props::TextAlign::Trailing,
6467 _ => props::TextAlign::Leading,
6468 };
6469 let v = match c % 4 {
6470 1 => TextVAlign::Middle,
6471 2 => TextVAlign::Baseline,
6472 3 => TextVAlign::Bottom,
6473 _ => TextVAlign::Top,
6474 };
6475 TextAnchor { h, v }
6476 }
6477}
6478
6479#[derive(Clone, Debug, PartialEq)]
6480pub enum DrawOp {
6481 Fill(Shape, Paint),
6482 /// Stroke `shape`. The paint may be a gradient, and [`StrokeStyle`] carries width, dash, cap
6483 /// and join; `Draw::stroke` builds the plain width-only case.
6484 Stroke(Shape, Paint, StrokeStyle),
6485 /// One line of text. `size` is absolute canvas points (no accessibility scale: canvas
6486 /// text is a label inside a drawing, docs/canvas.md); `font` picks the family, weight and
6487 /// slant, and its default is the platform's own UI face.
6488 Text {
6489 text: String,
6490 at: Point,
6491 size: f64,
6492 color: Color,
6493 anchor: TextAnchor,
6494 font: CanvasFont,
6495 },
6496 /// Draw one shape at many positions, the batched form of [`DrawOp::Fill`]/[`DrawOp::Stroke`]
6497 /// (docs/canvas.md "Stamping").
6498 ///
6499 /// Boxed because the payload is wider than the largest other op, and a bigger `DrawOp` would
6500 /// cost every op in every drawing, the exact thing this variant exists to stop paying.
6501 Stamp(Box<Stamp>),
6502 /// Draw an image into `rect` (docs/images.md).
6503 ///
6504 /// The source is a [`BitmapId`] and never bytes: a canvas re-records on every tracked read,
6505 /// so carrying a buffer here would hand the backend a megabyte to compare, and re-decode, on
6506 /// every frame. The app decodes once with `day::decode_image` and draws the handle.
6507 ///
6508 /// `opacity` multiplies the image's own alpha. A backend that cannot draw a bitmap at all
6509 /// draws nothing rather than a placeholder rectangle, the same way an unknown op is skipped.
6510 ///
6511 /// `source` is the region of the bitmap to draw, in the bitmap's own PIXELS (not points:
6512 /// [`BitmapInfo::scale`] says how many pixels make a point), `None` meaning the whole
6513 /// image. It is what lets one decoded sprite sheet serve every icon on a map: each draw
6514 /// picks its cell and scales it into `rect`. A region reaching outside the bitmap is clamped
6515 /// to it, never an error: the part inside draws where the mapping into `rect` puts it, and
6516 /// an empty intersection draws nothing. A backend without a sub-rect draw clips to `rect`
6517 /// and draws the whole image scaled so the region lands there ([`clamp_image_source`] is
6518 /// the shared arithmetic).
6519 Image {
6520 image: BitmapId,
6521 rect: Rect,
6522 opacity: f64,
6523 source: Option<Rect>,
6524 },
6525 /// Intersect the clip with `shape`; everything drawn afterwards is confined to it.
6526 ///
6527 /// Scoped by [`DrawOp::Save`]/[`DrawOp::Restore`], which is the only way to widen a clip
6528 /// again; every native 2-D context works this way, so there is no "unclip".
6529 Clip(Shape),
6530 /// Set the shadow everything drawn afterwards casts, or `None` to stop casting one
6531 /// (docs/canvas.md "Shadows"). Graphics state like the clip: [`DrawOp::Restore`] puts back
6532 /// the shadow that was set at the matching [`DrawOp::Save`].
6533 ///
6534 /// A backend whose 2-D context has no shadow draws the shapes without one; it never draws
6535 /// a hard-edged stand-in.
6536 Shadow(Option<Shadow>),
6537 /// Set how everything drawn afterwards combines with what is already on the canvas
6538 /// (docs/canvas.md "Blend modes"). Graphics state, scoped by [`DrawOp::Save`] and
6539 /// [`DrawOp::Restore`] like the clip and the shadow.
6540 Blend(BlendMode),
6541 /// Push the current transform, clip, shadow and blend mode (§11, shapes). Backends map to
6542 /// save/restore of the native 2-D context; `Concat` multiplies an affine onto the CTM (shape
6543 /// rotate/scale/offset).
6544 Save,
6545 Restore,
6546 Concat(day_geometry::Affine),
6547}
6548
6549// ---------------------------------------------------------------------------
6550// Built-in piece descriptors: full props (realize) + sparse patches (update).
6551// One binding = one attribute = one patch value: sparseness by construction (§8.1).
6552// ---------------------------------------------------------------------------
6553
6554/// A semantic (logical) text style. Each maps to the platform's native text style where the
6555/// toolkit has one: `UIFont`/`NSFont.preferredFont(forTextStyle:)` on Apple (Dynamic Type), the
6556/// `*TextBlockStyle` resources on XAML. A Day app thus matches the OS's own typography and
6557/// inherits its accessibility text scaling with no extra work. Backends without semantic styles
6558/// (GTK/Qt/Android) approximate with sizes that still track the platform's text-scale /
6559/// font-scale accessibility setting.
6560///
6561/// The set mirrors SwiftUI `Font.TextStyle` (largest → smallest).
6562#[derive(Clone, Copy, Debug, PartialEq, Default)]
6563pub enum Font {
6564 LargeTitle,
6565 Title,
6566 Title2,
6567 Title3,
6568 Headline,
6569 Subheadline,
6570 #[default]
6571 Body,
6572 Callout,
6573 Footnote,
6574 Caption,
6575 Caption2,
6576 /// A custom point size. Backends scale it by the platform's accessibility text-scale (iOS via
6577 /// `UIFontMetrics`, Android via `sp`, GTK via text-scaling-factor) so it stays legible.
6578 System(f64),
6579 /// A bundled custom font by **family name**, at a point size (`Font::Custom("Pacifico",
6580 /// 24.0)`). The family must ship in the project's `fonts/` directory; `day build` stages the
6581 /// file into each platform's native font store and the backend registers it at startup
6582 /// (§18.4). The name is the family name baked into the font file (what Font Book /
6583 /// fontconfig report), not the file name. The size scales with the platform accessibility
6584 /// text-scale exactly like [`Font::System`]; weight/italic apply only where the family ships
6585 /// (or the platform synthesizes) such a face. An unknown family falls back to the system font
6586 /// of the same size, with a warning in the log.
6587 Custom(&'static str, f64),
6588}
6589
6590impl Font {
6591 /// A bundled custom font by **typed family**, at a point size, the checked form of
6592 /// [`Font::Custom`]. Pass a generated `res::fonts::…` constant
6593 /// (`Font::custom(res::fonts::pacifico, 24.0)`), which exists only if the family ships in the
6594 /// project's `fonts/` directory, so the font is guaranteed bundled. For a family name known
6595 /// another way, the untyped [`Font::Custom`] variant is the escape hatch.
6596 #[must_use]
6597 pub const fn custom(family: FontFamily, size: f64) -> Font {
6598 Font::Custom(family.as_str(), size)
6599 }
6600}
6601
6602/// Font weight, matching `UIFont.Weight` / SwiftUI `Font.Weight` (lightest → heaviest).
6603/// Ordered by heaviness, so backends can e.g. map `>= Semibold` to a synthesized bold face.
6604#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
6605pub enum FontWeight {
6606 UltraLight,
6607 Thin,
6608 Light,
6609 Regular,
6610 Medium,
6611 Semibold,
6612 Bold,
6613 Heavy,
6614 Black,
6615}
6616
6617impl FontWeight {
6618 /// Every rung, lightest first.
6619 pub const ALL: [FontWeight; 9] = [
6620 FontWeight::UltraLight,
6621 FontWeight::Thin,
6622 FontWeight::Light,
6623 FontWeight::Regular,
6624 FontWeight::Medium,
6625 FontWeight::Semibold,
6626 FontWeight::Bold,
6627 FontWeight::Heavy,
6628 FontWeight::Black,
6629 ];
6630
6631 /// The CSS / OpenType numeric weight (100 … 900), the one number every platform font API
6632 /// also speaks (`Typeface.create(base, weight, italic)`, `QFont::Weight`,
6633 /// `DWRITE_FONT_WEIGHT`, `OH_Drawing_FontWeight`), and what the canvas wire carries.
6634 #[must_use]
6635 pub const fn css(self) -> u16 {
6636 match self {
6637 FontWeight::UltraLight => 100,
6638 FontWeight::Thin => 200,
6639 FontWeight::Light => 300,
6640 FontWeight::Regular => 400,
6641 FontWeight::Medium => 500,
6642 FontWeight::Semibold => 600,
6643 FontWeight::Bold => 700,
6644 FontWeight::Heavy => 800,
6645 FontWeight::Black => 900,
6646 }
6647 }
6648
6649 /// The nearest rung to a CSS weight (ties round heavier, like CSS font matching); anything
6650 /// outside 100 … 900 clamps.
6651 #[must_use]
6652 pub fn from_css(n: u16) -> FontWeight {
6653 let n = n.clamp(100, 900);
6654 let idx = (usize::from(n) + 50) / 100; // 100 → 1 … 900 → 9
6655 FontWeight::ALL[idx.clamp(1, 9) - 1]
6656 }
6657
6658 /// The English face name for a rung ("Semibold"), for platforms whose enumeration names
6659 /// no face (see [`FontFace::synthesized_name`]).
6660 #[must_use]
6661 pub const fn name(self) -> &'static str {
6662 match self {
6663 FontWeight::UltraLight => "Ultra Light",
6664 FontWeight::Thin => "Thin",
6665 FontWeight::Light => "Light",
6666 FontWeight::Regular => "Regular",
6667 FontWeight::Medium => "Medium",
6668 FontWeight::Semibold => "Semibold",
6669 FontWeight::Bold => "Bold",
6670 FontWeight::Heavy => "Heavy",
6671 FontWeight::Black => "Black",
6672 }
6673 }
6674}
6675
6676/// One face a font family ships (docs/fonts.md): its display name ("Bold Italic"), weight and
6677/// slant. What [`FontFamilyInfo::faces`] lists and what a font menu's style picker offers.
6678#[derive(Clone, Debug, PartialEq, Eq)]
6679pub struct FontFace {
6680 pub name: String,
6681 pub weight: FontWeight,
6682 pub italic: bool,
6683}
6684
6685impl FontFace {
6686 /// A display name from weight + slant ("Semibold Italic") for platforms whose enumeration
6687 /// API names no face (Android's `fonts.xml`, the CSS generic families).
6688 #[must_use]
6689 pub fn synthesized_name(weight: FontWeight, italic: bool) -> String {
6690 if italic {
6691 format!("{} Italic", weight.name())
6692 } else {
6693 weight.name().to_string()
6694 }
6695 }
6696}
6697
6698/// A platform (or bundled) font family and the faces it can draw canvas text in
6699/// ([`Toolkit::font_families`], docs/fonts.md).
6700#[derive(Clone, Debug, PartialEq, Eq)]
6701pub struct FontFamilyInfo {
6702 pub family: String,
6703 pub faces: Vec<FontFace>,
6704}
6705
6706impl FontFamilyInfo {
6707 /// Whether any face is [`FontWeight::Bold`] or heavier.
6708 #[must_use]
6709 pub fn has_bold(&self) -> bool {
6710 self.faces.iter().any(|f| f.weight >= FontWeight::Bold)
6711 }
6712 /// Whether any face is italic.
6713 #[must_use]
6714 pub fn has_italic(&self) -> bool {
6715 self.faces.iter().any(|f| f.italic)
6716 }
6717 /// The nearest face: an exact slant match preferred, then the smallest weight distance
6718 /// (ties go heavier, like CSS font matching). `None` only when the family lists no faces.
6719 #[must_use]
6720 pub fn face_for(&self, weight: FontWeight, italic: bool) -> Option<&FontFace> {
6721 let want = i32::from(weight.css());
6722 self.faces.iter().min_by_key(|f| {
6723 let slant = i32::from(f.italic != italic);
6724 let dist = (i32::from(f.weight.css()) - want).abs();
6725 // Heavier wins a tie: subtracting the bool sorts the heavier face first.
6726 (slant, dist, i32::from(i32::from(f.weight.css()) < want))
6727 })
6728 }
6729}
6730
6731/// Single-line text measurement in canvas points ([`Toolkit::measure_text`], docs/fonts.md).
6732///
6733/// Two boxes, and the difference between them matters. `width`/`height` is the **line box**: the
6734/// typographic slot the text occupies, the same for every string in a face at a size, and what
6735/// [`TextAnchor`] positions. [`ink`](TextMetrics::ink) is the **ink box**: where the glyphs
6736/// put marks. A line of digits leaves the descender space of its line box empty, so the
6737/// two disagree, and which one is wanted depends on the question: laying text out in a column
6738/// wants the line box, and centering it on a rule or keeping it clear of a mark wants the ink.
6739#[derive(Clone, Copy, Debug, PartialEq)]
6740pub struct TextMetrics {
6741 /// The advance width of the whole string.
6742 pub width: f64,
6743 /// The line box: ascent + descent at this size (plus the line gap where the engine reports
6744 /// one), which is the box [`TextAnchor`] positions.
6745 pub height: f64,
6746 /// The baseline's offset from the top of the line box.
6747 pub ascent: f64,
6748 /// The face's cap height at this size: baseline to the top of a capital.
6749 ///
6750 /// A property of the font, not of this string, reported here because it is what optical
6751 /// centering needs and asking for it separately would be a second measurement. Text made of
6752 /// capitals and digits looks centered on a rule when its cap box straddles it, not its line
6753 /// box: the line box reserves descender room that digits never use, so centering by it sits
6754 /// every label a little low. The cap middle is `ascent - cap_height / 2.0` below the line
6755 /// box's top.
6756 pub cap_height: f64,
6757 /// The ink box, the tight bounds of what is drawn, with its origin relative to the line
6758 /// box's top-leading corner, so `ink.origin` is where the marks start inside the slot.
6759 ///
6760 /// Empty (zero-size) for text that draws nothing, a space included. Where a toolkit cannot
6761 /// report ink it answers the whole line box, which is a superset: an overlap test against it
6762 /// can only be too cautious, never wrong.
6763 pub ink: Rect,
6764}
6765
6766impl TextMetrics {
6767 /// The portable guess `day::measure_text` falls back to when a toolkit cannot measure:
6768 /// 0.6 × size per character, 1.2 × size tall, the baseline at 0.9 × size, caps at 0.7 × size.
6769 /// Its ink is the whole line box, the safe direction to be wrong in (see
6770 /// [`ink`](TextMetrics::ink)).
6771 #[must_use]
6772 pub fn approximate(text: &str, size: f64) -> TextMetrics {
6773 let (width, height) = (0.6 * size * text.chars().count() as f64, 1.2 * size);
6774 TextMetrics {
6775 width,
6776 height,
6777 ascent: 0.9 * size,
6778 cap_height: 0.7 * size,
6779 ink: Rect::new(0.0, 0.0, width, height),
6780 }
6781 }
6782
6783 /// Read the eight-slot form the serializing backends (qt, xaml, arkui, web) fill across their
6784 /// C ABI: advance, line height, ascent, cap height, then the ink box relative to the line
6785 /// box's top-leading corner. One definition so four shims cannot drift from each other.
6786 #[must_use]
6787 pub fn from_slots(out: &[f64; 8]) -> TextMetrics {
6788 TextMetrics {
6789 width: out[0],
6790 height: out[1],
6791 ascent: out[2],
6792 cap_height: out[3],
6793 ink: Rect::new(out[4], out[5], out[6], out[7]),
6794 }
6795 }
6796
6797 /// The line box's top-leading corner, given a baseline-relative measurement, the shape every
6798 /// backend's metrics come in. `ink_*` are relative to the drawing origin on the baseline
6799 /// (`ink_top` negative above it), the convention Skia, Core Text and Qt all report in.
6800 #[must_use]
6801 pub fn from_baseline(
6802 width: f64,
6803 ascent: f64,
6804 descent: f64,
6805 cap_height: f64,
6806 ink: Rect,
6807 ) -> TextMetrics {
6808 TextMetrics {
6809 width,
6810 height: ascent + descent,
6811 ascent,
6812 cap_height,
6813 // Baseline-relative to line-box-relative is one shift by the ascent.
6814 ink: Rect::new(
6815 ink.origin.x,
6816 ink.origin.y + ascent,
6817 ink.size.width,
6818 ink.size.height,
6819 ),
6820 }
6821 }
6822}
6823
6824/// What canvas text is drawn with beyond its size (docs/canvas.md "Text"): a family, a weight and
6825/// a slant. The default is the platform's own UI face, regular, upright, which is what every
6826/// backend drew before the field existed, so a default font encodes to nothing on the wire.
6827#[derive(Clone, Debug, PartialEq, Eq, Default)]
6828pub struct CanvasFont {
6829 /// A platform or bundled family name (as [`Toolkit::font_families`] lists it); `None` =
6830 /// the platform's default UI face.
6831 pub family: Option<String>,
6832 /// `None` = Regular.
6833 pub weight: Option<FontWeight>,
6834 pub italic: bool,
6835}
6836
6837impl CanvasFont {
6838 /// The family name to send over the wire, empty for the default.
6839 #[must_use]
6840 pub fn family_str(&self) -> &str {
6841 self.family.as_deref().unwrap_or("")
6842 }
6843 /// The CSS weight to send over the wire, 0 for the default.
6844 pub fn css_weight(&self) -> u16 {
6845 self.weight.map_or(0, FontWeight::css)
6846 }
6847}
6848
6849/// Field separator inside one family of the shim-side font list ([`parse_font_list`]).
6850pub const FONT_LIST_FIELD: char = '\u{1f}';
6851/// Family separator of the shim-side font list ([`parse_font_list`]).
6852pub const FONT_LIST_FAMILY: char = '\u{1e}';
6853
6854/// Decode the text a non-Rust font enumerator hands back (the Qt, XAML and ArkUI shims, the
6855/// Android bridge, the web shim all produce this one format): families separated by U+001E;
6856/// inside a family, U+001F-separated fields: the family name, then one (name, CSS weight,
6857/// italic `0`/`1`) triple per face. Tolerant: a malformed face or family is skipped, an empty
6858/// face name is synthesized from its weight and slant, and a family with no faces is kept
6859/// with none (the caller decides what a face-less family means).
6860pub fn parse_font_list(s: &str) -> Vec<FontFamilyInfo> {
6861 let mut out = Vec::new();
6862 for fam in s.split(FONT_LIST_FAMILY) {
6863 let mut fields = fam.split(FONT_LIST_FIELD);
6864 let Some(family) = fields.next().map(str::trim).filter(|f| !f.is_empty()) else {
6865 continue;
6866 };
6867 let rest: Vec<&str> = fields.collect();
6868 let mut faces = Vec::new();
6869 for face in rest.chunks(3) {
6870 let [name, weight, italic] = face else {
6871 continue;
6872 };
6873 let Ok(weight) = weight.trim().parse::<u16>() else {
6874 continue;
6875 };
6876 let weight = FontWeight::from_css(weight);
6877 let italic = matches!(italic.trim(), "1" | "true");
6878 let name = name.trim();
6879 let name = if name.is_empty() {
6880 FontFace::synthesized_name(weight, italic)
6881 } else {
6882 name.to_string()
6883 };
6884 if !faces
6885 .iter()
6886 .any(|f: &FontFace| f.weight == weight && f.italic == italic)
6887 {
6888 faces.push(FontFace {
6889 name,
6890 weight,
6891 italic,
6892 });
6893 }
6894 }
6895 out.push(FontFamilyInfo {
6896 family: family.to_string(),
6897 faces,
6898 });
6899 }
6900 out
6901}
6902
6903/// The full font descriptor a label carries: a semantic (or custom) [`Font`] style plus an optional
6904/// weight override, an italic flag, and the tabular-figures request. Backends resolve this to one
6905/// native font.
6906#[derive(Clone, Copy, Debug, PartialEq)]
6907pub struct FontSpec {
6908 pub style: Font,
6909 pub weight: Option<FontWeight>,
6910 pub italic: bool,
6911 /// Ask for tabular (monospaced) figures: every digit takes the same advance, so a number that
6912 /// changes stops changing width.
6913 ///
6914 /// In a proportional system font `1` is narrower than `8`, so a readout beside a slider
6915 /// wobbles as the value changes even when the digit count is fixed. Every platform ships this
6916 /// as a font feature, so Day asks for the platform's own rather than substituting a monospaced
6917 /// family: the text keeps the system face, and only the digits change metrics.
6918 ///
6919 /// Reserving space (`Decorate::reserving`) and tabular figures solve the two halves of the
6920 /// same problem (reservation stops the box resizing, tabular stops the glyphs shifting inside
6921 /// it), and a numeric readout usually wants both.
6922 ///
6923 /// This rides the existing label realize/patch path rather than adding a Toolkit method, so it
6924 /// is not a backend duty and has no duty-matrix row. Every in-tree backend honors it: AppKit
6925 /// and UIKit re-pick the system face (`monospacedDigitSystemFont`), GTK and Qt and ArkUI set
6926 /// the `tnum` OpenType feature, Android `setFontFeatureSettings`, XAML the `Typography`
6927 /// `NumeralAlignment` property, and web-dom `font-variant-numeric`. A font with no `tnum` table,
6928 /// or an SDK predating the attribute, renders the stock proportional figures.
6929 pub tabular: bool,
6930 /// Ask for the platform's monospaced face at this style's size, what `` `code` `` in a
6931 /// markdown run needs (docs/text-runs.md).
6932 ///
6933 /// A flag rather than a `Font::Monospace(pt)` variant so the run keeps its semantic style:
6934 /// code inside a `Footnote` paragraph must stay footnote-sized and keep tracking the
6935 /// reader's text-size setting, which a fixed point size would throw away.
6936 ///
6937 /// Like [`Self::tabular`], this rides the label realize/patch path and is not a backend duty:
6938 /// every toolkit has a system monospace face (`monospacedSystemFont`, Pango's `monospace`
6939 /// family, `QFontDatabase::FixedFont`, `Typeface.MONOSPACE`, CSS `monospace`).
6940 pub monospace: bool,
6941 /// Multiply the resolved size. `1.0` is the style's own size, `1.6` a heading against a body
6942 /// paragraph, `0.8` a caption inside one.
6943 ///
6944 /// Relative rather than an absolute point size, so that an editor's font-size control can
6945 /// move this while text a person reads for an hour still tracks the platform's
6946 /// accessibility text-scale. `Font::System(pt)` remains the absolute escape hatch, and it
6947 /// is where an imported document's `\fs28` or `font-size: 14px` lands (docs/texteditor.md):
6948 /// faithful to the file, and no longer responsive to the reader, which is the trade that
6949 /// form makes.
6950 ///
6951 /// Three toolkits take it directly (`GtkTextTag::scale`, Android's `RelativeSizeSpan`, CSS
6952 /// `em`); the rest multiply it into the size they already compute.
6953 pub scale: f64,
6954 /// Ask for small capitals: lowercase letters drawn as capitals at the x-height (the
6955 /// OpenType `smcp` feature). Capitals stay full size.
6956 ///
6957 /// Like [`Self::tabular`], this is a font feature that rides the label realize/patch path:
6958 /// a UIKit or AppKit font descriptor feature (`kLowerCaseType`/`kLowerCaseSmallCapsSelector`),
6959 /// Pango's `font-features` attribute, `QFont::setCapitalization(SmallCaps)`, Android's
6960 /// `setFontFeatureSettings("smcp")`, XAML's `Typography.Capitals`, ArkUI's font feature
6961 /// string, and CSS `font-variant-caps`. A face with no `smcp` table draws its ordinary
6962 /// lowercase; a toolkit never substitutes scaled-down capitals.
6963 pub small_caps: bool,
6964 /// Ask for oldstyle (lowercase, text) figures: digits with ascenders and descenders that sit
6965 /// in running text the way lowercase letters do (the OpenType `onum` feature). Combines
6966 /// with [`Self::tabular`]. A face with no `onum` table draws its ordinary lining figures.
6967 pub oldstyle_figures: bool,
6968}
6969
6970impl Default for FontSpec {
6971 fn default() -> Self {
6972 FontSpec {
6973 style: Font::Body,
6974 weight: None,
6975 italic: false,
6976 tabular: false,
6977 monospace: false,
6978 scale: 1.0,
6979 small_caps: false,
6980 oldstyle_figures: false,
6981 }
6982 }
6983}
6984
6985impl From<Font> for FontSpec {
6986 fn from(style: Font) -> Self {
6987 FontSpec {
6988 style,
6989 ..FontSpec::default()
6990 }
6991 }
6992}
6993
6994impl FontSpec {
6995 /// The plain descriptor for a style: no weight override, no italic, scale 1.0.
6996 pub fn new(style: Font) -> Self {
6997 FontSpec::from(style)
6998 }
6999 /// This descriptor at a different relative size (see [`FontSpec::scale`]).
7000 #[must_use]
7001 pub fn scaled(mut self, scale: f64) -> Self {
7002 self.scale = scale;
7003 self
7004 }
7005 /// The point size this descriptor resolves to, given the size the platform assigns its
7006 /// semantic style. The one place `scale` is applied, so every backend's font resolver
7007 /// multiplies the same way.
7008 #[must_use]
7009 pub fn resolved_points(&self, style_points: f64) -> f64 {
7010 let base = match self.style {
7011 Font::System(pt) | Font::Custom(_, pt) => pt,
7012 _ => style_points,
7013 };
7014 (base * self.scale).max(1.0)
7015 }
7016 /// The OpenType feature tags this descriptor asks for, in a fixed order: `tnum` for
7017 /// [`Self::tabular`], `smcp` for [`Self::small_caps`], `onum` for
7018 /// [`Self::oldstyle_figures`]. One list, so every toolkit that takes a feature string
7019 /// (Pango, Android, ArkUI, CSS `font-feature-settings`) spells the same set.
7020 #[must_use]
7021 pub fn feature_tags(&self) -> Vec<&'static str> {
7022 let mut tags = Vec::new();
7023 if self.tabular {
7024 tags.push("tnum");
7025 }
7026 if self.small_caps {
7027 tags.push("smcp");
7028 }
7029 if self.oldstyle_figures {
7030 tags.push("onum");
7031 }
7032 tags
7033 }
7034}
7035
7036/// One styled span of a label's text (docs/text-runs.md).
7037///
7038/// `range` is a byte range into the label's `text`. Bytes, not chars: every backend that takes a
7039/// structured attributed string wants UTF-16 or byte offsets, `str` slicing is byte-based, and a
7040/// char count would have to be converted at every boundary. Ranges must be non-overlapping and
7041/// ascending; a gap between them is unstyled text, drawn with the label's own font.
7042///
7043/// A run says only what differs. `font` is the whole descriptor rather than a delta because a
7044/// bold run inside a Body paragraph is `FontSpec { style: Body, weight: Some(Bold), .. }`. The
7045/// style has to travel with the weight or the run loses its semantic size.
7046#[derive(Clone, Debug, PartialEq)]
7047pub struct TextRun {
7048 pub range: std::ops::Range<usize>,
7049 pub font: FontSpec,
7050 pub color: Option<Ink>,
7051 /// A highlight painted behind the glyphs. Every native text editor carries this attribute
7052 /// (docs/texteditor.md), and search hits and review comments are the two things an app is
7053 /// asked for the moment it has styled text at all.
7054 pub background: Option<Ink>,
7055 /// A line under the text: its style and, optionally, a color of its own.
7056 pub underline: Option<Decoration>,
7057 /// A line through the text. Separate from `FontSpec` because it is a decoration, not a face:
7058 /// no platform expresses it by picking a different font.
7059 pub strikethrough: Option<Decoration>,
7060 /// Makes this run a link to the given target. Rendering it is [`Cap::TextRuns`]; making it
7061 /// activatable is [`Cap::TextLinks`], which is a smaller set (see the docs).
7062 pub link: Option<String>,
7063}
7064
7065impl Default for TextRun {
7066 fn default() -> Self {
7067 TextRun {
7068 range: 0..0,
7069 font: FontSpec::default(),
7070 color: None,
7071 background: None,
7072 underline: None,
7073 strikethrough: None,
7074 link: None,
7075 }
7076 }
7077}
7078
7079impl TextRun {
7080 /// A run that only changes the font, the common case for emphasis.
7081 #[must_use]
7082 pub fn font(range: std::ops::Range<usize>, font: FontSpec) -> Self {
7083 TextRun {
7084 range,
7085 font,
7086 ..TextRun::default()
7087 }
7088 }
7089
7090 /// This run's attributes without its range: what a selection's style is compared against
7091 /// and what an editor's toolbar toggles (docs/texteditor.md).
7092 #[must_use]
7093 pub fn style(&self) -> RunStyle {
7094 RunStyle {
7095 font: self.font,
7096 color: self.color.map(Ink::resolved),
7097 background: self.background.map(Ink::resolved),
7098 underline: self.underline,
7099 strikethrough: self.strikethrough,
7100 link: self.link.clone(),
7101 }
7102 }
7103
7104 /// A run of `style` over `range`.
7105 #[must_use]
7106 pub fn styled(range: std::ops::Range<usize>, style: RunStyle) -> Self {
7107 TextRun {
7108 range,
7109 font: style.font,
7110 color: style.color.map(Ink::from),
7111 background: style.background.map(Ink::from),
7112 underline: style.underline,
7113 strikethrough: style.strikethrough,
7114 link: style.link,
7115 }
7116 }
7117}
7118
7119/// Serialize a label's text + runs as markup, for the two backends whose text widgets take a
7120/// string in their own dialect rather than a structured attributed string: GTK (Pango markup)
7121/// and Qt (its HTML subset). Shared so the escaping is written and tested once: a translated
7122/// string containing `&` or `<` corrupts the whole label otherwise, and it will be a translated
7123/// string that finds the bug.
7124///
7125/// `dialect` decides the spelling: Pango wants `<span foreground="#rrggbb"
7126/// font_family="monospace">`, Qt wants `<span style="color:#rrggbb">` with `<code>`. Both accept
7127/// `<b>`, `<i>`, `<u>`, `<s>` and `<a href>`, which is why one function can serve them.
7128///
7129/// `base_points` is the size the label itself resolved to. Only a relative-size run
7130/// ([`FontSpec::scale`]) needs it, and only in the Qt dialect: Pango markup takes a percentage
7131/// directly, while Qt's CSS subset understands `pt` and `px` and ignores `%`.
7132#[must_use]
7133pub fn runs_to_markup(
7134 text: &str,
7135 runs: &[TextRun],
7136 dialect: MarkupDialect,
7137 base_points: f64,
7138) -> String {
7139 let mut out = String::with_capacity(text.len() + runs.len() * 24);
7140 let mut at = 0usize;
7141 for r in runs {
7142 // Skip a run whose range does not address this string, without advancing `at`: dropping
7143 // the run loses styling, but advancing past it would drop the rest of the sentence.
7144 // `runs_are_valid` rejects these upstream; this keeps the failure cheap if one slips by.
7145 let Some(styled) = text.get(r.range.clone()) else {
7146 continue;
7147 };
7148 if r.range.start > at
7149 && let Some(plain) = text.get(at..r.range.start)
7150 {
7151 escape_markup_in(plain, &mut out, dialect);
7152 }
7153 open_run(r, dialect, base_points, &mut out);
7154 escape_markup_in(styled, &mut out, dialect);
7155 close_run(r, dialect, &mut out);
7156 at = r.range.end;
7157 }
7158 if let Some(tail) = text.get(at..) {
7159 escape_markup_in(tail, &mut out, dialect);
7160 }
7161 out
7162}
7163
7164impl Symbol {
7165 /// A 24×24 outline path for this symbol, Day's own drawing of it.
7166 ///
7167 /// The platform's icon comes first on every backend that has one (SF Symbols, the freedesktop
7168 /// icon theme, Fluent's glyph font). This is the fallback for when that lookup finds nothing,
7169 /// which is not an edge case: `view-filter-symbolic` exists on a GNOME desktop and nowhere
7170 /// else, so a GTK or Qt app run off that desktop drew a toolbar item with no icon at all.
7171 /// One table here means the same fallback shape everywhere instead of a gap per platform.
7172 ///
7173 /// `None` for a variant with no drawing yet: `Symbol` is `#[non_exhaustive]`, so a new one
7174 /// degrades to a label rather than failing to compile.
7175 #[must_use]
7176 pub fn outline_path(self) -> Option<&'static str> {
7177 use Symbol as S;
7178 // The wildcard is unreachable today (every variant is drawn below) and it is here for
7179 // the next one, which should degrade to a label rather than fail to compile.
7180 #[allow(unreachable_patterns)]
7181 Some(match self {
7182 S::Add => "M11 5h2v6h6v2h-6v6h-2v-6H5v-2h6z",
7183 S::Remove => "M5 11h14v2H5z",
7184 S::Delete => "M9 3h6l1 2h4v2H4V5h4zM6 8h12l-1 13H7z",
7185 S::Edit => {
7186 "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"
7187 }
7188 S::New => "M13 2H6v20h12V7h-5zm2 .5L19.5 7H15z",
7189 S::Open | S::Folder => "M2 5h7l2 2h11v12H2z",
7190 S::Save => "M3 3h13l5 5v13H3zm5 0h7v6H8zm-1 11h10v7H7z",
7191 S::Print => "M7 3h10v4H7zM4 8h16v8h-3v6H7v-6H4z",
7192 S::Refresh => "M12 4V1L8 5l4 4V6a6 6 0 1 1-6 6H4a8 8 0 1 0 8-8z",
7193 S::Search => {
7194 "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"
7195 }
7196 S::Share => "M12 3l5 5h-3v7h-4V8H7zM5 17h14v4H5z",
7197 // An eight-tooth gear, round about the center (radius 10 at the teeth, 7.6 at the
7198 // roots) with a 3.2 hole: square in its box, so it sits in a row's 24-point icon
7199 // slot at the same size as its neighbors.
7200 S::Settings => {
7201 "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"
7202 }
7203 S::Info => "M12 2a10 10 0 1 0 0 20 10 10 0 0 0 0-20m-1 5h2v2h-2zm0 4h2v6h-2z",
7204 S::Star => {
7205 "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"
7206 }
7207 S::Bookmark => "M6 2h12v20l-6-4-6 4z",
7208 S::Back => "M15.4 5.4L14 4l-8 8 8 8 1.4-1.4L8.8 12z",
7209 S::Forward => "M8.6 5.4L10 4l8 8-8 8-1.4-1.4L15.2 12z",
7210 S::Up => "M5.4 15.4L4 14l8-8 8 8-1.4 1.4L12 8.8z",
7211 S::Down => "M5.4 8.6L4 10l8 8 8-8-1.4-1.4L12 15.2z",
7212 S::Home => "M12 3l9 8h-3v10h-5v-6h-2v6H6V11H3z",
7213 S::Sidebar => "M3 4h18v16H3zm2 2v12h4V6zm6 0v12h8V6z",
7214 S::Filter => "M3 5h18l-7 8v6l-4 2v-8z",
7215 S::Sort => "M8 4v12H4l4 4 4-4H10V4zM14 6h7v2h-7zm0 4h5v2h-5zm0 4h3v2h-3z",
7216 S::More => {
7217 "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"
7218 }
7219 S::Play => "M8 5l11 7-11 7z",
7220 S::Pause => "M7 5h3v14H7zm7 0h3v14h-3z",
7221 S::Stop => "M6 6h12v12H6z",
7222 S::Camera => {
7223 "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"
7224 }
7225 S::Code => {
7226 "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"
7227 }
7228 S::Light => {
7229 "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"
7230 }
7231 S::Dark => "M12 3a9 9 0 1 0 9 9 7 7 0 0 1-9-9",
7232 // "Automatic": the half-filled circle every platform uses: the left half solid, the
7233 // right half an outline, which `evenodd` below turns into the ring it should be.
7234 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",
7235 S::ZoomIn => {
7236 "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"
7237 }
7238 S::ZoomOut => {
7239 "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"
7240 }
7241 // The ZoomIn lens with a numeral 1 in it, "back to actual size".
7242 S::ZoomReset => {
7243 "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"
7244 }
7245 S::Undo => "M12 5V2L7 7l5 5V9a5 5 0 1 1 0 10H8v2h4a7 7 0 0 0 0-14z",
7246 S::Redo => "M12 5V2l5 5-5 5V9a5 5 0 1 0 0 10h4v2h-4a7 7 0 0 1 0-14z",
7247 S::Copy => "M8 2h10v14H8zM4 6h2v14h12v2H4z",
7248 S::Cut => {
7249 "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"
7250 }
7251 S::Paste => "M9 2h6v2h3v18H6V4h3zm0 2v2h6V4z",
7252 S::Mail => "M2 5h20v14H2zm2 3.2V17h16V8.2l-8 5z",
7253 S::Document => "M14 2H6v20h12V6zm.5.8L17.2 6H14.5z",
7254 S::Check => "M9 16.2L4.8 12l-1.4 1.4L9 19 21 7l-1.4-1.4z",
7255 S::Close => {
7256 "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"
7257 }
7258 S::Warning => "M12 2l10 19H2zm-1 7h2v6h-2zm0 8h2v2h-2z",
7259 // Shape outlines, stroked as a 2-unit band (an even-odd ring), so they read as
7260 // outlines at any size rather than filled blocks.
7261 S::Rectangle => "M3 5h18v14H3zm2 2v10h14V7z",
7262 S::Oval => {
7263 "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"
7264 }
7265 // A circular ring (even-odd: outer disc minus inner) and its filled twin.
7266 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",
7267 S::CircleFilled => "M12 4a8 8 0 1 0 0 16 8 8 0 0 0 0-16z",
7268 S::Line => "M4.7 17.9l13.2-13.2 1.4 1.4L6.1 19.3z",
7269 // Group: a solid square stacked on another (the visible L of the back one);
7270 // Ungroup: the same two squares pulled apart.
7271 S::Group => "M8 4h12v12h-4V8H8zM4 8h12v12H4z",
7272 S::Ungroup => "M3 3h8v8H3zM13 13h8v8h-8z",
7273 // A crosshair: a dot in a ring with four ticks, the even-odd fill leaving the gap
7274 // between dot and ring empty.
7275 S::Location => {
7276 "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"
7277 }
7278 // `Symbol` is `#[non_exhaustive]`: a variant added upstream draws nothing here rather
7279 // than failing to compile, and its item keeps its label.
7280 _ => return None,
7281 })
7282 }
7283
7284 /// [`Self::outline_path`] wrapped as a standalone SVG document.
7285 #[must_use]
7286 pub fn outline_svg(self) -> Option<String> {
7287 self.outline_path().map(|d| {
7288 format!(
7289 "<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 24 24\">\
7290 <path fill-rule=\"evenodd\" d=\"{d}\"/></svg>"
7291 )
7292 })
7293 }
7294}
7295
7296/// Which markup dialect [`runs_to_markup`] should emit.
7297#[derive(Clone, Copy, Debug, PartialEq, Eq)]
7298pub enum MarkupDialect {
7299 /// Pango markup (GTK).
7300 Pango,
7301 /// Qt's rich-text HTML subset.
7302 QtHtml,
7303}
7304
7305/// XML-escape a run of plain text into `out`. `&` first, or the escapes escape each other.
7306///
7307/// Newlines are dialect-specific. Pango lays a literal `\n` out as a line break, but Qt's rich
7308/// text is HTML, where any run of whitespace collapses to one space, which silently ran a
7309/// two-paragraph body together into a single block. `<br>` is what says "break here" in HTML, so
7310/// the same string wraps the same way on both.
7311fn escape_markup_in(s: &str, out: &mut String, dialect: MarkupDialect) {
7312 for c in s.chars() {
7313 match c {
7314 '&' => out.push_str("&"),
7315 '<' => out.push_str("<"),
7316 '>' => out.push_str(">"),
7317 '"' => out.push_str("""),
7318 '\'' => out.push_str("'"),
7319 '\n' if dialect == MarkupDialect::QtHtml => out.push_str("<br>"),
7320 _ => out.push(c),
7321 }
7322 }
7323}
7324
7325/// [`escape_markup_in`] for the URL slot, where a newline cannot appear.
7326fn escape_markup(s: &str, out: &mut String) {
7327 escape_markup_in(s, out, MarkupDialect::Pango);
7328}
7329
7330fn hex(c: Color) -> String {
7331 format!(
7332 "#{:02x}{:02x}{:02x}",
7333 (c.r.clamp(0.0, 1.0) * 255.0) as u8,
7334 (c.g.clamp(0.0, 1.0) * 255.0) as u8,
7335 (c.b.clamp(0.0, 1.0) * 255.0) as u8
7336 )
7337}
7338
7339/// Does this run need a `<span>` in `dialect`, or do the plain tags cover it?
7340#[expect(
7341 clippy::float_cmp,
7342 reason = "a scale of exactly 1.0 is the unscaled default, compared as a sentinel"
7343)]
7344fn needs_span(r: &TextRun, dialect: MarkupDialect) -> bool {
7345 let extras = r.color.is_some()
7346 || r.background.is_some()
7347 || r.font.scale != 1.0
7348 || !r.font.feature_tags().is_empty()
7349 || !plain_line(r.underline)
7350 || !plain_line(r.strikethrough);
7351 match dialect {
7352 // Pango expresses the monospace family as a span attribute; Qt cannot (see below).
7353 MarkupDialect::Pango => extras || r.font.monospace,
7354 MarkupDialect::QtHtml => extras,
7355 }
7356}
7357
7358/// Is this decoration absent, or the one a bare `<u>`/`<s>` tag draws: a single line in the
7359/// text color? Anything else (a style, a color) has to travel as span attributes.
7360fn plain_line(d: Option<Decoration>) -> bool {
7361 d.is_none_or(|d| d == Decoration::SINGLE)
7362}
7363
7364/// Pango's `underline` attribute for a style. Pango has no dotted line, so `Dotted` draws
7365/// single; its `error` underline is the squiggle.
7366fn pango_underline(style: DecorationStyle) -> &'static str {
7367 match style {
7368 DecorationStyle::Single | DecorationStyle::Dotted => "single",
7369 DecorationStyle::Double => "double",
7370 DecorationStyle::Wavy => "error",
7371 }
7372}
7373
7374#[expect(
7375 clippy::float_cmp,
7376 reason = "a scale of exactly 1.0 is the unscaled default, compared as a sentinel"
7377)]
7378fn open_run(r: &TextRun, dialect: MarkupDialect, base_points: f64, out: &mut String) {
7379 use std::fmt::Write as _;
7380
7381 if let Some(url) = r.link.as_deref() {
7382 out.push_str("<a href=\"");
7383 escape_markup(url, out);
7384 out.push_str("\">");
7385 }
7386 // The span carries the attributes that have no tag: colors, relative size, and (on Pango)
7387 // the monospace family. Bold/italic/strike/underline are tags in both dialects, which keeps
7388 // the attribute string short and the escaping trivial.
7389 let color = r.color.map(|c| hex(c.resolved()));
7390 let background = r.background.map(|c| hex(c.resolved()));
7391 let mono = r.font.monospace;
7392 if needs_span(r, dialect) {
7393 match dialect {
7394 MarkupDialect::Pango => {
7395 out.push_str("<span");
7396 if let Some(c) = &color {
7397 let _ = write!(out, " foreground=\"{c}\"");
7398 }
7399 if let Some(c) = &background {
7400 let _ = write!(out, " background=\"{c}\"");
7401 }
7402 if mono {
7403 out.push_str(" font_family=\"monospace\"");
7404 }
7405 if r.font.scale != 1.0 {
7406 // Absolute, in Pango units (1/1024 pt), not the `font_scale`/`size="N%"`
7407 // pair: those are Pango 1.50 attributes, and a Pango that does not know an
7408 // attribute fails the whole markup parse, which renders the label empty
7409 // rather than merely unscaled. A point size still tracks the desktop's text
7410 // scaling, since Pango resolves points through the Xft DPI.
7411 let pts = r.font.resolved_points(base_points);
7412 let _ = write!(out, " size=\"{}\"", (pts * 1024.0).round() as i64);
7413 }
7414 let features = r.font.feature_tags();
7415 if !features.is_empty() {
7416 // The CSS `font-feature-settings` spelling Pango parses: `tnum 1, smcp 1`.
7417 let list: Vec<String> = features.iter().map(|t| format!("{t} 1")).collect();
7418 let _ = write!(out, " font_features=\"{}\"", list.join(", "));
7419 }
7420 // A styled or colored line travels as attributes; the plain one stays a tag.
7421 if let Some(d) = r.underline.filter(|_| !plain_line(r.underline)) {
7422 let _ = write!(out, " underline=\"{}\"", pango_underline(d.style));
7423 if let Some(c) = d.color {
7424 let _ = write!(out, " underline_color=\"{}\"", hex(c.resolved()));
7425 }
7426 }
7427 if let Some(d) = r.strikethrough.filter(|_| !plain_line(r.strikethrough)) {
7428 out.push_str(" strikethrough=\"true\"");
7429 if let Some(c) = d.color {
7430 let _ = write!(out, " strikethrough_color=\"{}\"", hex(c.resolved()));
7431 }
7432 }
7433 out.push('>');
7434 }
7435 MarkupDialect::QtHtml => {
7436 // Color only. Qt's rich text does not resolve the generic `monospace` family
7437 // from a style attribute (it rendered proportional), so the fixed face comes
7438 // from the `<code>` tag below, which Qt maps to its own fixed font.
7439 out.push_str("<span style=\"");
7440 if let Some(c) = &color {
7441 let _ = write!(out, "color:{c};");
7442 }
7443 if let Some(c) = &background {
7444 let _ = write!(out, "background-color:{c};");
7445 }
7446 if r.font.scale != 1.0 {
7447 // Points, not a percentage: Qt's rich-text CSS subset understands `pt` and
7448 // `px` and silently ignores `%`, which is why a scaled run rendered at the
7449 // base size here while every other backend scaled it.
7450 let pt = r.font.resolved_points(base_points);
7451 let _ = write!(out, "font-size:{pt}pt;");
7452 }
7453 if r.font.small_caps {
7454 out.push_str("font-variant:small-caps;");
7455 }
7456 // Qt's rich text draws one line style from markup; the color is a property
7457 // of the decoration as a whole. `Double`, `Dotted` and `Wavy` need a
7458 // `QTextCharFormat` underline style, which the Qt toolkit applies itself.
7459 if let Some(c) = r
7460 .underline
7461 .and_then(|d| d.color)
7462 .or_else(|| r.strikethrough.and_then(|d| d.color))
7463 {
7464 let _ = write!(out, "text-decoration-color:{};", hex(c.resolved()));
7465 }
7466 out.push_str("\">");
7467 }
7468 }
7469 }
7470 if dialect == MarkupDialect::QtHtml && mono {
7471 out.push_str("<code>");
7472 }
7473 if r.font.weight.is_some_and(|w| w >= FontWeight::Semibold) {
7474 out.push_str("<b>");
7475 }
7476 if r.font.italic {
7477 out.push_str("<i>");
7478 }
7479 let tags = dialect == MarkupDialect::QtHtml;
7480 if r.underline.is_some() && (tags || plain_line(r.underline)) {
7481 out.push_str("<u>");
7482 }
7483 if r.strikethrough.is_some() && (tags || plain_line(r.strikethrough)) {
7484 out.push_str("<s>");
7485 }
7486}
7487
7488fn close_run(r: &TextRun, dialect: MarkupDialect, out: &mut String) {
7489 let tags = dialect == MarkupDialect::QtHtml;
7490 if r.strikethrough.is_some() && (tags || plain_line(r.strikethrough)) {
7491 out.push_str("</s>");
7492 }
7493 if r.underline.is_some() && (tags || plain_line(r.underline)) {
7494 out.push_str("</u>");
7495 }
7496 if r.font.italic {
7497 out.push_str("</i>");
7498 }
7499 if r.font.weight.is_some_and(|w| w >= FontWeight::Semibold) {
7500 out.push_str("</b>");
7501 }
7502 if dialect == MarkupDialect::QtHtml && r.font.monospace {
7503 out.push_str("</code>");
7504 }
7505 if needs_span(r, dialect) {
7506 out.push_str("</span>");
7507 }
7508 if r.link.is_some() {
7509 out.push_str("</a>");
7510 }
7511}
7512
7513/// Are these runs well formed for `text`: ascending, non-overlapping, inside the string, and on
7514/// character boundaries?
7515///
7516/// Checked once in the pieces layer rather than in eight backends. A backend handed overlapping
7517/// ranges would produce a different wrong answer per platform, and a range splitting a multi-byte
7518/// character would panic on `str` slicing in some and render mojibake in others.
7519///
7520/// # Errors
7521///
7522/// Returns a message naming the first run that overlaps or precedes the run before it, ends
7523/// past the text, has an inverted range, or splits a multi-byte character.
7524pub fn runs_are_valid(text: &str, runs: &[TextRun]) -> Result<(), String> {
7525 let mut prev_end = 0usize;
7526 for (i, r) in runs.iter().enumerate() {
7527 if r.range.start < prev_end {
7528 return Err(format!(
7529 "run {i} starts at {} but the previous run ends at {prev_end} — runs must be \
7530 ascending and non-overlapping",
7531 r.range.start
7532 ));
7533 }
7534 if r.range.end > text.len() {
7535 return Err(format!(
7536 "run {i} ends at {} but the text is {} bytes",
7537 r.range.end,
7538 text.len()
7539 ));
7540 }
7541 if r.range.start > r.range.end {
7542 return Err(format!("run {i} has an inverted range {:?}", r.range));
7543 }
7544 if !text.is_char_boundary(r.range.start) || !text.is_char_boundary(r.range.end) {
7545 return Err(format!(
7546 "run {i} range {:?} splits a multi-byte character",
7547 r.range
7548 ));
7549 }
7550 prev_end = r.range.end;
7551 }
7552 Ok(())
7553}
7554
7555/// Shorten one line of `text` to fit `width`, putting an ellipsis where `mode` says, for a
7556/// toolkit whose label has no native head or middle truncation (docs/text.md "Truncation").
7557///
7558/// `measure` answers the width of a candidate string in the label's font. The search is a
7559/// bisection over how many characters to keep, so it measures about `log2(n)` candidates.
7560/// Text that already fits comes back unchanged; if not even the ellipsis fits, the ellipsis
7561/// alone is returned. Characters are Unicode scalar values, so a cut can separate a base
7562/// letter from a combining mark; a toolkit with a grapheme-aware native mode should use it.
7563///
7564/// ```
7565/// use day_spec::{elide, props::Truncation};
7566/// let width = |s: &str| s.chars().count() as f64;
7567/// assert_eq!(elide("/usr/local/share/day", Truncation::Middle, 9.0, width), "/usr…/day");
7568/// assert_eq!(elide("/usr/local/share/day", Truncation::Head, 9.0, width), "…hare/day");
7569/// assert_eq!(elide("/usr/local/share/day", Truncation::Tail, 9.0, width), "/usr/loc…");
7570/// ```
7571#[must_use]
7572pub fn elide(
7573 text: &str,
7574 mode: props::Truncation,
7575 width: f64,
7576 measure: impl Fn(&str) -> f64,
7577) -> String {
7578 const ELLIPSIS: char = '\u{2026}';
7579 if measure(text) <= width {
7580 return text.to_owned();
7581 }
7582 let chars: Vec<char> = text.chars().collect();
7583 let build = |keep: usize| -> String {
7584 let mut out = String::with_capacity(text.len());
7585 match mode {
7586 props::Truncation::Tail => {
7587 out.extend(&chars[..keep]);
7588 out.push(ELLIPSIS);
7589 }
7590 props::Truncation::Head => {
7591 out.push(ELLIPSIS);
7592 out.extend(&chars[chars.len() - keep..]);
7593 }
7594 props::Truncation::Middle => {
7595 let head = keep.div_ceil(2);
7596 out.extend(&chars[..head]);
7597 out.push(ELLIPSIS);
7598 out.extend(&chars[chars.len() - (keep - head)..]);
7599 }
7600 }
7601 out
7602 };
7603 // The largest `keep` whose candidate fits; `keep` < chars.len() because the whole text
7604 // does not fit.
7605 let (mut lo, mut hi) = (0usize, chars.len().saturating_sub(1));
7606 while lo < hi {
7607 let mid = (lo + hi).div_ceil(2);
7608 if measure(&build(mid)) <= width {
7609 lo = mid;
7610 } else {
7611 hi = mid - 1;
7612 }
7613 }
7614 build(lo)
7615}
7616
7617pub mod props {
7618 use super::*;
7619
7620 /// A container's native surface (docs/surfaces.md): what `.background(..)`,
7621 /// `.corner_radius(..)`, `.border(..)`, `.shadow(..)`, `.surface(..)` and `.card()` realize.
7622 #[derive(Clone, Debug, Default, PartialEq)]
7623 pub struct ContainerProps {
7624 /// What fills the surface: a solid [`Ink`] or a linear, radial or conic
7625 /// gradient. A gradient's unit points resolve against the surface's frame and follow it
7626 /// when it resizes. Every ink follows the appearance (docs/color.md "How a toolkit
7627 /// follows the appearance").
7628 pub fill: Option<super::Paint>,
7629 pub corner_radius: f64,
7630 /// Which corners [`Self::corner_radius`] rounds; the default is all four.
7631 pub corners: super::Corners,
7632 /// A line around the edge, inside the frame, following the rounded corners, drawn over
7633 /// the surface's content on every toolkit: a child that reaches the edge never covers
7634 /// it.
7635 pub border: Option<super::Border>,
7636 /// A shadow of the surface's rounded rectangle, drawn outside its frame. A surface
7637 /// with a shadow is built with `clips: false`: the shadow lies outside the bounds a
7638 /// clip would cut to, and on most toolkits the two cannot share a view.
7639 pub shadow: Option<super::Shadow>,
7640 pub clips: bool,
7641 /// Semantic, theme-adaptive surface, mapped by each backend to a native material that
7642 /// follows the platform's light/dark appearance automatically (it overrides
7643 /// [`Self::fill`] when set).
7644 pub role: Option<super::SurfaceRole>,
7645 }
7646 /// Post-realize changes to a container's surface. A constant surface sends none: these
7647 /// come only from a reactive modifier (`.background(signal)`, `.corner_radius(closure)`,
7648 /// `.surface(signal)`) or from Day emulating a frame-relative corner radius.
7649 #[derive(Clone, Debug, PartialEq)]
7650 pub enum ContainerPatch {
7651 /// The fill alone, the cheap and common change. With an animation, a solid fill
7652 /// changing to another solid fill animates (motion brief: the background color).
7653 Fill(Option<super::Paint>),
7654 /// Every styling field at once, an idempotent setter: fill, corner radius, corners,
7655 /// border, shadow and clipping. [`ContainerProps::role`] is realize-time and ignored
7656 /// here.
7657 Surface(Box<ContainerProps>),
7658 }
7659
7660 /// Realize props for a `scroll` container: which axis it scrolls, and how the native scroll
7661 /// view behaves (docs/scroll.md). Backends create the matching native scroll view (vertical
7662 /// `UIScrollView`/`ScrollView`, horizontal `HorizontalScrollView`, etc.).
7663 ///
7664 /// Everything past `horizontal` is a preference: a backend applies what its scroll view
7665 /// offers and ignores the rest, and the `Cap` named on a field says whether it does. Every
7666 /// default is the platform's own behavior, so `ScrollProps { horizontal, ..Default::default() }`
7667 /// is the scroll view Day has always made.
7668 #[derive(Clone, Debug, Default, PartialEq)]
7669 pub struct ScrollProps {
7670 pub horizontal: bool,
7671 /// Whether the scroll indicators (scroll bars) show.
7672 pub indicators: ScrollIndicators,
7673 /// Whether the content rubber-bands or glows past its edges: `None` keeps the
7674 /// platform's default, `Some(false)` stops at the edge, `Some(true)` asks for the
7675 /// overscroll effect even when the content fits.
7676 pub bounce: Option<bool>,
7677 /// Where the content comes to rest ([`crate::Cap::ScrollSnap`]).
7678 pub snap: ScrollSnap,
7679 /// When scrolling dismisses the software keyboard
7680 /// ([`crate::Cap::ScrollKeyboardDismiss`]).
7681 pub keyboard_dismiss: KeyboardDismiss,
7682 /// What a tap inside the scroll view does while the software keyboard is up
7683 /// ([`crate::Cap::ScrollKeyboardDismiss`]; `Native` only).
7684 pub keyboard_taps: KeyboardTaps,
7685 /// The content zooms between these scales ([`crate::Cap::ScrollZoom`]); `None` is a
7686 /// scroll view that does not zoom.
7687 pub zoom: Option<ZoomRange>,
7688 /// Send [`crate::Event::ScrollChanged`] as the content moves
7689 /// ([`crate::Cap::ScrollOffset`]). Off, the view installs no scroll observer.
7690 pub track_offset: bool,
7691 /// Send [`crate::Event::ScrollPhase`] as user-driven scrolling starts and stops
7692 /// ([`crate::Cap::ScrollPhases`]).
7693 pub track_phase: bool,
7694 }
7695
7696 /// Whether a scroll view shows its indicators ([`ScrollProps::indicators`]).
7697 #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
7698 pub enum ScrollIndicators {
7699 /// The platform's default: overlay bars that appear while scrolling, or classic bars.
7700 #[default]
7701 Automatic,
7702 /// No indicators. The content still scrolls.
7703 Hidden,
7704 }
7705
7706 /// Where a scroll view's content comes to rest ([`ScrollProps::snap`]).
7707 #[derive(Clone, Copy, Debug, Default, PartialEq)]
7708 pub enum ScrollSnap {
7709 /// Anywhere.
7710 #[default]
7711 None,
7712 /// On multiples of the viewport's extent along the scroll axis, one page per swipe.
7713 Page,
7714 /// On multiples of this many points along the scroll axis.
7715 Interval(f64),
7716 }
7717
7718 /// When scrolling dismisses the software keyboard ([`ScrollProps::keyboard_dismiss`]).
7719 #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
7720 pub enum KeyboardDismiss {
7721 /// Scrolling leaves the keyboard up.
7722 #[default]
7723 Never,
7724 /// The keyboard goes away when a drag begins.
7725 OnDrag,
7726 /// The keyboard follows the finger down once the drag reaches it, where the platform
7727 /// has that (UIKit); elsewhere the same as [`KeyboardDismiss::OnDrag`].
7728 Interactive,
7729 }
7730
7731 /// What a tap inside a scroll view does while the software keyboard is up
7732 /// ([`ScrollProps::keyboard_taps`]).
7733 #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
7734 pub enum KeyboardTaps {
7735 /// The tap reaches the control under it and the keyboard stays up.
7736 #[default]
7737 Deliver,
7738 /// The tap dismisses the keyboard and goes no further; the next tap is delivered.
7739 Dismiss,
7740 }
7741
7742 /// The scales a zooming scroll view moves between ([`ScrollProps::zoom`]); `1.0` is the
7743 /// content's natural size.
7744 #[derive(Clone, Copy, Debug, PartialEq)]
7745 pub struct ZoomRange {
7746 pub min: f64,
7747 pub max: f64,
7748 }
7749
7750 /// Post-realize changes to a `scroll` container.
7751 #[derive(Clone, Debug, PartialEq)]
7752 pub enum ScrollPatch {
7753 /// Zoom the content to `scale`, clamped to [`ScrollProps::zoom`], keeping the
7754 /// viewport's center where it is. The view answers with
7755 /// [`crate::Event::ScrollZoomed`] as the scale moves. Ignored where
7756 /// [`crate::Cap::ScrollZoom`] is `Unsupported`.
7757 Zoom { scale: f64, animated: bool },
7758 }
7759
7760 #[derive(Clone, Debug, Default, PartialEq)]
7761 pub struct LabelProps {
7762 pub text: String,
7763 pub font: FontSpec,
7764 pub color: Option<Ink>,
7765 /// What the text means, for the color the platform gives it (docs/text.md).
7766 ///
7767 /// Semantic the way [`crate::Font`] is semantic: an app says "this is secondary text"
7768 /// and each platform answers with its own answer: `secondaryLabelColor` on Apple,
7769 /// `?android:textColorSecondary`, GTK's `dim-label`. That is the only way a de-emphasized
7770 /// label stays correct in both appearances, since a literal grey that reads well on white
7771 /// is wrong on black. An explicit [`Self::color`] still wins; a backend that has no such
7772 /// color renders primary, which is legible and correct, just not dimmed.
7773 pub role: TextRole,
7774 pub wraps: bool,
7775 /// Maximum rendered lines; zero is unlimited. A duty on every toolkit: the label
7776 /// draws at most this many lines, ends the last one as [`Self::truncation`] says when
7777 /// text is left over, and measures no taller than that many lines. Changes arrive as
7778 /// [`LabelPatch::Paragraph`].
7779 pub max_lines: u32,
7780 /// Where the ellipsis goes when the text does not fit in one line (`wraps == false`)
7781 /// or in [`Self::max_lines`] lines.
7782 pub truncation: Truncation,
7783 /// Extra space after each character, in ems (multiples of the label's resolved font
7784 /// size), so tracking follows the reader's text size. `0.0` is the font's own
7785 /// spacing; a negative value tightens. A toolkit whose API takes points multiplies
7786 /// by the resolved size and repeats that when the font changes.
7787 pub letter_spacing: f64,
7788 /// The distance between baselines as a multiple of the label's resolved font size.
7789 /// `0.0` (and anything nonpositive or nonfinite) is the font's natural line height,
7790 /// about 1.2. The extra space is split above and below each line, so a one-line
7791 /// label grows too and its text stays centered in the line box.
7792 pub line_height: f64,
7793 /// Emit [`Event::TextSelected`] when the reader's
7794 /// selection in this label changes ([`Cap::LabelSelection`]).
7795 /// Set only on a selectable label; a toolkit that cannot report selections ignores it.
7796 pub reports_selection: bool,
7797 /// How the label's lines sit within its own width. Only observable on a label that
7798 /// wraps or carries explicit newlines: a single line fills its box, so its alignment is
7799 /// the container's business, not the label's.
7800 ///
7801 /// `Leading` is the default and is what running text wants; `Center` is for the short,
7802 /// centered block a welcome screen or an empty state uses. A backend that cannot set
7803 /// it renders leading-aligned, which is legible and correct, just not centered.
7804 pub align: TextAlign,
7805 /// Styled spans within `text` (docs/text-runs.md). Empty is the overwhelmingly common
7806 /// case and means exactly what a label has always meant: one font, one color. A backend
7807 /// that cannot draw runs ignores this and renders `text` uniformly, which is legible and
7808 /// correct, just unstyled.
7809 pub runs: Vec<crate::TextRun>,
7810 }
7811 /// What a label's text means, for the color the platform gives it (`LabelProps::role`).
7812 #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
7813 pub enum TextRole {
7814 /// Ordinary text, in the platform's primary label color.
7815 #[default]
7816 Primary,
7817 /// De-emphasized text: a caption, a hint, the "nothing selected" line an empty detail
7818 /// pane shows. Rendered in the platform's secondary label color.
7819 Secondary,
7820 }
7821
7822 impl LabelProps {
7823 /// The paragraph attributes as one value, what [`LabelPatch::Paragraph`] carries, so a
7824 /// toolkit applies them through one function at realize and on every patch.
7825 #[must_use]
7826 pub fn paragraph(&self) -> LabelParagraph {
7827 LabelParagraph {
7828 max_lines: self.max_lines,
7829 truncation: self.truncation,
7830 letter_spacing: self.letter_spacing,
7831 line_height: self.line_height,
7832 }
7833 }
7834 }
7835
7836 /// How a label's lines break, space and end: the paragraph attributes that can change
7837 /// after realize ([`LabelPatch::Paragraph`]). Each field means what the
7838 /// [`LabelProps`] field of the same name means.
7839 #[derive(Clone, Copy, Debug, Default, PartialEq)]
7840 pub struct LabelParagraph {
7841 pub max_lines: u32,
7842 pub truncation: Truncation,
7843 pub letter_spacing: f64,
7844 pub line_height: f64,
7845 }
7846
7847 /// Where a label that runs out of room puts its ellipsis (`LabelProps::truncation`).
7848 ///
7849 /// `Head` and `Middle` are guaranteed on a one-line label (`single_line()` or
7850 /// `max_lines(1)`). With more lines a toolkit applies them to the last line where the
7851 /// platform can and truncates the tail where it cannot.
7852 #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
7853 pub enum Truncation {
7854 /// Keep the start: `The quick brown…`. What running text wants.
7855 #[default]
7856 Tail,
7857 /// Keep the end: `…the lazy dog`. For text whose end identifies it.
7858 Head,
7859 /// Keep both ends: `The qui…azy dog`. For a file path or an identifier.
7860 Middle,
7861 }
7862
7863 /// How a paragraph's lines sit in the width they are given: a label's `align`, a canvas
7864 /// text anchor's horizontal part, and a styled document's paragraph alignment
7865 /// ([`ParagraphStyle::align`](crate::ParagraphStyle)).
7866 #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
7867 pub enum TextAlign {
7868 /// The reading direction's start edge: left in a left-to-right layout, right in a
7869 /// right-to-left one (docs/localization.md).
7870 #[default]
7871 Leading,
7872 Center,
7873 /// The reading direction's end edge.
7874 Trailing,
7875 /// Every line but the last stretched to both edges; the last line sits at the leading
7876 /// edge. A toolkit that cannot justify draws `Leading`. A canvas text anchor reads it
7877 /// as `Leading`.
7878 Justified,
7879 }
7880
7881 #[derive(Clone, Debug, PartialEq)]
7882 pub enum LabelPatch {
7883 Text(String),
7884 Color(Option<Ink>),
7885 Font(FontSpec),
7886 /// New text and its runs together. One patch, not two: a run's byte range is only
7887 /// meaningful against a particular string, so applying them separately would leave the
7888 /// widget briefly holding ranges that point into the wrong text.
7889 Runs(String, Vec<crate::TextRun>),
7890 /// The paragraph attributes, whole: the line limit, the truncation mode, the letter
7891 /// spacing and the line height. Sent when any reactive one changes, so the setter is
7892 /// idempotent. The label is measured again afterward.
7893 Paragraph(LabelParagraph),
7894 }
7895
7896 /// A button's native styling tier. `Automatic` is the toolkit's stock look; `Bordered`
7897 /// asks for a visually contained button where the stock look is borderless (iOS's plain
7898 /// system button reads as a link); `Prominent` asks for the platform's accent-filled /
7899 /// default-action affordance. Toolkits whose stock buttons are already contained treat
7900 /// `Bordered` as `Automatic`.
7901 // `Eq` is gone with the `Tinted` color: `Color` holds floats. `PartialEq` is what the
7902 // props diff uses, and that is unaffected.
7903 #[derive(Clone, Copy, Debug, Default, PartialEq)]
7904 pub enum ButtonStyleSpec {
7905 #[default]
7906 Automatic,
7907 Bordered,
7908 Prominent,
7909 /// A filled button in an app-chosen color, still drawn by the native control: the
7910 /// platform keeps its own pressed, hover, focus and disabled rendering, its button role,
7911 /// and its keyboard activation. The label color is not carried; each backend picks the
7912 /// readable one for the fill (see [`ButtonStyleSpec::on_tint`]), the same call the
7913 /// platform's own tinted buttons make.
7914 ///
7915 /// A backend with no way to recolor its button ignores this and draws its ordinary
7916 /// button. That is the trade: a plain button everywhere beats a colored
7917 /// rectangle that is no longer a button on the platforms that cannot.
7918 Tinted(Ink),
7919 /// A button no wider than its title asks for (a one-glyph "−" or "+" in a stepper,
7920 /// a "×" on a chip) on toolkits whose stock button carries a minimum width and wide
7921 /// insets (Material's 88 dp button turns a two-button stepper into 240 dp). The native
7922 /// control stays: only its minimum width and horizontal padding are reduced. A toolkit
7923 /// whose buttons already hug their title (AppKit, UIKit's plain button, Qt) draws its
7924 /// ordinary button.
7925 Compact,
7926 /// Borderless native action button; compact horizontal insets on Material.
7927 Plain,
7928 }
7929
7930 impl ButtonStyleSpec {
7931 /// The label color to draw on a [`ButtonStyleSpec::Tinted`] fill: whichever of black or
7932 /// white contrasts better against it, by WCAG's contrast ratio.
7933 ///
7934 /// Comparing the two ratios rather than thresholding the luminance is the difference
7935 /// between right and nearly right. A mid amber (`#F0A64C`) has a relative luminance of
7936 /// 0.44; under a "brighter than half" test it reads as dark and takes white text, at a
7937 /// hopeless 2.2:1. Its contrast against black is 9.7:1. The two ratios cross at a
7938 /// luminance of 0.179, not 0.5, and everything between those two numbers is a button
7939 /// nobody can read.
7940 pub fn on_tint(fill: Color) -> Color {
7941 // WCAG relative luminance: sRGB channels linearized, then weighted by the eye's
7942 // sensitivity to each.
7943 let lin = |c: f64| {
7944 let c = c.clamp(0.0, 1.0);
7945 if c <= 0.04045 {
7946 c / 12.92
7947 } else {
7948 ((c + 0.055) / 1.055).powf(2.4)
7949 }
7950 };
7951 let l = 0.2126 * lin(fill.r) + 0.7152 * lin(fill.g) + 0.0722 * lin(fill.b);
7952 // Contrast ratio is (lighter + 0.05) / (darker + 0.05); white is 1.0, black is 0.0.
7953 let against_white = 1.05 / (l + 0.05);
7954 let against_black = (l + 0.05) / 0.05;
7955 if against_black >= against_white {
7956 Color::BLACK
7957 } else {
7958 Color::WHITE
7959 }
7960 }
7961 }
7962
7963 #[derive(Clone, Debug, Default, PartialEq)]
7964 /// The visible content and accessible title of a button with an icon.
7965 pub struct ButtonContent {
7966 /// Also serves as the accessible name when only the icon is visible.
7967 pub title: String,
7968 pub icon: Option<Icon>,
7969 pub icon_only: bool,
7970 }
7971 #[derive(Clone, Debug, Default, PartialEq)]
7972 pub struct ButtonProps {
7973 pub title: String,
7974 pub icon: Option<Icon>,
7975 pub icon_only: bool,
7976 pub enabled: bool,
7977 pub style: ButtonStyleSpec,
7978 /// The button stands for the current choice among its siblings (a document tab, a
7979 /// view switcher): the platform's own checked or selected rendering, which keeps the
7980 /// button enabled, focusable and activatable, and tells assistive tech it is selected.
7981 /// A click never toggles it natively; only the app's next patch changes it.
7982 pub selected: bool,
7983 }
7984 #[derive(Clone, Debug, PartialEq)]
7985 pub enum ButtonPatch {
7986 Title(String),
7987 /// Update an icon button's label and icon together. Plain buttons still use `Title`.
7988 Content(ButtonContent),
7989 Enabled(bool),
7990 /// The selected state (see [`ButtonProps::selected`]).
7991 Selected(bool),
7992 /// A live style change: what a reactive `.tint(…)` sends, so a button can recolor with
7993 /// app state without being torn down and realized again.
7994 Style(ButtonStyleSpec),
7995 }
7996
7997 #[derive(Clone, Debug, Default, PartialEq)]
7998 pub struct ToggleProps {
7999 pub on: bool,
8000 pub enabled: bool,
8001 }
8002 #[derive(Clone, Debug, PartialEq)]
8003 pub enum TogglePatch {
8004 On(bool),
8005 Enabled(bool),
8006 }
8007
8008 #[derive(Clone, Debug, PartialEq)]
8009 pub struct SliderProps {
8010 pub value: f64,
8011 pub min: f64,
8012 pub max: f64,
8013 pub step: Option<f64>,
8014 pub enabled: bool,
8015 }
8016 impl Default for SliderProps {
8017 fn default() -> Self {
8018 SliderProps {
8019 value: 0.0,
8020 min: 0.0,
8021 max: 1.0,
8022 step: None,
8023 enabled: true,
8024 }
8025 }
8026 }
8027 #[derive(Clone, Debug, PartialEq)]
8028 pub enum SliderPatch {
8029 Value(f64),
8030 Enabled(bool),
8031 }
8032
8033 /// SwiftUI's `pickerStyle` analogue (`kinds::PICKER`). Each maps to a distinct native
8034 /// control per toolkit (docs/picker.md).
8035 #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
8036 pub enum PickerStyle {
8037 /// A dropdown/pop-up menu (`NSPopUpButton` / `GtkDropDown` / `QComboBox` / UIButton+UIMenu / Spinner).
8038 #[default]
8039 Menu,
8040 /// A horizontal segmented control (`NSSegmentedControl` / `UISegmentedControl` / linked toggles / …).
8041 Segmented,
8042 /// A vertical radio-button group laid out inline (`NSButton` radios / `GtkCheckButton` group / …).
8043 Inline,
8044 }
8045
8046 /// Full picker props (realize). `style` is set once at build; `options`, `selected` and
8047 /// `enabled` patch (via [`PickerPatch`]).
8048 #[derive(Clone, Debug, PartialEq)]
8049 pub struct PickerProps {
8050 /// Decorative boundaries before option indexes (not selectable options). Native menu
8051 /// grouping on AppKit/UIKit; ignored by other backends and non-menu styles.
8052 pub separators_before: Vec<usize>,
8053 pub options: Vec<String>,
8054 pub selected: usize,
8055 pub style: PickerStyle,
8056 /// Whether the picker takes input. Default `true`.
8057 pub enabled: bool,
8058 }
8059 impl Default for PickerProps {
8060 fn default() -> Self {
8061 PickerProps {
8062 separators_before: Vec::new(),
8063 options: Vec::new(),
8064 selected: 0,
8065 style: PickerStyle::default(),
8066 enabled: true,
8067 }
8068 }
8069 }
8070
8071 #[derive(Clone, Debug, PartialEq)]
8072 pub enum PickerPatch {
8073 Selected(usize),
8074 /// New option labels, for a picker whose choices come from data (a document list, a
8075 /// live count). The backend rebuilds its items and keeps the selected index where it
8076 /// still exists, clamping to the last option otherwise; a fresh
8077 /// [`PickerPatch::Selected`] follows whenever the app's own binding disagrees.
8078 Options(Vec<String>),
8079 /// Enable or disable the whole control, every style alike.
8080 Enabled(bool),
8081 }
8082
8083 /// Full text-area props (realize, `kinds::TEXT_AREA`; docs/textarea.md). `text` seeds the
8084 /// editor; `min_lines`/`max_lines` bound the auto-growing height in text lines
8085 /// (`max_lines == 0` = unbounded). `editable`/`selectable`/`spellcheck` control the native
8086 /// editor attributes (all default `true`); a backend that can't honor one answers
8087 /// `Cap::Text{Editable,Selectable,SpellCheck}` = `Unsupported`. `text` and the three attributes
8088 /// change after build (via [`TextAreaPatch`]); the rest are build-only.
8089 #[derive(Clone, Debug, PartialEq)]
8090 pub struct TextAreaProps {
8091 pub text: String,
8092 pub placeholder: String,
8093 pub min_lines: u32,
8094 pub max_lines: u32,
8095 /// Whether the user can edit the text (`false` = read-only). Default `true`.
8096 pub editable: bool,
8097 /// Whether the text can be selected (and copied). Default `true`.
8098 pub selectable: bool,
8099 /// Whether spell-check / autocorrect highlighting is on. Default `true`.
8100 pub spellcheck: bool,
8101 /// Plain Enter emits `Event::Submitted` instead of inserting a newline (Shift+Enter
8102 /// still inserts one where the platform can distinguish). Chat composers. Default
8103 /// `false`.
8104 pub submit_on_enter: bool,
8105 }
8106
8107 impl Default for TextAreaProps {
8108 fn default() -> Self {
8109 TextAreaProps {
8110 text: String::new(),
8111 placeholder: String::new(),
8112 min_lines: 1,
8113 max_lines: 0,
8114 editable: true,
8115 selectable: true,
8116 spellcheck: true,
8117 submit_on_enter: false,
8118 }
8119 }
8120 }
8121
8122 /// Imperative text-area updates: replace the text (programmatic sync), or flip one of the
8123 /// live attributes.
8124 #[derive(Clone, Debug, PartialEq)]
8125 pub enum TextAreaPatch {
8126 SetText(String),
8127 SetEditable(bool),
8128 SetSelectable(bool),
8129 SetSpellCheck(bool),
8130 }
8131
8132 #[derive(Clone, Debug, Default, PartialEq)]
8133 pub struct TextFieldProps {
8134 pub text: String,
8135 pub placeholder: String,
8136 pub enabled: bool,
8137 }
8138 #[derive(Clone, Debug, PartialEq)]
8139 pub enum TextFieldPatch {
8140 /// Origin-tagged write (§4.4): `from_native` suppresses the echo back into the widget.
8141 Text {
8142 text: String,
8143 from_native: bool,
8144 },
8145 Placeholder(String),
8146 Enabled(bool),
8147 /// Select a range of the field's text, or place the caret when the range is empty
8148 /// (docs/textfield.md "Selection"). Sent after any [`TextFieldPatch::Text`] of the same
8149 /// turn, so the range always counts the text the field now holds. A backend clamps it
8150 /// against its own text with [`TextSelection::utf16`] or [`TextSelection::bytes`] and
8151 /// applies it to a focused field; whether an unfocused field keeps it is the platform's
8152 /// (docs/textfield.md).
8153 Select(TextSelection),
8154 }
8155
8156 /// A range of a text field's text in Unicode scalar values (Rust `char`s), the unit
8157 /// [`TextFieldPatch::Select`] carries on every backend. `start..end` is half-open, and an
8158 /// empty range is a caret position. The helpers clamp to the text and convert to the unit a
8159 /// native field counts: UTF-16 code units (Apple, Android, Qt, WinUI, the web, ArkUI) or
8160 /// bytes. GTK counts characters, which is [`TextSelection::clamped`].
8161 #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
8162 pub struct TextSelection {
8163 pub start: usize,
8164 pub end: usize,
8165 }
8166
8167 impl TextSelection {
8168 /// The range from `start` to `end`, ordered so that `start <= end`.
8169 pub fn new(start: usize, end: usize) -> Self {
8170 TextSelection {
8171 start: start.min(end),
8172 end: start.max(end),
8173 }
8174 }
8175
8176 /// The range held to `text`: both ends at most its character count, `start <= end`.
8177 #[must_use]
8178 pub fn clamped(self, text: &str) -> Self {
8179 let n = text.chars().count();
8180 TextSelection::new(self.start.min(n), self.end.min(n))
8181 }
8182
8183 /// The clamped range as UTF-16 code-unit offsets into `text`: `(start, end)`.
8184 #[must_use]
8185 pub fn utf16(self, text: &str) -> (usize, usize) {
8186 let r = self.clamped(text);
8187 let at = |chars: usize| -> usize {
8188 text.chars().take(chars).map(char::len_utf16).sum::<usize>()
8189 };
8190 (at(r.start), at(r.end))
8191 }
8192
8193 /// The clamped range as UTF-8 byte offsets into `text`: `(start, end)`, each on a
8194 /// character boundary.
8195 #[must_use]
8196 pub fn bytes(self, text: &str) -> (usize, usize) {
8197 let r = self.clamped(text);
8198 let at = |chars: usize| -> usize {
8199 text.char_indices()
8200 .nth(chars)
8201 .map_or(text.len(), |(i, _)| i)
8202 };
8203 (at(r.start), at(r.end))
8204 }
8205 }
8206
8207 #[cfg(test)]
8208 mod text_selection_tests {
8209 use super::TextSelection;
8210
8211 #[test]
8212 fn orders_and_clamps() {
8213 assert_eq!(TextSelection::new(5, 2), TextSelection { start: 2, end: 5 });
8214 let r = TextSelection::new(3, usize::MAX).clamped("github.com");
8215 assert_eq!(r, TextSelection { start: 3, end: 10 });
8216 let past = TextSelection::new(40, 50).clamped("git");
8217 assert_eq!(past, TextSelection { start: 3, end: 3 });
8218 assert_eq!(
8219 TextSelection::new(0, 9).clamped(""),
8220 TextSelection::default()
8221 );
8222 }
8223
8224 #[test]
8225 fn converts_to_native_units() {
8226 // "é" is one char, one UTF-16 unit and two bytes; "😀" is one char, two UTF-16
8227 // units and four bytes.
8228 let text = "aé😀b";
8229 assert_eq!(TextSelection::new(1, 3).utf16(text), (1, 4));
8230 assert_eq!(TextSelection::new(1, 3).bytes(text), (1, 7));
8231 assert_eq!(TextSelection::new(0, usize::MAX).utf16(text), (0, 5));
8232 assert_eq!(TextSelection::new(0, usize::MAX).bytes(text), (0, 8));
8233 assert_eq!(TextSelection::new(4, 4).bytes(text), (8, 8));
8234 }
8235 }
8236
8237 /// How an image is scaled to fill its frame (§18.3). Maps to each toolkit's native scaling.
8238 #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
8239 pub enum ContentMode {
8240 /// Scale to fit entirely inside the frame, preserving aspect ratio (letterboxed). The
8241 /// default: an image never stretches unless asked. SwiftUI's `.scaledToFit`.
8242 #[default]
8243 Fit,
8244 /// Scale to fill the frame, preserving aspect ratio and cropping the overflow. SwiftUI's
8245 /// `.scaledToFill`.
8246 Fill,
8247 /// Stretch to fill the frame exactly, ignoring aspect ratio.
8248 Stretch,
8249 }
8250
8251 #[derive(Clone, Debug, Default, PartialEq)]
8252 pub struct ImageProps {
8253 /// Which pixels to draw: a staged asset name, encoded bytes, or an already-decoded
8254 /// image ([`ImageSource`], docs/images.md). A name resolves through the backend's own
8255 /// pipeline (§18.2); bytes and decoded ids need [`Cap::ImageDecode`], and a backend
8256 /// without it draws nothing rather than guessing.
8257 pub source: ImageSource,
8258 pub decorative: bool,
8259 /// How the image scales within its frame (default [`ContentMode::Fit`], no stretching).
8260 pub content_mode: ContentMode,
8261 /// Optional width:height ratio the view is constrained to (e.g. `16.0/9.0`). `None` lets the
8262 /// image take its allocated frame.
8263 pub aspect_ratio: Option<f64>,
8264 /// Monochrome tint for a template/vector glyph (docs/vectors.md): backends that can,
8265 /// recolor natively (template rendering on Apple, drawable tint on Android, pixel
8266 /// recolor on GTK); backends that can't yet ignore it and draw the source colors.
8267 /// `None` (the default, and every raster `image(…)`) means "as authored".
8268 pub tint: Option<Ink>,
8269 /// A monochrome template glyph (docs/vectors.md "Template"): with no `tint`, it draws
8270 /// in the foreground of the surface it sits on — the theme's label color on the
8271 /// desktops, the cell's tint on UIKit, `currentColor` on the web — and follows a
8272 /// theme switch. What a sidebar row's untinted icon is: a tinted glyph recolors the
8273 /// same way with or without this, and `false` (the default) draws an untinted glyph as
8274 /// authored. [`ImagePatch::Tint`]`(None)` on a template returns to that foreground,
8275 /// not to the authored colors.
8276 pub template: bool,
8277 }
8278
8279 /// A list row's standard content (`kinds::LIST_ITEM`, docs/list.md "List items"). Empty
8280 /// text means the part is absent.
8281 #[derive(Clone, Debug, Default, PartialEq)]
8282 pub struct ListItemProps {
8283 pub title: String,
8284 /// A second line under the title, in the platform's secondary style.
8285 pub subtitle: String,
8286 /// Trailing text (a count, a value), in the platform's secondary style.
8287 pub detail: String,
8288 /// The leading glyph: a symbol or a bundled image.
8289 pub icon: Option<crate::Icon>,
8290 /// The glyph's color; `None` takes the platform's own (template glyphs follow the
8291 /// foreground, the tint color on UIKit).
8292 pub icon_tint: Option<Ink>,
8293 /// A trailing check mark: the platform's selected-option mark (UIKit's checkmark
8294 /// accessory, a Material check icon), announced as checked.
8295 pub checked: bool,
8296 }
8297
8298 /// A live change to a realized list item; every part changes in place.
8299 #[derive(Clone, Debug, PartialEq)]
8300 pub enum ListItemPatch {
8301 Title(String),
8302 Subtitle(String),
8303 Detail(String),
8304 Icon(Option<crate::Icon>),
8305 IconTint(Option<Ink>),
8306 Checked(bool),
8307 }
8308
8309 /// A live change to a realized image or vector glyph.
8310 ///
8311 /// `content_mode` and the rest still describe which art this is and how it fills its frame,
8312 /// which a rebuild expresses better than a patch. Two things do want to follow a signal: the
8313 /// tint (a glyph that recolors with the selection or the theme should repaint, not be torn
8314 /// down and realized again, docs/vectors.md "Tint") and the source, now that it can be a
8315 /// buffer the app swaps (a download landing, a new photo picked, docs/images.md). Replacing
8316 /// the pixels of a view that is already on screen is what a patch is for; realizing a second
8317 /// view would flash.
8318 #[derive(Clone, Debug, PartialEq)]
8319 pub enum ImagePatch {
8320 /// Recolor the glyph, or `None` to draw the authored colors again.
8321 Tint(Option<Ink>),
8322 /// Draw different pixels in the same view. A backend that cannot decode the new source
8323 /// (bytes where [`Cap::ImageDecode`] is `Unsupported`) leaves what it was drawing.
8324 Source(ImageSource),
8325 }
8326
8327 #[derive(Clone, Debug, Default, PartialEq)]
8328 pub struct CanvasProps {
8329 pub ops: Vec<DrawOp>,
8330 }
8331
8332 /// Progress indicator. `value` is the completed fraction in `0.0..=1.0`; `None` means
8333 /// indeterminate (an animated spinner / busy bar, no known extent). Backends map this to
8334 /// their native determinate/indeterminate widgets (docs/progress.md).
8335 #[derive(Clone, Debug, PartialEq)]
8336 pub struct ProgressProps {
8337 pub value: Option<f64>,
8338 /// Whether an indeterminate indicator animates; ignored for a determinate bar.
8339 pub animating: bool,
8340 /// The platform's large indicator size.
8341 pub large: bool,
8342 }
8343 impl Default for ProgressProps {
8344 fn default() -> Self {
8345 Self {
8346 value: None,
8347 animating: true,
8348 large: false,
8349 }
8350 }
8351 }
8352 #[derive(Clone, Debug, PartialEq)]
8353 pub enum ProgressPatch {
8354 Animating(bool),
8355 /// New completed fraction, or `None` to switch to indeterminate.
8356 Value(Option<f64>),
8357 }
8358
8359 /// A rule between neighbors (`divider()`): a hairline across the width it is offered, or,
8360 /// with `vertical`, down the height it is offered (`divider().vertical()`, between a
8361 /// row's panes). A toolkit measures both the same way, as a horizontal rule, because the
8362 /// pieces layer swaps the axes of a vertical one's proposal and answer; realization is
8363 /// where the orientation matters, for the few widgets that draw a horizontal line
8364 /// regardless of their frame.
8365 #[derive(Clone, Debug, Default, PartialEq)]
8366 pub struct DividerProps {
8367 pub vertical: bool,
8368 }
8369
8370 /// How a navigation host lays its panes out (docs/navigation.md).
8371 ///
8372 /// This is the resolved presentation, what the toolkit must draw right now. The app asks for
8373 /// one through `Nav::presentation`, where leaving it unset means "automatic": the pieces
8374 /// layer resolves it from the window's [`SizeClass`] and the toolkit's `Cap::NavSplit`, and
8375 /// re-resolves it whenever the class changes. There is no `Auto` variant here because a
8376 /// backend can only ever draw a concrete one, so the undecided state stays on the app's side
8377 /// of the boundary where it can still be decided.
8378 #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
8379 pub enum NavPresentation {
8380 /// Sidebar beside detail, both visible (`NSSplitViewController`, nested `GtkPaned`s,
8381 /// a `NavigationView`). The sidebar pane gets its own container.
8382 Split,
8383 /// One page at a time, back-navigable. The sidebar pane becomes the stack's root.
8384 #[default]
8385 Stack,
8386 /// The rows drawn as a tab bar, one page's content beside it, no back stack: what a
8387 /// phone-shaped window wants from a one-of-N surface (`UITabBarController`, a Material
8388 /// `NavigationBarView`, `NavigationView.PaneDisplayMode = Top`). The `Pane::Sidebar` page
8389 /// is not drawn at all: its rows are the chrome.
8390 Tabs,
8391 /// The rows drawn as a narrow icon strip beside the content, the `Medium`-width answer
8392 /// between [`Self::Tabs`] and [`Self::Split`] (a Material `NavigationRailView`,
8393 /// `PaneDisplayMode = LeftCompact`, an ArkUI vertical `Tabs`).
8394 ///
8395 /// A backend with no rail rounds it to a neighbor of its own choosing rather than
8396 /// failing: UIKit answers `Tabs` (which is what iPadOS does at that width), GTK the same.
8397 /// Rounding is expected and correct; this variant is a request, not a contract.
8398 Rail,
8399 }
8400
8401 impl NavPresentation {
8402 /// `true` for [`NavPresentation::Split`], the shape most backend code wants.
8403 #[must_use]
8404 pub fn is_split(self) -> bool {
8405 self == NavPresentation::Split
8406 }
8407
8408 /// `true` when the rows are the chrome rather than a drawn page: [`Self::Tabs`] and
8409 /// [`Self::Rail`]. Both hide the `Pane::Sidebar` page and render its rows themselves, so
8410 /// backend code that only cares about that distinction asks this instead of matching both.
8411 #[must_use]
8412 pub fn rows_are_chrome(self) -> bool {
8413 matches!(self, NavPresentation::Tabs | NavPresentation::Rail)
8414 }
8415 }
8416
8417 /// Navigation host (docs/navigation.md).
8418 #[derive(Clone, Debug, Default, PartialEq)]
8419 pub struct NavProps {
8420 /// Document-tab chrome, independent of navigation destinations.
8421 pub documents: Option<DocumentTabsConfig>,
8422 pub title: String,
8423 /// The presentation to draw now; re-presented in place by [`NavPatch::Presentation`].
8424 pub presentation: NavPresentation,
8425 /// The app left the presentation automatic (`NavStyle::Automatic`, or a `Sidebar`
8426 /// nav host with no `.presentation(…)` pin), so it is free to follow the window.
8427 ///
8428 /// Only a toolkit answering `Cap::NavRepresent = Emulated` needs this: its own adaptive
8429 /// container owns the morph, and it must know whether the app asked for one at all before
8430 /// building it. With two presentations that bit could be inferred from a lowered `Split`;
8431 /// with four it cannot, so it is carried explicitly rather than encoded.
8432 ///
8433 /// `Native` re-presenters ignore it (they are told each presentation as it is resolved),
8434 /// and so do toolkits that cannot re-present.
8435 pub adaptive: bool,
8436 /// Draw the platform's own show/hide-sidebar affordance on this host's chrome
8437 /// (docs/toolbars.md). `true` for every `nav(Sidebar)` unless the app opted out:
8438 /// the toolkit owns both the button and the behavior
8439 /// (`NSToolbarToggleSidebarItemIdentifier`, the split view's collapse on GTK,
8440 /// `NavigationView.IsPaneOpen` on XAML), so an app that once declared the item by hand
8441 /// now declares nothing. Hosts with no sidebar ignore it.
8442 pub sidebar_toggle: bool,
8443 /// Search over this navigation surface (`Nav::searchable`, docs/search.md).
8444 /// `None` = the surface is not searchable and no field is rendered anywhere.
8445 pub search: Option<SearchProps>,
8446 /// `Some(width)` = this host has a content-list pane ([`Pane::List`]) at this preferred
8447 /// width in points, between the sidebar and the detail (docs/navigation.md). Read at
8448 /// realize, because a backend that builds a different container for a three-pane host
8449 /// (UIKit's triple-column style is init-only) needs to know before it builds. `None` on
8450 /// every host without one, including all of them on backends answering
8451 /// [`crate::Cap::NavContentList`] `Unsupported`: the pieces layer composes there and
8452 /// the prop is never set.
8453 pub list_width: Option<f64>,
8454 /// Whether that pane is showing for the destination the host opens on
8455 /// (`Nav::content_list_for`). Read at realize, like `list_width`, and for a
8456 /// related reason: a backend whose pane is a real split item can only honor a
8457 /// collapsed state reliably by setting it before the item joins the split. Told
8458 /// afterwards (by `NavPatch::ListVisible`, on a window that has not been displayed
8459 /// yet), AppKit reports the item collapsed and then lays it back out from its holding
8460 /// priorities, and the app opens with a list beside a page that does not own one.
8461 /// `true` on every host whose first destination has a list, and on hosts with no pane
8462 /// at all, where it means nothing.
8463 pub list_visible: bool,
8464 }
8465
8466 /// Switch only tab chrome; resident contents must retain their native identity.
8467 #[derive(Clone, Copy, Debug, PartialEq)]
8468 pub struct DocumentTabsPatch {
8469 pub native: bool,
8470 }
8471
8472 /// Localized document-tab chrome. Native callbacks emit stable route keys.
8473 #[derive(Clone, Debug, Default, PartialEq)]
8474 pub struct DocumentTabsConfig {
8475 pub new_label: String,
8476 pub close_label: String,
8477 pub can_add: bool,
8478 }
8479
8480 /// Where a searchable surface's field should be drawn.
8481 ///
8482 /// A preference, not an instruction: a backend that cannot honor the request falls back to
8483 /// whatever its platform does, exactly as SwiftUI's `searchable(placement:)` does ("depending
8484 /// on the containing view hierarchy and platform, the requested placement may not be able to
8485 /// be fulfilled"). `Automatic` is the one to reach for: it is what lets the field live in the
8486 /// window toolbar on a wide window and move into the navigation list on a narrow one.
8487 #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
8488 pub enum SearchPlacement {
8489 /// The platform decides, from the window's size class and its own convention.
8490 #[default]
8491 Automatic,
8492 /// In the window's toolbar (`NSSearchToolbarItem`, an `AdwHeaderBar` entry, a
8493 /// `CommandBar` `AutoSuggestBox`). `Inline` where the toolbar cannot hold a search field
8494 /// (`Cap::ToolbarSearch`).
8495 Toolbar,
8496 /// Attached to the navigation surface itself: above the sidebar list, or in the
8497 /// navigation bar's search drawer on the phones.
8498 Inline,
8499 }
8500
8501 /// Search over a navigation surface (docs/search.md). The query itself stays an app-owned
8502 /// signal; this carries only what the toolkit must draw, so moving the field between
8503 /// placements never moves the state.
8504 #[derive(Clone, Debug, Default, PartialEq)]
8505 pub struct SearchProps {
8506 /// Current text. Two-way: the user typing emits [`Event::SearchChanged`], and the app's
8507 /// own writes arrive as [`SearchPatch::Text`].
8508 pub text: String,
8509 /// Empty-state prompt.
8510 pub prompt: String,
8511 pub placement: SearchPlacement,
8512 /// Opt into native scrolling search/title chrome on mobile. Default false keeps
8513 /// the field pinned. Desktop toolbar search is unchanged.
8514 pub hides_on_scroll: bool,
8515 /// Start the UIKit navigation search drawer collapsed, with a compact toolbar title.
8516 /// Implies scrolling search on UIKit; ignored by other backends. Default false.
8517 pub initially_hidden: bool,
8518 /// Scope titles, empty = no scope bar. One-of-N: a `UISearchBar` scope bar, a Material
8519 /// `ChipGroup` of single-selection filter chips, an ArkUI `SegmentButtonV2`, an
8520 /// `NSSegmentedControl` (docs/search.md has the per-backend table).
8521 pub scopes: Vec<String>,
8522 /// Index into `scopes`; meaningless when `scopes` is empty.
8523 pub scope: usize,
8524 /// Completions offered for the current text. On a navigation surface these complete the
8525 /// field rather than replacing the list: the list is already the result set, so an
8526 /// overlay of results would cover the thing it is filtering.
8527 pub suggestions: Vec<String>,
8528 }
8529
8530 /// A targeted update to a live search field, the path a bound signal writes through, so
8531 /// syncing text never rebuilds (and refocuses) the field mid-word.
8532 #[derive(Clone, Debug, PartialEq)]
8533 pub enum SearchPatch {
8534 Focus,
8535 Text(String),
8536 Scope(usize),
8537 Suggestions(Vec<String>),
8538 }
8539 /// Applied to the nav host after a page child is attached / before it is removed;
8540 /// the toolkit animates its native presentation accordingly.
8541 #[derive(Clone, Debug, PartialEq)]
8542 pub enum NavPatch {
8543 /// The just-attached last page child became the top of the stack. `immersive` marks a
8544 /// page that keeps the floating transparent chrome on backends with an immersive nav
8545 /// mode (UIKit and edge-to-edge Material). Unmarked pages get the
8546 /// standard opaque bar.
8547 Pushed { title: String, immersive: bool },
8548 /// The top page is about to be removed; present its predecessor.
8549 Popped,
8550 /// Current top-of-stack title changed.
8551 Title(String),
8552 /// The top page has a back guard (`NavStack::on_back`, docs/navigation.md): while `true`,
8553 /// the toolkit must not auto-pop on a native back gesture/button but route it to
8554 /// Day as `Event::NavBack { already_popped: false }` so the app's guard decides. On
8555 /// backends whose back already routes through Day (AppKit/Qt/XAML/web custom headers)
8556 /// this is a no-op; iOS disables the swipe, Android holds its callback, GTK sets the
8557 /// page `can-pop=false`, ArkUI consumes `onBackPressed`.
8558 GuardTop(bool),
8559 /// Re-present the host: the window's size class crossed a breakpoint, or the app wrote a
8560 /// new `presentation`. The page children do not change: the toolkit rebuilds its
8561 /// chrome and re-homes the pages it already has, each one landing by its
8562 /// [`NavPageProps::pane`]. Rebuilding them instead would drop scroll offsets, field
8563 /// focus, and every native animation in flight, which is why this is a patch and not
8564 /// a rebuild.
8565 ///
8566 /// Backends with no split container ignore it and stay stacked.
8567 Presentation(NavPresentation),
8568 /// Show the resident [`Pane::Detail`] page at this index, counting the host's detail
8569 /// children in attach order. The counterpart to [`Self::Pushed`]/[`Self::Popped`] for the
8570 /// presentations where pages are resident rather than stacked
8571 /// ([`NavPresentation::rows_are_chrome`]): a tab bar switches between pages that all stay
8572 /// alive, so there is nothing to push and nothing to pop.
8573 ///
8574 /// Applied without re-emitting [`crate::Event::SelectionChanged`], per the from-native
8575 /// echo rule: this is the programmatic-sync direction.
8576 ///
8577 /// A backend drawing a stacked presentation never receives it; the pieces layer sends
8578 /// push/pop there instead.
8579 Select(usize),
8580 /// Reorder resident detail pages by their previous indices without rebuilding them.
8581 Reorder(Vec<usize>),
8582 /// Show or collapse the content-list pane ([`Pane::List`]), the per-destination
8583 /// visibility switch (`Nav::content_list_for`, docs/navigation.md): a nav host
8584 /// section that spans the whole detail area (a settings page) collapses the pane, and
8585 /// selecting a list-backed section brings it back. Only sent to hosts whose
8586 /// [`NavProps::list_width`] is set. Applied directly, not through an animator proxy:
8587 /// the screenshot step captures the instant the patch returns (the sidebar-toggle rule).
8588 ListVisible(bool),
8589 /// Stacked presentations on a merged-pane backend ([`crate::Cap::NavContentList`]
8590 /// `Emulated`) only: the resident [`Pane::List`] page joins (`true`) or leaves
8591 /// (`false`) the navigation stack directly above the sidebar root. The pieces layer
8592 /// sends it as the selection gains or loses a list-backed destination; the backend
8593 /// realizes the membership change through its platform's navigation APIs (UIKit:
8594 /// `showColumn(.supplementary)` / a pop to the root; never a manual splice, which
8595 /// destroys the split's collapse bookkeeping). Never sent to `Native` backends (their
8596 /// pane persists through every presentation) nor while split.
8597 ListInStack(bool),
8598 }
8599
8600 /// Which pane of a navigation host a page belongs to (docs/navigation.md).
8601 ///
8602 /// A page's pane is a fact about the model, not about how the host currently draws it: a
8603 /// nav host's list page is [`Pane::Sidebar`] whether the toolkit is showing a sidebar beside
8604 /// a detail or stacking the two. What the presentation decides is where each pane lands:
8605 /// its own splitter pane in [`NavPresentation::Split`], the root of the stack in
8606 /// [`NavPresentation::Stack`]. Keeping the two separate is what lets a host re-present on a
8607 /// size-class change (`NavPatch::Presentation`) by re-homing the pages it already has,
8608 /// instead of tearing the tree down and rebuilding it.
8609 #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
8610 pub enum Pane {
8611 /// The list / master pane of a nav host. At most one page per host.
8612 Sidebar,
8613 /// The content-list pane between the sidebar and the detail, Mail's message list
8614 /// (`Nav::content_list`, docs/navigation.md). At most one page per host, and only
8615 /// on hosts whose [`NavProps::list_width`] is set; a backend answering
8616 /// [`crate::Cap::NavContentList`] `Unsupported` never sees one.
8617 List,
8618 /// A destination page. Every page of a `nav_stack` presentation is one of these.
8619 #[default]
8620 Detail,
8621 }
8622
8623 /// One destination's native container.
8624 #[derive(Clone, Debug, Default, PartialEq)]
8625 pub struct NavPageProps {
8626 pub title: String,
8627 pub pane: Pane,
8628 /// Paint behind the top system/navigation bars on UIKit and edge-to-edge Android.
8629 /// Desktop toolkits retain their usual page chrome.
8630 pub immersive: bool,
8631 }
8632
8633 /// The largest a modal sheet grows on a desktop, in points: the window less a margin up to
8634 /// this (docs/cover.md "Modal sheet"). AppKit's native sheet and the composed card share it.
8635 pub const SHEET_MAX: crate::Size = crate::Size::new(640.0, 620.0);
8636 /// The largest a [`CoverProps::large`] sheet grows (docs/cover.md "Large sheet").
8637 pub const LARGE_SHEET_MAX: crate::Size = crate::Size::new(1040.0, 880.0);
8638
8639 /// A fullscreen cover's content container (docs/cover.md). Realized detached and hidden;
8640 /// `CoverPatch::Present` shows it over the whole window.
8641 #[derive(Clone, Debug, Default, PartialEq)]
8642 pub struct CoverProps {
8643 /// Prefer a native sheet; toolkits without sheet presentation keep their modal cover.
8644 pub sheet: bool,
8645 /// A half-height sheet rising from the bottom edge, the window content above it
8646 /// staying on show and, where the platform allows, interactive: an inspector over the
8647 /// canvas it describes. Implies `sheet`. The toolkit reports the sheet's own content
8648 /// size through `FrameChanged`, as for any cover (docs/cover.md "Half sheet").
8649 pub half: bool,
8650 /// A large sheet: most of the window, less a margin, for a document or web page that
8651 /// needs the room (docs/cover.md "Large sheet"). Implies `sheet`.
8652 pub large: bool,
8653 }
8654
8655 /// Applied to a `kinds::COVER` node as its bound signal opens and closes it.
8656 #[derive(Clone, Debug, PartialEq)]
8657 pub enum CoverPatch {
8658 /// Present the cover fullscreen (slide up where the platform animates modals).
8659 /// `background` paints the whole surface edge-to-edge (under the status bar / home
8660 /// indicator); the content container is inset to the safe area within it.
8661 /// `dismiss_disabled` = the user must not be able to dismiss it interactively
8662 /// (system back / sheet gestures); programmatic dismissal still works.
8663 Present {
8664 background: Option<Ink>,
8665 dismiss_disabled: bool,
8666 },
8667 /// The `interactive_dismiss_disabled` state changed while presented.
8668 DismissDisabled(bool),
8669 /// Dismiss the cover. When the hide transition finishes the backend emits
8670 /// [`crate::Event::CoverHidden`] on the node (trampoline backends send
8671 /// `BridgeKind::CoverHidden`), letting the piece dispose the content only after it
8672 /// left the screen.
8673 Dismiss,
8674 }
8675
8676 /// A `kinds::INSPECTOR` split (docs/inspector.md): content beside a trailing inspector
8677 /// pane. The pane's visibility is Day-owned state (the piece's bound signal), so the
8678 /// props carry the value to draw and [`InspectorPatch::Visible`] keeps it current;
8679 /// a native affordance hiding the pane (a dock close button, a dragged-shut divider)
8680 /// reports back with [`crate::Event::InspectorChanged`].
8681 #[derive(Clone, Debug, PartialEq)]
8682 pub struct InspectorProps {
8683 /// Whether the pane is showing now.
8684 pub visible: bool,
8685 /// The pane's preferred width in points. A backend with a user-draggable divider
8686 /// treats it as the initial width; one without draws it at exactly this.
8687 pub width: f64,
8688 /// Which side of the content the pane sits on. `Trailing` is the classic inspector;
8689 /// `Leading` is a utility pane like a layer panel (docs/tree.md).
8690 pub edge: PaneEdge,
8691 }
8692
8693 /// Which side an inspector pane occupies (docs/inspector.md).
8694 #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
8695 pub enum PaneEdge {
8696 #[default]
8697 Trailing,
8698 Leading,
8699 }
8700
8701 /// Applied to a `kinds::INSPECTOR` node as its bound signal changes.
8702 #[derive(Clone, Debug, PartialEq)]
8703 pub enum InspectorPatch {
8704 /// Show or hide the pane (animated where the platform animates panes). The
8705 /// programmatic-sync direction: applying it must not re-emit
8706 /// [`crate::Event::InspectorChanged`], per the from-native echo rule.
8707 Visible(bool),
8708 }
8709
8710 /// One pane of a `kinds::INSPECTOR` split (docs/inspector.md).
8711 #[derive(Clone, Debug, Default, PartialEq)]
8712 pub struct InspectorPaneProps {
8713 /// `true` for the inspector panel itself, `false` for the content pane.
8714 pub panel: bool,
8715 }
8716
8717 /// How a `kinds::SPLIT` lays its two panes (docs/split.md): beside each other, the divider
8718 /// standing, or stacked, the divider lying. Named by where the panes go, since that is
8719 /// what an app's "layout" toggle means; the divider runs the other way.
8720 #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
8721 pub enum SplitAxis {
8722 /// The panes side by side (first leading), the divider vertical.
8723 #[default]
8724 Horizontal,
8725 /// The panes stacked (first on top), the divider horizontal.
8726 Vertical,
8727 }
8728
8729 /// A `kinds::SPLIT` (docs/split.md): two panes with a divider the user drags. The first
8730 /// pane's share is Day-owned state (the piece's bound signal): the props carry the value
8731 /// to draw, [`SplitPatch::Fraction`] keeps it current, and a divider the user moved
8732 /// reports back as [`crate::Event::ValueChanged`] with the new share, which applying the
8733 /// patch must never re-emit (the from-native echo rule).
8734 #[derive(Clone, Debug, PartialEq)]
8735 pub struct SplitProps {
8736 pub axis: SplitAxis,
8737 /// The first pane's share of the split's length along `axis`, `0.0..=1.0`.
8738 pub fraction: f64,
8739 /// The least length either pane may be dragged to, in points.
8740 pub min_pane: f64,
8741 }
8742
8743 /// Applied to a `kinds::SPLIT` node as its bound signals change.
8744 #[derive(Clone, Debug, PartialEq)]
8745 pub enum SplitPatch {
8746 /// Turn the split the other way, keeping the share.
8747 Axis(SplitAxis),
8748 /// Move the divider so the first pane takes this share. The programmatic-sync
8749 /// direction: applying it must not re-emit [`crate::Event::ValueChanged`].
8750 Fraction(f64),
8751 }
8752
8753 /// One pane of a `kinds::SPLIT` (docs/split.md).
8754 #[derive(Clone, Debug, Default, PartialEq)]
8755 pub struct SplitPaneProps {
8756 /// `false` for the first pane, `true` for the second.
8757 pub second: bool,
8758 }
8759
8760 /// Native navigation item list. `items` are display titles in route order;
8761 /// `selected` highlights the active route (split presentation; None on mobile roots).
8762 /// `icons` (parallel to `items`, `None` = no icon) are bundled image names resolved by each
8763 /// backend via `resource::resolve_image_file`; a backend that can't decorate its rows just
8764 /// ignores them.
8765 #[derive(Clone, Debug, Default, PartialEq)]
8766 pub struct NavMenuProps {
8767 /// Stable document identities, parallel to items; empty for ordinary navigation.
8768 pub document_keys: Vec<String>,
8769 pub items: Vec<String>,
8770 pub icons: Vec<Option<String>>,
8771 /// A trailing accessory per row: an unread count, a status. Rendered right-aligned and
8772 /// de-emphasized, opposite the label. Parallel to `items`; `None` draws nothing.
8773 pub badges: Vec<Option<String>>,
8774 /// A trailing symbol accessory per row, in the same slot as [`Self::badges`] and drawn
8775 /// after it: a bundled image name resolved the way [`Self::icons`] is. This is what a
8776 /// row-level status glyph rides on (a starred page's star) where `badges` carries only
8777 /// text. Parallel to `items`; `None` draws nothing.
8778 pub badge_icons: Vec<Option<String>>,
8779 /// The tint for [`Self::badge_icons`], parallel to `items`. `None` leaves the glyph at
8780 /// the backend's neutral template tint; a status glyph that means something (a yellow
8781 /// star) names its own color here, exactly as [`Self::tints`] does for the leading icon.
8782 pub badge_tints: Vec<Option<Ink>>,
8783 /// A per-row icon tint (docs/vectors.md): the row's glyph recolored to this instead of
8784 /// the backend's neutral template tint. Parallel to `items`; `None` keeps the default.
8785 pub tints: Vec<Option<Ink>>,
8786 /// A section header introducing the row at the same index. `Some` opens a new group
8787 /// before that row; `None` continues the current one. Parallel to `items`, so adding a
8788 /// header never shifts the selection indices the rows are addressed by.
8789 pub sections: Vec<Option<String>>,
8790 /// A per-row context menu (docs/menus.md): shown on secondary-click / long-press on
8791 /// that row, the same [`crate::MenuItem`] model as everywhere else: items carry
8792 /// registered action ids, so a chosen entry dispatches [`crate::Event::MenuAction`]
8793 /// exactly like a piece context menu. Parallel to `items`; empty = no menu.
8794 pub menus: Vec<Vec<crate::MenuItem>>,
8795 /// Which rows drag to reorder (docs/navigation.md "Reordering sidebar destinations"),
8796 /// parallel to `items`; empty when the sidebar does not reorder. A row moves only
8797 /// within the run of movable rows around it, which a section header or a fixed row
8798 /// ends. A toolkit whose `Cap::NavReorder` is `Native` drags the rows in its own
8799 /// sidebar and reports a drop as [`crate::Event::ListReorder`] in item indices: `from`
8800 /// is the moved row, `to` the row whose position it takes, in the order before the move.
8801 pub movable: Vec<bool>,
8802 /// The sidebar regroups (docs/navigation.md "Moving rows between sections"): a movable
8803 /// row may also cross section headers, into any section whose rows are all movable. A
8804 /// toolkit whose `Cap::NavReorder` is `Native` offers those drops too and reports every
8805 /// drop as [`crate::Event::NavRegroup`] instead of [`crate::Event::ListReorder`]. `false`
8806 /// keeps [`Self::movable`]'s run rule.
8807 pub regroup: bool,
8808 /// Which movable rows keep the app's sorted order within their own section, parallel to
8809 /// `items`; empty when the sidebar does not regroup. Under [`Self::regroup`], a sorted
8810 /// row drops only into another section: no gap in its own section is offered.
8811 pub sorted: Vec<bool>,
8812 pub selected: Option<usize>,
8813 }
8814 #[derive(Clone, Debug, PartialEq)]
8815 // `Items` carries every row array; a patch travels boxed (`Box<dyn Any>`) and lives for one
8816 // update, so the variants' size difference costs nothing worth an indirection.
8817 #[allow(clippy::large_enum_variant)]
8818 pub enum NavMenuPatch {
8819 /// Active icon overlays by row index: None spins, Some(0..=1) fills a circle.
8820 /// Rows absent from this complete snapshot have no overlay. Does not relayout rows.
8821 /// Currently rendered by AppKit/UIKit; other backends may ignore this decoration.
8822 IconProgress(Vec<(usize, Option<f64>)>),
8823 /// Programmatic highlight sync: toolkits apply without re-emitting
8824 /// `SelectionChanged` (the `TextField` `from_native` echo rule).
8825 Selected(Option<usize>),
8826 /// The item set changed (data-driven `nav().items(signal, …)`): rebuild the rows
8827 /// from these labels/icons, then apply `selected` (docs/navigation.md). Applied without
8828 /// re-emitting `SelectionChanged`.
8829 ///
8830 /// `rows_changed` is `Some` when the rows themselves are the ones already shown (same
8831 /// keys, sections and row menus) and only these rows' title, icon, tint or badge moved:
8832 /// a count ticking, a language change. A backend updates those rows in place (a tab's
8833 /// badge, a menu item's title) rather than rebuilding, which on most platforms re-lays
8834 /// the bar and replays its selection animation; one that cannot rebuilds as for `None`.
8835 Items {
8836 rows_changed: Option<Box<[usize]>>,
8837 document_keys: Box<[String]>,
8838 items: Vec<String>,
8839 icons: Vec<Option<String>>,
8840 badges: Vec<Option<String>>,
8841 badge_icons: Vec<Option<String>>,
8842 badge_tints: Vec<Option<Ink>>,
8843 sections: Vec<Option<String>>,
8844 tints: Vec<Option<Ink>>,
8845 menus: Vec<Vec<crate::MenuItem>>,
8846 /// [`NavMenuProps::movable`] for the new rows.
8847 movable: Vec<bool>,
8848 /// [`NavMenuProps::sorted`] for the new rows ([`NavMenuProps::regroup`] holds for
8849 /// the sidebar's life).
8850 sorted: Vec<bool>,
8851 selected: Option<usize>,
8852 },
8853 }
8854
8855 /// How a recycling list sizes its rows (docs/list.md).
8856 #[derive(Clone, Copy, Debug, PartialEq, Default)]
8857 pub enum RowHeight {
8858 /// Every row is this tall, a true layout boundary; the fastest path.
8859 Uniform(f64),
8860 /// Rows self-size from their content (host re-measures on change; slower).
8861 #[default]
8862 Automatic,
8863 }
8864
8865 /// Configure a navigation sidebar's native pull-to-refresh control. Not a synthetic pan:
8866 /// supported toolkits own gesture arbitration and the progress indicator. A false state
8867 /// ends a pull, including a request the application declines. Never emits an event.
8868 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
8869 pub struct RefreshPatch {
8870 pub refreshing: bool,
8871 }
8872
8873 /// Native recycling list (docs/list.md). The host owns scrolling + cell reuse; Day supplies
8874 /// row content on demand through the injected `ListSource` (see `Toolkit::attach_list`).
8875 #[derive(Clone, Debug, Default, PartialEq)]
8876 pub struct ListProps {
8877 /// Whether the app handles row activation. Do not claim activation keys when false.
8878 pub activatable: bool,
8879 pub row_height: RowHeight,
8880 /// Whether the native list reports row selection (`Event::SelectionChanged` with the row).
8881 pub selectable: bool,
8882 /// Whether the native list allows selecting several rows at once. Where honored
8883 /// (docs/list.md has the matrix), every selection change reports the full set via
8884 /// `Event::SelectionSet`; single-selection backends keep reporting
8885 /// `Event::SelectionChanged` and treat this as `selectable`.
8886 pub multi_select: bool,
8887 /// Whether rows can be drag-reordered. The toolkit enables its native drag machinery and
8888 /// drives `ListSource::reorder` (validate via `can_move`, commit via `move_row`);
8889 /// probe `Cap::ListReorder` for per-backend support (docs/list.md).
8890 pub reorderable: bool,
8891 /// Whether rows can be deleted by the platform's own delete gesture: a trailing swipe on
8892 /// iOS and ArkUI, an `ItemTouchHelper` swipe on Android. The toolkit drives
8893 /// `ListSource::delete` (offer via `can_delete`, commit via `delete_row`); probe
8894 /// `Cap::ListDelete` for per-backend support (docs/list.md). Desktop toolkits have no such
8895 /// gesture and answer `Unsupported`; an app that must delete everywhere pairs this with an
8896 /// explicit control (a menu item, a button) rather than relying on the swipe.
8897 pub deletable: bool,
8898 /// The label on that affordance, already localized by the app. A toolkit cannot invent
8899 /// translated text (it has no access to the app's catalog), so the string arrives with
8900 /// the props. Empty means "no text": each backend falls back to its platform's own
8901 /// wordless idiom (a trash glyph), which works in every language.
8902 pub delete_label: String,
8903 /// The rows offer edge swipe actions (docs/list.md) through the injected
8904 /// `ListSource::swipe` (offer via `actions_at`, commit via `perform`); probe
8905 /// [`crate::Cap::ListSwipeActions`] for per-backend support. A backend without the
8906 /// affordance never shows one; an app that must offer the command everywhere
8907 /// pairs the swipe with an explicit control, exactly as `deletable` documents.
8908 pub swipe_actions: bool,
8909 /// Row separators, drawn by the host at the row boundary (docs/list.md), so they
8910 /// align with the native selection and ride the platform's own row animations (a
8911 /// macOS/iOS swipe slides the row content past a stationary separator, exactly as
8912 /// Mail's does). `None` keeps each platform's own default (iOS draws them, the
8913 /// desktops don't); `Some(true)`/`Some(false)` forces. A backend without a separator
8914 /// mechanism ignores a force (the matrix in docs/list.md says which); rows there
8915 /// separate by their pitch alone.
8916 pub separators: Option<bool>,
8917 /// The list starts in the platform's editing mode (docs/list.md): delete controls on
8918 /// the rows `deletable` offers, reorder grips on the rows `reorderable` moves, and a
8919 /// tap that still activates. Later changes arrive as [`ListPatch::Editing`]. Probe
8920 /// [`crate::Cap::ListEditing`]; a backend without an editing mode ignores it.
8921 pub editing: bool,
8922 /// The rows fall into sections, each opened by a header row (docs/list.md
8923 /// "Sections"): `ListSource::is_header` says which rows. Probe
8924 /// [`crate::Cap::ListSections`] for whether headers float natively.
8925 pub sections: bool,
8926 /// Draw the rows as the platform's inset grouped list (docs/list.md "Appearance"):
8927 /// rounded groups set in from the edges on a grouped background, as iOS Settings and
8928 /// Safari's History draw them. ios-uikit (`UITableViewStyleInsetGrouped`) and
8929 /// macos-appkit (`NSTableViewStyleInset`); the other toolkits draw their plain list.
8930 pub inset_grouped: bool,
8931 }
8932
8933 /// One row-level result-set change. Indexes are sequential (each delta describes the
8934 /// set as the previous ones left it), so a host applies them one at a time (or falls back
8935 /// to a reload; the source's snapshot already holds the final state either way).
8936 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
8937 pub enum RowDelta {
8938 Insert(usize),
8939 Remove(usize),
8940 Move(usize, usize),
8941 }
8942
8943 /// Immutable-at-realize props of a `kinds::TREE` host (docs/tree.md). Everything that
8944 /// changes after realize flows through [`TreePatch`] or the injected `TreeSource`.
8945 #[derive(Clone, Debug, PartialEq)]
8946 pub struct TreeProps {
8947 /// Two-level sectioned list: root branches are non-selectable headings.
8948 pub section_headers: bool,
8949 pub row_height: RowHeight,
8950 /// Rows highlight and report selection ([`crate::Event::TreeSelection`]).
8951 pub selectable: bool,
8952 /// Several rows may be selected at once; every change reports the full token set.
8953 pub multi_select: bool,
8954 /// Rows drag to a new parent/position through the platform's own mechanism, driving
8955 /// `TreeSource::moves`. Probe [`crate::Cap::TreeMove`] for support.
8956 pub movable: bool,
8957 /// Indentation per depth level, in points. `None` = the platform's default step.
8958 pub indent: Option<f64>,
8959 }
8960
8961 /// Post-realize changes to a `kinds::TREE` host (docs/tree.md). Token-addressed
8962 /// throughout; see [`crate::TreeSource`] for why indices cannot address tree rows.
8963 #[derive(Clone, Debug, PartialEq)]
8964 pub enum TreePatch {
8965 /// The node set changed (count/order/parentage/content): the host re-queries its
8966 /// `TreeSource`. Expansion and selection survive by token (docs/tree.md).
8967 Reload,
8968 /// Programmatically disclose (`true`) or collapse (`false`) one row. Applied without
8969 /// re-emitting [`crate::Event::TreeExpanded`] (the from-native echo rule).
8970 Expand(u64, bool),
8971 /// Programmatic selection sync (tokens; empty = clear), applied without re-emitting
8972 /// [`crate::Event::TreeSelection`].
8973 Selected(Vec<u64>),
8974 /// Scroll this row into view, realizing it if needed. The piece has already expanded
8975 /// the row's ancestors (through the app's expansion signal) before issuing this.
8976 Reveal(u64),
8977 }
8978
8979 #[derive(Clone, Debug, PartialEq)]
8980 pub enum ListPatch {
8981 /// The row set changed (count/order/content): the host re-queries its `ListSource`.
8982 Reload,
8983 /// The row set changed by exactly these deltas: a host that can, animates each row
8984 /// in, out, or across; one that cannot treats this as [`ListPatch::Reload`]. The
8985 /// data source answers with the final state throughout.
8986 Splice(Vec<RowDelta>),
8987 /// An `Automatic`-height row was re-laid at a new height after its first layout (its
8988 /// text changed, a wrapped line appeared, the backend corrected its width): the host
8989 /// gives the row bound to physical cell `cell` (the handle `ListSource::bind_row` got,
8990 /// as `usize`) the new `height`, padding included, the same value
8991 /// `ListSource::cell_height` now answers for it.
8992 ///
8993 /// Sent from inside a day-core layout pass, with the tree borrowed: a host applies it
8994 /// after the pass (posted to its main loop), never by asking the source anything
8995 /// synchronously, which would read a `0.0` height (docs/list.md "Row heights").
8996 RowSizeInvalidated { cell: usize, height: f64 },
8997 /// Imperatively scroll the native list so its last row is fully visible (a chat timeline
8998 /// sticking to the newest message). No-op when the list is empty (docs/list.md).
8999 ScrollToEnd,
9000 /// Imperatively scroll the native list so this row is visible, realizing it if needed
9001 /// (docs/list.md). Clamped to the row count; no-op when the list is empty.
9002 ScrollToRow(usize),
9003 /// Programmatic selection sync (row indices; empty = clear): toolkits apply without
9004 /// re-emitting a selection event, like every other programmatic sync.
9005 Selected(Vec<usize>),
9006 /// Enter (`true`) or leave (`false`) the platform's list editing mode, animated
9007 /// (docs/list.md, [`ListProps::editing`]). Ignored where `Cap::ListEditing` is
9008 /// `Unsupported`.
9009 Editing(bool),
9010 }
9011}
9012
9013// ---------------------------------------------------------------------------
9014// Imperative presentation (docs/dialogs.md)
9015// ---------------------------------------------------------------------------
9016
9017/// Sharing (docs/sharing.md): what [`Toolkit::share`] presents.
9018pub mod share {
9019 use crate::Symbol;
9020
9021 /// A share request: the page or link to share, and the app's own actions to offer beside
9022 /// the system's targets.
9023 #[derive(Clone, Debug, Default, PartialEq)]
9024 pub struct ShareSpec {
9025 /// The URL handed to the chosen target.
9026 pub url: String,
9027 /// Its title: the subject of a mail, the header of the chooser where it shows one.
9028 pub title: String,
9029 /// The app's actions, in order (`Cap::ShareActions`).
9030 pub actions: Vec<ShareAction>,
9031 }
9032
9033 /// One of the app's actions in a share chooser.
9034 #[derive(Clone, Debug, PartialEq)]
9035 pub struct ShareAction {
9036 /// The dispatch id a choice reports, as `Event::MenuAction(id)`.
9037 pub id: u64,
9038 /// The action's name, already localized.
9039 pub title: String,
9040 /// Its glyph, where the chooser draws one.
9041 pub symbol: Option<Symbol>,
9042 }
9043}
9044
9045pub mod present {
9046 /// A dialog button's semantic role: styling + default/cancel placement on each toolkit.
9047 #[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
9048 pub enum ButtonRole {
9049 #[default]
9050 Default,
9051 Cancel,
9052 Destructive,
9053 }
9054
9055 #[derive(Clone, Debug, PartialEq)]
9056 pub struct PresentButton {
9057 pub label: String,
9058 pub role: ButtonRole,
9059 }
9060
9061 /// A named group of file extensions for a file dialog (e.g. "Text" → `["txt", "md"]`).
9062 /// An empty `extensions` list means "all files".
9063 #[derive(Clone, Debug, PartialEq, Default)]
9064 pub struct FileFilter {
9065 pub name: String,
9066 pub extensions: Vec<String>,
9067 }
9068
9069 /// What a backend should present for a `req`. Kept toolkit-agnostic; the pieces layer
9070 /// maps a chosen button index back to a typed payload.
9071 #[derive(Clone, Debug, PartialEq)]
9072 pub enum PresentSpec {
9073 /// Alert / confirmation / action sheet: title + optional message + ordered buttons.
9074 /// `sheet` = present from the bottom on mobile (desktop falls back to an alert).
9075 Dialog {
9076 title: String,
9077 message: Option<String>,
9078 buttons: Vec<PresentButton>,
9079 sheet: bool,
9080 },
9081 /// A dialog with a single text field.
9082 Prompt {
9083 title: String,
9084 message: Option<String>,
9085 placeholder: String,
9086 initial: String,
9087 ok: String,
9088 cancel: String,
9089 },
9090 /// Native "open file" picker (docs/files.md). The backend must answer with
9091 /// `PresentResult::Files` whose entries are **readable local paths**: desktop returns
9092 /// the chosen path directly; iOS/Android copy the selection into app storage first, so
9093 /// the pieces layer can read it with `std::fs` regardless of platform. `multiple` lets
9094 /// the user pick several files at once; the answer then carries every chosen path, in
9095 /// the picker's order. A backend that cannot select more than one file still answers
9096 /// with the single pick.
9097 OpenFile {
9098 title: String,
9099 filters: Vec<FileFilter>,
9100 multiple: bool,
9101 },
9102 /// Native "choose folder" picker (docs/files.md). The backend answers with
9103 /// `PresentResult::Files` holding the one chosen directory path, or `Dismissed`. Only
9104 /// backends answering [`Cap::FolderDialog`](crate::Cap::FolderDialog) as `Native` show a
9105 /// chooser; the others resolve the request as `Dismissed` at once, so the await never hangs.
9106 OpenFolder { title: String },
9107 /// Native "save file" picker (docs/files.md). `src_path` is a Day-written temp file
9108 /// holding the bytes to save; iOS/Android deliver it to the chosen destination natively,
9109 /// and the pieces layer best-effort copies it to a chosen local path otherwise.
9110 SaveFile {
9111 title: String,
9112 suggested_name: String,
9113 src_path: String,
9114 filters: Vec<FileFilter>,
9115 },
9116 }
9117
9118 /// The user's answer to a presentation.
9119 #[derive(Clone, Debug, PartialEq)]
9120 pub enum PresentResult {
9121 /// A dialog button at `index` (in spec order) was chosen.
9122 Button(i64),
9123 /// A prompt was confirmed with `text`.
9124 Text(String),
9125 /// One or more file locators chosen from an open/save picker (docs/files.md). Each is a
9126 /// local filesystem path or, on Android save, a `content://` URI.
9127 Files(Vec<String>),
9128 /// Dismissed without choosing (tap-outside / Esc / cancel gesture).
9129 Dismissed,
9130 }
9131
9132 /// The unit-separator that joins string lists across the C ABI (Qt shim / Android JNI), the
9133 /// same encoding the nav menu, combobox, and dialog-button shims use.
9134 pub const UNIT_SEP: char = '\u{1f}';
9135
9136 std::thread_local! {
9137 /// An app-writable scratch directory. Backends whose OS temp dir isn't app-writable
9138 /// (Android → `getCacheDir()`) set this at startup; elsewhere it stays `None` and callers
9139 /// fall back to `std::env::temp_dir()`.
9140 // False positive, and only when checking an android target: the initializer already is
9141 // the `const` block the lint asks for. Android's TLS model makes the macro expand to a
9142 // form clippy reads as lazy, so the suggestion is unfollowable as well as unneeded.
9143 #[allow(clippy::missing_const_for_thread_local)]
9144 static APP_TEMP_DIR: std::cell::RefCell<Option<std::path::PathBuf>> =
9145 const { std::cell::RefCell::new(None) };
9146 }
9147
9148 /// Record an app-writable scratch directory (see [`app_temp_dir`]). Called by a backend at
9149 /// startup when the OS temp dir isn't writable by the app (Android).
9150 pub fn set_app_temp_dir(dir: impl Into<std::path::PathBuf>) {
9151 APP_TEMP_DIR.with(|d| *d.borrow_mut() = Some(dir.into()));
9152 }
9153
9154 /// An app-writable scratch directory: the backend-supplied one, else `std::env::temp_dir()`.
9155 /// Used by the file-save flow (docs/files.md) to stage bytes before the native save picker.
9156 #[must_use]
9157 pub fn app_temp_dir() -> std::path::PathBuf {
9158 APP_TEMP_DIR.with(|d| {
9159 d.borrow().clone().unwrap_or_else(|| {
9160 #[cfg(target_arch = "wasm32")]
9161 {
9162 // A browser has no filesystem and std's `temp_dir()` panics on wasm. A
9163 // nominal path keeps join/display plumbing alive; actual reads and writes
9164 // fail with ordinary io errors the file flows already surface.
9165 std::path::PathBuf::from("/day-tmp")
9166 }
9167 #[cfg(not(target_arch = "wasm32"))]
9168 std::env::temp_dir()
9169 })
9170 })
9171 }
9172
9173 /// The web build's file bytes (wasm32-unknown-unknown only): a browser has no filesystem,
9174 /// so the open/save flows carry bytes through this per-page store instead of `std::fs`:
9175 /// day-toolkit-dom writes a picked file's bytes here and answers with its virtual path; the pieces
9176 /// layer stages save bytes here for the shim to download. Paths are plain strings under
9177 /// `/day-web/`; lifetimes are one picker round-trip (the flows remove what they stage).
9178 #[cfg(all(target_family = "wasm", target_os = "unknown"))]
9179 pub mod web_files {
9180 std::thread_local! {
9181 static FILES: std::cell::RefCell<std::collections::HashMap<String, Vec<u8>>> =
9182 std::cell::RefCell::new(std::collections::HashMap::new());
9183 }
9184
9185 /// Store `bytes` under `path` (replacing any prior content).
9186 pub fn write(path: &str, bytes: Vec<u8>) {
9187 FILES.with(|f| f.borrow_mut().insert(path.to_string(), bytes));
9188 }
9189
9190 /// The bytes at `path`, if present.
9191 #[must_use]
9192 pub fn read(path: &str) -> Option<Vec<u8>> {
9193 FILES.with(|f| f.borrow().get(path).cloned())
9194 }
9195
9196 /// Drop `path`'s bytes.
9197 pub fn remove(path: &str) {
9198 FILES.with(|f| {
9199 f.borrow_mut().remove(path);
9200 });
9201 }
9202 }
9203
9204 impl PresentResult {
9205 /// Flat wire tag for the C ABI (Qt shim / Android JNI): 0 dismissed, 1 button, 2 text,
9206 /// 3 files (`text` is the chosen locators joined by the unit separator).
9207 pub fn decode(tag: i32, index: i64, text: String) -> PresentResult {
9208 match tag {
9209 1 => PresentResult::Button(index),
9210 2 => PresentResult::Text(text),
9211 3 => PresentResult::Files(
9212 text.split(UNIT_SEP)
9213 .filter(|s| !s.is_empty())
9214 .map(str::to_string)
9215 .collect(),
9216 ),
9217 _ => PresentResult::Dismissed,
9218 }
9219 }
9220 }
9221
9222 impl PresentSpec {
9223 /// Backend-facing flattening for the C ABI: `(title, message, button labels, button
9224 /// roles as ints, sheet-or-prompt fields)`. Pure-Rust backends read the enum directly.
9225 #[must_use]
9226 pub fn title(&self) -> &str {
9227 match self {
9228 PresentSpec::Dialog { title, .. }
9229 | PresentSpec::Prompt { title, .. }
9230 | PresentSpec::OpenFile { title, .. }
9231 | PresentSpec::OpenFolder { title }
9232 | PresentSpec::SaveFile { title, .. } => title,
9233 }
9234 }
9235 #[must_use]
9236 pub fn message(&self) -> Option<&str> {
9237 match self {
9238 PresentSpec::Dialog { message, .. } | PresentSpec::Prompt { message, .. } => {
9239 message.as_deref()
9240 }
9241 _ => None,
9242 }
9243 }
9244 /// Button labels joined with [`UNIT_SEP`], the encoding the nav menu and combobox
9245 /// shims already use for string lists.
9246 #[must_use]
9247 pub fn buttons_joined(&self) -> String {
9248 match self {
9249 PresentSpec::Dialog { buttons, .. } => buttons
9250 .iter()
9251 .map(|b| b.label.as_str())
9252 .collect::<Vec<_>>()
9253 .join(&UNIT_SEP.to_string()),
9254 PresentSpec::Prompt { ok, cancel, .. } => format!("{ok}{UNIT_SEP}{cancel}"),
9255 _ => String::new(),
9256 }
9257 }
9258 /// Button roles as ints (0 default, 1 cancel, 2 destructive), joined with commas.
9259 #[must_use]
9260 pub fn roles_joined(&self) -> String {
9261 let roles: Vec<i32> = match self {
9262 PresentSpec::Dialog { buttons, .. } => {
9263 buttons.iter().map(|b| b.role as i32).collect()
9264 }
9265 PresentSpec::Prompt { .. } => {
9266 vec![ButtonRole::Default as i32, ButtonRole::Cancel as i32]
9267 }
9268 _ => vec![],
9269 };
9270 roles
9271 .iter()
9272 .map(std::string::ToString::to_string)
9273 .collect::<Vec<_>>()
9274 .join(",")
9275 }
9276
9277 // --- file-dialog accessors (docs/files.md) ---
9278
9279 /// The file filters, if this is a file dialog.
9280 #[must_use]
9281 pub fn filters(&self) -> &[FileFilter] {
9282 match self {
9283 PresentSpec::OpenFile { filters, .. } | PresentSpec::SaveFile { filters, .. } => {
9284 filters
9285 }
9286 _ => &[],
9287 }
9288 }
9289 /// Whether an open-file dialog lets the user pick several files (`false` for every
9290 /// other spec).
9291 #[must_use]
9292 pub fn multiple(&self) -> bool {
9293 matches!(self, PresentSpec::OpenFile { multiple: true, .. })
9294 }
9295 /// The suggested file name for a save dialog (empty otherwise).
9296 #[must_use]
9297 pub fn suggested_name(&self) -> &str {
9298 match self {
9299 PresentSpec::SaveFile { suggested_name, .. } => suggested_name,
9300 _ => "",
9301 }
9302 }
9303 /// The Day-written temp source path for a save dialog (empty otherwise).
9304 #[must_use]
9305 pub fn src_path(&self) -> &str {
9306 match self {
9307 PresentSpec::SaveFile { src_path, .. } => src_path,
9308 _ => "",
9309 }
9310 }
9311 /// Filters flattened for the C ABI: each filter is `name|ext1,ext2`, joined by
9312 /// [`UNIT_SEP`]. A trailing `|` (no extensions) means "all files". Empty when unfiltered.
9313 #[must_use]
9314 pub fn filters_joined(&self) -> String {
9315 self.filters()
9316 .iter()
9317 .map(|f| format!("{}|{}", f.name, f.extensions.join(",")))
9318 .collect::<Vec<_>>()
9319 .join(&UNIT_SEP.to_string())
9320 }
9321 }
9322}
9323
9324// ---------------------------------------------------------------------------
9325// The Toolkit trait (§8.1)
9326// ---------------------------------------------------------------------------
9327
9328/// Timing supplied by a native display scheduler. Seconds on a monotonic clock; its epoch
9329/// is platform-specific. `target_timestamp` is absent when the platform cannot predict presentation.
9330#[derive(Clone, Copy, Debug, PartialEq)]
9331pub struct FrameStamp {
9332 pub timestamp: f64,
9333 pub target_timestamp: Option<f64>,
9334}
9335impl FrameStamp {
9336 #[must_use]
9337 pub fn new(timestamp: f64) -> Self {
9338 Self {
9339 timestamp,
9340 target_timestamp: None,
9341 }
9342 }
9343}
9344/// A one-shot native frame callback, always delivered asynchronously on the UI thread.
9345pub type FrameCallback = Box<dyn FnOnce(FrameStamp)>;
9346/// Cancels a pending callback and releases its native registration. UI-thread only, idempotent
9347/// in effect, and safe during/after delivery. Dropping without calling is allowed after delivery.
9348pub type CancelFrame = Box<dyn FnOnce()>;
9349
9350/// The margins and minimum height a native list gives each row ([`Toolkit::list_row_metrics`],
9351/// docs/list.md "Row metrics"): a `UITableView` cell's layout margins, a Material list item's
9352/// 16dp sides and 56dp height.
9353#[derive(Clone, Copy, Debug, Default, PartialEq)]
9354pub struct RowMetrics {
9355 /// Space between the row's edges and its content.
9356 pub insets: Insets,
9357 /// The least height a row takes, margins included; content centers vertically in it.
9358 pub min_height: f64,
9359}
9360
9361pub trait Toolkit: Sized + 'static {
9362 // `'static` so a handle clone can cross the object-safe TreeOps boundary boxed as `Any`
9363 // (`node_handle_any`, the tweaks door, docs/tweaks.md).
9364 type Handle: Clone + 'static;
9365
9366 /// Request one frame for the window containing `host`. Never call inline. Each native source
9367 /// must stop after delivery unless requested again; no polling timer. Hidden/unmapped windows
9368 /// may defer delivery until visible. Native callbacks must reach the UI thread before calling
9369 /// Rust. The returned closure cancels safely, including when the window has closed.
9370 /// The mock intentionally stays pending: tests inject a manual scheduler in day-core.
9371 fn request_frame(&mut self, _host: &Self::Handle, _cb: FrameCallback) -> CancelFrame {
9372 Box::new(|| {})
9373 }
9374
9375 fn capability(&self, _cap: Cap) -> Support {
9376 Support::Unsupported
9377 }
9378
9379 // node lifecycle
9380 fn realize(&mut self, kind: PieceKind, props: &dyn Any, id: NodeId) -> Self::Handle;
9381 fn update(
9382 &mut self,
9383 h: &Self::Handle,
9384 kind: PieceKind,
9385 patch: &dyn Any,
9386 anim: Option<&AnimSpec>,
9387 );
9388 /// Called from the turn-boundary release queue; backends may defer destruction further.
9389 fn release(&mut self, h: Self::Handle);
9390 /// Give a satellite piece a chance to drop its own per-view state, immediately before
9391 /// [`release`](Toolkit::release) frees `h` (§15.2).
9392 ///
9393 /// A backend that hosts third-party pieces implements this by looking `kind` up in its renderer
9394 /// registry and calling that piece's `release` hook. Defaulted to nothing: a backend with no
9395 /// registry has nothing to dispatch, and one that has not wired this yet leaves piece
9396 /// teardown unrun rather than failing to build.
9397 fn release_piece(&mut self, _kind: PieceKind, _h: &Self::Handle) {}
9398
9399 // tree
9400 fn insert(&mut self, parent: &Self::Handle, child: &Self::Handle, index: usize);
9401 fn remove(&mut self, parent: &Self::Handle, child: &Self::Handle);
9402 /// Put `child` at index `to` among `parent`'s native children: day's z-order resync, which
9403 /// walks the whole sibling row and asks for every position in turn. A child already at `to`
9404 /// must therefore cost nothing: a backend that re-parents unconditionally pays for the
9405 /// untouched siblings too, and where re-parenting means detach-then-add (no `ViewGroup` move
9406 /// primitive on Android) the detach resigns the focus of everything inside the subtree,
9407 /// which is how a text field being typed into loses the keyboard (docs/focus.md).
9408 fn move_child(&mut self, parent: &Self::Handle, child: &Self::Handle, to: usize);
9409
9410 // geometry (§7): frames are in the nearest realized native ancestor's space, in points.
9411 fn measure(&mut self, h: &Self::Handle, kind: PieceKind, p: Proposal) -> Size;
9412 /// Distance from the top of the widget's frame to its first text baseline, in points, when
9413 /// the widget is `size` (docs/baseline.md). `None` ⇒ it has no text baseline (an image, a
9414 /// slider, a bare container) and a baseline-aligned row falls back to box alignment for it.
9415 ///
9416 /// This is a measurement, not a layout mode: day places every frame itself (§7.1) and never
9417 /// hands a row to a native baseline-aligning container, so what it needs from the toolkit is
9418 /// where the text sits inside the box. Backends that cannot answer keep the default and rows
9419 /// stay centered, which is what every row did before this existed.
9420 fn first_baseline(&mut self, _h: &Self::Handle, _kind: PieceKind, _size: Size) -> Option<f64> {
9421 None
9422 }
9423 fn set_frame(&mut self, h: &Self::Handle, frame: Rect, anim: Option<&AnimSpec>);
9424
9425 // animatable visual channels (§8.4): cheap per-node opacity + transform that don't relayout.
9426 // Defaulted no-ops so backends adopt them incrementally; `anim = Some` ⇒ animate to the value
9427 // on the toolkit's own compositor, `None` ⇒ set instantly.
9428 fn set_opacity(&mut self, _h: &Self::Handle, _opacity: f64, _anim: Option<&AnimSpec>) {}
9429 fn set_transform(
9430 &mut self,
9431 _h: &Self::Handle,
9432 _t: Transform,
9433 _size: Size,
9434 _anim: Option<&AnimSpec>,
9435 ) {
9436 }
9437
9438 // text selection (docs/text.md): make this node's text user-selectable (copy/drag). Applied
9439 // once from the `.selectable()` modifier (day-pieces) to the widget it wraps (a `label`'s
9440 // native text view, most usefully). Unmanaged: Day sets it here and never patches it, so it
9441 // survives text updates. The default no-op means a backend without a selection affordance
9442 // silently leaves the text unselectable.
9443 //
9444 // Returns `Some(replacement)` when the toolkit had to rebuild the widget as a different
9445 // native class to gain a selection affordance (UIKit: `UILabel` has none, so the label
9446 // becomes a read-only `UITextView`); day-core re-points the node's handle at the
9447 // replacement, so later patches and layout reach the widget that is actually on screen.
9448 // Every property-flip backend returns `None`.
9449 fn set_selectable(&mut self, _h: &Self::Handle, _selectable: bool) -> Option<Self::Handle> {
9450 None
9451 }
9452
9453 /// Give one widget its reading direction (the `.layout_direction()` modifier,
9454 /// docs/localization.md "Direction of a subtree"). day-core calls this for every realized
9455 /// node inside a subtree whose direction differs from the app's, and again with the app's
9456 /// direction when an override is lifted, so the setter is idempotent.
9457 ///
9458 /// Day mirrors the frames itself, so this is about what happens inside the widget: a
9459 /// label's or field's base writing direction and which edge `TextAlign::Leading` means, the
9460 /// side a slider fills from, which way a disclosure chevron points, where a list row puts
9461 /// its accessory. It must never move a child Day has placed. Where the platform's
9462 /// direction property also mirrors child coordinates (XAML `FlowDirection` on a panel,
9463 /// Android `layoutDirection` on a view group), apply it to leaf controls only. Do not rely
9464 /// on native inheritance: Day calls this per node.
9465 ///
9466 /// The default does nothing, which leaves the widget in the app's direction.
9467 fn set_layout_direction(
9468 &mut self,
9469 _h: &Self::Handle,
9470 _kind: PieceKind,
9471 _direction: LayoutDirection,
9472 ) {
9473 }
9474
9475 // text entry (docs/textfield.md): how a `text_field` takes its text: hidden characters,
9476 // read-only, the keyboard and autofill purpose, the action key, the length bound. Called
9477 // once after `realize` when a field asks for anything but the defaults, and again with the
9478 // whole set whenever a reactive member changes, so the setter is idempotent.
9479 //
9480 // Returns `Some(replacement)` when hiding the characters takes a different native class
9481 // (AppKit: `NSSecureTextField`; WinUI: `PasswordBox`), the same contract as
9482 // `set_selectable`: the backend carries the text, the placeholder and its own event wiring
9483 // over, takes the old widget's place in the native tree, and day-core re-points the node's
9484 // handle. Required, with no default: a backend that left this out would show a password in
9485 // the clear. A member the toolkit has no notion of (an action key on a desktop) is ignored.
9486 fn set_input_traits(&mut self, h: &Self::Handle, traits: &InputTraits) -> Option<Self::Handle>;
9487
9488 // pointer shape (docs/cursor.md): the cursor to show while the pointer is over this node
9489 // and its descendants, from the `.cursor()` modifier. Called again whenever a reactive
9490 // cursor changes, so the setter is idempotent and cheap; `Cursor::Default` releases the
9491 // node. The default no-op is a backend with no pointer API to reach (`Cap::Cursor`
9492 // answers `Unsupported` there).
9493 fn set_cursor(&mut self, _h: &Self::Handle, _cursor: Cursor) {}
9494
9495 /// Show or hide a retained subtree, including its input and accessibility participation.
9496 /// The layout and reactive scope stay alive while hidden.
9497 fn set_presented(&mut self, _h: &Self::Handle, _visible: bool) {}
9498
9499 /// Attach overscroll delivery to a refresh host; the caller owns the mounted scope.
9500 fn attach_refresh(&mut self, _h: &Self::Handle, _host: NodeId) {}
9501
9502 // scroll (§7.6)
9503 fn set_scroll_content(&mut self, _h: &Self::Handle, _content: Size) {}
9504 // The room a classic (non-overlay) scroll bar takes out of a scroll view's content area
9505 // while the content overflows along `vertical`'s axis: its width for a vertical scroll, its
9506 // height for a horizontal one (docs/scroll.md). Day lays overflowing content out that much
9507 // narrower, so it fits beside the bar instead of reaching under it. 0 — the default — is
9508 // every backend whose bars overlay the content (AppKit, GTK, UIKit, Android, XAML, DOM).
9509 fn scroll_bar_inset(&mut self, _h: &Self::Handle, _vertical: bool) -> f64 {
9510 0.0
9511 }
9512 // The margins and minimum height the platform's own list gives a row (docs/list.md "Row
9513 // metrics"), asked of list `h` each time day-core lays a row. Day insets the row's content by
9514 // the margins and keeps it at least that tall, so a row reads at the platform's size without
9515 // the app padding it per platform. Zero — the default — leaves the row to its content.
9516 fn list_row_metrics(&mut self, _h: &Self::Handle) -> RowMetrics {
9517 RowMetrics::default()
9518 }
9519 fn scroll_to(&mut self, _h: &Self::Handle, _target: Rect, _animated: bool) {}
9520 /// Scroll a native navigation menu to its top or bottom without changing selection.
9521 /// The widget owns its content extent. Return false when the handle is unsupported.
9522 fn nav_scroll_to_edge(&mut self, _h: &Self::Handle, _bottom: bool) -> bool {
9523 false
9524 }
9525 fn scroll_offset(&mut self, _h: &Self::Handle) -> Point {
9526 Point::ZERO
9527 }
9528 /// Scroll list `h` to a row, or to its end, with the alignment and animation asked for
9529 /// (docs/list.md "Programmatic scrolling"). Answer `true` once handled. The default
9530 /// answers `false`, and day-core then sends the plain [`props::ListPatch::ScrollToRow`] or
9531 /// [`props::ListPatch::ScrollToEnd`] instead, which reveals the row wherever the platform
9532 /// puts it. A toolkit that answers `true` reports [`Cap::ListScrollAlign`] as `Native`.
9533 fn list_scroll(&mut self, _h: &Self::Handle, _to: ListScroll) -> bool {
9534 false
9535 }
9536
9537 // events: one trampoline, node-id keyed; enqueue-only contract (§8.3).
9538 fn set_event_sink(&mut self, sink: EventSink);
9539
9540 // gestures (docs/shapes.md): attach a native recognizer for `kind` to `h`, emitting
9541 // `Event::Tap/LongPress/Drag` for `node` (enqueue-only). Default no gesture; a piece opts in
9542 // when it has a handler. Idempotent per (handle, kind). A view no recognizer was attached
9543 // to takes no pointer input at all: a press on it reaches whatever is behind it
9544 // (docs/gestures.md "Pass-through").
9545 fn enable_gesture(&mut self, _h: &Self::Handle, _node: NodeId, _kind: GestureKind) {}
9546
9547 // native recognizers (docs/gestures.md "Recognizers"): whether `enable_gesture(kind)` attaches
9548 // the platform's own recognizer. `Unsupported` for `LongPress`, `DoubleTap`, `Press` or
9549 // `Touches` makes day-core derive the gesture from the tap and drag events instead and
9550 // never ask for it; the kinds every backend has had from the start default to `Native`.
9551 fn gesture_support(&self, kind: GestureKind) -> Support {
9552 match kind {
9553 GestureKind::LongPress
9554 | GestureKind::DoubleTap
9555 | GestureKind::Press
9556 | GestureKind::Touches => Support::Unsupported,
9557 _ => Support::Native,
9558 }
9559 }
9560
9561 // hit slop (docs/gestures.md "Hit slop"): grow the area in which `h` takes pointer input by
9562 // `slop` points on each edge, without moving or resizing it. Every recognizer on the view
9563 // (and a native control's own press) answers inside the grown area, clipped by nothing but
9564 // the window; a point two slop areas share goes to the view in front. Zero insets restore
9565 // the view's own bounds. Default no-op: the piece is hit inside its bounds only
9566 // (`Cap::HitSlop` answers `Unsupported`).
9567 fn set_hit_slop(&mut self, _h: &Self::Handle, _node: NodeId, _slop: Insets) {}
9568
9569 // drag axis (docs/gestures.md "Gestures inside a scroll view"): the node's drag follows one
9570 // axis only. `Some(axis)`: a pointer sequence that starts out along the other axis is not
9571 // the node's drag, so an enclosing scroll view takes it and no `Event::Drag` is sent;
9572 // one that starts along `axis` is the node's from `Began` to `Ended` and the scroll view
9573 // stays still. `None` (the default state): the node claims a drag in any direction.
9574 // Default no-op: the backend claims every direction, and day-core still withholds the
9575 // off-axis drags from the handler.
9576 fn set_drag_axis(&mut self, _h: &Self::Handle, _node: NodeId, _axis: Option<DragAxis>) {}
9577
9578 // subtree enablement (docs/forms.md "Disabling a group"): `enabled = false` disables every
9579 // native control under `h` (dimmed the platform's way, out of the focus order, reported
9580 // disabled to assistive technology) and stops pointer input to the subtree; `true`
9581 // restores each control to its own enabled state. day-core drops the Day events of a
9582 // disabled subtree on every backend, so the default no-op loses the native dimming and
9583 // the accessibility state only.
9584 fn set_subtree_enabled(&mut self, _h: &Self::Handle, _node: NodeId, _enabled: bool) {}
9585
9586 // input kind (docs/gestures.md "Input kind"): the kind of device behind the latest pointer
9587 // input, asked once at startup; changes arrive as `Event::PointerKindChanged`.
9588 fn primary_pointer(&self) -> PointerKind {
9589 PointerKind::platform_default()
9590 }
9591
9592 // focus (docs/focus.md): move native keyboard focus to (or away from) this control.
9593 // `focused = true` requests focus (on mobile this also raises the soft keyboard for text
9594 // inputs); `false` resigns it (dismissing the keyboard; platforms without a "focus nothing"
9595 // state resign to a focusable root). Backends report the resulting state, user- or
9596 // programmatic, with `Event::FocusChanged(bool)` through the sink; a request that cannot
9597 // be honored (unfocusable, unmounted) produces no event. The default no-op means a
9598 // backend without focus support neither moves nor reports focus.
9599 fn focus(&mut self, _h: &Self::Handle, _node: NodeId, _focused: bool) {}
9600
9601 // focusability (docs/focus.md): opt this container into the platform's focus system, the
9602 // canvas contract generalized (`Decorate::focusable`). A focusable container accepts focus,
9603 // takes it on a press (before the press reaches its gesture recognizers), reports both
9604 // directions with `Event::FocusChanged`, and delivers the non-text keys it hears while
9605 // focused as `Event::Key` for `node` (gated on `keys::handled`, like a canvas). Keys carry
9606 // their phase: `KeyPhase::Repeat` for the platform's auto-repeat and, where
9607 // `Cap::KeyPhases` is supported, `KeyPhase::Up` for the release. `Cap::Focusable` says
9608 // whether the duty is implemented. The default
9609 // no-op means the piece renders normally but never joins the focus order: `.focused(…)`
9610 // bindings stay quiet and `.on_key(…)` never fires, the same graceful silence unfocusable
9611 // controls already have. Idempotent; only `true` is ever sent today (a piece opts in at
9612 // build, it does not opt back out).
9613 fn set_focusable(&mut self, _h: &Self::Handle, _node: NodeId, _focusable: bool) {}
9614
9615 // recycling list (docs/list.md, §10): day-core hands the `LIST` host its row-pull `source`
9616 // once, right after realize. A recycling backend stores it and calls it from its native
9617 // data-source; the default no-op means a backend without list support renders nothing.
9618 fn attach_list(&mut self, _host: &Self::Handle, _source: ListSource) {}
9619
9620 // hierarchical tree (docs/tree.md): day-core hands the `TREE` host its token-addressed
9621 // row-pull `source` once, right after realize. A backend with a native tree stores it and
9622 // answers its data-source from it; the default no-op means a backend without tree support
9623 // renders nothing (`Cap::Tree` answers `Unsupported`, and apps gate on that).
9624 fn attach_tree(&mut self, _host: &Self::Handle, _source: TreeSource) {}
9625
9626 // routes (docs/navigation.md): day-core reports the app's current route path here whenever
9627 // it changes ("" = everything at its root), so a backend with a native notion of location
9628 // can mirror it: web-dom writes the URL hash (`#controls`), and browser back/forward or a
9629 // hand-edited hash comes back as `Event::RouteRequested`. Default no-op: most toolkits
9630 // have nowhere to put a route.
9631 fn set_route(&mut self, _route: &str) {}
9632
9633 // undo bridge (docs/model.md): mirror the app's undo stack into the platform's own undo
9634 // objects, so the stock Edit menu retitles and enables itself and the platform's gestures
9635 // land: the native front of one Day-owned history. The state flows down whenever it
9636 // changes; the user's invocation comes back up as `Event::Undo`. Default no-op: a backend
9637 // without a native undo system answers `Cap::UndoBridge` `Unsupported`, and the app's own
9638 // affordances (menu items, buttons, accelerators) drive the stack instead.
9639 fn set_undo_state(&mut self, _state: &UndoState) {}
9640
9641 // edit bridge (docs/menus.md): mirror what the app's standard-edit handlers can do, so
9642 // the platform's own menu validation enables Cut/Copy/Paste exactly as it does for text
9643 // widgets; invocations come back up as `Event::Edit`. Default no-op: a backend without
9644 // a native edit-command route answers `Cap::EditBridge` accordingly.
9645 fn set_edit_state(&mut self, _state: &EditState) {}
9646
9647 // ambient modifiers (docs/menus.md): the keyboard modifiers held right now, for
9648 // interactions whose meaning they change (shift-click multi-select). Pull-based: the
9649 // platforms expose exactly this query (NSEvent.modifierFlags, the shim's tracked mask).
9650 // Touch-only backends keep the all-false default.
9651 fn modifiers(&mut self) -> Modifiers {
9652 Modifiers::default()
9653 }
9654
9655 // Dynamic context menu (docs/menus.md): the menu is built when it is summoned. The provider
9656 // is called synchronously from the platform's own menu callback (UI thread, outside any
9657 // day-core borrow) with the location in the node's local coordinates, and its result is
9658 // shown. The static `set_context_menu` below stays the simple path; this one exists for
9659 // surfaces whose menu depends on what is under the pointer (a canvas selection,
9660 // docs/tree.md). Default no-op: a backend without the affordance shows nothing.
9661 fn set_drag_source(&mut self, _h: &Self::Handle, _source: transfer::Source) {}
9662 fn set_drop_target(&mut self, _h: &Self::Handle, _target: transfer::Target) {}
9663
9664 fn set_context_menu_fn(&mut self, _h: &Self::Handle, _node: NodeId, _f: ContextMenuFn) {}
9665
9666 // menus (§ menus): render `items` with the backend's native menu affordance, firing
9667 // `Event::MenuAction(id)` (enqueue-only) for each id'd item; `role` items use the native standard
9668 // command. Default no-op: a toolkit without a menu bar / context menu shows nothing.
9669 /// The application menu (macOS/Windows/Linux menu bar; the app-bar overflow on Android; the
9670 /// `UIMenuBuilder` main menu on iPadOS/Catalyst). Replaces any previous app menu.
9671 fn set_app_menu(&mut self, _items: &[MenuItem]) {}
9672 /// A context menu for `h`, shown on secondary-click (desktop) or long-press (mobile). Passing an
9673 /// empty slice removes it.
9674 fn set_context_menu(&mut self, _h: &Self::Handle, _node: NodeId, _items: &[MenuItem]) {}
9675 /// Make the button `h` (a [`kinds::BUTTON`] node) a pull-down menu button (docs/menus.md
9676 /// "Menu buttons"): its primary press (a click, a tap, the keyboard's Space or Return, the
9677 /// accessibility press) asks `f` for the menu at that moment and shows it under the button
9678 /// with the toolkit's own menu, instead of reporting [`Event::Pressed`]. `f` is called on
9679 /// the UI thread, outside any day-core borrow, with [`Point::ZERO`] (where on the button
9680 /// the press landed does not change its menu); an empty result shows nothing. Chosen items
9681 /// fire [`Event::MenuAction`] as a context menu's do.
9682 ///
9683 /// A toolkit with no native menu to show reports [`Event::ContextMenu`] for `node` instead,
9684 /// with `window` at the button's bottom-leading corner, and the pieces layer presents the
9685 /// composed menu there. Called once per realized button; the release sweep reclaims `f`.
9686 /// Resolve the press through [`resolve_button_menu`], which re-checks after `f` runs that
9687 /// the button was not released by it. Default no-op: the button stays an inert button.
9688 fn set_button_menu(&mut self, _h: &Self::Handle, _node: NodeId, _f: ContextMenuFn) {}
9689
9690 // toolbars (docs/toolbars.md): a window's native toolbar: NSToolbar, AdwHeaderBar, QToolBar,
9691 // CommandBar. `h` is the window root's handle (the same handle `open_window` returned, or the
9692 // primary root's); the backend walks from it to the window it belongs to. Default no-op: a
9693 // toolkit with no toolbar shows nothing rather than a drawn imitation, and reports
9694 // `Cap::Toolbar` as `Unsupported` so an app can put the command somewhere else.
9695 /// Edit the window's toolbar (docs/toolbars.md): the [`ToolbarOp`]s, removals first, then
9696 /// insertions in ascending position. The bar starts empty, and becomes empty again when every
9697 /// item has been removed, at which point the backend takes it off the window.
9698 ///
9699 /// An item no op names must keep its native widget untouched, which is what keeps a search
9700 /// field focused while the page around it changes. Day sends an edit only when the bar
9701 /// changed, at most once per turn, and an item keeps its [`ToolbarItem::action`] for as long
9702 /// as its window shows an item with that id, so a native item's handler never needs
9703 /// repointing. Keep a [`ToolbarMirror`] and place each new item after
9704 /// [`ToolbarMirror::prev_where`] its group.
9705 ///
9706 /// Returns whether the edit was applied. `false` (the window has no bar to edit yet) makes
9707 /// Day send the whole bar again at the next change rather than assume this one landed.
9708 fn edit_toolbar(&mut self, _h: &Self::Handle, _ops: &[ToolbarOp]) -> bool {
9709 true
9710 }
9711 /// Apply a targeted change to one live toolbar item, the path a bound signal writes through,
9712 /// so syncing a search field does not rebuild the bar. No-op if the item is not present.
9713 fn update_toolbar(&mut self, _h: &Self::Handle, _patch: &ToolbarPatch) {}
9714
9715 // lifecycle (docs/lifecycle.md): does this backend deliver `phase`? The default answers "yes" for
9716 // the universal phases (launch/activation/termination) and "no" for the mobile-only ones. Backends
9717 // that wire up more (the mobile ones) override this; it must agree with the crate's
9718 // `const fn lifecycle_supported`, which drives compile-time guards in `day::require_lifecycle!`.
9719 fn supports_lifecycle(&self, phase: Lifecycle) -> bool {
9720 phase.is_universal()
9721 }
9722
9723 // pillars
9724 /// Apply a node's accessibility annotations (docs/accessibility.md): the label, hint and
9725 /// value the screen reader speaks, an explicit role, whether the node is hidden from
9726 /// assistive technology, and the automation identifier. Called with the node's whole
9727 /// accumulated set each time any of it changes, so every member is written on every call.
9728 /// Only an explicit role is applied: a native control reports its own.
9729 fn set_a11y(&mut self, _h: &Self::Handle, _a11y: &A11yProps) {}
9730 /// Speak `text` through the screen reader without moving its focus (docs/accessibility.md;
9731 /// probe [`Cap::Announce`]). `urgent` interrupts what is being read; otherwise the sentence
9732 /// waits its turn. Nothing happens when no screen reader is running. The default is a
9733 /// backend that reaches no announcement API.
9734 fn announce(&mut self, _text: &str, _urgent: bool) {}
9735 /// Read a widget's native state back from the platform for `a11y_audit` and
9736 /// `assert_native` (§14.2, docs/testing.md) to diff against Day's expectation. Default:
9737 /// nothing read; the audit skips the node and `assert_native` records each field as unread.
9738 fn read_native(&self, _h: &Self::Handle) -> NativeSnapshot {
9739 NativeSnapshot::default()
9740 }
9741 /// Read what a widget shows at this moment, mid-animation included, for the
9742 /// `assert_displayed` step (docs/testing.md, docs/tween.md "The animation contract"): the
9743 /// presentation layer's opacity, frame, transform and background color on Core Animation,
9744 /// the animated `View` properties on Android, the computed style on the web. A field the
9745 /// toolkit cannot observe while its animator runs stays `None` and the step records it as
9746 /// unread. Default: nothing read.
9747 fn read_displayed(&self, _h: &Self::Handle) -> Displayed {
9748 Displayed::default()
9749 }
9750 fn replay(&mut self, _h: &Self::Handle, _ops: &[DrawOp], _size: Size) {}
9751
9752 /// Every family this toolkit can draw canvas text in, with the faces each ships
9753 /// (docs/fonts.md; probe [`Cap::FontList`]). Default: none. `day::font_families` calls
9754 /// this once per process and caches the answer: enumeration is slow on every platform
9755 /// (fontconfig, a DirectWrite collection, an XML parse on Android) and the set does not
9756 /// change under a running app.
9757 fn font_families(&mut self) -> Vec<FontFamilyInfo> {
9758 Vec::new()
9759 }
9760
9761 /// Measure one line of canvas text at `size` points in `font`, in the same engine
9762 /// [`Toolkit::replay`] draws [`DrawOp::Text`] with, so a `TextAnchor::LEADING` anchor plus
9763 /// the returned `ascent` lands on the drawn baseline. `None` = cannot measure; the facade
9764 /// then answers [`TextMetrics::approximate`].
9765 fn measure_text(&mut self, _text: &str, _size: f64, _font: &CanvasFont) -> Option<TextMetrics> {
9766 None
9767 }
9768 // --- raster images (docs/images.md) -------------------------------------------------
9769 //
9770 // Request-id shaped rather than blocking, because one backend can never answer
9771 // synchronously: a browser decodes through `createImageBitmap`, which is a promise. Every
9772 // other backend decodes inline and raises the completion before returning, so the shape
9773 // costs them nothing but a line, and the app-facing API can be one thing everywhere
9774 // instead of two (docs/async.md rule 3: a callback and a future, never a runtime).
9775
9776 /// Decode encoded image bytes (PNG/JPEG/…) into a native image, answering `req` with
9777 /// [`Event::ImageDecoded`].
9778 ///
9779 /// The id in that event is minted by the caller (day-core), not the backend: the backend
9780 /// keeps its own side table from that id to whatever it decoded.
9781 ///
9782 /// The default does nothing because a default body cannot reach the event sink
9783 /// (it is installed per backend by [`Toolkit::set_event_sink`], not reachable through this
9784 /// trait), so there is no way for it to answer. day-core asks [`Cap::ImageDecode`] first and
9785 /// resolves the request as [`ImageError::Unsupported`] itself, which is why a backend with
9786 /// no decoder needs no code here at all.
9787 fn decode_image(&mut self, _req: u64, _id: BitmapId, _bytes: &[u8]) {}
9788
9789 /// What a decoded image is: pixel size, scale, format, alpha ([`BitmapInfo`]).
9790 ///
9791 /// Synchronous: every backend that decoded the image already holds these facts. `None` means
9792 /// the id names nothing live.
9793 fn image_info(&mut self, _id: BitmapId) -> Option<BitmapInfo> {
9794 None
9795 }
9796
9797 /// The metadata beyond the pixels: EXIF orientation, DPI, capture time
9798 /// ([`ImageProperties`], probe [`Cap::ImageProperties`]). `None` where the backend has no
9799 /// metadata reader, which is most of them.
9800 fn image_properties(&mut self, _id: BitmapId) -> Option<ImageProperties> {
9801 None
9802 }
9803
9804 /// Encode a decoded image back to bytes per `spec`, answering `req` with
9805 /// [`Event::ImageEncoded`]. A format outside [`Self::encode_formats`] answers
9806 /// [`ImageError::Encode`] rather than silently substituting another one.
9807 ///
9808 /// Defaulted to nothing for the same reason as [`Self::decode_image`]: day-core probes
9809 /// [`Cap::ImageEncode`] and answers `Unsupported` without ever calling this.
9810 fn encode_image(&mut self, _req: u64, _id: BitmapId, _spec: &EncodeSpec) {}
9811
9812 /// Which formats [`Self::encode_image`] can write, the [`Cap::ImageEncode`]
9813 /// counterpart of [`Self::font_families`]/[`Cap::FontList`]. Empty by default.
9814 fn encode_formats(&mut self) -> Vec<ImageFormat> {
9815 Vec::new()
9816 }
9817
9818 /// Drop a decoded image and everything the backend cached for it. Called when the app's
9819 /// last handle to it goes away; an id the backend never saw is a no-op.
9820 fn release_image(&mut self, _id: BitmapId) {}
9821
9822 // --- canvas export (docs/canvas.md "Exporting") --------------------------------------
9823 //
9824 // Request-id shaped like the image duties above, for the same reason: the browser's
9825 // `createImageBitmap` is a promise, and a native toolkit may paint on another thread. A
9826 // backend may also answer inline, before returning. day-core validates sizes, enforces
9827 // the pixel limits and probes the caps first, so a backend sees only requests it can
9828 // attempt.
9829
9830 /// Replay `ops` into a new offscreen bitmap of `size` points at `scale` pixels per point
9831 /// ([`export_pixels`] gives the pixel size), with a transparent background and the
9832 /// canvas's top-left origin. Store it under `id` in the same table [`Self::decode_image`]
9833 /// fills, so `image_info`, `encode_image`, `release_image`, the `image` piece and
9834 /// [`DrawOp::Image`] all take it, then answer `req` with [`Event::BitmapRendered`] (its
9835 /// [`BitmapInfo::scale`] is `scale`).
9836 ///
9837 /// The painter must be the one [`Self::replay`] uses, so text, gradients, clips and stamps
9838 /// match the screen. Where the platform's 2-D API draws into a memory surface from any
9839 /// thread, the paint runs on a thread of [`offscreen`] and the answer is posted back, so
9840 /// a long replay never stalls the UI; the toolkit resolves on the UI thread, before it
9841 /// hands the job over, everything the painter would otherwise read from UI-thread state
9842 /// (the decoded images the ops reference, the fonts their text runs need). The contract
9843 /// holds either way: one answer per request, carrying that request's `req`, raised on the
9844 /// UI thread, and the bitmap in the table before it. Defaulted to nothing: day-core probes
9845 /// [`Cap::CanvasBitmap`] and answers [`ExportError::Unsupported`] itself.
9846 fn render_bitmap(
9847 &mut self,
9848 _req: u64,
9849 _id: BitmapId,
9850 _ops: &[DrawOp],
9851 _size: Size,
9852 _scale: f64,
9853 ) {
9854 }
9855
9856 /// Replay each page into one PDF document and answer `req` with [`Event::PdfRendered`].
9857 /// Units are PDF points, top-left origin; shapes and text stay vector, and images embed at
9858 /// their pixel size. `pages` is never empty. Defaulted to nothing: day-core probes
9859 /// [`Cap::CanvasPdf`] first.
9860 fn render_pdf(&mut self, _req: u64, _pages: &[PdfPage], _info: &PdfInfo) {}
9861
9862 /// Capture the primary window's content as encoded image bytes (the dayscript `screenshot`
9863 /// step, docs/window-image.md).
9864 ///
9865 /// # Errors
9866 ///
9867 /// Returns a message when the backend cannot capture; the default always does.
9868 fn snapshot_window(&mut self) -> Result<Vec<u8>, String> {
9869 Err("snapshot unsupported".into())
9870 }
9871 /// Where `root`, the primary window's root container, sits in [`Self::snapshot_window`]'s
9872 /// image, in points from its top-left. A reader of the capture (dayscript `sample_pixel`)
9873 /// maps Day's frames into it with this; it matters where the capture spans more than Day's
9874 /// content on more than one side, as Android's edge-to-edge content does (status bar
9875 /// above, navigation bar below).
9876 ///
9877 /// Defaulted to `None`, which the reader takes as "any rows beyond Day's content are
9878 /// above it", true where the only extra area is a title bar.
9879 fn snapshot_origin(&mut self, _root: &Self::Handle) -> Option<Point> {
9880 None
9881 }
9882 /// Establish a fresh screenshot checkpoint after reactive work and native transitions.
9883 /// `revision` is stable across retries and unique to the request; `host` selects a
9884 /// secondary window, or None for the primary. Never block the UI thread waiting for
9885 /// a frame. Pending requests are retried within the dayscript deadline.
9886 ///
9887 /// Ready means the platform render checkpoint completed, not that a vsync callback
9888 /// proves pixels were displayed. `OnCapture` delegates freshness to `snapshot_window`.
9889 ///
9890 /// # Errors
9891 ///
9892 /// Returns a message when the checkpoint cannot be established, for example because the
9893 /// window closed.
9894 fn prepare_snapshot(
9895 &mut self,
9896 _host: Option<&Self::Handle>,
9897 _revision: u32,
9898 ) -> Result<capture::Readiness, String> {
9899 // Compatible with external toolkits predating this hook: their synchronous
9900 // snapshot owns freshness, and no external-capture acknowledgment is fabricated.
9901 Ok(capture::Readiness::OnCapture)
9902 }
9903
9904 /// The same capture with the window's own chrome: title bar, toolbar, whatever the platform
9905 /// draws around the content (docs/window-image.md).
9906 ///
9907 /// Defaulted to [`Self::snapshot_window`]: a backend that cannot separate the two
9908 /// (or has no chrome to speak of, a phone) answers with the content shot rather than an
9909 /// error, so an app asking for chrome degrades to "what there was" instead of failing. The
9910 /// dayscript `screenshot` step never calls this, which is what keeps every captured gallery
9911 /// baseline byte-identical to before it existed.
9912 ///
9913 /// # Errors
9914 ///
9915 /// Returns a message when the backend cannot capture the window.
9916 fn snapshot_window_chrome(&mut self) -> Result<Vec<u8>, String> {
9917 self.snapshot_window()
9918 }
9919 /// Show/hide the sidebar pane of the navigation host `host`, which is what the sidebar
9920 /// affordance a `nav(Sidebar)` contributes for itself drives ([`SIDEBAR_TOGGLE_ID`]).
9921 /// `false` when `host` has no pane to toggle (a stack, a tab bar, no sidebar concept at all).
9922 ///
9923 /// Per host, not per process: a second window's button collapses that window's sidebar
9924 /// and not the first's. The item's own action makes the call, and dayscript's `toolbar:`
9925 /// step presses the item like any other, so a walkthrough drives exactly the path a click
9926 /// takes. Defaulted, so a backend with no sidebar needs no code. docs/toolbars.md,
9927 /// docs/navigation.md.
9928 fn toggle_sidebar(&mut self, _host: &Self::Handle) -> bool {
9929 false
9930 }
9931 /// Press the platform's own back affordance (the navigation bar's back button on iOS,
9932 /// the system back on Android) on the innermost navigation host that has something to
9933 /// pop. What `nav_back()` does not do: that is Day's rail, which pops the model and lets the
9934 /// backend follow, while this runs the native path first (the bar's `shouldPop`, the
9935 /// dispatcher's callbacks, the pop itself) and lets the backend report it to Day as a user
9936 /// back, guard and all. dayscript's `nav_back: { native: true }` drives it, so a walkthrough
9937 /// can cover the code that a real tap runs and Day's rail never reaches. `false` when this
9938 /// toolkit has no native back or nothing is popped by it. Defaulted, so a desktop needs no
9939 /// code. docs/navigation.md.
9940 fn native_back(&mut self) -> bool {
9941 false
9942 }
9943 /// Take (`true`) or release (`false`) the platform's system back for the app's own
9944 /// handlers ([`Decorate::on_system_back`](/api/day_pieces/trait.Decorate.html#method.on_system_back)):
9945 /// day-core arms it while at least one mounted handler is enabled. Armed, a system back that
9946 /// nothing native consumes first (a presented cover, a pushed page, an armed guard) reaches
9947 /// Day as [`Event::NavBack`] on [`WINDOW_NODE`] instead of leaving the app; released, the
9948 /// platform's default runs, predictive-back preview and all. Android registers an
9949 /// `OnBackPressedCallback` beneath its own; HarmonyOS consumes the page's `onBackPress`.
9950 /// Defaulted, so a toolkit with no system back (desktop, iOS, the web) needs no code.
9951 /// docs/navigation.md "Handling the system Back".
9952 fn set_system_back(&mut self, _armed: bool) {}
9953 /// Whether the UI has settled, with no native transition (modal present/dismiss, nav push)
9954 /// still animating. The dayscript `screenshot` step polls this before capturing so shots
9955 /// never catch a half-faded dialog or half-pushed page. Backends without async
9956 /// transitions (or without a way to know) report `true`.
9957 fn ui_idle(&mut self) -> bool {
9958 true
9959 }
9960
9961 // imperative presentation (docs/dialogs.md): show a native modal for request `req`;
9962 // the backend answers by enqueuing `Event::PresentResult { req, .. }`. `dismiss` is
9963 // used only when Day resolves programmatically (dayscript) while the modal is still up.
9964 fn present(&mut self, _req: u64, _spec: &present::PresentSpec) {}
9965 fn dismiss(&mut self, _req: u64) {}
9966
9967 /// Open `url` in the platform's default handler: the system browser for `http(s)`, the mail
9968 /// client for `mailto:`, etc. Backs the [`link`](/api/day_pieces/fn.link.html) piece. Fire and
9969 /// forget: there is no result, and an unopenable URL is ignored. The default no-ops so a
9970 /// backend that hasn't wired it up still compiles.
9971 fn open_url(&mut self, _url: &str) {}
9972
9973 /// Whether a native share chooser is available. Does not probe installed share targets.
9974 fn share_support(&self) -> Support {
9975 Support::Unsupported
9976 }
9977 /// Present the system share chooser for `spec` (docs/sharing.md). True means presentation
9978 /// started, not that sharing completed. Never sends data without the user's choice of a
9979 /// target. Where the chooser can carry the app's own actions (`Cap::ShareActions`), each
9980 /// of `spec.actions` appears with its title and glyph, and choosing one enqueues
9981 /// `Event::MenuAction(action.id)`; elsewhere the actions are left out. `anchor` is the
9982 /// control the chooser points at where it is a popover (iPad, macOS); without one the
9983 /// chooser uses the window's top trailing corner.
9984 fn share(&mut self, _spec: &share::ShareSpec, _anchor: Option<&Self::Handle>) -> bool {
9985 false
9986 }
9987
9988 /// Read current OS associations. Unsupported platforms must not fabricate a default.
9989 ///
9990 /// # Errors
9991 ///
9992 /// Returns [`applications::ApplicationError::Unsupported`] where the platform has no
9993 /// association query (the default), or the platform's own failure.
9994 fn application_handlers(
9995 &mut self,
9996 _query: &applications::HandlerQuery,
9997 ) -> Result<applications::ApplicationHandlers, applications::ApplicationError> {
9998 Err(applications::ApplicationError::Unsupported)
9999 }
10000
10001 /// Open with an opaque application identifier returned by `application_handlers`.
10002 fn open_url_with_application(
10003 &mut self,
10004 _url: &str,
10005 _application: &str,
10006 completion: applications::OpenApplicationCompletion,
10007 ) {
10008 completion(Err(applications::ApplicationError::Unsupported));
10009 }
10010
10011 /// Ask the OS to require a second swipe for its edge gestures on `edges` (docs/cover.md):
10012 /// the union requested by every mounted `defers_system_gestures` modifier, re-sent whenever
10013 /// that set changes (`Edges::NONE` when the last one unmounts). iOS defers the home
10014 /// indicator / notification edges; Android enters swipe-to-reveal immersive mode while
10015 /// non-empty. The default no-ops (desktop has no system edge gestures).
10016 fn defer_system_gestures(&mut self, _edges: Edges) {}
10017
10018 /// Hide (`true`) or show the system status bar (docs/cover.md): whether any mounted
10019 /// `status_bar_hidden` modifier currently asks for it hidden, re-sent whenever that answer
10020 /// may have changed (`false` when the last request unmounts). iOS answers the root and
10021 /// cover view controllers' `prefersStatusBarHidden`; Android and HarmonyOS hide the status
10022 /// bar through their window inset controls. The default no-ops (desktop and web have no
10023 /// status bar); report `Cap::StatusBarHidden` alongside an implementation.
10024 fn set_status_bar_hidden(&mut self, _hidden: bool) {}
10025
10026 /// Whether the platform is rendering in dark appearance right now. Apps painting
10027 /// custom surfaces (opaque overlay panels, scrims) branch on this so their fills track
10028 /// the theme the default text colors already follow; hardcoding either theme's
10029 /// surface produces dark-on-dark or light-on-light text on the other. Queried at
10030 /// build time (a piece rebuilt after a theme change re-queries). The default honors a
10031 /// `DAY_THEME` launch override and otherwise answers light.
10032 /// Resolve a semantic color for custom artwork. Backends with native palette access
10033 /// override this; the default follows light/dark appearance using Day's fixed palette.
10034 fn system_color(&mut self, role: SystemColor) -> Color {
10035 role.fallback(self.dark_mode())
10036 }
10037
10038 fn dark_mode(&mut self) -> bool {
10039 std::env::var("DAY_THEME").ok().as_deref() == Some("dark")
10040 }
10041 /// Whether the user asked the system for less motion (docs/accessibility.md; probe
10042 /// [`Cap::ReduceMotion`]): macOS and iOS "Reduce Motion", Android "Remove animations" (an
10043 /// animator duration scale of zero), GTK's `gtk-enable-animations` off, Windows "Show
10044 /// animations" off, the web's `prefers-reduced-motion`. Read at launch; a backend that
10045 /// watches the setting calls `day_core::note_motion_changed` when it flips. Day then applies
10046 /// every finite animation at its destination and keeps only indeterminate motion. The default
10047 /// is a backend that reads no such setting.
10048 fn reduce_motion(&mut self) -> bool {
10049 false
10050 }
10051
10052 /// The factor the system's text-size setting currently applies to `style`, against that
10053 /// style's size at the platform's default setting (docs/text.md "Text scale"): `1.0` at
10054 /// the default, `1.3` when the reader's setting draws this style 30% larger, below `1.0`
10055 /// for a smaller-than-default setting. Platforms that scale every style by one number
10056 /// (Android's `fontScale`, GNOME's `text-scaling-factor`, Windows' `TextScaleFactor`, the
10057 /// browser's default font size) ignore `style`; UIKit answers per style, because Dynamic
10058 /// Type grows small styles more than large ones.
10059 ///
10060 /// Read when a piece asks (`day::text_scale()`) and again after the toolkit calls
10061 /// `day_core::note_text_size_changed`, which every toolkit that can observe the setting
10062 /// calls when it changes. Day uses the answer to hold a label under its
10063 /// `max_text_scale` cap. The default is a platform with no text-size setting.
10064 fn text_scale(&mut self, _style: Font) -> f64 {
10065 1.0
10066 }
10067
10068 /// App-level appearance override: `Some(true)` forces dark, `Some(false)` forces light,
10069 /// `None` returns to following the system. Backends restyle their native widgets in
10070 /// place and answer the override from [`dark_mode`](Self::dark_mode); app-painted
10071 /// surfaces pick it up on their next rebuild. `Cap::Appearance` reports whether the
10072 /// backend honors this; the default ignores the call.
10073 fn set_appearance(&mut self, _dark: Option<bool>) {}
10074
10075 /// Put `badge` on the app's icon in the Dock / launcher / home screen (docs/badge.md).
10076 ///
10077 /// Fire-and-forget, like `set_appearance`: a payload this toolkit cannot render is ignored, and
10078 /// the app probes `Cap::AppBadge{Count,Text,Dot}` before choosing one. Never substitute: a
10079 /// backend that turned `Text("beta")` into `Count(1)` would put a wrong number on a user's
10080 /// icon, which is worse than showing nothing. The default ignores every call.
10081 fn set_app_badge(&mut self, _badge: &AppBadge) {}
10082
10083 // app lifecycle (mobile; desktop backends no-op)
10084 fn on_suspend(&mut self) {}
10085 fn on_resume(&mut self) {}
10086 fn on_memory_warning(&mut self) {}
10087
10088 // adoption of foreign native handles (polyglot pieces, §15.3)
10089 fn adopt(&mut self, _raw: RawHandle) -> Self::Handle {
10090 unimplemented!("this toolkit does not adopt foreign handles yet")
10091 }
10092
10093 // secondary windows (docs/windows.md)
10094
10095 /// Open a native OS window per `options` + `kind`: create and show the window, wire its
10096 /// events to `id` (`WindowResized` with the content size in points, `WindowClosed` after
10097 /// the native close, `WindowFocused` on key/active changes), and answer with its content
10098 /// container handle, the same contract as the `ready` root container. Backends whose
10099 /// window creation is asynchronous (a scene, an activity, an ability) answer
10100 /// [`WindowOpenReply::Pending`] and complete later through
10101 /// `day_core::finish_window_open(id, raw, size)`, which goes through [`Toolkit::adopt`].
10102 /// The default answers `Unsupported`; day-core then presents the content as a
10103 /// fullscreen cover in the primary window instead.
10104 fn open_window(
10105 &mut self,
10106 _id: NodeId,
10107 _options: &WindowOptions,
10108 _kind: WindowKind,
10109 ) -> WindowOpenReply<Self::Handle> {
10110 WindowOpenReply::Unsupported
10111 }
10112
10113 /// Close the native window whose content container is `host` (a handle `open_window`
10114 /// produced). Asynchronous: the platform confirms with `Event::WindowClosed` on the
10115 /// window's root node, and only then does day-core tear the subtree down. Idempotent; unknown
10116 /// hosts are ignored. Never called with the primary window's container.
10117 fn close_window(&mut self, _host: &Self::Handle) {}
10118
10119 /// End the application: the last window with [`WindowRole::Primary`] has closed
10120 /// (docs/windows.md). day-core decides when, since it owns the window registry and the role
10121 /// each window carries; the backend supplies only the platform's exit:
10122 /// `NSApplication.terminate`, `QCoreApplication::quit`, `GtkApplication.quit`,
10123 /// `PostQuitMessage`. Everything day-core wanted to happen first (secondary windows
10124 /// disposed, `WillTerminate` delivered) already has by the time this is called.
10125 ///
10126 /// The default does nothing, which is right for the backends whose process lifetime is
10127 /// not theirs to end: a browser tab, an Android activity, an iOS scene.
10128 fn quit_app(&mut self) {}
10129
10130 /// Bring the window whose content container is `host` to front and make it key/active:
10131 /// the focus half of open-or-focus singleton windows. Default no-op.
10132 fn focus_window(&mut self, _host: &Self::Handle) {}
10133
10134 /// Retitle the window whose content container is `host`. Default no-op.
10135 fn set_window_title(&mut self, _host: &Self::Handle, _title: &str) {}
10136
10137 /// Resize the window whose content container is `host` to fit `size` of content, and pin it
10138 /// there: what `WindowOptions::size_to_fit` asks for (docs/windows.md).
10139 ///
10140 /// `size` is the content size Day measured, not the window's outer frame: the backend adds
10141 /// its chrome. A settings panel is the case this exists for, and every desktop platform
10142 /// sizes one to its content rather than to a number the app guessed; a fixed height either
10143 /// clips the last row or leaves a band of empty panel under it, and which one you get depends
10144 /// on the user's text size.
10145 ///
10146 /// Default no-op, so a toolkit that cannot resize a live window keeps the size it was
10147 /// opened at, which is what every backend did before this existed.
10148 fn fit_window(&mut self, _host: &Self::Handle, _size: Size) {}
10149
10150 /// Snapshot the window whose content container is `host` (the dayscript `screenshot`
10151 /// step's `window:` target). The default answers the primary snapshot, so backends that
10152 /// never open windows stay correct without changes.
10153 ///
10154 /// # Errors
10155 ///
10156 /// Returns a message when the backend cannot capture that window.
10157 fn snapshot_window_of(&mut self, _host: &Self::Handle) -> Result<Vec<u8>, String> {
10158 self.snapshot_window()
10159 }
10160
10161 /// Apply one property change to the window whose content container is `host`
10162 /// (docs/windows.md "Window properties"). The primary window arrives with its root container,
10163 /// like [`set_window_title`](Self::set_window_title).
10164 ///
10165 /// Fire-and-forget, like [`set_app_badge`](Self::set_app_badge): a change this toolkit cannot
10166 /// make is ignored, and the app probes the matching `Cap` (named on each [`WindowChange`]
10167 /// variant) before relying on it. A change the platform completes later (a fullscreen
10168 /// transition, a zoom animation) reports its outcome through
10169 /// [`Event::WindowStateChanged`], never by assuming the request took. The default ignores
10170 /// every change.
10171 fn apply_window(&mut self, _host: &Self::Handle, _change: &WindowChange) {}
10172
10173 /// True OS window groups, as distinct from native tab widgets.
10174 fn native_window_tabs(&self) -> bool {
10175 false
10176 }
10177 /// Native in-window document/section tab control; OS grouping is reported separately.
10178 fn native_document_tabs(&self) -> bool {
10179 false
10180 }
10181 /// Join/reorder these windows in an OS tab group. Content remains window-owned.
10182 fn group_windows(&mut self, _hosts: &[Self::Handle]) {}
10183 /// Current native order of the group containing this window, including detached groups.
10184 fn window_tab_order(&self, _host: &Self::Handle) -> Vec<NodeId> {
10185 Vec::new()
10186 }
10187
10188 /// Install the app's Dock menu (docs/menus.md "Dock menu"): the items macOS shows above
10189 /// its own when the user right-clicks the app's Dock icon, built from the app's
10190 /// `[[shortcuts]]` and its `dock_menu(..)` entries. Same item model and dispatch as
10191 /// [`set_app_menu`](Self::set_app_menu); an empty slice removes the menu. `Cap::DockMenu`
10192 /// reports support; the default ignores the call.
10193 fn set_dock_menu(&mut self, _items: &[MenuItem]) {}
10194
10195 /// Make the node at `h` move its window when the user drags it, as a title bar does
10196 /// (`.window_drag_region()`, docs/window-chrome.md): the region's own background starts a
10197 /// native window drag (with the platform's snapping and edge tiling), a double click does
10198 /// what the user's title-bar double-click setting says, and controls inside the region keep
10199 /// receiving their own clicks. `false` releases it. `Cap::DragRegion`; the default ignores
10200 /// the call, so on a phone the region is an ordinary view.
10201 fn set_drag_region(&mut self, _h: &Self::Handle, _drag: bool) {}
10202
10203 /// Show these status items, replacing the previous set (docs/status-item.md): add the
10204 /// ones whose `id` is new, update the ones that changed, remove the ones no longer listed.
10205 /// A click on an item runs its `activate` action or opens its menu; menu choices dispatch
10206 /// [`Event::MenuAction`] like the app menu's. `Cap::StatusItem`; the default ignores the
10207 /// call, which is what a phone and the web do.
10208 fn set_status_items(&mut self, _items: &[StatusItemSpec]) {}
10209
10210 /// Show `progress` on the app's Dock or taskbar icon (docs/status-item.md).
10211 /// `Cap::AppProgress`; the default ignores it.
10212 fn set_app_progress(&mut self, _progress: AppProgress) {}
10213
10214 /// Show or hide the app's Dock icon while it runs: a menu-bar app hides it and lives in its
10215 /// status item (macOS activation policy). `Cap::DockVisibility`; the default ignores it.
10216 fn set_dock_visible(&mut self, _visible: bool) {}
10217
10218 /// Keep the process running when its last window closes (docs/windows.md "Keeping the app
10219 /// running"). When `true`, the backend must not end the app on its own as windows close: it
10220 /// reports every close, the first window's included, as `Event::WindowClosed`, and day-core
10221 /// decides whether to call [`quit_app`](Self::quit_app). When `false`, the backend keeps its
10222 /// platform's own rule. A backend whose process lifetime is not its own (a phone, a browser
10223 /// tab) ignores it, which is the default.
10224 fn set_keep_running(&mut self, _keep: bool) {}
10225
10226 /// The displays attached now (docs/windows.md "Monitors"). `Cap::Monitors`; the default
10227 /// answers none, and day-core then describes the primary window's own size as one display.
10228 fn monitors(&self) -> Vec<Monitor> {
10229 Vec::new()
10230 }
10231
10232 /// The outer frame of the window whose content container is `host`, in points on the
10233 /// desktop's coordinate space (top-left origin), or `None` where the platform does not say
10234 /// (a phone, Wayland's positions). Read when the app asks for it and when day-core saves a
10235 /// remembered frame (`WindowOptions::remember_frame`).
10236 fn window_frame(&self, _host: &Self::Handle) -> Option<Rect> {
10237 None
10238 }
10239
10240 /// Replace the launcher shortcuts the app set while running (docs/deep-links.md "Launcher
10241 /// shortcuts"), shown beside the ones Day.toml declares: iOS Home Screen quick actions,
10242 /// Android dynamic shortcuts, the macOS Dock menu. Each opens its route through the deep-link
10243 /// intake. `Cap::DynamicShortcuts`; the default ignores the call.
10244 fn set_launcher_shortcuts(&mut self, _shortcuts: &[LauncherShortcut]) {}
10245}
10246
10247/// What a secondary window is, so backends can apply platform conventions (docs/windows.md).
10248#[derive(Clone, Copy, PartialEq, Eq, Debug)]
10249pub enum WindowKind {
10250 /// A regular document/tool window: resizable, miniaturizable, platform-default tabbing.
10251 Normal,
10252 /// A settings/preferences window: singleton by convention; macOS disallows window
10253 /// tabbing and drops the resize/minimize chrome, mobile presents it modally. Pairs with
10254 /// day-core's key-singleton reopen (`open_window` with a key).
10255 Preferences,
10256 /// The About window (docs/settings.md): the same fixed, centered, untabbed panel chrome
10257 /// as [`Self::Preferences`] (every desktop treats the two alike), presented modally on
10258 /// mobile. Singleton under day-core's `day.about` key.
10259 About,
10260}
10261
10262impl WindowKind {
10263 /// Whether this is a panel (settings or About) rather than a document window: the kinds
10264 /// every desktop draws fixed-size, centered and out of the Window menu, and mobile presents
10265 /// as a cover.
10266 #[must_use]
10267 pub fn is_panel(self) -> bool {
10268 !matches!(self, WindowKind::Normal)
10269 }
10270}
10271
10272/// Whether a window keeps the app alive (docs/windows.md close policy).
10273///
10274/// A separate axis from [`WindowKind`], which describes chrome. They correlate (a
10275/// preferences panel is the archetypal window that should not hold an app open), but they are
10276/// not the same question, and conflating them would leave no way to say "an ordinary-looking
10277/// tool window that shouldn't outlive the documents".
10278///
10279/// Note the word "secondary" is overloaded around windows: elsewhere in day it means "a window
10280/// other than the first one opened". Here it means "does not keep the app alive", which is
10281/// about lifetime, not about order of creation.
10282#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
10283pub enum WindowRole {
10284 /// Closing the last one of these ends the app.
10285 #[default]
10286 Primary,
10287 /// Never keeps the app alive: when the last `Primary` closes, the app exits and takes
10288 /// these with it, however many are open.
10289 Secondary,
10290}
10291
10292impl From<WindowKind> for WindowRole {
10293 /// The default pairing: an ordinary window holds the app open, a preferences panel does
10294 /// not. An app that needs a different answer sets the role itself.
10295 fn from(kind: WindowKind) -> WindowRole {
10296 match kind {
10297 WindowKind::Normal => WindowRole::Primary,
10298 WindowKind::Preferences | WindowKind::About => WindowRole::Secondary,
10299 }
10300 }
10301}
10302
10303/// A backend's answer to [`Toolkit::open_window`] (docs/windows.md).
10304pub enum WindowOpenReply<H> {
10305 /// The window exists now; here is its content container (desktop backends).
10306 Open(H),
10307 /// Native creation started but completes asynchronously (a scene, an activity, an
10308 /// ability); the backend will call `day_core::finish_window_open` when the content
10309 /// container exists. day-core parks the window record until then.
10310 Pending,
10311 /// This toolkit cannot open windows (`Cap::MultiWindow` = `Unsupported`); day-core
10312 /// falls back to presenting the content as a fullscreen cover in the primary window.
10313 Unsupported,
10314}
10315
10316/// How a window is shown (docs/windows.md "Window properties"): what the window's `state()`
10317/// signal holds and what [`WindowChange::State`] asks for.
10318#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
10319pub enum WindowState {
10320 /// On screen at its own size: neither minimized, maximized nor fullscreen.
10321 #[default]
10322 Normal,
10323 /// Minimized to the Dock, taskbar or shelf. `Cap::WindowStates`.
10324 Minimized,
10325 /// Zoomed to fill the screen's work area, keeping its chrome. `Cap::WindowStates`.
10326 Maximized,
10327 /// Covering the whole screen with no window chrome; on a phone, the system bars hidden.
10328 /// `Cap::WindowFullscreen`.
10329 Fullscreen,
10330}
10331
10332impl WindowState {
10333 /// The wire code of [`bridge::BridgeKind::WindowStateChanged`].
10334 #[must_use]
10335 pub const fn code(self) -> i32 {
10336 match self {
10337 WindowState::Normal => 0,
10338 WindowState::Minimized => 1,
10339 WindowState::Maximized => 2,
10340 WindowState::Fullscreen => 3,
10341 }
10342 }
10343
10344 /// The state a wire code names; an unknown code reads as `Normal`.
10345 #[must_use]
10346 pub const fn from_code(code: i32) -> WindowState {
10347 match code {
10348 1 => WindowState::Minimized,
10349 2 => WindowState::Maximized,
10350 3 => WindowState::Fullscreen,
10351 _ => WindowState::Normal,
10352 }
10353 }
10354}
10355
10356/// How a window stacks against other apps' windows ([`WindowChange::Level`], `Cap::WindowLevel`).
10357#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
10358pub enum WindowLevel {
10359 /// Ordinary stacking: the focused app's windows come forward.
10360 #[default]
10361 Normal,
10362 /// Stays above other apps' ordinary windows: a palette, a timer, a video peek.
10363 Floating,
10364}
10365
10366/// How strongly a window asks for the user's attention ([`WindowChange::RequestAttention`]).
10367#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
10368pub enum Attention {
10369 /// Once: one Dock bounce, a taskbar button that flashes a few times.
10370 #[default]
10371 Informational,
10372 /// Until the user switches to the app.
10373 Critical,
10374}
10375
10376/// One change to one window (docs/windows.md "Window properties"), carried by
10377/// [`Toolkit::apply_window`]. Each variant names the `Cap` that reports whether the running
10378/// toolkit makes it.
10379#[derive(Clone, Debug, PartialEq)]
10380pub enum WindowChange {
10381 /// Minimize, zoom, take fullscreen, or return to normal. `Cap::WindowStates` for the
10382 /// first two, `Cap::WindowFullscreen` for fullscreen. The outcome comes back as
10383 /// [`Event::WindowStateChanged`].
10384 State(WindowState),
10385 /// Keep the window's content out of screenshots, recordings and screen sharing.
10386 /// `Cap::ContentProtection`.
10387 ContentProtected(bool),
10388 /// Move and/or resize. `origin` is the outer frame's top-left corner in points on the
10389 /// desktop's coordinate space (top-left origin, `Cap::WindowPosition`); `size` is the size Day
10390 /// lays the content out at, in points, the same size `WindowResized` reports
10391 /// (`Cap::WindowGeometry`): the backend adds its own chrome around it.
10392 Frame {
10393 origin: Option<Point>,
10394 size: Option<Size>,
10395 },
10396 /// The content size the user can resize the window to. `None` lifts that bound.
10397 /// `Cap::WindowGeometry`.
10398 Limits {
10399 min: Option<Size>,
10400 max: Option<Size>,
10401 },
10402 /// Stacking against other apps' windows. `Cap::WindowLevel`.
10403 Level(WindowLevel),
10404 /// Show the window on every virtual desktop / Space. `Cap::WindowLevel`.
10405 OnAllWorkspaces(bool),
10406 /// Leave the window out of the taskbar and the window switcher. `Cap::WindowLevel`.
10407 SkipTaskbar(bool),
10408 /// Whether the user can resize the window. `Cap::WindowGeometry`.
10409 Resizable(bool),
10410 /// Whether the window offers a minimize control. `Cap::WindowStates`.
10411 Minimizable(bool),
10412 /// Whether the window offers a maximize / zoom control. `Cap::WindowStates`.
10413 Maximizable(bool),
10414 /// Whether the window offers a close control. `Cap::WindowStates`.
10415 Closable(bool),
10416 /// Hide the window without closing it, or show it again. `Cap::WindowStates`.
10417 Visible(bool),
10418 /// This window's light/dark override over the app-wide [`Toolkit::set_appearance`].
10419 /// `Cap::WindowAppearance`.
10420 Appearance(Option<bool>),
10421 /// Bounce the Dock icon, flash the taskbar button. `Cap::RequestAttention`.
10422 RequestAttention(Attention),
10423}
10424
10425/// The frame a window wears (docs/window-chrome.md), set once when it opens.
10426#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
10427pub enum WindowChrome {
10428 /// The platform's title bar and frame.
10429 #[default]
10430 Standard,
10431 /// The content runs to the window's top edge, under the title bar, and the platform's own
10432 /// window controls (close, minimize, zoom) stay where they are. For a custom title bar: the
10433 /// backend reports the bar's height as the window's safe-area top inset (`day::safe_area()`),
10434 /// so the app pads its content by it and paints its background under it. Mark the draggable
10435 /// part with `.window_drag_region()`. `Cap::OverlayTitleBar`; where unsupported the window
10436 /// keeps its standard bar.
10437 Overlay,
10438 /// No title bar and no frame: a splash screen, a heads-up panel, a borderless utility. The
10439 /// window still resizes from its edges when resizable; mark the part that moves it with
10440 /// `.window_drag_region()`. `Cap::FramelessWindow`; where unsupported the window keeps its
10441 /// standard frame.
10442 Frameless,
10443}
10444
10445/// What shows behind a window's content (docs/window-chrome.md).
10446#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
10447pub enum WindowBackground {
10448 /// The platform's window background.
10449 #[default]
10450 Opaque,
10451 /// Nothing: pixels the content leaves unpainted show the desktop through the window. For
10452 /// rounded or shaped splash screens and overlays. `Cap::TransparentWindow`.
10453 Transparent,
10454 /// A translucent system material that blurs what is behind the window.
10455 /// `Cap::WindowMaterial`; where unsupported the window stays opaque.
10456 Material(WindowMaterial),
10457}
10458
10459/// The system materials a window background can use ([`WindowBackground::Material`]).
10460#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
10461pub enum WindowMaterial {
10462 /// The main-window material: macOS's window background, Windows 11's Mica.
10463 Window,
10464 /// A sidebar or source list: macOS's sidebar material, Windows 11's Mica Alt (tabbed).
10465 Sidebar,
10466 /// A transient surface (a popover, a menu-like panel, a heads-up display): macOS's popover
10467 /// material, Windows 11's Acrylic.
10468 Transient,
10469}
10470
10471/// Where a window opens ([`WindowOptions::placement`]).
10472#[derive(Clone, Copy, Debug, Default, PartialEq)]
10473pub enum WindowPlacement {
10474 /// The platform's choice: macOS cascades, Windows and Linux let the window manager decide.
10475 #[default]
10476 Automatic,
10477 /// Centered on the screen with the active window.
10478 Centered,
10479 /// The outer frame's top-left corner at this point, in points on the desktop's coordinate
10480 /// space (top-left origin). Falls back to `Automatic` without `Cap::WindowPosition`.
10481 At(Point),
10482}
10483
10484/// A small runtime RGBA image for a status item: charts, meters, or a grid of results.
10485///
10486/// Rows run top to bottom; samples are tightly packed, non-premultiplied sRGB RGBA8.
10487/// `scale` is pixels per logical point (2 for Retina). This owns its bytes, independent of
10488/// any window or decoded-image registry. Currently rendered by AppKit; other backends use
10489/// [`StatusItemSpec::icon`] as a fallback. See docs/status-item.md.
10490#[derive(Clone, PartialEq)]
10491pub struct StatusImage {
10492 width: u32,
10493 height: u32,
10494 scale: f64,
10495 rgba: std::sync::Arc<[u8]>,
10496}
10497
10498impl StatusImage {
10499 /// Validate a runtime image. Rejects empty/mismatched pixels, invalid scales, and images
10500 /// exceeding 16 MiB or 4096 logical points on either axis. No platform allocation occurs.
10501 pub fn rgba(
10502 width: u32,
10503 height: u32,
10504 scale: f64,
10505 pixels: impl Into<std::sync::Arc<[u8]>>,
10506 ) -> Option<Self> {
10507 let rgba = pixels.into();
10508 let expected = (width as usize)
10509 .checked_mul(height as usize)?
10510 .checked_mul(4)?;
10511 if width == 0
10512 || height == 0
10513 || expected > 16 * 1024 * 1024
10514 || rgba.len() != expected
10515 || !scale.is_finite()
10516 || scale <= 0.0
10517 || f64::from(width) / scale > 4096.0
10518 || f64::from(height) / scale > 4096.0
10519 {
10520 return None;
10521 }
10522 Some(Self {
10523 width,
10524 height,
10525 scale,
10526 rgba,
10527 })
10528 }
10529
10530 #[must_use]
10531 pub fn width(&self) -> u32 {
10532 self.width
10533 }
10534 #[must_use]
10535 pub fn height(&self) -> u32 {
10536 self.height
10537 }
10538 #[must_use]
10539 pub fn scale(&self) -> f64 {
10540 self.scale
10541 }
10542 #[must_use]
10543 pub fn pixels(&self) -> &[u8] {
10544 &self.rgba
10545 }
10546 pub fn size(&self) -> Size {
10547 Size::new(
10548 f64::from(self.width) / self.scale,
10549 f64::from(self.height) / self.scale,
10550 )
10551 }
10552}
10553
10554impl std::fmt::Debug for StatusImage {
10555 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
10556 f.debug_struct("StatusImage")
10557 .field("width", &self.width)
10558 .field("height", &self.height)
10559 .field("scale", &self.scale)
10560 .field("bytes", &self.rgba.len())
10561 .finish()
10562 }
10563}
10564
10565#[cfg(test)]
10566mod status_image_tests {
10567 use super::*;
10568
10569 #[test]
10570 fn validates_pixel_layout_and_logical_size() {
10571 let image = StatusImage::rgba(120, 36, 2.0, vec![255; 120 * 36 * 4]).unwrap();
10572 assert_eq!(image.size(), Size::new(60.0, 18.0));
10573 assert_eq!(image.clone(), image);
10574 assert!(StatusImage::rgba(0, 1, 1.0, vec![]).is_none());
10575 assert!(StatusImage::rgba(1, 1, 1.0, vec![0; 3]).is_none());
10576 assert!(StatusImage::rgba(u32::MAX, u32::MAX, 1.0, vec![]).is_none());
10577 for scale in [0.0, -1.0, f64::NAN, f64::INFINITY, 0.00001] {
10578 assert!(StatusImage::rgba(1, 1, scale, vec![0; 4]).is_none());
10579 }
10580 }
10581}
10582
10583/// One status item: an icon in the menu bar (macOS), the notification area (Windows) or a
10584/// `StatusNotifierItem` host's tray (Linux), with a menu (docs/status-item.md).
10585#[derive(Clone, Debug, PartialEq)]
10586pub struct StatusItemSpec {
10587 /// The app's name for the item, stable across updates: what a backend diffs by.
10588 pub id: String,
10589 /// The glyph. `None` shows the title alone (macOS) or the app's icon (elsewhere).
10590 pub icon: Option<Icon>,
10591 /// A runtime image. AppKit prefers this over `icon`, preserving aspect ratio and point
10592 /// size up to 18pt high; other backends ignore it and show `icon`/`title` as before.
10593 pub raster: Option<StatusImage>,
10594 /// Draw the icon as a template: its shape only, in the menu bar's or panel's own color, so
10595 /// it reads in light and dark. Symbols are always templates.
10596 pub template: bool,
10597 /// Text beside the icon where the platform shows one (the macOS menu bar). Empty: icon only.
10598 pub title: String,
10599 /// The hover text.
10600 pub tooltip: String,
10601 /// The menu the item opens. Same model and dispatch as the app menu.
10602 pub menu: Vec<MenuItem>,
10603 /// A dispatch id (the [`Event::MenuAction`] registry) run when the user clicks the item
10604 /// itself, where the platform separates a click from opening the menu (a left click on macOS
10605 /// and Windows, the host's "activate" on Linux). 0: a click opens the menu.
10606 pub activate: u64,
10607}
10608
10609/// One display (docs/windows.md "Monitors"), in points on the desktop's coordinate space:
10610/// top-left origin at the primary display's top-left corner.
10611#[derive(Clone, Debug, PartialEq)]
10612pub struct Monitor {
10613 /// Stable for the display across launches where the platform offers it (a display UUID, a
10614 /// connector name); an index otherwise.
10615 pub id: String,
10616 /// The display's name, for a picker ("Built-in Retina Display", "DELL U2720Q").
10617 pub name: String,
10618 /// The display's whole area.
10619 pub frame: Rect,
10620 /// The part windows should use: the frame minus the menu bar, Dock, taskbar or panels.
10621 pub work_area: Rect,
10622 /// Device pixels per point.
10623 pub scale: f64,
10624 /// The display the desktop's menu bar or primary taskbar is on.
10625 pub primary: bool,
10626}
10627
10628/// A launcher shortcut the app sets while it runs (docs/deep-links.md "Launcher shortcuts"): a
10629/// route to open and the label the launcher shows, already localized.
10630#[derive(Clone, Debug, PartialEq, Eq)]
10631pub struct LauncherShortcut {
10632 /// The route the shortcut opens, through the deep-link intake.
10633 pub route: String,
10634 /// What the launcher shows.
10635 pub label: String,
10636}
10637
10638/// A progress indicator on the app's Dock or taskbar icon ([`Toolkit::set_app_progress`],
10639/// docs/status-item.md).
10640#[derive(Clone, Copy, Debug, Default, PartialEq)]
10641pub enum AppProgress {
10642 /// No indicator.
10643 #[default]
10644 None,
10645 /// Work of unknown length.
10646 Indeterminate,
10647 /// A fraction done, 0.0 to 1.0.
10648 Value(f64),
10649 /// A fraction done, paused. Platforms without a paused state show `Value`.
10650 Paused(f64),
10651 /// A fraction done when the work failed. Platforms without an error state show `Value`.
10652 Error(f64),
10653}
10654
10655/// Whether and how a window joins macOS window tabs ([`WindowOptions::tabbing`],
10656/// `Cap::WindowTabbing`). Other platforms have no system window tabs and ignore it.
10657#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
10658pub enum WindowTabbing {
10659 /// The platform default for the window's kind: an ordinary window tabs with the app's other
10660 /// ordinary windows when the user's "Prefer tabs" setting says so; preferences never tab.
10661 #[default]
10662 Automatic,
10663 /// Tab only with windows of the same group, following the user's setting. The tab bar's
10664 /// "+" opens the builder registered for this group (`register_new_window_for`).
10665 Group(String),
10666 /// Always open as a tab of an existing window of the same group, whatever the setting.
10667 Preferred(String),
10668 /// Never become a tab.
10669 Disallowed,
10670}
10671
10672/// An app's generated locale catalog: `(DEFAULT, CATALOG)`, exactly what `day-build` emits as
10673/// `res::locales::{DEFAULT, CATALOG}` (§18.5). Carried in [`WindowOptions::locales`] so the
10674/// framework can install it at the one moment that is correct.
10675pub type AppLocales = (&'static str, &'static [(&'static str, &'static str)]);
10676
10677#[derive(Clone, Debug)]
10678pub struct WindowOptions {
10679 pub title: String,
10680 pub size: Size,
10681 pub min_size: Option<Size>,
10682 /// Create and mount the window without showing it or activating the app. Supported on
10683 /// AppKit; other backends currently ignore this option. Defaults to false.
10684 ///
10685 /// Menu-bar apps can keep their initial host hidden and open Preferences on demand.
10686 /// The window still exists and can be shown with `WindowHandle::set_visible(true)`;
10687 /// this does not change the app's keep-running policy.
10688 pub start_hidden: bool,
10689 /// Ask the backend to size this window to its content once it has been built and laid out,
10690 /// rather than keeping [`Self::size`] (docs/windows.md). `size` still decides the width and
10691 /// acts as the height ceiling, so a panel with more content than fits the screen scrolls
10692 /// instead of growing past it.
10693 ///
10694 /// What a preferences panel wants on every desktop. Ignored by backends that cannot resize a
10695 /// live window, and by the ones with no windows at all.
10696 pub size_to_fit: bool,
10697 /// The app's display name for the standard application menu / About (macOS). `None` falls back
10698 /// to `title`; set it when `title` carries extra decoration you don't want in `About <name>`
10699 /// (e.g. the showcase's window title is "Day Showcase (AppKit)" but its app name is "Showcase").
10700 pub app_name: Option<String>,
10701 /// The app's locale catalog, installed by `day::launch` (docs/localization.md).
10702 ///
10703 /// The order is why this is the framework's job: the OS's languages reach day-localization from the
10704 /// live backend, and the catalog has to be registered after that hint and before the first
10705 /// localized string is read. An app that installs it itself (before `launch`, where there
10706 /// is no backend yet) registers against an empty hint list and resolves to `DEFAULT`, so a
10707 /// French device opens an English window.
10708 pub locales: Option<AppLocales>,
10709 /// The title, computed once the catalog above is installed: how a window title comes from
10710 /// the catalog rather than a literal. Takes precedence over [`Self::title`], which stays the
10711 /// fallback for the moment before (and for apps with nothing to translate).
10712 ///
10713 /// A plain `fn` rather than a closure: this struct is `Clone`, and the callers are a
10714 /// non-capturing `|| res::str::app_title().format()`, which coerces.
10715 pub title_fn: Option<fn() -> String>,
10716 /// The app's version, for Day's exit line (`Clean exit for <app> v<version> …`,
10717 /// docs/lifecycle.md): `env!("CARGO_PKG_VERSION")` in the app crate, which the scaffold's
10718 /// `window()` sets. `None` falls back to the `DAY_APP_VERSION` the `day` CLI sets on a launch.
10719 pub version: Option<String>,
10720 /// macOS window tabbing for this window (`Cap::WindowTabbing`); ignored elsewhere.
10721 pub tabbing: WindowTabbing,
10722 /// The window's frame: standard, a title bar the content runs under, or none
10723 /// (docs/window-chrome.md). Desktop only; phones and the web ignore it.
10724 pub chrome: WindowChrome,
10725 /// What shows behind the content: the window background, nothing, or a system material.
10726 pub background: WindowBackground,
10727 /// Whether the window casts the platform's drop shadow. A transparent, shaped window often
10728 /// wants none.
10729 pub shadow: bool,
10730 /// Whether the user can resize the window by its edges.
10731 pub resizable: bool,
10732 /// Where the window opens.
10733 pub placement: WindowPlacement,
10734 /// The largest content size the user can resize the window to (`Cap::WindowGeometry`).
10735 pub max_size: Option<Size>,
10736 /// Remember this window's size, position and maximized state under this key, and reopen it
10737 /// that way next launch (docs/windows.md "Remembered frames"). A position that no attached
10738 /// display shows any more is dropped, so a window never reopens off-screen.
10739 pub remember_frame: Option<String>,
10740 /// The logical window this opens (docs/windows.md): `open_window` focuses an already-open
10741 /// window with the same key instead of opening a second (the preferences pattern). `None`
10742 /// always opens a new one.
10743 pub key: Option<String>,
10744 /// The kind of window: a regular one, a preferences panel, an About panel.
10745 pub kind: WindowKind,
10746}
10747
10748impl WindowOptions {
10749 /// The window title. Replaces a [`title_fn`](Self::title_fn) set earlier (the generated
10750 /// `res::window_options()` sets one), so the last title named wins.
10751 #[must_use]
10752 pub fn title(mut self, title: impl Into<String>) -> Self {
10753 self.title = title.into();
10754 self.title_fn = None;
10755 self
10756 }
10757 /// The content size the window opens at (desktop; phones fill the screen).
10758 #[must_use]
10759 pub fn size(mut self, width: f64, height: f64) -> Self {
10760 self.size = Size::new(width, height);
10761 self
10762 }
10763 /// The smallest content size the user can resize to.
10764 #[must_use]
10765 pub fn min_size(mut self, width: f64, height: f64) -> Self {
10766 self.min_size = Some(Size::new(width, height));
10767 self
10768 }
10769 /// The largest content size the user can resize to (`Cap::WindowGeometry`).
10770 #[must_use]
10771 pub fn max_size(mut self, width: f64, height: f64) -> Self {
10772 self.max_size = Some(Size::new(width, height));
10773 self
10774 }
10775 /// Create and mount the window without showing it; see [`Self::start_hidden`].
10776 #[must_use]
10777 pub fn start_hidden(mut self) -> Self {
10778 self.start_hidden = true;
10779 self
10780 }
10781 /// Size the window to its content once built; see [`Self::size_to_fit`].
10782 #[must_use]
10783 pub fn size_to_fit(mut self) -> Self {
10784 self.size_to_fit = true;
10785 self
10786 }
10787 /// The app's display name for the application menu and About; see [`Self::app_name`].
10788 #[must_use]
10789 pub fn app_name(mut self, name: impl Into<String>) -> Self {
10790 self.app_name = Some(name.into());
10791 self
10792 }
10793 /// The app's locale catalog, as `res::locales::{DEFAULT, CATALOG}`; see [`Self::locales`].
10794 #[must_use]
10795 pub fn locales(
10796 mut self,
10797 default: &'static str,
10798 catalog: &'static [(&'static str, &'static str)],
10799 ) -> Self {
10800 self.locales = Some((default, catalog));
10801 self
10802 }
10803 /// The title, computed once the catalog is installed; see [`Self::title_fn`].
10804 #[must_use]
10805 pub fn title_fn(mut self, f: fn() -> String) -> Self {
10806 self.title_fn = Some(f);
10807 self
10808 }
10809 /// The app's version, for Day's exit line; see [`Self::version`].
10810 #[must_use]
10811 pub fn version(mut self, version: impl Into<String>) -> Self {
10812 self.version = Some(version.into());
10813 self
10814 }
10815 /// macOS window tabbing for this window; see [`Self::tabbing`].
10816 #[must_use]
10817 pub fn tabbing(mut self, tabbing: WindowTabbing) -> Self {
10818 self.tabbing = tabbing;
10819 self
10820 }
10821 /// The window's frame; see [`Self::chrome`].
10822 #[must_use]
10823 pub fn chrome(mut self, chrome: WindowChrome) -> Self {
10824 self.chrome = chrome;
10825 self
10826 }
10827 /// What shows behind the content; see [`Self::background`].
10828 #[must_use]
10829 pub fn background(mut self, background: WindowBackground) -> Self {
10830 self.background = background;
10831 self
10832 }
10833 /// No drop shadow, for a transparent or shaped window; see [`Self::shadow`].
10834 #[must_use]
10835 pub fn no_shadow(mut self) -> Self {
10836 self.shadow = false;
10837 self
10838 }
10839 /// A window the user cannot resize; see [`Self::resizable`].
10840 #[must_use]
10841 pub fn fixed_size(mut self) -> Self {
10842 self.resizable = false;
10843 self
10844 }
10845 /// Where the window opens; see [`Self::placement`].
10846 #[must_use]
10847 pub fn placement(mut self, placement: WindowPlacement) -> Self {
10848 self.placement = placement;
10849 self
10850 }
10851 /// Remember and restore this window's frame under `key`; see [`Self::remember_frame`].
10852 #[must_use]
10853 pub fn remember_frame(mut self, key: impl Into<String>) -> Self {
10854 self.remember_frame = Some(key.into());
10855 self
10856 }
10857 /// The logical window this opens; see [`Self::key`].
10858 #[must_use]
10859 pub fn key(mut self, key: impl Into<String>) -> Self {
10860 self.key = Some(key.into());
10861 self
10862 }
10863 /// The kind of window; see [`Self::kind`].
10864 #[must_use]
10865 pub fn kind(mut self, kind: WindowKind) -> Self {
10866 self.kind = kind;
10867 self
10868 }
10869}
10870
10871impl Default for WindowOptions {
10872 fn default() -> Self {
10873 WindowOptions {
10874 title: "Day".into(),
10875 size: Size::new(480.0, 640.0),
10876 min_size: None,
10877 start_hidden: false,
10878 size_to_fit: false,
10879 app_name: None,
10880 locales: None,
10881 title_fn: None,
10882 version: None,
10883 tabbing: WindowTabbing::Automatic,
10884 chrome: WindowChrome::Standard,
10885 background: WindowBackground::Opaque,
10886 shadow: true,
10887 resizable: true,
10888 placement: WindowPlacement::Automatic,
10889 max_size: None,
10890 remember_frame: None,
10891 key: None,
10892 kind: WindowKind::Normal,
10893 }
10894 }
10895}
10896
10897/// A platform backend: owns the native main loop and exactly one window in v1 (§8.1).
10898///
10899/// `run` sets up the native app + window, installs the reactive scheduler + main poster,
10900/// then hands `(self, root_container, content_size)` to `ready` (which mounts the tree and
10901/// takes ownership of the backend), and finally runs the native main loop.
10902pub trait Platform: Toolkit {
10903 /// The process-constant target id, e.g. `"macos-appkit"`.
10904 const TARGET: &'static str;
10905 /// The toolkit half of the target, e.g. `"appkit"`.
10906 const TOOLKIT: &'static str;
10907 /// Whether [`Platform::run`] returning means the app is over. True for a backend that
10908 /// drives the native loop itself until the app quits (GTK, Qt, XAML; AppKit's never
10909 /// returns). False where the host owns the loop and `run` hands back at once, with the
10910 /// app still to come (ArkUI's ability, Android's activity, the web page, the mock's test):
10911 /// their `DidExit` is the host's last callback, not the return (docs/lifecycle.md).
10912 const RUN_ENDS_APP: bool = true;
10913
10914 fn run(self, options: WindowOptions, ready: Box<dyn FnOnce(Self, Self::Handle, Size)>);
10915
10916 /// Post a closure onto the native main loop. Callable from any thread; this is the
10917 /// single door the reactive scheduler and `Setter` deliveries ride (§3.3).
10918 fn post(f: Box<dyn FnOnce() + Send>);
10919
10920 /// Post `f` onto the native main loop after (at least) `ms` milliseconds: the timer
10921 /// door behind `day::sleep` (docs/async.md). Every shipped backend overrides it with the
10922 /// loop's own timer (`dispatch_after`, `Handler.postDelayed`, `g_timeout_add`,
10923 /// `QTimer::singleShot`, `SetTimer`, `setTimeout`), so a sleep costs no thread. The
10924 /// default is the fallback for a backend without one: a helper thread that sleeps the
10925 /// whole delay and rides [`Platform::post`] home. It is correct, but a thread per sleep
10926 /// adds up under a ticking loop, so the first use says so once in the log.
10927 fn post_delayed(ms: u32, f: Box<dyn FnOnce() + Send>) {
10928 static SAID: std::sync::Once = std::sync::Once::new();
10929 SAID.call_once(|| {
10930 log::warn!(
10931 "day: {} has no native timer door; `day::sleep` falls back to a helper thread \
10932 per delay (implement `Platform::post_delayed`)",
10933 Self::TARGET
10934 );
10935 });
10936 std::thread::spawn(move || {
10937 std::thread::sleep(std::time::Duration::from_millis(u64::from(ms)));
10938 Self::post(f);
10939 });
10940 }
10941
10942 /// Ordered OS locale preference list (BCP-47), for fluent-langneg (§12.2).
10943 fn locale_hints(&self) -> Vec<String> {
10944 Vec::new()
10945 }
10946}
10947
10948// ---------------------------------------------------------------------------
10949// Open renderer registry (§8.2)
10950// ---------------------------------------------------------------------------
10951
10952/// The scale a window snapshot is rendered at, when a scripted run states one
10953/// (`DAY_CAPTURE_SCALE=2`, set by `day launch --script` from Day.toml `[screenshots]`).
10954///
10955/// For the backends that render their own snapshot (GTK, Qt): the capture then measures
10956/// window points times this, whatever display the host has, which is what makes a CI capture
10957/// under a 1x xvfb the same 2560x1600 pixels a HiDPI laptop produces. A backend that reads the
10958/// compositor's pixels back (AppKit, XAML) captures at the display's own scale and ignores it.
10959/// `None` when unset or unparseable: capture at the backend's natural scale.
10960#[must_use]
10961pub fn capture_scale() -> Option<f64> {
10962 std::env::var("DAY_CAPTURE_SCALE")
10963 .ok()
10964 .and_then(|v| v.trim().parse::<f64>().ok())
10965 .filter(|s| s.is_finite() && (0.5..=4.0).contains(s))
10966}
10967
10968/// Seconds on a monotonic clock since the first call: the frame timestamp for a backend that
10969/// does not expose a native timestamp (§8.4). The origin is arbitrary. Not for the web
10970/// build, where `Instant` is unavailable and `requestAnimationFrame` stamps the frame itself.
10971pub fn frame_timestamp() -> f64 {
10972 static ORIGIN: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new();
10973 ORIGIN
10974 .get_or_init(std::time::Instant::now)
10975 .elapsed()
10976 .as_secs_f64()
10977}
10978
10979/// The user's language preference from the POSIX environment, newest-first, as BCP-47 tags.
10980///
10981/// `LANGUAGE` is the GNU multi-language list (`fr:en`); `LC_ALL`, `LC_MESSAGES` and `LANG` each
10982/// carry one locale in POSIX form (`fr_FR.UTF-8`), which becomes `fr-FR`. Shared by the backends
10983/// whose platform has no richer API to ask (§12.2, docs/localization.md).
10984#[must_use]
10985pub fn posix_locale_hints() -> Vec<String> {
10986 let mut out: Vec<String> = Vec::new();
10987 let mut push = |tag: &str| {
10988 // "C" and "POSIX" are the absence of a preference, not a language.
10989 let tag = tag.split('.').next().unwrap_or(tag).replace('_', "-");
10990 if tag.is_empty() || tag == "C" || tag == "POSIX" {
10991 return;
10992 }
10993 if !out.contains(&tag) {
10994 out.push(tag);
10995 }
10996 };
10997 if let Ok(list) = std::env::var("LANGUAGE") {
10998 for tag in list.split(':') {
10999 push(tag);
11000 }
11001 }
11002 for key in ["LC_ALL", "LC_MESSAGES", "LANG"] {
11003 if let Ok(v) = std::env::var(key) {
11004 push(&v);
11005 }
11006 }
11007 out
11008}
11009
11010/// Optional custom measure for a third-party piece (§8.2).
11011pub type MeasureFn<B> = fn(&mut B, &<B as Toolkit>::Handle, Proposal) -> Size;
11012
11013/// A third-party piece's per-toolkit implementation. `make` receives the concrete backend
11014/// (public helper surface) and returns a native handle the backend then owns like any built-in.
11015pub struct Renderer<B: Toolkit> {
11016 pub kind: PieceKind,
11017 pub make: fn(&mut B, &dyn Any, NodeId) -> B::Handle,
11018 pub update: fn(&mut B, &B::Handle, &dyn Any),
11019 pub measure: Option<MeasureFn<B>>,
11020 /// Teardown, run from the release queue just before [`Toolkit::release`] frees the handle.
11021 ///
11022 /// A piece that keeps per-view state (a retained delegate, a session map, a native
11023 /// observer) has no other place to drop it: `make`/`update` are the only other hooks, and a
11024 /// disposed node never calls them again. Without this a piece leaks one entry per realized
11025 /// view, and any map keyed by the handle's address can go on to answer for a later view that
11026 /// the allocator hands the same address.
11027 ///
11028 /// `None` for the pieces that own nothing (most of them).
11029 pub release: Option<fn(&mut B, &B::Handle)>,
11030}
11031
11032pub struct Registry<B: Toolkit> {
11033 map: HashMap<PieceKind, Renderer<B>>,
11034}
11035
11036impl<B: Toolkit> Default for Registry<B> {
11037 fn default() -> Self {
11038 Registry {
11039 map: HashMap::new(),
11040 }
11041 }
11042}
11043
11044impl<B: Toolkit> Registry<B> {
11045 pub fn register(&mut self, r: Renderer<B>) {
11046 let kind = r.kind;
11047 if self.map.insert(kind, r).is_some() {
11048 // Two pieces claiming one kind is last-linked-wins in link order, effectively
11049 // nondeterministic. Fail loudly in debug; in release, say so once at boot rather
11050 // than render the wrong widget silently.
11051 debug_assert!(
11052 false,
11053 "duplicate renderer registered for piece kind {kind:?}"
11054 );
11055 log::warn!("duplicate renderer for piece kind {kind:?} — later registration wins");
11056 }
11057 }
11058 #[must_use]
11059 pub fn get(&self, kind: PieceKind) -> Option<&Renderer<B>> {
11060 self.map.get(kind)
11061 }
11062 pub fn kinds(&self) -> impl Iterator<Item = PieceKind> + '_ {
11063 self.map.keys().copied()
11064 }
11065}
11066
11067/// The canvas wire op codes (§11, §15.3): slot 0 of every 9-number record in
11068/// [`encode_ops`]'s output. The numeric values are the frozen wire contract: the JNI, C++,
11069/// and JS decoders each hand-write these as constants, so a value here may never be reused
11070/// or renumbered; new ops append. `ALL` drives the density test that keeps this enum and
11071/// the encoder in step.
11072#[derive(Clone, Copy, Debug, PartialEq, Eq)]
11073#[repr(i32)]
11074pub enum OpCode {
11075 /// Fill a rect (a,b=origin, c,d=size).
11076 FillRect = 0,
11077 /// Stroke a rect (g=width).
11078 StrokeRect = 1,
11079 /// Fill a rounded rect (e=radius).
11080 FillRrect = 2,
11081 /// Fill an ellipse in a rect.
11082 FillEllipse = 3,
11083 /// Stroke an ellipse (g=width).
11084 StrokeEllipse = 4,
11085 /// Stroke an arc (e=start°, f=sweep°, g=width). `Fill(Shape::Arc)` also encodes as
11086 /// this with width 0, the known asymmetry; see [`encode_ops`].
11087 StrokeArc = 5,
11088 /// Line a,b → c,d (g=width).
11089 Line = 6,
11090 /// Text at a,b (e=size, f=anchor: 0 leading / 1 centered); the string rides the texts
11091 /// channel.
11092 Text = 7,
11093 /// Save the graphics state.
11094 Save = 8,
11095 /// Restore the graphics state.
11096 Restore = 9,
11097 /// Concat an affine transform (a..f).
11098 Concat = 10,
11099 /// Fill a polygon; points ride the texts channel as "x,y x,y …" (closed automatically),
11100 /// or the geometry channel of [`encode_ops_with_geometry`] (b = offset, c = count, and
11101 /// the texts entry is empty). `a` = the [`geometry_key`] of those points, or 0 for none.
11102 FillPolygon = 11,
11103 /// Stroke a polygon (g=width); points and key as [`OpCode::FillPolygon`].
11104 StrokePolygon = 12,
11105 /// Stroke a rounded rect (e=radius, g=width).
11106 StrokeRrect = 13,
11107 /// Set a gradient for the next shape record (f=type: 0 linear with a,b=start / c,d=end
11108 /// unit points; 1 radial with a,b=center unit point, c=unit radius; 2 conic with
11109 /// a,b=center unit point, c=start angle in canvas degrees, clockwise from +x, the stops
11110 /// running one full turn from it ([`ConicGradient`]); e=stop count).
11111 /// Stops ride the texts channel as "offset,aarrggbb offset,aarrggbb …". Unit geometry
11112 /// resolves against the shape's bounding box.
11113 SetGradient = 14,
11114 /// Fill a path (f=fill rule: 0 non-zero / 1 even-odd); segments ride the texts channel
11115 /// (see [`encode_path`]), or the geometry channel of [`encode_ops_with_geometry`]
11116 /// (b = offset, c = count, see [`path_numbers`]; the texts entry is empty). `a` = the
11117 /// [`geometry_key`] of those segments, or 0 for none.
11118 ///
11119 /// The key is a cache handle, not a payload: a decoder that recognizes it may keep the
11120 /// native geometry it built last time and skip re-parsing the segments, but it must still
11121 /// consume the texts entry either way, because that channel is positional and a skipped
11122 /// entry desynchronizes every record after it.
11123 FillPath = 15,
11124 /// Stroke a path (g=width); segments and key as [`OpCode::FillPath`].
11125 StrokePath = 16,
11126 /// Clip to a shape (f=shape kind: 0 rect / 1 rrect(e=radius) / 2 ellipse / 3 path
11127 /// (e=fill rule) / 4 polygon; a..d=geometry; path/polygon payloads ride the texts
11128 /// channel).
11129 ///
11130 /// For the two payload-bearing kinds (3 and 4) there is no geometry in the slots, so `a`
11131 /// carries the [`geometry_key`] instead, b and c the geometry channel's offset and count
11132 /// when there is one, and d stays 0. The other three kinds put real geometry in a..d and
11133 /// have nothing to cache.
11134 Clip = 17,
11135 /// Stroke style for the next stroke record (a=cap, b=join, c=miter limit, d=dash
11136 /// phase, e=dash count; the dash array rides the texts channel).
11137 StrokeStyle = 18,
11138 /// Font for the next text record (a=CSS weight 100 … 900, 0 = default; b=italic 0/1); the
11139 /// family name rides the texts channel, `""` = the platform's default face. Like
11140 /// [`OpCode::SetGradient`] and [`OpCode::StrokeStyle`] it is consumed by the record that
11141 /// follows and then cleared; a default [`CanvasFont`] emits no record at all, so a drawing
11142 /// without fonts encodes exactly as it did before this op existed.
11143 SetFont = 19,
11144 /// The next shape record is a template, drawn once per stamped position rather than once
11145 /// (docs/canvas.md "Stamping"). `a` = how many positions follow. Like [`OpCode::SetGradient`],
11146 /// [`OpCode::StrokeStyle`] and [`OpCode::SetFont`] it is a prefix, consumed by the record it
11147 /// applies to and then cleared.
11148 ///
11149 /// Between this and that template record come `ceil(a / 4)` [`OpCode::StampPoints`] records
11150 /// carrying the coordinates. A drawing with no stamps encodes exactly as it did before.
11151 Stamp = 20,
11152 /// Four stamped positions, filling the record edge to edge: `[op, x0, y0, x1, y1, x2, y2,
11153 /// x3, y3]`, the one record that uses its last slot for geometry instead of a color, because
11154 /// it carries no color of its own. The final record of a run is padded; the count in the
11155 /// [`OpCode::Stamp`] header says how many of the pairs are real.
11156 StampPoints = 21,
11157 /// Draw a decoded image: `a,b` = origin, `c,d` = size, `e` = the [`BitmapId`], `f` = opacity
11158 /// in `0.0..=1.0` (docs/images.md).
11159 ///
11160 /// The id rides the numeric channel because it is a number, and an `f64` carries a `u64` id
11161 /// exactly up to 2^53; ids are minted from 1 per process, so that ceiling is unreachable.
11162 /// Nothing rides the texts channel for this op.
11163 Image = 22,
11164 /// The source region for the next image record (`a,b` = origin, `c,d` = size, in the
11165 /// bitmap's own pixels): [`DrawOp::Image`]'s `source`. Like [`OpCode::SetFont`] it is a
11166 /// prefix, consumed by the record that follows and then cleared, and a whole-image draw
11167 /// emits none, so a drawing without regions encodes exactly as it did before this op
11168 /// existed. A decoder clamps the region to the bitmap and draws nothing for an empty
11169 /// intersection ([`clamp_image_source`]).
11170 ImageSource = 23,
11171 /// Set the shadow cast by every drawing record that follows: `a,b` = offset in points,
11172 /// `c` = blur radius (the CSS `box-shadow` blur, twice the Gaussian's standard deviation),
11173 /// the color slot = the shadow's color. A fully transparent color clears the shadow.
11174 ///
11175 /// Unlike the prefix records this is graphics state: it stays set until another
11176 /// [`OpCode::SetShadow`] or the [`OpCode::Restore`] that matches the [`OpCode::Save`] it was
11177 /// set under, so a decoder whose native context does not save it must keep its own stack.
11178 /// The offset and blur are not transformed by [`OpCode::Concat`].
11179 SetShadow = 24,
11180 /// Set the blend mode for every drawing record that follows: `a` = [`BlendMode::wire`]
11181 /// (0 normal, 1 multiply, 2 screen, 3 overlay, 4 darken, 5 lighten, 6 add, 7 erase).
11182 /// Graphics state, scoped by save and restore exactly as [`OpCode::SetShadow`] is. A decoder
11183 /// that meets a number it does not know draws with the normal mode.
11184 SetBlend = 25,
11185}
11186
11187impl OpCode {
11188 /// Every code, in wire order. The density test iterates this so a new variant that
11189 /// forgets to join fails loudly.
11190 pub const ALL: [OpCode; 26] = [
11191 OpCode::FillRect,
11192 OpCode::StrokeRect,
11193 OpCode::FillRrect,
11194 OpCode::FillEllipse,
11195 OpCode::StrokeEllipse,
11196 OpCode::StrokeArc,
11197 OpCode::Line,
11198 OpCode::Text,
11199 OpCode::Save,
11200 OpCode::Restore,
11201 OpCode::Concat,
11202 OpCode::FillPolygon,
11203 OpCode::StrokePolygon,
11204 OpCode::StrokeRrect,
11205 OpCode::SetGradient,
11206 OpCode::FillPath,
11207 OpCode::StrokePath,
11208 OpCode::Clip,
11209 OpCode::StrokeStyle,
11210 OpCode::SetFont,
11211 OpCode::Stamp,
11212 OpCode::StampPoints,
11213 OpCode::Image,
11214 OpCode::ImageSource,
11215 OpCode::SetShadow,
11216 OpCode::SetBlend,
11217 ];
11218
11219 /// The code back from a wire number (a decoder-side aid and the round-trip test's
11220 /// reference); `None` for anything outside the table.
11221 #[must_use]
11222 #[expect(
11223 clippy::float_cmp,
11224 reason = "wire codes are small integers, which f64 represents exactly"
11225 )]
11226 pub fn from_wire(n: f64) -> Option<OpCode> {
11227 OpCode::ALL.into_iter().find(|c| f64::from(*c as i32) == n)
11228 }
11229}
11230
11231/// Flat numeric encoding of a display list for shim/JNI boundaries (§11, §15.3): per op
11232/// 9 numbers [kind, a, b, c, d, e, f, g, rgba-bits]; text payloads ride separately in order.
11233/// The kind slot carries an [`OpCode`]; its doc comments are the per-slot contract.
11234///
11235/// Transports join `texts` with the unit separator U+001F (one entry per text-carrying
11236/// record, in order), so text payloads must not contain U+001F. Known asymmetry:
11237/// `Fill(Shape::Arc)` encodes as [`OpCode::StrokeArc`] with width 0. Filled arcs render
11238/// only on the direct-replay backends (AppKit/UIKit); use a polygon fan if a filled arc
11239/// must be portable.
11240/// Serialize a path for the `texts` side-channel: one space-separated token per segment,
11241/// `M x y` / `L x y` / `Q cx cy x y` / `C c1x c1y c2x c2y x y` / `Z`.
11242///
11243/// Text rather than numbers because that is the channel the encoder already has for
11244/// variable-length payloads, and every decoder (JS, Java, C++) can already split a string. The
11245/// numeric channel is a flat `[f64; 9]`-per-record array with no length prefix, so a path could
11246/// not ride it without changing the record shape for every backend at once.
11247/// A content key for a shape's variable-length geometry: the handle a backend caches decoded
11248/// native geometry under (a `Path2D`, a `QPainterPath`, an `android.graphics.Path`) so an
11249/// unchanged path is rebuilt once instead of re-parsed out of the texts channel every frame.
11250///
11251/// It hashes the geometry, not the op's position or its identity, so that a draw closure that
11252/// rebuilds its `PathBuilder` chain from scratch on every frame (which is what canvas consumers
11253/// do) produces an equal path, hashes the same and hits the same entry. An identity would miss
11254/// every time.
11255///
11256/// Two different paths that collided would draw each other, so the width matters: FNV-1a over the
11257/// IEEE bits, masked to the 53 bits an `f64` wire slot carries exactly. `0.0` is reserved for "no
11258/// key": a decoder seeing it must decode the payload as it always did, which is also what every
11259/// decoder written before this key existed does with the slot.
11260#[must_use]
11261pub fn geometry_key(shape: &Shape) -> f64 {
11262 fn mix(h: &mut u64, v: f64) {
11263 for byte in v.to_bits().to_le_bytes() {
11264 *h ^= u64::from(byte);
11265 *h = h.wrapping_mul(0x0000_0100_0000_01b3);
11266 }
11267 }
11268 fn mix_point(h: &mut u64, p: Point) {
11269 mix(h, p.x);
11270 mix(h, p.y);
11271 }
11272 let mut h: u64 = 0xcbf2_9ce4_8422_2325;
11273 match shape {
11274 Shape::Polygon(pts) => {
11275 // The discriminant joins the hash so a polygon and a path of the same points can
11276 // never share an entry: they decode to different geometry.
11277 mix(&mut h, 11.0);
11278 for p in pts {
11279 mix_point(&mut h, *p);
11280 }
11281 }
11282 Shape::Path(path) => {
11283 mix(&mut h, 15.0);
11284 mix(&mut h, rule_bits(path.rule));
11285 for seg in &path.segs {
11286 match seg {
11287 PathSeg::Move(a) => {
11288 mix(&mut h, 0.0);
11289 mix_point(&mut h, *a);
11290 }
11291 PathSeg::Line(a) => {
11292 mix(&mut h, 1.0);
11293 mix_point(&mut h, *a);
11294 }
11295 PathSeg::Quad(c, a) => {
11296 mix(&mut h, 2.0);
11297 mix_point(&mut h, *c);
11298 mix_point(&mut h, *a);
11299 }
11300 PathSeg::Cubic(c1, c2, a) => {
11301 mix(&mut h, 3.0);
11302 mix_point(&mut h, *c1);
11303 mix_point(&mut h, *c2);
11304 mix_point(&mut h, *a);
11305 }
11306 PathSeg::Close => mix(&mut h, 4.0),
11307 }
11308 }
11309 }
11310 // Everything else puts its whole geometry in the record's own slots, so there is nothing
11311 // to parse and nothing worth caching.
11312 _ => return 0.0,
11313 }
11314 let masked = h & ((1u64 << 53) - 1);
11315 // 0 means "no key", so the one hash that lands there borrows its neighbor.
11316 if masked == 0 { 1.0 } else { masked as f64 }
11317}
11318
11319/// Append a coordinate to the texts channel: a plain decimal with up to six fractional digits
11320/// and no trailing zeros (`12`, `-0.5`, `183.472938`), never an exponent.
11321///
11322/// Six decimals of a canvas point is a millionth of a point, far below anything a transform an
11323/// app would draw under can bring to a pixel, and the fixed form costs a tenth of the shortest
11324/// round-trip repr: one integer write instead of a float formatter and a temporary `String` per
11325/// coordinate, which was the larger half of a map tile's export on Android. The decoders parse
11326/// with their platform's general float reader, so a value the fixed form cannot carry (a
11327/// non-finite number, a magnitude past 2^53 millionths) falls back to `Display`.
11328fn push_wire_num(out: &mut String, v: f64) {
11329 use std::fmt::Write as _;
11330 const SCALE: f64 = 1_000_000.0;
11331 let scaled = (v * SCALE).round();
11332 if scaled.is_nan() || scaled.abs() >= 9.0e15 {
11333 let _ = write!(out, "{v}");
11334 return;
11335 }
11336 let mut n = scaled as i64;
11337 if n < 0 {
11338 out.push('-');
11339 n = -n;
11340 }
11341 let whole = n / 1_000_000;
11342 let mut frac = n % 1_000_000;
11343 let _ = write!(out, "{whole}");
11344 if frac != 0 {
11345 let mut digits = 6;
11346 while frac % 10 == 0 {
11347 frac /= 10;
11348 digits -= 1;
11349 }
11350 out.push('.');
11351 let _ = write!(out, "{frac:0digits$}");
11352 }
11353}
11354
11355/// Polygon points for the texts channel: `"x,y x,y …"`, numbers as [`push_wire_num`] writes
11356/// them.
11357fn encode_points(pts: &[Point]) -> String {
11358 let mut out = String::with_capacity(pts.len() * 16);
11359 for p in pts {
11360 if !out.is_empty() {
11361 out.push(' ');
11362 }
11363 push_wire_num(&mut out, p.x);
11364 out.push(',');
11365 push_wire_num(&mut out, p.y);
11366 }
11367 out
11368}
11369
11370/// Path segments for the texts channel: `"M x y L x y Q cx cy x y C … Z"`, one token per
11371/// command or number. Coordinates use up to six decimal places, without trailing zeros;
11372/// non-finite values and magnitudes outside the fixed-point range use their display form.
11373#[must_use]
11374pub fn encode_path(path: &Path) -> String {
11375 let mut out = String::with_capacity(path.segs.len() * 16);
11376 let points = |out: &mut String, cmd: char, pts: &[Point]| {
11377 if !out.is_empty() {
11378 out.push(' ');
11379 }
11380 out.push(cmd);
11381 for p in pts {
11382 out.push(' ');
11383 push_wire_num(out, p.x);
11384 out.push(' ');
11385 push_wire_num(out, p.y);
11386 }
11387 };
11388 for seg in &path.segs {
11389 match seg {
11390 PathSeg::Move(p) => points(&mut out, 'M', &[*p]),
11391 PathSeg::Line(p) => points(&mut out, 'L', &[*p]),
11392 PathSeg::Quad(c, p) => points(&mut out, 'Q', &[*c, *p]),
11393 PathSeg::Cubic(a, b, p) => points(&mut out, 'C', &[*a, *b, *p]),
11394 PathSeg::Close => points(&mut out, 'Z', &[]),
11395 }
11396 }
11397 out
11398}
11399
11400/// Clamp a [`DrawOp::Image`] `source` region to the bitmap it indexes (`pixels` wide and high),
11401/// keeping the region's mapping into `rect`: the answer is the part of the region inside the
11402/// bitmap and the part of `rect` it lands in.
11403///
11404/// The single definition of what an out-of-range region means. The mapping is kept rather than
11405/// the clamped part stretched over the whole of `rect`, because that is what every native
11406/// sub-rect draw does on its own (Qt, the HTML canvas) and what the clip-and-scale fallback
11407/// gives for free, so the backends agree. `None` (an empty region, an empty intersection, or a
11408/// bitmap with no pixels) draws nothing. Every backend that replays in Rust calls this; the
11409/// C++/Java/JS decoders repeat the same arithmetic.
11410#[must_use]
11411pub fn clamp_image_source(source: Rect, rect: Rect, pixels: Size) -> Option<(Rect, Rect)> {
11412 if !(source.size.width > 0.0 && source.size.height > 0.0) {
11413 return None;
11414 }
11415 let x0 = source.origin.x.max(0.0);
11416 let y0 = source.origin.y.max(0.0);
11417 let x1 = (source.origin.x + source.size.width).min(pixels.width);
11418 let y1 = (source.origin.y + source.size.height).min(pixels.height);
11419 if !(x1 > x0 && y1 > y0) {
11420 return None;
11421 }
11422 let kx = rect.size.width / source.size.width;
11423 let ky = rect.size.height / source.size.height;
11424 let dest = Rect::new(
11425 rect.origin.x + (x0 - source.origin.x) * kx,
11426 rect.origin.y + (y0 - source.origin.y) * ky,
11427 (x1 - x0) * kx,
11428 (y1 - y0) * ky,
11429 );
11430 Some((Rect::new(x0, y0, x1 - x0, y1 - y0), dest))
11431}
11432
11433/// `FillRule` as a wire number: 0 non-zero, 1 even-odd.
11434fn rule_bits(rule: FillRule) -> f64 {
11435 match rule {
11436 FillRule::NonZero => 0.0,
11437 FillRule::EvenOdd => 1.0,
11438 }
11439}
11440
11441/// Encode a display list for a decoder written in another language (Java, C++, JS): the
11442/// numbers channel, nine `f64` slots per record (`[kind, a, b, c, d, e, f, g, color]`, kinds
11443/// from [`OpCode`]), and the texts channel, one entry per record that carries text or
11444/// variable-length geometry, in record order.
11445#[must_use]
11446pub fn encode_ops(ops: &[DrawOp]) -> (Vec<f64>, Vec<String>) {
11447 encode_ops_into(ops, None)
11448}
11449
11450/// [`encode_ops`] with a third, geometry channel: the points of every path and polygon (fills,
11451/// strokes, clips) as numbers instead of text. Such a record's slot `b` is its offset into the
11452/// channel and slot `c` its count, and its texts entry is empty, so that channel stays
11453/// positional for a decoder that ignores the third one. Paths are written by
11454/// [`path_numbers`], polygons by [`point_numbers`].
11455///
11456/// Formatting a coordinate and parsing it back were, together, half of what a map tile's export
11457/// cost on Android (docs/canvas.md "Exporting"); a decoder that can take an array of doubles
11458/// across its boundary skips both.
11459#[must_use]
11460pub fn encode_ops_with_geometry(ops: &[DrawOp]) -> (Vec<f64>, Vec<String>, Vec<f64>) {
11461 let mut geometry = Vec::new();
11462 let (nums, texts) = encode_ops_into(ops, Some(&mut geometry));
11463 (nums, texts, geometry)
11464}
11465
11466/// A path's segments for the geometry channel: a command code, then its points — `0` move
11467/// (x y), `1` line (x y), `2` quad (cx cy x y), `3` cubic (x1 y1 x2 y2 x y), `4` close.
11468pub fn path_numbers(path: &Path, out: &mut Vec<f64>) {
11469 for seg in &path.segs {
11470 match seg {
11471 PathSeg::Move(p) => out.extend_from_slice(&[0.0, p.x, p.y]),
11472 PathSeg::Line(p) => out.extend_from_slice(&[1.0, p.x, p.y]),
11473 PathSeg::Quad(c, p) => out.extend_from_slice(&[2.0, c.x, c.y, p.x, p.y]),
11474 PathSeg::Cubic(a, b, p) => out.extend_from_slice(&[3.0, a.x, a.y, b.x, b.y, p.x, p.y]),
11475 PathSeg::Close => out.push(4.0),
11476 }
11477 }
11478}
11479
11480/// A polygon's points for the geometry channel: x then y, per point.
11481pub fn point_numbers(pts: &[Point], out: &mut Vec<f64>) {
11482 for p in pts {
11483 out.push(p.x);
11484 out.push(p.y);
11485 }
11486}
11487
11488/// Put a path's or polygon's points on the wire: on the geometry channel when the caller opened
11489/// one, as `numbers` writes them, answering (offset, count) for slots b and c and leaving an
11490/// empty texts entry; else as `text` on the texts channel, answering (0, 0).
11491fn geometry_payload(
11492 geometry: &mut Option<&mut Vec<f64>>,
11493 texts: &mut Vec<String>,
11494 text: impl FnOnce() -> String,
11495 numbers: impl FnOnce(&mut Vec<f64>),
11496) -> (f64, f64) {
11497 if let Some(g) = geometry {
11498 let offset = g.len();
11499 numbers(g);
11500 texts.push(String::new());
11501 (offset as f64, (g.len() - offset) as f64)
11502 } else {
11503 texts.push(text());
11504 (0.0, 0.0)
11505 }
11506}
11507
11508fn encode_ops_into(ops: &[DrawOp], mut geometry: Option<&mut Vec<f64>>) -> (Vec<f64>, Vec<String>) {
11509 fn color_bits(c: Color) -> f64 {
11510 let r = (c.r.clamp(0.0, 1.0) * 255.0) as u32;
11511 let g = (c.g.clamp(0.0, 1.0) * 255.0) as u32;
11512 let b = (c.b.clamp(0.0, 1.0) * 255.0) as u32;
11513 let a = (c.a.clamp(0.0, 1.0) * 255.0) as u32;
11514 f64::from((a << 24) | (r << 16) | (g << 8) | b)
11515 }
11516 #[allow(clippy::too_many_arguments)]
11517 fn push(
11518 k: OpCode,
11519 a: f64,
11520 b: f64,
11521 c: f64,
11522 d: f64,
11523 e: f64,
11524 f: f64,
11525 g: f64,
11526 col: Color,
11527 nums: &mut Vec<f64>,
11528 ) {
11529 nums.extend_from_slice(&[f64::from(k as i32), a, b, c, d, e, f, g, color_bits(col)]);
11530 }
11531 /// The kind-18 prefix a non-plain stroke style emits, applying to the next stroke record,
11532 /// the same "modifier record" rule the gradient and font records follow. A plain style emits
11533 /// nothing, so a drawing without dashes or caps encodes exactly as it always did.
11534 fn stroke_style_record(style: &StrokeStyle, nums: &mut Vec<f64>, texts: &mut Vec<String>) {
11535 if style.is_plain() {
11536 return;
11537 }
11538 push(
11539 OpCode::StrokeStyle,
11540 match style.cap {
11541 LineCap::Butt => 0.0,
11542 LineCap::Round => 1.0,
11543 LineCap::Square => 2.0,
11544 },
11545 match style.join {
11546 LineJoin::Miter => 0.0,
11547 LineJoin::Round => 1.0,
11548 LineJoin::Bevel => 2.0,
11549 },
11550 style.miter_limit,
11551 style.dash_phase,
11552 style.dash.len() as f64,
11553 0.0,
11554 0.0,
11555 Color::CLEAR,
11556 nums,
11557 );
11558 texts.push(
11559 style
11560 .dash
11561 .iter()
11562 .map(std::string::ToString::to_string)
11563 .collect::<Vec<_>>()
11564 .join(" "),
11565 );
11566 }
11567
11568 /// One shape record (the fill/stroke kinds shared by both ops).
11569 fn shape_record(
11570 stroke: bool,
11571 shape: &Shape,
11572 w: f64,
11573 col: Color,
11574 nums: &mut Vec<f64>,
11575 texts: &mut Vec<String>,
11576 geometry: &mut Option<&mut Vec<f64>>,
11577 ) {
11578 match shape {
11579 Shape::Rect(r) => push(
11580 if stroke {
11581 OpCode::StrokeRect
11582 } else {
11583 OpCode::FillRect
11584 },
11585 r.origin.x,
11586 r.origin.y,
11587 r.size.width,
11588 r.size.height,
11589 0.0,
11590 0.0,
11591 w,
11592 col,
11593 nums,
11594 ),
11595 Shape::RoundedRect(r, rad) => push(
11596 if stroke {
11597 OpCode::StrokeRrect
11598 } else {
11599 OpCode::FillRrect
11600 },
11601 r.origin.x,
11602 r.origin.y,
11603 r.size.width,
11604 r.size.height,
11605 *rad,
11606 0.0,
11607 w,
11608 col,
11609 nums,
11610 ),
11611 Shape::Ellipse(r) => push(
11612 if stroke {
11613 OpCode::StrokeEllipse
11614 } else {
11615 OpCode::FillEllipse
11616 },
11617 r.origin.x,
11618 r.origin.y,
11619 r.size.width,
11620 r.size.height,
11621 0.0,
11622 0.0,
11623 w,
11624 col,
11625 nums,
11626 ),
11627 Shape::Arc { rect, start, sweep } => push(
11628 OpCode::StrokeArc,
11629 rect.origin.x,
11630 rect.origin.y,
11631 rect.size.width,
11632 rect.size.height,
11633 start.degrees(),
11634 sweep.degrees(),
11635 w,
11636 col,
11637 nums,
11638 ),
11639 Shape::Line(p1, p2) => {
11640 push(OpCode::Line, p1.x, p1.y, p2.x, p2.y, 0.0, 0.0, w, col, nums);
11641 }
11642 Shape::Polygon(pts) => {
11643 // Variable-length points ride the texts side-channel ("x,y x,y …"),
11644 // consumed in record order exactly like text payloads, or the geometry
11645 // channel when there is one (slots b, c).
11646 let (offset, count) = geometry_payload(
11647 geometry,
11648 texts,
11649 || encode_points(pts),
11650 |g| point_numbers(pts, g),
11651 );
11652 push(
11653 if stroke {
11654 OpCode::StrokePolygon
11655 } else {
11656 OpCode::FillPolygon
11657 },
11658 geometry_key(shape),
11659 offset,
11660 count,
11661 0.0,
11662 0.0,
11663 0.0,
11664 w,
11665 col,
11666 nums,
11667 );
11668 }
11669 Shape::Path(path) => {
11670 // Same side-channels as Polygon, one token per segment (see `encode_path`).
11671 // The fill rule rides slot f; stroking ignores it.
11672 let (offset, count) = geometry_payload(
11673 geometry,
11674 texts,
11675 || encode_path(path),
11676 |g| path_numbers(path, g),
11677 );
11678 push(
11679 if stroke {
11680 OpCode::StrokePath
11681 } else {
11682 OpCode::FillPath
11683 },
11684 geometry_key(shape),
11685 offset,
11686 count,
11687 0.0,
11688 0.0,
11689 rule_bits(path.rule),
11690 w,
11691 col,
11692 nums,
11693 );
11694 }
11695 }
11696 }
11697 /// A gradient applies to the next shape record, fill or stroke. Geometry per type rides
11698 /// slots a..d and the type discriminant slot f: one record shape, so every decoder keeps a
11699 /// single gradient code path.
11700 fn gradient_record(
11701 geo: [f64; 4],
11702 kind: f64,
11703 stops: &[(f64, Ink)],
11704 nums: &mut Vec<f64>,
11705 texts: &mut Vec<String>,
11706 ) {
11707 push(
11708 OpCode::SetGradient,
11709 geo[0],
11710 geo[1],
11711 geo[2],
11712 geo[3],
11713 stops.len() as f64,
11714 kind,
11715 0.0,
11716 Color::CLEAR,
11717 nums,
11718 );
11719 texts.push(
11720 stops
11721 .iter()
11722 .map(|(o, c)| format!("{o},{:08x}", color_bits(c.resolved()) as u32))
11723 .collect::<Vec<_>>()
11724 .join(" "),
11725 );
11726 }
11727 /// The record a paint puts before its shape record, and the color that shape record
11728 /// carries. A gradient emits one kind-14 record; a solid color emits nothing.
11729 fn paint_record(paint: &Paint, nums: &mut Vec<f64>, texts: &mut Vec<String>) -> Color {
11730 let (geo, kind, stops) = match paint {
11731 Paint::Solid(c) => return c.resolved(),
11732 Paint::Linear(g) => ([g.start.x, g.start.y, g.end.x, g.end.y], 0.0, &g.stops),
11733 Paint::Radial(g) => ([g.center.x, g.center.y, g.radius, 0.0], 1.0, &g.stops),
11734 Paint::Conic(g) => (
11735 [g.center.x, g.center.y, g.start.degrees(), 0.0],
11736 2.0,
11737 &g.stops,
11738 ),
11739 };
11740 gradient_record(geo, kind, stops, nums, texts);
11741 // The gradient replaces the shape record's color, but it must be opaque, not clear:
11742 // Skia-based decoders (Android Paint, OH_Drawing) modulate a shader by the paint
11743 // alpha, so a clear slot would render the whole gradient invisible.
11744 Color::WHITE
11745 }
11746 let mut nums = Vec::with_capacity(ops.len() * 9);
11747 let mut texts = Vec::new();
11748 for op in ops {
11749 match op {
11750 DrawOp::Fill(shape, paint) => {
11751 // A gradient emits one kind-14 set-gradient record before its shape record;
11752 // the stops ride the texts channel as "offset,aarrggbb offset,aarrggbb …".
11753 // Geometry per type rides slots a..d, the type discriminant slot f: one
11754 // record shape, so every decoder keeps a single gradient code path.
11755 let col = paint_record(paint, &mut nums, &mut texts);
11756 shape_record(false, shape, 0.0, col, &mut nums, &mut texts, &mut geometry);
11757 }
11758 DrawOp::Stamp(st) => {
11759 // No copies means no drawing. Some native decoders use an empty point
11760 // buffer to mean an ordinary (unstamped) template, so omit the entire op.
11761 if st.at.is_empty() {
11762 continue;
11763 }
11764 // A prefix record, then the coordinates, then the template shape record: the
11765 // "applies to the next record" rule the gradient, stroke style and font records
11766 // already follow, so a decoder needs no new kind of state, only one more slot in
11767 // the state it keeps. The template goes last because a decoder has to hold the
11768 // points before it can draw with them.
11769 //
11770 // The points are numbers on the numeric channel, not the texts channel a
11771 // polygon's points ride: this op exists for tens of thousands of them, and
11772 // formatting that many floats into a string every frame would cost more than
11773 // the individual ops it replaces.
11774 let col = paint_record(&st.paint, &mut nums, &mut texts);
11775 push(
11776 OpCode::Stamp,
11777 st.at.len() as f64,
11778 0.0,
11779 0.0,
11780 0.0,
11781 0.0,
11782 0.0,
11783 0.0,
11784 Color::CLEAR,
11785 &mut nums,
11786 );
11787 for chunk in st.at.chunks(4) {
11788 // Written directly rather than through `push`: this is the one record whose
11789 // last slot is a coordinate rather than a color, which is what lets four
11790 // points fit with nothing wasted.
11791 let mut rec = [
11792 f64::from(OpCode::StampPoints as i32),
11793 0.0,
11794 0.0,
11795 0.0,
11796 0.0,
11797 0.0,
11798 0.0,
11799 0.0,
11800 0.0,
11801 ];
11802 for (i, p) in chunk.iter().enumerate() {
11803 rec[1 + i * 2] = p.x;
11804 rec[2 + i * 2] = p.y;
11805 }
11806 nums.extend_from_slice(&rec);
11807 }
11808 match &st.stroke {
11809 None => shape_record(
11810 false,
11811 &st.shape,
11812 0.0,
11813 col,
11814 &mut nums,
11815 &mut texts,
11816 &mut geometry,
11817 ),
11818 Some(style) => {
11819 stroke_style_record(style, &mut nums, &mut texts);
11820 shape_record(
11821 true,
11822 &st.shape,
11823 style.width,
11824 col,
11825 &mut nums,
11826 &mut texts,
11827 &mut geometry,
11828 );
11829 }
11830 }
11831 }
11832 DrawOp::Stroke(shape, paint, style) => {
11833 // A styled stroke emits one kind-18 record first, applying to the next stroke
11834 // only, the same "modifier record" shape the gradient uses, so decoders keep
11835 // one rule: consume, apply to the next shape record, reset.
11836 stroke_style_record(style, &mut nums, &mut texts);
11837 let col = paint_record(paint, &mut nums, &mut texts);
11838 shape_record(
11839 true,
11840 shape,
11841 style.width,
11842 col,
11843 &mut nums,
11844 &mut texts,
11845 &mut geometry,
11846 );
11847 }
11848 DrawOp::Clip(shape) => {
11849 // One record for every clip shape, with the shape kind in slot f and the
11850 // geometry in a..e; a path or polygon puts its points on the texts channel.
11851 // Encoding clips as a variant of `shape_record` instead would need a third
11852 // kind code per shape, which is five more numbers every decoder must learn.
11853 let (kind, geo, extra, payload): (f64, [f64; 4], f64, Option<String>) = match shape
11854 {
11855 Shape::Rect(r) => (
11856 0.0,
11857 [r.origin.x, r.origin.y, r.size.width, r.size.height],
11858 0.0,
11859 None,
11860 ),
11861 Shape::RoundedRect(r, rad) => (
11862 1.0,
11863 [r.origin.x, r.origin.y, r.size.width, r.size.height],
11864 *rad,
11865 None,
11866 ),
11867 Shape::Ellipse(r) => (
11868 2.0,
11869 [r.origin.x, r.origin.y, r.size.width, r.size.height],
11870 0.0,
11871 None,
11872 ),
11873 // Slot a carries the geometry key for these two sub-kinds only. The other
11874 // three put real geometry there, which is why the key rides the same slot
11875 // the payload-bearing kinds leave empty; b and c are the geometry
11876 // channel's offset and count when there is one.
11877 Shape::Path(p) => {
11878 let (offset, count) = geometry_payload(
11879 &mut geometry,
11880 &mut texts,
11881 || encode_path(p),
11882 |g| path_numbers(p, g),
11883 );
11884 (
11885 3.0,
11886 [geometry_key(shape), offset, count, 0.0],
11887 rule_bits(p.rule),
11888 None,
11889 )
11890 }
11891 Shape::Polygon(pts) => {
11892 let (offset, count) = geometry_payload(
11893 &mut geometry,
11894 &mut texts,
11895 || encode_points(pts),
11896 |g| point_numbers(pts, g),
11897 );
11898 (4.0, [geometry_key(shape), offset, count, 0.0], 0.0, None)
11899 }
11900 // A clip to a line or an arc has no interior to clip to. Clipping to an
11901 // empty region would blank everything after it, so clip to the shape's
11902 // bounds instead: wrong in the same direction as no clip at all.
11903 Shape::Line(..) | Shape::Arc { .. } => {
11904 let r = shape.bounds();
11905 (
11906 0.0,
11907 [r.origin.x, r.origin.y, r.size.width, r.size.height],
11908 0.0,
11909 None,
11910 )
11911 }
11912 };
11913 push(
11914 OpCode::Clip,
11915 geo[0],
11916 geo[1],
11917 geo[2],
11918 geo[3],
11919 extra,
11920 kind,
11921 0.0,
11922 Color::CLEAR,
11923 &mut nums,
11924 );
11925 if let Some(s) = payload {
11926 texts.push(s);
11927 }
11928 }
11929 DrawOp::Text {
11930 text,
11931 at,
11932 size,
11933 color,
11934 anchor,
11935 font,
11936 } => {
11937 if *font != CanvasFont::default() {
11938 push(
11939 OpCode::SetFont,
11940 f64::from(font.css_weight()),
11941 f64::from(u8::from(font.italic)),
11942 0.0,
11943 0.0,
11944 0.0,
11945 0.0,
11946 0.0,
11947 Color::CLEAR,
11948 &mut nums,
11949 );
11950 texts.push(
11951 font.family_str()
11952 .replace([FONT_LIST_FIELD, FONT_LIST_FAMILY], " "),
11953 );
11954 }
11955 push(
11956 OpCode::Text,
11957 at.x,
11958 at.y,
11959 0.0,
11960 0.0,
11961 *size,
11962 anchor.pack(),
11963 0.0,
11964 *color,
11965 &mut nums,
11966 );
11967 texts.push(text.clone());
11968 }
11969 DrawOp::Image {
11970 image,
11971 rect,
11972 opacity,
11973 source,
11974 } => {
11975 if let Some(src) = source {
11976 push(
11977 OpCode::ImageSource,
11978 src.origin.x,
11979 src.origin.y,
11980 src.size.width,
11981 src.size.height,
11982 0.0,
11983 0.0,
11984 0.0,
11985 Color::CLEAR,
11986 &mut nums,
11987 );
11988 }
11989 push(
11990 OpCode::Image,
11991 rect.origin.x,
11992 rect.origin.y,
11993 rect.size.width,
11994 rect.size.height,
11995 image.0 as f64,
11996 *opacity,
11997 0.0,
11998 Color::CLEAR,
11999 &mut nums,
12000 );
12001 }
12002 DrawOp::Shadow(shadow) => {
12003 // No shadow is a clear color: one record shape either way, and a decoder
12004 // needs no second "is there one" slot.
12005 let s = shadow.unwrap_or(Shadow::new(Color::CLEAR, 0.0));
12006 push(
12007 OpCode::SetShadow,
12008 s.dx,
12009 s.dy,
12010 s.blur.max(0.0),
12011 0.0,
12012 0.0,
12013 0.0,
12014 0.0,
12015 s.color.resolved(),
12016 &mut nums,
12017 );
12018 }
12019 DrawOp::Blend(mode) => push(
12020 OpCode::SetBlend,
12021 f64::from(mode.wire()),
12022 0.0,
12023 0.0,
12024 0.0,
12025 0.0,
12026 0.0,
12027 0.0,
12028 Color::CLEAR,
12029 &mut nums,
12030 ),
12031 DrawOp::Save => push(
12032 OpCode::Save,
12033 0.0,
12034 0.0,
12035 0.0,
12036 0.0,
12037 0.0,
12038 0.0,
12039 0.0,
12040 Color::CLEAR,
12041 &mut nums,
12042 ),
12043 DrawOp::Restore => push(
12044 OpCode::Restore,
12045 0.0,
12046 0.0,
12047 0.0,
12048 0.0,
12049 0.0,
12050 0.0,
12051 0.0,
12052 Color::CLEAR,
12053 &mut nums,
12054 ),
12055 DrawOp::Concat(m) => push(
12056 OpCode::Concat,
12057 m.a,
12058 m.b,
12059 m.c,
12060 m.d,
12061 m.tx,
12062 m.ty,
12063 0.0,
12064 Color::CLEAR,
12065 &mut nums,
12066 ),
12067 }
12068 }
12069 (nums, texts)
12070}
12071
12072#[cfg(test)]
12073mod font_list_tests {
12074 use super::*;
12075
12076 #[test]
12077 fn css_weights_round_trip_and_snap_to_the_nearest_rung() {
12078 for w in FontWeight::ALL {
12079 assert_eq!(FontWeight::from_css(w.css()), w);
12080 }
12081 assert_eq!(FontWeight::from_css(0), FontWeight::UltraLight);
12082 assert_eq!(FontWeight::from_css(350), FontWeight::Regular); // ties go heavier
12083 assert_eq!(FontWeight::from_css(649), FontWeight::Semibold);
12084 assert_eq!(FontWeight::from_css(1200), FontWeight::Black);
12085 }
12086
12087 fn sans() -> FontFamilyInfo {
12088 FontFamilyInfo {
12089 family: "Day Sans".into(),
12090 faces: vec![
12091 FontFace {
12092 name: "Regular".into(),
12093 weight: FontWeight::Regular,
12094 italic: false,
12095 },
12096 FontFace {
12097 name: "Bold".into(),
12098 weight: FontWeight::Bold,
12099 italic: false,
12100 },
12101 FontFace {
12102 name: "Light Italic".into(),
12103 weight: FontWeight::Light,
12104 italic: true,
12105 },
12106 ],
12107 }
12108 }
12109
12110 #[test]
12111 fn face_for_prefers_the_slant_then_the_nearest_weight() {
12112 let f = sans();
12113 assert!(f.has_bold() && f.has_italic());
12114 assert_eq!(f.face_for(FontWeight::Bold, false).unwrap().name, "Bold");
12115 assert_eq!(
12116 f.face_for(FontWeight::Semibold, false).unwrap().name,
12117 "Bold"
12118 );
12119 assert_eq!(
12120 f.face_for(FontWeight::Medium, false).unwrap().name,
12121 "Regular"
12122 );
12123 let tie = FontFamilyInfo {
12124 family: "Tie".into(),
12125 faces: vec![
12126 FontFace {
12127 name: "Light".into(),
12128 weight: FontWeight::Light,
12129 italic: false,
12130 },
12131 FontFace {
12132 name: "Bold".into(),
12133 weight: FontWeight::Bold,
12134 italic: false,
12135 },
12136 ],
12137 };
12138 // Medium sits 200 from both; the heavier face wins the tie.
12139 assert_eq!(
12140 tie.face_for(FontWeight::Medium, false).unwrap().name,
12141 "Bold"
12142 );
12143 assert_eq!(
12144 f.face_for(FontWeight::Black, true).unwrap().name,
12145 "Light Italic"
12146 );
12147 let none = FontFamilyInfo {
12148 family: "Empty".into(),
12149 faces: vec![],
12150 };
12151 assert!(none.face_for(FontWeight::Regular, false).is_none());
12152 assert!(!none.has_bold());
12153 }
12154
12155 #[test]
12156 fn the_shim_list_format_decodes_tolerantly() {
12157 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\
12158 \u{1e}\u{1e}Day Mono\u{1f}Regular\u{1f}400\u{1f}0\u{1e}Faceless";
12159 let list = parse_font_list(s);
12160 assert_eq!(list.len(), 3);
12161 assert_eq!(list[0].family, "Day Sans");
12162 assert_eq!(list[0].faces.len(), 2, "the bad weight is skipped");
12163 assert_eq!(list[0].faces[1].name, "Bold Italic"); // synthesized from 700 + italic
12164 assert_eq!(list[1].family, "Day Mono");
12165 assert_eq!(list[2].family, "Faceless");
12166 assert_eq!(list[2].faces, [] as [FontFace; 0]);
12167 }
12168
12169 #[test]
12170 fn approximate_metrics_scale_with_size_and_length() {
12171 let m = TextMetrics::approximate("abc", 10.0);
12172 assert_eq!((m.width, m.height, m.ascent), (18.0, 12.0, 9.0));
12173 assert_eq!(TextMetrics::approximate("", 10.0).width, 0.0);
12174 }
12175
12176 #[test]
12177 fn a_default_canvas_font_is_the_platform_face() {
12178 let f = CanvasFont::default();
12179 assert_eq!((f.family_str(), f.css_weight(), f.italic), ("", 0, false));
12180 }
12181}
12182
12183#[cfg(test)]
12184mod image_header_tests {
12185 use super::*;
12186
12187 /// A 4×2 PNG: signature, then an IHDR whose width and height are big-endian.
12188 fn png(w: u32, h: u32) -> Vec<u8> {
12189 let mut v = vec![0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a];
12190 v.extend(13u32.to_be_bytes());
12191 v.extend(b"IHDR");
12192 v.extend(w.to_be_bytes());
12193 v.extend(h.to_be_bytes());
12194 v
12195 }
12196
12197 /// A JPEG whose frame header sits behind one other segment, so the walk has to skip it.
12198 fn jpeg(w: u16, h: u16) -> Vec<u8> {
12199 let mut v = vec![0xFF, 0xD8]; // SOI
12200 v.extend([0xFF, 0xE0, 0x00, 0x04, 0x00, 0x00]); // APP0, length 4
12201 v.extend([0xFF, 0xC0, 0x00, 0x11, 0x08]); // SOF0, length 17, precision 8
12202 v.extend(h.to_be_bytes());
12203 v.extend(w.to_be_bytes());
12204 v
12205 }
12206
12207 #[test]
12208 fn a_header_states_the_size_before_anything_decodes() {
12209 assert_eq!(ImageFormat::dimensions(&png(512, 512)), Some((512, 512)));
12210 assert_eq!(ImageFormat::dimensions(&png(1, 65535)), Some((1, 65535)));
12211 // The JPEG walk must step over the APP0 segment to reach the frame header.
12212 assert_eq!(ImageFormat::dimensions(&jpeg(640, 480)), Some((640, 480)));
12213
12214 let mut gif = b"GIF89a".to_vec();
12215 gif.extend(320u16.to_le_bytes());
12216 gif.extend(240u16.to_le_bytes());
12217 assert_eq!(ImageFormat::dimensions(&gif), Some((320, 240)));
12218
12219 // A top-down BMP states its height as a negative number; the size is still positive.
12220 let mut bmp = b"BM".to_vec();
12221 bmp.resize(18, 0);
12222 bmp.extend(64i32.to_le_bytes());
12223 bmp.extend((-32i32).to_le_bytes());
12224 assert_eq!(ImageFormat::dimensions(&bmp), Some((64, 32)));
12225 }
12226
12227 #[test]
12228 fn a_truncated_or_unknown_header_answers_nothing_rather_than_a_guess() {
12229 assert_eq!(ImageFormat::dimensions(&[]), None);
12230 // The signature is there but the IHDR is not.
12231 assert_eq!(ImageFormat::dimensions(&png(8, 8)[..12]), None);
12232 // Not an image at all.
12233 assert_eq!(ImageFormat::dimensions(b"not an image"), None);
12234 // A JPEG that never reaches a frame header must not loop or invent a size.
12235 assert_eq!(
12236 ImageFormat::dimensions(&[0xFF, 0xD8, 0xFF, 0xE0, 0x00, 0x04, 0, 0]),
12237 None
12238 );
12239 }
12240}
12241
12242#[cfg(test)]
12243mod encode_ops_tests {
12244 use super::*;
12245
12246 /// The texts channel carries plain decimals: whole numbers without a point, fractions to
12247 /// six places with the trailing zeros gone, and the general form only past what the fixed
12248 /// one can hold.
12249 #[test]
12250 fn wire_numbers_are_short_plain_decimals() {
12251 let text = |v: f64| {
12252 let mut out = String::new();
12253 push_wire_num(&mut out, v);
12254 out
12255 };
12256 assert_eq!(text(12.0), "12");
12257 assert_eq!(text(-0.5), "-0.5");
12258 assert_eq!(text(183.472_938_472_938_4), "183.472938");
12259 assert_eq!(text(0.1 + 0.2), "0.3");
12260 assert_eq!(text(-0.000_000_1), "0");
12261 assert_eq!(text(2.000_05), "2.00005");
12262 assert_eq!(text(f64::INFINITY), "inf");
12263 assert_eq!(text(1.0e17), "100000000000000000");
12264 let path = Path {
12265 segs: vec![
12266 PathSeg::Move(Point::new(1.5, 2.0)),
12267 PathSeg::Line(Point::new(-3.25, 4.0)),
12268 PathSeg::Close,
12269 ],
12270 rule: FillRule::NonZero,
12271 };
12272 assert_eq!(encode_path(&path), "M 1.5 2 L -3.25 4 Z");
12273 assert_eq!(
12274 encode_points(&[Point::new(0.0, 0.0), Point::new(10.0, 0.125)]),
12275 "0,0 10,0.125"
12276 );
12277 }
12278
12279 /// With the geometry channel open, a path's and a polygon's points leave the texts channel
12280 /// (an empty entry keeps it positional) for the numbers, with offset and count in slots b
12281 /// and c; without it the texts channel carries them exactly as before.
12282 #[test]
12283 fn geometry_channel_carries_points_as_numbers() {
12284 let path = Shape::Path(Path {
12285 segs: vec![
12286 PathSeg::Move(Point::new(1.0, 2.0)),
12287 PathSeg::Quad(Point::new(3.0, 4.0), Point::new(5.0, 6.0)),
12288 PathSeg::Close,
12289 ],
12290 rule: FillRule::EvenOdd,
12291 });
12292 let polygon = Shape::Polygon(vec![Point::new(0.0, 0.0), Point::new(7.0, 8.0)]);
12293 let ops = vec![
12294 DrawOp::Clip(path.clone()),
12295 DrawOp::Fill(path.clone(), Paint::Solid(Color::WHITE.into())),
12296 DrawOp::Stroke(
12297 polygon.clone(),
12298 Paint::Solid(Color::WHITE.into()),
12299 StrokeStyle::default(),
12300 ),
12301 ];
12302 let (nums, texts, geometry) = encode_ops_with_geometry(&ops);
12303 assert_eq!(texts, vec!["", "", ""]);
12304 assert_eq!(
12305 geometry,
12306 vec![
12307 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,
12308 6.0, 4.0, 0.0, 0.0, 7.0, 8.0
12309 ]
12310 );
12311 // The clip (kind 17, sub-kind 3 in f) and the fill (kind 15) point at the two copies
12312 // of the path, the stroke (kind 12) at the polygon's four numbers.
12313 assert_eq!((nums[0], nums[2], nums[3], nums[6]), (17.0, 0.0, 9.0, 3.0));
12314 assert_eq!(
12315 (nums[9], nums[11], nums[12], nums[15]),
12316 (15.0, 9.0, 9.0, 1.0)
12317 );
12318 assert_eq!((nums[18], nums[20], nums[21]), (12.0, 18.0, 4.0));
12319 let (plain_nums, plain_texts) = encode_ops(&ops);
12320 assert_eq!(plain_texts[1], "M 1 2 Q 3 4 5 6 Z");
12321 assert_eq!(plain_texts[2], "0,0 7,8");
12322 assert_eq!((plain_nums[11], plain_nums[12]), (0.0, 0.0));
12323 }
12324
12325 /// A region outside the bitmap is clamped to it with its mapping into the rect kept, and an
12326 /// empty intersection draws nothing.
12327 #[test]
12328 fn image_source_clamps_to_the_bitmap() {
12329 let px = Size::new(64.0, 32.0);
12330 let dest = Rect::new(100.0, 200.0, 32.0, 32.0); // 2 points per source pixel
12331 assert_eq!(
12332 clamp_image_source(Rect::new(-8.0, -8.0, 16.0, 16.0), dest, px),
12333 Some((
12334 Rect::new(0.0, 0.0, 8.0, 8.0),
12335 Rect::new(116.0, 216.0, 16.0, 16.0)
12336 ))
12337 );
12338 assert_eq!(
12339 clamp_image_source(Rect::new(60.0, 28.0, 16.0, 16.0), dest, px),
12340 Some((
12341 Rect::new(60.0, 28.0, 4.0, 4.0),
12342 Rect::new(100.0, 200.0, 8.0, 8.0)
12343 ))
12344 );
12345 assert_eq!(
12346 clamp_image_source(Rect::new(16.0, 8.0, 16.0, 16.0), dest, px),
12347 Some((Rect::new(16.0, 8.0, 16.0, 16.0), dest))
12348 );
12349 assert_eq!(
12350 clamp_image_source(Rect::new(64.0, 0.0, 8.0, 8.0), dest, px),
12351 None
12352 );
12353 assert_eq!(
12354 clamp_image_source(Rect::new(0.0, 0.0, 0.0, 8.0), dest, px),
12355 None
12356 );
12357 assert_eq!(
12358 clamp_image_source(Rect::new(0.0, 0.0, 8.0, 8.0), dest, Size::new(0.0, 0.0)),
12359 None
12360 );
12361 }
12362
12363 /// The wire codes are a frozen dense table: any gap, duplicate, or variant missing from
12364 /// `ALL` breaks a decoder somewhere, so it must break here first.
12365 #[test]
12366 fn op_codes_are_dense_and_round_trip() {
12367 for (i, code) in OpCode::ALL.into_iter().enumerate() {
12368 assert_eq!(code as i32, i as i32, "{code:?} broke wire density");
12369 assert_eq!(OpCode::from_wire(i as f64), Some(code));
12370 }
12371 assert_eq!(OpCode::from_wire(OpCode::ALL.len() as f64), None);
12372 assert_eq!(OpCode::from_wire(-1.0), None);
12373 assert_eq!(OpCode::from_wire(0.5), None);
12374 }
12375
12376 /// Reference decode of a display list covering every op arm: the record stream must be
12377 /// whole 9-slot records of known codes, and the texts channel must carry exactly one
12378 /// entry per text-carrying record, in order: the contract every shim decoder assumes.
12379 #[test]
12380 #[expect(
12381 clippy::float_cmp,
12382 reason = "wire slots hold integer codes and exact test constants"
12383 )]
12384 fn encode_ops_emits_whole_records_and_matched_text_payloads() {
12385 let r = Rect::new(1.0, 2.0, 3.0, 4.0);
12386 let red = Color::rgb(1.0, 0.0, 0.0);
12387 let ops = vec![
12388 DrawOp::Fill(Shape::Rect(r), Paint::Solid(red.into())),
12389 DrawOp::Stroke(
12390 Shape::Rect(r),
12391 Paint::Solid(red.into()),
12392 StrokeStyle::round(2.0),
12393 ),
12394 DrawOp::Fill(Shape::RoundedRect(r, 5.0), Paint::Solid(red.into())),
12395 DrawOp::Fill(Shape::Ellipse(r), Paint::Solid(red.into())),
12396 // The documented asymmetry: a filled arc encodes as StrokeArc with width 0.
12397 DrawOp::Fill(
12398 Shape::Arc {
12399 rect: r,
12400 start: Angle::ZERO,
12401 sweep: Angle::QUARTER,
12402 },
12403 Paint::Solid(red.into()),
12404 ),
12405 DrawOp::Stroke(
12406 Shape::Line(Point::new(0.0, 0.0), Point::new(9.0, 9.0)),
12407 Paint::Solid(red.into()),
12408 StrokeStyle::width(1.0),
12409 ),
12410 DrawOp::Fill(
12411 Shape::Polygon(vec![
12412 Point::new(0.0, 0.0),
12413 Point::new(4.0, 0.0),
12414 Point::new(2.0, 3.0),
12415 ]),
12416 Paint::Solid(red.into()),
12417 ),
12418 DrawOp::Fill(
12419 Shape::Path(Path {
12420 segs: vec![
12421 PathSeg::Move(Point::new(0.0, 0.0)),
12422 PathSeg::Line(Point::new(5.0, 5.0)),
12423 PathSeg::Close,
12424 ],
12425 rule: FillRule::EvenOdd,
12426 }),
12427 Paint::Linear(LinearGradient::new(
12428 UnitPoint::new(0.0, 0.0),
12429 UnitPoint::new(1.0, 1.0),
12430 vec![(0.0, red), (1.0, Color::WHITE)],
12431 )),
12432 ),
12433 DrawOp::Clip(Shape::Rect(r)),
12434 DrawOp::Clip(Shape::Polygon(vec![
12435 Point::new(0.0, 0.0),
12436 Point::new(1.0, 0.0),
12437 Point::new(0.0, 1.0),
12438 ])),
12439 DrawOp::Text {
12440 text: "hi".into(),
12441 at: Point::new(7.0, 8.0),
12442 size: 12.0,
12443 color: red,
12444 anchor: TextAnchor::LEADING,
12445 font: CanvasFont::default(),
12446 },
12447 DrawOp::Text {
12448 text: "bold".into(),
12449 at: Point::new(7.0, 8.0),
12450 size: 12.0,
12451 color: red,
12452 anchor: TextAnchor::CENTERED,
12453 font: CanvasFont {
12454 family: Some("Day Sans".into()),
12455 weight: Some(FontWeight::Bold),
12456 italic: true,
12457 },
12458 },
12459 DrawOp::Save,
12460 DrawOp::Concat(Affine::IDENTITY),
12461 DrawOp::Restore,
12462 DrawOp::Image {
12463 image: BitmapId(7),
12464 rect: r,
12465 opacity: 0.5,
12466 source: None,
12467 },
12468 DrawOp::Image {
12469 image: BitmapId(7),
12470 rect: r,
12471 opacity: 1.0,
12472 source: Some(Rect::new(16.0, 32.0, 8.0, 8.0)),
12473 },
12474 ];
12475 let (nums, texts) = encode_ops(&ops);
12476 assert_eq!(nums.len() % 9, 0, "partial record on the wire");
12477
12478 let mut expected_texts = 0usize;
12479 let mut decoded = Vec::new();
12480 for rec in nums.chunks(9) {
12481 let code = OpCode::from_wire(rec[0])
12482 .unwrap_or_else(|| panic!("unknown op code {} on the wire", rec[0]));
12483 decoded.push(code);
12484 expected_texts += match code {
12485 OpCode::Text
12486 | OpCode::FillPolygon
12487 | OpCode::StrokePolygon
12488 | OpCode::SetGradient
12489 | OpCode::FillPath
12490 | OpCode::StrokePath
12491 | OpCode::StrokeStyle
12492 | OpCode::SetFont => 1,
12493 // Clip carries a payload only for its path (3) / polygon (4) sub-kinds.
12494 OpCode::Clip => usize::from(rec[6] == 3.0 || rec[6] == 4.0),
12495 _ => 0,
12496 };
12497 }
12498 assert_eq!(
12499 texts.len(),
12500 expected_texts,
12501 "texts channel out of step with the records that consume it"
12502 );
12503 // No payload may carry the transport separator.
12504 assert!(texts.iter().all(|t| !t.contains('\u{1f}')));
12505
12506 let expected = {
12507 use OpCode::*;
12508 vec![
12509 FillRect,
12510 StrokeStyle, // ::round(2.0) is not plain, so the style modifier precedes
12511 StrokeRect,
12512 FillRrect,
12513 FillEllipse,
12514 StrokeArc, // the filled arc's stroke encoding…
12515 Line,
12516 FillPolygon,
12517 SetGradient, // gradient precedes its shape record
12518 FillPath,
12519 Clip,
12520 Clip,
12521 Text,
12522 SetFont, // a non-default font precedes its text record…
12523 Text,
12524 Save,
12525 Concat,
12526 Restore,
12527 Image,
12528 ImageSource, // a region precedes its image record; a whole-image draw has none
12529 Image,
12530 ]
12531 };
12532 assert_eq!(decoded, expected);
12533 // The bitmap id rides the numeric channel intact (an f64 holds a u64 id exactly well
12534 // past any id this process will mint), and nothing of an image reaches the texts channel.
12535 let img = nums
12536 .chunks(9)
12537 .find(|r| r[0] == f64::from(OpCode::Image as i32))
12538 .expect("Image record");
12539 assert_eq!(&img[1..7], &[1.0, 2.0, 3.0, 4.0, 7.0, 0.5]);
12540 // The region rides its own prefix record, in bitmap pixels, with nothing else in it.
12541 let src = nums
12542 .chunks(9)
12543 .find(|r| r[0] == f64::from(OpCode::ImageSource as i32))
12544 .expect("ImageSource record");
12545 assert_eq!(&src[1..8], &[16.0, 32.0, 8.0, 8.0, 0.0, 0.0, 0.0]);
12546 // …carrying the CSS weight and the slant, with the family on the texts channel.
12547 let font_rec = nums
12548 .chunks(9)
12549 .find(|r| r[0] == f64::from(OpCode::SetFont as i32))
12550 .expect("SetFont record");
12551 assert_eq!(&font_rec[1..3], &[700.0, 1.0]);
12552 assert_eq!(texts.iter().filter(|t| *t == "Day Sans").count(), 1);
12553 // …with width 0, per the documented asymmetry.
12554 let arc = nums
12555 .chunks(9)
12556 .find(|r| r[0] == f64::from(OpCode::StrokeArc as i32));
12557 assert_eq!(arc.map(|r| r[7]), Some(0.0));
12558 // A gradient-filled shape's color slot is opaque white, never clear (Skia decoders
12559 // modulate the shader by it).
12560 let path_rec = nums
12561 .chunks(9)
12562 .find(|r| r[0] == f64::from(OpCode::FillPath as i32));
12563 assert_eq!(
12564 path_rec.map(|r| r[8] as u32),
12565 Some(0xFFFF_FFFF),
12566 "gradient shape record must carry opaque white"
12567 );
12568 }
12569
12570 #[test]
12571 #[expect(
12572 clippy::float_cmp,
12573 reason = "wire slots hold integer codes and exact test constants"
12574 )]
12575 fn variable_length_geometry_carries_a_content_key() {
12576 let path = |x: f64| {
12577 Shape::Path(Path {
12578 segs: vec![
12579 PathSeg::Move(Point::new(x, 0.0)),
12580 PathSeg::Cubic(
12581 Point::new(1.0, 1.0),
12582 Point::new(2.0, 2.0),
12583 Point::new(3.0, 3.0),
12584 ),
12585 PathSeg::Close,
12586 ],
12587 rule: FillRule::NonZero,
12588 })
12589 };
12590 let poly = Shape::Polygon(vec![
12591 Point::new(0.0, 0.0),
12592 Point::new(1.0, 0.0),
12593 Point::new(0.0, 1.0),
12594 ]);
12595
12596 // Equal geometry keys equal though the two were built separately. The key exists for
12597 // this: a draw closure rebuilds its paths from scratch on every frame.
12598 assert_eq!(geometry_key(&path(0.0)), geometry_key(&path(0.0)));
12599 assert_ne!(geometry_key(&path(0.0)), geometry_key(&path(1.0)));
12600 // The fill rule decides what the path draws, so it belongs to the key.
12601 let even_odd = Shape::Path(Path {
12602 segs: match path(0.0) {
12603 Shape::Path(p) => p.segs,
12604 _ => unreachable!(),
12605 },
12606 rule: FillRule::EvenOdd,
12607 });
12608 assert_ne!(geometry_key(&path(0.0)), geometry_key(&even_odd));
12609 // A polygon and a path decode to different geometry and never share an entry.
12610 assert_ne!(geometry_key(&poly), geometry_key(&path(0.0)));
12611 // Fixed-size shapes keep 0: their geometry rides the record's own slots.
12612 assert_eq!(
12613 geometry_key(&Shape::Rect(Rect::new(0.0, 0.0, 1.0, 1.0))),
12614 0.0
12615 );
12616 // And a key survives an f64 wire slot exactly, which is what the 53-bit mask buys.
12617 let k = geometry_key(&path(0.0));
12618 assert!(
12619 k > 0.0 && k < (1u64 << 53) as f64 && k.fract() == 0.0,
12620 "{k}"
12621 );
12622
12623 // It reaches the wire in slot a, for exactly the ops whose payload rides the texts
12624 // channel, and never displaces geometry that is already there.
12625 let (nums, _) = encode_ops(&[
12626 DrawOp::Fill(path(0.0), Paint::Solid(Color::WHITE.into())),
12627 DrawOp::Fill(poly.clone(), Paint::Solid(Color::WHITE.into())),
12628 DrawOp::Clip(path(0.0)),
12629 DrawOp::Clip(Shape::Rect(Rect::new(1.0, 2.0, 3.0, 4.0))),
12630 ]);
12631 let slot_a = |code: OpCode| {
12632 nums.chunks(9)
12633 .find(|r| r[0] == f64::from(code as i32))
12634 .unwrap_or_else(|| panic!("no {code:?} record"))[1]
12635 };
12636 assert_eq!(slot_a(OpCode::FillPath), geometry_key(&path(0.0)));
12637 assert_eq!(slot_a(OpCode::FillPolygon), geometry_key(&poly));
12638 let clips: Vec<&[f64]> = nums
12639 .chunks(9)
12640 .filter(|r| r[0] == f64::from(OpCode::Clip as i32))
12641 .collect();
12642 assert_eq!(clips[0][1], geometry_key(&path(0.0)), "path clip keys");
12643 assert_eq!(
12644 &clips[1][1..5],
12645 &[1.0, 2.0, 3.0, 4.0],
12646 "a rect clip still puts its geometry in a..d"
12647 );
12648 }
12649}
12650
12651#[cfg(test)]
12652mod markup_tests {
12653 use super::*;
12654
12655 fn bold(range: std::ops::Range<usize>) -> TextRun {
12656 TextRun::font(
12657 range,
12658 FontSpec {
12659 style: Font::Body,
12660 weight: Some(FontWeight::Bold),
12661 ..Default::default()
12662 },
12663 )
12664 }
12665
12666 #[test]
12667 fn plain_text_is_escaped_in_both_dialects() {
12668 // The case a translated string will find: markup metacharacters in the content.
12669 let text = "5 < 6 & \"quoted\" <b>not bold</b>";
12670 for d in [MarkupDialect::Pango, MarkupDialect::QtHtml] {
12671 let m = runs_to_markup(text, &[], d, 16.0);
12672 assert!(!m.contains("<b>"), "content tag survived into markup: {m}");
12673 assert!(m.contains("<b>"), "{m}");
12674 assert!(m.contains("&"), "{m}");
12675 assert!(m.contains("5 < 6"), "{m}");
12676 }
12677 }
12678
12679 #[test]
12680 fn a_styled_run_is_wrapped_and_its_text_escaped() {
12681 let text = "a <b> c";
12682 let m = runs_to_markup(text, &[bold(2..5)], MarkupDialect::Pango, 16.0);
12683 assert_eq!(m, "a <b><b></b> c");
12684 }
12685
12686 #[test]
12687 fn color_and_monospace_differ_per_dialect() {
12688 let text = "code";
12689 let run = TextRun {
12690 range: 0..4,
12691 font: FontSpec {
12692 style: Font::Body,
12693 monospace: true,
12694 ..Default::default()
12695 },
12696 color: Some(Color::rgb(1.0, 0.0, 0.0).into()),
12697 ..TextRun::default()
12698 };
12699 let pango = runs_to_markup(text, std::slice::from_ref(&run), MarkupDialect::Pango, 16.0);
12700 assert!(pango.contains("foreground=\"#ff0000\""), "{pango}");
12701 assert!(pango.contains("font_family=\"monospace\""), "{pango}");
12702 let qt = runs_to_markup(
12703 text,
12704 std::slice::from_ref(&run),
12705 MarkupDialect::QtHtml,
12706 16.0,
12707 );
12708 assert!(qt.contains("color:#ff0000"), "{qt}");
12709 // Qt takes its fixed face from <code>: a `font-family:monospace` style attribute
12710 // renders proportional (observed on Qt 6.11).
12711 assert!(qt.contains("<code>") && qt.contains("</code>"), "{qt}");
12712 }
12713
12714 #[test]
12715 fn the_new_attributes_reach_both_dialects() {
12716 let run = TextRun {
12717 range: 0..2,
12718 font: FontSpec::default().scaled(1.5),
12719 background: Some(Color::rgb(0.0, 1.0, 0.0).into()),
12720 underline: Some(Decoration::SINGLE),
12721 ..TextRun::default()
12722 };
12723 let pango = runs_to_markup("hi", std::slice::from_ref(&run), MarkupDialect::Pango, 16.0);
12724 assert!(pango.contains("background=\"#00ff00\""), "{pango}");
12725 // Pango takes an absolute size in 1/1024 pt (16 pt base × 1.5 = 24 pt), because the
12726 // relative attributes are Pango 1.50's and an unknown attribute empties the whole label.
12727 assert!(pango.contains("size=\"24576\""), "{pango}");
12728 assert!(pango.contains("<u>hi</u>"), "{pango}");
12729 let qt = runs_to_markup(
12730 "hi",
12731 std::slice::from_ref(&run),
12732 MarkupDialect::QtHtml,
12733 16.0,
12734 );
12735 assert!(qt.contains("background-color:#00ff00"), "{qt}");
12736 // Qt takes points: 16 pt base × 1.5 (observed; its CSS subset ignores a percentage).
12737 assert!(qt.contains("font-size:24pt"), "{qt}");
12738 assert!(qt.contains("<u>hi</u>"), "{qt}");
12739 }
12740
12741 #[test]
12742 fn a_link_target_is_escaped_too() {
12743 // A URL carrying `&` between query parameters is ordinary, and unescaped it truncates
12744 // the attribute and swallows the rest of the label.
12745 let text = "docs";
12746 let run = TextRun {
12747 range: 0..4,
12748 link: Some("https://x.dev/?a=1&b=2".into()),
12749 ..TextRun::default()
12750 };
12751 let m = runs_to_markup(text, &[run], MarkupDialect::Pango, 16.0);
12752 assert!(m.contains("a=1&b=2"), "{m}");
12753 }
12754
12755 #[test]
12756 fn tags_nest_and_close_in_reverse() {
12757 let run = TextRun {
12758 range: 0..2,
12759 font: FontSpec {
12760 style: Font::Body,
12761 weight: Some(FontWeight::Bold),
12762 italic: true,
12763 ..Default::default()
12764 },
12765 strikethrough: Some(Decoration::SINGLE),
12766 link: Some("u".into()),
12767 ..TextRun::default()
12768 };
12769 let m = runs_to_markup("hi", &[run], MarkupDialect::Pango, 16.0);
12770 assert_eq!(m, "<a href=\"u\"><b><i><s>hi</s></i></b></a>");
12771 }
12772
12773 #[test]
12774 fn runs_out_of_bounds_are_skipped_not_panicked() {
12775 // `runs_are_valid` rejects these upstream; this is the belt-and-braces path.
12776 let m = runs_to_markup("hi", &[bold(0..99)], MarkupDialect::Pango, 16.0);
12777 assert_eq!(m, "hi");
12778 }
12779
12780 #[test]
12781 fn validation_catches_the_four_ways_runs_go_wrong() {
12782 let text = "héllo";
12783 assert!(runs_are_valid(text, &[bold(0..1)]).is_ok());
12784 // Overlapping.
12785 assert!(runs_are_valid(text, &[bold(0..3), bold(2..4)]).is_err());
12786 // Past the end.
12787 assert!(runs_are_valid(text, &[bold(0..99)]).is_err());
12788 // Inverted. Built from parts, since a literal `3..1` is a clippy error in its own right.
12789 let (hi, lo) = (3, 1);
12790 assert!(runs_are_valid(text, &[bold(hi..lo)]).is_err());
12791 // Splitting the 2-byte `é`.
12792 assert!(runs_are_valid(text, &[bold(0..2)]).is_err());
12793 }
12794}
12795
12796#[cfg(test)]
12797mod route_of_url_tests {
12798 use super::route_of_url;
12799
12800 #[test]
12801 fn strips_the_scheme_and_keeps_route_and_params() {
12802 assert_eq!(
12803 route_of_url("notes://mail/inbox?hint=x"),
12804 "mail/inbox?hint=x"
12805 );
12806 assert_eq!(route_of_url("notes://home"), "home");
12807 // No scheme: already a route, unchanged.
12808 assert_eq!(route_of_url("mail/inbox"), "mail/inbox");
12809 assert_eq!(route_of_url(""), "");
12810 // Percent-encoding passes through; the route parser decodes, not this mapping.
12811 assert_eq!(route_of_url("n://a/b%2Fc?q=1%202"), "a/b%2Fc?q=1%202");
12812 }
12813}
12814
12815#[cfg(test)]
12816mod builtin_kind_tests {
12817 use super::*;
12818
12819 /// Every built-in round-trips through its wire key, and the keys are unique. Guards the
12820 /// `builtin_kinds!` expansion: a copy-paste slip in the table would alias two kinds.
12821 #[test]
12822 fn keys_round_trip_and_are_unique() {
12823 let mut seen = std::collections::HashSet::new();
12824 for &b in Builtin::ALL {
12825 assert_eq!(Builtin::from_key(b.key()), Some(b), "{b:?} key round-trip");
12826 assert!(seen.insert(b.key()), "duplicate key {:?}", b.key());
12827 assert!(
12828 b.key().starts_with("day."),
12829 "built-in {b:?} must use the reserved `day.` prefix"
12830 );
12831 }
12832 }
12833
12834 /// The `kinds::*` constants are the enum's keys, so the two spellings cannot drift.
12835 #[test]
12836 fn kinds_constants_match_the_enum() {
12837 assert_eq!(kinds::LABEL, Builtin::Label.key());
12838 assert_eq!(kinds::LIST_CELL, Builtin::ListCell.key());
12839 assert_eq!(kinds::COVER, Builtin::Cover.key());
12840 assert_eq!(kinds::INSPECTOR, Builtin::Inspector.key());
12841 assert_eq!(kinds::TREE, Builtin::Tree.key());
12842 // 19 after `Tabs`/`TabsPage` retired (the tab bar is a NAV presentation, not a kind),
12843 // +2 for the inspector split and its panes (docs/inspector.md), +1 for the tree
12844 // (docs/tree.md).
12845 assert_eq!(Builtin::ALL.len(), 25);
12846 }
12847
12848 /// An extension piece's kind is not a built-in.
12849 #[test]
12850 fn extension_kinds_are_not_builtin() {
12851 assert_eq!(Builtin::from_key("acme.combobox"), None);
12852 assert_eq!(Builtin::from_key("day.not_a_real_kind"), None);
12853 }
12854}
12855
12856#[cfg(test)]
12857mod locale_tests {
12858 /// POSIX locale strings are not BCP-47 tags, and "C" is not a language; that difference is
12859 /// the job of `posix_locale_hints` (§12.2).
12860 #[test]
12861 fn posix_hints_parse_and_drop_the_c_locale() {
12862 // The parsing is exercised through the same normalization the function applies.
12863 let normalize = |v: &str| v.split('.').next().unwrap_or(v).replace('_', "-");
12864 assert_eq!(normalize("fr_FR.UTF-8"), "fr-FR");
12865 assert_eq!(normalize("en_US"), "en-US");
12866 assert_eq!(normalize("C"), "C");
12867 // A real read never panics whatever this host's environment holds.
12868 let hints = super::posix_locale_hints();
12869 assert!(
12870 hints
12871 .iter()
12872 .all(|h| !h.is_empty() && h != "C" && h != "POSIX")
12873 );
12874 }
12875}
12876
12877#[cfg(test)]
12878mod sidetable_tests {
12879 use super::sidetable::{SideTable, sweep};
12880 use std::cell::Cell;
12881 use std::rc::Rc;
12882
12883 /// The registry exists so that one `sweep(key)` clears every table without any
12884 /// table needing its own line in a backend's `release()`.
12885 #[test]
12886 fn sweep_clears_every_registered_table_and_runs_teardowns() {
12887 let torn = Rc::new(Cell::new(0u32));
12888 let t2 = torn.clone();
12889 let plain: SideTable<&'static str> = SideTable::new();
12890 let hooked: SideTable<u32> = SideTable::with_teardown(move |_| t2.set(t2.get() + 1));
12891
12892 plain.insert(7, "a");
12893 hooked.insert(7, 1);
12894 hooked.insert(8, 2);
12895 sweep(7);
12896 assert!(!plain.contains(7));
12897 assert!(!hooked.contains(7), "swept from every table");
12898 assert!(hooked.contains(8), "other keys untouched");
12899 assert_eq!(torn.get(), 1, "teardown ran for the swept value");
12900
12901 // remove() runs the teardown too; take() bypasses it for ownership transfer.
12902 let _ = hooked.remove(8);
12903 assert_eq!(torn.get(), 2);
12904 hooked.insert(9, 3);
12905 assert_eq!(hooked.take(9), Some(3));
12906 assert_eq!(torn.get(), 2, "take() skips the hook");
12907 }
12908
12909 #[test]
12910 fn contain_returns_default_on_panic() {
12911 let ok = super::ffi_guard::contain(0i32, || 5);
12912 assert_eq!(ok, 5);
12913 let prev = std::panic::take_hook();
12914 std::panic::set_hook(Box::new(|_| {}));
12915 let contained = super::ffi_guard::contain(-1i32, || panic!("boom"));
12916 std::panic::set_hook(prev);
12917 assert_eq!(contained, -1, "the panic must not escape the guard");
12918 }
12919}
12920
12921#[cfg(test)]
12922mod cursor_tests {
12923 use super::Cursor;
12924
12925 /// Every named cursor has a distinct CSS keyword, and `NAMED` lists each exactly once: the
12926 /// gallery and every backend's table key on the keyword.
12927 #[test]
12928 fn named_cursors_have_distinct_css_names() {
12929 let mut seen = std::collections::BTreeSet::new();
12930 for c in &Cursor::NAMED {
12931 assert!(
12932 seen.insert(c.css_name().to_string()),
12933 "duplicate: {}",
12934 c.css_name()
12935 );
12936 assert!(!matches!(c, Cursor::Native(_)));
12937 }
12938 assert_eq!(seen.len(), Cursor::NAMED.len());
12939 assert_eq!(Cursor::native("dragCopy").css_name(), "dragCopy");
12940 assert_eq!(Cursor::default(), Cursor::Default);
12941 }
12942}
12943
12944#[cfg(test)]
12945mod text_anchor_tests {
12946 /// The anchor arithmetic every backend repeats. A drawing whose text lands in the wrong
12947 /// corner is a per-backend bug that only a screenshot catches, so the shared definition is
12948 /// pinned here and each shim is written to match it.
12949 #[test]
12950 fn text_anchor_offsets_place_the_line_box() {
12951 use crate::props::TextAlign;
12952 use crate::{TextAnchor, TextVAlign};
12953 // A 40-wide, 20-tall line box whose baseline sits 16 below its top.
12954 let (w, h, asc) = (40.0, 20.0, 16.0);
12955 let at = |ha, va| TextAnchor { h: ha, v: va }.offset(w, h, asc);
12956
12957 // The default is the drawing origin itself, every backend's native "draw here".
12958 assert_eq!(at(TextAlign::Leading, TextVAlign::Top), (0.0, 0.0));
12959 assert_eq!(TextAnchor::default(), TextAnchor::LEADING);
12960 // Horizontal: the box's leading edge, its middle, its trailing edge.
12961 assert_eq!(at(TextAlign::Center, TextVAlign::Top).0, -20.0);
12962 assert_eq!(at(TextAlign::Trailing, TextVAlign::Top).0, -40.0);
12963 // Vertical: top, middle, the baseline itself, bottom.
12964 assert_eq!(at(TextAlign::Leading, TextVAlign::Middle).1, -10.0);
12965 assert_eq!(at(TextAlign::Leading, TextVAlign::Baseline).1, -16.0);
12966 assert_eq!(at(TextAlign::Leading, TextVAlign::Bottom).1, -20.0);
12967 // The two named placements are the ones the two-variant enum used to have.
12968 assert_eq!(TextAnchor::CENTERED.offset(w, h, asc), (-20.0, -10.0));
12969 assert_eq!(TextAnchor::TRAILING.offset(w, h, asc), (-40.0, 0.0));
12970 }
12971
12972 /// The wire code the serializing backends (qt, xaml, arkui, android, web) decode by hand.
12973 #[test]
12974 fn text_anchor_packs_into_one_slot_and_round_trips() {
12975 use crate::props::TextAlign;
12976 use crate::{TextAnchor, TextVAlign};
12977 let mut seen = std::collections::BTreeSet::new();
12978 for h in [TextAlign::Leading, TextAlign::Center, TextAlign::Trailing] {
12979 for v in [
12980 TextVAlign::Top,
12981 TextVAlign::Middle,
12982 TextVAlign::Baseline,
12983 TextVAlign::Bottom,
12984 ] {
12985 let a = TextAnchor { h, v };
12986 let code = a.pack();
12987 assert!(
12988 (0.0..=11.0).contains(&code),
12989 "{code} outside the packed range"
12990 );
12991 assert!(seen.insert(code as u64), "two anchors share code {code}");
12992 assert_eq!(TextAnchor::unpack(code), a);
12993 }
12994 }
12995 assert_eq!(seen.len(), 12);
12996 // The shims decode as `h = code / 4`, `v = code % 4` in integer arithmetic.
12997 assert_eq!(TextAnchor::LEADING.pack(), 0.0);
12998 assert_eq!(TextAnchor::CENTERED.pack(), 5.0);
12999 // Junk answers the default rather than failing inside a native draw callback.
13000 assert_eq!(TextAnchor::unpack(-3.0), TextAnchor::LEADING);
13001 assert_eq!(TextAnchor::unpack(99.0), TextAnchor::unpack(11.0));
13002 }
13003
13004 /// The two shapes a backend's own metrics arrive in. Both land on the same contract: the line
13005 /// box's top-leading corner is the origin, and `ink` is relative to it.
13006 #[test]
13007 fn metrics_convert_from_a_backends_own_shape() {
13008 use crate::{Rect, TextMetrics};
13009 // Baseline-relative, y up-negative; Core Text, Skia and Qt all report like this.
13010 let m = TextMetrics::from_baseline(
13011 40.0,
13012 16.0,
13013 4.0,
13014 11.0,
13015 // Ink starting 1 right of the origin, from 11 above the baseline to 2 below it.
13016 Rect::new(1.0, -11.0, 38.0, 13.0),
13017 );
13018 assert_eq!(
13019 (m.width, m.height, m.ascent, m.cap_height),
13020 (40.0, 20.0, 16.0, 11.0)
13021 );
13022 // Shifted down by the ascent: the ink now starts 5 below the line box's top, which is
13023 // where a cap begins in a slot whose baseline is at 16.
13024 assert_eq!(m.ink, Rect::new(1.0, 5.0, 38.0, 13.0));
13025 assert_eq!(m.ascent - m.cap_height, m.ink.origin.y);
13026
13027 // The eight-slot wire form is already line-box-relative and passes straight through.
13028 let w = TextMetrics::from_slots(&[40.0, 20.0, 16.0, 11.0, 1.0, 5.0, 38.0, 13.0]);
13029 assert_eq!(w, m);
13030 }
13031
13032 /// The fallback must be usable, not merely present: a caller frames text with it on a toolkit
13033 /// that cannot measure, and every relation it relies on has to hold.
13034 #[test]
13035 fn the_approximation_is_internally_consistent() {
13036 use crate::TextMetrics;
13037 let m = TextMetrics::approximate("Agy", 20.0);
13038 assert!(m.ascent < m.height, "the baseline sits inside the line box");
13039 assert!(
13040 m.cap_height < m.ascent,
13041 "caps do not reach above the ascent"
13042 );
13043 // The ink box is the whole line box: a superset, so an overlap test using it can only be
13044 // too cautious. Never a claim to be tighter than it knows.
13045 assert_eq!(m.ink.origin.x, 0.0);
13046 assert_eq!(m.ink.origin.y, 0.0);
13047 assert_eq!(m.ink.size.width, m.width);
13048 assert_eq!(m.ink.size.height, m.height);
13049 // Empty text still answers a usable (zero-width, full-height) slot.
13050 let e = TextMetrics::approximate("", 20.0);
13051 assert_eq!(e.width, 0.0);
13052 assert!(e.height > 0.0);
13053 }
13054}
13055
13056#[cfg(test)]
13057mod cap_list_tests {
13058 use super::Cap;
13059
13060 #[test]
13061 fn every_capability_is_listed_once_in_its_place() {
13062 for (i, cap) in Cap::ALL.iter().enumerate() {
13063 assert_eq!(cap.ordinal(), i, "{cap:?} is out of place in Cap::ALL");
13064 }
13065 }
13066}
13067
13068#[cfg(test)]
13069mod button_menu_tests {
13070 use super::*;
13071 use std::cell::Cell;
13072 use std::rc::Rc;
13073
13074 fn action(label: &str) -> MenuItem {
13075 MenuItem::Action {
13076 id: None,
13077 action: 1,
13078 label: label.into(),
13079 shortcut: None,
13080 enabled: true,
13081 checked: None,
13082 role: None,
13083 icon: None,
13084 }
13085 }
13086
13087 #[test]
13088 fn a_provider_that_releases_its_button_shows_nothing() {
13089 let registered = Rc::new(Cell::new(true));
13090 let r = registered.clone();
13091 // The provider's app code removes the button (here: unregisters it), then still answers.
13092 let provider: ContextMenuFn = Rc::new(move |_| {
13093 r.set(false);
13094 vec![action("Open")]
13095 });
13096 assert!(resolve_button_menu(&provider, || registered.get()).is_none());
13097 }
13098
13099 #[test]
13100 fn a_live_button_shows_its_items_and_an_empty_menu_shows_nothing() {
13101 let provider: ContextMenuFn = Rc::new(|_| vec![action("Open")]);
13102 assert_eq!(
13103 resolve_button_menu(&provider, || true).map(|i| i.len()),
13104 Some(1)
13105 );
13106 let empty: ContextMenuFn = Rc::new(|_| Vec::new());
13107 let mut asked = false;
13108 assert!(
13109 resolve_button_menu(&empty, || {
13110 asked = true;
13111 true
13112 })
13113 .is_none()
13114 );
13115 assert!(!asked, "an empty menu needs no registry check");
13116 }
13117}
13118
13119#[cfg(test)]
13120mod elide_tests {
13121 use super::{elide, props::Truncation};
13122
13123 fn cells(s: &str) -> f64 {
13124 s.chars().count() as f64
13125 }
13126
13127 #[test]
13128 fn text_that_fits_is_untouched() {
13129 for mode in [Truncation::Tail, Truncation::Head, Truncation::Middle] {
13130 assert_eq!(elide("short", mode, 5.0, cells), "short");
13131 }
13132 }
13133
13134 #[test]
13135 fn each_mode_keeps_its_end_and_fills_the_width() {
13136 let text = "abcdefghijklmnopqrstuvwxyz";
13137 assert_eq!(elide(text, Truncation::Tail, 8.0, cells), "abcdefg\u{2026}");
13138 assert_eq!(elide(text, Truncation::Head, 8.0, cells), "\u{2026}tuvwxyz");
13139 assert_eq!(
13140 elide(text, Truncation::Middle, 8.0, cells),
13141 "abcd\u{2026}xyz"
13142 );
13143 }
13144
13145 #[test]
13146 fn nothing_fits_leaves_the_ellipsis() {
13147 for mode in [Truncation::Tail, Truncation::Head, Truncation::Middle] {
13148 assert_eq!(elide("abcdef", mode, 0.5, cells), "\u{2026}");
13149 }
13150 }
13151
13152 #[test]
13153 fn multibyte_text_is_cut_on_character_boundaries() {
13154 let text = "日本語のファイル名.txt";
13155 let got = elide(text, Truncation::Middle, 7.0, cells);
13156 assert_eq!(got.chars().count(), 7);
13157 assert!(got.starts_with("日本語") && got.ends_with("txt"), "{got}");
13158 }
13159}