day_spec/lib.rs
1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3
4//! day-spec: the toolkit specification (DESIGN.md §8).
5//!
6//! Backends depend only on this crate (never on day-core). One backend is linked per binary;
7//! `day-core` is monomorphized over the concrete [`Toolkit`].
8
9use std::any::Any;
10use std::collections::HashMap;
11
12pub use day_geometry::*;
13
14pub mod controls;
15pub use controls::datetime::{DayDate, DayTime, now_epoch_millis, now_epoch_secs};
16
17pub mod applications;
18pub mod capture;
19/// Inline markdown → styled runs (docs/markdown.md). Lives here rather than in day-pieces
20/// because it produces `TextRun`s, and every format codec beside it reads the same model.
21pub mod markdown;
22/// Bundled-resource random-access API + the per-backend `ResourceOpener` hook (§18.3).
23pub mod resource;
24/// Styled text: the document model `label().runs(…)` renders and `day-piece-text-editor` edits,
25/// with the Markdown / HTML / RTF codecs over it (docs/texteditor.md).
26pub mod styled;
27/// Import and export for [`StyledText`]: Markdown, HTML and RTF (docs/texteditor.md).
28pub mod styled_codec;
29pub mod transfer;
30
31pub use resource::{
32 AssetDir, AssetName, FontFamily, ImageName, Resource, ResourceOpener, VectorName,
33 resolve_asset_dir, resolve_image_file, resource, set_resource_opener,
34};
35pub use styled::{
36 ListStyle, ParagraphAlign, ParagraphRun, ParagraphStyle, RunStyle, StyledText, Underline,
37 coalesce_runs, paragraph_bounds, paragraphs_are_valid,
38};
39pub use styled_codec::{
40 DocStyle, html_to_styled, markdown_to_styled, rtf_to_styled, styled_to_html,
41 styled_to_markdown, styled_to_rtf,
42};
43
44/// Bundled custom fonts: name-table parsing, runtime font directory, family → file resolution
45/// (§18.4). Shared by the CLI stagers and the backends' startup registration. Lives in the leaf
46/// `day-fonts` crate (pure std, no `day-geometry`), re-exported here so `day_spec::fonts::…` is
47/// unchanged for the backends while the CLI can depend on `day-fonts` alone.
48pub use day_fonts as fonts;
49
50/// The route inside a deep-link URL (docs/deep-links.md): everything after `scheme://`,
51/// query included (`notes://mail/inbox?hint=x` ⇒ `mail/inbox?hint=x`). A string with no
52/// scheme passes through unchanged (it is already a route). One definition, shared by every
53/// platform's intake and the dayscript `deep_link` step, so a URL maps to the same route
54/// bytes everywhere; percent-decoding stays with the route parser (docs/navigation.md).
55#[must_use]
56pub fn route_of_url(url: &str) -> String {
57 match url.split_once("://") {
58 Some((_, rest)) => rest.to_string(),
59 None => url.to_string(),
60 }
61}
62
63// ---------------------------------------------------------------------------
64// Identity
65// ---------------------------------------------------------------------------
66
67/// Interned piece-kind key, e.g. `"day.label"` or `"acme.combobox"`.
68pub type PieceKind = &'static str;
69
70/// Declare the built-in piece vocabulary once: the [`Builtin`] enum, its string keys, and the
71/// `kinds::*` constants are all generated from this list, so they can never drift apart.
72///
73/// Adding a variant here is a breaking change for backends: every `Toolkit` must decide how
74/// to realize the new kind, and the exhaustive `match Builtin` in each backend's `realize`
75/// turns that decision into a compile error rather than a runtime placeholder.
76macro_rules! builtin_kinds {
77 ($( $(#[$meta:meta])* $variant:ident = $konst:ident => $key:literal ),+ $(,)?) => {
78 /// Every piece kind Day itself defines (§5.3). Backends match on this exhaustively in
79 /// `realize`; anything outside it is an extension piece resolved through the
80 /// [`Registry`] by its string [`PieceKind`].
81 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
82 pub enum Builtin {
83 $( $(#[$meta])* $variant, )+
84 }
85
86 impl Builtin {
87 /// This kind's wire key: the same string as the matching `kinds::*` constant.
88 pub const fn key(self) -> PieceKind {
89 match self { $( Builtin::$variant => $key, )+ }
90 }
91
92 /// The built-in this key names, or `None` for an extension piece's kind.
93 pub fn from_key(kind: PieceKind) -> Option<Builtin> {
94 match kind {
95 $( $key => Some(Builtin::$variant), )+
96 _ => None,
97 }
98 }
99
100 /// Every built-in, in declaration order (conformance tests iterate it).
101 pub const ALL: &'static [Builtin] = &[ $( Builtin::$variant, )+ ];
102 }
103
104 /// The built-in piece keys as plain strings, for the registry and the `PieceKind` API.
105 pub mod kinds {
106 $( $(#[$meta])* pub const $konst: super::PieceKind = super::Builtin::$variant.key(); )+
107 }
108 };
109}
110
111builtin_kinds! {
112 /// A dumb native panel (the column/row/stack backing).
113 Container = CONTAINER => "day.container",
114 Label = LABEL => "day.label",
115 Button = BUTTON => "day.button",
116 Toggle = TOGGLE => "day.toggle",
117 Slider = SLIDER => "day.slider",
118 TextField = TEXT_FIELD => "day.text_field",
119 /// A native multi-line text editor (docs/textarea.md). Built-in since 2026-07 (previously
120 /// the satellite `day-piece-textarea`).
121 TextArea = TEXT_AREA => "day.text_area",
122 /// A native option picker with menu/segmented/inline stylings (docs/picker.md). Built-in
123 /// since 2026-07 (previously the satellite `day-piece-picker`).
124 Picker = PICKER => "day.picker",
125 Divider = DIVIDER => "day.divider",
126 Scroll = SCROLL => "day.scroll",
127 Image = IMAGE => "day.image",
128 /// Progress indicator: determinate bar (fraction) or indeterminate spinner.
129 Progress = PROGRESS => "day.progress",
130 Canvas = CANVAS => "day.canvas",
131 /// Navigation host (docs/navigation.md): stack on mobile, split panes on desktop.
132 Nav = NAV => "day.nav",
133 /// One destination's native container inside a NAV host.
134 NavPage = NAV_PAGE => "day.nav_page",
135 /// Native navigation item list (docs/navigation.md): `NSOutlineView` source list /
136 /// `GtkListBox` navigation-sidebar / `QListWidget` / `UITableView` rows with chevrons.
137 NavMenu = NAV_MENU => "day.nav_menu",
138 /// Native recycling list (docs/list.md): `NSTableView` / `UITableView` / `RecyclerView` /
139 /// `GtkListView` / `QListView`. Owns scrolling + cell reuse; Day binds row content on demand.
140 List = LIST => "day.list",
141 /// A recycled row's content anchor inside a `LIST`; Day adopts the native cell as its handle.
142 /// Adopted, never realized: `Toolkit::adopt` wraps the native cell, so backends' `realize`
143 /// never sees this kind.
144 ListCell = LIST_CELL => "day.list_cell",
145 /// Native hierarchical tree (docs/tree.md): `NSOutlineView` / sidebar collection list /
146 /// `GtkListView`+`TreeListModel` / WinUI `TreeView` / ArkTS `TreeView`. Rows nest, disclose, and
147 /// drag-to-reparent; Day binds row content on demand through `Toolkit::attach_tree`.
148 /// Row cells are adopted (the same `LIST_CELL` anchor path as `List`).
149 Tree = TREE => "day.tree",
150 /// A fullscreen cover (docs/cover.md): a modal surface presented over the whole window,
151 /// edge-to-edge, driven by `CoverPatch::{Present,Dismiss}`. The handle is the cover's
152 /// content container; its frame is native-owned while presented (the backend sizes it to
153 /// the safe area and reports it via `Event::FrameChanged`).
154 Cover = COVER => "day.cover",
155 /// Content beside a trailing inspector pane (docs/inspector.md): the native split whose
156 /// second pane is a show/hidable properties panel. Exactly two `INSPECTOR_PANE` children:
157 /// the content, then the panel (`InspectorPaneProps::panel`). Only realized where
158 /// `Cap::Inspector` answers `Native`; everywhere else the `inspector` piece composes the
159 /// pane from plain containers and this kind never reaches the backend.
160 Inspector = INSPECTOR => "day.inspector",
161 /// One pane's container inside an `INSPECTOR` host: the `NAV_PAGE` of the inspector split.
162 /// Its frame is native-owned (the splitter/dock sizes it), reported via
163 /// `Event::FrameChanged` on this node; Day lays the pane's content out inside it.
164 InspectorPane = INSPECTOR_PANE => "day.inspector_pane",
165 /// Two panes with a divider the user drags (docs/split.md): the toolkit's own splitter,
166 /// side by side or stacked (`SplitProps::axis`), the first pane's share bound to the app
167 /// (`SplitProps::fraction`, reported back as `Event::ValueChanged`). Exactly two
168 /// `SPLIT_PANE` children, first then second. Only realized where `Cap::Split` answers
169 /// `Native`; everywhere else the `split` piece composes the panes and draws the divider
170 /// itself, and this kind never reaches the backend.
171 Split = SPLIT => "day.split",
172 /// One pane's container inside a `SPLIT` host: native-owned frame (the splitter sizes it),
173 /// reported via `Event::FrameChanged` on this node, like an `INSPECTOR_PANE`.
174 SplitPane = SPLIT_PANE => "day.split_pane",
175 /// A list row's standard content (docs/list.md "List items"): a leading icon, a title, an
176 /// optional subtitle and trailing detail, and a check mark, drawn the way the platform
177 /// draws its own list rows: a `UIListContentView` with the cell's default content
178 /// configuration, a Material list item, an `NSTableCellView`'s image and text, a GTK row
179 /// box. Only realized where `Cap::ListItem` answers `Native`; everywhere else the
180 /// `list_item` piece composes the same content and this kind never reaches the backend.
181 ListItem = LIST_ITEM => "day.list_item",
182}
183
184/// Whether a kind is worth asking [`Toolkit::first_baseline`] about (docs/baseline.md).
185///
186/// A blocklist, not an allowlist: the structural and graphic kinds below have no text of their
187/// own, and everything else (including extension pieces like the date/time pickers, whose kinds
188/// day-spec has never heard of) is assumed to be worth asking. An extension piece that turns
189/// out to have no baseline answers `None`, which costs one query; an allowlist would instead
190/// silently leave every extension piece centered, which is the bug this shape avoids.
191#[must_use]
192pub fn kind_has_baseline(kind: PieceKind) -> bool {
193 !matches!(
194 Builtin::from_key(kind),
195 Some(
196 Builtin::Container
197 | Builtin::Scroll
198 | Builtin::Divider
199 | Builtin::Image
200 | Builtin::Canvas
201 | Builtin::Slider
202 | Builtin::Toggle
203 | Builtin::Progress
204 | Builtin::Nav
205 | Builtin::NavPage
206 | Builtin::NavMenu
207 | Builtin::Split
208 | Builtin::SplitPane
209 | Builtin::List
210 | Builtin::ListCell
211 | Builtin::Cover
212 | Builtin::Inspector
213 | Builtin::InspectorPane
214 )
215 )
216}
217
218/// Placeholder leaves: the one hole in Day's rendering that is invisible to a screenshot.
219///
220/// When a backend has no renderer for a kind it realizes a visible `⟨kind⟩` label rather than
221/// failing. That is the right runtime behavior, but it means a missing renderer looks like a
222/// rendered app: the walkthrough passes, and the gallery's validator (which counts distinct
223/// colors) sees nothing wrong. That is how a stale `skip_on:` survived in the showcase
224/// walkthrough after the renderer it skipped had landed.
225///
226/// So every backend reports here instead of keeping its own warn-once set. The table is process-
227/// wide and append-only, which gives dayscript's `assert_no_placeholders` something to assert on
228/// (`crates/day-script`): a placeholder becomes a test failure instead of a silent gap.
229pub mod placeholder {
230 use super::PieceKind;
231 use std::collections::BTreeSet;
232 use std::sync::{Mutex, OnceLock};
233
234 fn table() -> &'static Mutex<BTreeSet<PieceKind>> {
235 static TABLE: OnceLock<Mutex<BTreeSet<PieceKind>>> = OnceLock::new();
236 TABLE.get_or_init(|| Mutex::new(BTreeSet::new()))
237 }
238
239 /// Record that `toolkit` had no renderer for `kind` and warn, once per kind, however many
240 /// nodes of it are realized. Call from a backend's `realize` fallback arm.
241 pub fn report(kind: PieceKind, toolkit: &str) {
242 let Ok(mut seen) = table().lock() else { return };
243 if seen.insert(kind) {
244 log::warn!(
245 "no renderer for piece kind \"{kind}\" on {toolkit} — is the piece's \
246 {toolkit} feature enabled? (rendering a placeholder)"
247 );
248 }
249 }
250
251 /// Every kind that has rendered a placeholder in this process, sorted. Empty is the goal.
252 #[must_use]
253 pub fn seen() -> Vec<PieceKind> {
254 table()
255 .lock()
256 .map_or_default(|s| s.iter().copied().collect())
257 }
258}
259
260/// Downcast a realize/update payload to the props/patch type a backend arm expects,
261/// warning (once per kind, via [`placeholder::report`]) instead of panicking on a
262/// mismatch. A mismatch means a piece registered under a builtin key or a day-core
263/// regression; degrade to the placeholder path, never abort: most backend arms run
264/// inside native up-calls, where a panic is a process kill.
265pub fn props_of<'a, T: 'static>(
266 kind: PieceKind,
267 toolkit: &str,
268 any: &'a dyn std::any::Any,
269) -> Option<&'a T> {
270 let p = any.downcast_ref::<T>();
271 if p.is_none() {
272 placeholder::report(kind, toolkit);
273 }
274 p
275}
276
277/// Pointer-keyed per-view side tables with an automatic release sweep.
278///
279/// Backends keep auxiliary per-view state in thread-local maps keyed by the native
280/// handle's address. Historically each map needed its own line in `release()`, a
281/// checklist that drifted repeatedly (missed entries have produced both leaks and
282/// stale-pointer CI segfaults, since a freed address gets recycled). A [`crate::sidetable::SideTable`]
283/// registers itself with a per-thread sweeper list at construction, so a backend's
284/// `release()` calls [`crate::sidetable::sweep`] once and every table, present and future, drops its
285/// entry for that handle, running its teardown hook if one was given.
286pub mod sidetable {
287 use std::cell::RefCell;
288 use std::collections::HashMap;
289 use std::rc::Rc;
290
291 /// One table's "remove this key" hook, registered at construction.
292 type Sweeper = Rc<dyn Fn(usize)>;
293
294 thread_local! {
295 static SWEEPERS: RefCell<Vec<Sweeper>> = const { RefCell::new(Vec::new()) };
296 }
297
298 /// A pointer-keyed map swept automatically by [`crate::sidetable::sweep`]. Construct inside a
299 /// `thread_local!` initializer; the optional teardown hook runs for each removed
300 /// value (release a retained native object, dispose an owned child, …), both on sweep
301 /// and on plain [`SideTable::remove`], so teardown cannot be bypassed by accident.
302 pub struct SideTable<V: 'static> {
303 map: Rc<RefCell<HashMap<usize, V>>>,
304 teardown: Option<Rc<dyn Fn(V)>>,
305 }
306
307 impl<V> Default for SideTable<V> {
308 fn default() -> Self {
309 Self::new()
310 }
311 }
312
313 impl<V> SideTable<V> {
314 #[must_use]
315 pub fn new() -> Self {
316 Self::build(None)
317 }
318
319 /// A table whose values need active teardown when their view goes away.
320 pub fn with_teardown(teardown: impl Fn(V) + 'static) -> Self {
321 Self::build(Some(Rc::new(teardown)))
322 }
323
324 fn build(teardown: Option<Rc<dyn Fn(V)>>) -> Self {
325 let map: Rc<RefCell<HashMap<usize, V>>> = Rc::default();
326 let (m, t) = (map.clone(), teardown.clone());
327 SWEEPERS.with(|s| {
328 s.borrow_mut().push(Rc::new(move |key| {
329 // Remove under the borrow, tear down outside it: hooks may re-enter
330 // toolkit code that reads other tables.
331 let v = m.borrow_mut().remove(&key);
332 if let (Some(v), Some(t)) = (v, &t) {
333 t(v);
334 }
335 }));
336 });
337 SideTable { map, teardown }
338 }
339
340 pub fn insert(&self, key: usize, value: V) -> Option<V> {
341 self.map.borrow_mut().insert(key, value)
342 }
343
344 /// Remove and tear down the entry (returns `None` always when a teardown hook
345 /// exists, because the value is consumed by it; use [`SideTable::take`] to skip it).
346 #[must_use]
347 pub fn remove(&self, key: usize) -> Option<V> {
348 let v = self.map.borrow_mut().remove(&key)?;
349 match &self.teardown {
350 Some(t) => {
351 t(v);
352 None
353 }
354 None => Some(v),
355 }
356 }
357
358 /// Remove without running the teardown hook (the caller takes ownership).
359 #[must_use]
360 pub fn take(&self, key: usize) -> Option<V> {
361 self.map.borrow_mut().remove(&key)
362 }
363
364 #[must_use]
365 pub fn contains(&self, key: usize) -> bool {
366 self.map.borrow().contains_key(&key)
367 }
368
369 #[must_use]
370 pub fn get(&self, key: usize) -> Option<V>
371 where
372 V: Clone,
373 {
374 self.map.borrow().get(&key).cloned()
375 }
376
377 /// Run `f` on the value in place (returns `None` if absent).
378 pub fn with<R>(&self, key: usize, f: impl FnOnce(&mut V) -> R) -> Option<R> {
379 self.map.borrow_mut().get_mut(&key).map(f)
380 }
381
382 /// Run `f` over every `(key, value)` (immutable; do not re-enter this table).
383 pub fn for_each(&self, mut f: impl FnMut(usize, &V)) {
384 for (k, v) in self.map.borrow().iter() {
385 f(*k, v);
386 }
387 }
388 }
389
390 /// Remove `key` from every table registered on this thread, running teardowns.
391 /// Call once from a backend's `release()` (and once per auxiliary native object a
392 /// release frees, e.g. an owned content container).
393 pub fn sweep(key: usize) {
394 // Clone the sweeper list first: a teardown may construct a new SideTable
395 // (registering a sweeper) without deadlocking on the borrow.
396 let sweepers: Vec<Sweeper> = SWEEPERS.with(|s| s.borrow().clone());
397 for f in sweepers {
398 f(key);
399 }
400 }
401}
402
403/// Containment for FFI entry points: native callbacks, JNI up-calls, posted-closure
404/// trampolines. A Rust panic unwinding out of an `extern "C"` frame is undefined
405/// behavior (an abort), so every backend trampoline runs its body through
406/// [`ffi_guard::contain`]: a caught panic is reported, the installed recovery hook
407/// restores runtime coherence (day-core installs the reactive runtime's
408/// `recover_from_panic` at boot), and the given default is returned.
409pub mod ffi_guard {
410 use std::sync::OnceLock;
411
412 static RECOVERY: OnceLock<fn()> = OnceLock::new();
413
414 /// Install the post-panic recovery hook (idempotent; first install wins). day-core
415 /// registers `day_reactive::recover_from_panic` here so a contained panic cannot
416 /// leave the reactive observer stack stranded.
417 pub fn set_recovery(f: fn()) {
418 let _ = RECOVERY.set(f);
419 }
420
421 /// Run `f`, containing any panic; on panic, report, run the recovery hook, and
422 /// return `default`.
423 pub fn contain<R>(default: R, f: impl FnOnce() -> R) -> R {
424 match std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)) {
425 Ok(r) => r,
426 Err(payload) => {
427 let msg = payload
428 .downcast_ref::<&str>()
429 .map(std::string::ToString::to_string)
430 .or_else(|| payload.downcast_ref::<String>().cloned())
431 .unwrap_or_else(|| "<non-string panic>".into());
432 log::error!("panic contained at an FFI boundary: {msg}");
433 if let Some(recover) = RECOVERY.get() {
434 recover();
435 }
436 default
437 }
438 }
439 }
440}
441
442/// The painting threads behind the offscreen exports (docs/canvas.md "Exporting").
443///
444/// `Toolkit::render_bitmap` answers with an event, so a toolkit whose 2-D API can draw into a
445/// memory surface from any thread paints there and posts the answer back to the UI thread. The
446/// pool is shared by every toolkit in the process: a few threads, one short of the cores and
447/// never more than four, so a screenful of requests cannot starve the UI thread or the app's
448/// own work. Jobs run in the order they were queued.
449///
450/// Not built for the web: a browser's `createImageBitmap` is already asynchronous, and
451/// `wasm32-unknown-unknown` has no threads to spawn.
452#[cfg(not(target_arch = "wasm32"))]
453pub mod offscreen {
454 use std::sync::atomic::{AtomicUsize, Ordering};
455 use std::sync::{Arc, Mutex, OnceLock, mpsc};
456
457 type Job = Box<dyn FnOnce() + Send + 'static>;
458
459 static QUEUE: OnceLock<Mutex<mpsc::Sender<Job>>> = OnceLock::new();
460 /// How many painting threads started; zero means every job runs where it was queued.
461 static WORKERS: AtomicUsize = AtomicUsize::new(0);
462
463 /// Run `job` on a painting thread, or inline when none could be started. A panic inside
464 /// `job` is contained ([`crate::ffi_guard::contain`]) so one bad replay cannot take the
465 /// thread, and with it every later export, down; the job itself should answer its request
466 /// in that case, which is why toolkits wrap the paint and not the post.
467 pub fn spawn(job: impl FnOnce() + Send + 'static) {
468 let queue = QUEUE.get_or_init(start);
469 if WORKERS.load(Ordering::Acquire) == 0 {
470 crate::ffi_guard::contain((), job);
471 return;
472 }
473 let job: Job = Box::new(job);
474 // The receivers live as long as the process, so a refused send means every worker left
475 // its loop; the job still runs, inline, rather than a request going unanswered.
476 let refused = match queue.lock() {
477 Ok(sender) => sender.send(job).err().map(|e| e.0),
478 Err(_) => Some(job),
479 };
480 if let Some(job) = refused {
481 crate::ffi_guard::contain((), job);
482 }
483 }
484
485 fn start() -> Mutex<mpsc::Sender<Job>> {
486 let (tx, rx) = mpsc::channel::<Job>();
487 let rx = Arc::new(Mutex::new(rx));
488 let want = std::thread::available_parallelism()
489 .map_or(2, std::num::NonZero::get)
490 .saturating_sub(1)
491 .clamp(1, 4);
492 let mut started = 0;
493 for i in 0..want {
494 let rx = Arc::clone(&rx);
495 let spawned = std::thread::Builder::new()
496 .name(format!("day-paint-{i}"))
497 .spawn(move || {
498 loop {
499 // The lock is held only while waiting for the next job, never while
500 // running one, so the other workers queue behind it fairly.
501 let next = match rx.lock() {
502 Ok(guard) => guard.recv(),
503 Err(_) => return,
504 };
505 match next {
506 Ok(job) => crate::ffi_guard::contain((), job),
507 Err(_) => return,
508 }
509 }
510 });
511 match spawned {
512 Ok(_) => started += 1,
513 Err(e) => log::error!("day-spec: could not start a painting thread: {e}"),
514 }
515 }
516 WORKERS.store(started, Ordering::Release);
517 Mutex::new(tx)
518 }
519}
520
521/// Realized-node identity as seen by backends (day-core's slotmap key, FFI-encoded).
522#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
523pub struct NodeId(pub u64);
524
525/// Default navigation sidebar width (split presentation) until the pane reports its size.
526/// Semantic container surfaces (see `ContainerProps::role`): each backend maps a role to its
527/// own theme-adaptive material so the fill tracks light/dark mode without app code.
528#[derive(Clone, Copy, Debug, PartialEq, Eq)]
529pub enum SurfaceRole {
530 /// A form `section` card, the platform's grouped-content background: AppKit quaternary
531 /// system fill, libadwaita `.card`, Qt `palette(alternate-base)`, UIKit tertiary system
532 /// fill, Material surface-container, XAML card background brush.
533 SectionCard,
534 /// The window's own background, the surface a page sits on: what an opaque cover paints
535 /// by default, and the card of a composed modal sheet (docs/cover.md "Modal sheet").
536 Window,
537 /// The layer between a composed modal sheet and the page under it, which says the page is
538 /// out of reach until the sheet goes. The container's `background` is the plain dimming a
539 /// backend draws when it has no material of its own; the web frosts the page instead.
540 Scrim,
541}
542
543pub const NAV_SIDEBAR_WIDTH: f64 = 240.0;
544
545/// Drag limits for a navigation host's sidebar pane, around [`NAV_SIDEBAR_WIDTH`]. Shared by the
546/// desktops whose divider the user can drag (docs/navigation.md): AppKit enforces both through
547/// its `NSSplitViewItem`; Qt honors the minimum through the pane's own minimum size and leaves
548/// the maximum to the user.
549pub const NAV_SIDEBAR_MIN_W: f64 = 160.0;
550pub const NAV_SIDEBAR_MAX_W: f64 = 400.0;
551
552/// Default preferred width of a navigation host's content-list pane
553/// (`props::NavProps::list_width`, docs/navigation.md), Mail's message-list proportion.
554pub const NAV_LIST_WIDTH: f64 = 300.0;
555
556/// Drag limits for the content-list pane, around the app's preferred width; the same split of
557/// duties as the sidebar's.
558pub const NAV_LIST_MIN_W: f64 = 220.0;
559pub const NAV_LIST_MAX_W: f64 = 560.0;
560
561/// Reserved id for window-level events (resize, lifecycle): day-core routes it to the root.
562pub const WINDOW_NODE: NodeId = NodeId(u64::MAX);
563
564/// Which nodes handle the non-text keys (docs/menus.md). Keys follow focus (the focused piece
565/// hears them and nobody else), so a backend whose focused view would have to claim a key from
566/// the platform's own dispatch (AppKit's responder chain, the DOM's default action) has to know
567/// whether the app wants it before swallowing it. An unclaimed arrow has to keep traveling, or
568/// a canvas inside a scroll view would silently eat the keys that scroll it.
569///
570/// It lives here, in day-spec, rather than in day-core: `day-toolkit-dom` depends on day-spec alone,
571/// and this is a fact about a node that both sides need.
572pub mod keys {
573 use super::NodeId;
574 use std::cell::RefCell;
575 use std::collections::HashSet;
576
577 thread_local! {
578 static HANDLED: RefCell<HashSet<NodeId>> = RefCell::new(HashSet::new());
579 }
580
581 /// Declare that `node` has a key handler (what `Decorate::on_key` records at build).
582 pub fn mark(node: NodeId) {
583 HANDLED.with(|h| h.borrow_mut().insert(node));
584 }
585
586 /// Whether `node` has one.
587 #[must_use]
588 pub fn handled(node: NodeId) -> bool {
589 HANDLED.with(|h| h.borrow().contains(&node))
590 }
591
592 thread_local! {
593 static TEXT: RefCell<HashSet<NodeId>> = RefCell::new(HashSet::new());
594 }
595
596 /// Declare that `node` takes the whole keyboard while focused (what `Decorate::keyboard`
597 /// records at build): every key the platform delivers reaches its handler, named the way
598 /// [`super::KeyEvent`] describes for the full route, and a touch platform raises its soft
599 /// keyboard for it.
600 pub fn mark_text(node: NodeId) {
601 TEXT.with(|h| h.borrow_mut().insert(node));
602 }
603
604 /// Whether `node` takes the whole keyboard: it declared so AND it [`handled`]s keys. A
605 /// declaration with no `.on_key` behind it claims nothing, so every backend asks this one
606 /// question before it raises a soft keyboard, names a letter or claims a Tab.
607 #[must_use]
608 pub fn text(node: NodeId) -> bool {
609 TEXT.with(|h| h.borrow().contains(&node)) && handled(node)
610 }
611
612 /// The keys a focused single-line text field hands to its key handler instead of acting
613 /// on them itself (docs/textfield.md "Keys"): what an address bar needs to walk a
614 /// suggestion list and to cancel an edit. Return stays the field's submit, Tab its focus
615 /// walk, and every other key its editing.
616 pub const FIELD_KEYS: [&str; 3] = ["ArrowUp", "ArrowDown", "Escape"];
617
618 /// Whether a focused text field at `node` claims the key named `key` (web name, see
619 /// [`super::KeyEvent::key`]) pressed with `modifiers`: one of [`FIELD_KEYS`], no modifier
620 /// held, and a handler declared for the field. A backend that answers yes reports
621 /// `Event::Key` for `node` and keeps the key from the native field.
622 #[must_use]
623 pub fn field_claims(node: NodeId, key: &str, modifiers: u8) -> bool {
624 modifiers == 0 && FIELD_KEYS.contains(&key) && handled(node)
625 }
626
627 /// Drop both marks for a node that left the tree (day-core calls it from its removal
628 /// path). Node ids are generational, so a stale id would never match a new node; this
629 /// keeps the registries from growing with every rebuilt canvas.
630 pub fn forget(node: NodeId) {
631 HANDLED.with(|h| h.borrow_mut().remove(&node));
632 TEXT.with(|h| h.borrow_mut().remove(&node));
633 }
634}
635
636/// Raw foreign native handle for polyglot adoption (§15.3).
637pub type RawHandle = *mut std::ffi::c_void;
638
639// ---------------------------------------------------------------------------
640// Events (§8.3)
641// ---------------------------------------------------------------------------
642
643/// The wire table for backends whose native side reaches Rust through one numeric-kind
644/// trampoline (Android's JNI `nativeOnEvent`, ArkUI's `day_arkui_on_event`). This enum
645/// defines those kind numbers; the Java and C++ sides carry mirrored constants that parity
646/// tests check against these discriminants (so a collision or drift fails `cargo test` on the
647/// host instead of silently mis-decoding events on a device). AppKit/UIKit/GTK/Qt emit `Event`
648/// values directly and never use these numbers; XAML uses per-event callbacks with its own
649/// small local codes.
650///
651/// Payload conventions ride `(num: f64, text: String)` per kind, documented on each variant.
652pub mod bridge {
653 /// One numeric event kind. `as i32` is the wire value.
654 #[repr(i32)]
655 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
656 pub enum BridgeKind {
657 /// Click/press. No payload.
658 Pressed = 0,
659 /// `text` = the field's full new text.
660 TextChanged = 1,
661 /// `num` != 0 ⇒ on.
662 ToggleChanged = 2,
663 /// `num` = the new value.
664 ValueChanged = 3,
665 /// `num` = the selected index.
666 SelectionChanged = 4,
667 /// `num` == 1 ⇒ the native side already popped (predictive back / up arrow).
668 NavBack = 5,
669 /// Nav/tab page size report; `text` = `"w,h"` in px (Rust divides by density).
670 FrameChanged = 6,
671 /// Warm deep link; `text` = the route.
672 Deeplink = 7,
673 /// Modal answered with a button; `num` = the button index.
674 PresentButton = 8,
675 /// Modal answered with text; `text` = the entry.
676 PresentText = 9,
677 /// Modal dismissed.
678 PresentDismissed = 10,
679 /// Gesture; `num` = phase (0 tap, 1 began, 2 changed, 3 ended), `text` = `"x,y,tx,ty"` px.
680 Gesture = 11,
681 /// Piece-defined open channel (`Event::Custom` with an empty tag): the piece reads the
682 /// raw `num`/`text` payload.
683 Custom = 12,
684 /// Menu selection; the event's node id is the chosen action's dispatch id.
685 MenuAction = 13,
686 /// App lifecycle; `num` = the phase code (`day_spec::Lifecycle` order).
687 Lifecycle = 14,
688 /// File-picker answer; `text` = chosen locators joined by the unit separator.
689 PresentFile = 15,
690 /// `num` != 0 ⇒ gained keyboard focus.
691 FocusChanged = 16,
692 /// IME action / Return.
693 Submitted = 17,
694 /// Root size change; `text` = `"w,h"` in px. Routed to `WINDOW_NODE` as a window
695 /// resize (the rail rotation, late inset passes, and the soft keyboard ride).
696 WindowResized = 18,
697 /// Safe-area report from an edge-to-edge backend; `text` =
698 /// `"top,bottom,leading,trailing"` in px (Rust divides by density and feeds
699 /// `day_core::set_safe_area`). Node id ignored; no `Event` is emitted.
700 SafeArea = 19,
701 /// A secondary window closed (docs/windows.md); the node id is the window's root.
702 WindowClosed = 20,
703 /// A secondary window's key/active state changed; `num` != 0 ⇒ focused.
704 WindowFocused = 21,
705 /// `num` = the settled value: the drag ended (see `Event::ValueCommitted`). A backend
706 /// that cannot tell a settled value from a moving one sends only `ValueChanged`.
707 ValueCommitted = 22,
708 /// Inline search on a `.searchable()` navigation surface (docs/search.md): the field's
709 /// new text, against the nav host's node. `num` = 1 ⇒ the text was submitted (Return or
710 /// the keyboard's Search key), decoding to [`crate::Event::SearchSubmitted`].
711 SearchChanged = 23,
712 /// The toolkit's own adaptive nav container changed presentation and is reporting it
713 /// (docs/size-classes.md). `num` = 1.0 for split, 0.0 for stacked.
714 NavPresentation = 24,
715 /// The system switched between light and dark appearance. No payload; node id ignored
716 /// and no `Event` is emitted; Rust calls `day_core::note_appearance_changed`, the same
717 /// thing AppKit's and GTK's own scheme observers do.
718 AppearanceChanged = 25,
719 /// A fullscreen cover's hide transition finished (docs/cover.md); no payload, and the
720 /// node id is the cover's. Decodes to [`crate::Event::CoverHidden`].
721 CoverHidden = 26,
722 /// A styled text run's link was tapped (docs/text-runs.md); `text` = the run's target.
723 /// Decodes to [`crate::Event::LinkActivated`].
724 LinkActivated = 27,
725 /// The platform's own undo affordance fired (⌘Z, a three-finger swipe, the Edit menu
726 /// through a native front); `num` != 0 ⇒ redo.
727 UndoInvoked = 28,
728 /// A toolbar item produced a value (docs/toolbars.md): the node id is the item's
729 /// dispatch action; `text` = `"on"` with `num` != 0 ⇒ a toggle turned on, `"on"` with
730 /// 0 ⇒ off, `"sel"` with `num` = the chosen segment, `"text:<query>"` ⇒ a search
731 /// item's new text, `"submit:<query>"` ⇒ that text submitted. Decodes to
732 /// [`crate::Event::ToolbarChanged`]. A plain toolbar button sends `MenuAction`.
733 ToolbarChanged = 30,
734 /// An activated list row; `num` is its current index.
735 ListActivated = 31,
736 /// External document copied into app storage; `text` = its local locator.
737 DocumentOpened = 32,
738 /// The user's reduce-motion setting flipped (docs/accessibility.md). No payload; node
739 /// id ignored and no `Event` is emitted; Rust calls `day_core::note_motion_changed`, as
740 /// the desktop backends' own observers do.
741 ReduceMotionChanged = 33,
742 /// Text committed on the full key route (docs/menus.md "The full route"): `text` =
743 /// what the input method or the key typed, `num` = the modifier mask. Decodes to an
744 /// [`crate::Event::Key`] whose `text` is set; a key that typed nothing rides `Key`.
745 Text = 36,
746 /// A non-text key reached the focused node (docs/menus.md); `text` = the day key name
747 /// (`"ArrowLeft"`, `"5"`, …), `num` = the [`crate::KeyEvent`] modifier mask. Decodes to
748 /// [`crate::Event::Key`].
749 Key = 29,
750 /// A window's display state changed (docs/windows.md): `num` = the
751 /// [`crate::WindowState`] code (0 normal, 1 minimized, 2 maximized, 3 fullscreen), against
752 /// the window's root node, or [`crate::WINDOW_NODE`] for the primary. Decodes to
753 /// [`crate::Event::WindowStateChanged`] through [`crate::WindowState::from_code`].
754 WindowStateChanged = 34,
755 /// Native pull-to-refresh request; no payload.
756 RefreshRequested = 35,
757 /// Text shared to the app from the system share sheet (Day.toml `share_target`,
758 /// docs/deep-links.md): `text` = the shared text, then the unit separator and the
759 /// subject when one came with it. Node id ignored and no `Event` is emitted; Rust calls
760 /// `day_core::request_shared_text`, which sends a web link in it to `on_open_url`.
761 SharedText = 37,
762 }
763
764 impl BridgeKind {
765 /// Every variant, for uniqueness/parity tests and exhaustive dispatch.
766 pub const ALL: [BridgeKind; 38] = [
767 BridgeKind::Pressed,
768 BridgeKind::TextChanged,
769 BridgeKind::ToggleChanged,
770 BridgeKind::ValueChanged,
771 BridgeKind::SelectionChanged,
772 BridgeKind::NavBack,
773 BridgeKind::FrameChanged,
774 BridgeKind::Deeplink,
775 BridgeKind::PresentButton,
776 BridgeKind::PresentText,
777 BridgeKind::PresentDismissed,
778 BridgeKind::Gesture,
779 BridgeKind::Custom,
780 BridgeKind::MenuAction,
781 BridgeKind::Lifecycle,
782 BridgeKind::PresentFile,
783 BridgeKind::FocusChanged,
784 BridgeKind::Submitted,
785 BridgeKind::WindowResized,
786 BridgeKind::SafeArea,
787 BridgeKind::WindowClosed,
788 BridgeKind::WindowFocused,
789 BridgeKind::ValueCommitted,
790 BridgeKind::SearchChanged,
791 BridgeKind::NavPresentation,
792 BridgeKind::AppearanceChanged,
793 BridgeKind::CoverHidden,
794 BridgeKind::LinkActivated,
795 BridgeKind::UndoInvoked,
796 BridgeKind::Key,
797 BridgeKind::ToolbarChanged,
798 BridgeKind::ListActivated,
799 BridgeKind::DocumentOpened,
800 BridgeKind::ReduceMotionChanged,
801 BridgeKind::WindowStateChanged,
802 BridgeKind::RefreshRequested,
803 BridgeKind::Text,
804 BridgeKind::SharedText,
805 ];
806 }
807
808 #[cfg(test)]
809 mod tests {
810 use super::BridgeKind;
811
812 /// The kind-15 lesson: two meanings on one number decode silently as the first. Every
813 /// discriminant must be unique, and the table must stay dense enough to spot gaps.
814 #[test]
815 fn discriminants_are_unique() {
816 let mut seen = std::collections::BTreeSet::new();
817 for k in BridgeKind::ALL {
818 assert!(
819 seen.insert(k as i32),
820 "duplicate bridge kind number {} ({k:?})",
821 k as i32
822 );
823 }
824 assert_eq!(seen.len(), BridgeKind::ALL.len());
825 }
826
827 /// `ALL` is what the uniqueness check above sees, so a variant left out of it is a variant
828 /// nothing checks, which is how `SearchChanged` and `NavPresentation` sat outside the
829 /// table. The wire numbers are assigned densely from 0, so demanding the set be exactly
830 /// `0..len` catches both a gap and an omission.
831 #[test]
832 fn table_covers_every_wire_number() {
833 let mut nums: Vec<i32> = BridgeKind::ALL.iter().map(|k| *k as i32).collect();
834 nums.sort_unstable();
835 let dense: Vec<i32> = (0..BridgeKind::ALL.len() as i32).collect();
836 assert_eq!(
837 nums, dense,
838 "bridge kinds must be dense from 0 — a missing entry means a variant no test sees"
839 );
840 }
841 }
842}
843
844#[derive(Clone, Debug, PartialEq)]
845pub enum Event {
846 Pressed,
847 TextChanged(String),
848 Submitted,
849 ToggleChanged(bool),
850 ValueChanged(f64),
851 /// A continuous control's value settled: the drag ended (mouse/touch up), or the value moved
852 /// by a discrete action (a keyboard arrow, a click on the track). Always preceded by the
853 /// `ValueChanged` carrying the same value.
854 ///
855 /// The pair exists because one gesture produces two different facts. `ValueChanged` is the
856 /// live one (bindings follow it so the UI tracks the thumb) and it fires continuously, which
857 /// is why nothing durable should key off it: a drag from 1 to 100 and back to 50 emits every
858 /// value in between. `ValueCommitted` fires once, with the value the user chose, and is what
859 /// a recording, a log, or a refetch should use.
860 ///
861 /// A backend that cannot tell the two apart emits only `ValueChanged`; its sliders then do not
862 /// record (docs/coverage-matrix.md).
863 ValueCommitted(f64),
864 SelectionChanged(i64),
865 /// A list row was activated: desktop double-click/Enter, or a touch tap.
866 /// Separate from selection so keyboard browsing need not open or play the row.
867 ListActivated(usize),
868 /// The platform's own undo affordance fired through a native front (⌘Z on the Edit menu,
869 /// a three-finger swipe, shake-to-undo); `redo` distinguishes the pair. Only backends
870 /// with a native undo system emit it; everywhere else the app's own controls call the
871 /// stack directly and this event never exists (docs/model.md).
872 Undo {
873 redo: bool,
874 },
875 /// The platform's own standard edit command fired through its native route (Edit ▸
876 /// Cut/Copy/Paste, ⌘X/⌘C/⌘V, the browser's `copy`/`paste` DOM events) with no text
877 /// widget claiming it first; the app's edit bridge answers (docs/menus.md). Transport
878 /// is the system clipboard (day-part-clipboard), not the event.
879 Edit(EditOp),
880 /// A multi-select list's selection changed: the full set of selected row indices,
881 /// ascending (empty = nothing selected). Emitted instead of `SelectionChanged` where
882 /// `ListProps::multi_select` is honored (docs/list.md).
883 SelectionSet(Vec<i64>),
884 FocusChanged(bool),
885 Tap(Point),
886 /// A link run inside a label was activated; the payload is [`TextRun::link`] verbatim.
887 LinkActivated(String),
888 LongPress(Point),
889 /// A context-menu summon reported by a toolkit that presents no native menu of its own
890 /// (web-dom): the pieces layer shows the composed menu (docs/menus.md). `local` is the
891 /// point in the node's own coordinates (what the app's provider receives); `window` the
892 /// same point in window coordinates (where the composed panel goes). Toolkits that serve
893 /// context menus natively never emit this.
894 ContextMenu {
895 local: Point,
896 window: Point,
897 },
898 /// A drag/pan gesture (docs/shapes.md). `location` is in the node's local coordinates;
899 /// `translation` is the cumulative movement since `Began`.
900 Drag {
901 phase: DragPhase,
902 location: Point,
903 translation: Point,
904 },
905 /// A pinch/magnify gesture over the node (docs/shapes.md): `scale` is cumulative since
906 /// `Began` (1.0 = unchanged), `location` the gesture's centroid in local coordinates,
907 /// the anchor a zoom keeps stationary. Only nodes that enabled
908 /// [`GestureKind::Pinch`] receive it; a backend with no recognizer emits nothing.
909 Pinch {
910 phase: DragPhase,
911 scale: f64,
912 location: Point,
913 },
914 /// A two-finger rotation over the node (docs/canvas.md "Zoom and pan"): `rotation` is in
915 /// radians, cumulative since `Began`, positive clockwise on screen; `location` the
916 /// gesture's centroid in local coordinates ([`Point::ZERO`] where the platform gives
917 /// none). A trackpad's rotate tick has no gesture session and arrives as a lone `Changed`
918 /// carrying that tick's own angle. Only nodes that enabled [`GestureKind::Rotate`]
919 /// receive it; a backend with no recognizer emits nothing.
920 Rotate {
921 phase: DragPhase,
922 rotation: f64,
923 location: Point,
924 },
925 /// A viewport pan over the node (docs/shapes.md): `delta` is the movement since the
926 /// previous event; incremental, not cumulative, because desktop wheels have no gesture
927 /// session to accumulate over (a discrete wheel tick arrives as a lone `Changed`).
928 /// Two-finger touch pans bracket theirs with `Began`/`Ended`. Distinct from
929 /// [`Event::Drag`], the primary pointer's press-drag.
930 Pan {
931 phase: DragPhase,
932 delta: Point,
933 location: Point,
934 },
935 /// The pointer moved over the node, or left it (docs/canvas.md "Interaction"). `location` is
936 /// in the node's local coordinates. Phases follow the drag vocabulary: `Began` on entry,
937 /// `Changed` for each move, `Ended` on exit, where `location` is the last point seen inside,
938 /// so a handler always knows where the pointer went out.
939 ///
940 /// Only nodes that enabled [`GestureKind::Hover`] receive it, and only on a device with a
941 /// pointer at all.
942 Hover {
943 phase: DragPhase,
944 location: Point,
945 },
946 ScrollChanged(Point),
947 /// A canvas node was re-framed by layout; re-record (§11). Nav pane/page containers
948 /// also report their allocated size with this (docs/navigation.md).
949 FrameChanged(Size),
950 /// Native back navigation (iOS back button/swipe, Android system back or toolbar up).
951 /// `already_popped` = the toolkit already performed the pop natively (iOS); the nav
952 /// host then syncs its stack without re-issuing `NavPatch::Popped`.
953 NavBack {
954 already_popped: bool,
955 },
956 /// A nav host's own adaptive container changed presentation, and Day is being told about it
957 /// after the fact (docs/size-classes.md).
958 ///
959 /// The counterpart to [`props::NavPatch::Presentation`], for the toolkits that answer
960 /// `Cap::NavRepresent = Emulated`: `UISplitViewController` collapsing as a Pro Max iPhone
961 /// rotates into portrait, `SlidingPaneLayout` deciding at measure time that two panes no
962 /// longer fit. Day did not ask for it and must not fight it; the pieces layer only
963 /// reconciles what follows, which is the selection rule (a split presentation cannot draw an
964 /// empty detail pane, so expanding with nothing selected picks the first item).
965 ///
966 /// Emitted on the NAV host node, and only when the presentation actually changed.
967 NavPresentationChanged(props::NavPresentation),
968 Key(KeyEvent),
969 Pointer(PointerEvent),
970 WindowResized(Size),
971 /// The platform asks the app to show a route (docs/navigation.md), a runtime deep link:
972 /// on web-dom, the URL hash changing under the app (hand-edited, or browser back/forward);
973 /// on mobile, a warm scheme link (iOS `application:openURL:`, Android `onNewIntent` via
974 /// `BridgeKind::Deeplink`). Emitted on [`WINDOW_NODE`] (day-core answers with `navigate()`
975 /// when the route differs from the current one) or on the active nav host's node (the nav
976 /// piece answers with `navigate()` itself, docs/deep-links.md). Launch-time deep links use
977 /// `DAY_DEEPLINK`/`set_launch_deeplink` instead; this variant is for changes while the
978 /// app runs.
979 RouteRequested(String),
980 /// A native modal answered request `req` (docs/dialogs.md).
981 PresentResult {
982 req: u64,
983 result: present::PresentResult,
984 },
985 /// A decode started by [`Toolkit::decode_image`] finished (docs/images.md).
986 ///
987 /// Keyed by request id like [`Event::PresentResult`], and for the same reason: the answer
988 /// belongs to a waiting caller, not to a tree node. It never crosses a native boundary
989 /// (every backend raises it from its own Rust arm once the platform decoder answers), so it
990 /// has no [`bridge::BridgeKind`], exactly like the completion events dialogs use in-process.
991 ///
992 /// No bitmap id rides here: day-core minted it and handed it to the backend with the bytes,
993 /// so it already knows which image a request answers for. A backend that stored the image
994 /// under that id has nothing more to say than the facts it read.
995 ImageDecoded {
996 req: u64,
997 result: Result<BitmapInfo, ImageError>,
998 },
999 /// An encode started by [`Toolkit::encode_image`] finished (docs/images.md): the encoded
1000 /// bytes, or why they could not be produced.
1001 ImageEncoded {
1002 req: u64,
1003 result: Result<Vec<u8>, ImageError>,
1004 },
1005 /// A canvas drawing started by [`Toolkit::render_bitmap`] finished rendering
1006 /// (docs/canvas.md "Exporting"). Keyed by request id like [`Event::ImageDecoded`], and like
1007 /// it carries no bitmap id: day-core minted the id and handed it over with the ops, so the
1008 /// answer is only the facts of the image the backend stored under it.
1009 BitmapRendered {
1010 req: u64,
1011 result: Result<BitmapInfo, ExportError>,
1012 },
1013 /// A PDF started by [`Toolkit::render_pdf`] finished (docs/canvas.md "Exporting"): the
1014 /// document's bytes, or why they could not be produced.
1015 PdfRendered {
1016 req: u64,
1017 result: Result<Vec<u8>, ExportError>,
1018 },
1019 /// An open, piece-defined event (§8.2). `tag` names the event for in-process emitters (a static
1020 /// literal); it is empty for events that cross a native boundary (JNI/C-ABI), which carry only the
1021 /// primitive `num`/`text` payload. A piece's `cx.on` reads whichever fields it needs. This is the
1022 /// escape hatch for events the fixed variants above don't cover (a web view's URL, a picked date, …).
1023 Custom {
1024 tag: &'static str,
1025 num: f64,
1026 text: String,
1027 },
1028 /// A menu item (app menu or context menu) with this action id was activated (§ menus). day-core
1029 /// routes it to the app closure registered for the id. Standard-role items don't carry an id
1030 /// (`role` items are handled natively) so they never emit this.
1031 MenuAction(u64),
1032 /// A toolbar item produced a value: a search field's text, a toggle's new state
1033 /// (docs/toolbars.md). `action` is the item's dispatch id, from the same registry
1034 /// [`Event::MenuAction`] uses, and day-core routes it to the closure registered for it.
1035 /// A plain toolbar button has no value and emits `MenuAction` instead.
1036 ToolbarChanged {
1037 action: u64,
1038 value: ToolbarValue,
1039 },
1040 /// A searchable navigation surface's field changed (docs/search.md). Emitted against the nav
1041 /// host's node, not through the toolbar's dispatch registry: search belongs to the surface,
1042 /// so the field can move between the toolbar and the navigation list without the app
1043 /// re-registering anything.
1044 SearchChanged(String),
1045 /// The user picked a different scope. Carries the index into `SearchProps::scopes`.
1046 SearchScopeChanged(usize),
1047 /// The user chose one of `SearchProps::suggestions`, by index. The toolkit has already put
1048 /// that completion in the field and emitted [`Event::SearchChanged`] for it; this says which
1049 /// one, for an app that wants to act on the choice itself.
1050 SearchSuggestionChosen(usize),
1051 /// The user submitted the inline field's text with its Return or Search key. Emitted
1052 /// after the last [`Event::SearchChanged`], with the text as submitted, for a search that
1053 /// runs on demand (a server query) rather than narrowing as the text changes.
1054 SearchSubmitted(String),
1055 /// The app moved through a lifecycle phase (docs/lifecycle.md). Backends emit this from the
1056 /// native app/activity delegate; day-core routes it to the app's `on_lifecycle` handlers.
1057 Lifecycle(Lifecycle),
1058 /// A secondary native window closed (the title-bar close, a platform gesture such as an
1059 /// app-switcher swipe or an activity finish, or `Toolkit::close_window`); emitted on the
1060 /// window's root node after the platform committed the close. day-core disposes the
1061 /// window's subtree on receipt, so native and programmatic closes share one teardown
1062 /// path (docs/windows.md). Never emitted for the primary window (its close terminates
1063 /// the app).
1064 WindowClosed,
1065 /// A secondary window's key/active state changed; emitted on the window's root node.
1066 /// day-core tracks the focused window with it (dialog parenting, dayscript targeting).
1067 WindowFocused(bool),
1068 /// A window's display state changed (docs/windows.md): the user minimized, zoomed or took it
1069 /// fullscreen, or a [`WindowChange::State`] request landed. Emitted on the window's root node
1070 /// (the primary's may arrive on [`WINDOW_NODE`]); day-core feeds the window's `state()`
1071 /// signal with it, so the app reads what the platform did rather than what it asked for.
1072 WindowStateChanged(WindowState),
1073 /// A native list committed a drag-reorder (docs/list.md): row `from` landed at row `to`.
1074 /// Emitted on the `LIST` node by the list piece's commit hook: the reorder driver
1075 /// rotates its snapshot synchronously inside the platform's drop callback, then reports
1076 /// through the event queue so the app's `on_reorder` never runs inside a native animation
1077 /// callstack.
1078 ListReorder {
1079 from: usize,
1080 to: usize,
1081 },
1082 /// A regrouping sidebar committed a drop (`props::NavMenuProps::regroup`, docs/navigation.md
1083 /// "Moving rows between sections"), in item indices into the rows as they were before the
1084 /// move: row `from` now sits in the section whose first row is item `section` (item 0 for
1085 /// rows above the first header), before item `before`, or at that section's end for
1086 /// `None`. `before` is never `from`. Emitted on the `NAV_MENU` node by a toolkit whose
1087 /// `Cap::NavReorder` is `Native`, deferred through the event queue exactly as
1088 /// [`Event::ListReorder`] is; the nav validates it against the app's rules before reporting.
1089 NavRegroup {
1090 from: usize,
1091 section: usize,
1092 before: Option<usize>,
1093 },
1094 /// A native list committed a swipe-delete (docs/list.md): the row at this index is gone.
1095 /// Deferred through the event queue exactly as [`Event::ListReorder`] is.
1096 ListDelete(usize),
1097 /// The native pull-to-refresh control requested an update. The app owns its busy state.
1098 RefreshRequested,
1099 /// A native list activated a swipe action (docs/list.md): the user pressed button `action`
1100 /// (an index into the row's [`ListSwipe::actions_at`] offer for `edge`) on row `index`, or
1101 /// swiped clear across for the edge's first action. Emitted on the `LIST` node by the list
1102 /// piece's commit hook and deferred through the event queue exactly as
1103 /// [`Event::ListReorder`] is, so the app's handler never runs inside a native animation
1104 /// callstack.
1105 ListSwipe {
1106 index: usize,
1107 edge: SwipeEdge,
1108 action: usize,
1109 },
1110 /// A fullscreen cover's hide transition finished (docs/cover.md): the content can now be
1111 /// disposed. Answers [`props::CoverPatch::Dismiss`]; delivery is a hard guarantee, and
1112 /// backends over-report rather than under-report; consumers gate on their own closing
1113 /// flag, so duplicates and belated reports are no-ops.
1114 CoverHidden,
1115 /// The user showed or hid an inspector pane through a native affordance (a dock widget's
1116 /// close button, a divider dragged shut) rather than through Day (docs/inspector.md).
1117 /// Emitted on the `kinds::INSPECTOR` node, and only when the visibility actually changed;
1118 /// the piece writes it back to the bound signal. Applying
1119 /// [`props::InspectorPatch::Visible`] must never re-emit it (the from-native echo rule).
1120 InspectorChanged(bool),
1121 /// The user disclosed or collapsed a tree row through the native affordance (docs/tree.md).
1122 /// Emitted on the `kinds::TREE` node; the piece writes it back to the app's expansion
1123 /// signal. Applying [`props::TreePatch::Expand`] must never re-emit it (the from-native
1124 /// echo rule).
1125 TreeExpanded {
1126 token: u64,
1127 expanded: bool,
1128 },
1129 /// A native tree committed a drag move (docs/tree.md): `token` now sits under `parent`
1130 /// (`None` = the root) at `index` (`None` = dropped onto the parent, an append). Deferred
1131 /// through the event queue exactly as [`Event::ListReorder`] is; the app's `on_move`
1132 /// writes its own data, whose refresh reloads the tree.
1133 TreeMove {
1134 token: u64,
1135 parent: Option<u64>,
1136 index: Option<usize>,
1137 },
1138 /// A tree's selection changed: the full set of selected row tokens (empty = cleared).
1139 /// Token-addressed, since a tree cannot speak row indices: expanding a row renumbers
1140 /// everything below it (docs/tree.md).
1141 TreeSelection(Vec<u64>),
1142}
1143
1144impl Event {
1145 /// Build a text-carrying [`Event::Custom`] (with `num` defaulted to 0), the common case for an
1146 /// in-process piece reporting a value back: `emit(node, Event::custom("webview:url", url))`.
1147 pub fn custom(tag: &'static str, text: impl Into<String>) -> Event {
1148 Event::Custom {
1149 tag,
1150 num: 0.0,
1151 text: text.into(),
1152 }
1153 }
1154}
1155
1156/// An app-lifecycle phase (docs/lifecycle.md). Each backend maps these onto its OS's native app /
1157/// activity delegate. Some phases only exist on some platforms (a mobile app enters the
1158/// background and can be low on memory, a desktop app cannot), so [`Lifecycle::is_universal`]
1159/// marks the ones every backend delivers, and [`Toolkit::supports_lifecycle`] reports per-backend
1160/// truth.
1161///
1162/// Rough native mapping:
1163///
1164/// | phase | AppKit | UIKit | GTK | Qt | Android | XAML |
1165/// |---|---|---|---|---|---|---|
1166/// | `WillLaunch` / `DidLaunch` | `applicationWill/DidFinishLaunching` | same | `startup`/mount | mount | `onCreate` | window create |
1167/// | `DidBecomeActive` | `didBecomeActive` | `didBecomeActive` | `notify::is-active` | `ApplicationActive` | `onResume` | `Activated` |
1168/// | `WillResignActive` | `willResignActive` | `willResignActive` | `notify::is-active` | `ApplicationInactive` | `onPause` | `Deactivated` |
1169/// | `WillEnterForeground` | — | `willEnterForeground` | — | — | `onStart` | — |
1170/// | `DidEnterBackground` | — | `didEnterBackground` | — | — | `onStop` | — |
1171/// | `DidReceiveMemoryWarning` | — | `didReceiveMemoryWarning` | — | — | `onTrimMemory` | — |
1172/// | `WillTerminate` | `willTerminate` | `willTerminate` | `shutdown` | `aboutToQuit` | `onDestroy` | window close |
1173/// | `DidExit` | after `willTerminate` | after `willTerminate` | `run` returned | `exec` returned | after `onDestroy` | loop returned |
1174#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1175pub enum Lifecycle {
1176 /// Before the window and UI are built: the first thing to run. Set up global state here.
1177 WillLaunch,
1178 /// The UI is mounted and the app is about to start running. Kick off startup work here.
1179 DidLaunch,
1180 /// The app came to the foreground and is the active, focused app receiving input.
1181 DidBecomeActive,
1182 /// The app is about to stop being active (an interruption, app switch, or losing focus).
1183 WillResignActive,
1184 /// The app is about to return to the foreground (mobile). Refresh what background invalidated.
1185 WillEnterForeground,
1186 /// The app left the foreground and is no longer visible (mobile). Persist state, release UI work.
1187 DidEnterBackground,
1188 /// The system is low on memory (mobile). Drop caches and non-essential memory now.
1189 DidReceiveMemoryWarning,
1190 /// The app is about to terminate: the last chance to save. Triggered by the Quit command,
1191 /// the platform's quit shortcut, or the OS reclaiming the app.
1192 WillTerminate,
1193 /// The run loop is over and nothing of the app will run after this: the last phase, after
1194 /// every `WillTerminate` handler. Day logs its exit line ("Clean exit for …") once the
1195 /// handlers have run, so a handler here is the app's last word before it.
1196 DidExit,
1197}
1198
1199impl Lifecycle {
1200 /// Every phase, in delivery order (launch → run → quit). Handy for logging/registration sweeps.
1201 pub const ALL: [Lifecycle; 9] = [
1202 Lifecycle::WillLaunch,
1203 Lifecycle::DidLaunch,
1204 Lifecycle::DidBecomeActive,
1205 Lifecycle::WillResignActive,
1206 Lifecycle::WillEnterForeground,
1207 Lifecycle::DidEnterBackground,
1208 Lifecycle::DidReceiveMemoryWarning,
1209 Lifecycle::WillTerminate,
1210 Lifecycle::DidExit,
1211 ];
1212
1213 /// True for phases every backend delivers (launch, activation, termination). The remaining
1214 /// phases (`WillEnterForeground`, `DidEnterBackground`, `DidReceiveMemoryWarning`) are mobile
1215 /// concepts and are only delivered by the mobile backends. `const` so it composes into a
1216 /// backend's `const fn lifecycle_supported` and thus into compile-time guards.
1217 #[must_use]
1218 pub const fn is_universal(self) -> bool {
1219 matches!(
1220 self,
1221 Lifecycle::WillLaunch
1222 | Lifecycle::DidLaunch
1223 | Lifecycle::DidBecomeActive
1224 | Lifecycle::WillResignActive
1225 | Lifecycle::WillTerminate
1226 | Lifecycle::DidExit
1227 )
1228 }
1229
1230 /// A stable, human-readable name (for logs/warnings).
1231 #[must_use]
1232 pub const fn name(self) -> &'static str {
1233 match self {
1234 Lifecycle::WillLaunch => "WillLaunch",
1235 Lifecycle::DidLaunch => "DidLaunch",
1236 Lifecycle::DidBecomeActive => "DidBecomeActive",
1237 Lifecycle::WillResignActive => "WillResignActive",
1238 Lifecycle::WillEnterForeground => "WillEnterForeground",
1239 Lifecycle::DidEnterBackground => "DidEnterBackground",
1240 Lifecycle::DidReceiveMemoryWarning => "DidReceiveMemoryWarning",
1241 Lifecycle::WillTerminate => "WillTerminate",
1242 Lifecycle::DidExit => "DidExit",
1243 }
1244 }
1245}
1246
1247/// The phase of a drag gesture (docs/shapes.md).
1248#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1249pub enum DragPhase {
1250 Began,
1251 Changed,
1252 Ended,
1253}
1254
1255/// A gesture a node wants delivered. Backends attach the matching native recognizer when day-core
1256/// calls [`Toolkit::enable_gesture`]; the default is no gesture (recognizers cost, so opt-in).
1257#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1258pub enum GestureKind {
1259 Tap,
1260 LongPress,
1261 Drag,
1262 /// The pointer moving over the node without pressing (docs/canvas.md "Interaction"), and
1263 /// leaving it. Delivered only where a pointer exists: every desktop, an iPad with a trackpad
1264 /// or pencil, an Android device with a mouse or stylus. A touch-only device reports none,
1265 /// which is the right answer, not a gap, so anything reachable by hover must also be
1266 /// reachable by a tap.
1267 Hover,
1268 /// Pinch/magnify (docs/shapes.md): trackpad magnification, two-finger touch pinch.
1269 Pinch,
1270 /// Rotation (docs/canvas.md "Zoom and pan"): trackpad rotate, two-finger touch twist.
1271 Rotate,
1272 /// Viewport pan (docs/shapes.md): trackpad two-finger scroll, two-finger touch pan.
1273 /// Distinct from [`GestureKind::Drag`], the primary pointer's press-drag.
1274 Pan,
1275}
1276
1277// ---------------------------------------------------------------------------
1278// Menus (app menu bar + context menus). The model is a toolkit-neutral tree; each backend renders
1279// it with its native affordance (NSMenu / GMenu+GtkPopoverMenu / QMenu / UIMenu / Android
1280// PopupMenu / XAML MenuFlyout) and its own conventions, so day imposes no menu manager of its own.
1281// ---------------------------------------------------------------------------
1282
1283/// A keyboard shortcut for a menu item. `primary` is the platform's command modifier (⌘ on Apple,
1284/// Ctrl on GTK/Qt/XAML) so one declaration reads correctly everywhere. `key` is a single character
1285/// (`"s"`, `"."`) or a named key (`"Return"`, `"Delete"`, `"Left"`, `"F1"`).
1286#[derive(Clone, Debug, PartialEq, Eq, Default)]
1287pub struct Shortcut {
1288 pub key: String,
1289 /// ⌘ (Apple) / Ctrl (elsewhere). The conventional command modifier.
1290 pub primary: bool,
1291 pub shift: bool,
1292 /// ⌥ / Alt.
1293 pub alt: bool,
1294 /// Literal Control (⌃ on Apple). Rare; prefer `primary` for the command modifier.
1295 pub control: bool,
1296}
1297
1298impl Shortcut {
1299 /// `primary`+`key` (⌘S / Ctrl+S), the common case: `Shortcut::primary("s").shift()`.
1300 pub fn primary(key: impl Into<String>) -> Shortcut {
1301 Shortcut {
1302 key: key.into(),
1303 primary: true,
1304 ..Default::default()
1305 }
1306 }
1307 /// `key` with no modifiers (e.g. `F1`, plain `Delete`).
1308 pub fn plain(key: impl Into<String>) -> Shortcut {
1309 Shortcut {
1310 key: key.into(),
1311 ..Default::default()
1312 }
1313 }
1314 #[must_use]
1315 pub fn shift(mut self) -> Shortcut {
1316 self.shift = true;
1317 self
1318 }
1319 #[must_use]
1320 pub fn alt(mut self) -> Shortcut {
1321 self.alt = true;
1322 self
1323 }
1324 #[must_use]
1325 pub fn control(mut self) -> Shortcut {
1326 self.control = true;
1327 self
1328 }
1329}
1330
1331/// A standard/system command. The backend supplies the native item, a selector on AppKit/UIKit
1332/// (`cut:`/`copy:`/`paste:`…) or a stock action on GTK/Qt/XAML, so it targets the focused
1333/// control, gets the platform's default label + shortcut, and enables/disables itself
1334/// automatically. This is how default items (Edit ▸ Cut/Copy/Paste, the app's Quit/About) are
1335/// accommodated without the app re-implementing them.
1336#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1337pub enum MenuRole {
1338 Cut,
1339 Copy,
1340 Paste,
1341 SelectAll,
1342 Undo,
1343 Redo,
1344 Delete,
1345 /// The app's About command (docs/settings.md). With an About registered through
1346 /// `day::register_about` the item lowers to that dispatch action (a Day-rendered About
1347 /// window, or the toolkit's own About dialog where one exists); without one AppKit shows
1348 /// its stock Info.plist panel and the other desktops show the label alone.
1349 About,
1350 Quit,
1351 Preferences,
1352 Minimize,
1353 CloseWindow,
1354 Fullscreen,
1355 /// File ▸ New Window (docs/windows.md): opens another window through the builder the
1356 /// app registered with `day::register_new_window`. No platform has a native selector
1357 /// for it, so the item lowers to the registered dispatch action (disabled when none).
1358 NewWindow,
1359 /// Check for Updates… (docs/settings.md): placed directly under About in the macOS App
1360 /// menu (the Sparkle convention) and in Help elsewhere. Lowers to the action an updater
1361 /// registered with `day::register_check_for_updates`; absent from the bar when none did.
1362 CheckForUpdates,
1363}
1364
1365/// The keyboard modifiers held at an interaction, queryable ambiently
1366/// ([`Toolkit::modifiers`]): `primary` is the platform's command key (⌘ on Apple platforms,
1367/// Ctrl elsewhere, the same convention [`Shortcut::primary`] uses). Touch-only backends
1368/// answer all-false.
1369#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1370pub struct Modifiers {
1371 pub shift: bool,
1372 pub primary: bool,
1373 pub alt: bool,
1374}
1375
1376/// A standard edit command a platform route delivered ([`Event::Edit`]).
1377#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1378pub enum EditOp {
1379 Cut,
1380 Copy,
1381 Paste,
1382 SelectAll,
1383}
1384
1385/// What the app's edit bridge can currently do, mirrored into the toolkit
1386/// ([`Toolkit::set_edit_state`]) so native menu validation enables the stock items.
1387/// `can_paste` is the app's half ("a paste handler is installed"); the toolkit combines it
1388/// with its own clipboard-has-text check where one exists.
1389#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1390pub struct EditState {
1391 pub can_cut: bool,
1392 pub can_copy: bool,
1393 pub can_paste: bool,
1394 pub can_select_all: bool,
1395}
1396
1397/// The undo stack's face, as a native front mirrors it ([`Toolkit::set_undo_state`]): what is
1398/// possible and what the menu titles should say. Labels arrive already localized: a toolkit
1399/// cannot invent translated text, the same rule as every other label in this file.
1400#[derive(Clone, Debug, PartialEq, Default)]
1401pub struct UndoState {
1402 pub can_undo: bool,
1403 pub can_redo: bool,
1404 /// The next undo unit's display label ("Rename"), empty when nothing is undoable. Fronts
1405 /// interpolate it into the platform's own title form ("Undo Rename").
1406 pub undo_label: String,
1407 pub redo_label: String,
1408}
1409
1410/// One entry in a menu (recursive: a `Submenu` nests).
1411#[derive(Clone, Debug, PartialEq)]
1412pub enum MenuItem {
1413 /// A command. `action` (nonzero) dispatches [`Event::MenuAction`] to the app; a `role`-only item
1414 /// uses the native standard command instead (action 0). `label`/`shortcut` override the role's
1415 /// defaults. `icon` is the platform's own glyph beside the title where menus carry one (macOS,
1416 /// Windows, GNOME, KDE, Android); a backend whose menus are text-only ignores it.
1417 ///
1418 /// The `id`/`action` split is [`ToolbarItem`]'s: `id` names the item and `action` is what it
1419 /// runs. They are separate because a label cannot serve as a name (it is localized, and an
1420 /// item that shows its own state changes it), so anything addressing an item from outside
1421 /// (dayscript's `menu: { id: … }`) needs something that does not move.
1422 Action {
1423 /// The app's own name for this item, where it gave one. Stable across locales and across
1424 /// a change of `checked`, and unique within the menu it is installed in.
1425 id: Option<String>,
1426 /// The item's command, as a dispatch id from the same registry [`Event::MenuAction`] uses
1427 /// (0 = no command), so a toolbar button and its menu twin can share one closure.
1428 action: u64,
1429 label: String,
1430 shortcut: Option<Shortcut>,
1431 enabled: bool,
1432 /// On/off state where the item stands for a setting or one of several choices, drawn with
1433 /// the platform's own check mark. `None` is a plain command and reserves no mark; `Some`
1434 /// makes the item checkable and says which way it currently sits.
1435 ///
1436 /// The item still runs its `action` when chosen; a backend never flips this on its own.
1437 /// The app owns the state, and re-installing the menu (`app_menu`, which re-lowers on change) is what moves
1438 /// the mark, so what the menu shows can never disagree with what the app thinks.
1439 checked: Option<bool>,
1440 role: Option<MenuRole>,
1441 icon: Option<Icon>,
1442 },
1443 /// A nested submenu. At the top level of an app menu a `role` claims one of the platform's
1444 /// standard menu-bar slots: the backend then uses this menu instead of its stock one, and
1445 /// places it where the platform expects that menu to sit.
1446 Submenu {
1447 label: String,
1448 items: Vec<MenuItem>,
1449 role: Option<MenuBarRole>,
1450 },
1451 /// A visual separator.
1452 Separator,
1453}
1454
1455/// A standard menu-bar slot (macOS's File/Edit/View/Window/Help, and their counterparts
1456/// elsewhere). A backend that has a house style for the menu bar fills every slot an app did
1457/// not claim with its own stock menu, so an app never has to restate the platform's furniture,
1458/// and can still replace any of it by tagging its own submenu with the matching role.
1459#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1460#[non_exhaustive]
1461pub enum MenuBarRole {
1462 File,
1463 Edit,
1464 View,
1465 /// KDE/Plasma's Settings menu (`Configure <App>`, Configure Shortcuts). No counterpart on
1466 /// macOS, where preferences live in the app menu, or on GNOME/Windows.
1467 Settings,
1468 /// macOS's Window menu. Windows and Linux desktops do not have one.
1469 Window,
1470 Help,
1471}
1472
1473// ---------------------------------------------------------------------------
1474// Window toolbars (docs/toolbars.md)
1475// ---------------------------------------------------------------------------
1476
1477/// A standard icon, named by what it means rather than by how it looks, so each backend can
1478/// draw the platform's own glyph for it: an SF Symbol on macOS, a freedesktop icon name on
1479/// GTK and Qt, a Fluent glyph on Windows. This is the only way an icon looks native on every
1480/// desktop at once; a bundled PNG cannot, because it is one artist's take on all four.
1481///
1482/// The set is kept small: the commands that recur across toolbars. Anything
1483/// app-specific is an [`Icon::Image`].
1484#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1485#[non_exhaustive]
1486pub enum Symbol {
1487 Add,
1488 Remove,
1489 Delete,
1490 Edit,
1491 New,
1492 Open,
1493 Save,
1494 Print,
1495 Refresh,
1496 Search,
1497 Share,
1498 Settings,
1499 Info,
1500 Star,
1501 Bookmark,
1502 Back,
1503 Forward,
1504 Up,
1505 Down,
1506 Home,
1507 /// Show/hide the sidebar, the leading item of most desktop toolbars.
1508 Sidebar,
1509 Filter,
1510 Sort,
1511 /// An overflow affordance (macOS `ellipsis`, Android's vertical `more_vert`, GNOME's hamburger,
1512 /// Fluent `More`).
1513 More,
1514 Play,
1515 Pause,
1516 Stop,
1517 /// A photo capture: a screenshot command, a camera control.
1518 Camera,
1519 /// Source code.
1520 Code,
1521 /// Light appearance (a sun). The three below are the vocabulary of a theme chooser, which
1522 /// every platform draws with the same three ideas.
1523 Light,
1524 /// Dark appearance (a moon).
1525 Dark,
1526 /// Follow the system: the half-filled circle every platform uses for "automatic".
1527 Auto,
1528 ZoomIn,
1529 ZoomOut,
1530 /// Back to actual size: the 100% zoom command between [`Symbol::ZoomIn`] and
1531 /// [`Symbol::ZoomOut`].
1532 ZoomReset,
1533 Undo,
1534 Redo,
1535 Copy,
1536 Cut,
1537 Paste,
1538 Mail,
1539 Folder,
1540 Document,
1541 Check,
1542 Close,
1543 Warning,
1544 /// A rectangle: the shape vocabulary a drawing surface needs (docs/shapes.md), and the
1545 /// glyphs every drawing, diagram and annotation tool puts in the same place.
1546 Rectangle,
1547 /// An ellipse.
1548 Oval,
1549 /// An outlined circle: the read/unread vocabulary (a read row, its dot removed), and the
1550 /// generic ring glyph.
1551 Circle,
1552 /// A filled circle: the unread dot itself.
1553 CircleFilled,
1554 /// A straight line segment.
1555 Line,
1556 /// Combine the selection into a group: the drawing-tool command (two stacked squares).
1557 Group,
1558 /// Dissolve a group back into its members (two separated squares).
1559 Ungroup,
1560 /// Text: a line of type as a drawing element (the drawing-tool "T").
1561 Text,
1562 /// The device's own position: a map's "show my location" button (Apple's arrow, the
1563 /// crosshair elsewhere).
1564 Location,
1565 /// The open tabs or windows: a browser's tab switcher (two overlapping squares).
1566 Tabs,
1567 /// A book: a library of bookmarks or saved reading (Safari's bookmarks button).
1568 Book,
1569 /// Past activity: a history list (a clock with a turning arrow).
1570 History,
1571}
1572
1573/// The SF Symbol each standard symbol draws as. The system's own glyphs match the user's
1574/// device: weight, optical size, accent color and all. Shared by both Apple backends
1575/// (toolbars on macOS, menus on both).
1576///
1577/// The match is exhaustive so that a new [`Symbol`] must name its glyph here rather than
1578/// silently drawing nothing on Apple. A name this OS release does not know still resolves to
1579/// no image, and the item falls back to its label.
1580#[must_use]
1581pub fn sf_symbol_name(s: Symbol) -> &'static str {
1582 match s {
1583 Symbol::Add => "plus",
1584 Symbol::Remove => "minus",
1585 Symbol::Delete => "trash",
1586 Symbol::Edit => "pencil",
1587 Symbol::New => "square.and.pencil",
1588 Symbol::Open | Symbol::Folder => "folder",
1589 Symbol::Save => "square.and.arrow.down",
1590 Symbol::Print => "printer",
1591 Symbol::Refresh => "arrow.clockwise",
1592 Symbol::Search => "magnifyingglass",
1593 Symbol::Share => "square.and.arrow.up",
1594 Symbol::Settings => "gearshape",
1595 Symbol::Info => "info.circle",
1596 Symbol::Star => "star",
1597 Symbol::Bookmark => "bookmark",
1598 Symbol::Back => "chevron.backward",
1599 Symbol::Forward => "chevron.forward",
1600 Symbol::Up => "chevron.up",
1601 Symbol::Down => "chevron.down",
1602 Symbol::Home => "house",
1603 Symbol::Sidebar => "sidebar.leading",
1604 Symbol::Filter => "line.3.horizontal.decrease",
1605 Symbol::Sort => "arrow.up.arrow.down",
1606 Symbol::More => "ellipsis",
1607 Symbol::Play => "play.fill",
1608 Symbol::Pause => "pause.fill",
1609 Symbol::Stop => "stop.fill",
1610 Symbol::Camera => "camera",
1611 Symbol::Code => "chevron.left.forwardslash.chevron.right",
1612 Symbol::Light => "sun.max",
1613 Symbol::Dark => "moon",
1614 Symbol::Auto => "circle.lefthalf.filled",
1615 Symbol::ZoomIn => "plus.magnifyingglass",
1616 Symbol::ZoomReset => "1.magnifyingglass",
1617 Symbol::ZoomOut => "minus.magnifyingglass",
1618 Symbol::Undo => "arrow.uturn.backward",
1619 Symbol::Redo => "arrow.uturn.forward",
1620 Symbol::Copy => "doc.on.doc",
1621 Symbol::Cut => "scissors",
1622 Symbol::Paste => "doc.on.clipboard",
1623 Symbol::Mail => "envelope",
1624 Symbol::Document => "doc",
1625 Symbol::Check => "checkmark",
1626 Symbol::Close => "xmark",
1627 Symbol::Warning => "exclamationmark.triangle",
1628 Symbol::Rectangle => "rectangle",
1629 Symbol::Oval => "oval",
1630 Symbol::Circle => "circle",
1631 Symbol::CircleFilled => "circle.fill",
1632 Symbol::Line => "line.diagonal",
1633 Symbol::Group | Symbol::Tabs => "square.on.square",
1634 Symbol::Ungroup => "square.on.square.dashed",
1635 Symbol::Text => "textformat",
1636 Symbol::Location => "location",
1637 Symbol::Book => "book",
1638 Symbol::History => "clock.arrow.circlepath",
1639 }
1640}
1641
1642/// A button or toolbar item's picture: a standard [`Symbol`] (drawn with the platform's own icon set) or
1643/// a bundled image from `resource/images` for something only this app has.
1644#[derive(Clone, Debug, PartialEq)]
1645pub enum Icon {
1646 Symbol(Symbol),
1647 /// A bundled image name, resolved the same way [`ImageName`] is elsewhere.
1648 Image(String),
1649}
1650
1651/// What a toolbar item is. The variants are the vocabulary every desktop toolbar shares; each
1652/// backend realizes one with its native control, never with a drawn imitation.
1653#[derive(Clone, Debug, PartialEq)]
1654pub enum ToolbarItemKind {
1655 /// A push button running the item's `action`.
1656 Button,
1657 /// A two-state button. `on` seeds it; the user flipping it emits
1658 /// [`ToolbarValue::On`], and the app's own writes arrive as [`ToolbarPatch::On`].
1659 Toggle { on: bool },
1660 /// A button that drops a menu: the same [`MenuItem`] model the menu bar uses, so a
1661 /// toolbar menu and its menu-bar twin are one list of commands.
1662 Menu { items: Vec<MenuItem> },
1663 /// A search field. Edits emit [`ToolbarValue::Text`]; the app's own writes arrive as
1664 /// [`ToolbarPatch::Text`].
1665 ///
1666 /// Day creates this item itself, from a `.searchable()` surface whose placement resolved to
1667 /// the toolbar (docs/search.md); apps declare search on the surface, never here.
1668 Search {
1669 text: String,
1670 placeholder: String,
1671 /// Completions for the current text, drawn by the field's own completion affordance
1672 /// where it has one (`AutoSuggestBox`, `QCompleter`, `<datalist>`). Empty = none.
1673 suggestions: Vec<String>,
1674 },
1675 /// A row of mutually exclusive choices drawn as one control: the native segmented control
1676 /// (`NSSegmentedControl`, a linked GTK/Qt button box, a XAML toggle strip, `.day-segmented`
1677 /// on the web).
1678 ///
1679 /// This is what a set of related toolbar toggles should be when exactly one of them is on at
1680 /// a time: three separate toggles say "three independent switches" to the eye and to a screen
1681 /// reader, and leave the app to keep them exclusive. Choosing a segment emits
1682 /// [`ToolbarValue::Selected`]; the app's own writes arrive as [`ToolbarPatch::Selected`].
1683 Segmented {
1684 /// One entry per segment. A segment with an icon draws it in place of its title where
1685 /// the platform does that, and keeps the title as its accessible name.
1686 segments: Vec<ToolbarSegment>,
1687 selected: usize,
1688 },
1689 /// Static text, for a status or a caption.
1690 Label,
1691 /// A divider between neighbors in the same placement bucket, where the platform draws one
1692 /// (macOS toolbars have no separator, so AppKit renders it as a fixed space,
1693 /// docs/toolbars.md). Grouping is all it does: alignment is [`ToolbarPlacement`]'s job.
1694 Separator,
1695}
1696
1697/// One choice inside a [`ToolbarItemKind::Segmented`] control.
1698#[derive(Clone, Debug, PartialEq)]
1699pub struct ToolbarSegment {
1700 /// The segment's name: its label where the platform shows text, its accessible name always.
1701 pub title: String,
1702 pub icon: Option<Icon>,
1703}
1704
1705/// The reserved id of the sidebar affordance a `nav(Sidebar)` supplies for itself
1706/// (docs/toolbars.md). Backends with a system item for the job (AppKit's
1707/// `NSToolbarToggleSidebarItem`) recognize it by this id and draw theirs instead; dayscript
1708/// recognizes it to drive the toolkit's own duty rather than an app closure.
1709pub const SIDEBAR_TOGGLE_ID: &str = "day::sidebar_toggle";
1710
1711/// The reserved id of a `.searchable()` surface's field (docs/search.md): the `ToolbarItem` a
1712/// desktop bar draws for it, and the name dayscript's `toolbar:` step drives it by wherever the
1713/// platform put it — on the bar, or inline on the navigation surface where the bar holds no
1714/// field, in which case day-core resolves the id to that host instead.
1715pub const SEARCH_ITEM_ID: &str = "day::search";
1716
1717/// One item in a window's toolbar (docs/toolbars.md).
1718#[derive(Clone, Debug, PartialEq)]
1719pub struct ToolbarItem {
1720 /// Stable identity: the native item identifier, the dayscript target, and the key a
1721 /// [`ToolbarPatch`] addresses. Unique within a toolbar.
1722 pub id: String,
1723 pub kind: ToolbarItemKind,
1724 /// The item's name. Shown beside or below the icon where the platform does that, and used
1725 /// verbatim in the overflow and customization menus, so it is never optional, even on a
1726 /// toolbar that only shows icons. It is also the item's accessible name.
1727 pub label: String,
1728 /// Hover help. Defaults to `label` where the platform expects a tooltip and none is given.
1729 pub tooltip: Option<String>,
1730 pub icon: Option<Icon>,
1731 pub enabled: bool,
1732 /// The item's command, as a dispatch id from the same registry [`Event::MenuAction`] uses
1733 /// (0 = no command), so a toolbar button and its menu twin can share one closure.
1734 pub action: u64,
1735 /// This item's role on the chrome carrying it (docs/toolbars.md). It never names a surface:
1736 /// Which chrome an item rides is decided by where the app declared it, so this says only
1737 /// where on that chrome it belongs.
1738 pub placement: ToolbarPlacement,
1739 /// Whether the item draws its title, its icon, or both, where the platform can do more than
1740 /// one. An item folded into an overflow menu shows its title whatever this asks for; a menu
1741 /// row with no words is not a menu row.
1742 pub label_style: LabelStyle,
1743 /// Draw this item in the platform's emphasized style (a tinted/filled bar button, a
1744 /// prominent `NSToolbarItem`). For the one action a chrome is really offering.
1745 pub prominent: bool,
1746 /// Which column of a multi-pane window this item came from (docs/toolbars.md), set by Day
1747 /// from the piece that declared it, never by an app.
1748 ///
1749 /// A desktop toolbar spans every column at once, and a three-pane app expects each column's
1750 /// commands to sit over that column: the sidebar's against the first divider, the list's over
1751 /// the list, the rest over the detail. That is what Mail, Notes and Finder do, and it is only
1752 /// expressible because the declaration site already said which pane the command belongs to.
1753 /// Backends that draw one undivided bar ignore it.
1754 pub column: ToolbarColumn,
1755}
1756
1757/// Which pane of a window's navigation a toolbar item was declared in (docs/toolbars.md).
1758#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1759pub enum ToolbarColumn {
1760 /// The window itself, over no particular column. Draws with the detail's items, which is
1761 /// where a command that acts on the whole window belongs when the panes are side by side.
1762 #[default]
1763 Window,
1764 /// The sidebar / master column.
1765 Sidebar,
1766 /// The content-list column between the sidebar and the detail.
1767 List,
1768 /// The detail column.
1769 Detail,
1770}
1771
1772/// Where an item sits on the chrome that carries it (docs/toolbars.md).
1773///
1774/// A placement is a role, never a surface. Which toolbar, navigation bar or column an item
1775/// rides follows from the piece that declared it, so an app never spells that out twice.
1776#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1777pub enum ToolbarPlacement {
1778 /// The natural spot on this chrome: after the leading group on a desktop toolbar, the
1779 /// trailing item group on a navigation bar, an `IF_ROOM` menu action on Android.
1780 #[default]
1781 Automatic,
1782 /// The leading edge: a pane toggle, a control that reveals what is to its left.
1783 Navigation,
1784 /// Centered: a title accessory, a transport, a status readout.
1785 Principal,
1786 /// Trailing, and the last thing a crowded chrome gives up.
1787 Primary,
1788 /// Trailing, and the first thing a crowded chrome folds into its overflow.
1789 Secondary,
1790 /// A bottom bar where the platform has one (iOS `toolbarItems`, an Android bottom app bar);
1791 /// [`ToolbarPlacement::Secondary`] everywhere else.
1792 Bottom,
1793}
1794
1795/// Which halves of an item's label a platform draws, where it can draw more than one.
1796#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1797pub enum LabelStyle {
1798 /// The platform's own convention for this chrome.
1799 #[default]
1800 Automatic,
1801 /// The icon alone (the title stays as the accessible name and the tooltip).
1802 IconOnly,
1803 /// The title alone, even where an icon was given.
1804 TitleOnly,
1805 /// Both, where the chrome has room for both.
1806 TitleAndIcon,
1807}
1808
1809/// A value a toolbar item produced.
1810#[derive(Clone, Debug, PartialEq)]
1811pub enum ToolbarValue {
1812 /// A search item's full new text.
1813 Text(String),
1814 /// A search item's text, submitted with the field's Return or Search key. Sent after the
1815 /// last [`ToolbarValue::Text`]; it changes no state of its own.
1816 Submit(String),
1817 /// A toggle item's new state.
1818 On(bool),
1819 /// A segmented item's newly chosen index.
1820 Selected(usize),
1821}
1822
1823/// A targeted update to one live toolbar item: the path that keeps a bound signal in sync
1824/// without rebuilding the bar (which would drop the search field's focus mid-keystroke).
1825#[derive(Clone, Debug, PartialEq)]
1826pub enum ToolbarPatch {
1827 /// Focus a search control and select its text without changing its value.
1828 Focus { item: String },
1829 /// Replace a search item's text.
1830 Text { item: String, text: String },
1831 /// Set a toggle item's state.
1832 On { item: String, on: bool },
1833 /// Select a segmented item's index.
1834 Selected { item: String, index: usize },
1835 /// Enable or disable any item.
1836 Enabled { item: String, on: bool },
1837 /// Replace a search item's completions (docs/search.md). Targeted rather than a rebuild,
1838 /// because these change on every keystroke and rebuilding the bar would take the field's
1839 /// focus with it.
1840 Suggestions { item: String, list: Vec<String> },
1841 /// Replace an item's words (a language change): its label, which an icon-only item still
1842 /// carries for the overflow menu and assistive technology, and its tooltip. The item keeps
1843 /// its native widget, its action and its place.
1844 Label {
1845 item: String,
1846 label: String,
1847 tooltip: Option<String>,
1848 },
1849 /// Replace a search item's empty-state prompt (docs/search.md), in the live field.
1850 Placeholder { item: String, text: String },
1851}
1852
1853impl ToolbarPatch {
1854 /// The id of the item this patch addresses.
1855 #[must_use]
1856 pub fn item(&self) -> &str {
1857 match self {
1858 ToolbarPatch::Focus { item }
1859 | ToolbarPatch::Text { item, .. }
1860 | ToolbarPatch::On { item, .. }
1861 | ToolbarPatch::Selected { item, .. }
1862 | ToolbarPatch::Enabled { item, .. }
1863 | ToolbarPatch::Suggestions { item, .. }
1864 | ToolbarPatch::Label { item, .. }
1865 | ToolbarPatch::Placeholder { item, .. } => item,
1866 }
1867 }
1868
1869 /// Write this patch's value into `items`, the model of a bar. `false` when no item there
1870 /// takes it (an unknown id, or a kind the value does not apply to).
1871 pub fn apply_to(&self, items: &mut [ToolbarItem]) -> bool {
1872 let Some(it) = items.iter_mut().find(|i| i.id == self.item()) else {
1873 return false;
1874 };
1875 match (self, &mut it.kind) {
1876 (ToolbarPatch::Focus { .. }, ToolbarItemKind::Search { .. }) => (),
1877 (ToolbarPatch::Text { text, .. }, ToolbarItemKind::Search { text: t, .. }) => {
1878 t.clone_from(text);
1879 }
1880 (
1881 ToolbarPatch::Suggestions { list, .. },
1882 ToolbarItemKind::Search { suggestions, .. },
1883 ) => suggestions.clone_from(list),
1884 (ToolbarPatch::On { on, .. }, ToolbarItemKind::Toggle { on: o }) => *o = *on,
1885 (
1886 ToolbarPatch::Selected { index, .. },
1887 ToolbarItemKind::Segmented { segments, selected },
1888 ) if *index < segments.len() => *selected = *index,
1889 (ToolbarPatch::Enabled { on, .. }, _) => it.enabled = *on,
1890 (ToolbarPatch::Label { label, tooltip, .. }, _) => {
1891 it.label = label.clone();
1892 it.tooltip = tooltip.clone();
1893 }
1894 (
1895 ToolbarPatch::Placeholder { text, .. },
1896 ToolbarItemKind::Search { placeholder, .. },
1897 ) => placeholder.clone_from(text),
1898 _ => return false,
1899 }
1900 true
1901 }
1902}
1903
1904/// One step of an edit to a window's toolbar (docs/toolbars.md).
1905///
1906/// Day hands a backend its bar as edits, never as a whole new model to rebuild, for the same
1907/// reason the view tree arrives as `insert`/`remove` rather than as a fresh tree: an item the
1908/// edit does not name keeps its native widget, and with it the keyboard focus, the caret, a
1909/// menu that is open. A value (search text, a toggle) never travels as an edit; it is a
1910/// [`ToolbarPatch`] on the live item.
1911///
1912/// An edit lists every [`ToolbarOp::Remove`] first, then every [`ToolbarOp::Insert`] in
1913/// ascending `index`, so applying them in order to the bar's current items (a
1914/// [`ToolbarMirror`] does exactly that) produces the new bar. Items keep their relative order
1915/// across an edit: an item that moves arrives as a remove and an insert, like one whose
1916/// presentation changed.
1917#[derive(Clone, Debug, PartialEq)]
1918pub enum ToolbarOp {
1919 /// The item with this id leaves the bar.
1920 Remove { id: String },
1921 /// `item` joins the bar at `index`, its position once this edit is complete.
1922 Insert { index: usize, item: ToolbarItem },
1923}
1924
1925impl ToolbarOp {
1926 /// Apply this op to `items`, a bar's model in order.
1927 pub fn apply_to(&self, items: &mut Vec<ToolbarItem>) {
1928 match self {
1929 ToolbarOp::Remove { id } => items.retain(|i| i.id != *id),
1930 ToolbarOp::Insert { index, item } => {
1931 items.insert((*index).min(items.len()), item.clone());
1932 }
1933 }
1934 }
1935}
1936
1937/// A backend's copy of one window's toolbar, kept in step with the [`ToolbarOp`]s and
1938/// [`ToolbarPatch`]es that reach it, and the one place a backend works out where a new item
1939/// goes (docs/toolbars.md).
1940///
1941/// Every backend lays its bar out as a few groups (the leading and trailing ends of a header
1942/// bar, the columns of a split window, the primary and overflow commands of a command bar) and
1943/// keeps model order within each. So an inserted item always goes right after
1944/// [`ToolbarMirror::prev_where`] its own group, or first in the group when that is `None`, and
1945/// nothing already on the bar moves.
1946#[derive(Clone, Debug, Default)]
1947pub struct ToolbarMirror {
1948 items: Vec<ToolbarItem>,
1949}
1950
1951impl ToolbarMirror {
1952 /// The bar's items, in model order.
1953 #[must_use]
1954 pub fn items(&self) -> &[ToolbarItem] {
1955 &self.items
1956 }
1957
1958 #[must_use]
1959 pub fn is_empty(&self) -> bool {
1960 self.items.is_empty()
1961 }
1962
1963 /// The item with this id.
1964 #[must_use]
1965 pub fn get(&self, id: &str) -> Option<&ToolbarItem> {
1966 self.items.iter().find(|i| i.id == id)
1967 }
1968
1969 /// The item dispatching `action`: how a backend whose native bar reports only an action
1970 /// id (a menu tap) finds what was tapped.
1971 #[must_use]
1972 pub fn by_action(&self, action: u64) -> Option<&ToolbarItem> {
1973 self.items
1974 .iter()
1975 .find(|i| i.action == action && action != 0)
1976 }
1977
1978 /// Take the item with `id` out, returning it.
1979 pub fn remove(&mut self, id: &str) -> Option<ToolbarItem> {
1980 let at = self.items.iter().position(|i| i.id == id)?;
1981 Some(self.items.remove(at))
1982 }
1983
1984 /// Put `item` at `index` (clamped to the end).
1985 pub fn insert(&mut self, index: usize, item: ToolbarItem) {
1986 let at = index.min(self.items.len());
1987 self.items.insert(at, item);
1988 }
1989
1990 /// Apply one op to the model: what a backend that repaints its whole native bar from the
1991 /// model (a menu of actions) does with each.
1992 pub fn apply(&mut self, op: &ToolbarOp) {
1993 op.apply_to(&mut self.items);
1994 }
1995
1996 /// Write a value patch into the model. `false` when no item takes it.
1997 pub fn patch(&mut self, patch: &ToolbarPatch) -> bool {
1998 patch.apply_to(&mut self.items)
1999 }
2000
2001 /// The nearest item before `index` that `same_group` accepts: the native item a new one at
2002 /// `index` goes right after, in that group. `None` = it goes first in the group.
2003 pub fn prev_where(
2004 &self,
2005 index: usize,
2006 same_group: impl Fn(&ToolbarItem) -> bool,
2007 ) -> Option<&ToolbarItem> {
2008 self.items[..index.min(self.items.len())]
2009 .iter()
2010 .rev()
2011 .find(|i| same_group(i))
2012 }
2013}
2014
2015#[derive(Clone, Debug, PartialEq)]
2016pub struct KeyEvent {
2017 /// The key's name, in the web `KeyboardEvent.key` vocabulary every platform can map onto:
2018 /// the four arrows ("`ArrowLeft`", "`ArrowRight`", "`ArrowUp`", "`ArrowDown`") and the ten digits
2019 /// ("0" through "9", from the main row or the numeric keypad) everywhere, plus
2020 /// "Delete" and "Backspace" on backends with no menu bar ([`Cap::AppMenu`] unsupported),
2021 /// where no accelerator can own those keys. A focused piece claims every key the route
2022 /// carries, so offering them on a menu-bar platform would let a canvas swallow the Delete
2023 /// its own Edit menu was about to act on (docs/menus.md). The two delete keys keep the
2024 /// names the platform gives the physical keys (a Mac's ⌫ is "Backspace" and its ⌦ is
2025 /// "Delete"), so a handler that means "remove this" takes both. A digit arrives only while
2026 /// neither [`KeyEvent::PRIMARY`] nor [`KeyEvent::ALT`] (nor a Mac's Control) is held: ⌘1
2027 /// and Ctrl+1 are accelerators, and a canvas claiming them would starve the menu. Most
2028 /// backends name the digit the keypress types, so a layout whose number row needs Shift for
2029 /// digits reports "1" with [`KeyEvent::SHIFT`] set; XAML and ArkUI read the physical key.
2030 /// Backends emit `Event::Key` only while no text widget has focus; a field's own editing
2031 /// keys never surface here. The one exception is a single-line text field with a key
2032 /// handler ([`keys::handled`] for its node): it hands "`ArrowUp`", "`ArrowDown`" and "Escape",
2033 /// pressed with no modifier, to that handler instead of acting on them itself, so an
2034 /// address bar can walk a suggestion list (docs/textfield.md "Keys").
2035 ///
2036 /// A piece that declared `Decorate::keyboard()` takes the full route instead: every key
2037 /// the platform delivers while it is focused. A key that types nothing is named by its
2038 /// web name ([`KeyEvent::NAMED`]: "Enter", "Tab", "Escape", "Backspace", "Delete", "Home",
2039 /// "End", "`PageUp`", "`PageDown`", "Insert", the arrows and "F1" through "F12"); a key that
2040 /// types is named by its unmodified character ("a", "A" under Shift, "8", "ü" on a layout
2041 /// that has one), and what it typed rides in [`KeyEvent::text`]. Under Control or Alt the
2042 /// name stays that character ("c" with [`KeyEvent::CONTROL`] set, never the control code
2043 /// it would type). Text an input method commits (a dead-key accent, a Japanese phrase,
2044 /// the soft keyboard's word) arrives with the text alone and an empty name: no single
2045 /// key is behind it. Only the platform's command chords stay out: ⌘ on Apple platforms
2046 /// and the browser's own shortcuts belong to the menu and the browser, so a terminal's
2047 /// ⌘C still copies. [`KeyEvent::typed`] is the question a text consumer asks.
2048 pub key: String,
2049 /// A [`KeyEvent::SHIFT`]/[`KeyEvent::PRIMARY`]/[`KeyEvent::ALT`]/[`KeyEvent::CONTROL`]
2050 /// mask.
2051 pub modifiers: u8,
2052 /// The text this press committed, on the full route: what the key typed ("a", "A", "é"
2053 /// after a dead key, the whole string an input method committed at once), or `None` for
2054 /// a key that typed nothing (a named key, a Control or Alt chord, a composition still in
2055 /// progress). Separate from [`KeyEvent::key`] so that a committed "Enter" is text and the
2056 /// Enter key is a key, whatever the input method sends. Always `None` on the short route.
2057 pub text: Option<String>,
2058}
2059
2060impl KeyEvent {
2061 pub const SHIFT: u8 = 1;
2062 /// The platform's command key: ⌘ on Apple platforms, Ctrl elsewhere (the
2063 /// [`Shortcut::primary`] convention).
2064 pub const PRIMARY: u8 = 2;
2065 pub const ALT: u8 = 4;
2066 /// The Control key itself, wherever it sits: on Apple platforms it is a different key from
2067 /// [`KeyEvent::PRIMARY`] (⌘), elsewhere the same one, so a Ctrl+C on Linux sets both.
2068 /// Carried on the full route only (`Decorate::keyboard`).
2069 pub const CONTROL: u8 = 8;
2070
2071 /// The ten digit key names, indexed by value.
2072 pub const DIGITS: [&'static str; 10] = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"];
2073
2074 /// Every name the full route gives a key that types nothing (the web `KeyboardEvent.key`
2075 /// vocabulary). A key outside this list is named by the text it types.
2076 pub const NAMED: [&'static str; 26] = [
2077 "ArrowLeft",
2078 "ArrowRight",
2079 "ArrowUp",
2080 "ArrowDown",
2081 "Enter",
2082 "Tab",
2083 "Escape",
2084 "Backspace",
2085 "Delete",
2086 "Home",
2087 "End",
2088 "PageUp",
2089 "PageDown",
2090 "Insert",
2091 "F1",
2092 "F2",
2093 "F3",
2094 "F4",
2095 "F5",
2096 "F6",
2097 "F7",
2098 "F8",
2099 "F9",
2100 "F10",
2101 "F11",
2102 "F12",
2103 ];
2104
2105 /// The text this press typed ([`KeyEvent::text`]), or `None` for a key that typed nothing.
2106 #[must_use]
2107 pub fn typed(&self) -> Option<&str> {
2108 self.text.as_deref()
2109 }
2110
2111 /// A key that types nothing (one of [`KeyEvent::NAMED`], or a chord's character under
2112 /// Control or Alt), on either route.
2113 pub fn named(key: impl Into<String>, modifiers: u8) -> KeyEvent {
2114 KeyEvent {
2115 key: key.into(),
2116 modifiers,
2117 text: None,
2118 }
2119 }
2120
2121 /// Text a press committed on the full route. The key is named by the text when the text
2122 /// is one character (the press typed it), and left empty for a longer commit, which no
2123 /// single key is behind.
2124 pub fn typed_text(text: impl Into<String>, modifiers: u8) -> KeyEvent {
2125 let text = text.into();
2126 let mut chars = text.chars();
2127 let key = match (chars.next(), chars.next()) {
2128 (Some(_), None) => text.clone(),
2129 _ => String::new(),
2130 };
2131 KeyEvent {
2132 key,
2133 modifiers,
2134 text: Some(text),
2135 }
2136 }
2137
2138 /// Text a press committed on the full route, named by the key that produced it
2139 /// (`key`, in the vocabulary above) when the backend knows it.
2140 pub fn typed_by(key: impl Into<String>, text: impl Into<String>, modifiers: u8) -> KeyEvent {
2141 KeyEvent {
2142 key: key.into(),
2143 modifiers,
2144 text: Some(text.into()),
2145 }
2146 }
2147
2148 /// The web name for the function key `F<n>`, `1..=12`.
2149 #[must_use]
2150 pub fn function_name(n: u8) -> Option<&'static str> {
2151 match n {
2152 1..=12 => Some(Self::NAMED[13 + n as usize]),
2153 _ => None,
2154 }
2155 }
2156
2157 /// The key name for a typed character when it is one of the ten digits: what a backend
2158 /// reports for a keypress that types `0`–`9`.
2159 #[must_use]
2160 pub fn digit_name(c: char) -> Option<&'static str> {
2161 c.to_digit(10).map(|d| Self::DIGITS[d as usize])
2162 }
2163
2164 /// The value of a digit key, or `None` for every other key.
2165 #[must_use]
2166 pub fn digit(&self) -> Option<u8> {
2167 match self.key.as_bytes() {
2168 [d @ b'0'..=b'9'] => Some(d - b'0'),
2169 _ => None,
2170 }
2171 }
2172
2173 #[must_use]
2174 pub fn shift(&self) -> bool {
2175 self.modifiers & Self::SHIFT != 0
2176 }
2177 #[must_use]
2178 pub fn primary(&self) -> bool {
2179 self.modifiers & Self::PRIMARY != 0
2180 }
2181 #[must_use]
2182 pub fn alt(&self) -> bool {
2183 self.modifiers & Self::ALT != 0
2184 }
2185 #[must_use]
2186 pub fn control(&self) -> bool {
2187 self.modifiers & Self::CONTROL != 0
2188 }
2189}
2190
2191#[cfg(test)]
2192mod key_event_tests {
2193 use super::KeyEvent;
2194
2195 #[test]
2196 fn digit_names_read_back_as_values() {
2197 for (value, c) in ('0'..='9').enumerate() {
2198 let name = KeyEvent::digit_name(c).expect("an ASCII digit names itself");
2199 let key = KeyEvent::named(name, 0);
2200 assert_eq!(key.digit(), Some(value as u8));
2201 }
2202 // Only the ASCII digits: a letter, an Arabic-Indic three, and a named key are not.
2203 assert_eq!(KeyEvent::digit_name('a'), None);
2204 assert_eq!(KeyEvent::digit_name('٣'), None);
2205 let arrow = KeyEvent::named("ArrowUp", 0);
2206 assert_eq!(arrow.digit(), None);
2207 }
2208
2209 #[test]
2210 fn typed_text_is_told_from_named_keys() {
2211 let a = KeyEvent::typed_text("a", 0);
2212 assert_eq!((a.key.as_str(), a.typed()), ("a", Some("a")));
2213 let space = KeyEvent::typed_text(" ", 0);
2214 assert_eq!((space.key.as_str(), space.typed()), (" ", Some(" ")));
2215 assert_eq!(KeyEvent::typed_text("7", 0).digit(), Some(7));
2216 // A longer commit has no key behind it.
2217 let phrase = KeyEvent::typed_text("こんにちは", 0);
2218 assert_eq!(
2219 (phrase.key.as_str(), phrase.typed()),
2220 ("", Some("こんにちは"))
2221 );
2222 // Text that spells a key name is still text, and the key is still a key.
2223 for name in KeyEvent::NAMED {
2224 assert_eq!(
2225 KeyEvent::named(name, 0).typed(),
2226 None,
2227 "{name} types nothing"
2228 );
2229 assert_eq!(KeyEvent::typed_text(name, 0).typed(), Some(name));
2230 }
2231 let accent = KeyEvent::typed_by("e", "é", 0);
2232 assert_eq!((accent.key.as_str(), accent.typed()), ("e", Some("é")));
2233 assert_eq!(KeyEvent::function_name(1), Some("F1"));
2234 assert_eq!(KeyEvent::function_name(12), Some("F12"));
2235 assert_eq!(KeyEvent::function_name(13), None);
2236 let chord = KeyEvent::named("c", KeyEvent::CONTROL | KeyEvent::SHIFT);
2237 assert!(chord.control() && chord.shift() && !chord.primary());
2238 assert_eq!(chord.typed(), None);
2239 }
2240
2241 #[test]
2242 fn a_declaration_claims_nothing_without_a_handler() {
2243 let node = super::NodeId(0xdead_0001);
2244 super::keys::mark_text(node);
2245 assert!(!super::keys::text(node), "no handler, no claim");
2246 super::keys::mark(node);
2247 assert!(super::keys::text(node) && super::keys::handled(node));
2248 super::keys::forget(node);
2249 assert!(!super::keys::text(node) && !super::keys::handled(node));
2250 }
2251}
2252
2253#[derive(Clone, Copy, Debug, PartialEq)]
2254pub struct PointerEvent {
2255 pub position: Point,
2256 pub down: bool,
2257}
2258
2259/// The event sink: enqueue-only. It may be invoked re-entrantly from inside any Toolkit method;
2260/// day-core drains queued events at safe points, each as a fresh batch (§3.3).
2261pub type EventSink = Box<dyn Fn(NodeId, Event)>;
2262
2263/// The synchronous row-pull closures for recycling lists (docs/list.md, §10). day-core injects one
2264/// per `LIST` host via [`Toolkit::attach_list`]; a recycling backend stores it and calls it from
2265/// its native data-source (on the UI thread, outside any day-core borrow). Each closure re-enters
2266/// day-core, so, unlike [`EventSink`], these run to completion synchronously (`bind_row` even
2267/// flushes + lays out the row before returning, so the host can measure the cell immediately).
2268#[derive(Clone)]
2269pub struct ListSource {
2270 /// Report the first actually visible row (exclude overscan). Enqueue-only; optional,
2271 /// so hosts without a viewport binding incur no app event work.
2272 pub first_visible: Option<std::rc::Rc<dyn Fn(usize)>>,
2273 /// Current row count.
2274 pub len: std::rc::Rc<dyn Fn() -> usize>,
2275 /// Present on a sectioned list (`ListProps::sections`, docs/list.md "Sections"): whether
2276 /// row `index` is a section header. Every row index the host sees counts headers, and
2277 /// day-core translates to the app's items. A header row is not selectable, activatable or
2278 /// swipeable; the host draws it in its platform's group-header style, sized to its content
2279 /// even in a `Uniform` list, and floats it where the platform does (macOS group rows,
2280 /// UIKit plain-table section headers).
2281 pub is_header: Option<std::rc::Rc<dyn Fn(usize) -> bool>>,
2282 /// Stable identity token for the row at `index` (for native diffing / animation).
2283 pub token_at: std::rc::Rc<dyn Fn(usize) -> u64>,
2284 /// Build (first use of this cell) or rebind (recycled cell) row `index` into the native cell.
2285 pub bind_row: std::rc::Rc<dyn Fn(usize, RawHandle)>,
2286 /// A host that emulates `Cap::ListSections` binds the header it pins over the top of the
2287 /// list with this instead of `bind_row` (docs/list.md "Sections"): the same build or
2288 /// rebind, but the copy carries no element ids, so a dayscript or accessibility lookup of a
2289 /// header finds the header row in the list, never its pinned copy.
2290 pub bind_pinned: std::rc::Rc<dyn Fn(usize, RawHandle)>,
2291 /// The native cell left the viewport; Day may drop per-cell bookkeeping (optional).
2292 pub recycle: std::rc::Rc<dyn Fn(RawHandle)>,
2293 /// The native host is done with this cell for good (a `GtkListItemFactory::teardown`, a
2294 /// `UITableViewCell` deallocating): Day disposes the row it built there, its scope, nodes
2295 /// and element ids. Without this a host that discards cells, as every pool does on a far
2296 /// jump, leaves one dead row behind in day-core per discarded cell. Safe inside a day-core
2297 /// borrow (the work is held for the borrow's end) and for a cell Day never saw.
2298 pub release: std::rc::Rc<dyn Fn(RawHandle)>,
2299 /// Re-lay the row bound to this cell at `width`, called from the cell's own native layout
2300 /// pass, the hook [`TreeSource::layout_cell`] already gives trees. day-core lays a row at the
2301 /// `LIST`'s width first, which is right wherever the cell is the row itself; a backend
2302 /// whose native row wraps the cell in chrome (`GtkListView`'s themed `row` node pads it)
2303 /// corrects it here, so the row fits the cell the platform gave it instead of holding the
2304 /// whole list wider than its frame. Skips quietly when called inside a day-core borrow (a
2305 /// snapshot pass).
2306 pub layout_cell: std::rc::Rc<dyn Fn(RawHandle, f64)>,
2307 /// The height day-core last laid the row bound to this cell at: the row's own height,
2308 /// padding included, as `RowHeight` resolves it. A backend whose cell measures itself
2309 /// (`GtkListView`'s `DayCell`) reports it as the cell's height, so a padded row keeps its
2310 /// bottom padding rather than the height of its last child's frame. `0.0` before the row's
2311 /// first layout, or inside a day-core borrow.
2312 pub cell_height: std::rc::Rc<dyn Fn(RawHandle) -> f64>,
2313 /// Drag-to-reorder closures, present when `ListProps::reorderable` (docs/list.md). `None` on
2314 /// non-reorderable lists; backends must not enable their drag machinery without it.
2315 pub reorder: Option<ListReorder>,
2316 /// Swipe-to-delete closures, present when `ListProps::deletable` (docs/list.md). `None` on
2317 /// non-deletable lists; backends must not offer their delete affordance without it.
2318 pub delete: Option<ListDelete>,
2319 /// Swipe-actions closures, present when `ListProps::swipe_actions` (docs/list.md). `None` on
2320 /// lists that declared none; backends must not install their row-action machinery
2321 /// without it.
2322 pub swipe: Option<ListSwipe>,
2323}
2324
2325/// The synchronous drag-to-reorder half of [`ListSource`] (docs/list.md). Both closures follow
2326/// `bind_row`'s discipline: called on the UI thread from inside native drag callbacks, outside
2327/// any day-core borrow, and they run to completion synchronously.
2328#[derive(Clone)]
2329pub struct ListReorder {
2330 /// May row `from` drop at row `to`? Called from the native validate/hover hook so the
2331 /// affordance (gap, insertion mark, forbidden cursor) reflects the app's answer live.
2332 /// Returns the accepted target index: `to` itself to allow, another index to retarget the
2333 /// drop, or `-1` to deny.
2334 pub can_move: std::rc::Rc<dyn Fn(usize, usize) -> i64>,
2335 /// Commit: row `from` dropped at row `to` (an index `can_move` accepted). Rotates Day's row
2336 /// snapshot before returning (so `len`/`token_at`/`bind_row` reflect the new order while the
2337 /// native move animates) and defers the app's own callback to the next event drain.
2338 pub move_row: std::rc::Rc<dyn Fn(usize, usize)>,
2339}
2340
2341/// The synchronous swipe-to-delete half of [`ListSource`] (docs/list.md), shaped exactly like
2342/// [`ListReorder`]: both closures are called on the UI thread from inside native swipe callbacks,
2343/// outside any day-core borrow, and run to completion synchronously.
2344///
2345/// Each platform spells the gesture its own way (a trailing swipe action on iOS, an
2346/// `ItemTouchHelper` swipe on Android, a `ListItem` swipe action on ArkUI), but all three ask the
2347/// same two questions, so this struct is one pair of closures rather than three shapes.
2348#[derive(Clone)]
2349pub struct ListDelete {
2350 /// May row `index` be deleted? Called before the affordance is offered, so a row the app
2351 /// protects shows no delete action at all rather than one that fails on use.
2352 pub can_delete: std::rc::Rc<dyn Fn(usize) -> bool>,
2353 /// Commit: delete row `index`. Removes it from Day's row snapshot before returning (so
2354 /// `len`/`token_at`/`bind_row` already reflect the shorter list while the native row-removal
2355 /// animates) and defers the app's own callback to the next event drain.
2356 pub delete_row: std::rc::Rc<dyn Fn(usize)>,
2357}
2358
2359/// Which edge of a row a swipe action rides (docs/list.md). Semantic, not geometric:
2360/// `Leading` follows the reading direction (the left edge in LTR, the right in RTL), the
2361/// mapping every platform's swipe API already makes.
2362#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2363pub enum SwipeEdge {
2364 Leading,
2365 Trailing,
2366}
2367
2368/// One offered swipe action (docs/list.md): pure data. The pieces layer keeps the handlers;
2369/// the backend answers a tap through [`ListSwipe::perform`] by index into the offer.
2370#[derive(Clone, Debug, PartialEq)]
2371pub struct ListSwipeAction {
2372 /// The word on the button, already localized (a toolkit cannot translate).
2373 pub label: String,
2374 /// Destructive styling: the platform's red.
2375 pub destructive: bool,
2376 /// Explicit button color; `None` = the platform's default for the style.
2377 pub tint: Option<Color>,
2378 /// A glyph for the button where the platform draws one: above the label on macOS, in
2379 /// place of it on iOS (docs/list.md).
2380 pub symbol: Option<Symbol>,
2381}
2382
2383/// The synchronous swipe-actions half of [`ListSource`] (docs/list.md), the generalized
2384/// sibling of [`ListDelete`]: reveal-as-you-swipe buttons on either row edge. The offer is
2385/// pulled per row at gesture time, so labels follow row state ("Mark Read" on an unread row,
2386/// "Mark Unread" on a read one); the commit defers to the event drain like every closure here.
2387#[derive(Clone)]
2388pub struct ListSwipe {
2389 /// The offer: the actions for row `index` on `edge`, called inside the platform's swipe
2390 /// callback, so keep it pure. Empty = no affordance for that row and edge. The first action
2391 /// is the full-swipe action where the platform activates one at the far edge.
2392 pub actions_at: std::rc::Rc<dyn Fn(usize, SwipeEdge) -> Vec<ListSwipeAction>>,
2393 /// The commit: the user activated action `action` (an index into the offer) on row
2394 /// `index`, `edge`. Unlike a delete this never reshapes the row snapshot; the app's
2395 /// handler is deferred to the next event drain, never run inside the native callback.
2396 pub perform: std::rc::Rc<dyn Fn(usize, SwipeEdge, usize)>,
2397}
2398
2399/// The synchronous row-pull closures for hierarchical trees (docs/tree.md): [`ListSource`]'s
2400/// shape, addressed by token instead of row index, because expanding a row renumbers every
2401/// index below it while tokens hold still. day-core injects one per `TREE` host via
2402/// [`Toolkit::attach_tree`]; the backend answers its native data-source from it. The same
2403/// synchronous discipline as [`ListSource`]: UI thread, outside any day-core borrow;
2404/// `bind_row` flushes and lays the row out before returning.
2405#[derive(Clone)]
2406pub struct TreeSource {
2407 /// How many children `parent` has (`None` = the root level).
2408 pub children_len: std::rc::Rc<dyn Fn(Option<u64>) -> usize>,
2409 /// The i-th child of `parent`: the stable token every backend keys its rows by.
2410 pub child_token: std::rc::Rc<dyn Fn(Option<u64>, usize) -> u64>,
2411 /// Whether this token can hold children at all: what draws (or omits) the disclosure.
2412 pub expandable: std::rc::Rc<dyn Fn(u64) -> bool>,
2413 /// Non-selectable section heading, separate from a navigation destination.
2414 pub section_header: std::rc::Rc<dyn Fn(u64) -> bool>,
2415 /// Current desired expansion, including restoration before the first native reload.
2416 pub expanded: std::rc::Rc<dyn Fn(u64) -> bool>,
2417 /// Build (first use of this cell) or rebind (recycled cell) the row for `token` into the
2418 /// native cell.
2419 pub bind_row: std::rc::Rc<dyn Fn(u64, RawHandle)>,
2420 /// The native cell left the viewport; Day may drop per-cell bookkeeping (optional).
2421 pub recycle: std::rc::Rc<dyn Fn(RawHandle)>,
2422 /// Re-lay the row bound to this cell at `width`, called from the cell's own native
2423 /// layout pass. Trees need this where lists don't: indentation makes every cell's
2424 /// content width per-row, so the host-width layout `bind_row` did is only a first
2425 /// approximation. Skips quietly when called inside a day-core borrow (a snapshot pass).
2426 pub layout_cell: std::rc::Rc<dyn Fn(RawHandle, f64)>,
2427 /// Native bounds for controls whose group headers have a different height from leaves.
2428 /// Overrides the initial row-height estimate and preserves the native height on rebind.
2429 pub layout_cell_size: std::rc::Rc<dyn Fn(RawHandle, Size)>,
2430 /// The height day-core last laid this cell's row at (see [`ListSource::cell_height`]).
2431 pub cell_height: std::rc::Rc<dyn Fn(RawHandle) -> f64>,
2432 /// The row's type-ahead string (docs/tree.md): what native type-select matches against.
2433 pub type_select_text: std::rc::Rc<dyn Fn(u64) -> String>,
2434 /// The row's context menu, built when the menu is summoned (docs/menus.md "Dynamic context
2435 /// menus"), called on the UI thread from the platform's own menu callback, outside any
2436 /// day-core borrow, like every closure here. `None` = rows carry no menu; an empty
2437 /// result suppresses the menu for that row.
2438 pub row_menu: Option<std::rc::Rc<dyn Fn(u64) -> Vec<MenuItem>>>,
2439 /// Drag-to-move closures, present when `TreeProps::movable` (docs/tree.md). `None` on
2440 /// immovable trees; backends must not enable their drag machinery without it.
2441 pub moves: Option<TreeMoves>,
2442}
2443
2444/// The synchronous drag half of [`TreeSource`] (docs/tree.md). Both closures follow
2445/// `bind_row`'s discipline: called on the UI thread from inside native drag callbacks.
2446#[derive(Clone)]
2447pub struct TreeMoves {
2448 /// The live verdict, consulted while the drag is over a target: may `token` land under
2449 /// `parent` at `index`? `index: None` means "dropped onto the parent" (append). Pure, since
2450 /// it runs inside the platform's drag-validate callback.
2451 #[allow(clippy::type_complexity)]
2452 pub can_move: std::rc::Rc<dyn Fn(u64, Option<u64>, Option<usize>) -> MoveVerdict>,
2453 /// Commit an accepted drop. Defers the app's `on_move` through the event queue
2454 /// ([`Event::TreeMove`]); the app's own data write drives the reload.
2455 #[allow(clippy::type_complexity)]
2456 pub move_node: std::rc::Rc<dyn Fn(u64, Option<u64>, Option<usize>)>,
2457}
2458
2459/// A summon-time context-menu provider (docs/menus.md): local-point in, menu out.
2460pub type ContextMenuFn = std::rc::Rc<dyn Fn(Point) -> Vec<MenuItem>>;
2461
2462/// Ask a menu button's provider for its menu at press time ([`Toolkit::set_button_menu`]), and
2463/// answer the items to show, or `None` to show nothing: an empty menu, or a provider that
2464/// removed its own button. The provider is app code; a signal it writes can rebuild the tree
2465/// synchronously and release the very button being pressed. `still_registered` asks the
2466/// toolkit's own registry, AFTER the provider has returned, whether the button is still the one
2467/// registered for this press; a toolkit holding a raw native handle must not touch it otherwise.
2468pub fn resolve_button_menu(
2469 provider: &ContextMenuFn,
2470 still_registered: impl FnOnce() -> bool,
2471) -> Option<Vec<MenuItem>> {
2472 let items = provider(Point::ZERO);
2473 if items.is_empty() || !still_registered() {
2474 return None;
2475 }
2476 Some(items)
2477}
2478
2479/// A tree move guard's verdict (docs/tree.md). No `Retarget` yet: the drop vocabulary is
2480/// already positional, so a guard that wants a different target denies and the user drops
2481/// where it is allowed.
2482#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2483pub enum MoveVerdict {
2484 Allow,
2485 Deny,
2486}
2487
2488/// One addressable widget within a composite native backing (docs/tree.md,
2489/// docs/tweaks.md), Qt's name for the concept (`QStyle::SubControl`). A `list`'s or
2490/// `tree`'s node handle is its scroller; `Subcontrol::Content` is the widget inside it.
2491/// Backends resolve an unknown subcontrol to `None`, never to the host.
2492#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
2493pub enum Subcontrol {
2494 /// The node's own handle: what every tweak accessor reached before subcontrols existed.
2495 Host,
2496 /// The content widget inside the scroller (`NSOutlineView`, `NSTableView`, …).
2497 Content,
2498 /// The header view, where the widget has one. Day's lists and trees ship headerless, so
2499 /// this answers `None` until a kind grows a header.
2500 Header,
2501}
2502
2503// ---------------------------------------------------------------------------
2504// Capabilities, animation, a11y
2505// ---------------------------------------------------------------------------
2506
2507/// What to show on the app's icon in the Dock, launcher, home screen, or taskbar (docs/badge.md).
2508///
2509/// Distinct from `NavItem::badge`, which annotates a sidebar row inside the window. This one
2510/// decorates the application itself and is drawn by the shell, not by Day.
2511///
2512/// What each payload needs is asked separately (`Cap::AppBadgeCount`, `AppBadgeText`,
2513/// `AppBadgeDot`) because the platforms differ in what they accept more than in whether they have
2514/// a badge at all: macOS takes arbitrary text, iOS and the web take a number, Android takes nothing.
2515#[derive(Clone, Debug, PartialEq, Eq, Default)]
2516pub enum AppBadge {
2517 /// Clear the badge.
2518 #[default]
2519 None,
2520 /// A count. Zero clears it, matching every platform's own convention.
2521 Count(u32),
2522 /// Short arbitrary text (`"99+"`, `"beta"`). Only macOS renders it; probe `Cap::AppBadgeText`.
2523 Text(String),
2524 /// An indicator with no value.
2525 Dot,
2526}
2527
2528/// How wide a window is, in coarse buckets (docs/size-classes.md).
2529///
2530/// The breakpoints are Android's window size classes, in density-independent points, and they are
2531/// used verbatim on every backend rather than per-platform. One table means one answer: a 700pt
2532/// window is [`WidthClass::Medium`] on a Mac, in a browser, and on a tablet, so an app that lays
2533/// out from the class gets the same layout at the same size everywhere. Apple publishes only two
2534/// buckets (compact/regular); those map onto this table rather than replacing it, with
2535/// [`WidthClass::Compact`] the compact one and everything above it regular.
2536#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug, Default)]
2537pub enum WidthClass {
2538 /// `< 600dp`: a phone in portrait. One pane at a time.
2539 #[default]
2540 Compact,
2541 /// `600–839dp`: a tablet in portrait, a narrow desktop window.
2542 Medium,
2543 /// `840–1199dp`: a tablet in landscape, a typical desktop window.
2544 Expanded,
2545 /// `1200–1599dp`: a large desktop window.
2546 Large,
2547 /// `≥ 1600dp`: a maximized window on a big display.
2548 ExtraLarge,
2549}
2550
2551/// How tall a window is (docs/size-classes.md). Consulted far less than [`WidthClass`]: it is
2552/// what tells a phone in landscape (wide enough for two panes, too short for a tall list) that
2553/// it should not grow vertical chrome.
2554#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug, Default)]
2555pub enum HeightClass {
2556 /// `< 480dp`: a phone in landscape.
2557 #[default]
2558 Compact,
2559 /// `480–899dp`: a phone in portrait, a tablet in landscape.
2560 Medium,
2561 /// `≥ 900dp`: a tablet in portrait, most desktop windows.
2562 Expanded,
2563}
2564
2565/// A window's size class (docs/size-classes.md), reported by the backend and read by apps
2566/// through `day::size_class()`.
2567///
2568/// Per-window, not per-app: two windows of one process can sit in different classes at the same
2569/// time (a narrow and a wide window side by side, iPadOS Stage Manager, Android split-screen), and
2570/// an app that keyed off a single global would lay the second window out for the first one's size.
2571#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
2572pub struct SizeClass {
2573 pub width: WidthClass,
2574 pub height: HeightClass,
2575}
2576
2577impl SizeClass {
2578 /// The `Compact`/`Medium` width boundary in dp: the narrowest window where a second
2579 /// pane starts to fit. Backends that hand an adaptive container its pane widths derive
2580 /// them from this (Android's list + minimum-detail widths sum to it), so the platform's
2581 /// measure-time decision and this table agree by construction (docs/size-classes.md).
2582 pub const SPLIT_MIN_WIDTH: f64 = 600.0;
2583
2584 /// Bucket a window's size in points. The one place the breakpoint numbers appear.
2585 #[must_use]
2586 pub fn from_size(width: f64, height: f64) -> Self {
2587 SizeClass {
2588 width: match width {
2589 w if w >= 1600.0 => WidthClass::ExtraLarge,
2590 w if w >= 1200.0 => WidthClass::Large,
2591 w if w >= 840.0 => WidthClass::Expanded,
2592 w if w >= Self::SPLIT_MIN_WIDTH => WidthClass::Medium,
2593 _ => WidthClass::Compact,
2594 },
2595 height: match height {
2596 h if h >= 900.0 => HeightClass::Expanded,
2597 h if h >= 480.0 => HeightClass::Medium,
2598 _ => HeightClass::Compact,
2599 },
2600 }
2601 }
2602
2603 /// Whether a two-pane presentation fits. The rule behind an automatic
2604 /// [`props::NavPresentation`]: anything wider than compact gets both panes.
2605 #[must_use]
2606 pub fn prefers_split(self) -> bool {
2607 self.width > WidthClass::Compact
2608 }
2609}
2610
2611#[derive(Clone, Copy, PartialEq, Eq, Debug)]
2612pub enum Cap {
2613 /// Standard searchfield control.
2614 SearchField,
2615 /// Standard combobox control.
2616 ComboBox,
2617 /// Standard stepper control.
2618 Stepper,
2619 /// Standard datetime control.
2620 DateTimePicker,
2621 /// Standard colorpicker control.
2622 ColorPicker,
2623 /// Standard pullrefresh control.
2624 PullRefresh,
2625 /// Standard pager control.
2626 Pager,
2627 /// User-driven pull recognition, separate from a refresh indicator.
2628 PullRefreshGesture,
2629
2630 /// Native data-transfer source and destination callbacks.
2631 DragDrop,
2632 /// Transfers between independent native applications (inbound).
2633 DragExternalImport,
2634 /// Transfers to independent native applications, including arbitrary binary MIME data.
2635 DragExternalExport,
2636 /// Lossless ordered items and alternatives between Day applications.
2637 DragMultipleItems,
2638 /// Existing native file references, distinct from promised/generated files.
2639 DragFileReferences,
2640 /// Native result can wait for asynchronous data receipt.
2641 DragDeferredReceipt,
2642 /// Generated files supplied to a destination after dropping.
2643 DragFilePromises,
2644 /// External move acknowledgment safe for source deletion.
2645 DragExternalMove,
2646 ListRecycling,
2647 /// The toolkit fronts the app's undo stack with the platform's own undo system
2648 /// ([`Toolkit::set_undo_state`] + `Event::Undo`): `Native` where one exists
2649 /// (`NSUndoManager` on macOS/iOS, `QUndoStack`), `Unsupported` everywhere else, where
2650 /// Day's menu items and accelerators drive the stack directly and nothing platform-owned
2651 /// needs mirroring (docs/model.md).
2652 UndoBridge,
2653 /// The toolkit routes the platform's standard Cut/Copy/Paste to the app's edit bridge
2654 /// ([`Toolkit::set_edit_state`] + `Event::Edit`): the same menu items, shortcuts, and
2655 /// responder precedence the platform's text editing uses; a focused text widget keeps
2656 /// its own clipboard behavior, everything else reaches the app (docs/menus.md).
2657 /// `Native` where a system route exists (the responder chain, the browser's clipboard
2658 /// events), `Emulated` where Day's own menu items dispatch it, `Unsupported` elsewhere.
2659 EditBridge,
2660 /// The toolkit realizes `ListProps::reorderable` as drag-to-reorder rows: `Native` when the
2661 /// platform's own mechanism drives it (`NSTableView` drag/drop, `UITableView` drag delegates,
2662 /// `ItemTouchHelper`, …), `Emulated` for a pointer-tracked fake (web-dom). `Unsupported` ⇒ the
2663 /// list renders normally but rows cannot be dragged (docs/list.md).
2664 ListReorder,
2665 /// Sidebar destinations can be dragged to reorder (`NavBuilder::reorder_items`) and between
2666 /// sections (`NavBuilder::regroup_items`). `Native` when the toolkit's own sidebar drags them
2667 /// (`NavMenuProps::movable`, and across headers under `NavMenuProps::regroup`); `Emulated`
2668 /// when Day stands a reorderable list in for the sidebar. Independent of `ListReorder`: UIKit
2669 /// supports draggable content lists but retains its native navigation collection for
2670 /// sidebars.
2671 NavReorder,
2672 /// The toolkit realizes `ListProps::deletable` as the platform's delete gesture:
2673 /// `Native` where the platform ships one (UIKit's trailing swipe actions, Android's
2674 /// `ItemTouchHelper`, ArkUI's `ListItem.swipeAction`), `Unsupported` on the desktop toolkits,
2675 /// whose lists have no swipe idiom and where deletion belongs to a menu or a button
2676 /// (docs/list.md).
2677 ListDelete,
2678 /// The toolkit realizes `ListProps::swipe_actions` as edge swipe actions: buttons
2679 /// that reveal as the row tracks the swipe, with the far edge activating the first one
2680 /// (docs/list.md). `Native` where the platform ships the affordance: macos-appkit
2681 /// (`NSTableView` row actions, Mail's own machinery) and ios-uikit
2682 /// (`UISwipeActionsConfiguration`). `Unsupported` everywhere else: the affordance is
2683 /// absent, and the app's command lives in its explicit controls.
2684 ListSwipeActions,
2685 /// The toolkit realizes `ListProps::editing` as the platform's list editing mode: rows
2686 /// show their delete controls and reorder grips while the list is editing (docs/list.md).
2687 /// `Native` on ios-uikit (`UITableView` editing). `Unsupported` everywhere else, where a
2688 /// list has no separate editing mode: its rows already drag, swipe and open menus as they
2689 /// are, and the list renders as if `editing` were off.
2690 ListEditing,
2691 /// The toolkit realizes `kinds::LIST_ITEM` as its own list row content (docs/list.md "List
2692 /// items"): `Native` where the platform has a standard row it draws itself (UIKit's
2693 /// `UIListContentConfiguration`, a Material list item, AppKit's image-and-text table cell,
2694 /// a GTK row box), so the row takes the platform's fonts, icon size, spacing, secondary
2695 /// colors and check mark. `Unsupported` ⇒ the `list_item` piece composes the same content
2696 /// from plain pieces. Apps have no reason to probe this; the piece does.
2697 ListItem,
2698 /// The toolkit realizes `kinds::TREE` as a hierarchical tree view (docs/tree.md):
2699 /// `Native` where a platform tree widget hosts Day-built rows (`NSOutlineView`, the UIKit
2700 /// sidebar list, GtkListView+TreeListModel, WinUI `TreeView`, ArkTS `TreeView`), `Emulated`
2701 /// where Day flattens the tree onto its list machinery, `Unsupported` where neither
2702 /// exists yet. An app gates its tree UI on this answer rather than showing a placeholder.
2703 Tree,
2704 /// The toolkit realizes `TreeProps::movable` as drag-to-reparent/restack rows
2705 /// (docs/tree.md). A strictly smaller set than [`Cap::Tree`]: a backend can render a
2706 /// tree it cannot yet drag within.
2707 TreeMove,
2708 /// Native two-level section headers; general trees may still be composed.
2709 TreeSections,
2710 /// The toolkit answers [`Toolkit::first_baseline`], so rows can align text on its baseline
2711 /// rather than on the middle of its box (docs/baseline.md). `Native` where the platform
2712 /// reports the baseline itself (`NSView.firstBaselineOffsetFromTop`, `View.getBaseline`,
2713 /// `gtk_widget_measure`), `Emulated` where Day derives it from the widget's font metrics,
2714 /// `Unsupported` ⇒ baseline-aligned rows fall back to centering and look exactly as they do
2715 /// today.
2716 BaselineAlignment,
2717 /// The toolkit draws a label's [`TextRun`]s: bold, italic, color or a monospace face within
2718 /// one wrapping paragraph (docs/text-runs.md). `Unsupported` ⇒ the label renders its text
2719 /// uniformly, which reads correctly and loses only the emphasis.
2720 TextRuns,
2721 /// The toolkit makes a run carrying [`TextRun::link`] activatable, emitting
2722 /// [`Event::LinkActivated`]. A strictly smaller set than [`Cap::TextRuns`]: several toolkits
2723 /// draw a link run in link colors but have no way to hit-test it, and one (Android) can do
2724 /// links or selection but not both (docs/text-runs.md).
2725 TextLinks,
2726 Lottie,
2727 NativeSymbols,
2728 /// The toolkit can rasterize its window and hand back the pixels
2729 /// (`Toolkit::snapshot_window`): what the dayscript `screenshot` step captures in-process
2730 /// and what `day::window_image()` offers the app (docs/window-image.md). `Unsupported` where
2731 /// a backend cannot draw itself into a bitmap: web-dom, which would need a rasterizer
2732 /// shipped with it. Probe it before offering a "save a screenshot" affordance, rather than
2733 /// offering one that fails when pressed.
2734 Snapshot,
2735 /// The toolkit can present `nav()` as sidebar+detail split panes, a statement about the
2736 /// toolkit, not about the window it is currently drawing. Whether a given host is split right
2737 /// now follows from its [`SizeClass`]: the pieces layer resolves an automatic
2738 /// [`props::NavPresentation`] against both, and re-resolves on every class change. A backend
2739 /// with no split container answers `Unsupported` and stays stacked at every size.
2740 NavSplit,
2741 /// The toolkit can draw a navigation host's rows as its own chrome: a tab bar
2742 /// ([`props::NavPresentation::Tabs`]) and, where it has one, a rail
2743 /// ([`props::NavPresentation::Rail`]). Like [`Self::NavSplit`] this is a statement about the
2744 /// toolkit, not about the window it is drawing right now.
2745 ///
2746 /// This is what `NavStyle::Automatic` resolves against (docs/navigation.md): a backend
2747 /// answering `Unsupported` gets the sidebar resolver instead (`Split` ↔ `Stack`), which is
2748 /// what every backend did before adaptive navigation existed. So an unimplemented backend
2749 /// degrades to its previous behavior rather than to a hole.
2750 ///
2751 /// `Emulated` means the rows are composed from other widgets rather than drawn by a native
2752 /// tab container (Qt, web-dom). `Native` means a real one (`UITabBarController`, a Material
2753 /// `NavigationBarView`, `NavigationView`).
2754 NavTabs,
2755 /// A narrow window should become a tab bar here, a separate question from [`Self::NavTabs`],
2756 /// which only says the toolkit *can* draw one.
2757 ///
2758 /// The two differ on every desktop. macOS, GNOME, Qt and Windows can all draw a tab bar, and
2759 /// must, because an app is free to pin `NavStyle::Tabs`; but none of them grows one when
2760 /// its window is dragged narrow. A narrow Mail.app hides its sidebar and pushes; it does not
2761 /// sprout a bottom tab bar, and an app that did would look like a port. The phones and the web
2762 /// are the opposite: those are the surfaces whose window size ranges from a phone to a
2763 /// desktop, and a tab bar is what their users expect at the narrow end.
2764 ///
2765 /// So this is a statement about the platform's idiom, not about its widget set:
2766 ///
2767 /// - `Native`/`Emulated`: `NavStyle::Automatic` may resolve to
2768 /// [`props::NavPresentation::Tabs`] on a compact window (ios-uikit, android-material,
2769 /// harmony-arkui, web-dom).
2770 /// - `Unsupported`: it may not; a compact window collapses to
2771 /// [`props::NavPresentation::Stack`] instead, exactly as `NavStyle::Sidebar` has always
2772 /// done (macos-appkit, linux-gtk, linux-qt, windows-winui).
2773 ///
2774 /// [`props::NavPresentation::Rail`] is not gated by this. A narrow sidebar is an ordinary
2775 /// desktop shape (on Windows it is what `NavigationView` does at that width on its own), so
2776 /// the rail rung stays available everywhere `Cap::NavSplit` is.
2777 NavTabsAdaptive,
2778 /// How a navigation host's presentation follows the window (docs/size-classes.md). All three
2779 /// answers mean something different here, and the difference is who decides:
2780 ///
2781 /// - `Native`: **Day tells the toolkit.** The pieces layer resolves the presentation from
2782 /// the [`SizeClass`], re-resolves on every change, and sends
2783 /// [`props::NavPatch::Presentation`]; the toolkit rebuilds its chrome and re-homes the
2784 /// pages it already has. The desktops and web-dom.
2785 /// - `Emulated`: **the toolkit tells Day.** Its own adaptive container owns the decision
2786 /// (`UISplitViewController` collapsing as a Pro Max iPhone rotates, `SlidingPaneLayout`
2787 /// measuring whether both panes fit), so Day must not push a presentation into it: that
2788 /// would be a second decision racing the platform's own animation. The toolkit
2789 /// reports what it did with [`Event::NavPresentationChanged`] and Day reconciles.
2790 /// - `Unsupported`: nobody re-presents. The presentation is resolved once, from
2791 /// [`Cap::NavSplit`] alone, and the window's size never enters into it. A toolkit that
2792 /// cannot change presentation must not have it decided by something that can, or a window
2793 /// launched narrow would be stuck stacked with no way back.
2794 NavRepresent,
2795 /// The toolkit places a navigation host's content-list page ([`props::Pane::List`]) in its
2796 /// own pane between the sidebar and the detail, the Mail shape: mailboxes, message list,
2797 /// message (docs/navigation.md). The three answers differ on what happens when the host
2798 /// leaves the split:
2799 ///
2800 /// - `Native`: the pane exists at every presentation. A narrow window collapses the
2801 /// sidebar but keeps the list beside the detail, exactly as a narrow Mail.app does
2802 /// (macos-appkit: a `contentList` `NSSplitViewItem`).
2803 /// - `Emulated`: the pane exists while split and merges into the navigation stack when
2804 /// the host collapses (ios-uikit: `UISplitViewController` triple-column). The pieces
2805 /// layer then interposes the list between the sidebar root and the detail
2806 /// ([`props::NavPatch::ListInStack`]) and gates the detail push on the app's
2807 /// `detail_visible` binding.
2808 /// - `Unsupported`: the backend never sees [`props::Pane::List`] or
2809 /// [`props::NavProps::list_width`]; the nav piece composes the pane beside (split)
2810 /// or in place of (stacked) the destination content itself.
2811 NavContentList,
2812 /// The toolkit shows the current destination's title in a native header/bar, so a page
2813 /// needn't repeat it in its own content. `Native` on XAML (the `NavigationView` header),
2814 /// UIKit (`UINavigationBar`), Android (`MaterialToolbar`), and ArkUI (`NavDestination`
2815 /// title bars). The desktop custom back-headers (AppKit/Qt/web) show a title only in
2816 /// stack mode, so those backends stay `Unsupported` (docs/navigation.md).
2817 NavHeader,
2818 /// The toolkit applies a runtime appearance override (`set_appearance`): native widgets
2819 /// restyle in place and `dark_mode` answers the override. Probe before showing a theme
2820 /// picker; on `Unsupported` backends the call is ignored.
2821 Appearance,
2822 /// The toolkit renders an application menu bar (docs/menus.md), so `app_menu` is visible to
2823 /// the user, and `register_preferences` gets its automatic Settings… item.
2824 ///
2825 /// The question an app asks before deciding where a command lives. Settings is the usual
2826 /// case: on a platform with a menu bar it belongs in the App menu and putting it in the
2827 /// navigation as well is clutter; on one without, the menu is a no-op and a Settings row is
2828 /// the only way in. Distinct from `Cap::Toolbar`: web-dom draws a window toolbar and has no
2829 /// menu bar at all, so keying off the toolbar strands Settings there.
2830 AppMenu,
2831 /// The toolkit can present native alert/confirm/sheet/prompt modals (docs/dialogs.md).
2832 Dialogs,
2833 /// The toolkit can present native open/save file pickers (docs/files.md).
2834 FileDialogs,
2835 /// The toolkit can present a native folder chooser (`PresentSpec::OpenFolder`,
2836 /// docs/files.md). `Native` on the four desktop toolkits (AppKit, GTK, Qt, WinUI); the
2837 /// phone and web backends answer `Unsupported` and resolve the request as `Dismissed`, so
2838 /// an app hides its "Add Folder…" command where this is not `Native`.
2839 FolderDialog,
2840 /// The toolkit runs backend-executed animation for `AnimSpec` intents on
2841 /// `update`/`set_frame`/`set_opacity`/`set_transform` (§8.4). `Unsupported` ⇒ animated calls
2842 /// apply instantly (still correct, just not animated).
2843 Animation,
2844 /// The toolkit presents a `kinds::COVER` node as a native fullscreen modal surface
2845 /// (docs/cover.md). `Unsupported` ⇒ the `cover` piece's content never shows.
2846 Cover,
2847 /// The toolkit presents a `.sheet()` cover as a native modal sheet (AppKit's window sheet,
2848 /// UIKit's page sheet) over the page it covers (docs/cover.md "Modal sheet"). `Unsupported`
2849 /// ⇒ the `cover` piece composes the sheet itself: on a window wider than compact, a card
2850 /// centered over the dimmed page; on a compact one, the full window.
2851 CoverSheet,
2852 /// The toolkit can hide the system status bar while a `status_bar_hidden` subtree is
2853 /// mounted (`Toolkit::set_status_bar_hidden`, docs/cover.md). `Native` on the phone and
2854 /// tablet backends; desktop and web have no status bar, so a setting that offers to hide
2855 /// it should be offered only where this is not `Unsupported`.
2856 StatusBarHidden,
2857 /// The toolkit's `text_area` can be made read-only (`TextAreaProps::editable = false`).
2858 TextEditable,
2859 /// The toolkit's `text_area` selectability can be toggled (`TextAreaProps::selectable`).
2860 /// `Unsupported` where selection is always on (GTK); `Emulated` where the backend
2861 /// collapses native selections itself (XAML, ArkUI).
2862 TextSelectable,
2863 /// The toolkit's `text_area` has built-in spell-check/autocorrect (`TextAreaProps::spellcheck`).
2864 /// `Unsupported` where the toolkit ships none (GTK, Qt, ArkUI).
2865 TextSpellCheck,
2866 /// The toolkit can open additional native OS windows (`Toolkit::open_window`,
2867 /// docs/windows.md). `Native` on the desktop backends and on mobile backends whose
2868 /// platform has a real secondary-window surface (iPad scenes, Android document
2869 /// activities, OHOS multiton abilities). On `Unsupported` backends
2870 /// `day_core::open_window` still works; the content presents as a fullscreen cover in
2871 /// the primary window instead. Probe it to adapt chrome: an `Unsupported` tier has no
2872 /// native title bar or close button, so window content should carry its own close
2873 /// affordance.
2874 MultiWindow,
2875 /// The toolkit can put a count on the app icon (`Toolkit::set_app_badge`, docs/badge.md).
2876 /// `Emulated` where the call is made but the shell may ignore it: desktop Linux, where the
2877 /// Unity launcher protocol is honored by Plasma and Dash-to-Dock but not by stock GNOME.
2878 AppBadgeCount,
2879 /// The toolkit renders `AppBadge::Text` as written. macOS only: `NSDockTile.badgeLabel` is an
2880 /// arbitrary string, while every other platform's badge is a number or nothing.
2881 AppBadgeText,
2882 /// The toolkit can show a valueless indicator (`AppBadge::Dot`).
2883 AppBadgeDot,
2884 /// The toolkit gives a window chrome that persists across pages
2885 /// (`Toolkit::edit_toolbar`, docs/toolbars.md): `Native` on the desktop backends and the
2886 /// phones, `Emulated` on web-dom, `Unsupported` where the only chrome belongs to a page.
2887 ///
2888 /// It no longer decides whether a command can be shown at all: a toolbar item declared on a
2889 /// piece rides that piece's own chrome everywhere. Probe it only for a layout decision that
2890 /// turns on a persistent bar existing.
2891 Toolbar,
2892 /// The window toolbar can hold a search field (docs/search.md): `Native` on the desktop
2893 /// backends, `Emulated` on web-dom. `Unsupported` on the phones, whose bar is a row of actions
2894 /// (an Android app-bar menu, iOS bar buttons, ArkUI title-bar menus): their field goes on the
2895 /// navigation surface instead, so `SearchPlacement::Toolbar` resolves to `Inline` there.
2896 ToolbarSearch,
2897 /// The toolkit realizes `kinds::INSPECTOR` as its own trailing-pane container
2898 /// (docs/inspector.md): an `NSSplitView` inspector pane, a `GtkPaned` with the panel as
2899 /// its end child, a `QDockWidget`, a XAML `SplitView` right pane. `Unsupported` ⇒ the
2900 /// `inspector` piece composes the pane from plain containers instead (same panel, same
2901 /// signal, no native divider), so an unimplemented backend degrades to a drawn pane, not
2902 /// to a hole. Apps normally have no reason to probe this; the piece does.
2903 Inspector,
2904 /// The toolkit realizes `kinds::SPLIT` as its own splitter (docs/split.md): an
2905 /// `NSSplitView`, a `GtkPaned`, a `QSplitter`, each side by side or stacked and with the
2906 /// divider the user drags. `Unsupported` ⇒ the `split` piece composes the two panes and
2907 /// draws and drags the divider itself (the web, the mobile toolkits, XAML), so the piece
2908 /// behaves the same everywhere and only the divider's look is the toolkit's. Apps have no
2909 /// reason to probe this; the piece does.
2910 Split,
2911 /// The toolkit shapes the pointer over a node from the `.cursor()` decorator
2912 /// ([`Toolkit::set_cursor`], docs/cursor.md). `Native` where the platform draws the requested
2913 /// shape from its own set (AppKit, GTK, the DOM, Android's `PointerIcon`), `Emulated` where
2914 /// some shapes map to a nearest neighbor (Qt, XAML) or the platform draws pointer effects
2915 /// rather than shapes (iPadOS), `Unsupported` where nothing changes: a touch-only toolkit,
2916 /// or one whose pointer API Day does not reach yet. Apps ask before offering an affordance
2917 /// that only a cursor reveals, such as a resize handle with no other visual.
2918 Cursor,
2919 /// The toolkit can enumerate the platform's font families with the faces each ships
2920 /// ([`Toolkit::font_families`], docs/fonts.md). `Native` where an OS font database answers
2921 /// (`NSFontManager`, `UIFont`, Pango, `QFontDatabase`, Android's `fonts.xml`,
2922 /// `OH_Drawing_FontMgr`, DirectWrite); `Emulated` where the list is composed rather than
2923 /// read: web-dom answers the CSS generic families plus the bundled `document.fonts`, since
2924 /// a browser exposes no local font list without a permission prompt; `Unsupported` means
2925 /// the list is empty and an app should offer only the default face. Measurement
2926 /// ([`Toolkit::measure_text`]) has no probe: a `None` answer degrades to
2927 /// [`TextMetrics::approximate`]. Probe this before offering a font menu, not before
2928 /// drawing; a [`CanvasFont`] draws everywhere.
2929 FontList,
2930 /// The toolkit reads the user's reduce-motion setting ([`Toolkit::reduce_motion`],
2931 /// docs/accessibility.md) and reports when it changes. `Native` where the platform has the
2932 /// switch and Day reaches it; `Unsupported` where Day reaches none (the app then animates as
2933 /// it would with the setting off, and `DAY_REDUCE_MOTION=1` still forces it on).
2934 ReduceMotion,
2935 /// The toolkit can speak a sentence through the screen reader without moving its focus
2936 /// ([`Toolkit::announce`], docs/accessibility.md): "Saved", "3 results", "Upload failed".
2937 /// `Native` where the platform has an announcement request (`NSAccessibility`'s
2938 /// announcement notification, `UIAccessibility`'s, Android's accessibility event, GTK
2939 /// 4.14's `gtk_accessible_announce`, a WinUI notification event); `Emulated` on the web,
2940 /// where an ARIA live region carries it; `Unsupported` where Day reaches no announcement
2941 /// API yet. An app with a visible status label needs no announcement: screen readers read
2942 /// what changes on screen only when told to, so this is for the change the user cannot
2943 /// otherwise learn about.
2944 Announce,
2945 /// The toolkit can turn encoded image bytes into a native image
2946 /// ([`Toolkit::decode_image`], docs/images.md): what `image(bytes)`, a pasted screenshot and
2947 /// a canvas image all rest on. `Native` wherever the platform decoder takes a buffer;
2948 /// `Unsupported` means only staged asset names draw, so an app should not offer "open an
2949 /// image" at all. Every backend that decodes also answers [`Toolkit::image_info`], so pixel
2950 /// size needs no probe of its own.
2951 ImageDecode,
2952 /// The toolkit can encode a decoded image back to bytes ([`Toolkit::encode_image`]).
2953 /// Which formats it encodes is [`Toolkit::encode_formats`], the same shape as
2954 /// [`Cap::FontList`]/[`Toolkit::font_families`], because "can encode" and "can encode WebP"
2955 /// are different questions and only the second one needs a list.
2956 ImageEncode,
2957 /// The toolkit can read an image's metadata beyond its pixels: EXIF orientation, DPI,
2958 /// capture time ([`Toolkit::image_properties`]). `Native` where a platform metadata reader
2959 /// is already linked (WinRT's `BitmapPropertiesView`, Android's `ExifInterface`);
2960 /// `Unsupported` where reading it would mean shipping a parser or a new framework, which is
2961 /// most places. An app that wants orientation must handle `None`.
2962 ImageProperties,
2963 /// The toolkit can replay a canvas drawing into an offscreen bitmap
2964 /// ([`Toolkit::render_bitmap`], docs/canvas.md "Exporting"): what `Drawing::to_bitmap` and
2965 /// `Drawing::to_png` rest on. `Native` where the toolkit's own canvas painter can target an
2966 /// image surface (a `CGBitmapContext`, a cairo image surface, a `QImage`, an android
2967 /// `Bitmap`, an `OH_Drawing_Bitmap`, a detached `<canvas>`); `Unsupported` where the
2968 /// on-screen canvas has no painter to retarget (WinUI builds XAML shapes instead).
2969 CanvasBitmap,
2970 /// The toolkit can replay canvas drawings into a PDF document ([`Toolkit::render_pdf`],
2971 /// docs/canvas.md "Exporting"), with vector shapes and the platform's own font embedding.
2972 /// `Native` only where the platform ships a PDF writer the canvas painter can draw into
2973 /// (Core Graphics on AppKit and UIKit, cairo on GTK, `QPdfWriter` on Qt, `PdfDocument` on
2974 /// Android); `Unsupported` on ArkUI, the web and WinUI, which have none.
2975 CanvasPdf,
2976 /// The toolkit minimizes, zooms, hides and restores a window on request
2977 /// ([`WindowChange::State`], [`WindowChange::Visible`], docs/windows.md) and reports what the
2978 /// user does through [`Event::WindowStateChanged`]. `Native` on the desktop backends;
2979 /// `Unsupported` on the phones and the web, whose windows the OS sizes.
2980 WindowStates,
2981 /// The toolkit takes a window fullscreen on request and reports when it enters and leaves
2982 /// ([`WindowState::Fullscreen`]). `Native` on the desktops, on Android (system bars hidden
2983 /// through `WindowInsetsController`), on HarmonyOS and on the web (the Fullscreen API, which
2984 /// browsers allow only during a user gesture); `Emulated` on iOS, which hides the status bar
2985 /// and lets the home indicator fade but always keeps the app full-screen anyway.
2986 WindowFullscreen,
2987 /// The toolkit keeps a window out of screenshots, recordings and screen sharing
2988 /// ([`WindowChange::ContentProtected`]). `Native` on macOS (`NSWindowSharingNone`), Windows
2989 /// (`WDA_EXCLUDEFROMCAPTURE`), Android (`FLAG_SECURE`) and HarmonyOS (privacy mode);
2990 /// `Emulated` on iOS, which has no switch for it: Day covers the content while the screen is
2991 /// being recorded or mirrored, but a screenshot still captures it. `Unsupported` on Linux
2992 /// and the web.
2993 ContentProtection,
2994 /// The toolkit honors [`WindowOptions::tabbing`]: macOS window tabs. `Unsupported` everywhere
2995 /// else, where no system window tabs exist.
2996 WindowTabbing,
2997 /// The toolkit shows a Dock menu ([`Toolkit::set_dock_menu`], docs/menus.md): the app's
2998 /// shortcuts and `dock_menu(..)` entries above the system's own items. macOS only.
2999 DockMenu,
3000 /// The toolkit resizes a window and bounds its size on request ([`WindowChange::Frame`]'s
3001 /// size, [`WindowChange::Limits`], [`WindowChange::Resizable`]).
3002 WindowGeometry,
3003 /// The toolkit moves a window to a requested position ([`WindowChange::Frame`]'s origin).
3004 /// `Unsupported` on GTK 4, which removed window positioning, and wherever the compositor owns
3005 /// placement (Wayland).
3006 WindowPosition,
3007 /// The toolkit changes how a window stacks ([`WindowChange::Level`],
3008 /// [`WindowChange::OnAllWorkspaces`], [`WindowChange::SkipTaskbar`]).
3009 WindowLevel,
3010 /// The toolkit gives one window its own light/dark appearance ([`WindowChange::Appearance`]).
3011 /// Where it cannot, the app-wide [`Toolkit::set_appearance`] still applies to every window.
3012 WindowAppearance,
3013 /// The toolkit asks for the user's attention on request ([`WindowChange::RequestAttention`]):
3014 /// a Dock bounce, a flashing taskbar button.
3015 RequestAttention,
3016 /// The toolkit opens a window with no title bar or frame ([`WindowChrome::Frameless`],
3017 /// docs/window-chrome.md). Desktop backends only.
3018 FramelessWindow,
3019 /// The toolkit runs a window's content under its title bar with the window controls kept
3020 /// ([`WindowChrome::Overlay`]) and reports the bar's height as the safe-area top inset.
3021 OverlayTitleBar,
3022 /// The toolkit opens a window whose unpainted pixels show the desktop
3023 /// ([`WindowBackground::Transparent`]).
3024 TransparentWindow,
3025 /// The toolkit puts a translucent system material behind a window
3026 /// ([`WindowBackground::Material`]): macOS's visual-effect materials, Windows 11's Mica and
3027 /// Acrylic. `Emulated` where an approximation stands in.
3028 WindowMaterial,
3029 /// The toolkit lets a piece move its window like a title bar does
3030 /// ([`Toolkit::set_drag_region`], `.window_drag_region()`). `Emulated` on the web, where
3031 /// only an installed app with a window-controls overlay honors it.
3032 DragRegion,
3033 /// The toolkit shows status items ([`Toolkit::set_status_items`], docs/status-item.md): the
3034 /// macOS menu bar, the Windows notification area, a Linux tray. On Linux the answer depends
3035 /// on the desktop: `Native` while a `StatusNotifierItem` host is running (KDE Plasma, most
3036 /// panels, GNOME with the AppIndicator extension), `Unsupported` without one (stock GNOME),
3037 /// so an app can keep a window instead of vanishing into a tray nobody shows.
3038 StatusItem,
3039 /// The toolkit shows progress on the app's Dock or taskbar icon
3040 /// ([`Toolkit::set_app_progress`]). `Emulated` on Linux, where the Unity launcher protocol is
3041 /// honored by KDE Plasma and Dash to Dock but not by every dock.
3042 AppProgress,
3043 /// The toolkit can hide the app's Dock icon while it runs ([`Toolkit::set_dock_visible`]).
3044 /// macOS only.
3045 DockVisibility,
3046 /// The toolkit lists the displays and their work areas ([`Toolkit::monitors`]). `Emulated`
3047 /// where the one screen the app runs on is reported (a phone, the web).
3048 Monitors,
3049 /// The toolkit shows launcher shortcuts the app sets while it runs
3050 /// ([`Toolkit::set_launcher_shortcuts`]).
3051 DynamicShortcuts,
3052 /// How the toolkit draws a sectioned list's headers (`ListProps::sections`, docs/list.md
3053 /// "Sections"). `Native` where the platform's list has group headers that pin to the top
3054 /// while their section scrolls under them: macos-appkit (`NSTableView` group rows with
3055 /// `floatsGroupRows`) and ios-uikit (plain-style `UITableView` section headers).
3056 /// `Emulated` where the host pins a copy of the current header over the top of the list
3057 /// itself. Headers are unselectable rows on every toolkit, so an app needs this only to
3058 /// describe the difference, never to decide whether to call `.sections`.
3059 ListSections,
3060 /// The toolkit's share chooser carries the app's own actions ([`share::ShareSpec::actions`],
3061 /// docs/sharing.md): Add Bookmark or Find on Page beside the system's targets, each with
3062 /// its title and glyph. `Native` on ios-uikit (a `UIActivity` per action), macos-appkit (an
3063 /// `NSSharingService` per action, offered by the picker's delegate) and android-material
3064 /// on Android 14 and later (`ChooserAction`). `Unsupported` everywhere else: the chooser
3065 /// shows the system's targets only, and the app offers its actions in its own menu.
3066 ShareActions,
3067}
3068
3069impl Cap {
3070 /// Every capability, in declaration order: what a conformance run asks the toolkit about,
3071 /// so the evidence can be held against the declared coverage matrix (docs/testing.md).
3072 pub const ALL: [Cap; 91] = [
3073 Cap::DragDrop,
3074 Cap::DragExternalImport,
3075 Cap::DragExternalExport,
3076 Cap::DragMultipleItems,
3077 Cap::DragFileReferences,
3078 Cap::DragDeferredReceipt,
3079 Cap::DragFilePromises,
3080 Cap::DragExternalMove,
3081 Cap::ListRecycling,
3082 Cap::UndoBridge,
3083 Cap::EditBridge,
3084 Cap::ListReorder,
3085 Cap::NavReorder,
3086 Cap::ListDelete,
3087 Cap::ListSwipeActions,
3088 Cap::Tree,
3089 Cap::TreeMove,
3090 Cap::BaselineAlignment,
3091 Cap::TextRuns,
3092 Cap::TextLinks,
3093 Cap::Lottie,
3094 Cap::NativeSymbols,
3095 Cap::Snapshot,
3096 Cap::NavSplit,
3097 Cap::NavTabs,
3098 Cap::NavTabsAdaptive,
3099 Cap::NavRepresent,
3100 Cap::NavContentList,
3101 Cap::NavHeader,
3102 Cap::Appearance,
3103 Cap::AppMenu,
3104 Cap::Dialogs,
3105 Cap::FileDialogs,
3106 Cap::Animation,
3107 Cap::Cover,
3108 Cap::StatusBarHidden,
3109 Cap::TextEditable,
3110 Cap::TextSelectable,
3111 Cap::TextSpellCheck,
3112 Cap::MultiWindow,
3113 Cap::AppBadgeCount,
3114 Cap::AppBadgeText,
3115 Cap::AppBadgeDot,
3116 Cap::Toolbar,
3117 Cap::ToolbarSearch,
3118 Cap::Inspector,
3119 Cap::Cursor,
3120 Cap::FontList,
3121 Cap::ReduceMotion,
3122 Cap::Announce,
3123 Cap::ImageDecode,
3124 Cap::ImageEncode,
3125 Cap::ImageProperties,
3126 Cap::WindowStates,
3127 Cap::WindowFullscreen,
3128 Cap::ContentProtection,
3129 Cap::WindowTabbing,
3130 Cap::DockMenu,
3131 Cap::WindowGeometry,
3132 Cap::WindowPosition,
3133 Cap::WindowLevel,
3134 Cap::WindowAppearance,
3135 Cap::RequestAttention,
3136 Cap::FramelessWindow,
3137 Cap::OverlayTitleBar,
3138 Cap::TransparentWindow,
3139 Cap::WindowMaterial,
3140 Cap::DragRegion,
3141 Cap::StatusItem,
3142 Cap::AppProgress,
3143 Cap::DockVisibility,
3144 Cap::Monitors,
3145 Cap::DynamicShortcuts,
3146 Cap::Split,
3147 Cap::TreeSections,
3148 Cap::CoverSheet,
3149 Cap::ListEditing,
3150 Cap::ListItem,
3151 Cap::CanvasBitmap,
3152 Cap::CanvasPdf,
3153 Cap::SearchField,
3154 Cap::ComboBox,
3155 Cap::Stepper,
3156 Cap::DateTimePicker,
3157 Cap::ColorPicker,
3158 Cap::PullRefresh,
3159 Cap::Pager,
3160 Cap::PullRefreshGesture,
3161 Cap::FolderDialog,
3162 Cap::ListSections,
3163 Cap::ShareActions,
3164 ];
3165
3166 /// The capability's place in [`Cap::ALL`]. Exhaustive, so a new variant fails to compile
3167 /// here until it is given one, and the unit test below then holds `ALL` to it.
3168 #[must_use]
3169 pub const fn ordinal(self) -> usize {
3170 match self {
3171 Cap::DragDrop => 0,
3172 Cap::DragExternalImport => 1,
3173 Cap::DragExternalExport => 2,
3174 Cap::DragMultipleItems => 3,
3175 Cap::DragFileReferences => 4,
3176 Cap::DragDeferredReceipt => 5,
3177 Cap::DragFilePromises => 6,
3178 Cap::DragExternalMove => 7,
3179 Cap::ListRecycling => 8,
3180 Cap::UndoBridge => 9,
3181 Cap::EditBridge => 10,
3182 Cap::ListReorder => 11,
3183 Cap::NavReorder => 12,
3184 Cap::ListDelete => 13,
3185 Cap::ListSwipeActions => 14,
3186 Cap::Tree => 15,
3187 Cap::TreeMove => 16,
3188 Cap::BaselineAlignment => 17,
3189 Cap::TextRuns => 18,
3190 Cap::TextLinks => 19,
3191 Cap::Lottie => 20,
3192 Cap::NativeSymbols => 21,
3193 Cap::Snapshot => 22,
3194 Cap::NavSplit => 23,
3195 Cap::NavTabs => 24,
3196 Cap::NavTabsAdaptive => 25,
3197 Cap::NavRepresent => 26,
3198 Cap::NavContentList => 27,
3199 Cap::NavHeader => 28,
3200 Cap::Appearance => 29,
3201 Cap::AppMenu => 30,
3202 Cap::Dialogs => 31,
3203 Cap::FileDialogs => 32,
3204 Cap::Animation => 33,
3205 Cap::Cover => 34,
3206 Cap::StatusBarHidden => 35,
3207 Cap::TextEditable => 36,
3208 Cap::TextSelectable => 37,
3209 Cap::TextSpellCheck => 38,
3210 Cap::MultiWindow => 39,
3211 Cap::AppBadgeCount => 40,
3212 Cap::AppBadgeText => 41,
3213 Cap::AppBadgeDot => 42,
3214 Cap::Toolbar => 43,
3215 Cap::ToolbarSearch => 44,
3216 Cap::Inspector => 45,
3217 Cap::Cursor => 46,
3218 Cap::FontList => 47,
3219 Cap::ReduceMotion => 48,
3220 Cap::Announce => 49,
3221 Cap::ImageDecode => 50,
3222 Cap::ImageEncode => 51,
3223 Cap::ImageProperties => 52,
3224 Cap::WindowStates => 53,
3225 Cap::WindowFullscreen => 54,
3226 Cap::ContentProtection => 55,
3227 Cap::WindowTabbing => 56,
3228 Cap::DockMenu => 57,
3229 Cap::WindowGeometry => 58,
3230 Cap::WindowPosition => 59,
3231 Cap::WindowLevel => 60,
3232 Cap::WindowAppearance => 61,
3233 Cap::RequestAttention => 62,
3234 Cap::FramelessWindow => 63,
3235 Cap::OverlayTitleBar => 64,
3236 Cap::TransparentWindow => 65,
3237 Cap::WindowMaterial => 66,
3238 Cap::DragRegion => 67,
3239 Cap::StatusItem => 68,
3240 Cap::AppProgress => 69,
3241 Cap::DockVisibility => 70,
3242 Cap::Monitors => 71,
3243 Cap::DynamicShortcuts => 72,
3244 Cap::Split => 73,
3245 Cap::TreeSections => 74,
3246 Cap::CoverSheet => 75,
3247 Cap::ListEditing => 76,
3248 Cap::ListItem => 77,
3249 Cap::CanvasBitmap => 78,
3250 Cap::CanvasPdf => 79,
3251 Cap::SearchField => 80,
3252 Cap::ComboBox => 81,
3253 Cap::Stepper => 82,
3254 Cap::DateTimePicker => 83,
3255 Cap::ColorPicker => 84,
3256 Cap::PullRefresh => 85,
3257 Cap::Pager => 86,
3258 Cap::PullRefreshGesture => 87,
3259 Cap::FolderDialog => 88,
3260 Cap::ListSections => 89,
3261 Cap::ShareActions => 90,
3262 }
3263 }
3264}
3265
3266// ---------------------------------------------------------------------------
3267// Raster images (docs/images.md): the currency shared by the `image` piece, the canvas, and
3268// the decode/metadata/encode duties below.
3269// ---------------------------------------------------------------------------
3270
3271/// A decoded image the toolkit holds, addressed by an id day-core mints.
3272///
3273/// Opaque, because what sits behind it is an `NSImage`, a `UIImage`, a `GdkTexture`, a
3274/// `QPixmap`, a `BitmapImage`, an android `Bitmap` or an `ImageBitmap`, and none of those cross
3275/// the boundary. The id is released through [`Toolkit::release_image`] when the app's handle
3276/// drops, so a backend's side table never outlives the app's interest in it.
3277#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
3278pub struct BitmapId(pub u64);
3279
3280/// An encoded image format: what [`BitmapInfo::format`] reports and [`EncodeSpec::format`] asks
3281/// for. Not every backend encodes every one: ask [`Toolkit::encode_formats`] (the
3282/// [`Cap::ImageEncode`] pair of [`Toolkit::font_families`]/[`Cap::FontList`]) rather than
3283/// assuming.
3284#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default)]
3285pub enum ImageFormat {
3286 #[default]
3287 Png,
3288 Jpeg,
3289 Webp,
3290 Gif,
3291 Bmp,
3292 Tiff,
3293 /// HEIF/HEIC, Apple's camera format; decodable on the Apple backends and Android, and
3294 /// encodable almost nowhere.
3295 Heif,
3296 /// Decoded from bytes whose magic numbers [`ImageFormat::sniff`] does not know. A backend may
3297 /// still decode it: the platform decoders read more formats than Day names.
3298 Unknown,
3299}
3300
3301impl ImageFormat {
3302 /// The IANA media type, which is also the string the ArkUI packer, GDI+ and the browser's
3303 /// `toBlob` take. `Unknown` answers `application/octet-stream`.
3304 #[must_use]
3305 pub fn mime(self) -> &'static str {
3306 match self {
3307 ImageFormat::Png => "image/png",
3308 ImageFormat::Jpeg => "image/jpeg",
3309 ImageFormat::Webp => "image/webp",
3310 ImageFormat::Gif => "image/gif",
3311 ImageFormat::Bmp => "image/bmp",
3312 ImageFormat::Tiff => "image/tiff",
3313 ImageFormat::Heif => "image/heif",
3314 ImageFormat::Unknown => "application/octet-stream",
3315 }
3316 }
3317
3318 /// The pixel size the encoded bytes declare, read from the container's own header
3319 /// (docs/images.md).
3320 ///
3321 /// Every backend that decodes natively reports its own dimensions; this exists for the one
3322 /// that cannot. The XAML backend's (`windows-winui`) `BitmapImage` learns its size
3323 /// asynchronously, only once the element has been shown, so a synchronous `image_info` there
3324 /// would have nothing to say.
3325 /// Reading the header instead gives the same answer the decoder would, before any decoding.
3326 ///
3327 /// `None` when the header is absent, truncated, or a container this does not parse.
3328 #[must_use]
3329 pub fn dimensions(bytes: &[u8]) -> Option<(u32, u32)> {
3330 let be16 = |i: usize| -> Option<u32> {
3331 Some(u32::from(u16::from_be_bytes([
3332 *bytes.get(i)?,
3333 *bytes.get(i + 1)?,
3334 ])))
3335 };
3336 let le16 = |i: usize| -> Option<u32> {
3337 Some(u32::from(u16::from_le_bytes([
3338 *bytes.get(i)?,
3339 *bytes.get(i + 1)?,
3340 ])))
3341 };
3342 let be32 = |i: usize| -> Option<u32> {
3343 Some(u32::from_be_bytes([
3344 *bytes.get(i)?,
3345 *bytes.get(i + 1)?,
3346 *bytes.get(i + 2)?,
3347 *bytes.get(i + 3)?,
3348 ]))
3349 };
3350 let le32 = |i: usize| -> Option<u32> {
3351 Some(u32::from_le_bytes([
3352 *bytes.get(i)?,
3353 *bytes.get(i + 1)?,
3354 *bytes.get(i + 2)?,
3355 *bytes.get(i + 3)?,
3356 ]))
3357 };
3358 match Self::sniff(bytes)? {
3359 // IHDR is always the first chunk: 8-byte signature, 4-byte length, 4-byte type.
3360 ImageFormat::Png => Some((be32(16)?, be32(20)?)),
3361 // The logical screen descriptor follows the 6-byte version stamp, little-endian.
3362 ImageFormat::Gif => Some((le16(6)?, le16(8)?)),
3363 // The DIB header's width/height are signed; a negative height is a top-down bitmap.
3364 ImageFormat::Bmp => Some((
3365 le32(18)?.cast_signed().unsigned_abs(),
3366 le32(22)?.cast_signed().unsigned_abs(),
3367 )),
3368 // Walk the segment chain to the frame header. Every SOF marker carries the size at
3369 // the same offsets; the arithmetic-coded and progressive ones are SOFs too, which is
3370 // why this matches the whole range rather than SOF0 alone. DNL/DHP (0xC4, 0xC8,
3371 // 0xCC) are not frame headers and are skipped like any other segment.
3372 ImageFormat::Jpeg => {
3373 let mut i = 2usize;
3374 // `<=`, not `<`: a frame header that ends the buffer is still a frame header, and
3375 // the size sits in its last four bytes.
3376 while i + 9 <= bytes.len() {
3377 if bytes[i] != 0xFF {
3378 i += 1;
3379 continue;
3380 }
3381 let marker = bytes[i + 1];
3382 // Padding fill bytes and the standalone markers carry no length.
3383 if marker == 0xFF || (0xD0..=0xD9).contains(&marker) || marker == 0x01 {
3384 i += 1;
3385 continue;
3386 }
3387 let is_sof = (0xC0..=0xCF).contains(&marker)
3388 && marker != 0xC4
3389 && marker != 0xC8
3390 && marker != 0xCC;
3391 if is_sof {
3392 // [marker][len:2][precision:1][height:2][width:2]
3393 return Some((be16(i + 7)?, be16(i + 5)?));
3394 }
3395 i += 2 + be16(i + 2)? as usize;
3396 }
3397 None
3398 }
3399 // RIFF: a 12-byte header, then a chunk id. VP8X states the size minus one in 24-bit
3400 // little-endian; lossy VP8 hides it in the 14 low bits after the start code; lossless
3401 // VP8L packs width-1 and height-1 into 14 bits each across four bytes.
3402 ImageFormat::Webp => match bytes.get(12..16)? {
3403 b"VP8X" => {
3404 let w = u32::from(*bytes.get(24)?)
3405 | u32::from(*bytes.get(25)?) << 8
3406 | u32::from(*bytes.get(26)?) << 16;
3407 let h = u32::from(*bytes.get(27)?)
3408 | u32::from(*bytes.get(28)?) << 8
3409 | u32::from(*bytes.get(29)?) << 16;
3410 Some((w + 1, h + 1))
3411 }
3412 b"VP8 " => Some((le16(26)? & 0x3FFF, le16(28)? & 0x3FFF)),
3413 b"VP8L" => {
3414 let bits = le32(21)?;
3415 Some(((bits & 0x3FFF) + 1, ((bits >> 14) & 0x3FFF) + 1))
3416 }
3417 _ => None,
3418 },
3419 // TIFF's IFD is a pointer chase and HEIF's is a box tree; neither is worth parsing
3420 // here, because every backend that reads them decodes natively and answers for itself.
3421 ImageFormat::Tiff | ImageFormat::Heif | ImageFormat::Unknown => None,
3422 }
3423 }
3424
3425 /// The format `bytes` begins with, by magic number: enough to fill [`BitmapInfo::format`]
3426 /// on every backend, including the ones whose decoder never says what it decoded.
3427 ///
3428 /// Hand-rolled rather than a crate: it is a dozen byte comparisons against fixed prefixes,
3429 /// and the alternative is an image-decoding dependency in the one crate that must stay
3430 /// dependency-free.
3431 #[must_use]
3432 pub fn sniff(bytes: &[u8]) -> Option<ImageFormat> {
3433 let starts = |sig: &[u8]| bytes.len() >= sig.len() && &bytes[..sig.len()] == sig;
3434 if starts(&[0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a]) {
3435 return Some(ImageFormat::Png);
3436 }
3437 if starts(&[0xff, 0xd8, 0xff]) {
3438 return Some(ImageFormat::Jpeg);
3439 }
3440 if starts(b"GIF87a") || starts(b"GIF89a") {
3441 return Some(ImageFormat::Gif);
3442 }
3443 if starts(b"BM") {
3444 return Some(ImageFormat::Bmp);
3445 }
3446 if starts(&[0x49, 0x49, 0x2a, 0x00]) || starts(&[0x4d, 0x4d, 0x00, 0x2a]) {
3447 return Some(ImageFormat::Tiff);
3448 }
3449 // RIFF....WEBP and ....ftypheic/heix/mif1 both carry their tag past a 4-byte prefix.
3450 if starts(b"RIFF") && bytes.len() >= 12 && &bytes[8..12] == b"WEBP" {
3451 return Some(ImageFormat::Webp);
3452 }
3453 if bytes.len() >= 12 && &bytes[4..8] == b"ftyp" {
3454 let brand = &bytes[8..12];
3455 if brand == b"heic" || brand == b"heix" || brand == b"mif1" || brand == b"msf1" {
3456 return Some(ImageFormat::Heif);
3457 }
3458 }
3459 None
3460 }
3461}
3462
3463/// What a decoded image is, in the terms every backend can answer
3464/// ([`Toolkit::image_info`], docs/images.md).
3465///
3466/// `pixels` is the image's own pixel size, not the points it draws at: an asset that stages at
3467/// 2× reports twice its point size and a `scale` of 2, so an app sizing a frame divides. Bytes
3468/// carry no density, so a decoded buffer always answers `scale: 1.0`.
3469#[derive(Clone, Copy, Debug, Default, PartialEq)]
3470pub struct BitmapInfo {
3471 pub pixels: Size,
3472 /// Pixels per point (1.0 for decoded bytes; 2 or 3 for a catalog/drawable asset that staged
3473 /// a density variant).
3474 pub scale: f64,
3475 /// The encoded format it came from, where the backend knows or [`ImageFormat::sniff`] said.
3476 pub format: Option<ImageFormat>,
3477 pub has_alpha: bool,
3478}
3479
3480/// What [`Toolkit::encode_image`] should produce (docs/images.md).
3481///
3482/// A struct rather than three positional arguments, per docs/api-style.md: the call site reads
3483/// `EncodeSpec { format: ImageFormat::Jpeg, quality: Some(0.8), ..Default::default() }`.
3484#[derive(Clone, Copy, Debug, PartialEq)]
3485pub struct EncodeSpec {
3486 pub format: ImageFormat,
3487 /// Lossy quality in `0.0..=1.0`. `None` takes the platform's default; a lossless format
3488 /// ignores it.
3489 pub quality: Option<f64>,
3490 /// Scale the longest side down to fit this box first (aspect preserved). `None` encodes at
3491 /// the image's own size.
3492 pub fit: Option<Size>,
3493}
3494
3495impl Default for EncodeSpec {
3496 fn default() -> Self {
3497 EncodeSpec {
3498 format: ImageFormat::Png,
3499 quality: None,
3500 fit: None,
3501 }
3502 }
3503}
3504
3505/// The metadata an image file carries beyond its pixels ([`Toolkit::image_properties`]).
3506///
3507/// Sparse by construction: every field is what the platform's own reader answered, and a
3508/// backend with no metadata reader at all answers `None` to the whole call rather than an empty
3509/// struct. Probe [`Cap::ImageProperties`] before offering an affordance that depends on it.
3510#[derive(Clone, Debug, Default, PartialEq)]
3511pub struct ImageProperties {
3512 /// The EXIF orientation tag (1–8), where one was recorded.
3513 pub orientation: Option<u16>,
3514 /// Pixels per inch, where the file records a resolution.
3515 pub dpi: Option<f64>,
3516 /// The capture timestamp as the file spells it (no parsing: the formats disagree).
3517 pub created: Option<String>,
3518 /// Everything else the platform reader named, in its own vocabulary. Keys are the
3519 /// platform's, so read them defensively.
3520 pub extra: Vec<(String, String)>,
3521}
3522
3523/// Why an image operation could not answer.
3524#[derive(Clone, Copy, Debug, PartialEq, Eq)]
3525pub enum ImageError {
3526 /// The bytes are not an image this platform decodes.
3527 Decode,
3528 /// The image decoded, but this backend cannot encode the format asked for. `encode_formats`
3529 /// says which it can.
3530 Encode,
3531 /// The backend has no path for this at all (probe [`Cap::ImageDecode`] /
3532 /// [`Cap::ImageEncode`]).
3533 Unsupported,
3534 /// The id named no live image: released already, or never decoded.
3535 Gone,
3536}
3537
3538impl std::fmt::Display for ImageError {
3539 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3540 match self {
3541 ImageError::Decode => write!(f, "the bytes are not a decodable image"),
3542 ImageError::Encode => write!(f, "this backend cannot encode that format"),
3543 ImageError::Unsupported => write!(f, "image support is unavailable on this backend"),
3544 ImageError::Gone => write!(f, "the image was released"),
3545 }
3546 }
3547}
3548
3549impl std::error::Error for ImageError {}
3550
3551// ---------------------------------------------------------------------------
3552// Canvas export (docs/canvas.md "Exporting"): a recorded drawing replayed into an offscreen
3553// bitmap or a PDF by the same painter the on-screen canvas uses.
3554// ---------------------------------------------------------------------------
3555
3556/// The largest side, in pixels, a rendered bitmap may have (docs/canvas.md "Exporting").
3557/// day-core answers [`ExportError::TooLarge`] above it before any toolkit allocates.
3558pub const EXPORT_MAX_SIDE: u32 = 16_384;
3559
3560/// The most pixels a rendered bitmap may hold in total: 64 megapixels, 256 MB at four bytes a
3561/// pixel, which is already more than the tightest per-app heap (Android's) comfortably holds.
3562pub const EXPORT_MAX_PIXELS: u64 = 64 * 1024 * 1024;
3563
3564/// The pixel size a drawing of `size` points renders to at `scale` pixels per point: each side
3565/// rounded up, so a drawing never loses its last partial pixel. Shared by day-core's limit
3566/// check and every backend, so the bitmap a backend allocates is the one day-core approved.
3567#[must_use]
3568pub fn export_pixels(size: Size, scale: f64) -> (u32, u32) {
3569 let side = |v: f64| (v * scale).ceil().clamp(0.0, f64::from(u32::MAX)) as u32;
3570 (side(size.width), side(size.height))
3571}
3572
3573/// One page of a PDF [`Toolkit::render_pdf`] writes: the page size in PDF points (1/72 inch,
3574/// the same unit as canvas points) and the ops to replay onto it, origin top-left.
3575#[derive(Clone, Debug, PartialEq)]
3576pub struct PdfPage {
3577 pub size: Size,
3578 pub ops: Vec<DrawOp>,
3579}
3580
3581/// The document information a PDF carries. A backend whose writer has no metadata API (Android's
3582/// `PdfDocument`) ignores it.
3583#[derive(Clone, Debug, Default, PartialEq)]
3584pub struct PdfInfo {
3585 pub title: Option<String>,
3586 pub author: Option<String>,
3587}
3588
3589/// Why a canvas export could not answer (docs/canvas.md "Exporting").
3590#[derive(Clone, Debug, PartialEq)]
3591pub enum ExportError {
3592 /// This toolkit has no path for the export (probe [`Cap::CanvasBitmap`] /
3593 /// [`Cap::CanvasPdf`]).
3594 Unsupported,
3595 /// The bitmap would exceed [`EXPORT_MAX_SIDE`] or [`EXPORT_MAX_PIXELS`]; checked in
3596 /// day-core before the toolkit runs. The size is the one that was refused, in pixels.
3597 TooLarge { width: u32, height: u32 },
3598 /// A zero, negative or non-finite size or scale, or a PDF with no pages.
3599 Invalid,
3600 /// The platform refused (out of memory, a writer error); the text is the platform's.
3601 Failed(String),
3602}
3603
3604impl std::fmt::Display for ExportError {
3605 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3606 match self {
3607 ExportError::Unsupported => write!(f, "this export is unavailable on this backend"),
3608 ExportError::TooLarge { width, height } => {
3609 write!(
3610 f,
3611 "a {width} × {height} pixel bitmap is too large to render"
3612 )
3613 }
3614 ExportError::Invalid => write!(f, "the drawing has no size or the PDF has no pages"),
3615 ExportError::Failed(why) => write!(f, "rendering failed: {why}"),
3616 }
3617 }
3618}
3619
3620impl std::error::Error for ExportError {}
3621
3622/// Where a raster image's pixels come from (docs/images.md).
3623///
3624/// One currency for both halves of the same question: `Named` is the staged asset every
3625/// `image(res::images::…)` has always drawn, `Bytes` is an encoded PNG/JPEG the app already
3626/// holds (a download, a file the user picked, a clipboard paste), and `Decoded` names an image
3627/// the toolkit decoded once so several nodes (and the canvas) share it.
3628#[derive(Clone)]
3629pub enum ImageSource {
3630 /// A staged asset name, resolved through the backend's own pipeline (§18.2).
3631 Named(String),
3632 /// Encoded bytes (PNG/JPEG/…) the app owns, decoded by the platform's own decoder. Shared
3633 /// rather than copied: handing over a new buffer is a refcount bump.
3634 Bytes(std::sync::Arc<Vec<u8>>),
3635 /// An image already decoded through [`Toolkit::decode_image`].
3636 Decoded(BitmapId),
3637}
3638
3639impl Default for ImageSource {
3640 fn default() -> Self {
3641 ImageSource::Named(String::new())
3642 }
3643}
3644
3645/// Bytes compare by identity, not content.
3646///
3647/// This is the equality a binding gates on (§4.2), so it runs on every evaluation, and
3648/// comparing two multi-megabyte buffers byte by byte would cost far more than the redundant
3649/// decode it saves. Handing over a distinct buffer holding the same pixels therefore re-decodes,
3650/// which is the same trade `Arc::ptr_eq` makes wherever else Day carries shared buffers.
3651impl PartialEq for ImageSource {
3652 fn eq(&self, other: &Self) -> bool {
3653 match (self, other) {
3654 (ImageSource::Named(a), ImageSource::Named(b)) => a == b,
3655 (ImageSource::Bytes(a), ImageSource::Bytes(b)) => std::sync::Arc::ptr_eq(a, b),
3656 (ImageSource::Decoded(a), ImageSource::Decoded(b)) => a == b,
3657 _ => false,
3658 }
3659 }
3660}
3661
3662/// Logs the buffer's length, never its contents: a `Debug` that dumped a megabyte of pixels
3663/// into a trace line would make the trace useless and slow.
3664impl std::fmt::Debug for ImageSource {
3665 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3666 match self {
3667 ImageSource::Named(n) => f.debug_tuple("Named").field(n).finish(),
3668 ImageSource::Bytes(b) => f.debug_tuple("Bytes").field(&b.len()).finish(),
3669 ImageSource::Decoded(id) => f.debug_tuple("Decoded").field(&id.0).finish(),
3670 }
3671 }
3672}
3673
3674impl From<BitmapId> for ImageSource {
3675 fn from(id: BitmapId) -> Self {
3676 ImageSource::Decoded(id)
3677 }
3678}
3679
3680/// A staged asset name is a source, so `image(res::images::cover)` keeps compiling unchanged.
3681///
3682/// There is no `From<&str>` here, for the same reason [`resource::ImageName`] has none:
3683/// `image("typo")` must stay a compile error rather than a blank view at runtime (resource.rs).
3684/// A path or URL string is not a source either: read the bytes and hand those over.
3685impl From<resource::ImageName> for ImageSource {
3686 fn from(name: resource::ImageName) -> Self {
3687 ImageSource::Named(name.as_str().to_owned())
3688 }
3689}
3690
3691impl From<resource::VectorName> for ImageSource {
3692 fn from(name: resource::VectorName) -> Self {
3693 ImageSource::Named(name.as_str().to_owned())
3694 }
3695}
3696
3697impl From<std::sync::Arc<Vec<u8>>> for ImageSource {
3698 fn from(bytes: std::sync::Arc<Vec<u8>>) -> Self {
3699 ImageSource::Bytes(bytes)
3700 }
3701}
3702
3703/// An owned string is a name, not bytes: the same conversion [`resource::ImageName`] offers for
3704/// a name computed at runtime, and the reason `image(some_string)` keeps compiling. A `&str`
3705/// still converts nowhere, so `image("typo")` stays a compile error (resource.rs).
3706impl From<String> for ImageSource {
3707 fn from(name: String) -> Self {
3708 ImageSource::Named(name)
3709 }
3710}
3711
3712impl From<Vec<u8>> for ImageSource {
3713 fn from(bytes: Vec<u8>) -> Self {
3714 ImageSource::Bytes(std::sync::Arc::new(bytes))
3715 }
3716}
3717
3718#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
3719pub enum Support {
3720 Native,
3721 Emulated,
3722 /// The default: what an unimplemented capability answers everywhere.
3723 #[default]
3724 Unsupported,
3725}
3726
3727/// What a text field collects (`text_field(..).input_purpose(_)`, docs/textfield.md).
3728///
3729/// One word for everything a platform keys off the kind of text: the on-screen keyboard's
3730/// layout, capitalization and correction, and the credential or contact the system offers to
3731/// fill in. A backend applies the parts its toolkit has: a desktop toolkit with no on-screen
3732/// keyboard still takes the autofill and correction half.
3733///
3734/// Purpose is independent of [`InputTraits::secure`]: a numeric PIN is `Number` and secure.
3735#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
3736pub enum InputPurpose {
3737 /// Free text: the default keyboard, with the platform's own capitalization and correction.
3738 #[default]
3739 Text,
3740 /// A person's name: words capitalized, never corrected.
3741 Name,
3742 /// An email address: the `@` keyboard, never capitalized or corrected.
3743 Email,
3744 /// A web address: the URL keyboard, never capitalized or corrected.
3745 Url,
3746 /// A telephone number: the phone pad.
3747 Phone,
3748 /// A whole number: the digit pad.
3749 Number,
3750 /// A number with a fractional part: the digit pad with a decimal separator.
3751 Decimal,
3752 /// An account name: never capitalized or corrected, and offered to the password manager.
3753 Username,
3754 /// An existing password, offered to the password manager for filling.
3755 Password,
3756 /// A password being chosen, so the password manager offers to make and save one.
3757 NewPassword,
3758 /// A code sent by message or mail, which the keyboard offers as it arrives. The keyboard
3759 /// stays the text one, since a code can carry letters.
3760 OneTimeCode,
3761}
3762
3763/// The on-screen keyboard's action key (`text_field(..).submit_label(_)`, docs/textfield.md).
3764///
3765/// The key always fires the field's `on_submit`; this names what it promises. A toolkit with
3766/// no on-screen keyboard ignores it.
3767#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
3768pub enum SubmitLabel {
3769 /// The platform's own key (Return).
3770 #[default]
3771 Return,
3772 Done,
3773 Go,
3774 Next,
3775 Search,
3776 Send,
3777}
3778
3779/// How a text field takes its text (docs/textfield.md): the whole set travels together through
3780/// [`Toolkit::set_input_traits`], so a backend that has to rebuild the widget for one member
3781/// has every other member in hand to dress the replacement.
3782#[derive(Clone, Debug, Default, PartialEq, Eq)]
3783pub struct InputTraits {
3784 /// Hide the characters (a password field).
3785 pub secure: bool,
3786 /// Show and select the text, take no edits.
3787 pub read_only: bool,
3788 pub purpose: InputPurpose,
3789 pub submit_label: SubmitLabel,
3790 /// The most characters (Unicode scalar values) the field takes; `None` is unbounded.
3791 /// day-pieces holds the bound on every backend. A toolkit applies its native limit as well
3792 /// only where that limit counts the same unit (GTK): one that counts UTF-16 units would
3793 /// refuse characters the bound allows.
3794 pub max_length: Option<u32>,
3795}
3796
3797/// The pointer's shape over a piece (the `.cursor()` decorator, docs/cursor.md).
3798///
3799/// The named variants are the CSS cursor vocabulary: the largest set any toolkit accepts as it
3800/// is (GTK and the DOM take the names verbatim), and every other toolkit's set is a subset of it
3801/// or maps onto it. A backend draws its own shape for each name, or the nearest one it has, and
3802/// answers [`Cap::Cursor`] with how faithful that is. [`Cursor::Native`] reaches a shape only one
3803/// toolkit names; the `day::cursor::<toolkit>` modules carry those as constants, gated on that
3804/// toolkit's feature, and every other backend ignores a name it does not know.
3805///
3806/// A cursor applies to the node and its descendants until a descendant sets its own.
3807/// [`Cursor::Default`] hands the shape back to the platform rather than pinning an arrow, so a
3808/// reactive cursor can release what it took.
3809#[derive(Clone, Debug, PartialEq, Eq, Hash, Default)]
3810pub enum Cursor {
3811 /// The platform default (an arrow), and the value that releases a node's cursor.
3812 #[default]
3813 Default,
3814 /// A pointing hand: links and other tap-to-activate content.
3815 Pointer,
3816 /// An I-beam over editable or selectable text.
3817 Text,
3818 /// An I-beam for vertical text.
3819 VerticalText,
3820 Crosshair,
3821 /// Four-way move.
3822 Move,
3823 /// An open hand: content that can be dragged.
3824 Grab,
3825 /// A closed hand: content being dragged.
3826 Grabbing,
3827 NotAllowed,
3828 /// The app is busy and cannot take input.
3829 Wait,
3830 /// The app is busy but still takes input.
3831 Progress,
3832 Help,
3833 ContextMenu,
3834 /// A drop will copy.
3835 Copy,
3836 /// A drop will link.
3837 Alias,
3838 /// A table cell.
3839 Cell,
3840 ZoomIn,
3841 ZoomOut,
3842 /// No pointer at all.
3843 None,
3844 /// Vertical (north–south) resize.
3845 NsResize,
3846 /// Horizontal (east–west) resize.
3847 EwResize,
3848 /// Diagonal resize, north-east to south-west.
3849 NeswResize,
3850 /// Diagonal resize, north-west to south-east.
3851 NwseResize,
3852 ColResize,
3853 RowResize,
3854 /// A toolkit's own named cursor, resolved by that backend's lookup and ignored by every
3855 /// other. Prefer the `day::cursor::<toolkit>` constants, which are gated on the toolkit.
3856 Native(std::borrow::Cow<'static, str>),
3857}
3858
3859impl Cursor {
3860 /// A toolkit-specific cursor by its native name (see [`Cursor::Native`]).
3861 #[must_use]
3862 pub const fn native(name: &'static str) -> Self {
3863 Cursor::Native(std::borrow::Cow::Borrowed(name))
3864 }
3865
3866 /// The CSS keyword for a named cursor, which GTK and the DOM take as it is. A native cursor
3867 /// answers its own name, so a backend keyed on CSS names may still recognize it.
3868 #[must_use]
3869 pub fn css_name(&self) -> &str {
3870 match self {
3871 Cursor::Default => "default",
3872 Cursor::Pointer => "pointer",
3873 Cursor::Text => "text",
3874 Cursor::VerticalText => "vertical-text",
3875 Cursor::Crosshair => "crosshair",
3876 Cursor::Move => "move",
3877 Cursor::Grab => "grab",
3878 Cursor::Grabbing => "grabbing",
3879 Cursor::NotAllowed => "not-allowed",
3880 Cursor::Wait => "wait",
3881 Cursor::Progress => "progress",
3882 Cursor::Help => "help",
3883 Cursor::ContextMenu => "context-menu",
3884 Cursor::Copy => "copy",
3885 Cursor::Alias => "alias",
3886 Cursor::Cell => "cell",
3887 Cursor::ZoomIn => "zoom-in",
3888 Cursor::ZoomOut => "zoom-out",
3889 Cursor::None => "none",
3890 Cursor::NsResize => "ns-resize",
3891 Cursor::EwResize => "ew-resize",
3892 Cursor::NeswResize => "nesw-resize",
3893 Cursor::NwseResize => "nwse-resize",
3894 Cursor::ColResize => "col-resize",
3895 Cursor::RowResize => "row-resize",
3896 Cursor::Native(name) => name,
3897 }
3898 }
3899
3900 /// Every named cursor, in declaration order, what a gallery or a test walks.
3901 pub const NAMED: [Cursor; 25] = [
3902 Cursor::Default,
3903 Cursor::Pointer,
3904 Cursor::Text,
3905 Cursor::VerticalText,
3906 Cursor::Crosshair,
3907 Cursor::Move,
3908 Cursor::Grab,
3909 Cursor::Grabbing,
3910 Cursor::NotAllowed,
3911 Cursor::Wait,
3912 Cursor::Progress,
3913 Cursor::Help,
3914 Cursor::ContextMenu,
3915 Cursor::Copy,
3916 Cursor::Alias,
3917 Cursor::Cell,
3918 Cursor::ZoomIn,
3919 Cursor::ZoomOut,
3920 Cursor::None,
3921 Cursor::NsResize,
3922 Cursor::EwResize,
3923 Cursor::NeswResize,
3924 Cursor::NwseResize,
3925 Cursor::ColResize,
3926 Cursor::RowResize,
3927 ];
3928}
3929
3930/// A set of screen edges, for the `defers_system_gestures` modifier (docs/cover.md). Mirrors
3931/// SwiftUI's `Edge.Set`: on iOS these map to `UIRectEdge` for
3932/// `preferredScreenEdgesDeferringSystemGestures`; on Android any non-empty set enters
3933/// swipe-to-reveal immersive mode (the closest platform analogue).
3934#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
3935pub struct Edges(pub u8);
3936
3937impl Edges {
3938 pub const NONE: Edges = Edges(0);
3939 pub const TOP: Edges = Edges(1);
3940 pub const BOTTOM: Edges = Edges(2);
3941 pub const LEADING: Edges = Edges(4);
3942 pub const TRAILING: Edges = Edges(8);
3943 pub const ALL: Edges = Edges(15);
3944
3945 #[must_use]
3946 pub fn contains(self, other: Edges) -> bool {
3947 self.0 & other.0 == other.0
3948 }
3949 #[must_use]
3950 pub fn union(self, other: Edges) -> Edges {
3951 Edges(self.0 | other.0)
3952 }
3953 #[must_use]
3954 pub fn is_empty(self) -> bool {
3955 self.0 == 0
3956 }
3957}
3958
3959impl std::ops::BitOr for Edges {
3960 type Output = Edges;
3961 fn bitor(self, rhs: Edges) -> Edges {
3962 self.union(rhs)
3963 }
3964}
3965
3966/// The timing curve of an animation (§8.4). Native backends map each variant onto their own
3967/// easing (`CAMediaTimingFunction`, `QEasingCurve`, ArkUI `ARKUI_CURVE_*`, spring animators); the
3968/// canvas/self-driven path samples it via [`Curve::fraction`]. `Spring` matches SwiftUI's
3969/// `.spring(response:dampingFraction:)`.
3970#[derive(Clone, Copy, Debug, PartialEq)]
3971pub enum Curve {
3972 Linear,
3973 EaseIn,
3974 EaseOut,
3975 EaseInOut,
3976 /// `response` = approximate settling period (seconds); `damping` = damping ratio (1.0 =
3977 /// critically damped, `<1` = bouncy overshoot).
3978 Spring {
3979 response: f64,
3980 damping: f64,
3981 },
3982}
3983
3984impl Curve {
3985 /// Fraction of the transition complete at `elapsed` seconds (0 at start, reaching 1, or
3986 /// overshooting it for an under-damped spring). Easing curves clamp to `duration`; springs
3987 /// evaluate their analytic unit-step response and use `duration` only as a settle cap. Drives
3988 /// the self-driven/canvas path; native backends interpolate on their own compositor instead.
3989 #[must_use]
3990 pub fn fraction(self, elapsed: f64, duration: f64) -> f64 {
3991 if let Curve::Spring { response, damping } = self {
3992 spring_step(response, damping, elapsed)
3993 } else {
3994 let t = if duration <= 0.0 {
3995 1.0
3996 } else {
3997 (elapsed / duration).clamp(0.0, 1.0)
3998 };
3999 self.ease(t)
4000 }
4001 }
4002
4003 /// Eased progress for normalized `t` in `0.0..=1.0` (springs pass through; use [`Self::fraction`]).
4004 #[inline]
4005 #[must_use]
4006 pub fn ease(self, t: f64) -> f64 {
4007 match self {
4008 Curve::Linear | Curve::Spring { .. } => t,
4009 Curve::EaseIn => t * t,
4010 Curve::EaseOut => 1.0 - (1.0 - t) * (1.0 - t),
4011 Curve::EaseInOut => t * t * (3.0 - 2.0 * t), // smoothstep
4012 }
4013 }
4014
4015 /// Whether the transition has settled, so the canvas frame clock can stop ticking it.
4016 #[must_use]
4017 pub fn is_settled(self, elapsed: f64, duration: f64) -> bool {
4018 match self {
4019 Curve::Spring { response, damping } => {
4020 let cap = response.max(0.0) * 4.0 + 0.2;
4021 if elapsed >= cap {
4022 return true;
4023 }
4024 (spring_step(response, damping, elapsed) - 1.0).abs() < 0.001
4025 && elapsed > response * 0.5
4026 }
4027 _ => elapsed >= duration.max(0.0),
4028 }
4029 }
4030}
4031
4032/// Unit-step response of a second-order spring (`response` = period seconds, `damping` = ratio),
4033/// evaluated at `t` seconds. Under-damped rings and overshoots; critically/over-damped eases in.
4034fn spring_step(response: f64, damping: f64, t: f64) -> f64 {
4035 if response <= 0.0 || t <= 0.0 {
4036 return if t <= 0.0 { 0.0 } else { 1.0 };
4037 }
4038 let omega0 = std::f64::consts::TAU / response;
4039 let zeta = damping.max(0.0);
4040 if zeta < 1.0 {
4041 let omega_d = omega0 * (1.0 - zeta * zeta).sqrt();
4042 let e = (-zeta * omega0 * t).exp();
4043 1.0 - e * ((omega_d * t).cos() + (zeta * omega0 / omega_d) * (omega_d * t).sin())
4044 } else {
4045 let e = (-omega0 * t).exp();
4046 1.0 - e * (1.0 + omega0 * t)
4047 }
4048}
4049
4050/// Animation intent (§8.4). Native-widget backends map it onto their own animator (Core Animation,
4051/// `ViewPropertyAnimator`, XAML Composition, `OH_ArkUI_AnimateTo`, …); the canvas/self-driven path
4052/// samples `curve` via [`Curve::fraction`]. Threaded through `Toolkit::update`/`set_frame`/
4053/// `set_opacity`/`set_transform`.
4054#[derive(Clone, Copy, Debug, PartialEq)]
4055pub struct AnimSpec {
4056 pub duration_ms: u32,
4057 pub delay_ms: u32,
4058 pub curve: Curve,
4059 /// Repeat count beyond the first play (`0` = play once); `u32::MAX` = repeat forever.
4060 pub repeat: u32,
4061 pub autoreverse: bool,
4062}
4063
4064impl Default for AnimSpec {
4065 /// The default feel: a smooth spring (SwiftUI's modern default).
4066 fn default() -> Self {
4067 AnimSpec {
4068 duration_ms: 350,
4069 delay_ms: 0,
4070 curve: Curve::Spring {
4071 response: 0.4,
4072 damping: 0.8,
4073 },
4074 repeat: 0,
4075 autoreverse: false,
4076 }
4077 }
4078}
4079
4080impl AnimSpec {
4081 /// A smooth spring: `response` = settling period (s), `damping` = ratio (1.0 = no bounce, `<1`
4082 /// bouncy). `duration_ms` is a nominal cap for backends that need a duration; spring backends
4083 /// use `response`/`damping` directly.
4084 pub fn spring(response: f64, damping: f64) -> Self {
4085 AnimSpec {
4086 // `response` is the animation's duration: every backend maps a spring to a
4087 // fixed-duration overshoot curve over exactly `duration_ms`, so timing is identical
4088 // across toolkits (a physics spring's settle time would vary per platform).
4089 duration_ms: (response * 1000.0).max(50.0) as u32,
4090 delay_ms: 0,
4091 curve: Curve::Spring { response, damping },
4092 repeat: 0,
4093 autoreverse: false,
4094 }
4095 }
4096 pub fn linear(duration_ms: u32) -> Self {
4097 Self::timed(duration_ms, Curve::Linear)
4098 }
4099 pub fn ease_in(duration_ms: u32) -> Self {
4100 Self::timed(duration_ms, Curve::EaseIn)
4101 }
4102 pub fn ease_out(duration_ms: u32) -> Self {
4103 Self::timed(duration_ms, Curve::EaseOut)
4104 }
4105 pub fn ease_in_out(duration_ms: u32) -> Self {
4106 Self::timed(duration_ms, Curve::EaseInOut)
4107 }
4108 fn timed(duration_ms: u32, curve: Curve) -> Self {
4109 AnimSpec {
4110 duration_ms,
4111 delay_ms: 0,
4112 curve,
4113 repeat: 0,
4114 autoreverse: false,
4115 }
4116 }
4117 /// Delay before the animation starts (builder).
4118 #[must_use]
4119 pub fn delay(mut self, ms: u32) -> Self {
4120 self.delay_ms = ms;
4121 self
4122 }
4123 /// Repeat `count` extra times (builder); `autoreverse` ping-pongs each cycle.
4124 #[must_use]
4125 pub fn repeat(mut self, count: u32, autoreverse: bool) -> Self {
4126 self.repeat = count;
4127 self.autoreverse = autoreverse;
4128 self
4129 }
4130 /// Repeat forever (builder), e.g. a pulsing indicator.
4131 #[must_use]
4132 pub fn repeat_forever(mut self, autoreverse: bool) -> Self {
4133 self.repeat = u32::MAX;
4134 self.autoreverse = autoreverse;
4135 self
4136 }
4137 #[inline]
4138 #[must_use]
4139 pub fn duration_secs(&self) -> f64 {
4140 f64::from(self.duration_ms) / 1000.0
4141 }
4142 #[inline]
4143 #[must_use]
4144 pub fn delay_secs(&self) -> f64 {
4145 f64::from(self.delay_ms) / 1000.0
4146 }
4147}
4148
4149#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
4150pub enum Role {
4151 #[default]
4152 None,
4153 Button,
4154 Toggle,
4155 Slider,
4156 TextInput,
4157 Heading(u8),
4158 Image,
4159 Meter,
4160 Group,
4161 /// A hierarchical tree container (docs/tree.md): `role="tree"`, `AXOutline`.
4162 Tree,
4163 /// One row of a tree: `role="treeitem"`, with level/expanded state where the platform
4164 /// carries them (docs/tree.md).
4165 TreeItem,
4166 /// One tab in a strip of peers (`role="tab"`, `AXTabButton`): the composed document
4167 /// strip's title buttons. Pair it with [`A11yProps::selected`] for the current one.
4168 Tab,
4169 /// The strip holding tabs (`role="tablist"`, `AXTabGroup`).
4170 TabList,
4171}
4172
4173impl Role {
4174 /// The a11y role a built-in piece kind reports natively, the audit's *expectation* when the
4175 /// user hasn't set an explicit `.role()`. Native controls already expose these, so Day records
4176 /// them for `a11y_audit` (§14.2) rather than overriding the widget; only canvas/custom pieces
4177 /// need Day to apply a role. Returns `None` for kinds with no inherent control role.
4178 #[must_use]
4179 pub fn for_kind(kind: PieceKind) -> Role {
4180 match kind {
4181 kinds::BUTTON => Role::Button,
4182 kinds::TOGGLE => Role::Toggle,
4183 kinds::SLIDER => Role::Slider,
4184 kinds::TEXT_FIELD => Role::TextInput,
4185 kinds::IMAGE => Role::Image,
4186 kinds::PROGRESS => Role::Meter,
4187 kinds::TREE => Role::Tree,
4188 _ => Role::None,
4189 }
4190 }
4191}
4192
4193#[derive(Clone, Debug, Default, PartialEq)]
4194pub struct A11yProps {
4195 pub label: Option<String>,
4196 pub hint: Option<String>,
4197 pub value: Option<String>,
4198 pub role: Role,
4199 pub identifier: Option<String>,
4200 pub hidden: bool,
4201 pub decorative: bool,
4202 /// Whether the element is the selected one among its peers (a tab, a row): the
4203 /// platform's selected state, read aloud as such. `None` leaves the widget's own answer.
4204 pub selected: Option<bool>,
4205}
4206
4207impl A11yProps {
4208 /// Merge another set of annotations onto this one: any field `other` sets (a `Some`, a
4209 /// non-`None` role, or a `true` flag) overrides ours; unset fields are left intact. Lets a
4210 /// node accumulate its `.a11y()`, `.id()`, and piece defaults into one stored result, so
4211 /// each `set_a11y` re-applies the full picture and `a11y_audit` has the complete expectation.
4212 pub fn merge(&mut self, other: &A11yProps) {
4213 if other.label.is_some() {
4214 self.label.clone_from(&other.label);
4215 }
4216 if other.hint.is_some() {
4217 self.hint.clone_from(&other.hint);
4218 }
4219 if other.value.is_some() {
4220 self.value.clone_from(&other.value);
4221 }
4222 if other.role != Role::None {
4223 self.role = other.role;
4224 }
4225 if other.identifier.is_some() {
4226 self.identifier.clone_from(&other.identifier);
4227 }
4228 self.hidden |= other.hidden;
4229 self.decorative |= other.decorative;
4230 if other.selected.is_some() {
4231 self.selected = other.selected;
4232 }
4233 }
4234
4235 /// The role to *expect* for a node of `kind` carrying these annotations: an explicit
4236 /// `.role()` wins, otherwise the kind's native default (`Role::for_kind`).
4237 #[must_use]
4238 pub fn resolved_role(&self, kind: PieceKind) -> Role {
4239 if self.role == Role::None {
4240 Role::for_kind(kind)
4241 } else {
4242 self.role
4243 }
4244 }
4245}
4246
4247/// A widget's actual native state, read back from the platform by `Toolkit::read_native`
4248/// (docs/testing.md): what the widget itself shows and reports, independently of Day's tree,
4249/// so `a11y_audit` and `assert_native` (§14.2) can diff it against Day's expectation.
4250///
4251/// Two groups. The accessibility fields (`role`, `label`, `value`, `identifier`) are read
4252/// together and `found` says whether they were: `found = false` means the backend cannot read
4253/// its accessibility tree, and the audit skips the node. Every other field is read on its own,
4254/// and `None` means "not read": the backend cannot read it, or it does not apply to this kind.
4255/// A reader never reports a field it did not take from the widget, so a `None` is a recorded
4256/// gap rather than a pass.
4257#[derive(Clone, Debug, Default, PartialEq)]
4258pub struct NativeSnapshot {
4259 /// The accessibility fields below were read.
4260 pub found: bool,
4261 /// The native role mapped back to Day's `Role` (best-effort).
4262 pub role: Role,
4263 /// The accessibility label the platform reports.
4264 pub label: Option<String>,
4265 /// The accessibility value the platform reports.
4266 pub value: Option<String>,
4267 /// The automation identifier, which Day sets from `.id()`.
4268 pub identifier: Option<String>,
4269 /// The text the widget displays: a label's string, a button's title, a text field's or
4270 /// text area's contents, without markup or mnemonic markers. `None` for a secure field
4271 /// that masks it.
4272 pub text: Option<String>,
4273 /// A slider's or progress indicator's value, in the range Day gave it.
4274 pub number: Option<f64>,
4275 /// A toggle's state, or a button's selected state (`ButtonProps::selected`).
4276 pub checked: Option<bool>,
4277 /// Whether the widget takes input.
4278 pub enabled: Option<bool>,
4279 /// Whether the widget is shown: not hidden itself, nor by an ancestor.
4280 pub visible: Option<bool>,
4281 /// The widget's frame in points, relative to the window's content area, origin top left.
4282 pub frame: Option<Rect>,
4283}
4284
4285// ---------------------------------------------------------------------------
4286// Canvas display list (§11): full op set lands with M8a; the types are v1.
4287// ---------------------------------------------------------------------------
4288
4289#[derive(Clone, Debug, PartialEq)]
4290pub enum Shape {
4291 Rect(Rect),
4292 RoundedRect(Rect, f64),
4293 Ellipse(Rect),
4294 /// Arc within `rect`'s inscribed ellipse; angles in degrees, 0 = +x axis, clockwise.
4295 Arc {
4296 rect: Rect,
4297 start_deg: f64,
4298 sweep_deg: f64,
4299 },
4300 Line(Point, Point),
4301 Polygon(Vec<Point>),
4302 /// An arbitrary path: curves, several contours, and a fill rule (docs/canvas.md).
4303 ///
4304 /// [`Shape::Polygon`] is the straight-line, single-contour special case, kept because it is
4305 /// what most drawing code wants and it encodes far more compactly.
4306 Path(Path),
4307}
4308
4309impl Shape {
4310 /// A rectangle rounded corner by corner (docs/canvas.md "Rounded corners"), as the simplest
4311 /// shape that draws it: a plain [`Shape::Rect`] when every corner is square, a
4312 /// [`Shape::RoundedRect`] (each toolkit's own rounded rectangle) when the corners agree, and a
4313 /// path ([`rounded_rect_segs`]) otherwise. The radii are [fitted](CornerRadii::fitted) first.
4314 ///
4315 /// ```
4316 /// use day_spec::{CornerRadii, Rect, Shape};
4317 ///
4318 /// // A bar standing on its axis: rounded on top, square where it meets the baseline.
4319 /// let bar = Shape::rounded_rect(Rect::new(0.0, 0.0, 20.0, 80.0), CornerRadii::top(6.0));
4320 /// std::assert_matches!(bar, Shape::Path(_));
4321 /// ```
4322 pub fn rounded_rect(rect: Rect, radii: CornerRadii) -> Shape {
4323 let r = radii.fitted(rect.size);
4324 if r.is_zero() || rect.size.width <= 0.0 || rect.size.height <= 0.0 {
4325 Shape::Rect(rect)
4326 } else if r.is_uniform() {
4327 Shape::RoundedRect(rect, r.top_left)
4328 } else {
4329 Shape::Path(Path {
4330 segs: rounded_rect_segs(rect, r),
4331 rule: FillRule::NonZero,
4332 })
4333 }
4334 }
4335
4336 /// The same shape moved by `(dx, dy)`.
4337 ///
4338 /// What a [`Stamp`] means by "the template translated by one point", and the one definition of
4339 /// it: a backend builds each copy of a batch with this rather than reaching for its own
4340 /// platform transform, so every toolkit stamps to the same coordinates.
4341 #[must_use]
4342 pub fn translated(&self, dx: f64, dy: f64) -> Shape {
4343 let r = |r: &Rect| {
4344 Rect::new(
4345 r.origin.x + dx,
4346 r.origin.y + dy,
4347 r.size.width,
4348 r.size.height,
4349 )
4350 };
4351 let p = |p: &Point| Point::new(p.x + dx, p.y + dy);
4352 match self {
4353 Shape::Rect(rect) => Shape::Rect(r(rect)),
4354 Shape::RoundedRect(rect, rad) => Shape::RoundedRect(r(rect), *rad),
4355 Shape::Ellipse(rect) => Shape::Ellipse(r(rect)),
4356 Shape::Arc {
4357 rect,
4358 start_deg,
4359 sweep_deg,
4360 } => Shape::Arc {
4361 rect: r(rect),
4362 start_deg: *start_deg,
4363 sweep_deg: *sweep_deg,
4364 },
4365 Shape::Line(a, b) => Shape::Line(p(a), p(b)),
4366 Shape::Polygon(pts) => Shape::Polygon(pts.iter().map(p).collect()),
4367 Shape::Path(path) => Shape::Path(Path {
4368 segs: path
4369 .segs
4370 .iter()
4371 .map(|seg| match seg {
4372 PathSeg::Move(a) => PathSeg::Move(p(a)),
4373 PathSeg::Line(a) => PathSeg::Line(p(a)),
4374 PathSeg::Quad(c, a) => PathSeg::Quad(p(c), p(a)),
4375 PathSeg::Cubic(c1, c2, a) => PathSeg::Cubic(p(c1), p(c2), p(a)),
4376 PathSeg::Close => PathSeg::Close,
4377 })
4378 .collect(),
4379 rule: path.rule,
4380 }),
4381 }
4382 }
4383
4384 /// The shape's bounding rectangle: the box gradient [`UnitPoint`]s resolve against.
4385 pub fn bounds(&self) -> Rect {
4386 match self {
4387 Shape::Rect(r) | Shape::RoundedRect(r, _) | Shape::Ellipse(r) => *r,
4388 Shape::Arc { rect, .. } => *rect,
4389 Shape::Line(a, b) => points_bounds(&[*a, *b]),
4390 Shape::Polygon(pts) => points_bounds(pts),
4391 Shape::Path(p) => p.bounds(),
4392 }
4393 }
4394}
4395
4396/// One step of a [`Path`]. Points are absolute, in the canvas's coordinate space.
4397#[derive(Clone, Copy, Debug, PartialEq)]
4398pub enum PathSeg {
4399 /// Start a new contour at this point.
4400 Move(Point),
4401 Line(Point),
4402 /// Quadratic bezier: one control point, then the end point.
4403 Quad(Point, Point),
4404 /// Cubic bezier: two control points, then the end point.
4405 Cubic(Point, Point, Point),
4406 /// Close the current contour back to its `Move`.
4407 Close,
4408}
4409
4410/// Which points count as inside when a path's contours overlap (docs/canvas.md).
4411///
4412/// This matters the moment a shape has a hole: the counter of an "o", a washer, a ring chart. It
4413/// is a property of the fill, so stroking ignores it.
4414#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
4415pub enum FillRule {
4416 /// Direction-sensitive: a hole needs its contour wound the opposite way. Every 2-D API's
4417 /// default, and what a font's glyph outlines assume.
4418 #[default]
4419 NonZero,
4420 /// Parity: any contour inside another cuts a hole regardless of winding. What PDF's `f*`
4421 /// operator and SVG's `fill-rule: evenodd` mean.
4422 EvenOdd,
4423}
4424
4425/// An arbitrary 2-D path: any number of contours, straight or curved, with a fill rule.
4426#[derive(Clone, Debug, PartialEq, Default)]
4427pub struct Path {
4428 pub segs: Vec<PathSeg>,
4429 pub rule: FillRule,
4430}
4431
4432impl Path {
4433 /// A conservative bounding box: the hull of every point including control points, which
4434 /// contains the true curve bounds (a bezier stays inside its control hull). Used only to
4435 /// resolve gradient unit points, where being slightly generous costs nothing and computing
4436 /// exact curve extrema would not.
4437 pub fn bounds(&self) -> Rect {
4438 let mut pts: Vec<Point> = Vec::with_capacity(self.segs.len() * 3);
4439 for seg in &self.segs {
4440 match seg {
4441 PathSeg::Move(p) | PathSeg::Line(p) => pts.push(*p),
4442 PathSeg::Quad(c, p) => pts.extend_from_slice(&[*c, *p]),
4443 PathSeg::Cubic(c1, c2, p) => pts.extend_from_slice(&[*c1, *c2, *p]),
4444 PathSeg::Close => {}
4445 }
4446 }
4447 points_bounds(&pts)
4448 }
4449}
4450
4451/// A radius for each corner of a rectangle, clockwise from the top left (docs/canvas.md "Rounded
4452/// corners"). The shape a bar in a chart wants (rounded at its value end, square against its
4453/// axis), a tab (rounded on top), or a card joined to its neighbor.
4454///
4455/// Radii are in points and never negative. [`CornerRadii::fitted`] shrinks them the way CSS
4456/// does when two radii on one side would overlap, which is what a caller animating a radius or
4457/// drawing a short bar needs to not think about.
4458#[derive(Clone, Copy, Debug, PartialEq, Default)]
4459pub struct CornerRadii {
4460 pub top_left: f64,
4461 pub top_right: f64,
4462 pub bottom_right: f64,
4463 pub bottom_left: f64,
4464}
4465
4466impl CornerRadii {
4467 /// The same radius on every corner: what [`Shape::RoundedRect`] draws.
4468 pub fn uniform(r: f64) -> Self {
4469 CornerRadii {
4470 top_left: r,
4471 top_right: r,
4472 bottom_right: r,
4473 bottom_left: r,
4474 }
4475 }
4476 /// Rounded along the top edge, square along the bottom: a bar standing on its axis.
4477 pub fn top(r: f64) -> Self {
4478 CornerRadii {
4479 top_left: r,
4480 top_right: r,
4481 ..Default::default()
4482 }
4483 }
4484 /// Rounded along the bottom edge: a bar hanging below its axis.
4485 pub fn bottom(r: f64) -> Self {
4486 CornerRadii {
4487 bottom_right: r,
4488 bottom_left: r,
4489 ..Default::default()
4490 }
4491 }
4492 /// Rounded along the left edge: a bar growing leftward from its axis.
4493 pub fn left(r: f64) -> Self {
4494 CornerRadii {
4495 top_left: r,
4496 bottom_left: r,
4497 ..Default::default()
4498 }
4499 }
4500 /// Rounded along the right edge: a bar growing rightward from its axis.
4501 pub fn right(r: f64) -> Self {
4502 CornerRadii {
4503 top_right: r,
4504 bottom_right: r,
4505 ..Default::default()
4506 }
4507 }
4508
4509 /// The four radii, clockwise from the top left.
4510 #[must_use]
4511 pub fn to_array(self) -> [f64; 4] {
4512 [
4513 self.top_left,
4514 self.top_right,
4515 self.bottom_right,
4516 self.bottom_left,
4517 ]
4518 }
4519
4520 /// Whether every corner is square.
4521 #[must_use]
4522 pub fn is_zero(self) -> bool {
4523 self.to_array().iter().all(|r| *r <= 0.0)
4524 }
4525
4526 /// Whether every corner has the same radius, so the rectangle is a [`Shape::RoundedRect`].
4527 #[must_use]
4528 #[expect(
4529 clippy::float_cmp,
4530 reason = "uniform means the four stored radii are exactly equal"
4531 )]
4532 pub fn is_uniform(self) -> bool {
4533 let [a, b, c, d] = self.to_array();
4534 a == b && b == c && c == d
4535 }
4536
4537 /// These radii made to fit a `size` rectangle, the rule CSS uses for `border-radius`: a
4538 /// negative or non-finite radius is square, and when the two radii along any side add up to
4539 /// more than that side, every radius is scaled down by the same factor until none overlap.
4540 /// Scaling all four together keeps the corners in proportion, where clamping each one alone
4541 /// would turn a pill into a lopsided shape.
4542 #[must_use]
4543 pub fn fitted(self, size: Size) -> Self {
4544 let clean = |r: f64| if r.is_finite() && r > 0.0 { r } else { 0.0 };
4545 let [tl, tr, br, bl] = self.to_array().map(clean);
4546 let (w, h) = (size.width.max(0.0), size.height.max(0.0));
4547 let factor = [(w, tl + tr), (w, bl + br), (h, tl + bl), (h, tr + br)]
4548 .into_iter()
4549 .filter(|(_, sum)| *sum > 0.0)
4550 .map(|(side, sum)| side / sum)
4551 .fold(1.0f64, f64::min);
4552 CornerRadii {
4553 top_left: tl * factor,
4554 top_right: tr * factor,
4555 bottom_right: br * factor,
4556 bottom_left: bl * factor,
4557 }
4558 }
4559}
4560
4561/// The point `angle_deg` round a circle: degrees, `0` = the +x axis, positive clockwise in device
4562/// space (y down), the convention [`Shape::Arc`] and every arc helper here use.
4563pub fn arc_point(center: Point, radius: f64, angle_deg: f64) -> Point {
4564 let a = angle_deg.to_radians();
4565 Point::new(center.x + radius * a.cos(), center.y + radius * a.sin())
4566}
4567
4568/// A circular arc as cubic beziers: `sweep_deg` of a circle of `radius` about `center`, from
4569/// `start_deg` ([`arc_point`]'s convention). The segments start *from* the arc's first point, which
4570/// the caller reaches itself (a move or a line); nothing for a zero or non-finite radius or sweep.
4571///
4572/// The arc is split into quarter turns at most, where a cubic tracks a circle best: the radial
4573/// error peaks at 2.7 × 10⁻⁴ of the radius, a quarter of a pixel on a circle a thousand points
4574/// across (docs/canvas.md "Paths"). The same beziers on every backend mean the same pixels on
4575/// every backend, which an arc op interpreted by nine rasterizers would not.
4576#[must_use]
4577pub fn arc_cubics(center: Point, radius: f64, start_deg: f64, sweep_deg: f64) -> Vec<PathSeg> {
4578 let (start, sweep) = (start_deg.to_radians(), sweep_deg.to_radians());
4579 if !radius.is_finite() || radius <= 0.0 || !sweep.is_finite() || sweep == 0.0 {
4580 return Vec::new();
4581 }
4582 let at = |a: f64| Point::new(center.x + radius * a.cos(), center.y + radius * a.sin());
4583 let steps = (sweep.abs() / std::f64::consts::FRAC_PI_2).ceil() as usize;
4584 let delta = sweep / steps as f64;
4585 // The exact control-handle length for a circular arc of this sweep. Negative for a negative
4586 // sweep, which is what turns the handles around for a counter-clockwise arc.
4587 let k = 4.0 / 3.0 * (delta / 4.0).tan() * radius;
4588 (0..steps)
4589 .map(|i| {
4590 let a = start + delta * i as f64;
4591 let b = a + delta;
4592 let (p0, p1) = (at(a), at(b));
4593 PathSeg::Cubic(
4594 Point::new(p0.x - k * a.sin(), p0.y + k * a.cos()),
4595 Point::new(p1.x + k * b.sin(), p1.y - k * b.cos()),
4596 p1,
4597 )
4598 })
4599 .collect()
4600}
4601
4602/// The closed contour of a rectangle rounded corner by corner, clockwise from the top left, with
4603/// the radii [fitted](CornerRadii::fitted) first. A square corner is a sharp point, not a
4604/// zero-length curve.
4605#[must_use]
4606pub fn rounded_rect_segs(rect: Rect, radii: CornerRadii) -> Vec<PathSeg> {
4607 let r = radii.fitted(rect.size);
4608 let (x0, y0) = (rect.origin.x, rect.origin.y);
4609 let (x1, y1) = (x0 + rect.size.width, y0 + rect.size.height);
4610 // Each corner: the point where its curve starts, then the quarter turn round its center.
4611 let corners = [
4612 (
4613 Point::new(x0 + r.top_left, y0 + r.top_left),
4614 r.top_left,
4615 180.0,
4616 ),
4617 (
4618 Point::new(x1 - r.top_right, y0 + r.top_right),
4619 r.top_right,
4620 270.0,
4621 ),
4622 (
4623 Point::new(x1 - r.bottom_right, y1 - r.bottom_right),
4624 r.bottom_right,
4625 0.0,
4626 ),
4627 (
4628 Point::new(x0 + r.bottom_left, y1 - r.bottom_left),
4629 r.bottom_left,
4630 90.0,
4631 ),
4632 ];
4633 let mut segs = Vec::with_capacity(14);
4634 for (i, (center, radius, start)) in corners.into_iter().enumerate() {
4635 let first = arc_point(center, radius, start);
4636 segs.push(if i == 0 {
4637 PathSeg::Move(first)
4638 } else {
4639 PathSeg::Line(first)
4640 });
4641 segs.extend(arc_cubics(center, radius, start, 90.0));
4642 }
4643 segs.push(PathSeg::Close);
4644 segs
4645}
4646
4647/// How a stroked line ends (docs/canvas.md). Names match PDF's `J`, SVG's `stroke-linecap`, and
4648/// every native 2-D API.
4649#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
4650pub enum LineCap {
4651 #[default]
4652 Butt,
4653 Round,
4654 Square,
4655}
4656
4657/// How two stroked segments meet (docs/canvas.md). Matches PDF's `j` and SVG's
4658/// `stroke-linejoin`.
4659#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
4660pub enum LineJoin {
4661 #[default]
4662 Miter,
4663 Round,
4664 Bevel,
4665}
4666
4667/// Everything about a stroke except its paint.
4668///
4669/// [`StrokeStyle::width`] and `From<f64>` keep the common "just a width" case a single
4670/// argument, so plain `stroke(shape, color, 2.0)` call sites read the same as they always did.
4671#[derive(Clone, Debug, PartialEq)]
4672pub struct StrokeStyle {
4673 pub width: f64,
4674 pub cap: LineCap,
4675 pub join: LineJoin,
4676 /// Ignored unless `join` is [`LineJoin::Miter`]. The 2-D convention: past this ratio of miter
4677 /// length to line width the join falls back to a bevel.
4678 pub miter_limit: f64,
4679 /// On/off run lengths, repeating. Empty means solid.
4680 pub dash: Vec<f64>,
4681 /// How far into the dash pattern the line starts.
4682 pub dash_phase: f64,
4683}
4684
4685impl Default for StrokeStyle {
4686 fn default() -> Self {
4687 // 10.0 is the miter limit PDF, PostScript, SVG and Cairo all default to.
4688 StrokeStyle {
4689 width: 1.0,
4690 cap: LineCap::Butt,
4691 join: LineJoin::Miter,
4692 miter_limit: 10.0,
4693 dash: Vec::new(),
4694 dash_phase: 0.0,
4695 }
4696 }
4697}
4698
4699impl StrokeStyle {
4700 /// A solid stroke of `width`, everything else default.
4701 #[must_use]
4702 pub fn width(width: f64) -> Self {
4703 StrokeStyle {
4704 width,
4705 ..Default::default()
4706 }
4707 }
4708 /// A dashed stroke: `dash` is on/off run lengths, repeating.
4709 #[must_use]
4710 pub fn dashed(width: f64, dash: Vec<f64>) -> Self {
4711 StrokeStyle {
4712 width,
4713 dash,
4714 ..Default::default()
4715 }
4716 }
4717 /// Rounded ends and joins, the shape a data line usually wants.
4718 #[must_use]
4719 pub fn round(width: f64) -> Self {
4720 StrokeStyle {
4721 width,
4722 cap: LineCap::Round,
4723 join: LineJoin::Round,
4724 ..Default::default()
4725 }
4726 }
4727 /// Is this the plain width-only stroke every pre-existing call site asks for? Backends use
4728 /// it to skip setting dash/cap/join state they would only have to set back.
4729 #[must_use]
4730 #[expect(
4731 clippy::float_cmp,
4732 reason = "10.0 is the stored default miter limit, compared as a sentinel"
4733 )]
4734 pub fn is_plain(&self) -> bool {
4735 self.cap == LineCap::Butt
4736 && self.join == LineJoin::Miter
4737 && self.dash.is_empty()
4738 && self.miter_limit == 10.0
4739 }
4740}
4741
4742impl From<f64> for StrokeStyle {
4743 fn from(width: f64) -> Self {
4744 StrokeStyle::width(width)
4745 }
4746}
4747
4748fn points_bounds(pts: &[Point]) -> Rect {
4749 let (mut x0, mut y0, mut x1, mut y1) = (f64::MAX, f64::MAX, f64::MIN, f64::MIN);
4750 for p in pts {
4751 x0 = x0.min(p.x);
4752 y0 = y0.min(p.y);
4753 x1 = x1.max(p.x);
4754 y1 = y1.max(p.y);
4755 }
4756 if pts.is_empty() {
4757 return Rect::ZERO;
4758 }
4759 Rect::new(x0, y0, x1 - x0, y1 - y0)
4760}
4761
4762/// A point in the unit space of a shape's bounding box: (0,0) = top-leading, (1,1) =
4763/// bottom-trailing. Gradient geometry is expressed in unit points so one paint value works for
4764/// any shape size (docs/shapes.md §3.2).
4765#[derive(Clone, Copy, Debug, PartialEq)]
4766pub struct UnitPoint {
4767 pub x: f64,
4768 pub y: f64,
4769}
4770
4771impl UnitPoint {
4772 #[must_use]
4773 pub const fn new(x: f64, y: f64) -> Self {
4774 UnitPoint { x, y }
4775 }
4776 pub const TOP: UnitPoint = UnitPoint::new(0.5, 0.0);
4777 pub const BOTTOM: UnitPoint = UnitPoint::new(0.5, 1.0);
4778 pub const LEADING: UnitPoint = UnitPoint::new(0.0, 0.5);
4779 pub const TRAILING: UnitPoint = UnitPoint::new(1.0, 0.5);
4780 pub const TOP_LEADING: UnitPoint = UnitPoint::new(0.0, 0.0);
4781 pub const TOP_TRAILING: UnitPoint = UnitPoint::new(1.0, 0.0);
4782 pub const BOTTOM_LEADING: UnitPoint = UnitPoint::new(0.0, 1.0);
4783 pub const BOTTOM_TRAILING: UnitPoint = UnitPoint::new(1.0, 1.0);
4784 pub const CENTER: UnitPoint = UnitPoint::new(0.5, 0.5);
4785
4786 /// Resolve to an absolute point within `rect`.
4787 pub fn resolve(&self, rect: Rect) -> Point {
4788 Point::new(
4789 rect.origin.x + self.x * rect.size.width,
4790 rect.origin.y + self.y * rect.size.height,
4791 )
4792 }
4793}
4794
4795/// A linear gradient (docs/shapes.md §3.2 / §7): color stops along the line from `start` to
4796/// `end`, both in the unit space of the filled shape's bounding box. Stops are
4797/// `(offset 0..=1, color)`, ascending.
4798#[derive(Clone, Debug, PartialEq)]
4799pub struct LinearGradient {
4800 pub start: UnitPoint,
4801 pub end: UnitPoint,
4802 pub stops: Vec<(f64, Color)>,
4803}
4804
4805impl LinearGradient {
4806 #[must_use]
4807 pub fn new(start: UnitPoint, end: UnitPoint, stops: Vec<(f64, Color)>) -> Self {
4808 LinearGradient { start, end, stops }
4809 }
4810 /// Top-to-bottom between two colors: the everyday sky/backdrop case.
4811 #[must_use]
4812 pub fn vertical(top: Color, bottom: Color) -> Self {
4813 LinearGradient::new(
4814 UnitPoint::TOP,
4815 UnitPoint::BOTTOM,
4816 vec![(0.0, top), (1.0, bottom)],
4817 )
4818 }
4819 /// Leading-to-trailing between two colors.
4820 #[must_use]
4821 pub fn horizontal(leading: Color, trailing: Color) -> Self {
4822 LinearGradient::new(
4823 UnitPoint::LEADING,
4824 UnitPoint::TRAILING,
4825 vec![(0.0, leading), (1.0, trailing)],
4826 )
4827 }
4828}
4829
4830/// A radial gradient (docs/shapes.md §3.2 / §7): color stops from `center` outward. Both the
4831/// center and the radius live in the unit space of the filled shape's bounding box, so the
4832/// gradient stretches into an ellipse when the bounds aren't square (the XAML relative-brush
4833/// behavior; the other backends reproduce it with a local matrix on a circular gradient). A
4834/// `radius` of `0.5` from the default center touches the edge midpoints of the bounds.
4835#[derive(Clone, Debug, PartialEq)]
4836pub struct RadialGradient {
4837 pub center: UnitPoint,
4838 pub radius: f64,
4839 pub stops: Vec<(f64, Color)>,
4840}
4841
4842impl RadialGradient {
4843 #[must_use]
4844 pub fn new(center: UnitPoint, radius: f64, stops: Vec<(f64, Color)>) -> Self {
4845 RadialGradient {
4846 center,
4847 radius,
4848 stops,
4849 }
4850 }
4851 /// Centered, edge-touching (radius 0.5) between two colors: the everyday glow case.
4852 #[must_use]
4853 pub fn centered(inner: Color, outer: Color) -> Self {
4854 RadialGradient::new(UnitPoint::CENTER, 0.5, vec![(0.0, inner), (1.0, outer)])
4855 }
4856}
4857
4858/// The payload of [`DrawOp::Stamp`]: one shape drawn at every position in `at`.
4859///
4860/// A scatter plot is the case this exists for. Drawn as individual ops, fifty thousand points are
4861/// fifty thousand `DrawOp`s, rebuilt, compared and cloned on every frame that re-records, before
4862/// a backend draws anything. As one `Stamp` they are one op and a flat array of coordinates, and
4863/// a backend can put every copy into one path and hand the rasterizer a single fill.
4864///
4865/// Every copy shares the shape, the size and the paint. Varying any of those means more than one
4866/// stamp: group by what varies, which for a chart is usually the series color.
4867#[derive(Clone, Debug, PartialEq)]
4868pub struct Stamp {
4869 /// The template, authored around the origin: each copy is this shape translated by one point.
4870 /// A 6-point dot is `Shape::Ellipse(Rect::new(-3.0, -3.0, 6.0, 6.0))`.
4871 pub shape: Shape,
4872 /// Where the copies go. Order is the drawing order, so later points paint over earlier ones.
4873 pub at: Vec<Point>,
4874 pub paint: Paint,
4875 /// `None` fills each copy; `Some` strokes it with this style.
4876 pub stroke: Option<StrokeStyle>,
4877}
4878
4879/// A fill source: a solid color, or a linear/radial gradient (docs/shapes.md §3.2; angular and
4880/// semantic tokens are later phases). `From<Color>` keeps every existing `fill(shape, color)`
4881/// call site compiling unchanged.
4882#[derive(Clone, Debug, PartialEq)]
4883pub enum Paint {
4884 Solid(Color),
4885 Linear(LinearGradient),
4886 Radial(RadialGradient),
4887}
4888
4889impl From<Color> for Paint {
4890 fn from(c: Color) -> Self {
4891 Paint::Solid(c)
4892 }
4893}
4894
4895impl From<LinearGradient> for Paint {
4896 fn from(g: LinearGradient) -> Self {
4897 Paint::Linear(g)
4898 }
4899}
4900
4901impl From<RadialGradient> for Paint {
4902 fn from(g: RadialGradient) -> Self {
4903 Paint::Radial(g)
4904 }
4905}
4906
4907/// Where `at` sits vertically. `Top`, `Middle` and `Bottom` are edges of the line box (ascent +
4908/// descent at the font's size, the box [`Toolkit::measure_text`] reports); `Baseline` is the
4909/// typographic baseline itself.
4910#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
4911pub enum TextVAlign {
4912 /// `at` is the top of the line box.
4913 #[default]
4914 Top,
4915 /// `at` is the vertical middle of the line box.
4916 Middle,
4917 /// `at` is the baseline itself: what every native 2-D text call takes, and what a run of labels
4918 /// sharing a line should align on rather than their individual boxes.
4919 Baseline,
4920 /// `at` is the bottom of the line box.
4921 Bottom,
4922}
4923
4924/// How canvas text hangs on its `at` point: one placement per axis (docs/canvas.md "Text").
4925///
4926/// Two axes rather than a list of named positions, because that is the shape of the problem and
4927/// of every native API underneath: `NSAttributedString` drawing, Pango extents,
4928/// `QFontMetricsF`, `Paint.Align`, `Canvas2D`'s `textAlign`/`textBaseline`. The alignment is done
4929/// by the backend, which is both cheaper and more accurate than doing it in app code: it already
4930/// has the laid-out metrics, where an app has to ask for them through
4931/// [`Toolkit::measure_text`] first.
4932///
4933/// [`TextAnchor::LEADING`] and [`TextAnchor::CENTERED`] name the two placements that used to be
4934/// this type's only variants.
4935#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
4936pub struct TextAnchor {
4937 /// The horizontal placement: the same three-way leading/center/trailing a wrapped label's
4938 /// lines take ([`props::TextAlign`]), because it is the same question with the same RTL rule.
4939 /// `Trailing` is what an axis label right-aligned against its axis wants, and the reason the
4940 /// horizontal axis is settable at all: emulating it in app code costs a
4941 /// [`Toolkit::measure_text`] call per label, where the backend already holds the width it is
4942 /// about to draw with.
4943 pub h: props::TextAlign,
4944 pub v: TextVAlign,
4945}
4946
4947impl TextAnchor {
4948 /// The top-leading corner of the line box, the default.
4949 pub const LEADING: TextAnchor = TextAnchor {
4950 h: props::TextAlign::Leading,
4951 v: TextVAlign::Top,
4952 };
4953 /// The center of the line box, both ways.
4954 pub const CENTERED: TextAnchor = TextAnchor {
4955 h: props::TextAlign::Center,
4956 v: TextVAlign::Middle,
4957 };
4958 /// The top-trailing corner of the line box.
4959 pub const TRAILING: TextAnchor = TextAnchor {
4960 h: props::TextAlign::Trailing,
4961 v: TextVAlign::Top,
4962 };
4963
4964 /// Where the text's top-leading corner goes, as an offset from `at`, given the line box this
4965 /// text measures to. The single definition of what an anchor means: every backend that draws
4966 /// in Rust calls this, and the C++/Java/JS shims repeat exactly this arithmetic.
4967 ///
4968 /// `height` is the line box (ascent + descent) and `ascent` the baseline's offset from its
4969 /// top, the two numbers [`TextMetrics`] carries.
4970 #[must_use]
4971 pub fn offset(self, width: f64, height: f64, ascent: f64) -> (f64, f64) {
4972 let dx = match self.h {
4973 props::TextAlign::Leading => 0.0,
4974 props::TextAlign::Center => -width / 2.0,
4975 props::TextAlign::Trailing => -width,
4976 };
4977 let dy = match self.v {
4978 TextVAlign::Top => 0.0,
4979 TextVAlign::Middle => -height / 2.0,
4980 TextVAlign::Baseline => -ascent,
4981 TextVAlign::Bottom => -height,
4982 };
4983 (dx, dy)
4984 }
4985
4986 /// The anchor as one number, for the numeric op stream the serializing backends share:
4987 /// `h * 4 + v`, so it still occupies the single slot the two-variant enum did.
4988 #[must_use]
4989 pub fn pack(self) -> f64 {
4990 f64::from(self.h as u8 * 4 + self.v as u8)
4991 }
4992
4993 /// Inverse of [`TextAnchor::pack`]. An unrecognized code answers the default rather than
4994 /// failing: a stream is only ever written by a matching encoder, and a drawing with text in
4995 /// the wrong corner beats one that panics inside a native draw callback.
4996 #[must_use]
4997 pub fn unpack(code: f64) -> TextAnchor {
4998 let c = code.round().clamp(0.0, 11.0) as u8;
4999 let h = match c / 4 {
5000 1 => props::TextAlign::Center,
5001 2 => props::TextAlign::Trailing,
5002 _ => props::TextAlign::Leading,
5003 };
5004 let v = match c % 4 {
5005 1 => TextVAlign::Middle,
5006 2 => TextVAlign::Baseline,
5007 3 => TextVAlign::Bottom,
5008 _ => TextVAlign::Top,
5009 };
5010 TextAnchor { h, v }
5011 }
5012}
5013
5014#[derive(Clone, Debug, PartialEq)]
5015pub enum DrawOp {
5016 Fill(Shape, Paint),
5017 /// Stroke `shape`. The paint may be a gradient, and [`StrokeStyle`] carries width, dash, cap
5018 /// and join; `Draw::stroke` builds the plain width-only case.
5019 Stroke(Shape, Paint, StrokeStyle),
5020 /// One line of text. `size` is absolute canvas points (no accessibility scale: canvas
5021 /// text is a label inside a drawing, docs/canvas.md); `font` picks the family, weight and
5022 /// slant, and its default is the platform's own UI face.
5023 Text {
5024 text: String,
5025 at: Point,
5026 size: f64,
5027 color: Color,
5028 anchor: TextAnchor,
5029 font: CanvasFont,
5030 },
5031 /// Draw one shape at many positions, the batched form of [`DrawOp::Fill`]/[`DrawOp::Stroke`]
5032 /// (docs/canvas.md "Stamping").
5033 ///
5034 /// Boxed because the payload is wider than the largest other op, and a bigger `DrawOp` would
5035 /// cost every op in every drawing, the exact thing this variant exists to stop paying.
5036 Stamp(Box<Stamp>),
5037 /// Draw an image into `rect` (docs/images.md).
5038 ///
5039 /// The source is a [`BitmapId`] and never bytes: a canvas re-records on every tracked read,
5040 /// so carrying a buffer here would hand the backend a megabyte to compare, and re-decode, on
5041 /// every frame. The app decodes once with `day::decode_image` and draws the handle.
5042 ///
5043 /// `opacity` multiplies the image's own alpha. A backend that cannot draw a bitmap at all
5044 /// draws nothing rather than a placeholder rectangle, the same way an unknown op is skipped.
5045 ///
5046 /// `source` is the region of the bitmap to draw, in the bitmap's own PIXELS (not points:
5047 /// [`BitmapInfo::scale`] says how many pixels make a point), `None` meaning the whole
5048 /// image. It is what lets one decoded sprite sheet serve every icon on a map: each draw
5049 /// picks its cell and scales it into `rect`. A region reaching outside the bitmap is clamped
5050 /// to it, never an error: the part inside draws where the mapping into `rect` puts it, and
5051 /// an empty intersection draws nothing. A backend without a sub-rect draw clips to `rect`
5052 /// and draws the whole image scaled so the region lands there ([`clamp_image_source`] is
5053 /// the shared arithmetic).
5054 Image {
5055 image: BitmapId,
5056 rect: Rect,
5057 opacity: f64,
5058 source: Option<Rect>,
5059 },
5060 /// Intersect the clip with `shape`; everything drawn afterwards is confined to it.
5061 ///
5062 /// Scoped by [`DrawOp::Save`]/[`DrawOp::Restore`], which is the only way to widen a clip
5063 /// again; every native 2-D context works this way, so there is no "unclip".
5064 Clip(Shape),
5065 /// Push the current transform + clip (§11, shapes). Backends map to save/restore of the
5066 /// native 2-D context; `Concat` multiplies an affine onto the CTM (shape rotate/scale/offset).
5067 Save,
5068 Restore,
5069 Concat(day_geometry::Affine),
5070}
5071
5072// ---------------------------------------------------------------------------
5073// Built-in piece descriptors: full props (realize) + sparse patches (update).
5074// One binding = one attribute = one patch value: sparseness by construction (§8.1).
5075// ---------------------------------------------------------------------------
5076
5077/// A semantic (logical) text style. Each maps to the platform's native text style where the
5078/// toolkit has one: `UIFont`/`NSFont.preferredFont(forTextStyle:)` on Apple (Dynamic Type), the
5079/// `*TextBlockStyle` resources on XAML. A Day app thus matches the OS's own typography and
5080/// inherits its accessibility text scaling with no extra work. Backends without semantic styles
5081/// (GTK/Qt/Android) approximate with sizes that still track the platform's text-scale /
5082/// font-scale accessibility setting.
5083///
5084/// The set mirrors SwiftUI `Font.TextStyle` (largest → smallest).
5085#[derive(Clone, Copy, Debug, PartialEq, Default)]
5086pub enum Font {
5087 LargeTitle,
5088 Title,
5089 Title2,
5090 Title3,
5091 Headline,
5092 Subheadline,
5093 #[default]
5094 Body,
5095 Callout,
5096 Footnote,
5097 Caption,
5098 Caption2,
5099 /// A custom point size. Backends scale it by the platform's accessibility text-scale (iOS via
5100 /// `UIFontMetrics`, Android via `sp`, GTK via text-scaling-factor) so it stays legible.
5101 System(f64),
5102 /// A bundled custom font by **family name**, at a point size (`Font::Custom("Pacifico",
5103 /// 24.0)`). The family must ship in the project's `fonts/` directory; `day build` stages the
5104 /// file into each platform's native font store and the backend registers it at startup
5105 /// (§18.4). The name is the family name baked into the font file (what Font Book /
5106 /// fontconfig report), not the file name. The size scales with the platform accessibility
5107 /// text-scale exactly like [`Font::System`]; weight/italic apply only where the family ships
5108 /// (or the platform synthesizes) such a face. An unknown family falls back to the system font
5109 /// of the same size, with a warning in the log.
5110 Custom(&'static str, f64),
5111}
5112
5113impl Font {
5114 /// A bundled custom font by **typed family**, at a point size, the checked form of
5115 /// [`Font::Custom`]. Pass a generated `res::fonts::…` constant
5116 /// (`Font::custom(res::fonts::pacifico, 24.0)`), which exists only if the family ships in the
5117 /// project's `fonts/` directory, so the font is guaranteed bundled. For a family name known
5118 /// another way, the untyped [`Font::Custom`] variant is the escape hatch.
5119 #[must_use]
5120 pub const fn custom(family: FontFamily, size: f64) -> Font {
5121 Font::Custom(family.as_str(), size)
5122 }
5123}
5124
5125/// Font weight, matching `UIFont.Weight` / SwiftUI `Font.Weight` (lightest → heaviest).
5126/// Ordered by heaviness, so backends can e.g. map `>= Semibold` to a synthesized bold face.
5127#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
5128pub enum FontWeight {
5129 UltraLight,
5130 Thin,
5131 Light,
5132 Regular,
5133 Medium,
5134 Semibold,
5135 Bold,
5136 Heavy,
5137 Black,
5138}
5139
5140impl FontWeight {
5141 /// Every rung, lightest first.
5142 pub const ALL: [FontWeight; 9] = [
5143 FontWeight::UltraLight,
5144 FontWeight::Thin,
5145 FontWeight::Light,
5146 FontWeight::Regular,
5147 FontWeight::Medium,
5148 FontWeight::Semibold,
5149 FontWeight::Bold,
5150 FontWeight::Heavy,
5151 FontWeight::Black,
5152 ];
5153
5154 /// The CSS / OpenType numeric weight (100 … 900), the one number every platform font API
5155 /// also speaks (`Typeface.create(base, weight, italic)`, `QFont::Weight`,
5156 /// `DWRITE_FONT_WEIGHT`, `OH_Drawing_FontWeight`), and what the canvas wire carries.
5157 #[must_use]
5158 pub const fn css(self) -> u16 {
5159 match self {
5160 FontWeight::UltraLight => 100,
5161 FontWeight::Thin => 200,
5162 FontWeight::Light => 300,
5163 FontWeight::Regular => 400,
5164 FontWeight::Medium => 500,
5165 FontWeight::Semibold => 600,
5166 FontWeight::Bold => 700,
5167 FontWeight::Heavy => 800,
5168 FontWeight::Black => 900,
5169 }
5170 }
5171
5172 /// The nearest rung to a CSS weight (ties round heavier, like CSS font matching); anything
5173 /// outside 100 … 900 clamps.
5174 #[must_use]
5175 pub fn from_css(n: u16) -> FontWeight {
5176 let n = n.clamp(100, 900);
5177 let idx = (usize::from(n) + 50) / 100; // 100 → 1 … 900 → 9
5178 FontWeight::ALL[idx.clamp(1, 9) - 1]
5179 }
5180
5181 /// The English face name for a rung ("Semibold"), for platforms whose enumeration names
5182 /// no face (see [`FontFace::synthesized_name`]).
5183 #[must_use]
5184 pub const fn name(self) -> &'static str {
5185 match self {
5186 FontWeight::UltraLight => "Ultra Light",
5187 FontWeight::Thin => "Thin",
5188 FontWeight::Light => "Light",
5189 FontWeight::Regular => "Regular",
5190 FontWeight::Medium => "Medium",
5191 FontWeight::Semibold => "Semibold",
5192 FontWeight::Bold => "Bold",
5193 FontWeight::Heavy => "Heavy",
5194 FontWeight::Black => "Black",
5195 }
5196 }
5197}
5198
5199/// One face a font family ships (docs/fonts.md): its display name ("Bold Italic"), weight and
5200/// slant. What [`FontFamilyInfo::faces`] lists and what a font menu's style picker offers.
5201#[derive(Clone, Debug, PartialEq, Eq)]
5202pub struct FontFace {
5203 pub name: String,
5204 pub weight: FontWeight,
5205 pub italic: bool,
5206}
5207
5208impl FontFace {
5209 /// A display name from weight + slant ("Semibold Italic") for platforms whose enumeration
5210 /// API names no face (Android's `fonts.xml`, the CSS generic families).
5211 #[must_use]
5212 pub fn synthesized_name(weight: FontWeight, italic: bool) -> String {
5213 if italic {
5214 format!("{} Italic", weight.name())
5215 } else {
5216 weight.name().to_string()
5217 }
5218 }
5219}
5220
5221/// A platform (or bundled) font family and the faces it can draw canvas text in
5222/// ([`Toolkit::font_families`], docs/fonts.md).
5223#[derive(Clone, Debug, PartialEq, Eq)]
5224pub struct FontFamilyInfo {
5225 pub family: String,
5226 pub faces: Vec<FontFace>,
5227}
5228
5229impl FontFamilyInfo {
5230 /// Whether any face is [`FontWeight::Bold`] or heavier.
5231 #[must_use]
5232 pub fn has_bold(&self) -> bool {
5233 self.faces.iter().any(|f| f.weight >= FontWeight::Bold)
5234 }
5235 /// Whether any face is italic.
5236 #[must_use]
5237 pub fn has_italic(&self) -> bool {
5238 self.faces.iter().any(|f| f.italic)
5239 }
5240 /// The nearest face: an exact slant match preferred, then the smallest weight distance
5241 /// (ties go heavier, like CSS font matching). `None` only when the family lists no faces.
5242 #[must_use]
5243 pub fn face_for(&self, weight: FontWeight, italic: bool) -> Option<&FontFace> {
5244 let want = i32::from(weight.css());
5245 self.faces.iter().min_by_key(|f| {
5246 let slant = i32::from(f.italic != italic);
5247 let dist = (i32::from(f.weight.css()) - want).abs();
5248 // Heavier wins a tie: subtracting the bool sorts the heavier face first.
5249 (slant, dist, i32::from(i32::from(f.weight.css()) < want))
5250 })
5251 }
5252}
5253
5254/// Single-line text measurement in canvas points ([`Toolkit::measure_text`], docs/fonts.md).
5255///
5256/// Two boxes, and the difference between them matters. `width`/`height` is the **line box**: the
5257/// typographic slot the text occupies, the same for every string in a face at a size, and what
5258/// [`TextAnchor`] positions. [`ink`](TextMetrics::ink) is the **ink box**: where the glyphs
5259/// put marks. A line of digits leaves the descender space of its line box empty, so the
5260/// two disagree, and which one is wanted depends on the question: laying text out in a column
5261/// wants the line box, and centering it on a rule or keeping it clear of a mark wants the ink.
5262#[derive(Clone, Copy, Debug, PartialEq)]
5263pub struct TextMetrics {
5264 /// The advance width of the whole string.
5265 pub width: f64,
5266 /// The line box: ascent + descent at this size (plus the line gap where the engine reports
5267 /// one), which is the box [`TextAnchor`] positions.
5268 pub height: f64,
5269 /// The baseline's offset from the top of the line box.
5270 pub ascent: f64,
5271 /// The face's cap height at this size: baseline to the top of a capital.
5272 ///
5273 /// A property of the font, not of this string, reported here because it is what optical
5274 /// centering needs and asking for it separately would be a second measurement. Text made of
5275 /// capitals and digits looks centered on a rule when its cap box straddles it, not its line
5276 /// box: the line box reserves descender room that digits never use, so centering by it sits
5277 /// every label a little low. The cap middle is `ascent - cap_height / 2.0` below the line
5278 /// box's top.
5279 pub cap_height: f64,
5280 /// The ink box, the tight bounds of what is drawn, with its origin relative to the line
5281 /// box's top-leading corner, so `ink.origin` is where the marks start inside the slot.
5282 ///
5283 /// Empty (zero-size) for text that draws nothing, a space included. Where a toolkit cannot
5284 /// report ink it answers the whole line box, which is a superset: an overlap test against it
5285 /// can only be too cautious, never wrong.
5286 pub ink: Rect,
5287}
5288
5289impl TextMetrics {
5290 /// The portable guess `day::measure_text` falls back to when a toolkit cannot measure:
5291 /// 0.6 × size per character, 1.2 × size tall, the baseline at 0.9 × size, caps at 0.7 × size.
5292 /// Its ink is the whole line box, the safe direction to be wrong in (see
5293 /// [`ink`](TextMetrics::ink)).
5294 #[must_use]
5295 pub fn approximate(text: &str, size: f64) -> TextMetrics {
5296 let (width, height) = (0.6 * size * text.chars().count() as f64, 1.2 * size);
5297 TextMetrics {
5298 width,
5299 height,
5300 ascent: 0.9 * size,
5301 cap_height: 0.7 * size,
5302 ink: Rect::new(0.0, 0.0, width, height),
5303 }
5304 }
5305
5306 /// Read the eight-slot form the serializing backends (qt, xaml, arkui, web) fill across their
5307 /// C ABI: advance, line height, ascent, cap height, then the ink box relative to the line
5308 /// box's top-leading corner. One definition so four shims cannot drift from each other.
5309 #[must_use]
5310 pub fn from_slots(out: &[f64; 8]) -> TextMetrics {
5311 TextMetrics {
5312 width: out[0],
5313 height: out[1],
5314 ascent: out[2],
5315 cap_height: out[3],
5316 ink: Rect::new(out[4], out[5], out[6], out[7]),
5317 }
5318 }
5319
5320 /// The line box's top-leading corner, given a baseline-relative measurement, the shape every
5321 /// backend's metrics come in. `ink_*` are relative to the drawing origin on the baseline
5322 /// (`ink_top` negative above it), the convention Skia, Core Text and Qt all report in.
5323 #[must_use]
5324 pub fn from_baseline(
5325 width: f64,
5326 ascent: f64,
5327 descent: f64,
5328 cap_height: f64,
5329 ink: Rect,
5330 ) -> TextMetrics {
5331 TextMetrics {
5332 width,
5333 height: ascent + descent,
5334 ascent,
5335 cap_height,
5336 // Baseline-relative to line-box-relative is one shift by the ascent.
5337 ink: Rect::new(
5338 ink.origin.x,
5339 ink.origin.y + ascent,
5340 ink.size.width,
5341 ink.size.height,
5342 ),
5343 }
5344 }
5345}
5346
5347/// What canvas text is drawn with beyond its size (docs/canvas.md "Text"): a family, a weight and
5348/// a slant. The default is the platform's own UI face, regular, upright, which is what every
5349/// backend drew before the field existed, so a default font encodes to nothing on the wire.
5350#[derive(Clone, Debug, PartialEq, Eq, Default)]
5351pub struct CanvasFont {
5352 /// A platform or bundled family name (as [`Toolkit::font_families`] lists it); `None` =
5353 /// the platform's default UI face.
5354 pub family: Option<String>,
5355 /// `None` = Regular.
5356 pub weight: Option<FontWeight>,
5357 pub italic: bool,
5358}
5359
5360impl CanvasFont {
5361 /// The family name to send over the wire, empty for the default.
5362 #[must_use]
5363 pub fn family_str(&self) -> &str {
5364 self.family.as_deref().unwrap_or("")
5365 }
5366 /// The CSS weight to send over the wire, 0 for the default.
5367 pub fn css_weight(&self) -> u16 {
5368 self.weight.map_or(0, FontWeight::css)
5369 }
5370}
5371
5372/// Field separator inside one family of the shim-side font list ([`parse_font_list`]).
5373pub const FONT_LIST_FIELD: char = '\u{1f}';
5374/// Family separator of the shim-side font list ([`parse_font_list`]).
5375pub const FONT_LIST_FAMILY: char = '\u{1e}';
5376
5377/// Decode the text a non-Rust font enumerator hands back (the Qt, XAML and ArkUI shims, the
5378/// Android bridge, the web shim all produce this one format): families separated by U+001E;
5379/// inside a family, U+001F-separated fields: the family name, then one (name, CSS weight,
5380/// italic `0`/`1`) triple per face. Tolerant: a malformed face or family is skipped, an empty
5381/// face name is synthesized from its weight and slant, and a family with no faces is kept
5382/// with none (the caller decides what a face-less family means).
5383pub fn parse_font_list(s: &str) -> Vec<FontFamilyInfo> {
5384 let mut out = Vec::new();
5385 for fam in s.split(FONT_LIST_FAMILY) {
5386 let mut fields = fam.split(FONT_LIST_FIELD);
5387 let Some(family) = fields.next().map(str::trim).filter(|f| !f.is_empty()) else {
5388 continue;
5389 };
5390 let rest: Vec<&str> = fields.collect();
5391 let mut faces = Vec::new();
5392 for face in rest.chunks(3) {
5393 let [name, weight, italic] = face else {
5394 continue;
5395 };
5396 let Ok(weight) = weight.trim().parse::<u16>() else {
5397 continue;
5398 };
5399 let weight = FontWeight::from_css(weight);
5400 let italic = matches!(italic.trim(), "1" | "true");
5401 let name = name.trim();
5402 let name = if name.is_empty() {
5403 FontFace::synthesized_name(weight, italic)
5404 } else {
5405 name.to_string()
5406 };
5407 if !faces
5408 .iter()
5409 .any(|f: &FontFace| f.weight == weight && f.italic == italic)
5410 {
5411 faces.push(FontFace {
5412 name,
5413 weight,
5414 italic,
5415 });
5416 }
5417 }
5418 out.push(FontFamilyInfo {
5419 family: family.to_string(),
5420 faces,
5421 });
5422 }
5423 out
5424}
5425
5426/// The full font descriptor a label carries: a semantic (or custom) [`Font`] style plus an optional
5427/// weight override, an italic flag, and the tabular-figures request. Backends resolve this to one
5428/// native font.
5429#[derive(Clone, Copy, Debug, PartialEq)]
5430pub struct FontSpec {
5431 pub style: Font,
5432 pub weight: Option<FontWeight>,
5433 pub italic: bool,
5434 /// Ask for tabular (monospaced) figures: every digit takes the same advance, so a number that
5435 /// changes stops changing width.
5436 ///
5437 /// In a proportional system font `1` is narrower than `8`, so a readout beside a slider
5438 /// wobbles as the value changes even when the digit count is fixed. Every platform ships this
5439 /// as a font feature, so Day asks for the platform's own rather than substituting a monospaced
5440 /// family: the text keeps the system face, and only the digits change metrics.
5441 ///
5442 /// Reserving space (`Decorate::reserving`) and tabular figures solve the two halves of the
5443 /// same problem (reservation stops the box resizing, tabular stops the glyphs shifting inside
5444 /// it), and a numeric readout usually wants both.
5445 ///
5446 /// This rides the existing label realize/patch path rather than adding a Toolkit method, so it
5447 /// is not a backend duty and has no duty-matrix row. Every in-tree backend honors it: AppKit
5448 /// and UIKit re-pick the system face (`monospacedDigitSystemFont`), GTK and Qt and ArkUI set
5449 /// the `tnum` OpenType feature, Android `setFontFeatureSettings`, XAML the `Typography`
5450 /// `NumeralAlignment` property, and web-dom `font-variant-numeric`. A font with no `tnum` table,
5451 /// or an SDK predating the attribute, renders the stock proportional figures.
5452 pub tabular: bool,
5453 /// Ask for the platform's monospaced face at this style's size, what `` `code` `` in a
5454 /// markdown run needs (docs/text-runs.md).
5455 ///
5456 /// A flag rather than a `Font::Monospace(pt)` variant so the run keeps its semantic style:
5457 /// code inside a `Footnote` paragraph must stay footnote-sized and keep tracking the
5458 /// reader's text-size setting, which a fixed point size would throw away.
5459 ///
5460 /// Like [`Self::tabular`], this rides the label realize/patch path and is not a backend duty:
5461 /// every toolkit has a system monospace face (`monospacedSystemFont`, Pango's `monospace`
5462 /// family, `QFontDatabase::FixedFont`, `Typeface.MONOSPACE`, CSS `monospace`).
5463 pub monospace: bool,
5464 /// Multiply the resolved size. `1.0` is the style's own size, `1.6` a heading against a body
5465 /// paragraph, `0.8` a caption inside one.
5466 ///
5467 /// Relative rather than an absolute point size, so that an editor's font-size control can
5468 /// move this while text a person reads for an hour still tracks the platform's
5469 /// accessibility text-scale. `Font::System(pt)` remains the absolute escape hatch, and it
5470 /// is where an imported document's `\fs28` or `font-size: 14px` lands (docs/texteditor.md):
5471 /// faithful to the file, and no longer responsive to the reader, which is the trade that
5472 /// form makes.
5473 ///
5474 /// Three toolkits take it directly (`GtkTextTag::scale`, Android's `RelativeSizeSpan`, CSS
5475 /// `em`); the rest multiply it into the size they already compute.
5476 pub scale: f64,
5477}
5478
5479impl Default for FontSpec {
5480 fn default() -> Self {
5481 FontSpec {
5482 style: Font::Body,
5483 weight: None,
5484 italic: false,
5485 tabular: false,
5486 monospace: false,
5487 scale: 1.0,
5488 }
5489 }
5490}
5491
5492impl From<Font> for FontSpec {
5493 fn from(style: Font) -> Self {
5494 FontSpec {
5495 style,
5496 ..FontSpec::default()
5497 }
5498 }
5499}
5500
5501impl FontSpec {
5502 /// The plain descriptor for a style: no weight override, no italic, scale 1.0.
5503 pub fn new(style: Font) -> Self {
5504 FontSpec::from(style)
5505 }
5506 /// This descriptor at a different relative size (see [`FontSpec::scale`]).
5507 #[must_use]
5508 pub fn scaled(mut self, scale: f64) -> Self {
5509 self.scale = scale;
5510 self
5511 }
5512 /// The point size this descriptor resolves to, given the size the platform assigns its
5513 /// semantic style. The one place `scale` is applied, so every backend's font resolver
5514 /// multiplies the same way.
5515 #[must_use]
5516 pub fn resolved_points(&self, style_points: f64) -> f64 {
5517 let base = match self.style {
5518 Font::System(pt) | Font::Custom(_, pt) => pt,
5519 _ => style_points,
5520 };
5521 (base * self.scale).max(1.0)
5522 }
5523}
5524
5525/// One styled span of a label's text (docs/text-runs.md).
5526///
5527/// `range` is a byte range into the label's `text`. Bytes, not chars: every backend that takes a
5528/// structured attributed string wants UTF-16 or byte offsets, `str` slicing is byte-based, and a
5529/// char count would have to be converted at every boundary. Ranges must be non-overlapping and
5530/// ascending; a gap between them is unstyled text, drawn with the label's own font.
5531///
5532/// A run says only what differs. `font` is the whole descriptor rather than a delta because a
5533/// bold run inside a Body paragraph is `FontSpec { style: Body, weight: Some(Bold), .. }`. The
5534/// style has to travel with the weight or the run loses its semantic size.
5535#[derive(Clone, Debug, PartialEq)]
5536pub struct TextRun {
5537 pub range: std::ops::Range<usize>,
5538 pub font: FontSpec,
5539 pub color: Option<Color>,
5540 /// A highlight painted behind the glyphs. Every native text editor carries this attribute
5541 /// (docs/texteditor.md), and search hits and review comments are the two things an app is
5542 /// asked for the moment it has styled text at all.
5543 pub background: Option<Color>,
5544 /// A line under the text.
5545 pub underline: Underline,
5546 /// A line through the text. Separate from `FontSpec` because it is a decoration, not a face:
5547 /// no platform expresses it by picking a different font.
5548 pub strikethrough: bool,
5549 /// Makes this run a link to the given target. Rendering it is [`Cap::TextRuns`]; making it
5550 /// activatable is [`Cap::TextLinks`], which is a smaller set (see the docs).
5551 pub link: Option<String>,
5552}
5553
5554impl Default for TextRun {
5555 fn default() -> Self {
5556 TextRun {
5557 range: 0..0,
5558 font: FontSpec::default(),
5559 color: None,
5560 background: None,
5561 underline: Underline::None,
5562 strikethrough: false,
5563 link: None,
5564 }
5565 }
5566}
5567
5568impl TextRun {
5569 /// A run that only changes the font, the common case for emphasis.
5570 #[must_use]
5571 pub fn font(range: std::ops::Range<usize>, font: FontSpec) -> Self {
5572 TextRun {
5573 range,
5574 font,
5575 ..TextRun::default()
5576 }
5577 }
5578
5579 /// This run's attributes without its range: what a selection's style is compared against
5580 /// and what an editor's toolbar toggles (docs/texteditor.md).
5581 #[must_use]
5582 pub fn style(&self) -> RunStyle {
5583 RunStyle {
5584 font: self.font,
5585 color: self.color,
5586 background: self.background,
5587 underline: self.underline,
5588 strikethrough: self.strikethrough,
5589 link: self.link.clone(),
5590 }
5591 }
5592
5593 /// A run of `style` over `range`.
5594 #[must_use]
5595 pub fn styled(range: std::ops::Range<usize>, style: RunStyle) -> Self {
5596 TextRun {
5597 range,
5598 font: style.font,
5599 color: style.color,
5600 background: style.background,
5601 underline: style.underline,
5602 strikethrough: style.strikethrough,
5603 link: style.link,
5604 }
5605 }
5606}
5607
5608/// Serialize a label's text + runs as markup, for the two backends whose text widgets take a
5609/// string in their own dialect rather than a structured attributed string: GTK (Pango markup)
5610/// and Qt (its HTML subset). Shared so the escaping is written and tested once: a translated
5611/// string containing `&` or `<` corrupts the whole label otherwise, and it will be a translated
5612/// string that finds the bug.
5613///
5614/// `dialect` decides the spelling: Pango wants `<span foreground="#rrggbb"
5615/// font_family="monospace">`, Qt wants `<span style="color:#rrggbb">` with `<code>`. Both accept
5616/// `<b>`, `<i>`, `<u>`, `<s>` and `<a href>`, which is why one function can serve them.
5617///
5618/// `base_points` is the size the label itself resolved to. Only a relative-size run
5619/// ([`FontSpec::scale`]) needs it, and only in the Qt dialect: Pango markup takes a percentage
5620/// directly, while Qt's CSS subset understands `pt` and `px` and ignores `%`.
5621#[must_use]
5622pub fn runs_to_markup(
5623 text: &str,
5624 runs: &[TextRun],
5625 dialect: MarkupDialect,
5626 base_points: f64,
5627) -> String {
5628 let mut out = String::with_capacity(text.len() + runs.len() * 24);
5629 let mut at = 0usize;
5630 for r in runs {
5631 // Skip a run whose range does not address this string, without advancing `at`: dropping
5632 // the run loses styling, but advancing past it would drop the rest of the sentence.
5633 // `runs_are_valid` rejects these upstream; this keeps the failure cheap if one slips by.
5634 let Some(styled) = text.get(r.range.clone()) else {
5635 continue;
5636 };
5637 if r.range.start > at
5638 && let Some(plain) = text.get(at..r.range.start)
5639 {
5640 escape_markup_in(plain, &mut out, dialect);
5641 }
5642 open_run(r, dialect, base_points, &mut out);
5643 escape_markup_in(styled, &mut out, dialect);
5644 close_run(r, dialect, &mut out);
5645 at = r.range.end;
5646 }
5647 if let Some(tail) = text.get(at..) {
5648 escape_markup_in(tail, &mut out, dialect);
5649 }
5650 out
5651}
5652
5653impl Symbol {
5654 /// A 24×24 outline path for this symbol, Day's own drawing of it.
5655 ///
5656 /// The platform's icon comes first on every backend that has one (SF Symbols, the freedesktop
5657 /// icon theme, Fluent's glyph font). This is the fallback for when that lookup finds nothing,
5658 /// which is not an edge case: `view-filter-symbolic` exists on a GNOME desktop and nowhere
5659 /// else, so a GTK or Qt app run off that desktop drew a toolbar item with no icon at all.
5660 /// One table here means the same fallback shape everywhere instead of a gap per platform.
5661 ///
5662 /// `None` for a variant with no drawing yet: `Symbol` is `#[non_exhaustive]`, so a new one
5663 /// degrades to a label rather than failing to compile.
5664 #[must_use]
5665 pub fn outline_path(self) -> Option<&'static str> {
5666 use Symbol as S;
5667 // The wildcard is unreachable today (every variant is drawn below) and it is here for
5668 // the next one, which should degrade to a label rather than fail to compile.
5669 #[allow(unreachable_patterns)]
5670 Some(match self {
5671 S::Add => "M11 5h2v6h6v2h-6v6h-2v-6H5v-2h6z",
5672 S::Remove => "M5 11h14v2H5z",
5673 S::Delete => "M9 3h6l1 2h4v2H4V5h4zM6 8h12l-1 13H7z",
5674 S::Edit => {
5675 "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"
5676 }
5677 S::New => "M13 2H6v20h12V7h-5zm2 .5L19.5 7H15z",
5678 S::Open | S::Folder => "M2 5h7l2 2h11v12H2z",
5679 S::Save => "M3 3h13l5 5v13H3zm5 0h7v6H8zm-1 11h10v7H7z",
5680 S::Print => "M7 3h10v4H7zM4 8h16v8h-3v6H7v-6H4z",
5681 S::Refresh => "M12 4V1L8 5l4 4V6a6 6 0 1 1-6 6H4a8 8 0 1 0 8-8z",
5682 S::Search => {
5683 "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"
5684 }
5685 S::Share => "M12 3l5 5h-3v7h-4V8H7zM5 17h14v4H5z",
5686 // An eight-tooth gear, round about the center (radius 10 at the teeth, 7.6 at the
5687 // roots) with a 3.2 hole: square in its box, so it sits in a row's 24-point icon
5688 // slot at the same size as its neighbors.
5689 S::Settings => {
5690 "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"
5691 }
5692 S::Info => "M12 2a10 10 0 1 0 0 20 10 10 0 0 0 0-20m-1 5h2v2h-2zm0 4h2v6h-2z",
5693 S::Star => {
5694 "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"
5695 }
5696 S::Bookmark => "M6 2h12v20l-6-4-6 4z",
5697 S::Back => "M15.4 5.4L14 4l-8 8 8 8 1.4-1.4L8.8 12z",
5698 S::Forward => "M8.6 5.4L10 4l8 8-8 8-1.4-1.4L15.2 12z",
5699 S::Up => "M5.4 15.4L4 14l8-8 8 8-1.4 1.4L12 8.8z",
5700 S::Down => "M5.4 8.6L4 10l8 8 8-8-1.4-1.4L12 15.2z",
5701 S::Home => "M12 3l9 8h-3v10h-5v-6h-2v6H6V11H3z",
5702 S::Sidebar => "M3 4h18v16H3zm2 2v12h4V6zm6 0v12h8V6z",
5703 S::Filter => "M3 5h18l-7 8v6l-4 2v-8z",
5704 S::Sort => "M8 4v12H4l4 4 4-4H10V4zM14 6h7v2h-7zm0 4h5v2h-5zm0 4h3v2h-3z",
5705 S::More => {
5706 "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"
5707 }
5708 S::Play => "M8 5l11 7-11 7z",
5709 S::Pause => "M7 5h3v14H7zm7 0h3v14h-3z",
5710 S::Stop => "M6 6h12v12H6z",
5711 S::Camera => {
5712 "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"
5713 }
5714 S::Code => {
5715 "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"
5716 }
5717 S::Light => {
5718 "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"
5719 }
5720 S::Dark => "M12 3a9 9 0 1 0 9 9 7 7 0 0 1-9-9",
5721 // "Automatic": the half-filled circle every platform uses: the left half solid, the
5722 // right half an outline, which `evenodd` below turns into the ring it should be.
5723 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",
5724 S::ZoomIn => {
5725 "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"
5726 }
5727 S::ZoomOut => {
5728 "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"
5729 }
5730 // The ZoomIn lens with a numeral 1 in it, "back to actual size".
5731 S::ZoomReset => {
5732 "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"
5733 }
5734 S::Undo => "M12 5V2L7 7l5 5V9a5 5 0 1 1 0 10H8v2h4a7 7 0 0 0 0-14z",
5735 S::Redo => "M12 5V2l5 5-5 5V9a5 5 0 1 0 0 10h4v2h-4a7 7 0 0 1 0-14z",
5736 S::Copy => "M8 2h10v14H8zM4 6h2v14h12v2H4z",
5737 S::Cut => {
5738 "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"
5739 }
5740 S::Paste => "M9 2h6v2h3v18H6V4h3zm0 2v2h6V4z",
5741 S::Mail => "M2 5h20v14H2zm2 3.2V17h16V8.2l-8 5z",
5742 S::Document => "M14 2H6v20h12V6zm.5.8L17.2 6H14.5z",
5743 S::Check => "M9 16.2L4.8 12l-1.4 1.4L9 19 21 7l-1.4-1.4z",
5744 S::Close => {
5745 "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"
5746 }
5747 S::Warning => "M12 2l10 19H2zm-1 7h2v6h-2zm0 8h2v2h-2z",
5748 // Shape outlines, stroked as a 2-unit band (an even-odd ring), so they read as
5749 // outlines at any size rather than filled blocks.
5750 S::Rectangle => "M3 5h18v14H3zm2 2v10h14V7z",
5751 S::Oval => {
5752 "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"
5753 }
5754 // A circular ring (even-odd: outer disc minus inner) and its filled twin.
5755 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",
5756 S::CircleFilled => "M12 4a8 8 0 1 0 0 16 8 8 0 0 0 0-16z",
5757 S::Line => "M4.7 17.9l13.2-13.2 1.4 1.4L6.1 19.3z",
5758 // Group: a solid square stacked on another (the visible L of the back one);
5759 // Ungroup: the same two squares pulled apart.
5760 S::Group => "M8 4h12v12h-4V8H8zM4 8h12v12H4z",
5761 S::Ungroup => "M3 3h8v8H3zM13 13h8v8h-8z",
5762 // A crosshair: a dot in a ring with four ticks, the even-odd fill leaving the gap
5763 // between dot and ring empty.
5764 S::Location => {
5765 "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"
5766 }
5767 // `Symbol` is `#[non_exhaustive]`: a variant added upstream draws nothing here rather
5768 // than failing to compile, and its item keeps its label.
5769 _ => return None,
5770 })
5771 }
5772
5773 /// [`Self::outline_path`] wrapped as a standalone SVG document.
5774 #[must_use]
5775 pub fn outline_svg(self) -> Option<String> {
5776 self.outline_path().map(|d| {
5777 format!(
5778 "<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 24 24\">\
5779 <path fill-rule=\"evenodd\" d=\"{d}\"/></svg>"
5780 )
5781 })
5782 }
5783}
5784
5785/// Which markup dialect [`runs_to_markup`] should emit.
5786#[derive(Clone, Copy, Debug, PartialEq, Eq)]
5787pub enum MarkupDialect {
5788 /// Pango markup (GTK).
5789 Pango,
5790 /// Qt's rich-text HTML subset.
5791 QtHtml,
5792}
5793
5794/// XML-escape a run of plain text into `out`. `&` first, or the escapes escape each other.
5795///
5796/// Newlines are dialect-specific. Pango lays a literal `\n` out as a line break, but Qt's rich
5797/// text is HTML, where any run of whitespace collapses to one space, which silently ran a
5798/// two-paragraph body together into a single block. `<br>` is what says "break here" in HTML, so
5799/// the same string wraps the same way on both.
5800fn escape_markup_in(s: &str, out: &mut String, dialect: MarkupDialect) {
5801 for c in s.chars() {
5802 match c {
5803 '&' => out.push_str("&"),
5804 '<' => out.push_str("<"),
5805 '>' => out.push_str(">"),
5806 '"' => out.push_str("""),
5807 '\'' => out.push_str("'"),
5808 '\n' if dialect == MarkupDialect::QtHtml => out.push_str("<br>"),
5809 _ => out.push(c),
5810 }
5811 }
5812}
5813
5814/// [`escape_markup_in`] for the URL slot, where a newline cannot appear.
5815fn escape_markup(s: &str, out: &mut String) {
5816 escape_markup_in(s, out, MarkupDialect::Pango);
5817}
5818
5819fn hex(c: Color) -> String {
5820 format!(
5821 "#{:02x}{:02x}{:02x}",
5822 (c.r.clamp(0.0, 1.0) * 255.0) as u8,
5823 (c.g.clamp(0.0, 1.0) * 255.0) as u8,
5824 (c.b.clamp(0.0, 1.0) * 255.0) as u8
5825 )
5826}
5827
5828/// Does this run need a `<span>` in `dialect`, or do the plain tags cover it?
5829#[expect(
5830 clippy::float_cmp,
5831 reason = "a scale of exactly 1.0 is the unscaled default, compared as a sentinel"
5832)]
5833fn needs_span(r: &TextRun, dialect: MarkupDialect) -> bool {
5834 let extras = r.color.is_some() || r.background.is_some() || r.font.scale != 1.0;
5835 match dialect {
5836 // Pango expresses the monospace family as a span attribute; Qt cannot (see below).
5837 MarkupDialect::Pango => extras || r.font.monospace,
5838 MarkupDialect::QtHtml => extras,
5839 }
5840}
5841
5842#[expect(
5843 clippy::float_cmp,
5844 reason = "a scale of exactly 1.0 is the unscaled default, compared as a sentinel"
5845)]
5846fn open_run(r: &TextRun, dialect: MarkupDialect, base_points: f64, out: &mut String) {
5847 use std::fmt::Write as _;
5848
5849 if let Some(url) = r.link.as_deref() {
5850 out.push_str("<a href=\"");
5851 escape_markup(url, out);
5852 out.push_str("\">");
5853 }
5854 // The span carries the attributes that have no tag: colors, relative size, and (on Pango)
5855 // the monospace family. Bold/italic/strike/underline are tags in both dialects, which keeps
5856 // the attribute string short and the escaping trivial.
5857 let color = r.color.map(hex);
5858 let background = r.background.map(hex);
5859 let mono = r.font.monospace;
5860 if needs_span(r, dialect) {
5861 match dialect {
5862 MarkupDialect::Pango => {
5863 out.push_str("<span");
5864 if let Some(c) = &color {
5865 let _ = write!(out, " foreground=\"{c}\"");
5866 }
5867 if let Some(c) = &background {
5868 let _ = write!(out, " background=\"{c}\"");
5869 }
5870 if mono {
5871 out.push_str(" font_family=\"monospace\"");
5872 }
5873 if r.font.scale != 1.0 {
5874 // Absolute, in Pango units (1/1024 pt), not the `font_scale`/`size="N%"`
5875 // pair: those are Pango 1.50 attributes, and a Pango that does not know an
5876 // attribute fails the whole markup parse, which renders the label empty
5877 // rather than merely unscaled. A point size still tracks the desktop's text
5878 // scaling, since Pango resolves points through the Xft DPI.
5879 let pts = r.font.resolved_points(base_points);
5880 let _ = write!(out, " size=\"{}\"", (pts * 1024.0).round() as i64);
5881 }
5882 out.push('>');
5883 }
5884 MarkupDialect::QtHtml => {
5885 // Color only. Qt's rich text does not resolve the generic `monospace` family
5886 // from a style attribute (it rendered proportional), so the fixed face comes
5887 // from the `<code>` tag below, which Qt maps to its own fixed font.
5888 out.push_str("<span style=\"");
5889 if let Some(c) = &color {
5890 let _ = write!(out, "color:{c};");
5891 }
5892 if let Some(c) = &background {
5893 let _ = write!(out, "background-color:{c};");
5894 }
5895 if r.font.scale != 1.0 {
5896 // Points, not a percentage: Qt's rich-text CSS subset understands `pt` and
5897 // `px` and silently ignores `%`, which is why a scaled run rendered at the
5898 // base size here while every other backend scaled it.
5899 let pt = r.font.resolved_points(base_points);
5900 let _ = write!(out, "font-size:{pt}pt;");
5901 }
5902 out.push_str("\">");
5903 }
5904 }
5905 }
5906 if dialect == MarkupDialect::QtHtml && mono {
5907 out.push_str("<code>");
5908 }
5909 if r.font.weight.is_some_and(|w| w >= FontWeight::Semibold) {
5910 out.push_str("<b>");
5911 }
5912 if r.font.italic {
5913 out.push_str("<i>");
5914 }
5915 if r.underline.is_on() {
5916 out.push_str("<u>");
5917 }
5918 if r.strikethrough {
5919 out.push_str("<s>");
5920 }
5921}
5922
5923fn close_run(r: &TextRun, dialect: MarkupDialect, out: &mut String) {
5924 if r.strikethrough {
5925 out.push_str("</s>");
5926 }
5927 if r.underline.is_on() {
5928 out.push_str("</u>");
5929 }
5930 if r.font.italic {
5931 out.push_str("</i>");
5932 }
5933 if r.font.weight.is_some_and(|w| w >= FontWeight::Semibold) {
5934 out.push_str("</b>");
5935 }
5936 if dialect == MarkupDialect::QtHtml && r.font.monospace {
5937 out.push_str("</code>");
5938 }
5939 if needs_span(r, dialect) {
5940 out.push_str("</span>");
5941 }
5942 if r.link.is_some() {
5943 out.push_str("</a>");
5944 }
5945}
5946
5947/// Are these runs well formed for `text`: ascending, non-overlapping, inside the string, and on
5948/// character boundaries?
5949///
5950/// Checked once in the pieces layer rather than in eight backends. A backend handed overlapping
5951/// ranges would produce a different wrong answer per platform, and a range splitting a multi-byte
5952/// character would panic on `str` slicing in some and render mojibake in others.
5953///
5954/// # Errors
5955///
5956/// Returns a message naming the first run that overlaps or precedes the run before it, ends
5957/// past the text, has an inverted range, or splits a multi-byte character.
5958pub fn runs_are_valid(text: &str, runs: &[TextRun]) -> Result<(), String> {
5959 let mut prev_end = 0usize;
5960 for (i, r) in runs.iter().enumerate() {
5961 if r.range.start < prev_end {
5962 return Err(format!(
5963 "run {i} starts at {} but the previous run ends at {prev_end} — runs must be \
5964 ascending and non-overlapping",
5965 r.range.start
5966 ));
5967 }
5968 if r.range.end > text.len() {
5969 return Err(format!(
5970 "run {i} ends at {} but the text is {} bytes",
5971 r.range.end,
5972 text.len()
5973 ));
5974 }
5975 if r.range.start > r.range.end {
5976 return Err(format!("run {i} has an inverted range {:?}", r.range));
5977 }
5978 if !text.is_char_boundary(r.range.start) || !text.is_char_boundary(r.range.end) {
5979 return Err(format!(
5980 "run {i} range {:?} splits a multi-byte character",
5981 r.range
5982 ));
5983 }
5984 prev_end = r.range.end;
5985 }
5986 Ok(())
5987}
5988
5989pub mod props {
5990 use super::*;
5991
5992 #[derive(Clone, Debug, Default, PartialEq)]
5993 pub struct ContainerProps {
5994 pub background: Option<Color>,
5995 pub corner_radius: f64,
5996 pub clips: bool,
5997 /// Semantic, theme-adaptive surface, mapped by each backend to a native material that
5998 /// follows the platform's light/dark appearance automatically (unlike the fixed-RGBA
5999 /// `background`, which it overrides when set).
6000 pub role: Option<super::SurfaceRole>,
6001 }
6002 /// Reactive surface update for a `background(..)` decorator whose color is a signal/closure:
6003 /// the backend re-applies the fill on the container's native backing view. Corner radius and
6004 /// clipping are fixed at realize (the `corner_radius(r)` decorator takes a plain `f64`).
6005 #[derive(Clone, Debug, PartialEq)]
6006 pub enum ContainerPatch {
6007 Background(Option<Color>),
6008 }
6009
6010 /// Realize props for a `scroll` container: which axis it scrolls. Backends create the matching
6011 /// native scroll view (vertical `UIScrollView`/`ScrollView`, horizontal
6012 /// `HorizontalScrollView`, etc.).
6013 #[derive(Clone, Debug, Default, PartialEq)]
6014 pub struct ScrollProps {
6015 pub horizontal: bool,
6016 }
6017
6018 #[derive(Clone, Debug, Default, PartialEq)]
6019 pub struct LabelProps {
6020 pub text: String,
6021 pub font: FontSpec,
6022 pub color: Option<Color>,
6023 /// What the text means, for the color the platform gives it (docs/text.md).
6024 ///
6025 /// Semantic the way [`crate::Font`] is semantic: an app says "this is secondary text"
6026 /// and each platform answers with its own answer: `secondaryLabelColor` on Apple,
6027 /// `?android:textColorSecondary`, GTK's `dim-label`. That is the only way a de-emphasized
6028 /// label stays correct in both appearances, since a literal grey that reads well on white
6029 /// is wrong on black. An explicit [`Self::color`] still wins; a backend that has no such
6030 /// color renders primary, which is legible and correct, just not dimmed.
6031 pub role: TextRole,
6032 pub wraps: bool,
6033 /// Maximum rendered lines; zero is unlimited. Apple and Android plain labels truncate
6034 /// the last line. Other backends may retain their ordinary wrapping behavior.
6035 pub max_lines: u32,
6036 /// How the label's lines sit within its own width. Only observable on a label that
6037 /// wraps or carries explicit newlines: a single line fills its box, so its alignment is
6038 /// the container's business, not the label's.
6039 ///
6040 /// `Leading` is the default and is what running text wants; `Center` is for the short,
6041 /// centered block a welcome screen or an empty state uses. A backend that cannot set
6042 /// it renders leading-aligned, which is legible and correct, just not centered.
6043 pub align: TextAlign,
6044 /// Styled spans within `text` (docs/text-runs.md). Empty is the overwhelmingly common
6045 /// case and means exactly what a label has always meant: one font, one color. A backend
6046 /// that cannot draw runs ignores this and renders `text` uniformly, which is legible and
6047 /// correct, just unstyled.
6048 pub runs: Vec<crate::TextRun>,
6049 }
6050 /// What a label's text means, for the color the platform gives it (`LabelProps::role`).
6051 #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
6052 pub enum TextRole {
6053 /// Ordinary text, in the platform's primary label color.
6054 #[default]
6055 Primary,
6056 /// De-emphasized text: a caption, a hint, the "nothing selected" line an empty detail
6057 /// pane shows. Rendered in the platform's secondary label color.
6058 Secondary,
6059 }
6060
6061 /// How a wrapped label's lines sit within its width (`LabelProps::align`).
6062 ///
6063 /// There is no `Justified` variant because no toolkit in Day's set agrees on how to justify
6064 /// the last line, and the ones that can do it at all need a paragraph style the others have
6065 /// no equivalent for.
6066 #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
6067 pub enum TextAlign {
6068 /// Left in a left-to-right locale, right in an RTL one (docs/localization.md).
6069 #[default]
6070 Leading,
6071 Center,
6072 Trailing,
6073 }
6074
6075 #[derive(Clone, Debug, PartialEq)]
6076 pub enum LabelPatch {
6077 Text(String),
6078 Color(Option<Color>),
6079 Font(FontSpec),
6080 /// New text and its runs together. One patch, not two: a run's byte range is only
6081 /// meaningful against a particular string, so applying them separately would leave the
6082 /// widget briefly holding ranges that point into the wrong text.
6083 Runs(String, Vec<crate::TextRun>),
6084 }
6085
6086 /// A button's native styling tier. `Automatic` is the toolkit's stock look; `Bordered`
6087 /// asks for a visually contained button where the stock look is borderless (iOS's plain
6088 /// system button reads as a link); `Prominent` asks for the platform's accent-filled /
6089 /// default-action affordance. Toolkits whose stock buttons are already contained treat
6090 /// `Bordered` as `Automatic`.
6091 // `Eq` is gone with the `Tinted` color: `Color` holds floats. `PartialEq` is what the
6092 // props diff uses, and that is unaffected.
6093 #[derive(Clone, Copy, Debug, Default, PartialEq)]
6094 pub enum ButtonStyleSpec {
6095 #[default]
6096 Automatic,
6097 Bordered,
6098 Prominent,
6099 /// A filled button in an app-chosen color, still drawn by the native control: the
6100 /// platform keeps its own pressed, hover, focus and disabled rendering, its button role,
6101 /// and its keyboard activation. The label color is not carried; each backend picks the
6102 /// readable one for the fill (see [`ButtonStyleSpec::on_tint`]), the same call the
6103 /// platform's own tinted buttons make.
6104 ///
6105 /// A backend with no way to recolor its button ignores this and draws its ordinary
6106 /// button. That is the trade: a plain button everywhere beats a colored
6107 /// rectangle that is no longer a button on the platforms that cannot.
6108 Tinted(Color),
6109 /// A button no wider than its title asks for (a one-glyph "−" or "+" in a stepper,
6110 /// a "×" on a chip) on toolkits whose stock button carries a minimum width and wide
6111 /// insets (Material's 88 dp button turns a two-button stepper into 240 dp). The native
6112 /// control stays: only its minimum width and horizontal padding are reduced. A toolkit
6113 /// whose buttons already hug their title (AppKit, UIKit's plain button, Qt) draws its
6114 /// ordinary button.
6115 Compact,
6116 /// Borderless native action button; compact horizontal insets on Material.
6117 Plain,
6118 }
6119
6120 impl ButtonStyleSpec {
6121 /// The label color to draw on a [`ButtonStyleSpec::Tinted`] fill: whichever of black or
6122 /// white contrasts better against it, by WCAG's contrast ratio.
6123 ///
6124 /// Comparing the two ratios rather than thresholding the luminance is the difference
6125 /// between right and nearly right. A mid amber (`#F0A64C`) has a relative luminance of
6126 /// 0.44; under a "brighter than half" test it reads as dark and takes white text, at a
6127 /// hopeless 2.2:1. Its contrast against black is 9.7:1. The two ratios cross at a
6128 /// luminance of 0.179, not 0.5, and everything between those two numbers is a button
6129 /// nobody can read.
6130 pub fn on_tint(fill: Color) -> Color {
6131 // WCAG relative luminance: sRGB channels linearized, then weighted by the eye's
6132 // sensitivity to each.
6133 let lin = |c: f64| {
6134 let c = c.clamp(0.0, 1.0);
6135 if c <= 0.04045 {
6136 c / 12.92
6137 } else {
6138 ((c + 0.055) / 1.055).powf(2.4)
6139 }
6140 };
6141 let l = 0.2126 * lin(fill.r) + 0.7152 * lin(fill.g) + 0.0722 * lin(fill.b);
6142 // Contrast ratio is (lighter + 0.05) / (darker + 0.05); white is 1.0, black is 0.0.
6143 let against_white = 1.05 / (l + 0.05);
6144 let against_black = (l + 0.05) / 0.05;
6145 if against_black >= against_white {
6146 Color::BLACK
6147 } else {
6148 Color::WHITE
6149 }
6150 }
6151 }
6152
6153 #[derive(Clone, Debug, Default, PartialEq)]
6154 /// The visible content and accessible title of a button with an icon.
6155 pub struct ButtonContent {
6156 /// Also serves as the accessible name when only the icon is visible.
6157 pub title: String,
6158 pub icon: Option<Icon>,
6159 pub icon_only: bool,
6160 }
6161 #[derive(Clone, Debug, Default, PartialEq)]
6162 pub struct ButtonProps {
6163 pub title: String,
6164 pub icon: Option<Icon>,
6165 pub icon_only: bool,
6166 pub enabled: bool,
6167 pub style: ButtonStyleSpec,
6168 /// The button stands for the current choice among its siblings (a document tab, a
6169 /// view switcher): the platform's own checked or selected rendering, which keeps the
6170 /// button enabled, focusable and activatable, and tells assistive tech it is selected.
6171 /// A click never toggles it natively; only the app's next patch changes it.
6172 pub selected: bool,
6173 }
6174 #[derive(Clone, Debug, PartialEq)]
6175 pub enum ButtonPatch {
6176 Title(String),
6177 /// Update an icon button's label and icon together. Plain buttons still use `Title`.
6178 Content(ButtonContent),
6179 Enabled(bool),
6180 /// The selected state (see [`ButtonProps::selected`]).
6181 Selected(bool),
6182 /// A live style change: what a reactive `.tint(…)` sends, so a button can recolor with
6183 /// app state without being torn down and realized again.
6184 Style(ButtonStyleSpec),
6185 }
6186
6187 #[derive(Clone, Debug, Default, PartialEq)]
6188 pub struct ToggleProps {
6189 pub on: bool,
6190 pub enabled: bool,
6191 }
6192 #[derive(Clone, Debug, PartialEq)]
6193 pub enum TogglePatch {
6194 On(bool),
6195 Enabled(bool),
6196 }
6197
6198 #[derive(Clone, Debug, PartialEq)]
6199 pub struct SliderProps {
6200 pub value: f64,
6201 pub min: f64,
6202 pub max: f64,
6203 pub step: Option<f64>,
6204 pub enabled: bool,
6205 }
6206 impl Default for SliderProps {
6207 fn default() -> Self {
6208 SliderProps {
6209 value: 0.0,
6210 min: 0.0,
6211 max: 1.0,
6212 step: None,
6213 enabled: true,
6214 }
6215 }
6216 }
6217 #[derive(Clone, Debug, PartialEq)]
6218 pub enum SliderPatch {
6219 Value(f64),
6220 Enabled(bool),
6221 }
6222
6223 /// SwiftUI's `pickerStyle` analogue (`kinds::PICKER`). Each maps to a distinct native
6224 /// control per toolkit (docs/picker.md).
6225 #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
6226 pub enum PickerStyle {
6227 /// A dropdown/pop-up menu (`NSPopUpButton` / `GtkDropDown` / `QComboBox` / UIButton+UIMenu / Spinner).
6228 #[default]
6229 Menu,
6230 /// A horizontal segmented control (`NSSegmentedControl` / `UISegmentedControl` / linked toggles / …).
6231 Segmented,
6232 /// A vertical radio-button group laid out inline (`NSButton` radios / `GtkCheckButton` group / …).
6233 Inline,
6234 }
6235
6236 /// Full picker props (realize). `style` is set once at build; `options`, `selected` and
6237 /// `enabled` patch (via [`PickerPatch`]).
6238 #[derive(Clone, Debug, PartialEq)]
6239 pub struct PickerProps {
6240 /// Decorative boundaries before option indexes (not selectable options). Native menu
6241 /// grouping on AppKit/UIKit; ignored by other backends and non-menu styles.
6242 pub separators_before: Vec<usize>,
6243 pub options: Vec<String>,
6244 pub selected: usize,
6245 pub style: PickerStyle,
6246 /// Whether the picker takes input. Default `true`.
6247 pub enabled: bool,
6248 }
6249 impl Default for PickerProps {
6250 fn default() -> Self {
6251 PickerProps {
6252 separators_before: Vec::new(),
6253 options: Vec::new(),
6254 selected: 0,
6255 style: PickerStyle::default(),
6256 enabled: true,
6257 }
6258 }
6259 }
6260
6261 #[derive(Clone, Debug, PartialEq)]
6262 pub enum PickerPatch {
6263 Selected(usize),
6264 /// New option labels, for a picker whose choices come from data (a document list, a
6265 /// live count). The backend rebuilds its items and keeps the selected index where it
6266 /// still exists, clamping to the last option otherwise; a fresh
6267 /// [`PickerPatch::Selected`] follows whenever the app's own binding disagrees.
6268 Options(Vec<String>),
6269 /// Enable or disable the whole control, every style alike.
6270 Enabled(bool),
6271 }
6272
6273 /// Full text-area props (realize, `kinds::TEXT_AREA`; docs/textarea.md). `text` seeds the
6274 /// editor; `min_lines`/`max_lines` bound the auto-growing height in text lines
6275 /// (`max_lines == 0` = unbounded). `editable`/`selectable`/`spellcheck` control the native
6276 /// editor attributes (all default `true`); a backend that can't honor one answers
6277 /// `Cap::Text{Editable,Selectable,SpellCheck}` = `Unsupported`. `text` and the three attributes
6278 /// change after build (via [`TextAreaPatch`]); the rest are build-only.
6279 #[derive(Clone, Debug, PartialEq)]
6280 pub struct TextAreaProps {
6281 pub text: String,
6282 pub placeholder: String,
6283 pub min_lines: u32,
6284 pub max_lines: u32,
6285 /// Whether the user can edit the text (`false` = read-only). Default `true`.
6286 pub editable: bool,
6287 /// Whether the text can be selected (and copied). Default `true`.
6288 pub selectable: bool,
6289 /// Whether spell-check / autocorrect highlighting is on. Default `true`.
6290 pub spellcheck: bool,
6291 /// Plain Enter emits `Event::Submitted` instead of inserting a newline (Shift+Enter
6292 /// still inserts one where the platform can distinguish). Chat composers. Default
6293 /// `false`.
6294 pub submit_on_enter: bool,
6295 }
6296
6297 impl Default for TextAreaProps {
6298 fn default() -> Self {
6299 TextAreaProps {
6300 text: String::new(),
6301 placeholder: String::new(),
6302 min_lines: 1,
6303 max_lines: 0,
6304 editable: true,
6305 selectable: true,
6306 spellcheck: true,
6307 submit_on_enter: false,
6308 }
6309 }
6310 }
6311
6312 /// Imperative text-area updates: replace the text (programmatic sync), or flip one of the
6313 /// live attributes.
6314 #[derive(Clone, Debug, PartialEq)]
6315 pub enum TextAreaPatch {
6316 SetText(String),
6317 SetEditable(bool),
6318 SetSelectable(bool),
6319 SetSpellCheck(bool),
6320 }
6321
6322 #[derive(Clone, Debug, Default, PartialEq)]
6323 pub struct TextFieldProps {
6324 pub text: String,
6325 pub placeholder: String,
6326 pub enabled: bool,
6327 }
6328 #[derive(Clone, Debug, PartialEq)]
6329 pub enum TextFieldPatch {
6330 /// Origin-tagged write (§4.4): `from_native` suppresses the echo back into the widget.
6331 Text {
6332 text: String,
6333 from_native: bool,
6334 },
6335 Placeholder(String),
6336 Enabled(bool),
6337 /// Select a range of the field's text, or place the caret when the range is empty
6338 /// (docs/textfield.md "Selection"). Sent after any [`TextFieldPatch::Text`] of the same
6339 /// turn, so the range always counts the text the field now holds. A backend clamps it
6340 /// against its own text with [`TextSelection::utf16`] or [`TextSelection::bytes`] and
6341 /// applies it to a focused field; whether an unfocused field keeps it is the platform's
6342 /// (docs/textfield.md).
6343 Select(TextSelection),
6344 }
6345
6346 /// A range of a text field's text in Unicode scalar values (Rust `char`s), the unit
6347 /// [`TextFieldPatch::Select`] carries on every backend. `start..end` is half-open, and an
6348 /// empty range is a caret position. The helpers clamp to the text and convert to the unit a
6349 /// native field counts: UTF-16 code units (Apple, Android, Qt, WinUI, the web, ArkUI) or
6350 /// bytes. GTK counts characters, which is [`TextSelection::clamped`].
6351 #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
6352 pub struct TextSelection {
6353 pub start: usize,
6354 pub end: usize,
6355 }
6356
6357 impl TextSelection {
6358 /// The range from `start` to `end`, ordered so that `start <= end`.
6359 pub fn new(start: usize, end: usize) -> Self {
6360 TextSelection {
6361 start: start.min(end),
6362 end: start.max(end),
6363 }
6364 }
6365
6366 /// The range held to `text`: both ends at most its character count, `start <= end`.
6367 #[must_use]
6368 pub fn clamped(self, text: &str) -> Self {
6369 let n = text.chars().count();
6370 TextSelection::new(self.start.min(n), self.end.min(n))
6371 }
6372
6373 /// The clamped range as UTF-16 code-unit offsets into `text`: `(start, end)`.
6374 #[must_use]
6375 pub fn utf16(self, text: &str) -> (usize, usize) {
6376 let r = self.clamped(text);
6377 let at = |chars: usize| -> usize {
6378 text.chars().take(chars).map(char::len_utf16).sum::<usize>()
6379 };
6380 (at(r.start), at(r.end))
6381 }
6382
6383 /// The clamped range as UTF-8 byte offsets into `text`: `(start, end)`, each on a
6384 /// character boundary.
6385 #[must_use]
6386 pub fn bytes(self, text: &str) -> (usize, usize) {
6387 let r = self.clamped(text);
6388 let at = |chars: usize| -> usize {
6389 text.char_indices()
6390 .nth(chars)
6391 .map_or(text.len(), |(i, _)| i)
6392 };
6393 (at(r.start), at(r.end))
6394 }
6395 }
6396
6397 #[cfg(test)]
6398 mod text_selection_tests {
6399 use super::TextSelection;
6400
6401 #[test]
6402 fn orders_and_clamps() {
6403 assert_eq!(TextSelection::new(5, 2), TextSelection { start: 2, end: 5 });
6404 let r = TextSelection::new(3, usize::MAX).clamped("github.com");
6405 assert_eq!(r, TextSelection { start: 3, end: 10 });
6406 let past = TextSelection::new(40, 50).clamped("git");
6407 assert_eq!(past, TextSelection { start: 3, end: 3 });
6408 assert_eq!(
6409 TextSelection::new(0, 9).clamped(""),
6410 TextSelection::default()
6411 );
6412 }
6413
6414 #[test]
6415 fn converts_to_native_units() {
6416 // "é" is one char, one UTF-16 unit and two bytes; "😀" is one char, two UTF-16
6417 // units and four bytes.
6418 let text = "aé😀b";
6419 assert_eq!(TextSelection::new(1, 3).utf16(text), (1, 4));
6420 assert_eq!(TextSelection::new(1, 3).bytes(text), (1, 7));
6421 assert_eq!(TextSelection::new(0, usize::MAX).utf16(text), (0, 5));
6422 assert_eq!(TextSelection::new(0, usize::MAX).bytes(text), (0, 8));
6423 assert_eq!(TextSelection::new(4, 4).bytes(text), (8, 8));
6424 }
6425 }
6426
6427 /// How an image is scaled to fill its frame (§18.3). Maps to each toolkit's native scaling.
6428 #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
6429 pub enum ContentMode {
6430 /// Scale to fit entirely inside the frame, preserving aspect ratio (letterboxed). The
6431 /// default: an image never stretches unless asked. SwiftUI's `.scaledToFit`.
6432 #[default]
6433 Fit,
6434 /// Scale to fill the frame, preserving aspect ratio and cropping the overflow. SwiftUI's
6435 /// `.scaledToFill`.
6436 Fill,
6437 /// Stretch to fill the frame exactly, ignoring aspect ratio.
6438 Stretch,
6439 }
6440
6441 #[derive(Clone, Debug, Default, PartialEq)]
6442 pub struct ImageProps {
6443 /// Which pixels to draw: a staged asset name, encoded bytes, or an already-decoded
6444 /// image ([`ImageSource`], docs/images.md). A name resolves through the backend's own
6445 /// pipeline (§18.2); bytes and decoded ids need [`Cap::ImageDecode`], and a backend
6446 /// without it draws nothing rather than guessing.
6447 pub source: ImageSource,
6448 pub decorative: bool,
6449 /// How the image scales within its frame (default [`ContentMode::Fit`], no stretching).
6450 pub content_mode: ContentMode,
6451 /// Optional width:height ratio the view is constrained to (e.g. `16.0/9.0`). `None` lets the
6452 /// image take its allocated frame.
6453 pub aspect_ratio: Option<f64>,
6454 /// Monochrome tint for a template/vector glyph (docs/vectors.md): backends that can,
6455 /// recolor natively (template rendering on Apple, drawable tint on Android, pixel
6456 /// recolor on GTK); backends that can't yet ignore it and draw the source colors.
6457 /// `None` (the default, and every raster `image(…)`) means "as authored".
6458 pub tint: Option<Color>,
6459 /// A monochrome template glyph (docs/vectors.md "Template"): with no `tint`, it draws
6460 /// in the foreground of the surface it sits on — the theme's label color on the
6461 /// desktops, the cell's tint on UIKit, `currentColor` on the web — and follows a
6462 /// theme switch. What a sidebar row's untinted icon is: a tinted glyph recolors the
6463 /// same way with or without this, and `false` (the default) draws an untinted glyph as
6464 /// authored. [`ImagePatch::Tint`]`(None)` on a template returns to that foreground,
6465 /// not to the authored colors.
6466 pub template: bool,
6467 }
6468
6469 /// A list row's standard content (`kinds::LIST_ITEM`, docs/list.md "List items"). Empty
6470 /// text means the part is absent.
6471 #[derive(Clone, Debug, Default, PartialEq)]
6472 pub struct ListItemProps {
6473 pub title: String,
6474 /// A second line under the title, in the platform's secondary style.
6475 pub subtitle: String,
6476 /// Trailing text (a count, a value), in the platform's secondary style.
6477 pub detail: String,
6478 /// The leading glyph: a symbol or a bundled image.
6479 pub icon: Option<crate::Icon>,
6480 /// The glyph's color; `None` takes the platform's own (template glyphs follow the
6481 /// foreground, the tint color on UIKit).
6482 pub icon_tint: Option<Color>,
6483 /// A trailing check mark: the platform's selected-option mark (UIKit's checkmark
6484 /// accessory, a Material check icon), announced as checked.
6485 pub checked: bool,
6486 }
6487
6488 /// A live change to a realized list item; every part changes in place.
6489 #[derive(Clone, Debug, PartialEq)]
6490 pub enum ListItemPatch {
6491 Title(String),
6492 Subtitle(String),
6493 Detail(String),
6494 Icon(Option<crate::Icon>),
6495 IconTint(Option<Color>),
6496 Checked(bool),
6497 }
6498
6499 /// A live change to a realized image or vector glyph.
6500 ///
6501 /// `content_mode` and the rest still describe which art this is and how it fills its frame,
6502 /// which a rebuild expresses better than a patch. Two things do want to follow a signal: the
6503 /// tint (a glyph that recolors with the selection or the theme should repaint, not be torn
6504 /// down and realized again, docs/vectors.md "Tint") and the source, now that it can be a
6505 /// buffer the app swaps (a download landing, a new photo picked, docs/images.md). Replacing
6506 /// the pixels of a view that is already on screen is what a patch is for; realizing a second
6507 /// view would flash.
6508 #[derive(Clone, Debug, PartialEq)]
6509 pub enum ImagePatch {
6510 /// Recolor the glyph, or `None` to draw the authored colors again.
6511 Tint(Option<Color>),
6512 /// Draw different pixels in the same view. A backend that cannot decode the new source
6513 /// (bytes where [`Cap::ImageDecode`] is `Unsupported`) leaves what it was drawing.
6514 Source(ImageSource),
6515 }
6516
6517 #[derive(Clone, Debug, Default, PartialEq)]
6518 pub struct CanvasProps {
6519 pub ops: Vec<DrawOp>,
6520 }
6521
6522 /// Progress indicator. `value` is the completed fraction in `0.0..=1.0`; `None` means
6523 /// indeterminate (an animated spinner / busy bar, no known extent). Backends map this to
6524 /// their native determinate/indeterminate widgets (docs/progress.md).
6525 #[derive(Clone, Debug, PartialEq)]
6526 pub struct ProgressProps {
6527 pub value: Option<f64>,
6528 /// Whether an indeterminate indicator animates; ignored for a determinate bar.
6529 pub animating: bool,
6530 /// The platform's large indicator size.
6531 pub large: bool,
6532 }
6533 impl Default for ProgressProps {
6534 fn default() -> Self {
6535 Self {
6536 value: None,
6537 animating: true,
6538 large: false,
6539 }
6540 }
6541 }
6542 #[derive(Clone, Debug, PartialEq)]
6543 pub enum ProgressPatch {
6544 Animating(bool),
6545 /// New completed fraction, or `None` to switch to indeterminate.
6546 Value(Option<f64>),
6547 }
6548
6549 /// A rule between neighbors (`divider()`): a hairline across the width it is offered, or,
6550 /// with `vertical`, down the height it is offered (`divider().vertical()`, between a
6551 /// row's panes). A toolkit measures both the same way, as a horizontal rule, because the
6552 /// pieces layer swaps the axes of a vertical one's proposal and answer; realization is
6553 /// where the orientation matters, for the few widgets that draw a horizontal line
6554 /// regardless of their frame.
6555 #[derive(Clone, Debug, Default, PartialEq)]
6556 pub struct DividerProps {
6557 pub vertical: bool,
6558 }
6559
6560 /// How a navigation host lays its panes out (docs/navigation.md).
6561 ///
6562 /// This is the resolved presentation, what the toolkit must draw right now. The app asks for
6563 /// one through `Nav::presentation`, where leaving it unset means "automatic": the pieces
6564 /// layer resolves it from the window's [`SizeClass`] and the toolkit's `Cap::NavSplit`, and
6565 /// re-resolves it whenever the class changes. There is no `Auto` variant here because a
6566 /// backend can only ever draw a concrete one, so the undecided state stays on the app's side
6567 /// of the boundary where it can still be decided.
6568 #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
6569 pub enum NavPresentation {
6570 /// Sidebar beside detail, both visible (`NSSplitViewController`, nested `GtkPaned`s,
6571 /// a `NavigationView`). The sidebar pane gets its own container.
6572 Split,
6573 /// One page at a time, back-navigable. The sidebar pane becomes the stack's root.
6574 #[default]
6575 Stack,
6576 /// The rows drawn as a tab bar, one page's content beside it, no back stack: what a
6577 /// phone-shaped window wants from a one-of-N surface (`UITabBarController`, a Material
6578 /// `NavigationBarView`, `NavigationView.PaneDisplayMode = Top`). The `Pane::Sidebar` page
6579 /// is not drawn at all: its rows are the chrome.
6580 Tabs,
6581 /// The rows drawn as a narrow icon strip beside the content, the `Medium`-width answer
6582 /// between [`Self::Tabs`] and [`Self::Split`] (a Material `NavigationRailView`,
6583 /// `PaneDisplayMode = LeftCompact`, an ArkUI vertical `Tabs`).
6584 ///
6585 /// A backend with no rail rounds it to a neighbor of its own choosing rather than
6586 /// failing: UIKit answers `Tabs` (which is what iPadOS does at that width), GTK the same.
6587 /// Rounding is expected and correct; this variant is a request, not a contract.
6588 Rail,
6589 }
6590
6591 impl NavPresentation {
6592 /// `true` for [`NavPresentation::Split`], the shape most backend code wants.
6593 #[must_use]
6594 pub fn is_split(self) -> bool {
6595 self == NavPresentation::Split
6596 }
6597
6598 /// `true` when the rows are the chrome rather than a drawn page: [`Self::Tabs`] and
6599 /// [`Self::Rail`]. Both hide the `Pane::Sidebar` page and render its rows themselves, so
6600 /// backend code that only cares about that distinction asks this instead of matching both.
6601 #[must_use]
6602 pub fn rows_are_chrome(self) -> bool {
6603 matches!(self, NavPresentation::Tabs | NavPresentation::Rail)
6604 }
6605 }
6606
6607 /// Navigation host (docs/navigation.md).
6608 #[derive(Clone, Debug, Default, PartialEq)]
6609 pub struct NavProps {
6610 /// Document-tab chrome, independent of navigation destinations.
6611 pub documents: Option<DocumentTabsConfig>,
6612 pub title: String,
6613 /// The presentation to draw now; re-presented in place by [`NavPatch::Presentation`].
6614 pub presentation: NavPresentation,
6615 /// The app left the presentation automatic (`NavStyle::Automatic`, or a `Sidebar`
6616 /// nav host with no `.presentation(…)` pin), so it is free to follow the window.
6617 ///
6618 /// Only a toolkit answering `Cap::NavRepresent = Emulated` needs this: its own adaptive
6619 /// container owns the morph, and it must know whether the app asked for one at all before
6620 /// building it. With two presentations that bit could be inferred from a lowered `Split`;
6621 /// with four it cannot, so it is carried explicitly rather than encoded.
6622 ///
6623 /// `Native` re-presenters ignore it (they are told each presentation as it is resolved),
6624 /// and so do toolkits that cannot re-present.
6625 pub adaptive: bool,
6626 /// Draw the platform's own show/hide-sidebar affordance on this host's chrome
6627 /// (docs/toolbars.md). `true` for every `nav(Sidebar)` unless the app opted out:
6628 /// the toolkit owns both the button and the behavior
6629 /// (`NSToolbarToggleSidebarItemIdentifier`, the split view's collapse on GTK,
6630 /// `NavigationView.IsPaneOpen` on XAML), so an app that once declared the item by hand
6631 /// now declares nothing. Hosts with no sidebar ignore it.
6632 pub sidebar_toggle: bool,
6633 /// Search over this navigation surface (`Nav::searchable`, docs/search.md).
6634 /// `None` = the surface is not searchable and no field is rendered anywhere.
6635 pub search: Option<SearchProps>,
6636 /// `Some(width)` = this host has a content-list pane ([`Pane::List`]) at this preferred
6637 /// width in points, between the sidebar and the detail (docs/navigation.md). Read at
6638 /// realize, because a backend that builds a different container for a three-pane host
6639 /// (UIKit's triple-column style is init-only) needs to know before it builds. `None` on
6640 /// every host without one, including all of them on backends answering
6641 /// [`crate::Cap::NavContentList`] `Unsupported`: the pieces layer composes there and
6642 /// the prop is never set.
6643 pub list_width: Option<f64>,
6644 /// Whether that pane is showing for the destination the host opens on
6645 /// (`Nav::content_list_for`). Read at realize, like `list_width`, and for a
6646 /// related reason: a backend whose pane is a real split item can only honor a
6647 /// collapsed state reliably by setting it before the item joins the split. Told
6648 /// afterwards (by `NavPatch::ListVisible`, on a window that has not been displayed
6649 /// yet), AppKit reports the item collapsed and then lays it back out from its holding
6650 /// priorities, and the app opens with a list beside a page that does not own one.
6651 /// `true` on every host whose first destination has a list, and on hosts with no pane
6652 /// at all, where it means nothing.
6653 pub list_visible: bool,
6654 }
6655
6656 /// Switch only tab chrome; resident contents must retain their native identity.
6657 #[derive(Clone, Copy, Debug, PartialEq)]
6658 pub struct DocumentTabsPatch {
6659 pub native: bool,
6660 }
6661
6662 /// Localized document-tab chrome. Native callbacks emit stable route keys.
6663 #[derive(Clone, Debug, Default, PartialEq)]
6664 pub struct DocumentTabsConfig {
6665 pub new_label: String,
6666 pub close_label: String,
6667 pub can_add: bool,
6668 }
6669
6670 /// Where a searchable surface's field should be drawn.
6671 ///
6672 /// A preference, not an instruction: a backend that cannot honor the request falls back to
6673 /// whatever its platform does, exactly as SwiftUI's `searchable(placement:)` does ("depending
6674 /// on the containing view hierarchy and platform, the requested placement may not be able to
6675 /// be fulfilled"). `Automatic` is the one to reach for: it is what lets the field live in the
6676 /// window toolbar on a wide window and move into the navigation list on a narrow one.
6677 #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
6678 pub enum SearchPlacement {
6679 /// The platform decides, from the window's size class and its own convention.
6680 #[default]
6681 Automatic,
6682 /// In the window's toolbar (`NSSearchToolbarItem`, an `AdwHeaderBar` entry, a
6683 /// `CommandBar` `AutoSuggestBox`). `Inline` where the toolbar cannot hold a search field
6684 /// (`Cap::ToolbarSearch`).
6685 Toolbar,
6686 /// Attached to the navigation surface itself: above the sidebar list, or in the
6687 /// navigation bar's search drawer on the phones.
6688 Inline,
6689 }
6690
6691 /// Search over a navigation surface (docs/search.md). The query itself stays an app-owned
6692 /// signal; this carries only what the toolkit must draw, so moving the field between
6693 /// placements never moves the state.
6694 #[derive(Clone, Debug, Default, PartialEq)]
6695 pub struct SearchProps {
6696 /// Current text. Two-way: the user typing emits [`Event::SearchChanged`], and the app's
6697 /// own writes arrive as [`SearchPatch::Text`].
6698 pub text: String,
6699 /// Empty-state prompt.
6700 pub prompt: String,
6701 pub placement: SearchPlacement,
6702 /// Opt into native scrolling search/title chrome on mobile. Default false keeps
6703 /// the field pinned. Desktop toolbar search is unchanged.
6704 pub hides_on_scroll: bool,
6705 /// Start the UIKit navigation search drawer collapsed, with a compact toolbar title.
6706 /// Implies scrolling search on UIKit; ignored by other backends. Default false.
6707 pub initially_hidden: bool,
6708 /// Scope titles, empty = no scope bar. One-of-N: a `UISearchBar` scope bar, a Material
6709 /// `ChipGroup` of single-selection filter chips, an ArkUI `SegmentButtonV2`, an
6710 /// `NSSegmentedControl` (docs/search.md has the per-backend table).
6711 pub scopes: Vec<String>,
6712 /// Index into `scopes`; meaningless when `scopes` is empty.
6713 pub scope: usize,
6714 /// Completions offered for the current text. On a navigation surface these complete the
6715 /// field rather than replacing the list: the list is already the result set, so an
6716 /// overlay of results would cover the thing it is filtering.
6717 pub suggestions: Vec<String>,
6718 }
6719
6720 /// A targeted update to a live search field, the path a bound signal writes through, so
6721 /// syncing text never rebuilds (and refocuses) the field mid-word.
6722 #[derive(Clone, Debug, PartialEq)]
6723 pub enum SearchPatch {
6724 Focus,
6725 Text(String),
6726 Scope(usize),
6727 Suggestions(Vec<String>),
6728 }
6729 /// Applied to the nav host after a page child is attached / before it is removed;
6730 /// the toolkit animates its native presentation accordingly.
6731 #[derive(Clone, Debug, PartialEq)]
6732 pub enum NavPatch {
6733 /// The just-attached last page child became the top of the stack. `immersive` marks a
6734 /// page that keeps the floating transparent chrome on backends with an immersive nav
6735 /// mode (day-toolkit-material edge-to-edge today; ignored elsewhere). Unmarked pages get the
6736 /// standard opaque bar.
6737 Pushed { title: String, immersive: bool },
6738 /// The top page is about to be removed; present its predecessor.
6739 Popped,
6740 /// Current top-of-stack title changed.
6741 Title(String),
6742 /// The top page has a back guard (`NavStack::on_back`, docs/navigation.md): while `true`,
6743 /// the toolkit must not auto-pop on a native back gesture/button but route it to
6744 /// Day as `Event::NavBack { already_popped: false }` so the app's guard decides. On
6745 /// backends whose back already routes through Day (AppKit/Qt/XAML/web custom headers)
6746 /// this is a no-op; iOS disables the swipe, Android holds its callback, GTK sets the
6747 /// page `can-pop=false`, ArkUI consumes `onBackPressed`.
6748 GuardTop(bool),
6749 /// Re-present the host: the window's size class crossed a breakpoint, or the app wrote a
6750 /// new `presentation`. The page children do not change: the toolkit rebuilds its
6751 /// chrome and re-homes the pages it already has, each one landing by its
6752 /// [`NavPageProps::pane`]. Rebuilding them instead would drop scroll offsets, field
6753 /// focus, and every native animation in flight, which is why this is a patch and not
6754 /// a rebuild.
6755 ///
6756 /// Backends with no split container ignore it and stay stacked.
6757 Presentation(NavPresentation),
6758 /// Show the resident [`Pane::Detail`] page at this index, counting the host's detail
6759 /// children in attach order. The counterpart to [`Self::Pushed`]/[`Self::Popped`] for the
6760 /// presentations where pages are resident rather than stacked
6761 /// ([`NavPresentation::rows_are_chrome`]): a tab bar switches between pages that all stay
6762 /// alive, so there is nothing to push and nothing to pop.
6763 ///
6764 /// Applied without re-emitting [`crate::Event::SelectionChanged`], per the from-native
6765 /// echo rule: this is the programmatic-sync direction.
6766 ///
6767 /// A backend drawing a stacked presentation never receives it; the pieces layer sends
6768 /// push/pop there instead.
6769 Select(usize),
6770 /// Reorder resident detail pages by their previous indices without rebuilding them.
6771 Reorder(Vec<usize>),
6772 /// Show or collapse the content-list pane ([`Pane::List`]), the per-destination
6773 /// visibility switch (`Nav::content_list_for`, docs/navigation.md): a nav host
6774 /// section that spans the whole detail area (a settings page) collapses the pane, and
6775 /// selecting a list-backed section brings it back. Only sent to hosts whose
6776 /// [`NavProps::list_width`] is set. Applied directly, not through an animator proxy:
6777 /// the screenshot step captures the instant the patch returns (the sidebar-toggle rule).
6778 ListVisible(bool),
6779 /// Stacked presentations on a merged-pane backend ([`crate::Cap::NavContentList`]
6780 /// `Emulated`) only: the resident [`Pane::List`] page joins (`true`) or leaves
6781 /// (`false`) the navigation stack directly above the sidebar root. The pieces layer
6782 /// sends it as the selection gains or loses a list-backed destination; the backend
6783 /// realizes the membership change through its platform's navigation APIs (UIKit:
6784 /// `showColumn(.supplementary)` / a pop to the root; never a manual splice, which
6785 /// destroys the split's collapse bookkeeping). Never sent to `Native` backends (their
6786 /// pane persists through every presentation) nor while split.
6787 ListInStack(bool),
6788 }
6789
6790 /// Which pane of a navigation host a page belongs to (docs/navigation.md).
6791 ///
6792 /// A page's pane is a fact about the model, not about how the host currently draws it: a
6793 /// nav host's list page is [`Pane::Sidebar`] whether the toolkit is showing a sidebar beside
6794 /// a detail or stacking the two. What the presentation decides is where each pane lands:
6795 /// its own splitter pane in [`NavPresentation::Split`], the root of the stack in
6796 /// [`NavPresentation::Stack`]. Keeping the two separate is what lets a host re-present on a
6797 /// size-class change (`NavPatch::Presentation`) by re-homing the pages it already has,
6798 /// instead of tearing the tree down and rebuilding it.
6799 #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
6800 pub enum Pane {
6801 /// The list / master pane of a nav host. At most one page per host.
6802 Sidebar,
6803 /// The content-list pane between the sidebar and the detail, Mail's message list
6804 /// (`Nav::content_list`, docs/navigation.md). At most one page per host, and only
6805 /// on hosts whose [`NavProps::list_width`] is set; a backend answering
6806 /// [`crate::Cap::NavContentList`] `Unsupported` never sees one.
6807 List,
6808 /// A destination page. Every page of a `nav_stack` presentation is one of these.
6809 #[default]
6810 Detail,
6811 }
6812
6813 /// One destination's native container.
6814 #[derive(Clone, Debug, Default, PartialEq)]
6815 pub struct NavPageProps {
6816 pub title: String,
6817 pub pane: Pane,
6818 }
6819
6820 /// The largest a modal sheet grows on a desktop, in points: the window less a margin up to
6821 /// this (docs/cover.md "Modal sheet"). AppKit's native sheet and the composed card share it.
6822 pub const SHEET_MAX: crate::Size = crate::Size::new(640.0, 620.0);
6823 /// The largest a [`CoverProps::large`] sheet grows (docs/cover.md "Large sheet").
6824 pub const LARGE_SHEET_MAX: crate::Size = crate::Size::new(1040.0, 880.0);
6825
6826 /// A fullscreen cover's content container (docs/cover.md). Realized detached and hidden;
6827 /// `CoverPatch::Present` shows it over the whole window.
6828 #[derive(Clone, Debug, Default, PartialEq)]
6829 pub struct CoverProps {
6830 /// Prefer a native sheet; toolkits without sheet presentation keep their modal cover.
6831 pub sheet: bool,
6832 /// A half-height sheet rising from the bottom edge, the window content above it
6833 /// staying on show and, where the platform allows, interactive: an inspector over the
6834 /// canvas it describes. Implies `sheet`. The toolkit reports the sheet's own content
6835 /// size through `FrameChanged`, as for any cover (docs/cover.md "Half sheet").
6836 pub half: bool,
6837 /// A large sheet: most of the window, less a margin, for a document or web page that
6838 /// needs the room (docs/cover.md "Large sheet"). Implies `sheet`.
6839 pub large: bool,
6840 }
6841
6842 /// Applied to a `kinds::COVER` node as its bound signal opens and closes it.
6843 #[derive(Clone, Debug, PartialEq)]
6844 pub enum CoverPatch {
6845 /// Present the cover fullscreen (slide up where the platform animates modals).
6846 /// `background` paints the whole surface edge-to-edge (under the status bar / home
6847 /// indicator); the content container is inset to the safe area within it.
6848 /// `dismiss_disabled` = the user must not be able to dismiss it interactively
6849 /// (system back / sheet gestures); programmatic dismissal still works.
6850 Present {
6851 background: Option<Color>,
6852 dismiss_disabled: bool,
6853 },
6854 /// The `interactive_dismiss_disabled` state changed while presented.
6855 DismissDisabled(bool),
6856 /// Dismiss the cover. When the hide transition finishes the backend emits
6857 /// [`crate::Event::CoverHidden`] on the node (trampoline backends send
6858 /// `BridgeKind::CoverHidden`), letting the piece dispose the content only after it
6859 /// left the screen.
6860 Dismiss,
6861 }
6862
6863 /// A `kinds::INSPECTOR` split (docs/inspector.md): content beside a trailing inspector
6864 /// pane. The pane's visibility is Day-owned state (the piece's bound signal), so the
6865 /// props carry the value to draw and [`InspectorPatch::Visible`] keeps it current;
6866 /// a native affordance hiding the pane (a dock close button, a dragged-shut divider)
6867 /// reports back with [`crate::Event::InspectorChanged`].
6868 #[derive(Clone, Debug, PartialEq)]
6869 pub struct InspectorProps {
6870 /// Whether the pane is showing now.
6871 pub visible: bool,
6872 /// The pane's preferred width in points. A backend with a user-draggable divider
6873 /// treats it as the initial width; one without draws it at exactly this.
6874 pub width: f64,
6875 /// Which side of the content the pane sits on. `Trailing` is the classic inspector;
6876 /// `Leading` is a utility pane like a layer panel (docs/tree.md).
6877 pub edge: PaneEdge,
6878 }
6879
6880 /// Which side an inspector pane occupies (docs/inspector.md).
6881 #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
6882 pub enum PaneEdge {
6883 #[default]
6884 Trailing,
6885 Leading,
6886 }
6887
6888 /// Applied to a `kinds::INSPECTOR` node as its bound signal changes.
6889 #[derive(Clone, Debug, PartialEq)]
6890 pub enum InspectorPatch {
6891 /// Show or hide the pane (animated where the platform animates panes). The
6892 /// programmatic-sync direction: applying it must not re-emit
6893 /// [`crate::Event::InspectorChanged`], per the from-native echo rule.
6894 Visible(bool),
6895 }
6896
6897 /// One pane of a `kinds::INSPECTOR` split (docs/inspector.md).
6898 #[derive(Clone, Debug, Default, PartialEq)]
6899 pub struct InspectorPaneProps {
6900 /// `true` for the inspector panel itself, `false` for the content pane.
6901 pub panel: bool,
6902 }
6903
6904 /// How a `kinds::SPLIT` lays its two panes (docs/split.md): beside each other, the divider
6905 /// standing, or stacked, the divider lying. Named by where the panes go, since that is
6906 /// what an app's "layout" toggle means; the divider runs the other way.
6907 #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
6908 pub enum SplitAxis {
6909 /// The panes side by side (first leading), the divider vertical.
6910 #[default]
6911 Horizontal,
6912 /// The panes stacked (first on top), the divider horizontal.
6913 Vertical,
6914 }
6915
6916 /// A `kinds::SPLIT` (docs/split.md): two panes with a divider the user drags. The first
6917 /// pane's share is Day-owned state (the piece's bound signal): the props carry the value
6918 /// to draw, [`SplitPatch::Fraction`] keeps it current, and a divider the user moved
6919 /// reports back as [`crate::Event::ValueChanged`] with the new share, which applying the
6920 /// patch must never re-emit (the from-native echo rule).
6921 #[derive(Clone, Debug, PartialEq)]
6922 pub struct SplitProps {
6923 pub axis: SplitAxis,
6924 /// The first pane's share of the split's length along `axis`, `0.0..=1.0`.
6925 pub fraction: f64,
6926 /// The least length either pane may be dragged to, in points.
6927 pub min_pane: f64,
6928 }
6929
6930 /// Applied to a `kinds::SPLIT` node as its bound signals change.
6931 #[derive(Clone, Debug, PartialEq)]
6932 pub enum SplitPatch {
6933 /// Turn the split the other way, keeping the share.
6934 Axis(SplitAxis),
6935 /// Move the divider so the first pane takes this share. The programmatic-sync
6936 /// direction: applying it must not re-emit [`crate::Event::ValueChanged`].
6937 Fraction(f64),
6938 }
6939
6940 /// One pane of a `kinds::SPLIT` (docs/split.md).
6941 #[derive(Clone, Debug, Default, PartialEq)]
6942 pub struct SplitPaneProps {
6943 /// `false` for the first pane, `true` for the second.
6944 pub second: bool,
6945 }
6946
6947 /// Native navigation item list. `items` are display titles in route order;
6948 /// `selected` highlights the active route (split presentation; None on mobile roots).
6949 /// `icons` (parallel to `items`, `None` = no icon) are bundled image names resolved by each
6950 /// backend via `resource::resolve_image_file`; a backend that can't decorate its rows just
6951 /// ignores them.
6952 #[derive(Clone, Debug, Default, PartialEq)]
6953 pub struct NavMenuProps {
6954 /// Stable document identities, parallel to items; empty for ordinary navigation.
6955 pub document_keys: Vec<String>,
6956 pub items: Vec<String>,
6957 pub icons: Vec<Option<String>>,
6958 /// A trailing accessory per row: an unread count, a status. Rendered right-aligned and
6959 /// de-emphasized, opposite the label. Parallel to `items`; `None` draws nothing.
6960 pub badges: Vec<Option<String>>,
6961 /// A trailing symbol accessory per row, in the same slot as [`Self::badges`] and drawn
6962 /// after it: a bundled image name resolved the way [`Self::icons`] is. This is what a
6963 /// row-level status glyph rides on (a starred page's star) where `badges` carries only
6964 /// text. Parallel to `items`; `None` draws nothing.
6965 pub badge_icons: Vec<Option<String>>,
6966 /// The tint for [`Self::badge_icons`], parallel to `items`. `None` leaves the glyph at
6967 /// the backend's neutral template tint; a status glyph that means something (a yellow
6968 /// star) names its own color here, exactly as [`Self::tints`] does for the leading icon.
6969 pub badge_tints: Vec<Option<Color>>,
6970 /// A per-row icon tint (docs/vectors.md): the row's glyph recolored to this instead of
6971 /// the backend's neutral template tint. Parallel to `items`; `None` keeps the default.
6972 pub tints: Vec<Option<Color>>,
6973 /// A section header introducing the row at the same index. `Some` opens a new group
6974 /// before that row; `None` continues the current one. Parallel to `items`, so adding a
6975 /// header never shifts the selection indices the rows are addressed by.
6976 pub sections: Vec<Option<String>>,
6977 /// A per-row context menu (docs/menus.md): shown on secondary-click / long-press on
6978 /// that row, the same [`crate::MenuItem`] model as everywhere else: items carry
6979 /// registered action ids, so a chosen entry dispatches [`crate::Event::MenuAction`]
6980 /// exactly like a piece context menu. Parallel to `items`; empty = no menu.
6981 pub menus: Vec<Vec<crate::MenuItem>>,
6982 /// Which rows drag to reorder (docs/navigation.md "Reordering sidebar destinations"),
6983 /// parallel to `items`; empty when the sidebar does not reorder. A row moves only
6984 /// within the run of movable rows around it, which a section header or a fixed row
6985 /// ends. A toolkit whose `Cap::NavReorder` is `Native` drags the rows in its own
6986 /// sidebar and reports a drop as [`crate::Event::ListReorder`] in item indices: `from`
6987 /// is the moved row, `to` the row whose position it takes, in the order before the move.
6988 pub movable: Vec<bool>,
6989 /// The sidebar regroups (docs/navigation.md "Moving rows between sections"): a movable
6990 /// row may also cross section headers, into any section whose rows are all movable. A
6991 /// toolkit whose `Cap::NavReorder` is `Native` offers those drops too and reports every
6992 /// drop as [`crate::Event::NavRegroup`] instead of [`crate::Event::ListReorder`]. `false`
6993 /// keeps [`Self::movable`]'s run rule.
6994 pub regroup: bool,
6995 /// Which movable rows keep the app's sorted order within their own section, parallel to
6996 /// `items`; empty when the sidebar does not regroup. Under [`Self::regroup`], a sorted
6997 /// row drops only into another section: no gap in its own section is offered.
6998 pub sorted: Vec<bool>,
6999 pub selected: Option<usize>,
7000 }
7001 #[derive(Clone, Debug, PartialEq)]
7002 // `Items` carries every row array; a patch travels boxed (`Box<dyn Any>`) and lives for one
7003 // update, so the variants' size difference costs nothing worth an indirection.
7004 #[allow(clippy::large_enum_variant)]
7005 pub enum NavMenuPatch {
7006 /// Active icon overlays by row index: None spins, Some(0..=1) fills a circle.
7007 /// Rows absent from this complete snapshot have no overlay. Does not relayout rows.
7008 /// Currently rendered by AppKit/UIKit; other backends may ignore this decoration.
7009 IconProgress(Vec<(usize, Option<f64>)>),
7010 /// Programmatic highlight sync: toolkits apply without re-emitting
7011 /// `SelectionChanged` (the `TextField` `from_native` echo rule).
7012 Selected(Option<usize>),
7013 /// The item set changed (data-driven `nav().items(signal, …)`): rebuild the rows
7014 /// from these labels/icons, then apply `selected` (docs/navigation.md). Applied without
7015 /// re-emitting `SelectionChanged`.
7016 ///
7017 /// `rows_changed` is `Some` when the rows themselves are the ones already shown (same
7018 /// keys, sections and row menus) and only these rows' title, icon, tint or badge moved:
7019 /// a count ticking, a language change. A backend updates those rows in place (a tab's
7020 /// badge, a menu item's title) rather than rebuilding, which on most platforms re-lays
7021 /// the bar and replays its selection animation; one that cannot rebuilds as for `None`.
7022 Items {
7023 rows_changed: Option<Box<[usize]>>,
7024 document_keys: Box<[String]>,
7025 items: Vec<String>,
7026 icons: Vec<Option<String>>,
7027 badges: Vec<Option<String>>,
7028 badge_icons: Vec<Option<String>>,
7029 badge_tints: Vec<Option<Color>>,
7030 sections: Vec<Option<String>>,
7031 tints: Vec<Option<Color>>,
7032 menus: Vec<Vec<crate::MenuItem>>,
7033 /// [`NavMenuProps::movable`] for the new rows.
7034 movable: Vec<bool>,
7035 /// [`NavMenuProps::sorted`] for the new rows ([`NavMenuProps::regroup`] holds for
7036 /// the sidebar's life).
7037 sorted: Vec<bool>,
7038 selected: Option<usize>,
7039 },
7040 }
7041
7042 /// How a recycling list sizes its rows (docs/list.md).
7043 #[derive(Clone, Copy, Debug, PartialEq, Default)]
7044 pub enum RowHeight {
7045 /// Every row is this tall, a true layout boundary; the fastest path.
7046 Uniform(f64),
7047 /// Rows self-size from their content (host re-measures on change; slower).
7048 #[default]
7049 Automatic,
7050 }
7051
7052 /// Configure a navigation sidebar's native pull-to-refresh control. Not a synthetic pan:
7053 /// supported toolkits own gesture arbitration and the progress indicator. A false state
7054 /// ends a pull, including a request the application declines. Never emits an event.
7055 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
7056 pub struct RefreshPatch {
7057 pub refreshing: bool,
7058 }
7059
7060 /// Native recycling list (docs/list.md). The host owns scrolling + cell reuse; Day supplies
7061 /// row content on demand through the injected `ListSource` (see `Toolkit::attach_list`).
7062 #[derive(Clone, Debug, Default, PartialEq)]
7063 pub struct ListProps {
7064 /// Whether the app handles row activation. Do not claim activation keys when false.
7065 pub activatable: bool,
7066 pub row_height: RowHeight,
7067 /// Whether the native list reports row selection (`Event::SelectionChanged` with the row).
7068 pub selectable: bool,
7069 /// Whether the native list allows selecting several rows at once. Where honored
7070 /// (docs/list.md has the matrix), every selection change reports the full set via
7071 /// `Event::SelectionSet`; single-selection backends keep reporting
7072 /// `Event::SelectionChanged` and treat this as `selectable`.
7073 pub multi_select: bool,
7074 /// Whether rows can be drag-reordered. The toolkit enables its native drag machinery and
7075 /// drives `ListSource::reorder` (validate via `can_move`, commit via `move_row`);
7076 /// probe `Cap::ListReorder` for per-backend support (docs/list.md).
7077 pub reorderable: bool,
7078 /// Whether rows can be deleted by the platform's own delete gesture: a trailing swipe on
7079 /// iOS and ArkUI, an `ItemTouchHelper` swipe on Android. The toolkit drives
7080 /// `ListSource::delete` (offer via `can_delete`, commit via `delete_row`); probe
7081 /// `Cap::ListDelete` for per-backend support (docs/list.md). Desktop toolkits have no such
7082 /// gesture and answer `Unsupported`; an app that must delete everywhere pairs this with an
7083 /// explicit control (a menu item, a button) rather than relying on the swipe.
7084 pub deletable: bool,
7085 /// The label on that affordance, already localized by the app. A toolkit cannot invent
7086 /// translated text (it has no access to the app's catalog), so the string arrives with
7087 /// the props. Empty means "no text": each backend falls back to its platform's own
7088 /// wordless idiom (a trash glyph), which works in every language.
7089 pub delete_label: String,
7090 /// The rows offer edge swipe actions (docs/list.md) through the injected
7091 /// `ListSource::swipe` (offer via `actions_at`, commit via `perform`); probe
7092 /// [`crate::Cap::ListSwipeActions`] for per-backend support. A backend without the
7093 /// affordance never shows one; an app that must offer the command everywhere
7094 /// pairs the swipe with an explicit control, exactly as `deletable` documents.
7095 pub swipe_actions: bool,
7096 /// Row separators, drawn by the host at the row boundary (docs/list.md), so they
7097 /// align with the native selection and ride the platform's own row animations (a
7098 /// macOS/iOS swipe slides the row content past a stationary separator, exactly as
7099 /// Mail's does). `None` keeps each platform's own default (iOS draws them, the
7100 /// desktops don't); `Some(true)`/`Some(false)` forces. A backend without a separator
7101 /// mechanism ignores a force (the matrix in docs/list.md says which); rows there
7102 /// separate by their pitch alone.
7103 pub separators: Option<bool>,
7104 /// The list starts in the platform's editing mode (docs/list.md): delete controls on
7105 /// the rows `deletable` offers, reorder grips on the rows `reorderable` moves, and a
7106 /// tap that still activates. Later changes arrive as [`ListPatch::Editing`]. Probe
7107 /// [`crate::Cap::ListEditing`]; a backend without an editing mode ignores it.
7108 pub editing: bool,
7109 /// The rows fall into sections, each opened by a header row (docs/list.md
7110 /// "Sections"): `ListSource::is_header` says which rows. Probe
7111 /// [`crate::Cap::ListSections`] for whether headers float natively.
7112 pub sections: bool,
7113 /// Draw the rows as the platform's inset grouped list (docs/list.md "Appearance"):
7114 /// rounded groups set in from the edges on a grouped background, as iOS Settings and
7115 /// Safari's History draw them. ios-uikit (`UITableViewStyleInsetGrouped`) and
7116 /// macos-appkit (`NSTableViewStyleInset`); the other toolkits draw their plain list.
7117 pub inset_grouped: bool,
7118 }
7119
7120 /// One row-level result-set change. Indexes are sequential (each delta describes the
7121 /// set as the previous ones left it), so a host applies them one at a time (or falls back
7122 /// to a reload; the source's snapshot already holds the final state either way).
7123 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
7124 pub enum RowDelta {
7125 Insert(usize),
7126 Remove(usize),
7127 Move(usize, usize),
7128 }
7129
7130 /// Immutable-at-realize props of a `kinds::TREE` host (docs/tree.md). Everything that
7131 /// changes after realize flows through [`TreePatch`] or the injected `TreeSource`.
7132 #[derive(Clone, Debug, PartialEq)]
7133 pub struct TreeProps {
7134 /// Two-level sectioned list: root branches are non-selectable headings.
7135 pub section_headers: bool,
7136 pub row_height: RowHeight,
7137 /// Rows highlight and report selection ([`crate::Event::TreeSelection`]).
7138 pub selectable: bool,
7139 /// Several rows may be selected at once; every change reports the full token set.
7140 pub multi_select: bool,
7141 /// Rows drag to a new parent/position through the platform's own mechanism, driving
7142 /// `TreeSource::moves`. Probe [`crate::Cap::TreeMove`] for support.
7143 pub movable: bool,
7144 /// Indentation per depth level, in points. `None` = the platform's default step.
7145 pub indent: Option<f64>,
7146 }
7147
7148 /// Post-realize changes to a `kinds::TREE` host (docs/tree.md). Token-addressed
7149 /// throughout; see [`crate::TreeSource`] for why indices cannot address tree rows.
7150 #[derive(Clone, Debug, PartialEq)]
7151 pub enum TreePatch {
7152 /// The node set changed (count/order/parentage/content): the host re-queries its
7153 /// `TreeSource`. Expansion and selection survive by token (docs/tree.md).
7154 Reload,
7155 /// Programmatically disclose (`true`) or collapse (`false`) one row. Applied without
7156 /// re-emitting [`crate::Event::TreeExpanded`] (the from-native echo rule).
7157 Expand(u64, bool),
7158 /// Programmatic selection sync (tokens; empty = clear), applied without re-emitting
7159 /// [`crate::Event::TreeSelection`].
7160 Selected(Vec<u64>),
7161 /// Scroll this row into view, realizing it if needed. The piece has already expanded
7162 /// the row's ancestors (through the app's expansion signal) before issuing this.
7163 Reveal(u64),
7164 }
7165
7166 #[derive(Clone, Debug, PartialEq)]
7167 pub enum ListPatch {
7168 /// The row set changed (count/order/content): the host re-queries its `ListSource`.
7169 Reload,
7170 /// The row set changed by exactly these deltas: a host that can, animates each row
7171 /// in, out, or across; one that cannot treats this as [`ListPatch::Reload`]. The
7172 /// data source answers with the final state throughout.
7173 Splice(Vec<RowDelta>),
7174 /// An `Automatic`-height row was re-laid at a new height after its first layout (its
7175 /// text changed, a wrapped line appeared, the backend corrected its width): the host
7176 /// gives the row bound to physical cell `cell` (the handle `ListSource::bind_row` got,
7177 /// as `usize`) the new `height`, padding included, the same value
7178 /// `ListSource::cell_height` now answers for it.
7179 ///
7180 /// Sent from inside a day-core layout pass, with the tree borrowed: a host applies it
7181 /// after the pass (posted to its main loop), never by asking the source anything
7182 /// synchronously, which would read a `0.0` height (docs/list.md "Row heights").
7183 RowSizeInvalidated { cell: usize, height: f64 },
7184 /// Imperatively scroll the native list so its last row is fully visible (a chat timeline
7185 /// sticking to the newest message). No-op when the list is empty (docs/list.md).
7186 ScrollToEnd,
7187 /// Imperatively scroll the native list so this row is visible, realizing it if needed
7188 /// (docs/list.md). Clamped to the row count; no-op when the list is empty.
7189 ScrollToRow(usize),
7190 /// Programmatic selection sync (row indices; empty = clear): toolkits apply without
7191 /// re-emitting a selection event, like every other programmatic sync.
7192 Selected(Vec<usize>),
7193 /// Enter (`true`) or leave (`false`) the platform's list editing mode, animated
7194 /// (docs/list.md, [`ListProps::editing`]). Ignored where `Cap::ListEditing` is
7195 /// `Unsupported`.
7196 Editing(bool),
7197 }
7198}
7199
7200// ---------------------------------------------------------------------------
7201// Imperative presentation (docs/dialogs.md)
7202// ---------------------------------------------------------------------------
7203
7204/// Sharing (docs/sharing.md): what [`Toolkit::share`] presents.
7205pub mod share {
7206 use crate::Symbol;
7207
7208 /// A share request: the page or link to share, and the app's own actions to offer beside
7209 /// the system's targets.
7210 #[derive(Clone, Debug, Default, PartialEq)]
7211 pub struct ShareSpec {
7212 /// The URL handed to the chosen target.
7213 pub url: String,
7214 /// Its title: the subject of a mail, the header of the chooser where it shows one.
7215 pub title: String,
7216 /// The app's actions, in order (`Cap::ShareActions`).
7217 pub actions: Vec<ShareAction>,
7218 }
7219
7220 /// One of the app's actions in a share chooser.
7221 #[derive(Clone, Debug, PartialEq)]
7222 pub struct ShareAction {
7223 /// The dispatch id a choice reports, as `Event::MenuAction(id)`.
7224 pub id: u64,
7225 /// The action's name, already localized.
7226 pub title: String,
7227 /// Its glyph, where the chooser draws one.
7228 pub symbol: Option<Symbol>,
7229 }
7230}
7231
7232pub mod present {
7233 /// A dialog button's semantic role: styling + default/cancel placement on each toolkit.
7234 #[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
7235 pub enum ButtonRole {
7236 #[default]
7237 Default,
7238 Cancel,
7239 Destructive,
7240 }
7241
7242 #[derive(Clone, Debug, PartialEq)]
7243 pub struct PresentButton {
7244 pub label: String,
7245 pub role: ButtonRole,
7246 }
7247
7248 /// A named group of file extensions for a file dialog (e.g. "Text" → `["txt", "md"]`).
7249 /// An empty `extensions` list means "all files".
7250 #[derive(Clone, Debug, PartialEq, Default)]
7251 pub struct FileFilter {
7252 pub name: String,
7253 pub extensions: Vec<String>,
7254 }
7255
7256 /// What a backend should present for a `req`. Kept toolkit-agnostic; the pieces layer
7257 /// maps a chosen button index back to a typed payload.
7258 #[derive(Clone, Debug, PartialEq)]
7259 pub enum PresentSpec {
7260 /// Alert / confirmation / action sheet: title + optional message + ordered buttons.
7261 /// `sheet` = present from the bottom on mobile (desktop falls back to an alert).
7262 Dialog {
7263 title: String,
7264 message: Option<String>,
7265 buttons: Vec<PresentButton>,
7266 sheet: bool,
7267 },
7268 /// A dialog with a single text field.
7269 Prompt {
7270 title: String,
7271 message: Option<String>,
7272 placeholder: String,
7273 initial: String,
7274 ok: String,
7275 cancel: String,
7276 },
7277 /// Native "open file" picker (docs/files.md). The backend must answer with
7278 /// `PresentResult::Files` whose entries are **readable local paths**: desktop returns
7279 /// the chosen path directly; iOS/Android copy the selection into app storage first, so
7280 /// the pieces layer can read it with `std::fs` regardless of platform. `multiple` lets
7281 /// the user pick several files at once; the answer then carries every chosen path, in
7282 /// the picker's order. A backend that cannot select more than one file still answers
7283 /// with the single pick.
7284 OpenFile {
7285 title: String,
7286 filters: Vec<FileFilter>,
7287 multiple: bool,
7288 },
7289 /// Native "choose folder" picker (docs/files.md). The backend answers with
7290 /// `PresentResult::Files` holding the one chosen directory path, or `Dismissed`. Only
7291 /// backends answering [`Cap::FolderDialog`](crate::Cap::FolderDialog) as `Native` show a
7292 /// chooser; the others resolve the request as `Dismissed` at once, so the await never hangs.
7293 OpenFolder { title: String },
7294 /// Native "save file" picker (docs/files.md). `src_path` is a Day-written temp file
7295 /// holding the bytes to save; iOS/Android deliver it to the chosen destination natively,
7296 /// and the pieces layer best-effort copies it to a chosen local path otherwise.
7297 SaveFile {
7298 title: String,
7299 suggested_name: String,
7300 src_path: String,
7301 filters: Vec<FileFilter>,
7302 },
7303 }
7304
7305 /// The user's answer to a presentation.
7306 #[derive(Clone, Debug, PartialEq)]
7307 pub enum PresentResult {
7308 /// A dialog button at `index` (in spec order) was chosen.
7309 Button(i64),
7310 /// A prompt was confirmed with `text`.
7311 Text(String),
7312 /// One or more file locators chosen from an open/save picker (docs/files.md). Each is a
7313 /// local filesystem path or, on Android save, a `content://` URI.
7314 Files(Vec<String>),
7315 /// Dismissed without choosing (tap-outside / Esc / cancel gesture).
7316 Dismissed,
7317 }
7318
7319 /// The unit-separator that joins string lists across the C ABI (Qt shim / Android JNI), the
7320 /// same encoding the nav menu, combobox, and dialog-button shims use.
7321 pub const UNIT_SEP: char = '\u{1f}';
7322
7323 std::thread_local! {
7324 /// An app-writable scratch directory. Backends whose OS temp dir isn't app-writable
7325 /// (Android → `getCacheDir()`) set this at startup; elsewhere it stays `None` and callers
7326 /// fall back to `std::env::temp_dir()`.
7327 // False positive, and only when checking an android target: the initializer already is
7328 // the `const` block the lint asks for. Android's TLS model makes the macro expand to a
7329 // form clippy reads as lazy, so the suggestion is unfollowable as well as unneeded.
7330 #[allow(clippy::missing_const_for_thread_local)]
7331 static APP_TEMP_DIR: std::cell::RefCell<Option<std::path::PathBuf>> =
7332 const { std::cell::RefCell::new(None) };
7333 }
7334
7335 /// Record an app-writable scratch directory (see [`app_temp_dir`]). Called by a backend at
7336 /// startup when the OS temp dir isn't writable by the app (Android).
7337 pub fn set_app_temp_dir(dir: impl Into<std::path::PathBuf>) {
7338 APP_TEMP_DIR.with(|d| *d.borrow_mut() = Some(dir.into()));
7339 }
7340
7341 /// An app-writable scratch directory: the backend-supplied one, else `std::env::temp_dir()`.
7342 /// Used by the file-save flow (docs/files.md) to stage bytes before the native save picker.
7343 #[must_use]
7344 pub fn app_temp_dir() -> std::path::PathBuf {
7345 APP_TEMP_DIR.with(|d| {
7346 d.borrow().clone().unwrap_or_else(|| {
7347 #[cfg(target_arch = "wasm32")]
7348 {
7349 // A browser has no filesystem and std's `temp_dir()` panics on wasm. A
7350 // nominal path keeps join/display plumbing alive; actual reads and writes
7351 // fail with ordinary io errors the file flows already surface.
7352 std::path::PathBuf::from("/day-tmp")
7353 }
7354 #[cfg(not(target_arch = "wasm32"))]
7355 std::env::temp_dir()
7356 })
7357 })
7358 }
7359
7360 /// The web build's file bytes (wasm32-unknown-unknown only): a browser has no filesystem,
7361 /// so the open/save flows carry bytes through this per-page store instead of `std::fs`:
7362 /// day-toolkit-dom writes a picked file's bytes here and answers with its virtual path; the pieces
7363 /// layer stages save bytes here for the shim to download. Paths are plain strings under
7364 /// `/day-web/`; lifetimes are one picker round-trip (the flows remove what they stage).
7365 #[cfg(all(target_family = "wasm", target_os = "unknown"))]
7366 pub mod web_files {
7367 std::thread_local! {
7368 static FILES: std::cell::RefCell<std::collections::HashMap<String, Vec<u8>>> =
7369 std::cell::RefCell::new(std::collections::HashMap::new());
7370 }
7371
7372 /// Store `bytes` under `path` (replacing any prior content).
7373 pub fn write(path: &str, bytes: Vec<u8>) {
7374 FILES.with(|f| f.borrow_mut().insert(path.to_string(), bytes));
7375 }
7376
7377 /// The bytes at `path`, if present.
7378 #[must_use]
7379 pub fn read(path: &str) -> Option<Vec<u8>> {
7380 FILES.with(|f| f.borrow().get(path).cloned())
7381 }
7382
7383 /// Drop `path`'s bytes.
7384 pub fn remove(path: &str) {
7385 FILES.with(|f| {
7386 f.borrow_mut().remove(path);
7387 });
7388 }
7389 }
7390
7391 impl PresentResult {
7392 /// Flat wire tag for the C ABI (Qt shim / Android JNI): 0 dismissed, 1 button, 2 text,
7393 /// 3 files (`text` is the chosen locators joined by the unit separator).
7394 pub fn decode(tag: i32, index: i64, text: String) -> PresentResult {
7395 match tag {
7396 1 => PresentResult::Button(index),
7397 2 => PresentResult::Text(text),
7398 3 => PresentResult::Files(
7399 text.split(UNIT_SEP)
7400 .filter(|s| !s.is_empty())
7401 .map(str::to_string)
7402 .collect(),
7403 ),
7404 _ => PresentResult::Dismissed,
7405 }
7406 }
7407 }
7408
7409 impl PresentSpec {
7410 /// Backend-facing flattening for the C ABI: `(title, message, button labels, button
7411 /// roles as ints, sheet-or-prompt fields)`. Pure-Rust backends read the enum directly.
7412 #[must_use]
7413 pub fn title(&self) -> &str {
7414 match self {
7415 PresentSpec::Dialog { title, .. }
7416 | PresentSpec::Prompt { title, .. }
7417 | PresentSpec::OpenFile { title, .. }
7418 | PresentSpec::OpenFolder { title }
7419 | PresentSpec::SaveFile { title, .. } => title,
7420 }
7421 }
7422 #[must_use]
7423 pub fn message(&self) -> Option<&str> {
7424 match self {
7425 PresentSpec::Dialog { message, .. } | PresentSpec::Prompt { message, .. } => {
7426 message.as_deref()
7427 }
7428 _ => None,
7429 }
7430 }
7431 /// Button labels joined with [`UNIT_SEP`], the encoding the nav menu and combobox
7432 /// shims already use for string lists.
7433 #[must_use]
7434 pub fn buttons_joined(&self) -> String {
7435 match self {
7436 PresentSpec::Dialog { buttons, .. } => buttons
7437 .iter()
7438 .map(|b| b.label.as_str())
7439 .collect::<Vec<_>>()
7440 .join(&UNIT_SEP.to_string()),
7441 PresentSpec::Prompt { ok, cancel, .. } => format!("{ok}{UNIT_SEP}{cancel}"),
7442 _ => String::new(),
7443 }
7444 }
7445 /// Button roles as ints (0 default, 1 cancel, 2 destructive), joined with commas.
7446 #[must_use]
7447 pub fn roles_joined(&self) -> String {
7448 let roles: Vec<i32> = match self {
7449 PresentSpec::Dialog { buttons, .. } => {
7450 buttons.iter().map(|b| b.role as i32).collect()
7451 }
7452 PresentSpec::Prompt { .. } => {
7453 vec![ButtonRole::Default as i32, ButtonRole::Cancel as i32]
7454 }
7455 _ => vec![],
7456 };
7457 roles
7458 .iter()
7459 .map(std::string::ToString::to_string)
7460 .collect::<Vec<_>>()
7461 .join(",")
7462 }
7463
7464 // --- file-dialog accessors (docs/files.md) ---
7465
7466 /// The file filters, if this is a file dialog.
7467 #[must_use]
7468 pub fn filters(&self) -> &[FileFilter] {
7469 match self {
7470 PresentSpec::OpenFile { filters, .. } | PresentSpec::SaveFile { filters, .. } => {
7471 filters
7472 }
7473 _ => &[],
7474 }
7475 }
7476 /// Whether an open-file dialog lets the user pick several files (`false` for every
7477 /// other spec).
7478 #[must_use]
7479 pub fn multiple(&self) -> bool {
7480 matches!(self, PresentSpec::OpenFile { multiple: true, .. })
7481 }
7482 /// The suggested file name for a save dialog (empty otherwise).
7483 #[must_use]
7484 pub fn suggested_name(&self) -> &str {
7485 match self {
7486 PresentSpec::SaveFile { suggested_name, .. } => suggested_name,
7487 _ => "",
7488 }
7489 }
7490 /// The Day-written temp source path for a save dialog (empty otherwise).
7491 #[must_use]
7492 pub fn src_path(&self) -> &str {
7493 match self {
7494 PresentSpec::SaveFile { src_path, .. } => src_path,
7495 _ => "",
7496 }
7497 }
7498 /// Filters flattened for the C ABI: each filter is `name|ext1,ext2`, joined by
7499 /// [`UNIT_SEP`]. A trailing `|` (no extensions) means "all files". Empty when unfiltered.
7500 #[must_use]
7501 pub fn filters_joined(&self) -> String {
7502 self.filters()
7503 .iter()
7504 .map(|f| format!("{}|{}", f.name, f.extensions.join(",")))
7505 .collect::<Vec<_>>()
7506 .join(&UNIT_SEP.to_string())
7507 }
7508 }
7509}
7510
7511// ---------------------------------------------------------------------------
7512// App directories (docs/fs.md "Where files live")
7513// ---------------------------------------------------------------------------
7514
7515/// Where an app keeps its own files: its data, cache and configuration directories, each a
7516/// folder named after the app id in the place its platform sets aside for that kind of file
7517/// (docs/fs.md "Where files live"). Every Day crate that stores files resolves them here, so an
7518/// app's database, documents, caches, settings file and remembered window frames sit together
7519/// and apart from every other app's.
7520///
7521/// These only resolve paths; nothing is created until something is written. Each is `None` where
7522/// the platform has no such directory: the web, or an Android or HarmonyOS process whose host
7523/// passed none.
7524pub mod storage {
7525 use std::path::PathBuf;
7526
7527 /// The app's id, `[app] id` from Day.toml: `DAY_APP_ID` from `day launch`, else the value
7528 /// `day build` baked in, else the executable's name (a test binary or a bare `cargo run`).
7529 /// Made safe as a single folder name.
7530 #[must_use]
7531 pub fn app_id() -> String {
7532 std::env::var("DAY_APP_ID")
7533 .ok()
7534 .filter(|id| !id.is_empty())
7535 .or_else(|| {
7536 option_env!("DAY_APP_ID")
7537 .filter(|id| !id.is_empty())
7538 .map(str::to_owned)
7539 })
7540 .or_else(|| {
7541 let exe = std::env::current_exe().ok()?;
7542 exe.file_stem()?.to_str().map(str::to_owned)
7543 })
7544 .map_or_else(|| "day-app".to_owned(), |id| folder_name(&id))
7545 }
7546
7547 /// The app's data directory, for what it cannot recreate: databases, documents, downloads
7548 /// the user kept. Application Support on Apple platforms (inside the container when
7549 /// sandboxed), `%LOCALAPPDATA%` on Windows, `$XDG_DATA_HOME` on Linux, the app's files
7550 /// directory on Android and HarmonyOS. `DAY_DATA_DIR` replaces it.
7551 #[must_use]
7552 pub fn data_dir() -> Option<PathBuf> {
7553 resolve(Dir::Data, Os::HOST, &app_id(), &env_path)
7554 }
7555
7556 /// [`data_dir`] for the app `app_id` rather than this process's own: a host that keeps a
7557 /// folder per hosted app (a day-lite superapp, a crash reporter's store), or a tool finding
7558 /// where an app it launched writes. On Android and HarmonyOS, where the host's directory is
7559 /// already the one app's, the id changes nothing.
7560 #[must_use]
7561 pub fn data_dir_for(app_id: &str) -> Option<PathBuf> {
7562 resolve(Dir::Data, Os::HOST, &folder_name(app_id), &env_path)
7563 }
7564
7565 /// The app's cache directory, for what it can fetch or compute again: the system may clear
7566 /// it, and backups skip it. Caches on Apple platforms, `%LOCALAPPDATA%\<id>\cache` on
7567 /// Windows, `$XDG_CACHE_HOME` on Linux, the app's cache directory on Android and HarmonyOS.
7568 /// `DAY_CACHE_DIR` replaces it; with only `DAY_DATA_DIR` set it is that directory's `cache`.
7569 #[must_use]
7570 pub fn cache_dir() -> Option<PathBuf> {
7571 resolve(Dir::Cache, Os::HOST, &app_id(), &env_path)
7572 }
7573
7574 /// The app's configuration directory, for small settings files: Application Support on
7575 /// Apple platforms (whose preferences proper are the user defaults), the roaming
7576 /// `%APPDATA%` on Windows, `$XDG_CONFIG_HOME` on Linux. With `DAY_DATA_DIR` set (as the
7577 /// Android and HarmonyOS hosts do) it is that directory's `config`.
7578 #[must_use]
7579 pub fn config_dir() -> Option<PathBuf> {
7580 resolve(Dir::Config, Os::HOST, &app_id(), &env_path)
7581 }
7582
7583 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
7584 enum Dir {
7585 Data,
7586 Cache,
7587 Config,
7588 }
7589
7590 /// The platform families whose conventions differ.
7591 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
7592 enum Os {
7593 /// macOS and iOS: `~/Library`, which is the app's container when sandboxed.
7594 Apple,
7595 Windows,
7596 /// Android and HarmonyOS: the host passes the app's private directories.
7597 Hosted,
7598 /// Linux and the BSDs: the XDG base directories.
7599 Unix,
7600 Web,
7601 }
7602
7603 impl Os {
7604 const HOST: Os = if cfg!(any(target_os = "macos", target_os = "ios")) {
7605 Os::Apple
7606 } else if cfg!(target_os = "windows") {
7607 Os::Windows
7608 } else if cfg!(any(target_os = "android", target_env = "ohos")) {
7609 Os::Hosted
7610 } else if cfg!(target_family = "wasm") {
7611 Os::Web
7612 } else {
7613 Os::Unix
7614 };
7615 }
7616
7617 /// An environment variable naming a directory: set, non-empty and absolute, else ignored.
7618 fn env_path(name: &str) -> Option<PathBuf> {
7619 let path = PathBuf::from(std::env::var_os(name)?);
7620 path.is_absolute().then_some(path)
7621 }
7622
7623 /// One folder name: no separators, no `.`/`..`, nothing a filesystem rejects.
7624 fn folder_name(id: &str) -> String {
7625 let name: String = id
7626 .chars()
7627 .map(|c| match c {
7628 '/' | '\\' | ':' | '*' | '?' | '"' | '<' | '>' | '|' => '_',
7629 c if c.is_control() => '_',
7630 c => c,
7631 })
7632 .collect();
7633 match name.trim() {
7634 "" | "." | ".." => "day-app".to_owned(),
7635 name => name.to_owned(),
7636 }
7637 }
7638
7639 /// The pure resolution, over a platform and an environment, so every platform's rules are
7640 /// testable on any host.
7641 fn resolve(
7642 dir: Dir,
7643 os: Os,
7644 id: &str,
7645 var: &dyn Fn(&str) -> Option<PathBuf>,
7646 ) -> Option<PathBuf> {
7647 // The explicit overrides: a mobile host's own directories, or a test's scratch root.
7648 if dir == Dir::Cache
7649 && let Some(cache) = var("DAY_CACHE_DIR")
7650 {
7651 return Some(cache);
7652 }
7653 if let Some(data) = var("DAY_DATA_DIR") {
7654 return Some(match dir {
7655 Dir::Data => data,
7656 Dir::Cache => data.join("cache"),
7657 Dir::Config => data.join("config"),
7658 });
7659 }
7660 let home = || var("HOME");
7661 match os {
7662 // One expression serves sandboxed and unsandboxed apps: inside the App Sandbox,
7663 // and always on iOS, `HOME` is the container's Data folder, so the same Library
7664 // path lands inside it. Apple asks for a bundle-id folder within Application
7665 // Support and Caches either way. XDG variables are ignored here: a Finder launch
7666 // never sees a shell's, so honoring them would split one app's data across two
7667 // places depending on how it was started.
7668 Os::Apple => {
7669 let library = home()?.join("Library");
7670 let base = match dir {
7671 Dir::Data | Dir::Config => library.join("Application Support"),
7672 Dir::Cache => library.join("Caches"),
7673 };
7674 Some(base.join(id))
7675 }
7676 // Local for data and caches: a database or cache roams badly, and a DPAPI-sealed
7677 // file cannot be read on another machine. Roaming for the small settings files.
7678 Os::Windows => {
7679 let profile = |leaf: &str| Some(var("USERPROFILE")?.join("AppData").join(leaf));
7680 let local = || var("LOCALAPPDATA").or_else(|| profile("Local"));
7681 match dir {
7682 Dir::Data => Some(local()?.join(id)),
7683 Dir::Cache => Some(local()?.join(id).join("cache")),
7684 Dir::Config => Some(var("APPDATA").or_else(|| profile("Roaming"))?.join(id)),
7685 }
7686 }
7687 Os::Unix => {
7688 let (xdg, fallback) = match dir {
7689 Dir::Data => ("XDG_DATA_HOME", ".local/share"),
7690 Dir::Cache => ("XDG_CACHE_HOME", ".cache"),
7691 Dir::Config => ("XDG_CONFIG_HOME", ".config"),
7692 };
7693 Some(var(xdg).or_else(|| Some(home()?.join(fallback)))?.join(id))
7694 }
7695 Os::Hosted | Os::Web => None,
7696 }
7697 }
7698
7699 #[cfg(test)]
7700 mod tests {
7701 use super::*;
7702 use std::collections::HashMap;
7703
7704 /// The resolved path as text. `Path::join` uses the host's separator, so on a Windows host
7705 /// another platform's path comes back with `\` between the joined parts; the expectations
7706 /// are that platform's own, so its separators are compared as `/`.
7707 fn at(os: Os, dir: Dir, vars: &[(&str, &str)]) -> Option<String> {
7708 let vars: HashMap<&str, &str> = vars.iter().copied().collect();
7709 let var = |name: &str| vars.get(name).map(PathBuf::from);
7710 resolve(dir, os, "dev.example.notes", &var).map(|p| {
7711 let text = p.display().to_string();
7712 if os == Os::Windows {
7713 text
7714 } else {
7715 text.replace('\\', "/")
7716 }
7717 })
7718 }
7719
7720 #[test]
7721 fn apple_uses_library_folders_named_for_the_app() {
7722 let home = [("HOME", "/Users/ada"), ("XDG_DATA_HOME", "/Users/ada/.xdg")];
7723 let support = "/Users/ada/Library/Application Support/dev.example.notes";
7724 assert_eq!(at(Os::Apple, Dir::Data, &home).as_deref(), Some(support));
7725 assert_eq!(at(Os::Apple, Dir::Config, &home).as_deref(), Some(support));
7726 assert_eq!(
7727 at(Os::Apple, Dir::Cache, &home).as_deref(),
7728 Some("/Users/ada/Library/Caches/dev.example.notes")
7729 );
7730 // A sandboxed app's HOME is its container, so its folders land inside it.
7731 let container = [(
7732 "HOME",
7733 "/Users/ada/Library/Containers/dev.example.notes/Data",
7734 )];
7735 assert_eq!(
7736 at(Os::Apple, Dir::Data, &container).as_deref(),
7737 Some(
7738 "/Users/ada/Library/Containers/dev.example.notes/Data/Library/Application Support/dev.example.notes"
7739 )
7740 );
7741 }
7742
7743 #[test]
7744 fn windows_keeps_data_local_and_settings_roaming() {
7745 let vars = [
7746 ("LOCALAPPDATA", r"C:\Users\ada\AppData\Local"),
7747 ("APPDATA", r"C:\Users\ada\AppData\Roaming"),
7748 ];
7749 let data = at(Os::Windows, Dir::Data, &vars).unwrap_or_default();
7750 assert!(data.starts_with(r"C:\Users\ada\AppData\Local"), "{data}");
7751 assert!(data.ends_with("dev.example.notes"), "{data}");
7752 let cache = at(Os::Windows, Dir::Cache, &vars).unwrap_or_default();
7753 assert!(cache.ends_with("cache"), "{cache}");
7754 let config = at(Os::Windows, Dir::Config, &vars).unwrap_or_default();
7755 assert!(
7756 config.starts_with(r"C:\Users\ada\AppData\Roaming"),
7757 "{config}"
7758 );
7759 }
7760
7761 #[test]
7762 fn unix_follows_xdg_then_home() {
7763 let xdg = [
7764 ("HOME", "/home/ada"),
7765 ("XDG_DATA_HOME", "/data"),
7766 ("XDG_CACHE_HOME", "/cache"),
7767 ("XDG_CONFIG_HOME", "/config"),
7768 ];
7769 assert_eq!(
7770 at(Os::Unix, Dir::Data, &xdg).as_deref(),
7771 Some("/data/dev.example.notes")
7772 );
7773 assert_eq!(
7774 at(Os::Unix, Dir::Cache, &xdg).as_deref(),
7775 Some("/cache/dev.example.notes")
7776 );
7777 assert_eq!(
7778 at(Os::Unix, Dir::Config, &xdg).as_deref(),
7779 Some("/config/dev.example.notes")
7780 );
7781 let home = [("HOME", "/home/ada")];
7782 assert_eq!(
7783 at(Os::Unix, Dir::Data, &home).as_deref(),
7784 Some("/home/ada/.local/share/dev.example.notes")
7785 );
7786 assert_eq!(
7787 at(Os::Unix, Dir::Cache, &home).as_deref(),
7788 Some("/home/ada/.cache/dev.example.notes")
7789 );
7790 assert_eq!(
7791 at(Os::Unix, Dir::Config, &home).as_deref(),
7792 Some("/home/ada/.config/dev.example.notes")
7793 );
7794 }
7795
7796 #[test]
7797 fn hosts_and_tests_override_every_platform() {
7798 let host = [
7799 ("DAY_DATA_DIR", "/data/user/0/dev.example.notes/files"),
7800 ("DAY_CACHE_DIR", "/data/user/0/dev.example.notes/cache"),
7801 ];
7802 for os in [Os::Hosted, Os::Apple, Os::Windows, Os::Unix] {
7803 assert_eq!(
7804 at(os, Dir::Data, &host).as_deref(),
7805 Some("/data/user/0/dev.example.notes/files")
7806 );
7807 assert_eq!(
7808 at(os, Dir::Cache, &host).as_deref(),
7809 Some("/data/user/0/dev.example.notes/cache")
7810 );
7811 }
7812 let scratch = [("HOME", "/Users/ada"), ("DAY_DATA_DIR", "/tmp/run")];
7813 assert_eq!(
7814 at(Os::Apple, Dir::Cache, &scratch).as_deref(),
7815 Some("/tmp/run/cache")
7816 );
7817 assert_eq!(
7818 at(Os::Apple, Dir::Config, &scratch).as_deref(),
7819 Some("/tmp/run/config")
7820 );
7821 // Without a host directory there is nowhere to put anything.
7822 assert_eq!(at(Os::Hosted, Dir::Data, &[("HOME", "/")]), None);
7823 assert_eq!(at(Os::Web, Dir::Data, &[("HOME", "/")]), None);
7824 }
7825
7826 #[test]
7827 fn app_ids_become_one_folder_name() {
7828 assert_eq!(folder_name("dev.daybrite.news"), "dev.daybrite.news");
7829 assert_eq!(folder_name("a/b\\c:d"), "a_b_c_d");
7830 assert_eq!(folder_name(".."), "day-app");
7831 assert_eq!(folder_name(""), "day-app");
7832 }
7833 }
7834}
7835
7836// ---------------------------------------------------------------------------
7837// The Toolkit trait (§8.1)
7838// ---------------------------------------------------------------------------
7839
7840/// Timing supplied by a native display scheduler. Seconds on a monotonic clock; its epoch
7841/// is platform-specific. `target_timestamp` is absent when the platform cannot predict presentation.
7842#[derive(Clone, Copy, Debug, PartialEq)]
7843pub struct FrameStamp {
7844 pub timestamp: f64,
7845 pub target_timestamp: Option<f64>,
7846}
7847impl FrameStamp {
7848 #[must_use]
7849 pub fn new(timestamp: f64) -> Self {
7850 Self {
7851 timestamp,
7852 target_timestamp: None,
7853 }
7854 }
7855}
7856/// A one-shot native frame callback, always delivered asynchronously on the UI thread.
7857pub type FrameCallback = Box<dyn FnOnce(FrameStamp)>;
7858/// Cancels a pending callback and releases its native registration. UI-thread only, idempotent
7859/// in effect, and safe during/after delivery. Dropping without calling is allowed after delivery.
7860pub type CancelFrame = Box<dyn FnOnce()>;
7861
7862/// The margins and minimum height a native list gives each row ([`Toolkit::list_row_metrics`],
7863/// docs/list.md "Row metrics"): a `UITableView` cell's layout margins, a Material list item's
7864/// 16dp sides and 56dp height.
7865#[derive(Clone, Copy, Debug, Default, PartialEq)]
7866pub struct RowMetrics {
7867 /// Space between the row's edges and its content.
7868 pub insets: Insets,
7869 /// The least height a row takes, margins included; content centers vertically in it.
7870 pub min_height: f64,
7871}
7872
7873/// Platform colors for custom drawing. Native controls keep their own semantic styling.
7874#[derive(Clone, Copy, Debug, PartialEq, Eq)]
7875#[repr(u8)]
7876pub enum SystemColor {
7877 Accent,
7878 Text,
7879 SecondaryText,
7880 Background,
7881 Surface,
7882}
7883
7884impl SystemColor {
7885 /// All roles, in discriminant order, for toolkit palette snapshots.
7886 pub const ALL: [Self; 5] = [
7887 Self::Accent,
7888 Self::Text,
7889 Self::SecondaryText,
7890 Self::Background,
7891 Self::Surface,
7892 ];
7893
7894 /// Day's fallback palette when the toolkit cannot resolve a role.
7895 /// These are fixed sRGB colors, not an approximation of a user-selected system accent.
7896 pub const fn fallback(self, dark: bool) -> Color {
7897 Color::hex(match (self, dark) {
7898 (Self::Accent, false) => 0x000a_66ff,
7899 (Self::Accent, true) => 0x003f_83ff,
7900 (Self::Text, false) => 0x001d_1d1f,
7901 (Self::Text, true) => 0x00f5_f5f7,
7902 (Self::SecondaryText, false) => 0x006e_6e73,
7903 (Self::SecondaryText, true) => 0x0098_989d,
7904 (Self::Background, false) => 0x00ff_ffff,
7905 (Self::Background, true) => 0x001e_1e20,
7906 (Self::Surface, false) => 0x00f3_f2f7,
7907 (Self::Surface, true) => 0x002c_2c2e,
7908 })
7909 }
7910}
7911
7912pub trait Toolkit: Sized + 'static {
7913 // `'static` so a handle clone can cross the object-safe TreeOps boundary boxed as `Any`
7914 // (`node_handle_any`, the tweaks door, docs/tweaks.md).
7915 type Handle: Clone + 'static;
7916
7917 /// Request one frame for the window containing `host`. Never call inline. Each native source
7918 /// must stop after delivery unless requested again; no polling timer. Hidden/unmapped windows
7919 /// may defer delivery until visible. Native callbacks must reach the UI thread before calling
7920 /// Rust. The returned closure cancels safely, including when the window has closed.
7921 /// The mock intentionally stays pending: tests inject a manual scheduler in day-core.
7922 fn request_frame(&mut self, _host: &Self::Handle, _cb: FrameCallback) -> CancelFrame {
7923 Box::new(|| {})
7924 }
7925
7926 fn capability(&self, _cap: Cap) -> Support {
7927 Support::Unsupported
7928 }
7929
7930 // node lifecycle
7931 fn realize(&mut self, kind: PieceKind, props: &dyn Any, id: NodeId) -> Self::Handle;
7932 fn update(
7933 &mut self,
7934 h: &Self::Handle,
7935 kind: PieceKind,
7936 patch: &dyn Any,
7937 anim: Option<&AnimSpec>,
7938 );
7939 /// Called from the turn-boundary release queue; backends may defer destruction further.
7940 fn release(&mut self, h: Self::Handle);
7941 /// Give a satellite piece a chance to drop its own per-view state, immediately before
7942 /// [`release`](Toolkit::release) frees `h` (§15.2).
7943 ///
7944 /// A backend that hosts third-party pieces implements this by looking `kind` up in its renderer
7945 /// registry and calling that piece's `release` hook. Defaulted to nothing: a backend with no
7946 /// registry has nothing to dispatch, and one that has not wired this yet leaves piece
7947 /// teardown unrun rather than failing to build.
7948 fn release_piece(&mut self, _kind: PieceKind, _h: &Self::Handle) {}
7949
7950 // tree
7951 fn insert(&mut self, parent: &Self::Handle, child: &Self::Handle, index: usize);
7952 fn remove(&mut self, parent: &Self::Handle, child: &Self::Handle);
7953 /// Put `child` at index `to` among `parent`'s native children: day's z-order resync, which
7954 /// walks the whole sibling row and asks for every position in turn. A child already at `to`
7955 /// must therefore cost nothing: a backend that re-parents unconditionally pays for the
7956 /// untouched siblings too, and where re-parenting means detach-then-add (no `ViewGroup` move
7957 /// primitive on Android) the detach resigns the focus of everything inside the subtree,
7958 /// which is how a text field being typed into loses the keyboard (docs/focus.md).
7959 fn move_child(&mut self, parent: &Self::Handle, child: &Self::Handle, to: usize);
7960
7961 // geometry (§7): frames are in the nearest realized native ancestor's space, in points.
7962 fn measure(&mut self, h: &Self::Handle, kind: PieceKind, p: Proposal) -> Size;
7963 /// Distance from the top of the widget's frame to its first text baseline, in points, when
7964 /// the widget is `size` (docs/baseline.md). `None` ⇒ it has no text baseline (an image, a
7965 /// slider, a bare container) and a baseline-aligned row falls back to box alignment for it.
7966 ///
7967 /// This is a measurement, not a layout mode: day places every frame itself (§7.1) and never
7968 /// hands a row to a native baseline-aligning container, so what it needs from the toolkit is
7969 /// where the text sits inside the box. Backends that cannot answer keep the default and rows
7970 /// stay centered, which is what every row did before this existed.
7971 fn first_baseline(&mut self, _h: &Self::Handle, _kind: PieceKind, _size: Size) -> Option<f64> {
7972 None
7973 }
7974 fn set_frame(&mut self, h: &Self::Handle, frame: Rect, anim: Option<&AnimSpec>);
7975
7976 // animatable visual channels (§8.4): cheap per-node opacity + transform that don't relayout.
7977 // Defaulted no-ops so backends adopt them incrementally; `anim = Some` ⇒ animate to the value
7978 // on the toolkit's own compositor, `None` ⇒ set instantly.
7979 fn set_opacity(&mut self, _h: &Self::Handle, _opacity: f64, _anim: Option<&AnimSpec>) {}
7980 fn set_transform(
7981 &mut self,
7982 _h: &Self::Handle,
7983 _t: Transform,
7984 _size: Size,
7985 _anim: Option<&AnimSpec>,
7986 ) {
7987 }
7988
7989 // text selection (docs/text.md): make this node's text user-selectable (copy/drag). Applied
7990 // once from the `.selectable()` modifier (day-pieces) to the widget it wraps (a `label`'s
7991 // native text view, most usefully). Unmanaged: Day sets it here and never patches it, so it
7992 // survives text updates. The default no-op means a backend without a selection affordance
7993 // silently leaves the text unselectable.
7994 //
7995 // Returns `Some(replacement)` when the toolkit had to rebuild the widget as a different
7996 // native class to gain a selection affordance (UIKit: `UILabel` has none, so the label
7997 // becomes a read-only `UITextView`); day-core re-points the node's handle at the
7998 // replacement, so later patches and layout reach the widget that is actually on screen.
7999 // Every property-flip backend returns `None`.
8000 fn set_selectable(&mut self, _h: &Self::Handle, _selectable: bool) -> Option<Self::Handle> {
8001 None
8002 }
8003
8004 // text entry (docs/textfield.md): how a `text_field` takes its text: hidden characters,
8005 // read-only, the keyboard and autofill purpose, the action key, the length bound. Called
8006 // once after `realize` when a field asks for anything but the defaults, and again with the
8007 // whole set whenever a reactive member changes, so the setter is idempotent.
8008 //
8009 // Returns `Some(replacement)` when hiding the characters takes a different native class
8010 // (AppKit: `NSSecureTextField`; WinUI: `PasswordBox`), the same contract as
8011 // `set_selectable`: the backend carries the text, the placeholder and its own event wiring
8012 // over, takes the old widget's place in the native tree, and day-core re-points the node's
8013 // handle. Required, with no default: a backend that left this out would show a password in
8014 // the clear. A member the toolkit has no notion of (an action key on a desktop) is ignored.
8015 fn set_input_traits(&mut self, h: &Self::Handle, traits: &InputTraits) -> Option<Self::Handle>;
8016
8017 // pointer shape (docs/cursor.md): the cursor to show while the pointer is over this node
8018 // and its descendants, from the `.cursor()` modifier. Called again whenever a reactive
8019 // cursor changes, so the setter is idempotent and cheap; `Cursor::Default` releases the
8020 // node. The default no-op is a backend with no pointer API to reach (`Cap::Cursor`
8021 // answers `Unsupported` there).
8022 fn set_cursor(&mut self, _h: &Self::Handle, _cursor: Cursor) {}
8023
8024 /// Show or hide a retained subtree, including its input and accessibility participation.
8025 /// The layout and reactive scope stay alive while hidden.
8026 fn set_presented(&mut self, _h: &Self::Handle, _visible: bool) {}
8027
8028 /// Attach overscroll delivery to a refresh host; the caller owns the mounted scope.
8029 fn attach_refresh(&mut self, _h: &Self::Handle, _host: NodeId) {}
8030
8031 // scroll (§7.6)
8032 fn set_scroll_content(&mut self, _h: &Self::Handle, _content: Size) {}
8033 // The room a classic (non-overlay) scroll bar takes out of a scroll view's content area
8034 // while the content overflows along `vertical`'s axis: its width for a vertical scroll, its
8035 // height for a horizontal one (docs/scroll.md). Day lays overflowing content out that much
8036 // narrower, so it fits beside the bar instead of reaching under it. 0 — the default — is
8037 // every backend whose bars overlay the content (AppKit, GTK, UIKit, Android, XAML, DOM).
8038 fn scroll_bar_inset(&mut self, _h: &Self::Handle, _vertical: bool) -> f64 {
8039 0.0
8040 }
8041 // The margins and minimum height the platform's own list gives a row (docs/list.md "Row
8042 // metrics"), asked of list `h` each time day-core lays a row. Day insets the row's content by
8043 // the margins and keeps it at least that tall, so a row reads at the platform's size without
8044 // the app padding it per platform. Zero — the default — leaves the row to its content.
8045 fn list_row_metrics(&mut self, _h: &Self::Handle) -> RowMetrics {
8046 RowMetrics::default()
8047 }
8048 fn scroll_to(&mut self, _h: &Self::Handle, _target: Rect, _animated: bool) {}
8049 /// Scroll a native navigation menu to its top or bottom without changing selection.
8050 /// The widget owns its content extent. Return false when the handle is unsupported.
8051 fn nav_scroll_to_edge(&mut self, _h: &Self::Handle, _bottom: bool) -> bool {
8052 false
8053 }
8054 fn scroll_offset(&mut self, _h: &Self::Handle) -> Point {
8055 Point::ZERO
8056 }
8057
8058 // events: one trampoline, node-id keyed; enqueue-only contract (§8.3).
8059 fn set_event_sink(&mut self, sink: EventSink);
8060
8061 // gestures (docs/shapes.md): attach a native recognizer for `kind` to `h`, emitting
8062 // `Event::Tap/LongPress/Drag` for `node` (enqueue-only). Default no gesture; a piece opts in
8063 // when it has a handler. Idempotent per (handle, kind).
8064 fn enable_gesture(&mut self, _h: &Self::Handle, _node: NodeId, _kind: GestureKind) {}
8065
8066 // focus (docs/focus.md): move native keyboard focus to (or away from) this control.
8067 // `focused = true` requests focus (on mobile this also raises the soft keyboard for text
8068 // inputs); `false` resigns it (dismissing the keyboard; platforms without a "focus nothing"
8069 // state resign to a focusable root). Backends report the resulting state, user- or
8070 // programmatic, with `Event::FocusChanged(bool)` through the sink; a request that cannot
8071 // be honored (unfocusable, unmounted) produces no event. The default no-op means a
8072 // backend without focus support neither moves nor reports focus.
8073 fn focus(&mut self, _h: &Self::Handle, _node: NodeId, _focused: bool) {}
8074
8075 // focusability (docs/focus.md): opt this container into the platform's focus system, the
8076 // canvas contract generalized (`Decorate::focusable`). A focusable container accepts focus,
8077 // takes it on a press (before the press reaches its gesture recognizers), reports both
8078 // directions with `Event::FocusChanged`, and delivers the non-text keys it hears while
8079 // focused as `Event::Key` for `node` (gated on `keys::handled`, like a canvas). The default
8080 // no-op means the piece renders normally but never joins the focus order: `.focused(…)`
8081 // bindings stay quiet and `.on_key(…)` never fires, the same graceful silence unfocusable
8082 // controls already have. Idempotent; only `true` is ever sent today (a piece opts in at
8083 // build, it does not opt back out).
8084 fn set_focusable(&mut self, _h: &Self::Handle, _node: NodeId, _focusable: bool) {}
8085
8086 // recycling list (docs/list.md, §10): day-core hands the `LIST` host its row-pull `source`
8087 // once, right after realize. A recycling backend stores it and calls it from its native
8088 // data-source; the default no-op means a backend without list support renders nothing.
8089 fn attach_list(&mut self, _host: &Self::Handle, _source: ListSource) {}
8090
8091 // hierarchical tree (docs/tree.md): day-core hands the `TREE` host its token-addressed
8092 // row-pull `source` once, right after realize. A backend with a native tree stores it and
8093 // answers its data-source from it; the default no-op means a backend without tree support
8094 // renders nothing (`Cap::Tree` answers `Unsupported`, and apps gate on that).
8095 fn attach_tree(&mut self, _host: &Self::Handle, _source: TreeSource) {}
8096
8097 // routes (docs/navigation.md): day-core reports the app's current route path here whenever
8098 // it changes ("" = everything at its root), so a backend with a native notion of location
8099 // can mirror it: web-dom writes the URL hash (`#controls`), and browser back/forward or a
8100 // hand-edited hash comes back as `Event::RouteRequested`. Default no-op: most toolkits
8101 // have nowhere to put a route.
8102 fn set_route(&mut self, _route: &str) {}
8103
8104 // undo bridge (docs/model.md): mirror the app's undo stack into the platform's own undo
8105 // objects, so the stock Edit menu retitles and enables itself and the platform's gestures
8106 // land: the native front of one Day-owned history. The state flows down whenever it
8107 // changes; the user's invocation comes back up as `Event::Undo`. Default no-op: a backend
8108 // without a native undo system answers `Cap::UndoBridge` `Unsupported`, and the app's own
8109 // affordances (menu items, buttons, accelerators) drive the stack instead.
8110 fn set_undo_state(&mut self, _state: &UndoState) {}
8111
8112 // edit bridge (docs/menus.md): mirror what the app's standard-edit handlers can do, so
8113 // the platform's own menu validation enables Cut/Copy/Paste exactly as it does for text
8114 // widgets; invocations come back up as `Event::Edit`. Default no-op: a backend without
8115 // a native edit-command route answers `Cap::EditBridge` accordingly.
8116 fn set_edit_state(&mut self, _state: &EditState) {}
8117
8118 // ambient modifiers (docs/menus.md): the keyboard modifiers held right now, for
8119 // interactions whose meaning they change (shift-click multi-select). Pull-based: the
8120 // platforms expose exactly this query (NSEvent.modifierFlags, the shim's tracked mask).
8121 // Touch-only backends keep the all-false default.
8122 fn modifiers(&mut self) -> Modifiers {
8123 Modifiers::default()
8124 }
8125
8126 // Dynamic context menu (docs/menus.md): the menu is built when it is summoned. The provider
8127 // is called synchronously from the platform's own menu callback (UI thread, outside any
8128 // day-core borrow) with the location in the node's local coordinates, and its result is
8129 // shown. The static `set_context_menu` below stays the simple path; this one exists for
8130 // surfaces whose menu depends on what is under the pointer (a canvas selection,
8131 // docs/tree.md). Default no-op: a backend without the affordance shows nothing.
8132 fn set_drag_source(&mut self, _h: &Self::Handle, _source: transfer::Source) {}
8133 fn set_drop_target(&mut self, _h: &Self::Handle, _target: transfer::Target) {}
8134
8135 fn set_context_menu_fn(&mut self, _h: &Self::Handle, _node: NodeId, _f: ContextMenuFn) {}
8136
8137 // menus (§ menus): render `items` with the backend's native menu affordance, firing
8138 // `Event::MenuAction(id)` (enqueue-only) for each id'd item; `role` items use the native standard
8139 // command. Default no-op: a toolkit without a menu bar / context menu shows nothing.
8140 /// The application menu (macOS/Windows/Linux menu bar; the app-bar overflow on Android; the
8141 /// `UIMenuBuilder` main menu on iPadOS/Catalyst). Replaces any previous app menu.
8142 fn set_app_menu(&mut self, _items: &[MenuItem]) {}
8143 /// A context menu for `h`, shown on secondary-click (desktop) or long-press (mobile). Passing an
8144 /// empty slice removes it.
8145 fn set_context_menu(&mut self, _h: &Self::Handle, _node: NodeId, _items: &[MenuItem]) {}
8146 /// Make the button `h` (a [`kinds::BUTTON`] node) a pull-down menu button (docs/menus.md
8147 /// "Menu buttons"): its primary press (a click, a tap, the keyboard's Space or Return, the
8148 /// accessibility press) asks `f` for the menu at that moment and shows it under the button
8149 /// with the toolkit's own menu, instead of reporting [`Event::Pressed`]. `f` is called on
8150 /// the UI thread, outside any day-core borrow, with [`Point::ZERO`] (where on the button
8151 /// the press landed does not change its menu); an empty result shows nothing. Chosen items
8152 /// fire [`Event::MenuAction`] as a context menu's do.
8153 ///
8154 /// A toolkit with no native menu to show reports [`Event::ContextMenu`] for `node` instead,
8155 /// with `window` at the button's bottom-leading corner, and the pieces layer presents the
8156 /// composed menu there. Called once per realized button; the release sweep reclaims `f`.
8157 /// Resolve the press through [`resolve_button_menu`], which re-checks after `f` runs that
8158 /// the button was not released by it. Default no-op: the button stays an inert button.
8159 fn set_button_menu(&mut self, _h: &Self::Handle, _node: NodeId, _f: ContextMenuFn) {}
8160
8161 // toolbars (docs/toolbars.md): a window's native toolbar: NSToolbar, AdwHeaderBar, QToolBar,
8162 // CommandBar. `h` is the window root's handle (the same handle `open_window` returned, or the
8163 // primary root's); the backend walks from it to the window it belongs to. Default no-op: a
8164 // toolkit with no toolbar shows nothing rather than a drawn imitation, and reports
8165 // `Cap::Toolbar` as `Unsupported` so an app can put the command somewhere else.
8166 /// Edit the window's toolbar (docs/toolbars.md): the [`ToolbarOp`]s, removals first, then
8167 /// insertions in ascending position. The bar starts empty, and becomes empty again when every
8168 /// item has been removed, at which point the backend takes it off the window.
8169 ///
8170 /// An item no op names must keep its native widget untouched, which is what keeps a search
8171 /// field focused while the page around it changes. Day sends an edit only when the bar
8172 /// changed, at most once per turn, and an item keeps its [`ToolbarItem::action`] for as long
8173 /// as its window shows an item with that id, so a native item's handler never needs
8174 /// repointing. Keep a [`ToolbarMirror`] and place each new item after
8175 /// [`ToolbarMirror::prev_where`] its group.
8176 ///
8177 /// Returns whether the edit was applied. `false` (the window has no bar to edit yet) makes
8178 /// Day send the whole bar again at the next change rather than assume this one landed.
8179 fn edit_toolbar(&mut self, _h: &Self::Handle, _ops: &[ToolbarOp]) -> bool {
8180 true
8181 }
8182 /// Apply a targeted change to one live toolbar item, the path a bound signal writes through,
8183 /// so syncing a search field does not rebuild the bar. No-op if the item is not present.
8184 fn update_toolbar(&mut self, _h: &Self::Handle, _patch: &ToolbarPatch) {}
8185
8186 // lifecycle (docs/lifecycle.md): does this backend deliver `phase`? The default answers "yes" for
8187 // the universal phases (launch/activation/termination) and "no" for the mobile-only ones. Backends
8188 // that wire up more (the mobile ones) override this; it must agree with the crate's
8189 // `const fn lifecycle_supported`, which drives compile-time guards in `day::require_lifecycle!`.
8190 fn supports_lifecycle(&self, phase: Lifecycle) -> bool {
8191 phase.is_universal()
8192 }
8193
8194 // pillars
8195 /// Apply a node's accessibility annotations (docs/accessibility.md): the label, hint and
8196 /// value the screen reader speaks, an explicit role, whether the node is hidden from
8197 /// assistive technology, and the automation identifier. Called with the node's whole
8198 /// accumulated set each time any of it changes, so every member is written on every call.
8199 /// Only an explicit role is applied: a native control reports its own.
8200 fn set_a11y(&mut self, _h: &Self::Handle, _a11y: &A11yProps) {}
8201 /// Speak `text` through the screen reader without moving its focus (docs/accessibility.md;
8202 /// probe [`Cap::Announce`]). `urgent` interrupts what is being read; otherwise the sentence
8203 /// waits its turn. Nothing happens when no screen reader is running. The default is a
8204 /// backend that reaches no announcement API.
8205 fn announce(&mut self, _text: &str, _urgent: bool) {}
8206 /// Read a widget's native state back from the platform for `a11y_audit` and
8207 /// `assert_native` (§14.2, docs/testing.md) to diff against Day's expectation. Default:
8208 /// nothing read; the audit skips the node and `assert_native` records each field as unread.
8209 fn read_native(&self, _h: &Self::Handle) -> NativeSnapshot {
8210 NativeSnapshot::default()
8211 }
8212 fn replay(&mut self, _h: &Self::Handle, _ops: &[DrawOp], _size: Size) {}
8213
8214 /// Every family this toolkit can draw canvas text in, with the faces each ships
8215 /// (docs/fonts.md; probe [`Cap::FontList`]). Default: none. `day::font_families` calls
8216 /// this once per process and caches the answer: enumeration is slow on every platform
8217 /// (fontconfig, a DirectWrite collection, an XML parse on Android) and the set does not
8218 /// change under a running app.
8219 fn font_families(&mut self) -> Vec<FontFamilyInfo> {
8220 Vec::new()
8221 }
8222
8223 /// Measure one line of canvas text at `size` points in `font`, in the same engine
8224 /// [`Toolkit::replay`] draws [`DrawOp::Text`] with, so a `TextAnchor::LEADING` anchor plus
8225 /// the returned `ascent` lands on the drawn baseline. `None` = cannot measure; the facade
8226 /// then answers [`TextMetrics::approximate`].
8227 fn measure_text(&mut self, _text: &str, _size: f64, _font: &CanvasFont) -> Option<TextMetrics> {
8228 None
8229 }
8230 // --- raster images (docs/images.md) -------------------------------------------------
8231 //
8232 // Request-id shaped rather than blocking, because one backend can never answer
8233 // synchronously: a browser decodes through `createImageBitmap`, which is a promise. Every
8234 // other backend decodes inline and raises the completion before returning, so the shape
8235 // costs them nothing but a line, and the app-facing API can be one thing everywhere
8236 // instead of two (docs/async.md rule 3: a callback and a future, never a runtime).
8237
8238 /// Decode encoded image bytes (PNG/JPEG/…) into a native image, answering `req` with
8239 /// [`Event::ImageDecoded`].
8240 ///
8241 /// The id in that event is minted by the caller (day-core), not the backend: the backend
8242 /// keeps its own side table from that id to whatever it decoded.
8243 ///
8244 /// The default does nothing because a default body cannot reach the event sink
8245 /// (it is installed per backend by [`Toolkit::set_event_sink`], not reachable through this
8246 /// trait), so there is no way for it to answer. day-core asks [`Cap::ImageDecode`] first and
8247 /// resolves the request as [`ImageError::Unsupported`] itself, which is why a backend with
8248 /// no decoder needs no code here at all.
8249 fn decode_image(&mut self, _req: u64, _id: BitmapId, _bytes: &[u8]) {}
8250
8251 /// What a decoded image is: pixel size, scale, format, alpha ([`BitmapInfo`]).
8252 ///
8253 /// Synchronous: every backend that decoded the image already holds these facts. `None` means
8254 /// the id names nothing live.
8255 fn image_info(&mut self, _id: BitmapId) -> Option<BitmapInfo> {
8256 None
8257 }
8258
8259 /// The metadata beyond the pixels: EXIF orientation, DPI, capture time
8260 /// ([`ImageProperties`], probe [`Cap::ImageProperties`]). `None` where the backend has no
8261 /// metadata reader, which is most of them.
8262 fn image_properties(&mut self, _id: BitmapId) -> Option<ImageProperties> {
8263 None
8264 }
8265
8266 /// Encode a decoded image back to bytes per `spec`, answering `req` with
8267 /// [`Event::ImageEncoded`]. A format outside [`Self::encode_formats`] answers
8268 /// [`ImageError::Encode`] rather than silently substituting another one.
8269 ///
8270 /// Defaulted to nothing for the same reason as [`Self::decode_image`]: day-core probes
8271 /// [`Cap::ImageEncode`] and answers `Unsupported` without ever calling this.
8272 fn encode_image(&mut self, _req: u64, _id: BitmapId, _spec: &EncodeSpec) {}
8273
8274 /// Which formats [`Self::encode_image`] can write, the [`Cap::ImageEncode`]
8275 /// counterpart of [`Self::font_families`]/[`Cap::FontList`]. Empty by default.
8276 fn encode_formats(&mut self) -> Vec<ImageFormat> {
8277 Vec::new()
8278 }
8279
8280 /// Drop a decoded image and everything the backend cached for it. Called when the app's
8281 /// last handle to it goes away; an id the backend never saw is a no-op.
8282 fn release_image(&mut self, _id: BitmapId) {}
8283
8284 // --- canvas export (docs/canvas.md "Exporting") --------------------------------------
8285 //
8286 // Request-id shaped like the image duties above, for the same reason: the browser's
8287 // `createImageBitmap` is a promise, and a native toolkit may paint on another thread. A
8288 // backend may also answer inline, before returning. day-core validates sizes, enforces
8289 // the pixel limits and probes the caps first, so a backend sees only requests it can
8290 // attempt.
8291
8292 /// Replay `ops` into a new offscreen bitmap of `size` points at `scale` pixels per point
8293 /// ([`export_pixels`] gives the pixel size), with a transparent background and the
8294 /// canvas's top-left origin. Store it under `id` in the same table [`Self::decode_image`]
8295 /// fills, so `image_info`, `encode_image`, `release_image`, the `image` piece and
8296 /// [`DrawOp::Image`] all take it, then answer `req` with [`Event::BitmapRendered`] (its
8297 /// [`BitmapInfo::scale`] is `scale`).
8298 ///
8299 /// The painter must be the one [`Self::replay`] uses, so text, gradients, clips and stamps
8300 /// match the screen. Where the platform's 2-D API draws into a memory surface from any
8301 /// thread, the paint runs on a thread of [`offscreen`] and the answer is posted back, so
8302 /// a long replay never stalls the UI; the toolkit resolves on the UI thread, before it
8303 /// hands the job over, everything the painter would otherwise read from UI-thread state
8304 /// (the decoded images the ops reference, the fonts their text runs need). The contract
8305 /// holds either way: one answer per request, carrying that request's `req`, raised on the
8306 /// UI thread, and the bitmap in the table before it. Defaulted to nothing: day-core probes
8307 /// [`Cap::CanvasBitmap`] and answers [`ExportError::Unsupported`] itself.
8308 fn render_bitmap(
8309 &mut self,
8310 _req: u64,
8311 _id: BitmapId,
8312 _ops: &[DrawOp],
8313 _size: Size,
8314 _scale: f64,
8315 ) {
8316 }
8317
8318 /// Replay each page into one PDF document and answer `req` with [`Event::PdfRendered`].
8319 /// Units are PDF points, top-left origin; shapes and text stay vector, and images embed at
8320 /// their pixel size. `pages` is never empty. Defaulted to nothing: day-core probes
8321 /// [`Cap::CanvasPdf`] first.
8322 fn render_pdf(&mut self, _req: u64, _pages: &[PdfPage], _info: &PdfInfo) {}
8323
8324 /// Capture the primary window's content as encoded image bytes (the dayscript `screenshot`
8325 /// step, docs/window-image.md).
8326 ///
8327 /// # Errors
8328 ///
8329 /// Returns a message when the backend cannot capture; the default always does.
8330 fn snapshot_window(&mut self) -> Result<Vec<u8>, String> {
8331 Err("snapshot unsupported".into())
8332 }
8333 /// Where `root`, the primary window's root container, sits in [`Self::snapshot_window`]'s
8334 /// image, in points from its top-left. A reader of the capture (dayscript `sample_pixel`)
8335 /// maps Day's frames into it with this; it matters where the capture spans more than Day's
8336 /// content on more than one side, as Android's edge-to-edge content does (status bar
8337 /// above, navigation bar below).
8338 ///
8339 /// Defaulted to `None`, which the reader takes as "any rows beyond Day's content are
8340 /// above it", true where the only extra area is a title bar.
8341 fn snapshot_origin(&mut self, _root: &Self::Handle) -> Option<Point> {
8342 None
8343 }
8344 /// Establish a fresh screenshot checkpoint after reactive work and native transitions.
8345 /// `revision` is stable across retries and unique to the request; `host` selects a
8346 /// secondary window, or None for the primary. Never block the UI thread waiting for
8347 /// a frame. Pending requests are retried within the dayscript deadline.
8348 ///
8349 /// Ready means the platform render checkpoint completed, not that a vsync callback
8350 /// proves pixels were displayed. `OnCapture` delegates freshness to `snapshot_window`.
8351 ///
8352 /// # Errors
8353 ///
8354 /// Returns a message when the checkpoint cannot be established, for example because the
8355 /// window closed.
8356 fn prepare_snapshot(
8357 &mut self,
8358 _host: Option<&Self::Handle>,
8359 _revision: u32,
8360 ) -> Result<capture::Readiness, String> {
8361 // Compatible with external toolkits predating this hook: their synchronous
8362 // snapshot owns freshness, and no external-capture acknowledgment is fabricated.
8363 Ok(capture::Readiness::OnCapture)
8364 }
8365
8366 /// The same capture with the window's own chrome: title bar, toolbar, whatever the platform
8367 /// draws around the content (docs/window-image.md).
8368 ///
8369 /// Defaulted to [`Self::snapshot_window`]: a backend that cannot separate the two
8370 /// (or has no chrome to speak of, a phone) answers with the content shot rather than an
8371 /// error, so an app asking for chrome degrades to "what there was" instead of failing. The
8372 /// dayscript `screenshot` step never calls this, which is what keeps every captured gallery
8373 /// baseline byte-identical to before it existed.
8374 ///
8375 /// # Errors
8376 ///
8377 /// Returns a message when the backend cannot capture the window.
8378 fn snapshot_window_chrome(&mut self) -> Result<Vec<u8>, String> {
8379 self.snapshot_window()
8380 }
8381 /// Show/hide the sidebar pane of the navigation host `host`, which is what the sidebar
8382 /// affordance a `nav(Sidebar)` contributes for itself drives ([`SIDEBAR_TOGGLE_ID`]).
8383 /// `false` when `host` has no pane to toggle (a stack, a tab bar, no sidebar concept at all).
8384 ///
8385 /// Per host, not per process: a second window's button collapses that window's sidebar
8386 /// and not the first's. The item's own action makes the call, and dayscript's `toolbar:`
8387 /// step presses the item like any other, so a walkthrough drives exactly the path a click
8388 /// takes. Defaulted, so a backend with no sidebar needs no code. docs/toolbars.md,
8389 /// docs/navigation.md.
8390 fn toggle_sidebar(&mut self, _host: &Self::Handle) -> bool {
8391 false
8392 }
8393 /// Press the platform's own back affordance (the navigation bar's back button on iOS,
8394 /// the system back on Android) on the innermost navigation host that has something to
8395 /// pop. What `nav_back()` does not do: that is Day's rail, which pops the model and lets the
8396 /// backend follow, while this runs the native path first (the bar's `shouldPop`, the
8397 /// dispatcher's callbacks, the pop itself) and lets the backend report it to Day as a user
8398 /// back, guard and all. dayscript's `nav_back: { native: true }` drives it, so a walkthrough
8399 /// can cover the code that a real tap runs and Day's rail never reaches. `false` when this
8400 /// toolkit has no native back or nothing is popped by it. Defaulted, so a desktop needs no
8401 /// code. docs/navigation.md.
8402 fn native_back(&mut self) -> bool {
8403 false
8404 }
8405 /// Take (`true`) or release (`false`) the platform's system back for the app's own
8406 /// handlers ([`Decorate::on_system_back`](/api/day_pieces/trait.Decorate.html#method.on_system_back)):
8407 /// day-core arms it while at least one mounted handler is enabled. Armed, a system back that
8408 /// nothing native consumes first (a presented cover, a pushed page, an armed guard) reaches
8409 /// Day as [`Event::NavBack`] on [`WINDOW_NODE`] instead of leaving the app; released, the
8410 /// platform's default runs, predictive-back preview and all. Android registers an
8411 /// `OnBackPressedCallback` beneath its own; HarmonyOS consumes the page's `onBackPress`.
8412 /// Defaulted, so a toolkit with no system back (desktop, iOS, the web) needs no code.
8413 /// docs/navigation.md "Handling the system Back".
8414 fn set_system_back(&mut self, _armed: bool) {}
8415 /// Whether the UI has settled, with no native transition (modal present/dismiss, nav push)
8416 /// still animating. The dayscript `screenshot` step polls this before capturing so shots
8417 /// never catch a half-faded dialog or half-pushed page. Backends without async
8418 /// transitions (or without a way to know) report `true`.
8419 fn ui_idle(&mut self) -> bool {
8420 true
8421 }
8422
8423 // imperative presentation (docs/dialogs.md): show a native modal for request `req`;
8424 // the backend answers by enqueuing `Event::PresentResult { req, .. }`. `dismiss` is
8425 // used only when Day resolves programmatically (dayscript) while the modal is still up.
8426 fn present(&mut self, _req: u64, _spec: &present::PresentSpec) {}
8427 fn dismiss(&mut self, _req: u64) {}
8428
8429 /// Open `url` in the platform's default handler: the system browser for `http(s)`, the mail
8430 /// client for `mailto:`, etc. Backs the [`link`](/api/day_pieces/fn.link.html) piece. Fire and
8431 /// forget: there is no result, and an unopenable URL is ignored. The default no-ops so a
8432 /// backend that hasn't wired it up still compiles.
8433 fn open_url(&mut self, _url: &str) {}
8434
8435 /// Whether a native share chooser is available. Does not probe installed share targets.
8436 fn share_support(&self) -> Support {
8437 Support::Unsupported
8438 }
8439 /// Present the system share chooser for `spec` (docs/sharing.md). True means presentation
8440 /// started, not that sharing completed. Never sends data without the user's choice of a
8441 /// target. Where the chooser can carry the app's own actions (`Cap::ShareActions`), each
8442 /// of `spec.actions` appears with its title and glyph, and choosing one enqueues
8443 /// `Event::MenuAction(action.id)`; elsewhere the actions are left out. `anchor` is the
8444 /// control the chooser points at where it is a popover (iPad, macOS); without one the
8445 /// chooser uses the window's top trailing corner.
8446 fn share(&mut self, _spec: &share::ShareSpec, _anchor: Option<&Self::Handle>) -> bool {
8447 false
8448 }
8449
8450 /// Read current OS associations. Unsupported platforms must not fabricate a default.
8451 ///
8452 /// # Errors
8453 ///
8454 /// Returns [`applications::ApplicationError::Unsupported`] where the platform has no
8455 /// association query (the default), or the platform's own failure.
8456 fn application_handlers(
8457 &mut self,
8458 _query: &applications::HandlerQuery,
8459 ) -> Result<applications::ApplicationHandlers, applications::ApplicationError> {
8460 Err(applications::ApplicationError::Unsupported)
8461 }
8462
8463 /// Open with an opaque application identifier returned by `application_handlers`.
8464 fn open_url_with_application(
8465 &mut self,
8466 _url: &str,
8467 _application: &str,
8468 completion: applications::OpenApplicationCompletion,
8469 ) {
8470 completion(Err(applications::ApplicationError::Unsupported));
8471 }
8472
8473 /// Ask the OS to require a second swipe for its edge gestures on `edges` (docs/cover.md):
8474 /// the union requested by every mounted `defers_system_gestures` modifier, re-sent whenever
8475 /// that set changes (`Edges::NONE` when the last one unmounts). iOS defers the home
8476 /// indicator / notification edges; Android enters swipe-to-reveal immersive mode while
8477 /// non-empty. The default no-ops (desktop has no system edge gestures).
8478 fn defer_system_gestures(&mut self, _edges: Edges) {}
8479
8480 /// Hide (`true`) or show the system status bar (docs/cover.md): whether any mounted
8481 /// `status_bar_hidden` modifier currently asks for it hidden, re-sent whenever that answer
8482 /// may have changed (`false` when the last request unmounts). iOS answers the root and
8483 /// cover view controllers' `prefersStatusBarHidden`; Android and HarmonyOS hide the status
8484 /// bar through their window inset controls. The default no-ops (desktop and web have no
8485 /// status bar); report `Cap::StatusBarHidden` alongside an implementation.
8486 fn set_status_bar_hidden(&mut self, _hidden: bool) {}
8487
8488 /// Whether the platform is rendering in dark appearance right now. Apps painting
8489 /// custom surfaces (opaque overlay panels, scrims) branch on this so their fills track
8490 /// the theme the default text colors already follow; hardcoding either theme's
8491 /// surface produces dark-on-dark or light-on-light text on the other. Queried at
8492 /// build time (a piece rebuilt after a theme change re-queries). The default honors a
8493 /// `DAY_THEME` launch override and otherwise answers light.
8494 /// Resolve a semantic color for custom artwork. Backends with native palette access
8495 /// override this; the default follows light/dark appearance using Day's fixed palette.
8496 fn system_color(&mut self, role: SystemColor) -> Color {
8497 role.fallback(self.dark_mode())
8498 }
8499
8500 fn dark_mode(&mut self) -> bool {
8501 std::env::var("DAY_THEME").ok().as_deref() == Some("dark")
8502 }
8503 /// Whether the user asked the system for less motion (docs/accessibility.md; probe
8504 /// [`Cap::ReduceMotion`]): macOS and iOS "Reduce Motion", Android "Remove animations" (an
8505 /// animator duration scale of zero), GTK's `gtk-enable-animations` off, Windows "Show
8506 /// animations" off, the web's `prefers-reduced-motion`. Read at launch; a backend that
8507 /// watches the setting calls `day_core::note_motion_changed` when it flips. Day then applies
8508 /// every finite animation at its destination and keeps only indeterminate motion. The default
8509 /// is a backend that reads no such setting.
8510 fn reduce_motion(&mut self) -> bool {
8511 false
8512 }
8513
8514 /// App-level appearance override: `Some(true)` forces dark, `Some(false)` forces light,
8515 /// `None` returns to following the system. Backends restyle their native widgets in
8516 /// place and answer the override from [`dark_mode`](Self::dark_mode); app-painted
8517 /// surfaces pick it up on their next rebuild. `Cap::Appearance` reports whether the
8518 /// backend honors this; the default ignores the call.
8519 fn set_appearance(&mut self, _dark: Option<bool>) {}
8520
8521 /// Put `badge` on the app's icon in the Dock / launcher / home screen (docs/badge.md).
8522 ///
8523 /// Fire-and-forget, like `set_appearance`: a payload this toolkit cannot render is ignored, and
8524 /// the app probes `Cap::AppBadge{Count,Text,Dot}` before choosing one. Never substitute: a
8525 /// backend that turned `Text("beta")` into `Count(1)` would put a wrong number on a user's
8526 /// icon, which is worse than showing nothing. The default ignores every call.
8527 fn set_app_badge(&mut self, _badge: &AppBadge) {}
8528
8529 // app lifecycle (mobile; desktop backends no-op)
8530 fn on_suspend(&mut self) {}
8531 fn on_resume(&mut self) {}
8532 fn on_memory_warning(&mut self) {}
8533
8534 // adoption of foreign native handles (polyglot pieces, §15.3)
8535 fn adopt(&mut self, _raw: RawHandle) -> Self::Handle {
8536 unimplemented!("this toolkit does not adopt foreign handles yet")
8537 }
8538
8539 // secondary windows (docs/windows.md)
8540
8541 /// Open a native OS window per `options` + `kind`: create and show the window, wire its
8542 /// events to `id` (`WindowResized` with the content size in points, `WindowClosed` after
8543 /// the native close, `WindowFocused` on key/active changes), and answer with its content
8544 /// container handle, the same contract as the `ready` root container. Backends whose
8545 /// window creation is asynchronous (a scene, an activity, an ability) answer
8546 /// [`WindowOpenReply::Pending`] and complete later through
8547 /// `day_core::finish_window_open(id, raw, size)`, which goes through [`Toolkit::adopt`].
8548 /// The default answers `Unsupported`; day-core then presents the content as a
8549 /// fullscreen cover in the primary window instead.
8550 fn open_window(
8551 &mut self,
8552 _id: NodeId,
8553 _options: &WindowOptions,
8554 _kind: WindowKind,
8555 ) -> WindowOpenReply<Self::Handle> {
8556 WindowOpenReply::Unsupported
8557 }
8558
8559 /// Close the native window whose content container is `host` (a handle `open_window`
8560 /// produced). Asynchronous: the platform confirms with `Event::WindowClosed` on the
8561 /// window's root node, and only then does day-core tear the subtree down. Idempotent; unknown
8562 /// hosts are ignored. Never called with the primary window's container.
8563 fn close_window(&mut self, _host: &Self::Handle) {}
8564
8565 /// End the application: the last window with [`WindowRole::Primary`] has closed
8566 /// (docs/windows.md). day-core decides when, since it owns the window registry and the role
8567 /// each window carries; the backend supplies only the platform's exit:
8568 /// `NSApplication.terminate`, `QCoreApplication::quit`, `GtkApplication.quit`,
8569 /// `PostQuitMessage`. Everything day-core wanted to happen first (secondary windows
8570 /// disposed, `WillTerminate` delivered) already has by the time this is called.
8571 ///
8572 /// The default does nothing, which is right for the backends whose process lifetime is
8573 /// not theirs to end: a browser tab, an Android activity, an iOS scene.
8574 fn quit_app(&mut self) {}
8575
8576 /// Bring the window whose content container is `host` to front and make it key/active:
8577 /// the focus half of open-or-focus singleton windows. Default no-op.
8578 fn focus_window(&mut self, _host: &Self::Handle) {}
8579
8580 /// Retitle the window whose content container is `host`. Default no-op.
8581 fn set_window_title(&mut self, _host: &Self::Handle, _title: &str) {}
8582
8583 /// Resize the window whose content container is `host` to fit `size` of content, and pin it
8584 /// there: what `WindowOptions::size_to_fit` asks for (docs/windows.md).
8585 ///
8586 /// `size` is the content size Day measured, not the window's outer frame: the backend adds
8587 /// its chrome. A settings panel is the case this exists for, and every desktop platform
8588 /// sizes one to its content rather than to a number the app guessed; a fixed height either
8589 /// clips the last row or leaves a band of empty panel under it, and which one you get depends
8590 /// on the user's text size.
8591 ///
8592 /// Default no-op, so a toolkit that cannot resize a live window keeps the size it was
8593 /// opened at, which is what every backend did before this existed.
8594 fn fit_window(&mut self, _host: &Self::Handle, _size: Size) {}
8595
8596 /// Snapshot the window whose content container is `host` (the dayscript `screenshot`
8597 /// step's `window:` target). The default answers the primary snapshot, so backends that
8598 /// never open windows stay correct without changes.
8599 ///
8600 /// # Errors
8601 ///
8602 /// Returns a message when the backend cannot capture that window.
8603 fn snapshot_window_of(&mut self, _host: &Self::Handle) -> Result<Vec<u8>, String> {
8604 self.snapshot_window()
8605 }
8606
8607 /// Apply one property change to the window whose content container is `host`
8608 /// (docs/windows.md "Window properties"). The primary window arrives with its root container,
8609 /// like [`set_window_title`](Self::set_window_title).
8610 ///
8611 /// Fire-and-forget, like [`set_app_badge`](Self::set_app_badge): a change this toolkit cannot
8612 /// make is ignored, and the app probes the matching `Cap` (named on each [`WindowChange`]
8613 /// variant) before relying on it. A change the platform completes later (a fullscreen
8614 /// transition, a zoom animation) reports its outcome through
8615 /// [`Event::WindowStateChanged`], never by assuming the request took. The default ignores
8616 /// every change.
8617 fn apply_window(&mut self, _host: &Self::Handle, _change: &WindowChange) {}
8618
8619 /// True OS window groups, as distinct from native tab widgets.
8620 fn native_window_tabs(&self) -> bool {
8621 false
8622 }
8623 /// Native in-window document/section tab control; OS grouping is reported separately.
8624 fn native_document_tabs(&self) -> bool {
8625 false
8626 }
8627 /// Join/reorder these windows in an OS tab group. Content remains window-owned.
8628 fn group_windows(&mut self, _hosts: &[Self::Handle]) {}
8629 /// Current native order of the group containing this window, including detached groups.
8630 fn window_tab_order(&self, _host: &Self::Handle) -> Vec<NodeId> {
8631 Vec::new()
8632 }
8633
8634 /// Install the app's Dock menu (docs/menus.md "Dock menu"): the items macOS shows above
8635 /// its own when the user right-clicks the app's Dock icon, built from the app's
8636 /// `[[shortcuts]]` and its `dock_menu(..)` entries. Same item model and dispatch as
8637 /// [`set_app_menu`](Self::set_app_menu); an empty slice removes the menu. `Cap::DockMenu`
8638 /// reports support; the default ignores the call.
8639 fn set_dock_menu(&mut self, _items: &[MenuItem]) {}
8640
8641 /// Make the node at `h` move its window when the user drags it, as a title bar does
8642 /// (`.window_drag_region()`, docs/window-chrome.md): the region's own background starts a
8643 /// native window drag (with the platform's snapping and edge tiling), a double click does
8644 /// what the user's title-bar double-click setting says, and controls inside the region keep
8645 /// receiving their own clicks. `false` releases it. `Cap::DragRegion`; the default ignores
8646 /// the call, so on a phone the region is an ordinary view.
8647 fn set_drag_region(&mut self, _h: &Self::Handle, _drag: bool) {}
8648
8649 /// Show these status items, replacing the previous set (docs/status-item.md): add the
8650 /// ones whose `id` is new, update the ones that changed, remove the ones no longer listed.
8651 /// A click on an item runs its `activate` action or opens its menu; menu choices dispatch
8652 /// [`Event::MenuAction`] like the app menu's. `Cap::StatusItem`; the default ignores the
8653 /// call, which is what a phone and the web do.
8654 fn set_status_items(&mut self, _items: &[StatusItemSpec]) {}
8655
8656 /// Show `progress` on the app's Dock or taskbar icon (docs/status-item.md).
8657 /// `Cap::AppProgress`; the default ignores it.
8658 fn set_app_progress(&mut self, _progress: AppProgress) {}
8659
8660 /// Show or hide the app's Dock icon while it runs: a menu-bar app hides it and lives in its
8661 /// status item (macOS activation policy). `Cap::DockVisibility`; the default ignores it.
8662 fn set_dock_visible(&mut self, _visible: bool) {}
8663
8664 /// Keep the process running when its last window closes (docs/windows.md "Keeping the app
8665 /// running"). When `true`, the backend must not end the app on its own as windows close: it
8666 /// reports every close, the first window's included, as `Event::WindowClosed`, and day-core
8667 /// decides whether to call [`quit_app`](Self::quit_app). When `false`, the backend keeps its
8668 /// platform's own rule. A backend whose process lifetime is not its own (a phone, a browser
8669 /// tab) ignores it, which is the default.
8670 fn set_keep_running(&mut self, _keep: bool) {}
8671
8672 /// The displays attached now (docs/windows.md "Monitors"). `Cap::Monitors`; the default
8673 /// answers none, and day-core then describes the primary window's own size as one display.
8674 fn monitors(&self) -> Vec<Monitor> {
8675 Vec::new()
8676 }
8677
8678 /// The outer frame of the window whose content container is `host`, in points on the
8679 /// desktop's coordinate space (top-left origin), or `None` where the platform does not say
8680 /// (a phone, Wayland's positions). Read when the app asks for it and when day-core saves a
8681 /// remembered frame (`WindowOptions::remember_frame`).
8682 fn window_frame(&self, _host: &Self::Handle) -> Option<Rect> {
8683 None
8684 }
8685
8686 /// Replace the launcher shortcuts the app set while running (docs/deep-links.md "Launcher
8687 /// shortcuts"), shown beside the ones Day.toml declares: iOS Home Screen quick actions,
8688 /// Android dynamic shortcuts, the macOS Dock menu. Each opens its route through the deep-link
8689 /// intake. `Cap::DynamicShortcuts`; the default ignores the call.
8690 fn set_launcher_shortcuts(&mut self, _shortcuts: &[LauncherShortcut]) {}
8691}
8692
8693/// What a secondary window is, so backends can apply platform conventions (docs/windows.md).
8694#[derive(Clone, Copy, PartialEq, Eq, Debug)]
8695pub enum WindowKind {
8696 /// A regular document/tool window: resizable, miniaturizable, platform-default tabbing.
8697 Normal,
8698 /// A settings/preferences window: singleton by convention; macOS disallows window
8699 /// tabbing and drops the resize/minimize chrome, mobile presents it modally. Pairs with
8700 /// day-core's key-singleton reopen (`open_window` with a key).
8701 Preferences,
8702 /// The About window (docs/settings.md): the same fixed, centered, untabbed panel chrome
8703 /// as [`Self::Preferences`] (every desktop treats the two alike), presented modally on
8704 /// mobile. Singleton under day-core's `day.about` key.
8705 About,
8706}
8707
8708impl WindowKind {
8709 /// Whether this is a panel (settings or About) rather than a document window: the kinds
8710 /// every desktop draws fixed-size, centered and out of the Window menu, and mobile presents
8711 /// as a cover.
8712 #[must_use]
8713 pub fn is_panel(self) -> bool {
8714 !matches!(self, WindowKind::Normal)
8715 }
8716}
8717
8718/// Whether a window keeps the app alive (docs/windows.md close policy).
8719///
8720/// A separate axis from [`WindowKind`], which describes chrome. They correlate (a
8721/// preferences panel is the archetypal window that should not hold an app open), but they are
8722/// not the same question, and conflating them would leave no way to say "an ordinary-looking
8723/// tool window that shouldn't outlive the documents".
8724///
8725/// Note the word "secondary" is overloaded around windows: elsewhere in day it means "a window
8726/// other than the first one opened". Here it means "does not keep the app alive", which is
8727/// about lifetime, not about order of creation.
8728#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
8729pub enum WindowRole {
8730 /// Closing the last one of these ends the app.
8731 #[default]
8732 Primary,
8733 /// Never keeps the app alive: when the last `Primary` closes, the app exits and takes
8734 /// these with it, however many are open.
8735 Secondary,
8736}
8737
8738impl From<WindowKind> for WindowRole {
8739 /// The default pairing: an ordinary window holds the app open, a preferences panel does
8740 /// not. An app that needs a different answer sets the role itself.
8741 fn from(kind: WindowKind) -> WindowRole {
8742 match kind {
8743 WindowKind::Normal => WindowRole::Primary,
8744 WindowKind::Preferences | WindowKind::About => WindowRole::Secondary,
8745 }
8746 }
8747}
8748
8749/// A backend's answer to [`Toolkit::open_window`] (docs/windows.md).
8750pub enum WindowOpenReply<H> {
8751 /// The window exists now; here is its content container (desktop backends).
8752 Open(H),
8753 /// Native creation started but completes asynchronously (a scene, an activity, an
8754 /// ability); the backend will call `day_core::finish_window_open` when the content
8755 /// container exists. day-core parks the window record until then.
8756 Pending,
8757 /// This toolkit cannot open windows (`Cap::MultiWindow` = `Unsupported`); day-core
8758 /// falls back to presenting the content as a fullscreen cover in the primary window.
8759 Unsupported,
8760}
8761
8762/// How a window is shown (docs/windows.md "Window properties"): what the window's `state()`
8763/// signal holds and what [`WindowChange::State`] asks for.
8764#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
8765pub enum WindowState {
8766 /// On screen at its own size: neither minimized, maximized nor fullscreen.
8767 #[default]
8768 Normal,
8769 /// Minimized to the Dock, taskbar or shelf. `Cap::WindowStates`.
8770 Minimized,
8771 /// Zoomed to fill the screen's work area, keeping its chrome. `Cap::WindowStates`.
8772 Maximized,
8773 /// Covering the whole screen with no window chrome; on a phone, the system bars hidden.
8774 /// `Cap::WindowFullscreen`.
8775 Fullscreen,
8776}
8777
8778impl WindowState {
8779 /// The wire code of [`bridge::BridgeKind::WindowStateChanged`].
8780 #[must_use]
8781 pub const fn code(self) -> i32 {
8782 match self {
8783 WindowState::Normal => 0,
8784 WindowState::Minimized => 1,
8785 WindowState::Maximized => 2,
8786 WindowState::Fullscreen => 3,
8787 }
8788 }
8789
8790 /// The state a wire code names; an unknown code reads as `Normal`.
8791 #[must_use]
8792 pub const fn from_code(code: i32) -> WindowState {
8793 match code {
8794 1 => WindowState::Minimized,
8795 2 => WindowState::Maximized,
8796 3 => WindowState::Fullscreen,
8797 _ => WindowState::Normal,
8798 }
8799 }
8800}
8801
8802/// How a window stacks against other apps' windows ([`WindowChange::Level`], `Cap::WindowLevel`).
8803#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
8804pub enum WindowLevel {
8805 /// Ordinary stacking: the focused app's windows come forward.
8806 #[default]
8807 Normal,
8808 /// Stays above other apps' ordinary windows: a palette, a timer, a video peek.
8809 Floating,
8810}
8811
8812/// How strongly a window asks for the user's attention ([`WindowChange::RequestAttention`]).
8813#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
8814pub enum Attention {
8815 /// Once: one Dock bounce, a taskbar button that flashes a few times.
8816 #[default]
8817 Informational,
8818 /// Until the user switches to the app.
8819 Critical,
8820}
8821
8822/// One change to one window (docs/windows.md "Window properties"), carried by
8823/// [`Toolkit::apply_window`]. Each variant names the `Cap` that reports whether the running
8824/// toolkit makes it.
8825#[derive(Clone, Debug, PartialEq)]
8826pub enum WindowChange {
8827 /// Minimize, zoom, take fullscreen, or return to normal. `Cap::WindowStates` for the
8828 /// first two, `Cap::WindowFullscreen` for fullscreen. The outcome comes back as
8829 /// [`Event::WindowStateChanged`].
8830 State(WindowState),
8831 /// Keep the window's content out of screenshots, recordings and screen sharing.
8832 /// `Cap::ContentProtection`.
8833 ContentProtected(bool),
8834 /// Move and/or resize. `origin` is the outer frame's top-left corner in points on the
8835 /// desktop's coordinate space (top-left origin, `Cap::WindowPosition`); `size` is the size Day
8836 /// lays the content out at, in points, the same size `WindowResized` reports
8837 /// (`Cap::WindowGeometry`): the backend adds its own chrome around it.
8838 Frame {
8839 origin: Option<Point>,
8840 size: Option<Size>,
8841 },
8842 /// The content size the user can resize the window to. `None` lifts that bound.
8843 /// `Cap::WindowGeometry`.
8844 Limits {
8845 min: Option<Size>,
8846 max: Option<Size>,
8847 },
8848 /// Stacking against other apps' windows. `Cap::WindowLevel`.
8849 Level(WindowLevel),
8850 /// Show the window on every virtual desktop / Space. `Cap::WindowLevel`.
8851 OnAllWorkspaces(bool),
8852 /// Leave the window out of the taskbar and the window switcher. `Cap::WindowLevel`.
8853 SkipTaskbar(bool),
8854 /// Whether the user can resize the window. `Cap::WindowGeometry`.
8855 Resizable(bool),
8856 /// Whether the window offers a minimize control. `Cap::WindowStates`.
8857 Minimizable(bool),
8858 /// Whether the window offers a maximize / zoom control. `Cap::WindowStates`.
8859 Maximizable(bool),
8860 /// Whether the window offers a close control. `Cap::WindowStates`.
8861 Closable(bool),
8862 /// Hide the window without closing it, or show it again. `Cap::WindowStates`.
8863 Visible(bool),
8864 /// This window's light/dark override over the app-wide [`Toolkit::set_appearance`].
8865 /// `Cap::WindowAppearance`.
8866 Appearance(Option<bool>),
8867 /// Bounce the Dock icon, flash the taskbar button. `Cap::RequestAttention`.
8868 RequestAttention(Attention),
8869}
8870
8871/// The frame a window wears (docs/window-chrome.md), set once when it opens.
8872#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
8873pub enum WindowChrome {
8874 /// The platform's title bar and frame.
8875 #[default]
8876 Standard,
8877 /// The content runs to the window's top edge, under the title bar, and the platform's own
8878 /// window controls (close, minimize, zoom) stay where they are. For a custom title bar: the
8879 /// backend reports the bar's height as the window's safe-area top inset (`day::safe_area()`),
8880 /// so the app pads its content by it and paints its background under it. Mark the draggable
8881 /// part with `.window_drag_region()`. `Cap::OverlayTitleBar`; where unsupported the window
8882 /// keeps its standard bar.
8883 Overlay,
8884 /// No title bar and no frame: a splash screen, a heads-up panel, a borderless utility. The
8885 /// window still resizes from its edges when resizable; mark the part that moves it with
8886 /// `.window_drag_region()`. `Cap::FramelessWindow`; where unsupported the window keeps its
8887 /// standard frame.
8888 Frameless,
8889}
8890
8891/// What shows behind a window's content (docs/window-chrome.md).
8892#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
8893pub enum WindowBackground {
8894 /// The platform's window background.
8895 #[default]
8896 Opaque,
8897 /// Nothing: pixels the content leaves unpainted show the desktop through the window. For
8898 /// rounded or shaped splash screens and overlays. `Cap::TransparentWindow`.
8899 Transparent,
8900 /// A translucent system material that blurs what is behind the window.
8901 /// `Cap::WindowMaterial`; where unsupported the window stays opaque.
8902 Material(WindowMaterial),
8903}
8904
8905/// The system materials a window background can use ([`WindowBackground::Material`]).
8906#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
8907pub enum WindowMaterial {
8908 /// The main-window material: macOS's window background, Windows 11's Mica.
8909 Window,
8910 /// A sidebar or source list: macOS's sidebar material, Windows 11's Mica Alt (tabbed).
8911 Sidebar,
8912 /// A transient surface (a popover, a menu-like panel, a heads-up display): macOS's popover
8913 /// material, Windows 11's Acrylic.
8914 Transient,
8915}
8916
8917/// Where a window opens ([`WindowOptions::placement`]).
8918#[derive(Clone, Copy, Debug, Default, PartialEq)]
8919pub enum WindowPlacement {
8920 /// The platform's choice: macOS cascades, Windows and Linux let the window manager decide.
8921 #[default]
8922 Automatic,
8923 /// Centered on the screen with the active window.
8924 Centered,
8925 /// The outer frame's top-left corner at this point, in points on the desktop's coordinate
8926 /// space (top-left origin). Falls back to `Automatic` without `Cap::WindowPosition`.
8927 At(Point),
8928}
8929
8930/// A small runtime RGBA image for a status item: charts, meters, or a grid of results.
8931///
8932/// Rows run top to bottom; samples are tightly packed, non-premultiplied sRGB RGBA8.
8933/// `scale` is pixels per logical point (2 for Retina). This owns its bytes, independent of
8934/// any window or decoded-image registry. Currently rendered by AppKit; other backends use
8935/// [`StatusItemSpec::icon`] as a fallback. See docs/status-item.md.
8936#[derive(Clone, PartialEq)]
8937pub struct StatusImage {
8938 width: u32,
8939 height: u32,
8940 scale: f64,
8941 rgba: std::sync::Arc<[u8]>,
8942}
8943
8944impl StatusImage {
8945 /// Validate a runtime image. Rejects empty/mismatched pixels, invalid scales, and images
8946 /// exceeding 16 MiB or 4096 logical points on either axis. No platform allocation occurs.
8947 pub fn rgba(
8948 width: u32,
8949 height: u32,
8950 scale: f64,
8951 pixels: impl Into<std::sync::Arc<[u8]>>,
8952 ) -> Option<Self> {
8953 let rgba = pixels.into();
8954 let expected = (width as usize)
8955 .checked_mul(height as usize)?
8956 .checked_mul(4)?;
8957 if width == 0
8958 || height == 0
8959 || expected > 16 * 1024 * 1024
8960 || rgba.len() != expected
8961 || !scale.is_finite()
8962 || scale <= 0.0
8963 || f64::from(width) / scale > 4096.0
8964 || f64::from(height) / scale > 4096.0
8965 {
8966 return None;
8967 }
8968 Some(Self {
8969 width,
8970 height,
8971 scale,
8972 rgba,
8973 })
8974 }
8975
8976 #[must_use]
8977 pub fn width(&self) -> u32 {
8978 self.width
8979 }
8980 #[must_use]
8981 pub fn height(&self) -> u32 {
8982 self.height
8983 }
8984 #[must_use]
8985 pub fn scale(&self) -> f64 {
8986 self.scale
8987 }
8988 #[must_use]
8989 pub fn pixels(&self) -> &[u8] {
8990 &self.rgba
8991 }
8992 pub fn size(&self) -> Size {
8993 Size::new(
8994 f64::from(self.width) / self.scale,
8995 f64::from(self.height) / self.scale,
8996 )
8997 }
8998}
8999
9000impl std::fmt::Debug for StatusImage {
9001 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
9002 f.debug_struct("StatusImage")
9003 .field("width", &self.width)
9004 .field("height", &self.height)
9005 .field("scale", &self.scale)
9006 .field("bytes", &self.rgba.len())
9007 .finish()
9008 }
9009}
9010
9011#[cfg(test)]
9012mod status_image_tests {
9013 use super::*;
9014
9015 #[test]
9016 fn validates_pixel_layout_and_logical_size() {
9017 let image = StatusImage::rgba(120, 36, 2.0, vec![255; 120 * 36 * 4]).unwrap();
9018 assert_eq!(image.size(), Size::new(60.0, 18.0));
9019 assert_eq!(image.clone(), image);
9020 assert!(StatusImage::rgba(0, 1, 1.0, vec![]).is_none());
9021 assert!(StatusImage::rgba(1, 1, 1.0, vec![0; 3]).is_none());
9022 assert!(StatusImage::rgba(u32::MAX, u32::MAX, 1.0, vec![]).is_none());
9023 for scale in [0.0, -1.0, f64::NAN, f64::INFINITY, 0.00001] {
9024 assert!(StatusImage::rgba(1, 1, scale, vec![0; 4]).is_none());
9025 }
9026 }
9027}
9028
9029/// One status item: an icon in the menu bar (macOS), the notification area (Windows) or a
9030/// `StatusNotifierItem` host's tray (Linux), with a menu (docs/status-item.md).
9031#[derive(Clone, Debug, PartialEq)]
9032pub struct StatusItemSpec {
9033 /// The app's name for the item, stable across updates: what a backend diffs by.
9034 pub id: String,
9035 /// The glyph. `None` shows the title alone (macOS) or the app's icon (elsewhere).
9036 pub icon: Option<Icon>,
9037 /// A runtime image. AppKit prefers this over `icon`, preserving aspect ratio and point
9038 /// size up to 18pt high; other backends ignore it and show `icon`/`title` as before.
9039 pub raster: Option<StatusImage>,
9040 /// Draw the icon as a template: its shape only, in the menu bar's or panel's own color, so
9041 /// it reads in light and dark. Symbols are always templates.
9042 pub template: bool,
9043 /// Text beside the icon where the platform shows one (the macOS menu bar). Empty: icon only.
9044 pub title: String,
9045 /// The hover text.
9046 pub tooltip: String,
9047 /// The menu the item opens. Same model and dispatch as the app menu.
9048 pub menu: Vec<MenuItem>,
9049 /// A dispatch id (the [`Event::MenuAction`] registry) run when the user clicks the item
9050 /// itself, where the platform separates a click from opening the menu (a left click on macOS
9051 /// and Windows, the host's "activate" on Linux). 0: a click opens the menu.
9052 pub activate: u64,
9053}
9054
9055/// One display (docs/windows.md "Monitors"), in points on the desktop's coordinate space:
9056/// top-left origin at the primary display's top-left corner.
9057#[derive(Clone, Debug, PartialEq)]
9058pub struct Monitor {
9059 /// Stable for the display across launches where the platform offers it (a display UUID, a
9060 /// connector name); an index otherwise.
9061 pub id: String,
9062 /// The display's name, for a picker ("Built-in Retina Display", "DELL U2720Q").
9063 pub name: String,
9064 /// The display's whole area.
9065 pub frame: Rect,
9066 /// The part windows should use: the frame minus the menu bar, Dock, taskbar or panels.
9067 pub work_area: Rect,
9068 /// Device pixels per point.
9069 pub scale: f64,
9070 /// The display the desktop's menu bar or primary taskbar is on.
9071 pub primary: bool,
9072}
9073
9074/// A launcher shortcut the app sets while it runs (docs/deep-links.md "Launcher shortcuts"): a
9075/// route to open and the label the launcher shows, already localized.
9076#[derive(Clone, Debug, PartialEq, Eq)]
9077pub struct LauncherShortcut {
9078 /// The route the shortcut opens, through the deep-link intake.
9079 pub route: String,
9080 /// What the launcher shows.
9081 pub label: String,
9082}
9083
9084/// A progress indicator on the app's Dock or taskbar icon ([`Toolkit::set_app_progress`],
9085/// docs/status-item.md).
9086#[derive(Clone, Copy, Debug, Default, PartialEq)]
9087pub enum AppProgress {
9088 /// No indicator.
9089 #[default]
9090 None,
9091 /// Work of unknown length.
9092 Indeterminate,
9093 /// A fraction done, 0.0 to 1.0.
9094 Value(f64),
9095 /// A fraction done, paused. Platforms without a paused state show `Value`.
9096 Paused(f64),
9097 /// A fraction done when the work failed. Platforms without an error state show `Value`.
9098 Error(f64),
9099}
9100
9101/// Whether and how a window joins macOS window tabs ([`WindowOptions::tabbing`],
9102/// `Cap::WindowTabbing`). Other platforms have no system window tabs and ignore it.
9103#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
9104pub enum WindowTabbing {
9105 /// The platform default for the window's kind: an ordinary window tabs with the app's other
9106 /// ordinary windows when the user's "Prefer tabs" setting says so; preferences never tab.
9107 #[default]
9108 Automatic,
9109 /// Tab only with windows of the same group, following the user's setting. The tab bar's
9110 /// "+" opens the builder registered for this group (`register_new_window_for`).
9111 Group(String),
9112 /// Always open as a tab of an existing window of the same group, whatever the setting.
9113 Preferred(String),
9114 /// Never become a tab.
9115 Disallowed,
9116}
9117
9118/// An app's generated locale catalog: `(DEFAULT, CATALOG)`, exactly what `day-build` emits as
9119/// `res::locales::{DEFAULT, CATALOG}` (§18.5). Carried in [`WindowOptions::locales`] so the
9120/// framework can install it at the one moment that is correct.
9121pub type AppLocales = (&'static str, &'static [(&'static str, &'static str)]);
9122
9123#[derive(Clone, Debug)]
9124pub struct WindowOptions {
9125 pub title: String,
9126 pub size: Size,
9127 pub min_size: Option<Size>,
9128 /// Create and mount the window without showing it or activating the app. Supported on
9129 /// AppKit; other backends currently ignore this option. Defaults to false.
9130 ///
9131 /// Menu-bar apps can keep their initial host hidden and open Preferences on demand.
9132 /// The window still exists and can be shown with `WindowHandle::set_visible(true)`;
9133 /// this does not change the app's keep-running policy.
9134 pub start_hidden: bool,
9135 /// Ask the backend to size this window to its content once it has been built and laid out,
9136 /// rather than keeping [`Self::size`] (docs/windows.md). `size` still decides the width and
9137 /// acts as the height ceiling, so a panel with more content than fits the screen scrolls
9138 /// instead of growing past it.
9139 ///
9140 /// What a preferences panel wants on every desktop. Ignored by backends that cannot resize a
9141 /// live window, and by the ones with no windows at all.
9142 pub size_to_fit: bool,
9143 /// The app's display name for the standard application menu / About (macOS). `None` falls back
9144 /// to `title`; set it when `title` carries extra decoration you don't want in `About <name>`
9145 /// (e.g. the showcase's window title is "Day Showcase (AppKit)" but its app name is "Showcase").
9146 pub app_name: Option<String>,
9147 /// The app's locale catalog, installed by `day::launch` (docs/localization.md).
9148 ///
9149 /// The order is why this is the framework's job: the OS's languages reach day-localization from the
9150 /// live backend, and the catalog has to be registered after that hint and before the first
9151 /// localized string is read. An app that installs it itself (before `launch`, where there
9152 /// is no backend yet) registers against an empty hint list and resolves to `DEFAULT`, so a
9153 /// French device opens an English window.
9154 pub locales: Option<AppLocales>,
9155 /// The title, computed once the catalog above is installed: how a window title comes from
9156 /// the catalog rather than a literal. Takes precedence over [`Self::title`], which stays the
9157 /// fallback for the moment before (and for apps with nothing to translate).
9158 ///
9159 /// A plain `fn` rather than a closure: this struct is `Clone`, and the callers are a
9160 /// non-capturing `|| res::str::app_title().format()`, which coerces.
9161 pub title_fn: Option<fn() -> String>,
9162 /// The app's version, for Day's exit line (`Clean exit for <app> v<version> …`,
9163 /// docs/lifecycle.md): `env!("CARGO_PKG_VERSION")` in the app crate, which the scaffold's
9164 /// `window()` sets. `None` falls back to the `DAY_APP_VERSION` the `day` CLI sets on a launch.
9165 pub version: Option<String>,
9166 /// macOS window tabbing for this window (`Cap::WindowTabbing`); ignored elsewhere.
9167 pub tabbing: WindowTabbing,
9168 /// The window's frame: standard, a title bar the content runs under, or none
9169 /// (docs/window-chrome.md). Desktop only; phones and the web ignore it.
9170 pub chrome: WindowChrome,
9171 /// What shows behind the content: the window background, nothing, or a system material.
9172 pub background: WindowBackground,
9173 /// Whether the window casts the platform's drop shadow. A transparent, shaped window often
9174 /// wants none.
9175 pub shadow: bool,
9176 /// Whether the user can resize the window by its edges.
9177 pub resizable: bool,
9178 /// Where the window opens.
9179 pub placement: WindowPlacement,
9180 /// The largest content size the user can resize the window to (`Cap::WindowGeometry`).
9181 pub max_size: Option<Size>,
9182 /// Remember this window's size, position and maximized state under this key, and reopen it
9183 /// that way next launch (docs/windows.md "Remembered frames"). A position that no attached
9184 /// display shows any more is dropped, so a window never reopens off-screen.
9185 pub remember_frame: Option<String>,
9186 /// The logical window this opens (docs/windows.md): `open_window` focuses an already-open
9187 /// window with the same key instead of opening a second (the preferences pattern). `None`
9188 /// always opens a new one.
9189 pub key: Option<String>,
9190 /// The kind of window: a regular one, a preferences panel, an About panel.
9191 pub kind: WindowKind,
9192}
9193
9194impl WindowOptions {
9195 /// The window title. Replaces a [`title_fn`](Self::title_fn) set earlier (the generated
9196 /// `res::window_options()` sets one), so the last title named wins.
9197 #[must_use]
9198 pub fn title(mut self, title: impl Into<String>) -> Self {
9199 self.title = title.into();
9200 self.title_fn = None;
9201 self
9202 }
9203 /// The content size the window opens at (desktop; phones fill the screen).
9204 #[must_use]
9205 pub fn size(mut self, width: f64, height: f64) -> Self {
9206 self.size = Size::new(width, height);
9207 self
9208 }
9209 /// The smallest content size the user can resize to.
9210 #[must_use]
9211 pub fn min_size(mut self, width: f64, height: f64) -> Self {
9212 self.min_size = Some(Size::new(width, height));
9213 self
9214 }
9215 /// The largest content size the user can resize to (`Cap::WindowGeometry`).
9216 #[must_use]
9217 pub fn max_size(mut self, width: f64, height: f64) -> Self {
9218 self.max_size = Some(Size::new(width, height));
9219 self
9220 }
9221 /// Create and mount the window without showing it; see [`Self::start_hidden`].
9222 #[must_use]
9223 pub fn start_hidden(mut self) -> Self {
9224 self.start_hidden = true;
9225 self
9226 }
9227 /// Size the window to its content once built; see [`Self::size_to_fit`].
9228 #[must_use]
9229 pub fn size_to_fit(mut self) -> Self {
9230 self.size_to_fit = true;
9231 self
9232 }
9233 /// The app's display name for the application menu and About; see [`Self::app_name`].
9234 #[must_use]
9235 pub fn app_name(mut self, name: impl Into<String>) -> Self {
9236 self.app_name = Some(name.into());
9237 self
9238 }
9239 /// The app's locale catalog, as `res::locales::{DEFAULT, CATALOG}`; see [`Self::locales`].
9240 #[must_use]
9241 pub fn locales(
9242 mut self,
9243 default: &'static str,
9244 catalog: &'static [(&'static str, &'static str)],
9245 ) -> Self {
9246 self.locales = Some((default, catalog));
9247 self
9248 }
9249 /// The title, computed once the catalog is installed; see [`Self::title_fn`].
9250 #[must_use]
9251 pub fn title_fn(mut self, f: fn() -> String) -> Self {
9252 self.title_fn = Some(f);
9253 self
9254 }
9255 /// The app's version, for Day's exit line; see [`Self::version`].
9256 #[must_use]
9257 pub fn version(mut self, version: impl Into<String>) -> Self {
9258 self.version = Some(version.into());
9259 self
9260 }
9261 /// macOS window tabbing for this window; see [`Self::tabbing`].
9262 #[must_use]
9263 pub fn tabbing(mut self, tabbing: WindowTabbing) -> Self {
9264 self.tabbing = tabbing;
9265 self
9266 }
9267 /// The window's frame; see [`Self::chrome`].
9268 #[must_use]
9269 pub fn chrome(mut self, chrome: WindowChrome) -> Self {
9270 self.chrome = chrome;
9271 self
9272 }
9273 /// What shows behind the content; see [`Self::background`].
9274 #[must_use]
9275 pub fn background(mut self, background: WindowBackground) -> Self {
9276 self.background = background;
9277 self
9278 }
9279 /// No drop shadow, for a transparent or shaped window; see [`Self::shadow`].
9280 #[must_use]
9281 pub fn no_shadow(mut self) -> Self {
9282 self.shadow = false;
9283 self
9284 }
9285 /// A window the user cannot resize; see [`Self::resizable`].
9286 #[must_use]
9287 pub fn fixed_size(mut self) -> Self {
9288 self.resizable = false;
9289 self
9290 }
9291 /// Where the window opens; see [`Self::placement`].
9292 #[must_use]
9293 pub fn placement(mut self, placement: WindowPlacement) -> Self {
9294 self.placement = placement;
9295 self
9296 }
9297 /// Remember and restore this window's frame under `key`; see [`Self::remember_frame`].
9298 #[must_use]
9299 pub fn remember_frame(mut self, key: impl Into<String>) -> Self {
9300 self.remember_frame = Some(key.into());
9301 self
9302 }
9303 /// The logical window this opens; see [`Self::key`].
9304 #[must_use]
9305 pub fn key(mut self, key: impl Into<String>) -> Self {
9306 self.key = Some(key.into());
9307 self
9308 }
9309 /// The kind of window; see [`Self::kind`].
9310 #[must_use]
9311 pub fn kind(mut self, kind: WindowKind) -> Self {
9312 self.kind = kind;
9313 self
9314 }
9315}
9316
9317impl Default for WindowOptions {
9318 fn default() -> Self {
9319 WindowOptions {
9320 title: "Day".into(),
9321 size: Size::new(480.0, 640.0),
9322 min_size: None,
9323 start_hidden: false,
9324 size_to_fit: false,
9325 app_name: None,
9326 locales: None,
9327 title_fn: None,
9328 version: None,
9329 tabbing: WindowTabbing::Automatic,
9330 chrome: WindowChrome::Standard,
9331 background: WindowBackground::Opaque,
9332 shadow: true,
9333 resizable: true,
9334 placement: WindowPlacement::Automatic,
9335 max_size: None,
9336 remember_frame: None,
9337 key: None,
9338 kind: WindowKind::Normal,
9339 }
9340 }
9341}
9342
9343/// A platform backend: owns the native main loop and exactly one window in v1 (§8.1).
9344///
9345/// `run` sets up the native app + window, installs the reactive scheduler + main poster,
9346/// then hands `(self, root_container, content_size)` to `ready` (which mounts the tree and
9347/// takes ownership of the backend), and finally runs the native main loop.
9348pub trait Platform: Toolkit {
9349 /// The process-constant target id, e.g. `"macos-appkit"`.
9350 const TARGET: &'static str;
9351 /// The toolkit half of the target, e.g. `"appkit"`.
9352 const TOOLKIT: &'static str;
9353 /// Whether [`Platform::run`] returning means the app is over. True for a backend that
9354 /// drives the native loop itself until the app quits (GTK, Qt, XAML; AppKit's never
9355 /// returns). False where the host owns the loop and `run` hands back at once, with the
9356 /// app still to come (ArkUI's ability, Android's activity, the web page, the mock's test):
9357 /// their `DidExit` is the host's last callback, not the return (docs/lifecycle.md).
9358 const RUN_ENDS_APP: bool = true;
9359
9360 fn run(self, options: WindowOptions, ready: Box<dyn FnOnce(Self, Self::Handle, Size)>);
9361
9362 /// Post a closure onto the native main loop. Callable from any thread; this is the
9363 /// single door the reactive scheduler and `Setter` deliveries ride (§3.3).
9364 fn post(f: Box<dyn FnOnce() + Send>);
9365
9366 /// Post `f` onto the native main loop after (at least) `ms` milliseconds: the timer
9367 /// door behind `day::sleep` (docs/async.md). Every shipped backend overrides it with the
9368 /// loop's own timer (`dispatch_after`, `Handler.postDelayed`, `g_timeout_add`,
9369 /// `QTimer::singleShot`, `SetTimer`, `setTimeout`), so a sleep costs no thread. The
9370 /// default is the fallback for a backend without one: a helper thread that sleeps the
9371 /// whole delay and rides [`Platform::post`] home. It is correct, but a thread per sleep
9372 /// adds up under a ticking loop, so the first use says so once in the log.
9373 fn post_delayed(ms: u32, f: Box<dyn FnOnce() + Send>) {
9374 static SAID: std::sync::Once = std::sync::Once::new();
9375 SAID.call_once(|| {
9376 log::warn!(
9377 "day: {} has no native timer door; `day::sleep` falls back to a helper thread \
9378 per delay (implement `Platform::post_delayed`)",
9379 Self::TARGET
9380 );
9381 });
9382 std::thread::spawn(move || {
9383 std::thread::sleep(std::time::Duration::from_millis(u64::from(ms)));
9384 Self::post(f);
9385 });
9386 }
9387
9388 /// Ordered OS locale preference list (BCP-47), for fluent-langneg (§12.2).
9389 fn locale_hints(&self) -> Vec<String> {
9390 Vec::new()
9391 }
9392}
9393
9394// ---------------------------------------------------------------------------
9395// Open renderer registry (§8.2)
9396// ---------------------------------------------------------------------------
9397
9398/// The scale a window snapshot is rendered at, when a scripted run states one
9399/// (`DAY_CAPTURE_SCALE=2`, set by `day launch --script` from Day.toml `[screenshots]`).
9400///
9401/// For the backends that render their own snapshot (GTK, Qt): the capture then measures
9402/// window points times this, whatever display the host has, which is what makes a CI capture
9403/// under a 1x xvfb the same 2560x1600 pixels a HiDPI laptop produces. A backend that reads the
9404/// compositor's pixels back (AppKit, XAML) captures at the display's own scale and ignores it.
9405/// `None` when unset or unparseable: capture at the backend's natural scale.
9406#[must_use]
9407pub fn capture_scale() -> Option<f64> {
9408 std::env::var("DAY_CAPTURE_SCALE")
9409 .ok()
9410 .and_then(|v| v.trim().parse::<f64>().ok())
9411 .filter(|s| s.is_finite() && (0.5..=4.0).contains(s))
9412}
9413
9414/// Seconds on a monotonic clock since the first call: the frame timestamp for a backend that
9415/// does not expose a native timestamp (§8.4). The origin is arbitrary. Not for the web
9416/// build, where `Instant` is unavailable and `requestAnimationFrame` stamps the frame itself.
9417pub fn frame_timestamp() -> f64 {
9418 static ORIGIN: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new();
9419 ORIGIN
9420 .get_or_init(std::time::Instant::now)
9421 .elapsed()
9422 .as_secs_f64()
9423}
9424
9425/// The user's language preference from the POSIX environment, newest-first, as BCP-47 tags.
9426///
9427/// `LANGUAGE` is the GNU multi-language list (`fr:en`); `LC_ALL`, `LC_MESSAGES` and `LANG` each
9428/// carry one locale in POSIX form (`fr_FR.UTF-8`), which becomes `fr-FR`. Shared by the backends
9429/// whose platform has no richer API to ask (§12.2, docs/localization.md).
9430#[must_use]
9431pub fn posix_locale_hints() -> Vec<String> {
9432 let mut out: Vec<String> = Vec::new();
9433 let mut push = |tag: &str| {
9434 // "C" and "POSIX" are the absence of a preference, not a language.
9435 let tag = tag.split('.').next().unwrap_or(tag).replace('_', "-");
9436 if tag.is_empty() || tag == "C" || tag == "POSIX" {
9437 return;
9438 }
9439 if !out.contains(&tag) {
9440 out.push(tag);
9441 }
9442 };
9443 if let Ok(list) = std::env::var("LANGUAGE") {
9444 for tag in list.split(':') {
9445 push(tag);
9446 }
9447 }
9448 for key in ["LC_ALL", "LC_MESSAGES", "LANG"] {
9449 if let Ok(v) = std::env::var(key) {
9450 push(&v);
9451 }
9452 }
9453 out
9454}
9455
9456/// Optional custom measure for a third-party piece (§8.2).
9457pub type MeasureFn<B> = fn(&mut B, &<B as Toolkit>::Handle, Proposal) -> Size;
9458
9459/// A third-party piece's per-toolkit implementation. `make` receives the concrete backend
9460/// (public helper surface) and returns a native handle the backend then owns like any built-in.
9461pub struct Renderer<B: Toolkit> {
9462 pub kind: PieceKind,
9463 pub make: fn(&mut B, &dyn Any, NodeId) -> B::Handle,
9464 pub update: fn(&mut B, &B::Handle, &dyn Any),
9465 pub measure: Option<MeasureFn<B>>,
9466 /// Teardown, run from the release queue just before [`Toolkit::release`] frees the handle.
9467 ///
9468 /// A piece that keeps per-view state (a retained delegate, a session map, a native
9469 /// observer) has no other place to drop it: `make`/`update` are the only other hooks, and a
9470 /// disposed node never calls them again. Without this a piece leaks one entry per realized
9471 /// view, and any map keyed by the handle's address can go on to answer for a later view that
9472 /// the allocator hands the same address.
9473 ///
9474 /// `None` for the pieces that own nothing (most of them).
9475 pub release: Option<fn(&mut B, &B::Handle)>,
9476}
9477
9478pub struct Registry<B: Toolkit> {
9479 map: HashMap<PieceKind, Renderer<B>>,
9480}
9481
9482impl<B: Toolkit> Default for Registry<B> {
9483 fn default() -> Self {
9484 Registry {
9485 map: HashMap::new(),
9486 }
9487 }
9488}
9489
9490impl<B: Toolkit> Registry<B> {
9491 pub fn register(&mut self, r: Renderer<B>) {
9492 let kind = r.kind;
9493 if self.map.insert(kind, r).is_some() {
9494 // Two pieces claiming one kind is last-linked-wins in link order, effectively
9495 // nondeterministic. Fail loudly in debug; in release, say so once at boot rather
9496 // than render the wrong widget silently.
9497 debug_assert!(
9498 false,
9499 "duplicate renderer registered for piece kind {kind:?}"
9500 );
9501 log::warn!("duplicate renderer for piece kind {kind:?} — later registration wins");
9502 }
9503 }
9504 #[must_use]
9505 pub fn get(&self, kind: PieceKind) -> Option<&Renderer<B>> {
9506 self.map.get(kind)
9507 }
9508 pub fn kinds(&self) -> impl Iterator<Item = PieceKind> + '_ {
9509 self.map.keys().copied()
9510 }
9511}
9512
9513/// The canvas wire op codes (§11, §15.3): slot 0 of every 9-number record in
9514/// [`encode_ops`]'s output. The numeric values are the frozen wire contract: the JNI, C++,
9515/// and JS decoders each hand-write these as constants, so a value here may never be reused
9516/// or renumbered; new ops append. `ALL` drives the density test that keeps this enum and
9517/// the encoder in step.
9518#[derive(Clone, Copy, Debug, PartialEq, Eq)]
9519#[repr(i32)]
9520pub enum OpCode {
9521 /// Fill a rect (a,b=origin, c,d=size).
9522 FillRect = 0,
9523 /// Stroke a rect (g=width).
9524 StrokeRect = 1,
9525 /// Fill a rounded rect (e=radius).
9526 FillRrect = 2,
9527 /// Fill an ellipse in a rect.
9528 FillEllipse = 3,
9529 /// Stroke an ellipse (g=width).
9530 StrokeEllipse = 4,
9531 /// Stroke an arc (e=start°, f=sweep°, g=width). `Fill(Shape::Arc)` also encodes as
9532 /// this with width 0, the known asymmetry; see [`encode_ops`].
9533 StrokeArc = 5,
9534 /// Line a,b → c,d (g=width).
9535 Line = 6,
9536 /// Text at a,b (e=size, f=anchor: 0 leading / 1 centered); the string rides the texts
9537 /// channel.
9538 Text = 7,
9539 /// Save the graphics state.
9540 Save = 8,
9541 /// Restore the graphics state.
9542 Restore = 9,
9543 /// Concat an affine transform (a..f).
9544 Concat = 10,
9545 /// Fill a polygon; points ride the texts channel as "x,y x,y …" (closed automatically),
9546 /// or the geometry channel of [`encode_ops_with_geometry`] (b = offset, c = count, and
9547 /// the texts entry is empty). `a` = the [`geometry_key`] of those points, or 0 for none.
9548 FillPolygon = 11,
9549 /// Stroke a polygon (g=width); points and key as [`OpCode::FillPolygon`].
9550 StrokePolygon = 12,
9551 /// Stroke a rounded rect (e=radius, g=width).
9552 StrokeRrect = 13,
9553 /// Set a gradient for the next shape record (f=type: 0 linear with a,b=start / c,d=end
9554 /// unit points; 1 radial with a,b=center unit point, c=unit radius; e=stop count).
9555 /// Stops ride the texts channel as "offset,aarrggbb offset,aarrggbb …". Unit geometry
9556 /// resolves against the shape's bounding box.
9557 SetGradient = 14,
9558 /// Fill a path (f=fill rule: 0 non-zero / 1 even-odd); segments ride the texts channel
9559 /// (see [`encode_path`]), or the geometry channel of [`encode_ops_with_geometry`]
9560 /// (b = offset, c = count, see [`path_numbers`]; the texts entry is empty). `a` = the
9561 /// [`geometry_key`] of those segments, or 0 for none.
9562 ///
9563 /// The key is a cache handle, not a payload: a decoder that recognizes it may keep the
9564 /// native geometry it built last time and skip re-parsing the segments, but it must still
9565 /// consume the texts entry either way, because that channel is positional and a skipped
9566 /// entry desynchronizes every record after it.
9567 FillPath = 15,
9568 /// Stroke a path (g=width); segments and key as [`OpCode::FillPath`].
9569 StrokePath = 16,
9570 /// Clip to a shape (f=shape kind: 0 rect / 1 rrect(e=radius) / 2 ellipse / 3 path
9571 /// (e=fill rule) / 4 polygon; a..d=geometry; path/polygon payloads ride the texts
9572 /// channel).
9573 ///
9574 /// For the two payload-bearing kinds (3 and 4) there is no geometry in the slots, so `a`
9575 /// carries the [`geometry_key`] instead, b and c the geometry channel's offset and count
9576 /// when there is one, and d stays 0. The other three kinds put real geometry in a..d and
9577 /// have nothing to cache.
9578 Clip = 17,
9579 /// Stroke style for the next stroke record (a=cap, b=join, c=miter limit, d=dash
9580 /// phase, e=dash count; the dash array rides the texts channel).
9581 StrokeStyle = 18,
9582 /// Font for the next text record (a=CSS weight 100 … 900, 0 = default; b=italic 0/1); the
9583 /// family name rides the texts channel, `""` = the platform's default face. Like
9584 /// [`OpCode::SetGradient`] and [`OpCode::StrokeStyle`] it is consumed by the record that
9585 /// follows and then cleared; a default [`CanvasFont`] emits no record at all, so a drawing
9586 /// without fonts encodes exactly as it did before this op existed.
9587 SetFont = 19,
9588 /// The next shape record is a template, drawn once per stamped position rather than once
9589 /// (docs/canvas.md "Stamping"). `a` = how many positions follow. Like [`OpCode::SetGradient`],
9590 /// [`OpCode::StrokeStyle`] and [`OpCode::SetFont`] it is a prefix, consumed by the record it
9591 /// applies to and then cleared.
9592 ///
9593 /// Between this and that template record come `ceil(a / 4)` [`OpCode::StampPoints`] records
9594 /// carrying the coordinates. A drawing with no stamps encodes exactly as it did before.
9595 Stamp = 20,
9596 /// Four stamped positions, filling the record edge to edge: `[op, x0, y0, x1, y1, x2, y2,
9597 /// x3, y3]`, the one record that uses its last slot for geometry instead of a color, because
9598 /// it carries no color of its own. The final record of a run is padded; the count in the
9599 /// [`OpCode::Stamp`] header says how many of the pairs are real.
9600 StampPoints = 21,
9601 /// Draw a decoded image: `a,b` = origin, `c,d` = size, `e` = the [`BitmapId`], `f` = opacity
9602 /// in `0.0..=1.0` (docs/images.md).
9603 ///
9604 /// The id rides the numeric channel because it is a number, and an `f64` carries a `u64` id
9605 /// exactly up to 2^53; ids are minted from 1 per process, so that ceiling is unreachable.
9606 /// Nothing rides the texts channel for this op.
9607 Image = 22,
9608 /// The source region for the next image record (`a,b` = origin, `c,d` = size, in the
9609 /// bitmap's own pixels): [`DrawOp::Image`]'s `source`. Like [`OpCode::SetFont`] it is a
9610 /// prefix, consumed by the record that follows and then cleared, and a whole-image draw
9611 /// emits none, so a drawing without regions encodes exactly as it did before this op
9612 /// existed. A decoder clamps the region to the bitmap and draws nothing for an empty
9613 /// intersection ([`clamp_image_source`]).
9614 ImageSource = 23,
9615}
9616
9617impl OpCode {
9618 /// Every code, in wire order. The density test iterates this so a new variant that
9619 /// forgets to join fails loudly.
9620 pub const ALL: [OpCode; 24] = [
9621 OpCode::FillRect,
9622 OpCode::StrokeRect,
9623 OpCode::FillRrect,
9624 OpCode::FillEllipse,
9625 OpCode::StrokeEllipse,
9626 OpCode::StrokeArc,
9627 OpCode::Line,
9628 OpCode::Text,
9629 OpCode::Save,
9630 OpCode::Restore,
9631 OpCode::Concat,
9632 OpCode::FillPolygon,
9633 OpCode::StrokePolygon,
9634 OpCode::StrokeRrect,
9635 OpCode::SetGradient,
9636 OpCode::FillPath,
9637 OpCode::StrokePath,
9638 OpCode::Clip,
9639 OpCode::StrokeStyle,
9640 OpCode::SetFont,
9641 OpCode::Stamp,
9642 OpCode::StampPoints,
9643 OpCode::Image,
9644 OpCode::ImageSource,
9645 ];
9646
9647 /// The code back from a wire number (a decoder-side aid and the round-trip test's
9648 /// reference); `None` for anything outside the table.
9649 #[must_use]
9650 #[expect(
9651 clippy::float_cmp,
9652 reason = "wire codes are small integers, which f64 represents exactly"
9653 )]
9654 pub fn from_wire(n: f64) -> Option<OpCode> {
9655 OpCode::ALL.into_iter().find(|c| f64::from(*c as i32) == n)
9656 }
9657}
9658
9659/// Flat numeric encoding of a display list for shim/JNI boundaries (§11, §15.3): per op
9660/// 9 numbers [kind, a, b, c, d, e, f, g, rgba-bits]; text payloads ride separately in order.
9661/// The kind slot carries an [`OpCode`]; its doc comments are the per-slot contract.
9662///
9663/// Transports join `texts` with the unit separator U+001F (one entry per text-carrying
9664/// record, in order), so text payloads must not contain U+001F. Known asymmetry:
9665/// `Fill(Shape::Arc)` encodes as [`OpCode::StrokeArc`] with width 0. Filled arcs render
9666/// only on the direct-replay backends (AppKit/UIKit); use a polygon fan if a filled arc
9667/// must be portable.
9668/// Serialize a path for the `texts` side-channel: one space-separated token per segment,
9669/// `M x y` / `L x y` / `Q cx cy x y` / `C c1x c1y c2x c2y x y` / `Z`.
9670///
9671/// Text rather than numbers because that is the channel the encoder already has for
9672/// variable-length payloads, and every decoder (JS, Java, C++) can already split a string. The
9673/// numeric channel is a flat `[f64; 9]`-per-record array with no length prefix, so a path could
9674/// not ride it without changing the record shape for every backend at once.
9675/// A content key for a shape's variable-length geometry: the handle a backend caches decoded
9676/// native geometry under (a `Path2D`, a `QPainterPath`, an `android.graphics.Path`) so an
9677/// unchanged path is rebuilt once instead of re-parsed out of the texts channel every frame.
9678///
9679/// It hashes the geometry, not the op's position or its identity, so that a draw closure that
9680/// rebuilds its `PathBuilder` chain from scratch on every frame (which is what canvas consumers
9681/// do) produces an equal path, hashes the same and hits the same entry. An identity would miss
9682/// every time.
9683///
9684/// Two different paths that collided would draw each other, so the width matters: FNV-1a over the
9685/// IEEE bits, masked to the 53 bits an `f64` wire slot carries exactly. `0.0` is reserved for "no
9686/// key": a decoder seeing it must decode the payload as it always did, which is also what every
9687/// decoder written before this key existed does with the slot.
9688#[must_use]
9689pub fn geometry_key(shape: &Shape) -> f64 {
9690 fn mix(h: &mut u64, v: f64) {
9691 for byte in v.to_bits().to_le_bytes() {
9692 *h ^= u64::from(byte);
9693 *h = h.wrapping_mul(0x0000_0100_0000_01b3);
9694 }
9695 }
9696 fn mix_point(h: &mut u64, p: Point) {
9697 mix(h, p.x);
9698 mix(h, p.y);
9699 }
9700 let mut h: u64 = 0xcbf2_9ce4_8422_2325;
9701 match shape {
9702 Shape::Polygon(pts) => {
9703 // The discriminant joins the hash so a polygon and a path of the same points can
9704 // never share an entry: they decode to different geometry.
9705 mix(&mut h, 11.0);
9706 for p in pts {
9707 mix_point(&mut h, *p);
9708 }
9709 }
9710 Shape::Path(path) => {
9711 mix(&mut h, 15.0);
9712 mix(&mut h, rule_bits(path.rule));
9713 for seg in &path.segs {
9714 match seg {
9715 PathSeg::Move(a) => {
9716 mix(&mut h, 0.0);
9717 mix_point(&mut h, *a);
9718 }
9719 PathSeg::Line(a) => {
9720 mix(&mut h, 1.0);
9721 mix_point(&mut h, *a);
9722 }
9723 PathSeg::Quad(c, a) => {
9724 mix(&mut h, 2.0);
9725 mix_point(&mut h, *c);
9726 mix_point(&mut h, *a);
9727 }
9728 PathSeg::Cubic(c1, c2, a) => {
9729 mix(&mut h, 3.0);
9730 mix_point(&mut h, *c1);
9731 mix_point(&mut h, *c2);
9732 mix_point(&mut h, *a);
9733 }
9734 PathSeg::Close => mix(&mut h, 4.0),
9735 }
9736 }
9737 }
9738 // Everything else puts its whole geometry in the record's own slots, so there is nothing
9739 // to parse and nothing worth caching.
9740 _ => return 0.0,
9741 }
9742 let masked = h & ((1u64 << 53) - 1);
9743 // 0 means "no key", so the one hash that lands there borrows its neighbor.
9744 if masked == 0 { 1.0 } else { masked as f64 }
9745}
9746
9747/// Append a coordinate to the texts channel: a plain decimal with up to six fractional digits
9748/// and no trailing zeros (`12`, `-0.5`, `183.472938`), never an exponent.
9749///
9750/// Six decimals of a canvas point is a millionth of a point, far below anything a transform an
9751/// app would draw under can bring to a pixel, and the fixed form costs a tenth of the shortest
9752/// round-trip repr: one integer write instead of a float formatter and a temporary `String` per
9753/// coordinate, which was the larger half of a map tile's export on Android. The decoders parse
9754/// with their platform's general float reader, so a value the fixed form cannot carry (a
9755/// non-finite number, a magnitude past 2^53 millionths) falls back to `Display`.
9756fn push_wire_num(out: &mut String, v: f64) {
9757 use std::fmt::Write as _;
9758 const SCALE: f64 = 1_000_000.0;
9759 let scaled = (v * SCALE).round();
9760 if scaled.is_nan() || scaled.abs() >= 9.0e15 {
9761 let _ = write!(out, "{v}");
9762 return;
9763 }
9764 let mut n = scaled as i64;
9765 if n < 0 {
9766 out.push('-');
9767 n = -n;
9768 }
9769 let whole = n / 1_000_000;
9770 let mut frac = n % 1_000_000;
9771 let _ = write!(out, "{whole}");
9772 if frac != 0 {
9773 let mut digits = 6;
9774 while frac % 10 == 0 {
9775 frac /= 10;
9776 digits -= 1;
9777 }
9778 out.push('.');
9779 let _ = write!(out, "{frac:0digits$}");
9780 }
9781}
9782
9783/// Polygon points for the texts channel: `"x,y x,y …"`, numbers as [`push_wire_num`] writes
9784/// them.
9785fn encode_points(pts: &[Point]) -> String {
9786 let mut out = String::with_capacity(pts.len() * 16);
9787 for p in pts {
9788 if !out.is_empty() {
9789 out.push(' ');
9790 }
9791 push_wire_num(&mut out, p.x);
9792 out.push(',');
9793 push_wire_num(&mut out, p.y);
9794 }
9795 out
9796}
9797
9798/// Path segments for the texts channel: `"M x y L x y Q cx cy x y C … Z"`, one token per
9799/// command or number. Coordinates use up to six decimal places, without trailing zeros;
9800/// non-finite values and magnitudes outside the fixed-point range use their display form.
9801#[must_use]
9802pub fn encode_path(path: &Path) -> String {
9803 let mut out = String::with_capacity(path.segs.len() * 16);
9804 let points = |out: &mut String, cmd: char, pts: &[Point]| {
9805 if !out.is_empty() {
9806 out.push(' ');
9807 }
9808 out.push(cmd);
9809 for p in pts {
9810 out.push(' ');
9811 push_wire_num(out, p.x);
9812 out.push(' ');
9813 push_wire_num(out, p.y);
9814 }
9815 };
9816 for seg in &path.segs {
9817 match seg {
9818 PathSeg::Move(p) => points(&mut out, 'M', &[*p]),
9819 PathSeg::Line(p) => points(&mut out, 'L', &[*p]),
9820 PathSeg::Quad(c, p) => points(&mut out, 'Q', &[*c, *p]),
9821 PathSeg::Cubic(a, b, p) => points(&mut out, 'C', &[*a, *b, *p]),
9822 PathSeg::Close => points(&mut out, 'Z', &[]),
9823 }
9824 }
9825 out
9826}
9827
9828/// Clamp a [`DrawOp::Image`] `source` region to the bitmap it indexes (`pixels` wide and high),
9829/// keeping the region's mapping into `rect`: the answer is the part of the region inside the
9830/// bitmap and the part of `rect` it lands in.
9831///
9832/// The single definition of what an out-of-range region means. The mapping is kept rather than
9833/// the clamped part stretched over the whole of `rect`, because that is what every native
9834/// sub-rect draw does on its own (Qt, the HTML canvas) and what the clip-and-scale fallback
9835/// gives for free, so the backends agree. `None` (an empty region, an empty intersection, or a
9836/// bitmap with no pixels) draws nothing. Every backend that replays in Rust calls this; the
9837/// C++/Java/JS decoders repeat the same arithmetic.
9838#[must_use]
9839pub fn clamp_image_source(source: Rect, rect: Rect, pixels: Size) -> Option<(Rect, Rect)> {
9840 if !(source.size.width > 0.0 && source.size.height > 0.0) {
9841 return None;
9842 }
9843 let x0 = source.origin.x.max(0.0);
9844 let y0 = source.origin.y.max(0.0);
9845 let x1 = (source.origin.x + source.size.width).min(pixels.width);
9846 let y1 = (source.origin.y + source.size.height).min(pixels.height);
9847 if !(x1 > x0 && y1 > y0) {
9848 return None;
9849 }
9850 let kx = rect.size.width / source.size.width;
9851 let ky = rect.size.height / source.size.height;
9852 let dest = Rect::new(
9853 rect.origin.x + (x0 - source.origin.x) * kx,
9854 rect.origin.y + (y0 - source.origin.y) * ky,
9855 (x1 - x0) * kx,
9856 (y1 - y0) * ky,
9857 );
9858 Some((Rect::new(x0, y0, x1 - x0, y1 - y0), dest))
9859}
9860
9861/// `FillRule` as a wire number: 0 non-zero, 1 even-odd.
9862fn rule_bits(rule: FillRule) -> f64 {
9863 match rule {
9864 FillRule::NonZero => 0.0,
9865 FillRule::EvenOdd => 1.0,
9866 }
9867}
9868
9869/// Encode a display list for a decoder written in another language (Java, C++, JS): the
9870/// numbers channel, nine `f64` slots per record (`[kind, a, b, c, d, e, f, g, color]`, kinds
9871/// from [`OpCode`]), and the texts channel, one entry per record that carries text or
9872/// variable-length geometry, in record order.
9873#[must_use]
9874pub fn encode_ops(ops: &[DrawOp]) -> (Vec<f64>, Vec<String>) {
9875 encode_ops_into(ops, None)
9876}
9877
9878/// [`encode_ops`] with a third, geometry channel: the points of every path and polygon (fills,
9879/// strokes, clips) as numbers instead of text. Such a record's slot `b` is its offset into the
9880/// channel and slot `c` its count, and its texts entry is empty, so that channel stays
9881/// positional for a decoder that ignores the third one. Paths are written by
9882/// [`path_numbers`], polygons by [`point_numbers`].
9883///
9884/// Formatting a coordinate and parsing it back were, together, half of what a map tile's export
9885/// cost on Android (docs/canvas.md "Exporting"); a decoder that can take an array of doubles
9886/// across its boundary skips both.
9887#[must_use]
9888pub fn encode_ops_with_geometry(ops: &[DrawOp]) -> (Vec<f64>, Vec<String>, Vec<f64>) {
9889 let mut geometry = Vec::new();
9890 let (nums, texts) = encode_ops_into(ops, Some(&mut geometry));
9891 (nums, texts, geometry)
9892}
9893
9894/// A path's segments for the geometry channel: a command code, then its points — `0` move
9895/// (x y), `1` line (x y), `2` quad (cx cy x y), `3` cubic (x1 y1 x2 y2 x y), `4` close.
9896pub fn path_numbers(path: &Path, out: &mut Vec<f64>) {
9897 for seg in &path.segs {
9898 match seg {
9899 PathSeg::Move(p) => out.extend_from_slice(&[0.0, p.x, p.y]),
9900 PathSeg::Line(p) => out.extend_from_slice(&[1.0, p.x, p.y]),
9901 PathSeg::Quad(c, p) => out.extend_from_slice(&[2.0, c.x, c.y, p.x, p.y]),
9902 PathSeg::Cubic(a, b, p) => out.extend_from_slice(&[3.0, a.x, a.y, b.x, b.y, p.x, p.y]),
9903 PathSeg::Close => out.push(4.0),
9904 }
9905 }
9906}
9907
9908/// A polygon's points for the geometry channel: x then y, per point.
9909pub fn point_numbers(pts: &[Point], out: &mut Vec<f64>) {
9910 for p in pts {
9911 out.push(p.x);
9912 out.push(p.y);
9913 }
9914}
9915
9916/// Put a path's or polygon's points on the wire: on the geometry channel when the caller opened
9917/// one, as `numbers` writes them, answering (offset, count) for slots b and c and leaving an
9918/// empty texts entry; else as `text` on the texts channel, answering (0, 0).
9919fn geometry_payload(
9920 geometry: &mut Option<&mut Vec<f64>>,
9921 texts: &mut Vec<String>,
9922 text: impl FnOnce() -> String,
9923 numbers: impl FnOnce(&mut Vec<f64>),
9924) -> (f64, f64) {
9925 if let Some(g) = geometry {
9926 let offset = g.len();
9927 numbers(g);
9928 texts.push(String::new());
9929 (offset as f64, (g.len() - offset) as f64)
9930 } else {
9931 texts.push(text());
9932 (0.0, 0.0)
9933 }
9934}
9935
9936fn encode_ops_into(ops: &[DrawOp], mut geometry: Option<&mut Vec<f64>>) -> (Vec<f64>, Vec<String>) {
9937 fn color_bits(c: Color) -> f64 {
9938 let r = (c.r.clamp(0.0, 1.0) * 255.0) as u32;
9939 let g = (c.g.clamp(0.0, 1.0) * 255.0) as u32;
9940 let b = (c.b.clamp(0.0, 1.0) * 255.0) as u32;
9941 let a = (c.a.clamp(0.0, 1.0) * 255.0) as u32;
9942 f64::from((a << 24) | (r << 16) | (g << 8) | b)
9943 }
9944 #[allow(clippy::too_many_arguments)]
9945 fn push(
9946 k: OpCode,
9947 a: f64,
9948 b: f64,
9949 c: f64,
9950 d: f64,
9951 e: f64,
9952 f: f64,
9953 g: f64,
9954 col: Color,
9955 nums: &mut Vec<f64>,
9956 ) {
9957 nums.extend_from_slice(&[f64::from(k as i32), a, b, c, d, e, f, g, color_bits(col)]);
9958 }
9959 /// The kind-18 prefix a non-plain stroke style emits, applying to the next stroke record,
9960 /// the same "modifier record" rule the gradient and font records follow. A plain style emits
9961 /// nothing, so a drawing without dashes or caps encodes exactly as it always did.
9962 fn stroke_style_record(style: &StrokeStyle, nums: &mut Vec<f64>, texts: &mut Vec<String>) {
9963 if style.is_plain() {
9964 return;
9965 }
9966 push(
9967 OpCode::StrokeStyle,
9968 match style.cap {
9969 LineCap::Butt => 0.0,
9970 LineCap::Round => 1.0,
9971 LineCap::Square => 2.0,
9972 },
9973 match style.join {
9974 LineJoin::Miter => 0.0,
9975 LineJoin::Round => 1.0,
9976 LineJoin::Bevel => 2.0,
9977 },
9978 style.miter_limit,
9979 style.dash_phase,
9980 style.dash.len() as f64,
9981 0.0,
9982 0.0,
9983 Color::CLEAR,
9984 nums,
9985 );
9986 texts.push(
9987 style
9988 .dash
9989 .iter()
9990 .map(std::string::ToString::to_string)
9991 .collect::<Vec<_>>()
9992 .join(" "),
9993 );
9994 }
9995
9996 /// One shape record (the fill/stroke kinds shared by both ops).
9997 fn shape_record(
9998 stroke: bool,
9999 shape: &Shape,
10000 w: f64,
10001 col: Color,
10002 nums: &mut Vec<f64>,
10003 texts: &mut Vec<String>,
10004 geometry: &mut Option<&mut Vec<f64>>,
10005 ) {
10006 match shape {
10007 Shape::Rect(r) => push(
10008 if stroke {
10009 OpCode::StrokeRect
10010 } else {
10011 OpCode::FillRect
10012 },
10013 r.origin.x,
10014 r.origin.y,
10015 r.size.width,
10016 r.size.height,
10017 0.0,
10018 0.0,
10019 w,
10020 col,
10021 nums,
10022 ),
10023 Shape::RoundedRect(r, rad) => push(
10024 if stroke {
10025 OpCode::StrokeRrect
10026 } else {
10027 OpCode::FillRrect
10028 },
10029 r.origin.x,
10030 r.origin.y,
10031 r.size.width,
10032 r.size.height,
10033 *rad,
10034 0.0,
10035 w,
10036 col,
10037 nums,
10038 ),
10039 Shape::Ellipse(r) => push(
10040 if stroke {
10041 OpCode::StrokeEllipse
10042 } else {
10043 OpCode::FillEllipse
10044 },
10045 r.origin.x,
10046 r.origin.y,
10047 r.size.width,
10048 r.size.height,
10049 0.0,
10050 0.0,
10051 w,
10052 col,
10053 nums,
10054 ),
10055 Shape::Arc {
10056 rect,
10057 start_deg,
10058 sweep_deg,
10059 } => push(
10060 OpCode::StrokeArc,
10061 rect.origin.x,
10062 rect.origin.y,
10063 rect.size.width,
10064 rect.size.height,
10065 *start_deg,
10066 *sweep_deg,
10067 w,
10068 col,
10069 nums,
10070 ),
10071 Shape::Line(p1, p2) => {
10072 push(OpCode::Line, p1.x, p1.y, p2.x, p2.y, 0.0, 0.0, w, col, nums);
10073 }
10074 Shape::Polygon(pts) => {
10075 // Variable-length points ride the texts side-channel ("x,y x,y …"),
10076 // consumed in record order exactly like text payloads, or the geometry
10077 // channel when there is one (slots b, c).
10078 let (offset, count) = geometry_payload(
10079 geometry,
10080 texts,
10081 || encode_points(pts),
10082 |g| point_numbers(pts, g),
10083 );
10084 push(
10085 if stroke {
10086 OpCode::StrokePolygon
10087 } else {
10088 OpCode::FillPolygon
10089 },
10090 geometry_key(shape),
10091 offset,
10092 count,
10093 0.0,
10094 0.0,
10095 0.0,
10096 w,
10097 col,
10098 nums,
10099 );
10100 }
10101 Shape::Path(path) => {
10102 // Same side-channels as Polygon, one token per segment (see `encode_path`).
10103 // The fill rule rides slot f; stroking ignores it.
10104 let (offset, count) = geometry_payload(
10105 geometry,
10106 texts,
10107 || encode_path(path),
10108 |g| path_numbers(path, g),
10109 );
10110 push(
10111 if stroke {
10112 OpCode::StrokePath
10113 } else {
10114 OpCode::FillPath
10115 },
10116 geometry_key(shape),
10117 offset,
10118 count,
10119 0.0,
10120 0.0,
10121 rule_bits(path.rule),
10122 w,
10123 col,
10124 nums,
10125 );
10126 }
10127 }
10128 }
10129 /// A gradient applies to the next shape record, fill or stroke. Geometry per type rides
10130 /// slots a..d and the type discriminant slot f: one record shape, so every decoder keeps a
10131 /// single gradient code path.
10132 fn gradient_record(
10133 geo: [f64; 4],
10134 kind: f64,
10135 stops: &[(f64, Color)],
10136 nums: &mut Vec<f64>,
10137 texts: &mut Vec<String>,
10138 ) {
10139 push(
10140 OpCode::SetGradient,
10141 geo[0],
10142 geo[1],
10143 geo[2],
10144 geo[3],
10145 stops.len() as f64,
10146 kind,
10147 0.0,
10148 Color::CLEAR,
10149 nums,
10150 );
10151 texts.push(
10152 stops
10153 .iter()
10154 .map(|(o, c)| format!("{o},{:08x}", color_bits(*c) as u32))
10155 .collect::<Vec<_>>()
10156 .join(" "),
10157 );
10158 }
10159 let mut nums = Vec::with_capacity(ops.len() * 9);
10160 let mut texts = Vec::new();
10161 for op in ops {
10162 match op {
10163 DrawOp::Fill(shape, paint) => {
10164 // A gradient emits one kind-14 set-gradient record before its shape record;
10165 // the stops ride the texts channel as "offset,aarrggbb offset,aarrggbb …".
10166 // Geometry per type rides slots a..d, the type discriminant slot f: one
10167 // record shape, so every decoder keeps a single gradient code path.
10168 let col = match paint {
10169 Paint::Solid(c) => *c,
10170 Paint::Linear(g) => {
10171 gradient_record(
10172 [g.start.x, g.start.y, g.end.x, g.end.y],
10173 0.0,
10174 &g.stops,
10175 &mut nums,
10176 &mut texts,
10177 );
10178 // The gradient replaces the shape record's color, but it must be
10179 // opaque, not clear: Skia-based decoders (Android Paint, OH_Drawing)
10180 // modulate a shader by the paint alpha, so a clear slot would render
10181 // the whole gradient invisible.
10182 Color::WHITE
10183 }
10184 Paint::Radial(g) => {
10185 gradient_record(
10186 [g.center.x, g.center.y, g.radius, 0.0],
10187 1.0,
10188 &g.stops,
10189 &mut nums,
10190 &mut texts,
10191 );
10192 Color::WHITE
10193 }
10194 };
10195 shape_record(false, shape, 0.0, col, &mut nums, &mut texts, &mut geometry);
10196 }
10197 DrawOp::Stamp(st) => {
10198 // No copies means no drawing. Some native decoders use an empty point
10199 // buffer to mean an ordinary (unstamped) template, so omit the entire op.
10200 if st.at.is_empty() {
10201 continue;
10202 }
10203 // A prefix record, then the coordinates, then the template shape record: the
10204 // "applies to the next record" rule the gradient, stroke style and font records
10205 // already follow, so a decoder needs no new kind of state, only one more slot in
10206 // the state it keeps. The template goes last because a decoder has to hold the
10207 // points before it can draw with them.
10208 //
10209 // The points are numbers on the numeric channel, not the texts channel a
10210 // polygon's points ride: this op exists for tens of thousands of them, and
10211 // formatting that many floats into a string every frame would cost more than
10212 // the individual ops it replaces.
10213 let col = match &st.paint {
10214 Paint::Solid(c) => *c,
10215 Paint::Linear(g) => {
10216 gradient_record(
10217 [g.start.x, g.start.y, g.end.x, g.end.y],
10218 0.0,
10219 &g.stops,
10220 &mut nums,
10221 &mut texts,
10222 );
10223 Color::WHITE
10224 }
10225 Paint::Radial(g) => {
10226 gradient_record(
10227 [g.center.x, g.center.y, g.radius, 0.0],
10228 1.0,
10229 &g.stops,
10230 &mut nums,
10231 &mut texts,
10232 );
10233 Color::WHITE
10234 }
10235 };
10236 push(
10237 OpCode::Stamp,
10238 st.at.len() as f64,
10239 0.0,
10240 0.0,
10241 0.0,
10242 0.0,
10243 0.0,
10244 0.0,
10245 Color::CLEAR,
10246 &mut nums,
10247 );
10248 for chunk in st.at.chunks(4) {
10249 // Written directly rather than through `push`: this is the one record whose
10250 // last slot is a coordinate rather than a color, which is what lets four
10251 // points fit with nothing wasted.
10252 let mut rec = [
10253 f64::from(OpCode::StampPoints as i32),
10254 0.0,
10255 0.0,
10256 0.0,
10257 0.0,
10258 0.0,
10259 0.0,
10260 0.0,
10261 0.0,
10262 ];
10263 for (i, p) in chunk.iter().enumerate() {
10264 rec[1 + i * 2] = p.x;
10265 rec[2 + i * 2] = p.y;
10266 }
10267 nums.extend_from_slice(&rec);
10268 }
10269 match &st.stroke {
10270 None => shape_record(
10271 false,
10272 &st.shape,
10273 0.0,
10274 col,
10275 &mut nums,
10276 &mut texts,
10277 &mut geometry,
10278 ),
10279 Some(style) => {
10280 stroke_style_record(style, &mut nums, &mut texts);
10281 shape_record(
10282 true,
10283 &st.shape,
10284 style.width,
10285 col,
10286 &mut nums,
10287 &mut texts,
10288 &mut geometry,
10289 );
10290 }
10291 }
10292 }
10293 DrawOp::Stroke(shape, paint, style) => {
10294 // A styled stroke emits one kind-18 record first, applying to the next stroke
10295 // only, the same "modifier record" shape the gradient uses, so decoders keep
10296 // one rule: consume, apply to the next shape record, reset.
10297 stroke_style_record(style, &mut nums, &mut texts);
10298 let col = match paint {
10299 Paint::Solid(c) => *c,
10300 Paint::Linear(g) => {
10301 gradient_record(
10302 [g.start.x, g.start.y, g.end.x, g.end.y],
10303 0.0,
10304 &g.stops,
10305 &mut nums,
10306 &mut texts,
10307 );
10308 Color::WHITE
10309 }
10310 Paint::Radial(g) => {
10311 gradient_record(
10312 [g.center.x, g.center.y, g.radius, 0.0],
10313 1.0,
10314 &g.stops,
10315 &mut nums,
10316 &mut texts,
10317 );
10318 Color::WHITE
10319 }
10320 };
10321 shape_record(
10322 true,
10323 shape,
10324 style.width,
10325 col,
10326 &mut nums,
10327 &mut texts,
10328 &mut geometry,
10329 );
10330 }
10331 DrawOp::Clip(shape) => {
10332 // One record for every clip shape, with the shape kind in slot f and the
10333 // geometry in a..e; a path or polygon puts its points on the texts channel.
10334 // Encoding clips as a variant of `shape_record` instead would need a third
10335 // kind code per shape, which is five more numbers every decoder must learn.
10336 let (kind, geo, extra, payload): (f64, [f64; 4], f64, Option<String>) = match shape
10337 {
10338 Shape::Rect(r) => (
10339 0.0,
10340 [r.origin.x, r.origin.y, r.size.width, r.size.height],
10341 0.0,
10342 None,
10343 ),
10344 Shape::RoundedRect(r, rad) => (
10345 1.0,
10346 [r.origin.x, r.origin.y, r.size.width, r.size.height],
10347 *rad,
10348 None,
10349 ),
10350 Shape::Ellipse(r) => (
10351 2.0,
10352 [r.origin.x, r.origin.y, r.size.width, r.size.height],
10353 0.0,
10354 None,
10355 ),
10356 // Slot a carries the geometry key for these two sub-kinds only. The other
10357 // three put real geometry there, which is why the key rides the same slot
10358 // the payload-bearing kinds leave empty; b and c are the geometry
10359 // channel's offset and count when there is one.
10360 Shape::Path(p) => {
10361 let (offset, count) = geometry_payload(
10362 &mut geometry,
10363 &mut texts,
10364 || encode_path(p),
10365 |g| path_numbers(p, g),
10366 );
10367 (
10368 3.0,
10369 [geometry_key(shape), offset, count, 0.0],
10370 rule_bits(p.rule),
10371 None,
10372 )
10373 }
10374 Shape::Polygon(pts) => {
10375 let (offset, count) = geometry_payload(
10376 &mut geometry,
10377 &mut texts,
10378 || encode_points(pts),
10379 |g| point_numbers(pts, g),
10380 );
10381 (4.0, [geometry_key(shape), offset, count, 0.0], 0.0, None)
10382 }
10383 // A clip to a line or an arc has no interior to clip to. Clipping to an
10384 // empty region would blank everything after it, so clip to the shape's
10385 // bounds instead: wrong in the same direction as no clip at all.
10386 Shape::Line(..) | Shape::Arc { .. } => {
10387 let r = shape.bounds();
10388 (
10389 0.0,
10390 [r.origin.x, r.origin.y, r.size.width, r.size.height],
10391 0.0,
10392 None,
10393 )
10394 }
10395 };
10396 push(
10397 OpCode::Clip,
10398 geo[0],
10399 geo[1],
10400 geo[2],
10401 geo[3],
10402 extra,
10403 kind,
10404 0.0,
10405 Color::CLEAR,
10406 &mut nums,
10407 );
10408 if let Some(s) = payload {
10409 texts.push(s);
10410 }
10411 }
10412 DrawOp::Text {
10413 text,
10414 at,
10415 size,
10416 color,
10417 anchor,
10418 font,
10419 } => {
10420 if *font != CanvasFont::default() {
10421 push(
10422 OpCode::SetFont,
10423 f64::from(font.css_weight()),
10424 f64::from(u8::from(font.italic)),
10425 0.0,
10426 0.0,
10427 0.0,
10428 0.0,
10429 0.0,
10430 Color::CLEAR,
10431 &mut nums,
10432 );
10433 texts.push(
10434 font.family_str()
10435 .replace([FONT_LIST_FIELD, FONT_LIST_FAMILY], " "),
10436 );
10437 }
10438 push(
10439 OpCode::Text,
10440 at.x,
10441 at.y,
10442 0.0,
10443 0.0,
10444 *size,
10445 anchor.pack(),
10446 0.0,
10447 *color,
10448 &mut nums,
10449 );
10450 texts.push(text.clone());
10451 }
10452 DrawOp::Image {
10453 image,
10454 rect,
10455 opacity,
10456 source,
10457 } => {
10458 if let Some(src) = source {
10459 push(
10460 OpCode::ImageSource,
10461 src.origin.x,
10462 src.origin.y,
10463 src.size.width,
10464 src.size.height,
10465 0.0,
10466 0.0,
10467 0.0,
10468 Color::CLEAR,
10469 &mut nums,
10470 );
10471 }
10472 push(
10473 OpCode::Image,
10474 rect.origin.x,
10475 rect.origin.y,
10476 rect.size.width,
10477 rect.size.height,
10478 image.0 as f64,
10479 *opacity,
10480 0.0,
10481 Color::CLEAR,
10482 &mut nums,
10483 );
10484 }
10485 DrawOp::Save => push(
10486 OpCode::Save,
10487 0.0,
10488 0.0,
10489 0.0,
10490 0.0,
10491 0.0,
10492 0.0,
10493 0.0,
10494 Color::CLEAR,
10495 &mut nums,
10496 ),
10497 DrawOp::Restore => push(
10498 OpCode::Restore,
10499 0.0,
10500 0.0,
10501 0.0,
10502 0.0,
10503 0.0,
10504 0.0,
10505 0.0,
10506 Color::CLEAR,
10507 &mut nums,
10508 ),
10509 DrawOp::Concat(m) => push(
10510 OpCode::Concat,
10511 m.a,
10512 m.b,
10513 m.c,
10514 m.d,
10515 m.tx,
10516 m.ty,
10517 0.0,
10518 Color::CLEAR,
10519 &mut nums,
10520 ),
10521 }
10522 }
10523 (nums, texts)
10524}
10525
10526#[cfg(test)]
10527mod font_list_tests {
10528 use super::*;
10529
10530 #[test]
10531 fn css_weights_round_trip_and_snap_to_the_nearest_rung() {
10532 for w in FontWeight::ALL {
10533 assert_eq!(FontWeight::from_css(w.css()), w);
10534 }
10535 assert_eq!(FontWeight::from_css(0), FontWeight::UltraLight);
10536 assert_eq!(FontWeight::from_css(350), FontWeight::Regular); // ties go heavier
10537 assert_eq!(FontWeight::from_css(649), FontWeight::Semibold);
10538 assert_eq!(FontWeight::from_css(1200), FontWeight::Black);
10539 }
10540
10541 fn sans() -> FontFamilyInfo {
10542 FontFamilyInfo {
10543 family: "Day Sans".into(),
10544 faces: vec![
10545 FontFace {
10546 name: "Regular".into(),
10547 weight: FontWeight::Regular,
10548 italic: false,
10549 },
10550 FontFace {
10551 name: "Bold".into(),
10552 weight: FontWeight::Bold,
10553 italic: false,
10554 },
10555 FontFace {
10556 name: "Light Italic".into(),
10557 weight: FontWeight::Light,
10558 italic: true,
10559 },
10560 ],
10561 }
10562 }
10563
10564 #[test]
10565 fn face_for_prefers_the_slant_then_the_nearest_weight() {
10566 let f = sans();
10567 assert!(f.has_bold() && f.has_italic());
10568 assert_eq!(f.face_for(FontWeight::Bold, false).unwrap().name, "Bold");
10569 assert_eq!(
10570 f.face_for(FontWeight::Semibold, false).unwrap().name,
10571 "Bold"
10572 );
10573 assert_eq!(
10574 f.face_for(FontWeight::Medium, false).unwrap().name,
10575 "Regular"
10576 );
10577 let tie = FontFamilyInfo {
10578 family: "Tie".into(),
10579 faces: vec![
10580 FontFace {
10581 name: "Light".into(),
10582 weight: FontWeight::Light,
10583 italic: false,
10584 },
10585 FontFace {
10586 name: "Bold".into(),
10587 weight: FontWeight::Bold,
10588 italic: false,
10589 },
10590 ],
10591 };
10592 // Medium sits 200 from both; the heavier face wins the tie.
10593 assert_eq!(
10594 tie.face_for(FontWeight::Medium, false).unwrap().name,
10595 "Bold"
10596 );
10597 assert_eq!(
10598 f.face_for(FontWeight::Black, true).unwrap().name,
10599 "Light Italic"
10600 );
10601 let none = FontFamilyInfo {
10602 family: "Empty".into(),
10603 faces: vec![],
10604 };
10605 assert!(none.face_for(FontWeight::Regular, false).is_none());
10606 assert!(!none.has_bold());
10607 }
10608
10609 #[test]
10610 fn the_shim_list_format_decodes_tolerantly() {
10611 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\
10612 \u{1e}\u{1e}Day Mono\u{1f}Regular\u{1f}400\u{1f}0\u{1e}Faceless";
10613 let list = parse_font_list(s);
10614 assert_eq!(list.len(), 3);
10615 assert_eq!(list[0].family, "Day Sans");
10616 assert_eq!(list[0].faces.len(), 2, "the bad weight is skipped");
10617 assert_eq!(list[0].faces[1].name, "Bold Italic"); // synthesized from 700 + italic
10618 assert_eq!(list[1].family, "Day Mono");
10619 assert_eq!(list[2].family, "Faceless");
10620 assert_eq!(list[2].faces, [] as [FontFace; 0]);
10621 }
10622
10623 #[test]
10624 fn approximate_metrics_scale_with_size_and_length() {
10625 let m = TextMetrics::approximate("abc", 10.0);
10626 assert_eq!((m.width, m.height, m.ascent), (18.0, 12.0, 9.0));
10627 assert_eq!(TextMetrics::approximate("", 10.0).width, 0.0);
10628 }
10629
10630 #[test]
10631 fn a_default_canvas_font_is_the_platform_face() {
10632 let f = CanvasFont::default();
10633 assert_eq!((f.family_str(), f.css_weight(), f.italic), ("", 0, false));
10634 }
10635}
10636
10637#[cfg(test)]
10638mod image_header_tests {
10639 use super::*;
10640
10641 /// A 4×2 PNG: signature, then an IHDR whose width and height are big-endian.
10642 fn png(w: u32, h: u32) -> Vec<u8> {
10643 let mut v = vec![0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a];
10644 v.extend(13u32.to_be_bytes());
10645 v.extend(b"IHDR");
10646 v.extend(w.to_be_bytes());
10647 v.extend(h.to_be_bytes());
10648 v
10649 }
10650
10651 /// A JPEG whose frame header sits behind one other segment, so the walk has to skip it.
10652 fn jpeg(w: u16, h: u16) -> Vec<u8> {
10653 let mut v = vec![0xFF, 0xD8]; // SOI
10654 v.extend([0xFF, 0xE0, 0x00, 0x04, 0x00, 0x00]); // APP0, length 4
10655 v.extend([0xFF, 0xC0, 0x00, 0x11, 0x08]); // SOF0, length 17, precision 8
10656 v.extend(h.to_be_bytes());
10657 v.extend(w.to_be_bytes());
10658 v
10659 }
10660
10661 #[test]
10662 fn a_header_states_the_size_before_anything_decodes() {
10663 assert_eq!(ImageFormat::dimensions(&png(512, 512)), Some((512, 512)));
10664 assert_eq!(ImageFormat::dimensions(&png(1, 65535)), Some((1, 65535)));
10665 // The JPEG walk must step over the APP0 segment to reach the frame header.
10666 assert_eq!(ImageFormat::dimensions(&jpeg(640, 480)), Some((640, 480)));
10667
10668 let mut gif = b"GIF89a".to_vec();
10669 gif.extend(320u16.to_le_bytes());
10670 gif.extend(240u16.to_le_bytes());
10671 assert_eq!(ImageFormat::dimensions(&gif), Some((320, 240)));
10672
10673 // A top-down BMP states its height as a negative number; the size is still positive.
10674 let mut bmp = b"BM".to_vec();
10675 bmp.resize(18, 0);
10676 bmp.extend(64i32.to_le_bytes());
10677 bmp.extend((-32i32).to_le_bytes());
10678 assert_eq!(ImageFormat::dimensions(&bmp), Some((64, 32)));
10679 }
10680
10681 #[test]
10682 fn a_truncated_or_unknown_header_answers_nothing_rather_than_a_guess() {
10683 assert_eq!(ImageFormat::dimensions(&[]), None);
10684 // The signature is there but the IHDR is not.
10685 assert_eq!(ImageFormat::dimensions(&png(8, 8)[..12]), None);
10686 // Not an image at all.
10687 assert_eq!(ImageFormat::dimensions(b"not an image"), None);
10688 // A JPEG that never reaches a frame header must not loop or invent a size.
10689 assert_eq!(
10690 ImageFormat::dimensions(&[0xFF, 0xD8, 0xFF, 0xE0, 0x00, 0x04, 0, 0]),
10691 None
10692 );
10693 }
10694}
10695
10696#[cfg(test)]
10697mod encode_ops_tests {
10698 use super::*;
10699
10700 /// The texts channel carries plain decimals: whole numbers without a point, fractions to
10701 /// six places with the trailing zeros gone, and the general form only past what the fixed
10702 /// one can hold.
10703 #[test]
10704 fn wire_numbers_are_short_plain_decimals() {
10705 let text = |v: f64| {
10706 let mut out = String::new();
10707 push_wire_num(&mut out, v);
10708 out
10709 };
10710 assert_eq!(text(12.0), "12");
10711 assert_eq!(text(-0.5), "-0.5");
10712 assert_eq!(text(183.472_938_472_938_4), "183.472938");
10713 assert_eq!(text(0.1 + 0.2), "0.3");
10714 assert_eq!(text(-0.000_000_1), "0");
10715 assert_eq!(text(2.000_05), "2.00005");
10716 assert_eq!(text(f64::INFINITY), "inf");
10717 assert_eq!(text(1.0e17), "100000000000000000");
10718 let path = Path {
10719 segs: vec![
10720 PathSeg::Move(Point::new(1.5, 2.0)),
10721 PathSeg::Line(Point::new(-3.25, 4.0)),
10722 PathSeg::Close,
10723 ],
10724 rule: FillRule::NonZero,
10725 };
10726 assert_eq!(encode_path(&path), "M 1.5 2 L -3.25 4 Z");
10727 assert_eq!(
10728 encode_points(&[Point::new(0.0, 0.0), Point::new(10.0, 0.125)]),
10729 "0,0 10,0.125"
10730 );
10731 }
10732
10733 /// With the geometry channel open, a path's and a polygon's points leave the texts channel
10734 /// (an empty entry keeps it positional) for the numbers, with offset and count in slots b
10735 /// and c; without it the texts channel carries them exactly as before.
10736 #[test]
10737 fn geometry_channel_carries_points_as_numbers() {
10738 let path = Shape::Path(Path {
10739 segs: vec![
10740 PathSeg::Move(Point::new(1.0, 2.0)),
10741 PathSeg::Quad(Point::new(3.0, 4.0), Point::new(5.0, 6.0)),
10742 PathSeg::Close,
10743 ],
10744 rule: FillRule::EvenOdd,
10745 });
10746 let polygon = Shape::Polygon(vec![Point::new(0.0, 0.0), Point::new(7.0, 8.0)]);
10747 let ops = vec![
10748 DrawOp::Clip(path.clone()),
10749 DrawOp::Fill(path.clone(), Paint::Solid(Color::WHITE)),
10750 DrawOp::Stroke(
10751 polygon.clone(),
10752 Paint::Solid(Color::WHITE),
10753 StrokeStyle::default(),
10754 ),
10755 ];
10756 let (nums, texts, geometry) = encode_ops_with_geometry(&ops);
10757 assert_eq!(texts, vec!["", "", ""]);
10758 assert_eq!(
10759 geometry,
10760 vec![
10761 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,
10762 6.0, 4.0, 0.0, 0.0, 7.0, 8.0
10763 ]
10764 );
10765 // The clip (kind 17, sub-kind 3 in f) and the fill (kind 15) point at the two copies
10766 // of the path, the stroke (kind 12) at the polygon's four numbers.
10767 assert_eq!((nums[0], nums[2], nums[3], nums[6]), (17.0, 0.0, 9.0, 3.0));
10768 assert_eq!(
10769 (nums[9], nums[11], nums[12], nums[15]),
10770 (15.0, 9.0, 9.0, 1.0)
10771 );
10772 assert_eq!((nums[18], nums[20], nums[21]), (12.0, 18.0, 4.0));
10773 let (plain_nums, plain_texts) = encode_ops(&ops);
10774 assert_eq!(plain_texts[1], "M 1 2 Q 3 4 5 6 Z");
10775 assert_eq!(plain_texts[2], "0,0 7,8");
10776 assert_eq!((plain_nums[11], plain_nums[12]), (0.0, 0.0));
10777 }
10778
10779 /// A region outside the bitmap is clamped to it with its mapping into the rect kept, and an
10780 /// empty intersection draws nothing.
10781 #[test]
10782 fn image_source_clamps_to_the_bitmap() {
10783 let px = Size::new(64.0, 32.0);
10784 let dest = Rect::new(100.0, 200.0, 32.0, 32.0); // 2 points per source pixel
10785 assert_eq!(
10786 clamp_image_source(Rect::new(-8.0, -8.0, 16.0, 16.0), dest, px),
10787 Some((
10788 Rect::new(0.0, 0.0, 8.0, 8.0),
10789 Rect::new(116.0, 216.0, 16.0, 16.0)
10790 ))
10791 );
10792 assert_eq!(
10793 clamp_image_source(Rect::new(60.0, 28.0, 16.0, 16.0), dest, px),
10794 Some((
10795 Rect::new(60.0, 28.0, 4.0, 4.0),
10796 Rect::new(100.0, 200.0, 8.0, 8.0)
10797 ))
10798 );
10799 assert_eq!(
10800 clamp_image_source(Rect::new(16.0, 8.0, 16.0, 16.0), dest, px),
10801 Some((Rect::new(16.0, 8.0, 16.0, 16.0), dest))
10802 );
10803 assert_eq!(
10804 clamp_image_source(Rect::new(64.0, 0.0, 8.0, 8.0), dest, px),
10805 None
10806 );
10807 assert_eq!(
10808 clamp_image_source(Rect::new(0.0, 0.0, 0.0, 8.0), dest, px),
10809 None
10810 );
10811 assert_eq!(
10812 clamp_image_source(Rect::new(0.0, 0.0, 8.0, 8.0), dest, Size::new(0.0, 0.0)),
10813 None
10814 );
10815 }
10816
10817 /// The wire codes are a frozen dense table: any gap, duplicate, or variant missing from
10818 /// `ALL` breaks a decoder somewhere, so it must break here first.
10819 #[test]
10820 fn op_codes_are_dense_and_round_trip() {
10821 for (i, code) in OpCode::ALL.into_iter().enumerate() {
10822 assert_eq!(code as i32, i as i32, "{code:?} broke wire density");
10823 assert_eq!(OpCode::from_wire(i as f64), Some(code));
10824 }
10825 assert_eq!(OpCode::from_wire(OpCode::ALL.len() as f64), None);
10826 assert_eq!(OpCode::from_wire(-1.0), None);
10827 assert_eq!(OpCode::from_wire(0.5), None);
10828 }
10829
10830 /// Reference decode of a display list covering every op arm: the record stream must be
10831 /// whole 9-slot records of known codes, and the texts channel must carry exactly one
10832 /// entry per text-carrying record, in order: the contract every shim decoder assumes.
10833 #[test]
10834 #[expect(
10835 clippy::float_cmp,
10836 reason = "wire slots hold integer codes and exact test constants"
10837 )]
10838 fn encode_ops_emits_whole_records_and_matched_text_payloads() {
10839 let r = Rect::new(1.0, 2.0, 3.0, 4.0);
10840 let red = Color::rgb(1.0, 0.0, 0.0);
10841 let ops = vec![
10842 DrawOp::Fill(Shape::Rect(r), Paint::Solid(red)),
10843 DrawOp::Stroke(Shape::Rect(r), Paint::Solid(red), StrokeStyle::round(2.0)),
10844 DrawOp::Fill(Shape::RoundedRect(r, 5.0), Paint::Solid(red)),
10845 DrawOp::Fill(Shape::Ellipse(r), Paint::Solid(red)),
10846 // The documented asymmetry: a filled arc encodes as StrokeArc with width 0.
10847 DrawOp::Fill(
10848 Shape::Arc {
10849 rect: r,
10850 start_deg: 0.0,
10851 sweep_deg: 90.0,
10852 },
10853 Paint::Solid(red),
10854 ),
10855 DrawOp::Stroke(
10856 Shape::Line(Point::new(0.0, 0.0), Point::new(9.0, 9.0)),
10857 Paint::Solid(red),
10858 StrokeStyle::width(1.0),
10859 ),
10860 DrawOp::Fill(
10861 Shape::Polygon(vec![
10862 Point::new(0.0, 0.0),
10863 Point::new(4.0, 0.0),
10864 Point::new(2.0, 3.0),
10865 ]),
10866 Paint::Solid(red),
10867 ),
10868 DrawOp::Fill(
10869 Shape::Path(Path {
10870 segs: vec![
10871 PathSeg::Move(Point::new(0.0, 0.0)),
10872 PathSeg::Line(Point::new(5.0, 5.0)),
10873 PathSeg::Close,
10874 ],
10875 rule: FillRule::EvenOdd,
10876 }),
10877 Paint::Linear(LinearGradient::new(
10878 UnitPoint::new(0.0, 0.0),
10879 UnitPoint::new(1.0, 1.0),
10880 vec![(0.0, red), (1.0, Color::WHITE)],
10881 )),
10882 ),
10883 DrawOp::Clip(Shape::Rect(r)),
10884 DrawOp::Clip(Shape::Polygon(vec![
10885 Point::new(0.0, 0.0),
10886 Point::new(1.0, 0.0),
10887 Point::new(0.0, 1.0),
10888 ])),
10889 DrawOp::Text {
10890 text: "hi".into(),
10891 at: Point::new(7.0, 8.0),
10892 size: 12.0,
10893 color: red,
10894 anchor: TextAnchor::LEADING,
10895 font: CanvasFont::default(),
10896 },
10897 DrawOp::Text {
10898 text: "bold".into(),
10899 at: Point::new(7.0, 8.0),
10900 size: 12.0,
10901 color: red,
10902 anchor: TextAnchor::CENTERED,
10903 font: CanvasFont {
10904 family: Some("Day Sans".into()),
10905 weight: Some(FontWeight::Bold),
10906 italic: true,
10907 },
10908 },
10909 DrawOp::Save,
10910 DrawOp::Concat(Affine::IDENTITY),
10911 DrawOp::Restore,
10912 DrawOp::Image {
10913 image: BitmapId(7),
10914 rect: r,
10915 opacity: 0.5,
10916 source: None,
10917 },
10918 DrawOp::Image {
10919 image: BitmapId(7),
10920 rect: r,
10921 opacity: 1.0,
10922 source: Some(Rect::new(16.0, 32.0, 8.0, 8.0)),
10923 },
10924 ];
10925 let (nums, texts) = encode_ops(&ops);
10926 assert_eq!(nums.len() % 9, 0, "partial record on the wire");
10927
10928 let mut expected_texts = 0usize;
10929 let mut decoded = Vec::new();
10930 for rec in nums.chunks(9) {
10931 let code = OpCode::from_wire(rec[0])
10932 .unwrap_or_else(|| panic!("unknown op code {} on the wire", rec[0]));
10933 decoded.push(code);
10934 expected_texts += match code {
10935 OpCode::Text
10936 | OpCode::FillPolygon
10937 | OpCode::StrokePolygon
10938 | OpCode::SetGradient
10939 | OpCode::FillPath
10940 | OpCode::StrokePath
10941 | OpCode::StrokeStyle
10942 | OpCode::SetFont => 1,
10943 // Clip carries a payload only for its path (3) / polygon (4) sub-kinds.
10944 OpCode::Clip => usize::from(rec[6] == 3.0 || rec[6] == 4.0),
10945 _ => 0,
10946 };
10947 }
10948 assert_eq!(
10949 texts.len(),
10950 expected_texts,
10951 "texts channel out of step with the records that consume it"
10952 );
10953 // No payload may carry the transport separator.
10954 assert!(texts.iter().all(|t| !t.contains('\u{1f}')));
10955
10956 let expected = {
10957 use OpCode::*;
10958 vec![
10959 FillRect,
10960 StrokeStyle, // ::round(2.0) is not plain, so the style modifier precedes
10961 StrokeRect,
10962 FillRrect,
10963 FillEllipse,
10964 StrokeArc, // the filled arc's stroke encoding…
10965 Line,
10966 FillPolygon,
10967 SetGradient, // gradient precedes its shape record
10968 FillPath,
10969 Clip,
10970 Clip,
10971 Text,
10972 SetFont, // a non-default font precedes its text record…
10973 Text,
10974 Save,
10975 Concat,
10976 Restore,
10977 Image,
10978 ImageSource, // a region precedes its image record; a whole-image draw has none
10979 Image,
10980 ]
10981 };
10982 assert_eq!(decoded, expected);
10983 // The bitmap id rides the numeric channel intact (an f64 holds a u64 id exactly well
10984 // past any id this process will mint), and nothing of an image reaches the texts channel.
10985 let img = nums
10986 .chunks(9)
10987 .find(|r| r[0] == f64::from(OpCode::Image as i32))
10988 .expect("Image record");
10989 assert_eq!(&img[1..7], &[1.0, 2.0, 3.0, 4.0, 7.0, 0.5]);
10990 // The region rides its own prefix record, in bitmap pixels, with nothing else in it.
10991 let src = nums
10992 .chunks(9)
10993 .find(|r| r[0] == f64::from(OpCode::ImageSource as i32))
10994 .expect("ImageSource record");
10995 assert_eq!(&src[1..8], &[16.0, 32.0, 8.0, 8.0, 0.0, 0.0, 0.0]);
10996 // …carrying the CSS weight and the slant, with the family on the texts channel.
10997 let font_rec = nums
10998 .chunks(9)
10999 .find(|r| r[0] == f64::from(OpCode::SetFont as i32))
11000 .expect("SetFont record");
11001 assert_eq!(&font_rec[1..3], &[700.0, 1.0]);
11002 assert_eq!(texts.iter().filter(|t| *t == "Day Sans").count(), 1);
11003 // …with width 0, per the documented asymmetry.
11004 let arc = nums
11005 .chunks(9)
11006 .find(|r| r[0] == f64::from(OpCode::StrokeArc as i32));
11007 assert_eq!(arc.map(|r| r[7]), Some(0.0));
11008 // A gradient-filled shape's color slot is opaque white, never clear (Skia decoders
11009 // modulate the shader by it).
11010 let path_rec = nums
11011 .chunks(9)
11012 .find(|r| r[0] == f64::from(OpCode::FillPath as i32));
11013 assert_eq!(
11014 path_rec.map(|r| r[8] as u32),
11015 Some(0xFFFF_FFFF),
11016 "gradient shape record must carry opaque white"
11017 );
11018 }
11019
11020 #[test]
11021 #[expect(
11022 clippy::float_cmp,
11023 reason = "wire slots hold integer codes and exact test constants"
11024 )]
11025 fn variable_length_geometry_carries_a_content_key() {
11026 let path = |x: f64| {
11027 Shape::Path(Path {
11028 segs: vec![
11029 PathSeg::Move(Point::new(x, 0.0)),
11030 PathSeg::Cubic(
11031 Point::new(1.0, 1.0),
11032 Point::new(2.0, 2.0),
11033 Point::new(3.0, 3.0),
11034 ),
11035 PathSeg::Close,
11036 ],
11037 rule: FillRule::NonZero,
11038 })
11039 };
11040 let poly = Shape::Polygon(vec![
11041 Point::new(0.0, 0.0),
11042 Point::new(1.0, 0.0),
11043 Point::new(0.0, 1.0),
11044 ]);
11045
11046 // Equal geometry keys equal though the two were built separately. The key exists for
11047 // this: a draw closure rebuilds its paths from scratch on every frame.
11048 assert_eq!(geometry_key(&path(0.0)), geometry_key(&path(0.0)));
11049 assert_ne!(geometry_key(&path(0.0)), geometry_key(&path(1.0)));
11050 // The fill rule decides what the path draws, so it belongs to the key.
11051 let even_odd = Shape::Path(Path {
11052 segs: match path(0.0) {
11053 Shape::Path(p) => p.segs,
11054 _ => unreachable!(),
11055 },
11056 rule: FillRule::EvenOdd,
11057 });
11058 assert_ne!(geometry_key(&path(0.0)), geometry_key(&even_odd));
11059 // A polygon and a path decode to different geometry and never share an entry.
11060 assert_ne!(geometry_key(&poly), geometry_key(&path(0.0)));
11061 // Fixed-size shapes keep 0: their geometry rides the record's own slots.
11062 assert_eq!(
11063 geometry_key(&Shape::Rect(Rect::new(0.0, 0.0, 1.0, 1.0))),
11064 0.0
11065 );
11066 // And a key survives an f64 wire slot exactly, which is what the 53-bit mask buys.
11067 let k = geometry_key(&path(0.0));
11068 assert!(
11069 k > 0.0 && k < (1u64 << 53) as f64 && k.fract() == 0.0,
11070 "{k}"
11071 );
11072
11073 // It reaches the wire in slot a, for exactly the ops whose payload rides the texts
11074 // channel, and never displaces geometry that is already there.
11075 let (nums, _) = encode_ops(&[
11076 DrawOp::Fill(path(0.0), Paint::Solid(Color::WHITE)),
11077 DrawOp::Fill(poly.clone(), Paint::Solid(Color::WHITE)),
11078 DrawOp::Clip(path(0.0)),
11079 DrawOp::Clip(Shape::Rect(Rect::new(1.0, 2.0, 3.0, 4.0))),
11080 ]);
11081 let slot_a = |code: OpCode| {
11082 nums.chunks(9)
11083 .find(|r| r[0] == f64::from(code as i32))
11084 .unwrap_or_else(|| panic!("no {code:?} record"))[1]
11085 };
11086 assert_eq!(slot_a(OpCode::FillPath), geometry_key(&path(0.0)));
11087 assert_eq!(slot_a(OpCode::FillPolygon), geometry_key(&poly));
11088 let clips: Vec<&[f64]> = nums
11089 .chunks(9)
11090 .filter(|r| r[0] == f64::from(OpCode::Clip as i32))
11091 .collect();
11092 assert_eq!(clips[0][1], geometry_key(&path(0.0)), "path clip keys");
11093 assert_eq!(
11094 &clips[1][1..5],
11095 &[1.0, 2.0, 3.0, 4.0],
11096 "a rect clip still puts its geometry in a..d"
11097 );
11098 }
11099}
11100
11101#[cfg(test)]
11102mod markup_tests {
11103 use super::*;
11104
11105 fn bold(range: std::ops::Range<usize>) -> TextRun {
11106 TextRun::font(
11107 range,
11108 FontSpec {
11109 style: Font::Body,
11110 weight: Some(FontWeight::Bold),
11111 ..Default::default()
11112 },
11113 )
11114 }
11115
11116 #[test]
11117 fn plain_text_is_escaped_in_both_dialects() {
11118 // The case a translated string will find: markup metacharacters in the content.
11119 let text = "5 < 6 & \"quoted\" <b>not bold</b>";
11120 for d in [MarkupDialect::Pango, MarkupDialect::QtHtml] {
11121 let m = runs_to_markup(text, &[], d, 16.0);
11122 assert!(!m.contains("<b>"), "content tag survived into markup: {m}");
11123 assert!(m.contains("<b>"), "{m}");
11124 assert!(m.contains("&"), "{m}");
11125 assert!(m.contains("5 < 6"), "{m}");
11126 }
11127 }
11128
11129 #[test]
11130 fn a_styled_run_is_wrapped_and_its_text_escaped() {
11131 let text = "a <b> c";
11132 let m = runs_to_markup(text, &[bold(2..5)], MarkupDialect::Pango, 16.0);
11133 assert_eq!(m, "a <b><b></b> c");
11134 }
11135
11136 #[test]
11137 fn color_and_monospace_differ_per_dialect() {
11138 let text = "code";
11139 let run = TextRun {
11140 range: 0..4,
11141 font: FontSpec {
11142 style: Font::Body,
11143 monospace: true,
11144 ..Default::default()
11145 },
11146 color: Some(Color::rgb(1.0, 0.0, 0.0)),
11147 ..TextRun::default()
11148 };
11149 let pango = runs_to_markup(text, std::slice::from_ref(&run), MarkupDialect::Pango, 16.0);
11150 assert!(pango.contains("foreground=\"#ff0000\""), "{pango}");
11151 assert!(pango.contains("font_family=\"monospace\""), "{pango}");
11152 let qt = runs_to_markup(
11153 text,
11154 std::slice::from_ref(&run),
11155 MarkupDialect::QtHtml,
11156 16.0,
11157 );
11158 assert!(qt.contains("color:#ff0000"), "{qt}");
11159 // Qt takes its fixed face from <code>: a `font-family:monospace` style attribute
11160 // renders proportional (observed on Qt 6.11).
11161 assert!(qt.contains("<code>") && qt.contains("</code>"), "{qt}");
11162 }
11163
11164 #[test]
11165 fn the_new_attributes_reach_both_dialects() {
11166 let run = TextRun {
11167 range: 0..2,
11168 font: FontSpec::default().scaled(1.5),
11169 background: Some(Color::rgb(0.0, 1.0, 0.0)),
11170 underline: Underline::Single,
11171 ..TextRun::default()
11172 };
11173 let pango = runs_to_markup("hi", std::slice::from_ref(&run), MarkupDialect::Pango, 16.0);
11174 assert!(pango.contains("background=\"#00ff00\""), "{pango}");
11175 // Pango takes an absolute size in 1/1024 pt (16 pt base × 1.5 = 24 pt), because the
11176 // relative attributes are Pango 1.50's and an unknown attribute empties the whole label.
11177 assert!(pango.contains("size=\"24576\""), "{pango}");
11178 assert!(pango.contains("<u>hi</u>"), "{pango}");
11179 let qt = runs_to_markup(
11180 "hi",
11181 std::slice::from_ref(&run),
11182 MarkupDialect::QtHtml,
11183 16.0,
11184 );
11185 assert!(qt.contains("background-color:#00ff00"), "{qt}");
11186 // Qt takes points: 16 pt base × 1.5 (observed; its CSS subset ignores a percentage).
11187 assert!(qt.contains("font-size:24pt"), "{qt}");
11188 assert!(qt.contains("<u>hi</u>"), "{qt}");
11189 }
11190
11191 #[test]
11192 fn a_link_target_is_escaped_too() {
11193 // A URL carrying `&` between query parameters is ordinary, and unescaped it truncates
11194 // the attribute and swallows the rest of the label.
11195 let text = "docs";
11196 let run = TextRun {
11197 range: 0..4,
11198 link: Some("https://x.dev/?a=1&b=2".into()),
11199 ..TextRun::default()
11200 };
11201 let m = runs_to_markup(text, &[run], MarkupDialect::Pango, 16.0);
11202 assert!(m.contains("a=1&b=2"), "{m}");
11203 }
11204
11205 #[test]
11206 fn tags_nest_and_close_in_reverse() {
11207 let run = TextRun {
11208 range: 0..2,
11209 font: FontSpec {
11210 style: Font::Body,
11211 weight: Some(FontWeight::Bold),
11212 italic: true,
11213 ..Default::default()
11214 },
11215 strikethrough: true,
11216 link: Some("u".into()),
11217 ..TextRun::default()
11218 };
11219 let m = runs_to_markup("hi", &[run], MarkupDialect::Pango, 16.0);
11220 assert_eq!(m, "<a href=\"u\"><b><i><s>hi</s></i></b></a>");
11221 }
11222
11223 #[test]
11224 fn runs_out_of_bounds_are_skipped_not_panicked() {
11225 // `runs_are_valid` rejects these upstream; this is the belt-and-braces path.
11226 let m = runs_to_markup("hi", &[bold(0..99)], MarkupDialect::Pango, 16.0);
11227 assert_eq!(m, "hi");
11228 }
11229
11230 #[test]
11231 fn validation_catches_the_four_ways_runs_go_wrong() {
11232 let text = "héllo";
11233 assert!(runs_are_valid(text, &[bold(0..1)]).is_ok());
11234 // Overlapping.
11235 assert!(runs_are_valid(text, &[bold(0..3), bold(2..4)]).is_err());
11236 // Past the end.
11237 assert!(runs_are_valid(text, &[bold(0..99)]).is_err());
11238 // Inverted. Built from parts, since a literal `3..1` is a clippy error in its own right.
11239 let (hi, lo) = (3, 1);
11240 assert!(runs_are_valid(text, &[bold(hi..lo)]).is_err());
11241 // Splitting the 2-byte `é`.
11242 assert!(runs_are_valid(text, &[bold(0..2)]).is_err());
11243 }
11244}
11245
11246#[cfg(test)]
11247mod route_of_url_tests {
11248 use super::route_of_url;
11249
11250 #[test]
11251 fn strips_the_scheme_and_keeps_route_and_params() {
11252 assert_eq!(
11253 route_of_url("notes://mail/inbox?hint=x"),
11254 "mail/inbox?hint=x"
11255 );
11256 assert_eq!(route_of_url("notes://home"), "home");
11257 // No scheme: already a route, unchanged.
11258 assert_eq!(route_of_url("mail/inbox"), "mail/inbox");
11259 assert_eq!(route_of_url(""), "");
11260 // Percent-encoding passes through; the route parser decodes, not this mapping.
11261 assert_eq!(route_of_url("n://a/b%2Fc?q=1%202"), "a/b%2Fc?q=1%202");
11262 }
11263}
11264
11265#[cfg(test)]
11266mod builtin_kind_tests {
11267 use super::*;
11268
11269 /// Every built-in round-trips through its wire key, and the keys are unique. Guards the
11270 /// `builtin_kinds!` expansion: a copy-paste slip in the table would alias two kinds.
11271 #[test]
11272 fn keys_round_trip_and_are_unique() {
11273 let mut seen = std::collections::HashSet::new();
11274 for &b in Builtin::ALL {
11275 assert_eq!(Builtin::from_key(b.key()), Some(b), "{b:?} key round-trip");
11276 assert!(seen.insert(b.key()), "duplicate key {:?}", b.key());
11277 assert!(
11278 b.key().starts_with("day."),
11279 "built-in {b:?} must use the reserved `day.` prefix"
11280 );
11281 }
11282 }
11283
11284 /// The `kinds::*` constants are the enum's keys, so the two spellings cannot drift.
11285 #[test]
11286 fn kinds_constants_match_the_enum() {
11287 assert_eq!(kinds::LABEL, Builtin::Label.key());
11288 assert_eq!(kinds::LIST_CELL, Builtin::ListCell.key());
11289 assert_eq!(kinds::COVER, Builtin::Cover.key());
11290 assert_eq!(kinds::INSPECTOR, Builtin::Inspector.key());
11291 assert_eq!(kinds::TREE, Builtin::Tree.key());
11292 // 19 after `Tabs`/`TabsPage` retired (the tab bar is a NAV presentation, not a kind),
11293 // +2 for the inspector split and its panes (docs/inspector.md), +1 for the tree
11294 // (docs/tree.md).
11295 assert_eq!(Builtin::ALL.len(), 25);
11296 }
11297
11298 /// An extension piece's kind is not a built-in.
11299 #[test]
11300 fn extension_kinds_are_not_builtin() {
11301 assert_eq!(Builtin::from_key("acme.combobox"), None);
11302 assert_eq!(Builtin::from_key("day.not_a_real_kind"), None);
11303 }
11304}
11305
11306#[cfg(test)]
11307mod locale_tests {
11308 /// POSIX locale strings are not BCP-47 tags, and "C" is not a language; that difference is
11309 /// the job of `posix_locale_hints` (§12.2).
11310 #[test]
11311 fn posix_hints_parse_and_drop_the_c_locale() {
11312 // The parsing is exercised through the same normalization the function applies.
11313 let normalize = |v: &str| v.split('.').next().unwrap_or(v).replace('_', "-");
11314 assert_eq!(normalize("fr_FR.UTF-8"), "fr-FR");
11315 assert_eq!(normalize("en_US"), "en-US");
11316 assert_eq!(normalize("C"), "C");
11317 // A real read never panics whatever this host's environment holds.
11318 let hints = super::posix_locale_hints();
11319 assert!(
11320 hints
11321 .iter()
11322 .all(|h| !h.is_empty() && h != "C" && h != "POSIX")
11323 );
11324 }
11325}
11326
11327#[cfg(test)]
11328mod sidetable_tests {
11329 use super::sidetable::{SideTable, sweep};
11330 use std::cell::Cell;
11331 use std::rc::Rc;
11332
11333 /// The registry exists so that one `sweep(key)` clears every table without any
11334 /// table needing its own line in a backend's `release()`.
11335 #[test]
11336 fn sweep_clears_every_registered_table_and_runs_teardowns() {
11337 let torn = Rc::new(Cell::new(0u32));
11338 let t2 = torn.clone();
11339 let plain: SideTable<&'static str> = SideTable::new();
11340 let hooked: SideTable<u32> = SideTable::with_teardown(move |_| t2.set(t2.get() + 1));
11341
11342 plain.insert(7, "a");
11343 hooked.insert(7, 1);
11344 hooked.insert(8, 2);
11345 sweep(7);
11346 assert!(!plain.contains(7));
11347 assert!(!hooked.contains(7), "swept from every table");
11348 assert!(hooked.contains(8), "other keys untouched");
11349 assert_eq!(torn.get(), 1, "teardown ran for the swept value");
11350
11351 // remove() runs the teardown too; take() bypasses it for ownership transfer.
11352 let _ = hooked.remove(8);
11353 assert_eq!(torn.get(), 2);
11354 hooked.insert(9, 3);
11355 assert_eq!(hooked.take(9), Some(3));
11356 assert_eq!(torn.get(), 2, "take() skips the hook");
11357 }
11358
11359 #[test]
11360 fn contain_returns_default_on_panic() {
11361 let ok = super::ffi_guard::contain(0i32, || 5);
11362 assert_eq!(ok, 5);
11363 let prev = std::panic::take_hook();
11364 std::panic::set_hook(Box::new(|_| {}));
11365 let contained = super::ffi_guard::contain(-1i32, || panic!("boom"));
11366 std::panic::set_hook(prev);
11367 assert_eq!(contained, -1, "the panic must not escape the guard");
11368 }
11369}
11370
11371#[cfg(test)]
11372mod cursor_tests {
11373 use super::Cursor;
11374
11375 /// Every named cursor has a distinct CSS keyword, and `NAMED` lists each exactly once: the
11376 /// gallery and every backend's table key on the keyword.
11377 #[test]
11378 fn named_cursors_have_distinct_css_names() {
11379 let mut seen = std::collections::BTreeSet::new();
11380 for c in &Cursor::NAMED {
11381 assert!(
11382 seen.insert(c.css_name().to_string()),
11383 "duplicate: {}",
11384 c.css_name()
11385 );
11386 assert!(!matches!(c, Cursor::Native(_)));
11387 }
11388 assert_eq!(seen.len(), Cursor::NAMED.len());
11389 assert_eq!(Cursor::native("dragCopy").css_name(), "dragCopy");
11390 assert_eq!(Cursor::default(), Cursor::Default);
11391 }
11392}
11393
11394#[cfg(test)]
11395mod text_anchor_tests {
11396 /// The anchor arithmetic every backend repeats. A drawing whose text lands in the wrong
11397 /// corner is a per-backend bug that only a screenshot catches, so the shared definition is
11398 /// pinned here and each shim is written to match it.
11399 #[test]
11400 fn text_anchor_offsets_place_the_line_box() {
11401 use crate::props::TextAlign;
11402 use crate::{TextAnchor, TextVAlign};
11403 // A 40-wide, 20-tall line box whose baseline sits 16 below its top.
11404 let (w, h, asc) = (40.0, 20.0, 16.0);
11405 let at = |ha, va| TextAnchor { h: ha, v: va }.offset(w, h, asc);
11406
11407 // The default is the drawing origin itself, every backend's native "draw here".
11408 assert_eq!(at(TextAlign::Leading, TextVAlign::Top), (0.0, 0.0));
11409 assert_eq!(TextAnchor::default(), TextAnchor::LEADING);
11410 // Horizontal: the box's leading edge, its middle, its trailing edge.
11411 assert_eq!(at(TextAlign::Center, TextVAlign::Top).0, -20.0);
11412 assert_eq!(at(TextAlign::Trailing, TextVAlign::Top).0, -40.0);
11413 // Vertical: top, middle, the baseline itself, bottom.
11414 assert_eq!(at(TextAlign::Leading, TextVAlign::Middle).1, -10.0);
11415 assert_eq!(at(TextAlign::Leading, TextVAlign::Baseline).1, -16.0);
11416 assert_eq!(at(TextAlign::Leading, TextVAlign::Bottom).1, -20.0);
11417 // The two named placements are the ones the two-variant enum used to have.
11418 assert_eq!(TextAnchor::CENTERED.offset(w, h, asc), (-20.0, -10.0));
11419 assert_eq!(TextAnchor::TRAILING.offset(w, h, asc), (-40.0, 0.0));
11420 }
11421
11422 /// The wire code the serializing backends (qt, xaml, arkui, android, web) decode by hand.
11423 #[test]
11424 fn text_anchor_packs_into_one_slot_and_round_trips() {
11425 use crate::props::TextAlign;
11426 use crate::{TextAnchor, TextVAlign};
11427 let mut seen = std::collections::BTreeSet::new();
11428 for h in [TextAlign::Leading, TextAlign::Center, TextAlign::Trailing] {
11429 for v in [
11430 TextVAlign::Top,
11431 TextVAlign::Middle,
11432 TextVAlign::Baseline,
11433 TextVAlign::Bottom,
11434 ] {
11435 let a = TextAnchor { h, v };
11436 let code = a.pack();
11437 assert!(
11438 (0.0..=11.0).contains(&code),
11439 "{code} outside the packed range"
11440 );
11441 assert!(seen.insert(code as u64), "two anchors share code {code}");
11442 assert_eq!(TextAnchor::unpack(code), a);
11443 }
11444 }
11445 assert_eq!(seen.len(), 12);
11446 // The shims decode as `h = code / 4`, `v = code % 4` in integer arithmetic.
11447 assert_eq!(TextAnchor::LEADING.pack(), 0.0);
11448 assert_eq!(TextAnchor::CENTERED.pack(), 5.0);
11449 // Junk answers the default rather than failing inside a native draw callback.
11450 assert_eq!(TextAnchor::unpack(-3.0), TextAnchor::LEADING);
11451 assert_eq!(TextAnchor::unpack(99.0), TextAnchor::unpack(11.0));
11452 }
11453
11454 /// The two shapes a backend's own metrics arrive in. Both land on the same contract: the line
11455 /// box's top-leading corner is the origin, and `ink` is relative to it.
11456 #[test]
11457 fn metrics_convert_from_a_backends_own_shape() {
11458 use crate::{Rect, TextMetrics};
11459 // Baseline-relative, y up-negative; Core Text, Skia and Qt all report like this.
11460 let m = TextMetrics::from_baseline(
11461 40.0,
11462 16.0,
11463 4.0,
11464 11.0,
11465 // Ink starting 1 right of the origin, from 11 above the baseline to 2 below it.
11466 Rect::new(1.0, -11.0, 38.0, 13.0),
11467 );
11468 assert_eq!(
11469 (m.width, m.height, m.ascent, m.cap_height),
11470 (40.0, 20.0, 16.0, 11.0)
11471 );
11472 // Shifted down by the ascent: the ink now starts 5 below the line box's top, which is
11473 // where a cap begins in a slot whose baseline is at 16.
11474 assert_eq!(m.ink, Rect::new(1.0, 5.0, 38.0, 13.0));
11475 assert_eq!(m.ascent - m.cap_height, m.ink.origin.y);
11476
11477 // The eight-slot wire form is already line-box-relative and passes straight through.
11478 let w = TextMetrics::from_slots(&[40.0, 20.0, 16.0, 11.0, 1.0, 5.0, 38.0, 13.0]);
11479 assert_eq!(w, m);
11480 }
11481
11482 /// The fallback must be usable, not merely present: a caller frames text with it on a toolkit
11483 /// that cannot measure, and every relation it relies on has to hold.
11484 #[test]
11485 fn the_approximation_is_internally_consistent() {
11486 use crate::TextMetrics;
11487 let m = TextMetrics::approximate("Agy", 20.0);
11488 assert!(m.ascent < m.height, "the baseline sits inside the line box");
11489 assert!(
11490 m.cap_height < m.ascent,
11491 "caps do not reach above the ascent"
11492 );
11493 // The ink box is the whole line box: a superset, so an overlap test using it can only be
11494 // too cautious. Never a claim to be tighter than it knows.
11495 assert_eq!(m.ink.origin.x, 0.0);
11496 assert_eq!(m.ink.origin.y, 0.0);
11497 assert_eq!(m.ink.size.width, m.width);
11498 assert_eq!(m.ink.size.height, m.height);
11499 // Empty text still answers a usable (zero-width, full-height) slot.
11500 let e = TextMetrics::approximate("", 20.0);
11501 assert_eq!(e.width, 0.0);
11502 assert!(e.height > 0.0);
11503 }
11504}
11505
11506#[cfg(test)]
11507mod cap_list_tests {
11508 use super::Cap;
11509
11510 #[test]
11511 fn every_capability_is_listed_once_in_its_place() {
11512 for (i, cap) in Cap::ALL.iter().enumerate() {
11513 assert_eq!(cap.ordinal(), i, "{cap:?} is out of place in Cap::ALL");
11514 }
11515 }
11516}
11517
11518#[cfg(test)]
11519mod button_menu_tests {
11520 use super::*;
11521 use std::cell::Cell;
11522 use std::rc::Rc;
11523
11524 fn action(label: &str) -> MenuItem {
11525 MenuItem::Action {
11526 id: None,
11527 action: 1,
11528 label: label.into(),
11529 shortcut: None,
11530 enabled: true,
11531 checked: None,
11532 role: None,
11533 icon: None,
11534 }
11535 }
11536
11537 #[test]
11538 fn a_provider_that_releases_its_button_shows_nothing() {
11539 let registered = Rc::new(Cell::new(true));
11540 let r = registered.clone();
11541 // The provider's app code removes the button (here: unregisters it), then still answers.
11542 let provider: ContextMenuFn = Rc::new(move |_| {
11543 r.set(false);
11544 vec![action("Open")]
11545 });
11546 assert!(resolve_button_menu(&provider, || registered.get()).is_none());
11547 }
11548
11549 #[test]
11550 fn a_live_button_shows_its_items_and_an_empty_menu_shows_nothing() {
11551 let provider: ContextMenuFn = Rc::new(|_| vec![action("Open")]);
11552 assert_eq!(
11553 resolve_button_menu(&provider, || true).map(|i| i.len()),
11554 Some(1)
11555 );
11556 let empty: ContextMenuFn = Rc::new(|_| Vec::new());
11557 let mut asked = false;
11558 assert!(
11559 resolve_button_menu(&empty, || {
11560 asked = true;
11561 true
11562 })
11563 .is_none()
11564 );
11565 assert!(!asked, "an empty menu needs no registry check");
11566 }
11567}