day_spec/lib.rs
1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3
4//! day-spec: the toolkit specification (DESIGN.md §8).
5//!
6//! Backends depend only on this crate (never on day-core). One backend is linked per binary;
7//! `day-core` is monomorphized over the concrete [`Toolkit`].
8
9use std::any::Any;
10use std::collections::HashMap;
11
12pub use day_geometry::*;
13
14pub mod controls;
15pub use controls::datetime::{DayDate, DayTime};
16
17pub mod applications;
18pub mod capture;
19/// Inline markdown → styled runs (docs/markdown.md). Lives here rather than in day-pieces
20/// because it produces `TextRun`s, and every format codec beside it reads the same model.
21pub mod markdown;
22/// Bundled-resource random-access API + the per-backend `ResourceOpener` hook (§18.3).
23pub mod resource;
24/// Styled text: the document model `label().runs(…)` renders and `day-piece-text-editor` edits,
25/// with the Markdown / HTML / RTF codecs over it (docs/texteditor.md).
26pub mod styled;
27/// Import and export for [`StyledText`]: Markdown, HTML and RTF (docs/texteditor.md).
28pub mod styled_codec;
29pub mod transfer;
30
31pub use resource::{
32 AssetDir, AssetName, FontFamily, ImageName, Resource, ResourceOpener, VectorName,
33 resolve_asset_dir, resolve_image_file, resource, set_resource_opener,
34};
35pub use styled::{
36 ListStyle, ParagraphAlign, ParagraphRun, ParagraphStyle, RunStyle, StyledText, Underline,
37 coalesce_runs, paragraph_bounds, paragraphs_are_valid,
38};
39pub use styled_codec::{
40 DocStyle, html_to_styled, markdown_to_styled, rtf_to_styled, styled_to_html,
41 styled_to_markdown, styled_to_rtf,
42};
43
44/// Bundled custom fonts: name-table parsing, runtime font directory, family → file resolution
45/// (§18.4). Shared by the CLI stagers and the backends' startup registration. Lives in the leaf
46/// `day-fonts` crate (pure std, no `day-geometry`), re-exported here so `day_spec::fonts::…` is
47/// unchanged for the backends while the CLI can depend on `day-fonts` alone.
48pub use day_fonts as fonts;
49
50/// The route inside a deep-link URL (docs/deep-links.md): everything after `scheme://`,
51/// query included (`notes://mail/inbox?hint=x` ⇒ `mail/inbox?hint=x`). A string with no
52/// scheme passes through unchanged (it is already a route). One definition, shared by every
53/// platform's intake and the dayscript `deep_link` step, so a URL maps to the same route
54/// bytes everywhere; percent-decoding stays with the route parser (docs/navigation.md).
55pub fn route_of_url(url: &str) -> String {
56 match url.split_once("://") {
57 Some((_, rest)) => rest.to_string(),
58 None => url.to_string(),
59 }
60}
61
62// ---------------------------------------------------------------------------
63// Identity
64// ---------------------------------------------------------------------------
65
66/// Interned piece-kind key, e.g. `"day.label"` or `"acme.combobox"`.
67pub type PieceKind = &'static str;
68
69/// Declare the built-in piece vocabulary once: the [`Builtin`] enum, its string keys, and the
70/// `kinds::*` constants are all generated from this list, so they can never drift apart.
71///
72/// Adding a variant here is a breaking change for backends: every `Toolkit` must decide how
73/// to realize the new kind, and the exhaustive `match Builtin` in each backend's `realize`
74/// turns that decision into a compile error rather than a runtime placeholder.
75macro_rules! builtin_kinds {
76 ($( $(#[$meta:meta])* $variant:ident = $konst:ident => $key:literal ),+ $(,)?) => {
77 /// Every piece kind Day itself defines (§5.3). Backends match on this exhaustively in
78 /// `realize`; anything outside it is an extension piece resolved through the
79 /// [`Registry`] by its string [`PieceKind`].
80 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
81 pub enum Builtin {
82 $( $(#[$meta])* $variant, )+
83 }
84
85 impl Builtin {
86 /// This kind's wire key: the same string as the matching `kinds::*` constant.
87 pub const fn key(self) -> PieceKind {
88 match self { $( Builtin::$variant => $key, )+ }
89 }
90
91 /// The built-in this key names, or `None` for an extension piece's kind.
92 pub fn from_key(kind: PieceKind) -> Option<Builtin> {
93 match kind {
94 $( $key => Some(Builtin::$variant), )+
95 _ => None,
96 }
97 }
98
99 /// Every built-in, in declaration order (conformance tests iterate it).
100 pub const ALL: &'static [Builtin] = &[ $( Builtin::$variant, )+ ];
101 }
102
103 /// The built-in piece keys as plain strings, for the registry and the `PieceKind` API.
104 pub mod kinds {
105 $( $(#[$meta])* pub const $konst: super::PieceKind = super::Builtin::$variant.key(); )+
106 }
107 };
108}
109
110builtin_kinds! {
111 /// A dumb native panel (the column/row/stack backing).
112 Container = CONTAINER => "day.container",
113 Label = LABEL => "day.label",
114 Button = BUTTON => "day.button",
115 Toggle = TOGGLE => "day.toggle",
116 Slider = SLIDER => "day.slider",
117 TextField = TEXT_FIELD => "day.text_field",
118 /// A native multi-line text editor (docs/textarea.md). Built-in since 2026-07 (previously
119 /// the satellite `day-piece-textarea`).
120 TextArea = TEXT_AREA => "day.text_area",
121 /// A native option picker with menu/segmented/inline stylings (docs/picker.md). Built-in
122 /// since 2026-07 (previously the satellite `day-piece-picker`).
123 Picker = PICKER => "day.picker",
124 Divider = DIVIDER => "day.divider",
125 Scroll = SCROLL => "day.scroll",
126 Image = IMAGE => "day.image",
127 /// Progress indicator: determinate bar (fraction) or indeterminate spinner.
128 Progress = PROGRESS => "day.progress",
129 Canvas = CANVAS => "day.canvas",
130 /// Navigation host (docs/navigation.md): stack on mobile, split panes on desktop.
131 Nav = NAV => "day.nav",
132 /// One destination's native container inside a NAV host.
133 NavPage = NAV_PAGE => "day.nav_page",
134 /// Native navigation item list (docs/navigation.md): NSOutlineView source list /
135 /// GtkListBox navigation-sidebar / QListWidget / UITableView rows with chevrons.
136 NavMenu = NAV_MENU => "day.nav_menu",
137 /// Native recycling list (docs/list.md): NSTableView / UITableView / RecyclerView /
138 /// GtkListView / QListView. Owns scrolling + cell reuse; Day binds row content on demand.
139 List = LIST => "day.list",
140 /// A recycled row's content anchor inside a `LIST`; Day adopts the native cell as its handle.
141 /// Adopted, never realized: `Toolkit::adopt` wraps the native cell, so backends' `realize`
142 /// never sees this kind.
143 ListCell = LIST_CELL => "day.list_cell",
144 /// Native hierarchical tree (docs/tree.md): NSOutlineView / sidebar collection list /
145 /// GtkListView+TreeListModel / WinUI TreeView / ArkTS TreeView. Rows nest, disclose, and
146 /// drag-to-reparent; Day binds row content on demand through `Toolkit::attach_tree`.
147 /// Row cells are adopted (the same `LIST_CELL` anchor path as `List`).
148 Tree = TREE => "day.tree",
149 /// A fullscreen cover (docs/cover.md): a modal surface presented over the whole window,
150 /// edge-to-edge, driven by `CoverPatch::{Present,Dismiss}`. The handle is the cover's
151 /// content container; its frame is native-owned while presented (the backend sizes it to
152 /// the safe area and reports it via `Event::FrameChanged`).
153 Cover = COVER => "day.cover",
154 /// Content beside a trailing inspector pane (docs/inspector.md): the native split whose
155 /// second pane is a show/hidable properties panel. Exactly two `INSPECTOR_PANE` children:
156 /// the content, then the panel (`InspectorPaneProps::panel`). Only realized where
157 /// `Cap::Inspector` answers `Native`; everywhere else the `inspector` piece composes the
158 /// pane from plain containers and this kind never reaches the backend.
159 Inspector = INSPECTOR => "day.inspector",
160 /// One pane's container inside an `INSPECTOR` host: the `NAV_PAGE` of the inspector split.
161 /// Its frame is native-owned (the splitter/dock sizes it), reported via
162 /// `Event::FrameChanged` on this node; Day lays the pane's content out inside it.
163 InspectorPane = INSPECTOR_PANE => "day.inspector_pane",
164 /// Two panes with a divider the user drags (docs/split.md): the toolkit's own splitter,
165 /// side by side or stacked (`SplitProps::axis`), the first pane's share bound to the app
166 /// (`SplitProps::fraction`, reported back as `Event::ValueChanged`). Exactly two
167 /// `SPLIT_PANE` children, first then second. Only realized where `Cap::Split` answers
168 /// `Native`; everywhere else the `split` piece composes the panes and draws the divider
169 /// itself, and this kind never reaches the backend.
170 Split = SPLIT => "day.split",
171 /// One pane's container inside a `SPLIT` host: native-owned frame (the splitter sizes it),
172 /// reported via `Event::FrameChanged` on this node, like an `INSPECTOR_PANE`.
173 SplitPane = SPLIT_PANE => "day.split_pane",
174 /// A list row's standard content (docs/list.md "List items"): a leading icon, a title, an
175 /// optional subtitle and trailing detail, and a check mark, drawn the way the platform
176 /// draws its own list rows: a `UIListContentView` with the cell's default content
177 /// configuration, a Material list item, an `NSTableCellView`'s image and text, a GTK row
178 /// box. Only realized where `Cap::ListItem` answers `Native`; everywhere else the
179 /// `list_item` piece composes the same content and this kind never reaches the backend.
180 ListItem = LIST_ITEM => "day.list_item",
181}
182
183/// Whether a kind is worth asking [`Toolkit::first_baseline`] about (docs/baseline.md).
184///
185/// A blocklist, not an allowlist: the structural and graphic kinds below have no text of their
186/// own, and everything else (including extension pieces like the date/time pickers, whose kinds
187/// day-spec has never heard of) is assumed to be worth asking. An extension piece that turns
188/// out to have no baseline answers `None`, which costs one query; an allowlist would instead
189/// silently leave every extension piece centered, which is the bug this shape avoids.
190pub fn kind_has_baseline(kind: PieceKind) -> bool {
191 !matches!(
192 Builtin::from_key(kind),
193 Some(
194 Builtin::Container
195 | Builtin::Scroll
196 | Builtin::Divider
197 | Builtin::Image
198 | Builtin::Canvas
199 | Builtin::Slider
200 | Builtin::Toggle
201 | Builtin::Progress
202 | Builtin::Nav
203 | Builtin::NavPage
204 | Builtin::NavMenu
205 | Builtin::Split
206 | Builtin::SplitPane
207 | Builtin::List
208 | Builtin::ListCell
209 | Builtin::Cover
210 | Builtin::Inspector
211 | Builtin::InspectorPane
212 )
213 )
214}
215
216/// Placeholder leaves: the one hole in Day's rendering that is invisible to a screenshot.
217///
218/// When a backend has no renderer for a kind it realizes a visible `⟨kind⟩` label rather than
219/// failing. That is the right runtime behavior, but it means a missing renderer looks like a
220/// rendered app: the walkthrough passes, and the gallery's validator (which counts distinct
221/// colors) sees nothing wrong. That is how a stale `skip_on:` survived in the showcase
222/// walkthrough after the renderer it skipped had landed.
223///
224/// So every backend reports here instead of keeping its own warn-once set. The table is process-
225/// wide and append-only, which gives dayscript's `assert_no_placeholders` something to assert on
226/// (`crates/day-script`): a placeholder becomes a test failure instead of a silent gap.
227pub mod placeholder {
228 use super::PieceKind;
229 use std::collections::BTreeSet;
230 use std::sync::{Mutex, OnceLock};
231
232 fn table() -> &'static Mutex<BTreeSet<PieceKind>> {
233 static TABLE: OnceLock<Mutex<BTreeSet<PieceKind>>> = OnceLock::new();
234 TABLE.get_or_init(|| Mutex::new(BTreeSet::new()))
235 }
236
237 /// Record that `toolkit` had no renderer for `kind` and warn, once per kind, however many
238 /// nodes of it are realized. Call from a backend's `realize` fallback arm.
239 pub fn report(kind: PieceKind, toolkit: &str) {
240 let Ok(mut seen) = table().lock() else { return };
241 if seen.insert(kind) {
242 log::warn!(
243 "no renderer for piece kind \"{kind}\" on {toolkit} — is the piece's \
244 {toolkit} feature enabled? (rendering a placeholder)"
245 );
246 }
247 }
248
249 /// Every kind that has rendered a placeholder in this process, sorted. Empty is the goal.
250 pub fn seen() -> Vec<PieceKind> {
251 table()
252 .lock()
253 .map(|s| s.iter().copied().collect())
254 .unwrap_or_default()
255 }
256}
257
258/// Downcast a realize/update payload to the props/patch type a backend arm expects,
259/// warning (once per kind, via [`placeholder::report`]) instead of panicking on a
260/// mismatch. A mismatch means a piece registered under a builtin key or a day-core
261/// regression; degrade to the placeholder path, never abort: most backend arms run
262/// inside native up-calls, where a panic is a process kill.
263pub fn props_of<'a, T: 'static>(
264 kind: PieceKind,
265 toolkit: &str,
266 any: &'a dyn std::any::Any,
267) -> Option<&'a T> {
268 let p = any.downcast_ref::<T>();
269 if p.is_none() {
270 placeholder::report(kind, toolkit);
271 }
272 p
273}
274
275/// Pointer-keyed per-view side tables with an automatic release sweep.
276///
277/// Backends keep auxiliary per-view state in thread-local maps keyed by the native
278/// handle's address. Historically each map needed its own line in `release()`, a
279/// checklist that drifted repeatedly (missed entries have produced both leaks and
280/// stale-pointer CI segfaults, since a freed address gets recycled). A [`crate::sidetable::SideTable`]
281/// registers itself with a per-thread sweeper list at construction, so a backend's
282/// `release()` calls [`crate::sidetable::sweep`] once and every table, present and future, drops its
283/// entry for that handle, running its teardown hook if one was given.
284pub mod sidetable {
285 use std::cell::RefCell;
286 use std::collections::HashMap;
287 use std::rc::Rc;
288
289 /// One table's "remove this key" hook, registered at construction.
290 type Sweeper = Rc<dyn Fn(usize)>;
291
292 thread_local! {
293 static SWEEPERS: RefCell<Vec<Sweeper>> = const { RefCell::new(Vec::new()) };
294 }
295
296 /// A pointer-keyed map swept automatically by [`crate::sidetable::sweep`]. Construct inside a
297 /// `thread_local!` initializer; the optional teardown hook runs for each removed
298 /// value (release a retained native object, dispose an owned child, …), both on sweep
299 /// and on plain [`SideTable::remove`], so teardown cannot be bypassed by accident.
300 pub struct SideTable<V: 'static> {
301 map: Rc<RefCell<HashMap<usize, V>>>,
302 teardown: Option<Rc<dyn Fn(V)>>,
303 }
304
305 impl<V> Default for SideTable<V> {
306 fn default() -> Self {
307 Self::new()
308 }
309 }
310
311 impl<V> SideTable<V> {
312 pub fn new() -> Self {
313 Self::build(None)
314 }
315
316 /// A table whose values need active teardown when their view goes away.
317 pub fn with_teardown(teardown: impl Fn(V) + 'static) -> Self {
318 Self::build(Some(Rc::new(teardown)))
319 }
320
321 fn build(teardown: Option<Rc<dyn Fn(V)>>) -> Self {
322 let map: Rc<RefCell<HashMap<usize, V>>> = Rc::default();
323 let (m, t) = (map.clone(), teardown.clone());
324 SWEEPERS.with(|s| {
325 s.borrow_mut().push(Rc::new(move |key| {
326 // Remove under the borrow, tear down outside it: hooks may re-enter
327 // toolkit code that reads other tables.
328 let v = m.borrow_mut().remove(&key);
329 if let (Some(v), Some(t)) = (v, &t) {
330 t(v);
331 }
332 }));
333 });
334 SideTable { map, teardown }
335 }
336
337 pub fn insert(&self, key: usize, value: V) -> Option<V> {
338 self.map.borrow_mut().insert(key, value)
339 }
340
341 /// Remove and tear down the entry (returns `None` always when a teardown hook
342 /// exists, because the value is consumed by it; use [`SideTable::take`] to skip it).
343 pub fn remove(&self, key: usize) -> Option<V> {
344 let v = self.map.borrow_mut().remove(&key)?;
345 match &self.teardown {
346 Some(t) => {
347 t(v);
348 None
349 }
350 None => Some(v),
351 }
352 }
353
354 /// Remove without running the teardown hook (the caller takes ownership).
355 pub fn take(&self, key: usize) -> Option<V> {
356 self.map.borrow_mut().remove(&key)
357 }
358
359 pub fn contains(&self, key: usize) -> bool {
360 self.map.borrow().contains_key(&key)
361 }
362
363 pub fn get(&self, key: usize) -> Option<V>
364 where
365 V: Clone,
366 {
367 self.map.borrow().get(&key).cloned()
368 }
369
370 /// Run `f` on the value in place (returns `None` if absent).
371 pub fn with<R>(&self, key: usize, f: impl FnOnce(&mut V) -> R) -> Option<R> {
372 self.map.borrow_mut().get_mut(&key).map(f)
373 }
374
375 /// Run `f` over every `(key, value)` (immutable; do not re-enter this table).
376 pub fn for_each(&self, mut f: impl FnMut(usize, &V)) {
377 for (k, v) in self.map.borrow().iter() {
378 f(*k, v);
379 }
380 }
381 }
382
383 /// Remove `key` from every table registered on this thread, running teardowns.
384 /// Call once from a backend's `release()` (and once per auxiliary native object a
385 /// release frees, e.g. an owned content container).
386 pub fn sweep(key: usize) {
387 // Clone the sweeper list first: a teardown may construct a new SideTable
388 // (registering a sweeper) without deadlocking on the borrow.
389 let sweepers: Vec<Sweeper> = SWEEPERS.with(|s| s.borrow().clone());
390 for f in sweepers {
391 f(key);
392 }
393 }
394}
395
396/// Containment for FFI entry points: native callbacks, JNI up-calls, posted-closure
397/// trampolines. A Rust panic unwinding out of an `extern "C"` frame is undefined
398/// behavior (an abort), so every backend trampoline runs its body through
399/// [`ffi_guard::contain`]: a caught panic is reported, the installed recovery hook
400/// restores runtime coherence (day-core installs the reactive runtime's
401/// `recover_from_panic` at boot), and the given default is returned.
402pub mod ffi_guard {
403 use std::sync::OnceLock;
404
405 static RECOVERY: OnceLock<fn()> = OnceLock::new();
406
407 /// Install the post-panic recovery hook (idempotent; first install wins). day-core
408 /// registers `day_reactive::recover_from_panic` here so a contained panic cannot
409 /// leave the reactive observer stack stranded.
410 pub fn set_recovery(f: fn()) {
411 let _ = RECOVERY.set(f);
412 }
413
414 /// Run `f`, containing any panic; on panic, report, run the recovery hook, and
415 /// return `default`.
416 pub fn contain<R>(default: R, f: impl FnOnce() -> R) -> R {
417 match std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)) {
418 Ok(r) => r,
419 Err(payload) => {
420 let msg = payload
421 .downcast_ref::<&str>()
422 .map(|s| s.to_string())
423 .or_else(|| payload.downcast_ref::<String>().cloned())
424 .unwrap_or_else(|| "<non-string panic>".into());
425 log::error!("panic contained at an FFI boundary: {msg}");
426 if let Some(recover) = RECOVERY.get() {
427 recover();
428 }
429 default
430 }
431 }
432 }
433}
434
435/// Realized-node identity as seen by backends (day-core's slotmap key, FFI-encoded).
436#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
437pub struct NodeId(pub u64);
438
439/// Default navigation sidebar width (split presentation) until the pane reports its size.
440/// Semantic container surfaces (see `ContainerProps::role`): each backend maps a role to its
441/// own theme-adaptive material so the fill tracks light/dark mode without app code.
442#[derive(Clone, Copy, Debug, PartialEq, Eq)]
443pub enum SurfaceRole {
444 /// A form `section` card, the platform's grouped-content background: AppKit quaternary
445 /// system fill, libadwaita `.card`, Qt `palette(alternate-base)`, UIKit tertiary system
446 /// fill, Material surface-container, XAML card background brush.
447 SectionCard,
448 /// The window's own background, the surface a page sits on: what an opaque cover paints
449 /// by default, and the card of a composed modal sheet (docs/cover.md "Modal sheet").
450 Window,
451 /// The layer between a composed modal sheet and the page under it, which says the page is
452 /// out of reach until the sheet goes. The container's `background` is the plain dimming a
453 /// backend draws when it has no material of its own; the web frosts the page instead.
454 Scrim,
455}
456
457pub const NAV_SIDEBAR_WIDTH: f64 = 240.0;
458
459/// Drag limits for a navigation host's sidebar pane, around [`NAV_SIDEBAR_WIDTH`]. Shared by the
460/// desktops whose divider the user can drag (docs/navigation.md): AppKit enforces both through
461/// its `NSSplitViewItem`; Qt honors the minimum through the pane's own minimum size and leaves
462/// the maximum to the user.
463pub const NAV_SIDEBAR_MIN_W: f64 = 160.0;
464pub const NAV_SIDEBAR_MAX_W: f64 = 400.0;
465
466/// Default preferred width of a navigation host's content-list pane
467/// (`props::NavProps::list_width`, docs/navigation.md), Mail's message-list proportion.
468pub const NAV_LIST_WIDTH: f64 = 300.0;
469
470/// Drag limits for the content-list pane, around the app's preferred width; the same split of
471/// duties as the sidebar's.
472pub const NAV_LIST_MIN_W: f64 = 220.0;
473pub const NAV_LIST_MAX_W: f64 = 560.0;
474
475/// Reserved id for window-level events (resize, lifecycle): day-core routes it to the root.
476pub const WINDOW_NODE: NodeId = NodeId(u64::MAX);
477
478/// Which nodes handle the non-text keys (docs/menus.md). Keys follow focus (the focused piece
479/// hears them and nobody else), so a backend whose focused view would have to claim a key from
480/// the platform's own dispatch (AppKit's responder chain, the DOM's default action) has to know
481/// whether the app wants it before swallowing it. An unclaimed arrow has to keep traveling, or
482/// a canvas inside a scroll view would silently eat the keys that scroll it.
483///
484/// It lives here, in day-spec, rather than in day-core: `day-toolkit-dom` depends on day-spec alone,
485/// and this is a fact about a node that both sides need.
486pub mod keys {
487 use super::NodeId;
488 use std::cell::RefCell;
489 use std::collections::HashSet;
490
491 thread_local! {
492 static HANDLED: RefCell<HashSet<NodeId>> = RefCell::new(HashSet::new());
493 }
494
495 /// Declare that `node` has a key handler (what `Decorate::on_key` records at build).
496 pub fn mark(node: NodeId) {
497 HANDLED.with(|h| h.borrow_mut().insert(node));
498 }
499
500 /// Whether `node` has one.
501 pub fn handled(node: NodeId) -> bool {
502 HANDLED.with(|h| h.borrow().contains(&node))
503 }
504
505 thread_local! {
506 static TEXT: RefCell<HashSet<NodeId>> = RefCell::new(HashSet::new());
507 }
508
509 /// Declare that `node` takes the whole keyboard while focused (what `Decorate::keyboard`
510 /// records at build): every key the platform delivers reaches its handler, named the way
511 /// [`super::KeyEvent`] describes for the full route, and a touch platform raises its soft
512 /// keyboard for it.
513 pub fn mark_text(node: NodeId) {
514 TEXT.with(|h| h.borrow_mut().insert(node));
515 }
516
517 /// Whether `node` takes the whole keyboard: it declared so AND it [`handled`]s keys. A
518 /// declaration with no `.on_key` behind it claims nothing, so every backend asks this one
519 /// question before it raises a soft keyboard, names a letter or claims a Tab.
520 pub fn text(node: NodeId) -> bool {
521 TEXT.with(|h| h.borrow().contains(&node)) && handled(node)
522 }
523
524 /// Drop both marks for a node that left the tree (day-core calls it from its removal
525 /// path). Node ids are generational, so a stale id would never match a new node; this
526 /// keeps the registries from growing with every rebuilt canvas.
527 pub fn forget(node: NodeId) {
528 HANDLED.with(|h| h.borrow_mut().remove(&node));
529 TEXT.with(|h| h.borrow_mut().remove(&node));
530 }
531}
532
533/// Raw foreign native handle for polyglot adoption (§15.3).
534pub type RawHandle = *mut std::ffi::c_void;
535
536// ---------------------------------------------------------------------------
537// Events (§8.3)
538// ---------------------------------------------------------------------------
539
540/// The wire table for backends whose native side reaches Rust through one numeric-kind
541/// trampoline (Android's JNI `nativeOnEvent`, ArkUI's `day_arkui_on_event`). This enum
542/// defines those kind numbers; the Java and C++ sides carry mirrored constants that parity
543/// tests check against these discriminants (so a collision or drift fails `cargo test` on the
544/// host instead of silently mis-decoding events on a device). AppKit/UIKit/GTK/Qt emit `Event`
545/// values directly and never use these numbers; XAML uses per-event callbacks with its own
546/// small local codes.
547///
548/// Payload conventions ride `(num: f64, text: String)` per kind, documented on each variant.
549pub mod bridge {
550 /// One numeric event kind. `as i32` is the wire value.
551 #[repr(i32)]
552 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
553 pub enum BridgeKind {
554 /// Click/press. No payload.
555 Pressed = 0,
556 /// `text` = the field's full new text.
557 TextChanged = 1,
558 /// `num` != 0 ⇒ on.
559 ToggleChanged = 2,
560 /// `num` = the new value.
561 ValueChanged = 3,
562 /// `num` = the selected index.
563 SelectionChanged = 4,
564 /// `num` == 1 ⇒ the native side already popped (predictive back / up arrow).
565 NavBack = 5,
566 /// Nav/tab page size report; `text` = `"w,h"` in px (Rust divides by density).
567 FrameChanged = 6,
568 /// Warm deep link; `text` = the route.
569 Deeplink = 7,
570 /// Modal answered with a button; `num` = the button index.
571 PresentButton = 8,
572 /// Modal answered with text; `text` = the entry.
573 PresentText = 9,
574 /// Modal dismissed.
575 PresentDismissed = 10,
576 /// Gesture; `num` = phase (0 tap, 1 began, 2 changed, 3 ended), `text` = `"x,y,tx,ty"` px.
577 Gesture = 11,
578 /// Piece-defined open channel (`Event::Custom` with an empty tag): the piece reads the
579 /// raw `num`/`text` payload.
580 Custom = 12,
581 /// Menu selection; the event's node id is the chosen action's dispatch id.
582 MenuAction = 13,
583 /// App lifecycle; `num` = the phase code (`day_spec::Lifecycle` order).
584 Lifecycle = 14,
585 /// File-picker answer; `text` = chosen locators joined by the unit separator.
586 PresentFile = 15,
587 /// `num` != 0 ⇒ gained keyboard focus.
588 FocusChanged = 16,
589 /// IME action / Return.
590 Submitted = 17,
591 /// Root size change; `text` = `"w,h"` in px. Routed to `WINDOW_NODE` as a window
592 /// resize (the rail rotation, late inset passes, and the soft keyboard ride).
593 WindowResized = 18,
594 /// Safe-area report from an edge-to-edge backend; `text` =
595 /// `"top,bottom,leading,trailing"` in px (Rust divides by density and feeds
596 /// `day_core::set_safe_area`). Node id ignored; no `Event` is emitted.
597 SafeArea = 19,
598 /// A secondary window closed (docs/windows.md); the node id is the window's root.
599 WindowClosed = 20,
600 /// A secondary window's key/active state changed; `num` != 0 ⇒ focused.
601 WindowFocused = 21,
602 /// `num` = the settled value: the drag ended (see `Event::ValueCommitted`). A backend
603 /// that cannot tell a settled value from a moving one sends only `ValueChanged`.
604 ValueCommitted = 22,
605 /// Inline search on a `.searchable()` navigation surface (docs/search.md): the field's
606 /// new text, against the nav host's node. `num` = 1 ⇒ the text was submitted (Return or
607 /// the keyboard's Search key), decoding to [`crate::Event::SearchSubmitted`].
608 SearchChanged = 23,
609 /// The toolkit's own adaptive nav container changed presentation and is reporting it
610 /// (docs/size-classes.md). `num` = 1.0 for split, 0.0 for stacked.
611 NavPresentation = 24,
612 /// The system switched between light and dark appearance. No payload; node id ignored
613 /// and no `Event` is emitted; Rust calls `day_core::note_appearance_changed`, the same
614 /// thing AppKit's and GTK's own scheme observers do.
615 AppearanceChanged = 25,
616 /// A fullscreen cover's hide transition finished (docs/cover.md); no payload, and the
617 /// node id is the cover's. Decodes to [`crate::Event::CoverHidden`].
618 CoverHidden = 26,
619 /// A styled text run's link was tapped (docs/text-runs.md); `text` = the run's target.
620 /// Decodes to [`crate::Event::LinkActivated`].
621 LinkActivated = 27,
622 /// The platform's own undo affordance fired (⌘Z, a three-finger swipe, the Edit menu
623 /// through a native front); `num` != 0 ⇒ redo.
624 UndoInvoked = 28,
625 /// A toolbar item produced a value (docs/toolbars.md): the node id is the item's
626 /// dispatch action; `text` = `"on"` with `num` != 0 ⇒ a toggle turned on, `"on"` with
627 /// 0 ⇒ off, `"sel"` with `num` = the chosen segment, `"text:<query>"` ⇒ a search
628 /// item's new text, `"submit:<query>"` ⇒ that text submitted. Decodes to
629 /// [`crate::Event::ToolbarChanged`]. A plain toolbar button sends `MenuAction`.
630 ToolbarChanged = 30,
631 /// An activated list row; `num` is its current index.
632 ListActivated = 31,
633 /// External document copied into app storage; `text` = its local locator.
634 DocumentOpened = 32,
635 /// The user's reduce-motion setting flipped (docs/accessibility.md). No payload; node
636 /// id ignored and no `Event` is emitted; Rust calls `day_core::note_motion_changed`, as
637 /// the desktop backends' own observers do.
638 ReduceMotionChanged = 33,
639 /// Text committed on the full key route (docs/menus.md "The full route"): `text` =
640 /// what the input method or the key typed, `num` = the modifier mask. Decodes to an
641 /// [`crate::Event::Key`] whose `text` is set; a key that typed nothing rides `Key`.
642 Text = 36,
643 /// A non-text key reached the focused node (docs/menus.md); `text` = the day key name
644 /// (`"ArrowLeft"`, `"5"`, …), `num` = the [`crate::KeyEvent`] modifier mask. Decodes to
645 /// [`crate::Event::Key`].
646 Key = 29,
647 /// A window's display state changed (docs/windows.md): `num` = the
648 /// [`crate::WindowState`] code (0 normal, 1 minimized, 2 maximized, 3 fullscreen), against
649 /// the window's root node, or [`crate::WINDOW_NODE`] for the primary. Decodes to
650 /// [`crate::Event::WindowStateChanged`] through [`crate::WindowState::from_code`].
651 WindowStateChanged = 34,
652 /// Native pull-to-refresh request; no payload.
653 RefreshRequested = 35,
654 }
655
656 impl BridgeKind {
657 /// Every variant, for uniqueness/parity tests and exhaustive dispatch.
658 pub const ALL: [BridgeKind; 36] = [
659 BridgeKind::Pressed,
660 BridgeKind::TextChanged,
661 BridgeKind::ToggleChanged,
662 BridgeKind::ValueChanged,
663 BridgeKind::SelectionChanged,
664 BridgeKind::NavBack,
665 BridgeKind::FrameChanged,
666 BridgeKind::Deeplink,
667 BridgeKind::PresentButton,
668 BridgeKind::PresentText,
669 BridgeKind::PresentDismissed,
670 BridgeKind::Gesture,
671 BridgeKind::Custom,
672 BridgeKind::MenuAction,
673 BridgeKind::Lifecycle,
674 BridgeKind::PresentFile,
675 BridgeKind::FocusChanged,
676 BridgeKind::Submitted,
677 BridgeKind::WindowResized,
678 BridgeKind::SafeArea,
679 BridgeKind::WindowClosed,
680 BridgeKind::WindowFocused,
681 BridgeKind::ValueCommitted,
682 BridgeKind::SearchChanged,
683 BridgeKind::NavPresentation,
684 BridgeKind::AppearanceChanged,
685 BridgeKind::CoverHidden,
686 BridgeKind::LinkActivated,
687 BridgeKind::UndoInvoked,
688 BridgeKind::Key,
689 BridgeKind::ToolbarChanged,
690 BridgeKind::ListActivated,
691 BridgeKind::DocumentOpened,
692 BridgeKind::ReduceMotionChanged,
693 BridgeKind::WindowStateChanged,
694 BridgeKind::RefreshRequested,
695 ];
696 }
697
698 #[cfg(test)]
699 mod tests {
700 use super::BridgeKind;
701
702 /// The kind-15 lesson: two meanings on one number decode silently as the first. Every
703 /// discriminant must be unique, and the table must stay dense enough to spot gaps.
704 #[test]
705 fn discriminants_are_unique() {
706 let mut seen = std::collections::BTreeSet::new();
707 for k in BridgeKind::ALL {
708 assert!(
709 seen.insert(k as i32),
710 "duplicate bridge kind number {} ({k:?})",
711 k as i32
712 );
713 }
714 assert_eq!(seen.len(), BridgeKind::ALL.len());
715 }
716
717 /// `ALL` is what the uniqueness check above sees, so a variant left out of it is a variant
718 /// nothing checks, which is how `SearchChanged` and `NavPresentation` sat outside the
719 /// table. The wire numbers are assigned densely from 0, so demanding the set be exactly
720 /// `0..len` catches both a gap and an omission.
721 #[test]
722 fn table_covers_every_wire_number() {
723 let mut nums: Vec<i32> = BridgeKind::ALL.iter().map(|k| *k as i32).collect();
724 nums.sort_unstable();
725 let dense: Vec<i32> = (0..BridgeKind::ALL.len() as i32).collect();
726 assert_eq!(
727 nums, dense,
728 "bridge kinds must be dense from 0 — a missing entry means a variant no test sees"
729 );
730 }
731 }
732}
733
734#[derive(Clone, Debug, PartialEq)]
735pub enum Event {
736 Pressed,
737 TextChanged(String),
738 Submitted,
739 ToggleChanged(bool),
740 ValueChanged(f64),
741 /// A continuous control's value settled: the drag ended (mouse/touch up), or the value moved
742 /// by a discrete action (a keyboard arrow, a click on the track). Always preceded by the
743 /// `ValueChanged` carrying the same value.
744 ///
745 /// The pair exists because one gesture produces two different facts. `ValueChanged` is the
746 /// live one (bindings follow it so the UI tracks the thumb) and it fires continuously, which
747 /// is why nothing durable should key off it: a drag from 1 to 100 and back to 50 emits every
748 /// value in between. `ValueCommitted` fires once, with the value the user chose, and is what
749 /// a recording, a log, or a refetch should use.
750 ///
751 /// A backend that cannot tell the two apart emits only `ValueChanged`; its sliders then do not
752 /// record (docs/coverage-matrix.md).
753 ValueCommitted(f64),
754 SelectionChanged(i64),
755 /// A list row was activated: desktop double-click/Enter, or a touch tap.
756 /// Separate from selection so keyboard browsing need not open or play the row.
757 ListActivated(usize),
758 /// The platform's own undo affordance fired through a native front (⌘Z on the Edit menu,
759 /// a three-finger swipe, shake-to-undo); `redo` distinguishes the pair. Only backends
760 /// with a native undo system emit it; everywhere else the app's own controls call the
761 /// stack directly and this event never exists (docs/model.md).
762 Undo {
763 redo: bool,
764 },
765 /// The platform's own standard edit command fired through its native route (Edit ▸
766 /// Cut/Copy/Paste, ⌘X/⌘C/⌘V, the browser's `copy`/`paste` DOM events) with no text
767 /// widget claiming it first; the app's edit bridge answers (docs/menus.md). Transport
768 /// is the system clipboard (day-part-clipboard), not the event.
769 Edit(EditOp),
770 /// A multi-select list's selection changed: the full set of selected row indices,
771 /// ascending (empty = nothing selected). Emitted instead of `SelectionChanged` where
772 /// `ListProps::multi_select` is honored (docs/list.md).
773 SelectionSet(Vec<i64>),
774 FocusChanged(bool),
775 Tap(Point),
776 /// A link run inside a label was activated; the payload is [`TextRun::link`] verbatim.
777 LinkActivated(String),
778 LongPress(Point),
779 /// A context-menu summon reported by a toolkit that presents no native menu of its own
780 /// (web-dom): the pieces layer shows the composed menu (docs/menus.md). `local` is the
781 /// point in the node's own coordinates (what the app's provider receives); `window` the
782 /// same point in window coordinates (where the composed panel goes). Toolkits that serve
783 /// context menus natively never emit this.
784 ContextMenu {
785 local: Point,
786 window: Point,
787 },
788 /// A drag/pan gesture (docs/shapes.md). `location` is in the node's local coordinates;
789 /// `translation` is the cumulative movement since `Began`.
790 Drag {
791 phase: DragPhase,
792 location: Point,
793 translation: Point,
794 },
795 /// A pinch/magnify gesture over the node (docs/shapes.md): `scale` is cumulative since
796 /// `Began` (1.0 = unchanged), `location` the gesture's centroid in local coordinates,
797 /// the anchor a zoom keeps stationary. Only nodes that enabled
798 /// [`GestureKind::Pinch`] receive it; a backend with no recognizer emits nothing.
799 Pinch {
800 phase: DragPhase,
801 scale: f64,
802 location: Point,
803 },
804 /// A viewport pan over the node (docs/shapes.md): `delta` is the movement since the
805 /// previous event; incremental, not cumulative, because desktop wheels have no gesture
806 /// session to accumulate over (a discrete wheel tick arrives as a lone `Changed`).
807 /// Two-finger touch pans bracket theirs with `Began`/`Ended`. Distinct from
808 /// [`Event::Drag`], the primary pointer's press-drag.
809 Pan {
810 phase: DragPhase,
811 delta: Point,
812 location: Point,
813 },
814 /// The pointer moved over the node, or left it (docs/canvas.md "Interaction"). `location` is
815 /// in the node's local coordinates. Phases follow the drag vocabulary: `Began` on entry,
816 /// `Changed` for each move, `Ended` on exit, where `location` is the last point seen inside,
817 /// so a handler always knows where the pointer went out.
818 ///
819 /// Only nodes that enabled [`GestureKind::Hover`] receive it, and only on a device with a
820 /// pointer at all.
821 Hover {
822 phase: DragPhase,
823 location: Point,
824 },
825 ScrollChanged(Point),
826 /// A canvas node was re-framed by layout; re-record (§11). Nav pane/page containers
827 /// also report their allocated size with this (docs/navigation.md).
828 FrameChanged(Size),
829 /// Native back navigation (iOS back button/swipe, Android system back or toolbar up).
830 /// `already_popped` = the toolkit already performed the pop natively (iOS); the nav
831 /// host then syncs its stack without re-issuing `NavPatch::Popped`.
832 NavBack {
833 already_popped: bool,
834 },
835 /// A nav host's own adaptive container changed presentation, and Day is being told about it
836 /// after the fact (docs/size-classes.md).
837 ///
838 /// The counterpart to [`props::NavPatch::Presentation`], for the toolkits that answer
839 /// `Cap::NavRepresent = Emulated`: `UISplitViewController` collapsing as a Pro Max iPhone
840 /// rotates into portrait, `SlidingPaneLayout` deciding at measure time that two panes no
841 /// longer fit. Day did not ask for it and must not fight it; the pieces layer only
842 /// reconciles what follows, which is the selection rule (a split presentation cannot draw an
843 /// empty detail pane, so expanding with nothing selected picks the first item).
844 ///
845 /// Emitted on the NAV host node, and only when the presentation actually changed.
846 NavPresentationChanged(props::NavPresentation),
847 Key(KeyEvent),
848 Pointer(PointerEvent),
849 WindowResized(Size),
850 /// The platform asks the app to show a route (docs/navigation.md), a runtime deep link:
851 /// on web-dom, the URL hash changing under the app (hand-edited, or browser back/forward);
852 /// on mobile, a warm scheme link (iOS `application:openURL:`, Android `onNewIntent` via
853 /// `BridgeKind::Deeplink`). Emitted on [`WINDOW_NODE`] (day-core answers with `navigate()`
854 /// when the route differs from the current one) or on the active nav host's node (the nav
855 /// piece answers with `navigate()` itself, docs/deep-links.md). Launch-time deep links use
856 /// `DAY_DEEPLINK`/`set_launch_deeplink` instead; this variant is for changes while the
857 /// app runs.
858 RouteRequested(String),
859 /// A native modal answered request `req` (docs/dialogs.md).
860 PresentResult {
861 req: u64,
862 result: present::PresentResult,
863 },
864 /// A decode started by [`Toolkit::decode_image`] finished (docs/images.md).
865 ///
866 /// Keyed by request id like [`Event::PresentResult`], and for the same reason: the answer
867 /// belongs to a waiting caller, not to a tree node. It never crosses a native boundary
868 /// (every backend raises it from its own Rust arm once the platform decoder answers), so it
869 /// has no [`bridge::BridgeKind`], exactly like the completion events dialogs use in-process.
870 ///
871 /// No bitmap id rides here: day-core minted it and handed it to the backend with the bytes,
872 /// so it already knows which image a request answers for. A backend that stored the image
873 /// under that id has nothing more to say than the facts it read.
874 ImageDecoded {
875 req: u64,
876 result: Result<BitmapInfo, ImageError>,
877 },
878 /// An encode started by [`Toolkit::encode_image`] finished (docs/images.md): the encoded
879 /// bytes, or why they could not be produced.
880 ImageEncoded {
881 req: u64,
882 result: Result<Vec<u8>, ImageError>,
883 },
884 /// A canvas drawing started by [`Toolkit::render_bitmap`] finished rendering
885 /// (docs/canvas.md "Exporting"). Keyed by request id like [`Event::ImageDecoded`], and like
886 /// it carries no bitmap id: day-core minted the id and handed it over with the ops, so the
887 /// answer is only the facts of the image the backend stored under it.
888 BitmapRendered {
889 req: u64,
890 result: Result<BitmapInfo, ExportError>,
891 },
892 /// A PDF started by [`Toolkit::render_pdf`] finished (docs/canvas.md "Exporting"): the
893 /// document's bytes, or why they could not be produced.
894 PdfRendered {
895 req: u64,
896 result: Result<Vec<u8>, ExportError>,
897 },
898 /// An open, piece-defined event (§8.2). `tag` names the event for in-process emitters (a static
899 /// literal); it is empty for events that cross a native boundary (JNI/C-ABI), which carry only the
900 /// primitive `num`/`text` payload. A piece's `cx.on` reads whichever fields it needs. This is the
901 /// escape hatch for events the fixed variants above don't cover (a web view's URL, a picked date, …).
902 Custom {
903 tag: &'static str,
904 num: f64,
905 text: String,
906 },
907 /// A menu item (app menu or context menu) with this action id was activated (§ menus). day-core
908 /// routes it to the app closure registered for the id. Standard-role items don't carry an id
909 /// (`role` items are handled natively) so they never emit this.
910 MenuAction(u64),
911 /// A toolbar item produced a value: a search field's text, a toggle's new state
912 /// (docs/toolbars.md). `action` is the item's dispatch id, from the same registry
913 /// [`Event::MenuAction`] uses, and day-core routes it to the closure registered for it.
914 /// A plain toolbar button has no value and emits `MenuAction` instead.
915 ToolbarChanged {
916 action: u64,
917 value: ToolbarValue,
918 },
919 /// A searchable navigation surface's field changed (docs/search.md). Emitted against the nav
920 /// host's node, not through the toolbar's dispatch registry: search belongs to the surface,
921 /// so the field can move between the toolbar and the navigation list without the app
922 /// re-registering anything.
923 SearchChanged(String),
924 /// The user picked a different scope. Carries the index into `SearchProps::scopes`.
925 SearchScopeChanged(usize),
926 /// The user chose one of `SearchProps::suggestions`, by index. The toolkit has already put
927 /// that completion in the field and emitted [`Event::SearchChanged`] for it; this says which
928 /// one, for an app that wants to act on the choice itself.
929 SearchSuggestionChosen(usize),
930 /// The user submitted the inline field's text with its Return or Search key. Emitted
931 /// after the last [`Event::SearchChanged`], with the text as submitted, for a search that
932 /// runs on demand (a server query) rather than narrowing as the text changes.
933 SearchSubmitted(String),
934 /// The app moved through a lifecycle phase (docs/lifecycle.md). Backends emit this from the
935 /// native app/activity delegate; day-core routes it to the app's `on_lifecycle` handlers.
936 Lifecycle(Lifecycle),
937 /// A secondary native window closed (the title-bar close, a platform gesture such as an
938 /// app-switcher swipe or an activity finish, or `Toolkit::close_window`); emitted on the
939 /// window's root node after the platform committed the close. day-core disposes the
940 /// window's subtree on receipt, so native and programmatic closes share one teardown
941 /// path (docs/windows.md). Never emitted for the primary window (its close terminates
942 /// the app).
943 WindowClosed,
944 /// A secondary window's key/active state changed; emitted on the window's root node.
945 /// day-core tracks the focused window with it (dialog parenting, dayscript targeting).
946 WindowFocused(bool),
947 /// A window's display state changed (docs/windows.md): the user minimized, zoomed or took it
948 /// fullscreen, or a [`WindowChange::State`] request landed. Emitted on the window's root node
949 /// (the primary's may arrive on [`WINDOW_NODE`]); day-core feeds the window's `state()`
950 /// signal with it, so the app reads what the platform did rather than what it asked for.
951 WindowStateChanged(WindowState),
952 /// A native list committed a drag-reorder (docs/list.md): row `from` landed at row `to`.
953 /// Emitted on the `LIST` node by the list piece's commit hook: the reorder driver
954 /// rotates its snapshot synchronously inside the platform's drop callback, then reports
955 /// through the event queue so the app's `on_reorder` never runs inside a native animation
956 /// callstack.
957 ListReorder {
958 from: usize,
959 to: usize,
960 },
961 /// A regrouping sidebar committed a drop (`props::NavMenuProps::regroup`, docs/navigation.md
962 /// "Moving rows between sections"), in item indices into the rows as they were before the
963 /// move: row `from` now sits in the section whose first row is item `section` (item 0 for
964 /// rows above the first header), before item `before`, or at that section's end for
965 /// `None`. `before` is never `from`. Emitted on the `NAV_MENU` node by a toolkit whose
966 /// `Cap::NavReorder` is `Native`, deferred through the event queue exactly as
967 /// [`Event::ListReorder`] is; the nav validates it against the app's rules before reporting.
968 NavRegroup {
969 from: usize,
970 section: usize,
971 before: Option<usize>,
972 },
973 /// A native list committed a swipe-delete (docs/list.md): the row at this index is gone.
974 /// Deferred through the event queue exactly as [`Event::ListReorder`] is.
975 ListDelete(usize),
976 /// The native pull-to-refresh control requested an update. The app owns its busy state.
977 RefreshRequested,
978 /// A native list activated a swipe action (docs/list.md): the user pressed button `action`
979 /// (an index into the row's [`ListSwipe::actions_at`] offer for `edge`) on row `index`, or
980 /// swiped clear across for the edge's first action. Emitted on the `LIST` node by the list
981 /// piece's commit hook and deferred through the event queue exactly as
982 /// [`Event::ListReorder`] is, so the app's handler never runs inside a native animation
983 /// callstack.
984 ListSwipe {
985 index: usize,
986 edge: SwipeEdge,
987 action: usize,
988 },
989 /// A fullscreen cover's hide transition finished (docs/cover.md): the content can now be
990 /// disposed. Answers [`props::CoverPatch::Dismiss`]; delivery is a hard guarantee, and
991 /// backends over-report rather than under-report; consumers gate on their own closing
992 /// flag, so duplicates and belated reports are no-ops.
993 CoverHidden,
994 /// The user showed or hid an inspector pane through a native affordance (a dock widget's
995 /// close button, a divider dragged shut) rather than through Day (docs/inspector.md).
996 /// Emitted on the `kinds::INSPECTOR` node, and only when the visibility actually changed;
997 /// the piece writes it back to the bound signal. Applying
998 /// [`props::InspectorPatch::Visible`] must never re-emit it (the from-native echo rule).
999 InspectorChanged(bool),
1000 /// The user disclosed or collapsed a tree row through the native affordance (docs/tree.md).
1001 /// Emitted on the `kinds::TREE` node; the piece writes it back to the app's expansion
1002 /// signal. Applying [`props::TreePatch::Expand`] must never re-emit it (the from-native
1003 /// echo rule).
1004 TreeExpanded {
1005 token: u64,
1006 expanded: bool,
1007 },
1008 /// A native tree committed a drag move (docs/tree.md): `token` now sits under `parent`
1009 /// (`None` = the root) at `index` (`None` = dropped onto the parent, an append). Deferred
1010 /// through the event queue exactly as [`Event::ListReorder`] is; the app's `on_move`
1011 /// writes its own data, whose refresh reloads the tree.
1012 TreeMove {
1013 token: u64,
1014 parent: Option<u64>,
1015 index: Option<usize>,
1016 },
1017 /// A tree's selection changed: the full set of selected row tokens (empty = cleared).
1018 /// Token-addressed, since a tree cannot speak row indices: expanding a row renumbers
1019 /// everything below it (docs/tree.md).
1020 TreeSelection(Vec<u64>),
1021}
1022
1023impl Event {
1024 /// Build a text-carrying [`Event::Custom`] (with `num` defaulted to 0), the common case for an
1025 /// in-process piece reporting a value back: `emit(node, Event::custom("webview:url", url))`.
1026 pub fn custom(tag: &'static str, text: impl Into<String>) -> Event {
1027 Event::Custom {
1028 tag,
1029 num: 0.0,
1030 text: text.into(),
1031 }
1032 }
1033}
1034
1035/// An app-lifecycle phase (docs/lifecycle.md). Each backend maps these onto its OS's native app /
1036/// activity delegate. Some phases only exist on some platforms (a mobile app enters the
1037/// background and can be low on memory, a desktop app cannot), so [`Lifecycle::is_universal`]
1038/// marks the ones every backend delivers, and [`Toolkit::supports_lifecycle`] reports per-backend
1039/// truth.
1040///
1041/// Rough native mapping:
1042///
1043/// | phase | AppKit | UIKit | GTK | Qt | Android | XAML |
1044/// |---|---|---|---|---|---|---|
1045/// | `WillLaunch` / `DidLaunch` | `applicationWill/DidFinishLaunching` | same | `startup`/mount | mount | `onCreate` | window create |
1046/// | `DidBecomeActive` | `didBecomeActive` | `didBecomeActive` | `notify::is-active` | `ApplicationActive` | `onResume` | `Activated` |
1047/// | `WillResignActive` | `willResignActive` | `willResignActive` | `notify::is-active` | `ApplicationInactive` | `onPause` | `Deactivated` |
1048/// | `WillEnterForeground` | — | `willEnterForeground` | — | — | `onStart` | — |
1049/// | `DidEnterBackground` | — | `didEnterBackground` | — | — | `onStop` | — |
1050/// | `DidReceiveMemoryWarning` | — | `didReceiveMemoryWarning` | — | — | `onTrimMemory` | — |
1051/// | `WillTerminate` | `willTerminate` | `willTerminate` | `shutdown` | `aboutToQuit` | `onDestroy` | window close |
1052/// | `DidExit` | after `willTerminate` | after `willTerminate` | `run` returned | `exec` returned | after `onDestroy` | loop returned |
1053#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1054pub enum Lifecycle {
1055 /// Before the window and UI are built: the first thing to run. Set up global state here.
1056 WillLaunch,
1057 /// The UI is mounted and the app is about to start running. Kick off startup work here.
1058 DidLaunch,
1059 /// The app came to the foreground and is the active, focused app receiving input.
1060 DidBecomeActive,
1061 /// The app is about to stop being active (an interruption, app switch, or losing focus).
1062 WillResignActive,
1063 /// The app is about to return to the foreground (mobile). Refresh what background invalidated.
1064 WillEnterForeground,
1065 /// The app left the foreground and is no longer visible (mobile). Persist state, release UI work.
1066 DidEnterBackground,
1067 /// The system is low on memory (mobile). Drop caches and non-essential memory now.
1068 DidReceiveMemoryWarning,
1069 /// The app is about to terminate: the last chance to save. Triggered by the Quit command,
1070 /// the platform's quit shortcut, or the OS reclaiming the app.
1071 WillTerminate,
1072 /// The run loop is over and nothing of the app will run after this: the last phase, after
1073 /// every `WillTerminate` handler. Day logs its exit line ("Clean exit for …") once the
1074 /// handlers have run, so a handler here is the app's last word before it.
1075 DidExit,
1076}
1077
1078impl Lifecycle {
1079 /// Every phase, in delivery order (launch → run → quit). Handy for logging/registration sweeps.
1080 pub const ALL: [Lifecycle; 9] = [
1081 Lifecycle::WillLaunch,
1082 Lifecycle::DidLaunch,
1083 Lifecycle::DidBecomeActive,
1084 Lifecycle::WillResignActive,
1085 Lifecycle::WillEnterForeground,
1086 Lifecycle::DidEnterBackground,
1087 Lifecycle::DidReceiveMemoryWarning,
1088 Lifecycle::WillTerminate,
1089 Lifecycle::DidExit,
1090 ];
1091
1092 /// True for phases every backend delivers (launch, activation, termination). The remaining
1093 /// phases (`WillEnterForeground`, `DidEnterBackground`, `DidReceiveMemoryWarning`) are mobile
1094 /// concepts and are only delivered by the mobile backends. `const` so it composes into a
1095 /// backend's `const fn lifecycle_supported` and thus into compile-time guards.
1096 pub const fn is_universal(self) -> bool {
1097 matches!(
1098 self,
1099 Lifecycle::WillLaunch
1100 | Lifecycle::DidLaunch
1101 | Lifecycle::DidBecomeActive
1102 | Lifecycle::WillResignActive
1103 | Lifecycle::WillTerminate
1104 | Lifecycle::DidExit
1105 )
1106 }
1107
1108 /// A stable, human-readable name (for logs/warnings).
1109 pub const fn name(self) -> &'static str {
1110 match self {
1111 Lifecycle::WillLaunch => "WillLaunch",
1112 Lifecycle::DidLaunch => "DidLaunch",
1113 Lifecycle::DidBecomeActive => "DidBecomeActive",
1114 Lifecycle::WillResignActive => "WillResignActive",
1115 Lifecycle::WillEnterForeground => "WillEnterForeground",
1116 Lifecycle::DidEnterBackground => "DidEnterBackground",
1117 Lifecycle::DidReceiveMemoryWarning => "DidReceiveMemoryWarning",
1118 Lifecycle::WillTerminate => "WillTerminate",
1119 Lifecycle::DidExit => "DidExit",
1120 }
1121 }
1122}
1123
1124/// The phase of a drag gesture (docs/shapes.md).
1125#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1126pub enum DragPhase {
1127 Began,
1128 Changed,
1129 Ended,
1130}
1131
1132/// A gesture a node wants delivered. Backends attach the matching native recognizer when day-core
1133/// calls [`Toolkit::enable_gesture`]; the default is no gesture (recognizers cost, so opt-in).
1134#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1135pub enum GestureKind {
1136 Tap,
1137 LongPress,
1138 Drag,
1139 /// The pointer moving over the node without pressing (docs/canvas.md "Interaction"), and
1140 /// leaving it. Delivered only where a pointer exists: every desktop, an iPad with a trackpad
1141 /// or pencil, an Android device with a mouse or stylus. A touch-only device reports none,
1142 /// which is the right answer, not a gap, so anything reachable by hover must also be
1143 /// reachable by a tap.
1144 Hover,
1145 /// Pinch/magnify (docs/shapes.md): trackpad magnification, two-finger touch pinch.
1146 Pinch,
1147 /// Viewport pan (docs/shapes.md): trackpad two-finger scroll, two-finger touch pan.
1148 /// Distinct from [`GestureKind::Drag`], the primary pointer's press-drag.
1149 Pan,
1150}
1151
1152// ---------------------------------------------------------------------------
1153// Menus (app menu bar + context menus). The model is a toolkit-neutral tree; each backend renders
1154// it with its native affordance (NSMenu / GMenu+GtkPopoverMenu / QMenu / UIMenu / Android
1155// PopupMenu / XAML MenuFlyout) and its own conventions, so day imposes no menu manager of its own.
1156// ---------------------------------------------------------------------------
1157
1158/// A keyboard shortcut for a menu item. `primary` is the platform's command modifier (⌘ on Apple,
1159/// Ctrl on GTK/Qt/XAML) so one declaration reads correctly everywhere. `key` is a single character
1160/// (`"s"`, `"."`) or a named key (`"Return"`, `"Delete"`, `"Left"`, `"F1"`).
1161#[derive(Clone, Debug, PartialEq, Eq, Default)]
1162pub struct Shortcut {
1163 pub key: String,
1164 /// ⌘ (Apple) / Ctrl (elsewhere). The conventional command modifier.
1165 pub primary: bool,
1166 pub shift: bool,
1167 /// ⌥ / Alt.
1168 pub alt: bool,
1169 /// Literal Control (⌃ on Apple). Rare; prefer `primary` for the command modifier.
1170 pub control: bool,
1171}
1172
1173impl Shortcut {
1174 /// `primary`+`key` (⌘S / Ctrl+S), the common case: `Shortcut::primary("s").shift()`.
1175 pub fn primary(key: impl Into<String>) -> Shortcut {
1176 Shortcut {
1177 key: key.into(),
1178 primary: true,
1179 ..Default::default()
1180 }
1181 }
1182 /// `key` with no modifiers (e.g. `F1`, plain `Delete`).
1183 pub fn plain(key: impl Into<String>) -> Shortcut {
1184 Shortcut {
1185 key: key.into(),
1186 ..Default::default()
1187 }
1188 }
1189 pub fn shift(mut self) -> Shortcut {
1190 self.shift = true;
1191 self
1192 }
1193 pub fn alt(mut self) -> Shortcut {
1194 self.alt = true;
1195 self
1196 }
1197 pub fn control(mut self) -> Shortcut {
1198 self.control = true;
1199 self
1200 }
1201}
1202
1203/// A standard/system command. The backend supplies the native item, a selector on AppKit/UIKit
1204/// (`cut:`/`copy:`/`paste:`…) or a stock action on GTK/Qt/XAML, so it targets the focused
1205/// control, gets the platform's default label + shortcut, and enables/disables itself
1206/// automatically. This is how default items (Edit ▸ Cut/Copy/Paste, the app's Quit/About) are
1207/// accommodated without the app re-implementing them.
1208#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1209pub enum MenuRole {
1210 Cut,
1211 Copy,
1212 Paste,
1213 SelectAll,
1214 Undo,
1215 Redo,
1216 Delete,
1217 /// The app's About command (docs/settings.md). With an About registered through
1218 /// `day::register_about` the item lowers to that dispatch action (a Day-rendered About
1219 /// window, or the toolkit's own About dialog where one exists); without one AppKit shows
1220 /// its stock Info.plist panel and the other desktops show the label alone.
1221 About,
1222 Quit,
1223 Preferences,
1224 Minimize,
1225 CloseWindow,
1226 Fullscreen,
1227 /// File ▸ New Window (docs/windows.md): opens another window through the builder the
1228 /// app registered with `day::register_new_window`. No platform has a native selector
1229 /// for it, so the item lowers to the registered dispatch action (disabled when none).
1230 NewWindow,
1231 /// Check for Updates… (docs/settings.md): placed directly under About in the macOS App
1232 /// menu (the Sparkle convention) and in Help elsewhere. Lowers to the action an updater
1233 /// registered with `day::register_check_for_updates`; absent from the bar when none did.
1234 CheckForUpdates,
1235}
1236
1237/// The keyboard modifiers held at an interaction, queryable ambiently
1238/// ([`Toolkit::modifiers`]): `primary` is the platform's command key (⌘ on Apple platforms,
1239/// Ctrl elsewhere, the same convention [`Shortcut::primary`] uses). Touch-only backends
1240/// answer all-false.
1241#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1242pub struct Modifiers {
1243 pub shift: bool,
1244 pub primary: bool,
1245 pub alt: bool,
1246}
1247
1248/// A standard edit command a platform route delivered ([`Event::Edit`]).
1249#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1250pub enum EditOp {
1251 Cut,
1252 Copy,
1253 Paste,
1254 SelectAll,
1255}
1256
1257/// What the app's edit bridge can currently do, mirrored into the toolkit
1258/// ([`Toolkit::set_edit_state`]) so native menu validation enables the stock items.
1259/// `can_paste` is the app's half ("a paste handler is installed"); the toolkit combines it
1260/// with its own clipboard-has-text check where one exists.
1261#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1262pub struct EditState {
1263 pub can_cut: bool,
1264 pub can_copy: bool,
1265 pub can_paste: bool,
1266 pub can_select_all: bool,
1267}
1268
1269/// The undo stack's face, as a native front mirrors it ([`Toolkit::set_undo_state`]): what is
1270/// possible and what the menu titles should say. Labels arrive already localized: a toolkit
1271/// cannot invent translated text, the same rule as every other label in this file.
1272#[derive(Clone, Debug, PartialEq, Default)]
1273pub struct UndoState {
1274 pub can_undo: bool,
1275 pub can_redo: bool,
1276 /// The next undo unit's display label ("Rename"), empty when nothing is undoable. Fronts
1277 /// interpolate it into the platform's own title form ("Undo Rename").
1278 pub undo_label: String,
1279 pub redo_label: String,
1280}
1281
1282/// One entry in a menu (recursive: a `Submenu` nests).
1283#[derive(Clone, Debug, PartialEq)]
1284pub enum MenuItem {
1285 /// A command. `action` (nonzero) dispatches [`Event::MenuAction`] to the app; a `role`-only item
1286 /// uses the native standard command instead (action 0). `label`/`shortcut` override the role's
1287 /// defaults. `icon` is the platform's own glyph beside the title where menus carry one (macOS,
1288 /// Windows, GNOME, KDE, Android); a backend whose menus are text-only ignores it.
1289 ///
1290 /// The `id`/`action` split is [`ToolbarItem`]'s: `id` names the item and `action` is what it
1291 /// runs. They are separate because a label cannot serve as a name (it is localized, and an
1292 /// item that shows its own state changes it), so anything addressing an item from outside
1293 /// (dayscript's `menu: { id: … }`) needs something that does not move.
1294 Action {
1295 /// The app's own name for this item, where it gave one. Stable across locales and across
1296 /// a change of `checked`, and unique within the menu it is installed in.
1297 id: Option<String>,
1298 /// The item's command, as a dispatch id from the same registry [`Event::MenuAction`] uses
1299 /// (0 = no command), so a toolbar button and its menu twin can share one closure.
1300 action: u64,
1301 label: String,
1302 shortcut: Option<Shortcut>,
1303 enabled: bool,
1304 /// On/off state where the item stands for a setting or one of several choices, drawn with
1305 /// the platform's own check mark. `None` is a plain command and reserves no mark; `Some`
1306 /// makes the item checkable and says which way it currently sits.
1307 ///
1308 /// The item still runs its `action` when chosen; a backend never flips this on its own.
1309 /// The app owns the state, and re-installing the menu (`app_menu`, which re-lowers on change) is what moves
1310 /// the mark, so what the menu shows can never disagree with what the app thinks.
1311 checked: Option<bool>,
1312 role: Option<MenuRole>,
1313 icon: Option<Icon>,
1314 },
1315 /// A nested submenu. At the top level of an app menu a `role` claims one of the platform's
1316 /// standard menu-bar slots: the backend then uses this menu instead of its stock one, and
1317 /// places it where the platform expects that menu to sit.
1318 Submenu {
1319 label: String,
1320 items: Vec<MenuItem>,
1321 role: Option<MenuBarRole>,
1322 },
1323 /// A visual separator.
1324 Separator,
1325}
1326
1327/// A standard menu-bar slot (macOS's File/Edit/View/Window/Help, and their counterparts
1328/// elsewhere). A backend that has a house style for the menu bar fills every slot an app did
1329/// not claim with its own stock menu, so an app never has to restate the platform's furniture,
1330/// and can still replace any of it by tagging its own submenu with the matching role.
1331#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1332#[non_exhaustive]
1333pub enum MenuBarRole {
1334 File,
1335 Edit,
1336 View,
1337 /// KDE/Plasma's Settings menu (`Configure <App>`, Configure Shortcuts). No counterpart on
1338 /// macOS, where preferences live in the app menu, or on GNOME/Windows.
1339 Settings,
1340 /// macOS's Window menu. Windows and Linux desktops do not have one.
1341 Window,
1342 Help,
1343}
1344
1345// ---------------------------------------------------------------------------
1346// Window toolbars (docs/toolbars.md)
1347// ---------------------------------------------------------------------------
1348
1349/// A standard icon, named by what it means rather than by how it looks, so each backend can
1350/// draw the platform's own glyph for it: an SF Symbol on macOS, a freedesktop icon name on
1351/// GTK and Qt, a Fluent glyph on Windows. This is the only way an icon looks native on every
1352/// desktop at once; a bundled PNG cannot, because it is one artist's take on all four.
1353///
1354/// The set is kept small: the commands that recur across toolbars. Anything
1355/// app-specific is an [`Icon::Image`].
1356#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1357#[non_exhaustive]
1358pub enum Symbol {
1359 Add,
1360 Remove,
1361 Delete,
1362 Edit,
1363 New,
1364 Open,
1365 Save,
1366 Print,
1367 Refresh,
1368 Search,
1369 Share,
1370 Settings,
1371 Info,
1372 Star,
1373 Bookmark,
1374 Back,
1375 Forward,
1376 Up,
1377 Down,
1378 Home,
1379 /// Show/hide the sidebar, the leading item of most desktop toolbars.
1380 Sidebar,
1381 Filter,
1382 Sort,
1383 /// An overflow affordance (macOS `ellipsis`, GNOME's hamburger, Fluent `More`).
1384 More,
1385 Play,
1386 Pause,
1387 Stop,
1388 /// A photo capture: a screenshot command, a camera control.
1389 Camera,
1390 /// Source code.
1391 Code,
1392 /// Light appearance (a sun). The three below are the vocabulary of a theme chooser, which
1393 /// every platform draws with the same three ideas.
1394 Light,
1395 /// Dark appearance (a moon).
1396 Dark,
1397 /// Follow the system: the half-filled circle every platform uses for "automatic".
1398 Auto,
1399 ZoomIn,
1400 ZoomOut,
1401 /// Back to actual size: the 100% zoom command between [`Symbol::ZoomIn`] and
1402 /// [`Symbol::ZoomOut`].
1403 ZoomReset,
1404 Undo,
1405 Redo,
1406 Copy,
1407 Cut,
1408 Paste,
1409 Mail,
1410 Folder,
1411 Document,
1412 Check,
1413 Close,
1414 Warning,
1415 /// A rectangle: the shape vocabulary a drawing surface needs (docs/shapes.md), and the
1416 /// glyphs every drawing, diagram and annotation tool puts in the same place.
1417 Rectangle,
1418 /// An ellipse.
1419 Oval,
1420 /// An outlined circle: the read/unread vocabulary (a read row, its dot removed), and the
1421 /// generic ring glyph.
1422 Circle,
1423 /// A filled circle: the unread dot itself.
1424 CircleFilled,
1425 /// A straight line segment.
1426 Line,
1427 /// Combine the selection into a group: the drawing-tool command (two stacked squares).
1428 Group,
1429 /// Dissolve a group back into its members (two separated squares).
1430 Ungroup,
1431 /// Text: a line of type as a drawing element (the drawing-tool "T").
1432 Text,
1433}
1434
1435/// The SF Symbol each standard symbol draws as. The system's own glyphs match the user's
1436/// device: weight, optical size, accent color and all. Shared by both Apple backends
1437/// (toolbars on macOS, menus on both).
1438///
1439/// The match is exhaustive so that a new [`Symbol`] must name its glyph here rather than
1440/// silently drawing nothing on Apple. A name this OS release does not know still resolves to
1441/// no image, and the item falls back to its label.
1442pub fn sf_symbol_name(s: Symbol) -> &'static str {
1443 match s {
1444 Symbol::Add => "plus",
1445 Symbol::Remove => "minus",
1446 Symbol::Delete => "trash",
1447 Symbol::Edit => "pencil",
1448 Symbol::New => "square.and.pencil",
1449 Symbol::Open => "folder",
1450 Symbol::Save => "square.and.arrow.down",
1451 Symbol::Print => "printer",
1452 Symbol::Refresh => "arrow.clockwise",
1453 Symbol::Search => "magnifyingglass",
1454 Symbol::Share => "square.and.arrow.up",
1455 Symbol::Settings => "gearshape",
1456 Symbol::Info => "info.circle",
1457 Symbol::Star => "star",
1458 Symbol::Bookmark => "bookmark",
1459 Symbol::Back => "chevron.backward",
1460 Symbol::Forward => "chevron.forward",
1461 Symbol::Up => "chevron.up",
1462 Symbol::Down => "chevron.down",
1463 Symbol::Home => "house",
1464 Symbol::Sidebar => "sidebar.leading",
1465 Symbol::Filter => "line.3.horizontal.decrease",
1466 Symbol::Sort => "arrow.up.arrow.down",
1467 Symbol::More => "ellipsis",
1468 Symbol::Play => "play.fill",
1469 Symbol::Pause => "pause.fill",
1470 Symbol::Stop => "stop.fill",
1471 Symbol::Camera => "camera",
1472 Symbol::Code => "chevron.left.forwardslash.chevron.right",
1473 Symbol::Light => "sun.max",
1474 Symbol::Dark => "moon",
1475 Symbol::Auto => "circle.lefthalf.filled",
1476 Symbol::ZoomIn => "plus.magnifyingglass",
1477 Symbol::ZoomReset => "1.magnifyingglass",
1478 Symbol::ZoomOut => "minus.magnifyingglass",
1479 Symbol::Undo => "arrow.uturn.backward",
1480 Symbol::Redo => "arrow.uturn.forward",
1481 Symbol::Copy => "doc.on.doc",
1482 Symbol::Cut => "scissors",
1483 Symbol::Paste => "doc.on.clipboard",
1484 Symbol::Mail => "envelope",
1485 Symbol::Folder => "folder",
1486 Symbol::Document => "doc",
1487 Symbol::Check => "checkmark",
1488 Symbol::Close => "xmark",
1489 Symbol::Warning => "exclamationmark.triangle",
1490 Symbol::Rectangle => "rectangle",
1491 Symbol::Oval => "oval",
1492 Symbol::Circle => "circle",
1493 Symbol::CircleFilled => "circle.fill",
1494 Symbol::Line => "line.diagonal",
1495 Symbol::Group => "square.on.square",
1496 Symbol::Ungroup => "square.on.square.dashed",
1497 Symbol::Text => "textformat",
1498 }
1499}
1500
1501/// A button or toolbar item's picture: a standard [`Symbol`] (drawn with the platform's own icon set) or
1502/// a bundled image from `resource/images` for something only this app has.
1503#[derive(Clone, Debug, PartialEq)]
1504pub enum Icon {
1505 Symbol(Symbol),
1506 /// A bundled image name, resolved the same way [`ImageName`] is elsewhere.
1507 Image(String),
1508}
1509
1510/// What a toolbar item is. The variants are the vocabulary every desktop toolbar shares; each
1511/// backend realizes one with its native control, never with a drawn imitation.
1512#[derive(Clone, Debug, PartialEq)]
1513pub enum ToolbarItemKind {
1514 /// A push button running the item's `action`.
1515 Button,
1516 /// A two-state button. `on` seeds it; the user flipping it emits
1517 /// [`ToolbarValue::On`], and the app's own writes arrive as [`ToolbarPatch::On`].
1518 Toggle { on: bool },
1519 /// A button that drops a menu: the same [`MenuItem`] model the menu bar uses, so a
1520 /// toolbar menu and its menu-bar twin are one list of commands.
1521 Menu { items: Vec<MenuItem> },
1522 /// A search field. Edits emit [`ToolbarValue::Text`]; the app's own writes arrive as
1523 /// [`ToolbarPatch::Text`].
1524 ///
1525 /// Day creates this item itself, from a `.searchable()` surface whose placement resolved to
1526 /// the toolbar (docs/search.md); apps declare search on the surface, never here.
1527 Search {
1528 text: String,
1529 placeholder: String,
1530 /// Completions for the current text, drawn by the field's own completion affordance
1531 /// where it has one (`AutoSuggestBox`, `QCompleter`, `<datalist>`). Empty = none.
1532 suggestions: Vec<String>,
1533 },
1534 /// A row of mutually exclusive choices drawn as one control: the native segmented control
1535 /// (`NSSegmentedControl`, a linked GTK/Qt button box, a XAML toggle strip, `.day-segmented`
1536 /// on the web).
1537 ///
1538 /// This is what a set of related toolbar toggles should be when exactly one of them is on at
1539 /// a time: three separate toggles say "three independent switches" to the eye and to a screen
1540 /// reader, and leave the app to keep them exclusive. Choosing a segment emits
1541 /// [`ToolbarValue::Selected`]; the app's own writes arrive as [`ToolbarPatch::Selected`].
1542 Segmented {
1543 /// One entry per segment. A segment with an icon draws it in place of its title where
1544 /// the platform does that, and keeps the title as its accessible name.
1545 segments: Vec<ToolbarSegment>,
1546 selected: usize,
1547 },
1548 /// Static text, for a status or a caption.
1549 Label,
1550 /// A divider between neighbors in the same placement bucket, where the platform draws one
1551 /// (macOS toolbars have no separator, so AppKit renders it as a fixed space,
1552 /// docs/toolbars.md). Grouping is all it does: alignment is [`ToolbarPlacement`]'s job.
1553 Separator,
1554}
1555
1556/// One choice inside a [`ToolbarItemKind::Segmented`] control.
1557#[derive(Clone, Debug, PartialEq)]
1558pub struct ToolbarSegment {
1559 /// The segment's name: its label where the platform shows text, its accessible name always.
1560 pub title: String,
1561 pub icon: Option<Icon>,
1562}
1563
1564/// The reserved id of the sidebar affordance a `nav(Sidebar)` supplies for itself
1565/// (docs/toolbars.md). Backends with a system item for the job (AppKit's
1566/// `NSToolbarToggleSidebarItem`) recognize it by this id and draw theirs instead; dayscript
1567/// recognizes it to drive the toolkit's own duty rather than an app closure.
1568pub const SIDEBAR_TOGGLE_ID: &str = "day::sidebar_toggle";
1569
1570/// The reserved id of a `.searchable()` surface's field (docs/search.md): the `ToolbarItem` a
1571/// desktop bar draws for it, and the name dayscript's `toolbar:` step drives it by wherever the
1572/// platform put it — on the bar, or inline on the navigation surface where the bar holds no
1573/// field, in which case day-core resolves the id to that host instead.
1574pub const SEARCH_ITEM_ID: &str = "day::search";
1575
1576/// One item in a window's toolbar (docs/toolbars.md).
1577#[derive(Clone, Debug, PartialEq)]
1578pub struct ToolbarItem {
1579 /// Stable identity: the native item identifier, the dayscript target, and the key a
1580 /// [`ToolbarPatch`] addresses. Unique within a toolbar.
1581 pub id: String,
1582 pub kind: ToolbarItemKind,
1583 /// The item's name. Shown beside or below the icon where the platform does that, and used
1584 /// verbatim in the overflow and customization menus, so it is never optional, even on a
1585 /// toolbar that only shows icons. It is also the item's accessible name.
1586 pub label: String,
1587 /// Hover help. Defaults to `label` where the platform expects a tooltip and none is given.
1588 pub tooltip: Option<String>,
1589 pub icon: Option<Icon>,
1590 pub enabled: bool,
1591 /// The item's command, as a dispatch id from the same registry [`Event::MenuAction`] uses
1592 /// (0 = no command), so a toolbar button and its menu twin can share one closure.
1593 pub action: u64,
1594 /// This item's role on the chrome carrying it (docs/toolbars.md). It never names a surface:
1595 /// Which chrome an item rides is decided by where the app declared it, so this says only
1596 /// where on that chrome it belongs.
1597 pub placement: ToolbarPlacement,
1598 /// Whether the item draws its title, its icon, or both, where the platform can do more than
1599 /// one. An item folded into an overflow menu shows its title whatever this asks for; a menu
1600 /// row with no words is not a menu row.
1601 pub label_style: LabelStyle,
1602 /// Draw this item in the platform's emphasized style (a tinted/filled bar button, a
1603 /// prominent `NSToolbarItem`). For the one action a chrome is really offering.
1604 pub prominent: bool,
1605 /// Which column of a multi-pane window this item came from (docs/toolbars.md), set by Day
1606 /// from the piece that declared it, never by an app.
1607 ///
1608 /// A desktop toolbar spans every column at once, and a three-pane app expects each column's
1609 /// commands to sit over that column: the sidebar's against the first divider, the list's over
1610 /// the list, the rest over the detail. That is what Mail, Notes and Finder do, and it is only
1611 /// expressible because the declaration site already said which pane the command belongs to.
1612 /// Backends that draw one undivided bar ignore it.
1613 pub column: ToolbarColumn,
1614}
1615
1616/// Which pane of a window's navigation a toolbar item was declared in (docs/toolbars.md).
1617#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1618pub enum ToolbarColumn {
1619 /// The window itself, over no particular column. Draws with the detail's items, which is
1620 /// where a command that acts on the whole window belongs when the panes are side by side.
1621 #[default]
1622 Window,
1623 /// The sidebar / master column.
1624 Sidebar,
1625 /// The content-list column between the sidebar and the detail.
1626 List,
1627 /// The detail column.
1628 Detail,
1629}
1630
1631/// Where an item sits on the chrome that carries it (docs/toolbars.md).
1632///
1633/// A placement is a role, never a surface. Which toolbar, navigation bar or column an item
1634/// rides follows from the piece that declared it, so an app never spells that out twice.
1635#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1636pub enum ToolbarPlacement {
1637 /// The natural spot on this chrome: after the leading group on a desktop toolbar, the
1638 /// trailing item group on a navigation bar, an `IF_ROOM` menu action on Android.
1639 #[default]
1640 Automatic,
1641 /// The leading edge: a pane toggle, a control that reveals what is to its left.
1642 Navigation,
1643 /// Centered: a title accessory, a transport, a status readout.
1644 Principal,
1645 /// Trailing, and the last thing a crowded chrome gives up.
1646 Primary,
1647 /// Trailing, and the first thing a crowded chrome folds into its overflow.
1648 Secondary,
1649 /// A bottom bar where the platform has one (iOS `toolbarItems`, an Android bottom app bar);
1650 /// [`ToolbarPlacement::Secondary`] everywhere else.
1651 Bottom,
1652}
1653
1654/// Which halves of an item's label a platform draws, where it can draw more than one.
1655#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1656pub enum LabelStyle {
1657 /// The platform's own convention for this chrome.
1658 #[default]
1659 Automatic,
1660 /// The icon alone (the title stays as the accessible name and the tooltip).
1661 IconOnly,
1662 /// The title alone, even where an icon was given.
1663 TitleOnly,
1664 /// Both, where the chrome has room for both.
1665 TitleAndIcon,
1666}
1667
1668/// A value a toolbar item produced.
1669#[derive(Clone, Debug, PartialEq)]
1670pub enum ToolbarValue {
1671 /// A search item's full new text.
1672 Text(String),
1673 /// A search item's text, submitted with the field's Return or Search key. Sent after the
1674 /// last [`ToolbarValue::Text`]; it changes no state of its own.
1675 Submit(String),
1676 /// A toggle item's new state.
1677 On(bool),
1678 /// A segmented item's newly chosen index.
1679 Selected(usize),
1680}
1681
1682/// A targeted update to one live toolbar item: the path that keeps a bound signal in sync
1683/// without rebuilding the bar (which would drop the search field's focus mid-keystroke).
1684#[derive(Clone, Debug, PartialEq)]
1685pub enum ToolbarPatch {
1686 /// Focus a search control and select its text without changing its value.
1687 Focus { item: String },
1688 /// Replace a search item's text.
1689 Text { item: String, text: String },
1690 /// Set a toggle item's state.
1691 On { item: String, on: bool },
1692 /// Select a segmented item's index.
1693 Selected { item: String, index: usize },
1694 /// Enable or disable any item.
1695 Enabled { item: String, on: bool },
1696 /// Replace a search item's completions (docs/search.md). Targeted rather than a rebuild,
1697 /// because these change on every keystroke and rebuilding the bar would take the field's
1698 /// focus with it.
1699 Suggestions { item: String, list: Vec<String> },
1700 /// Replace an item's words (a language change): its label, which an icon-only item still
1701 /// carries for the overflow menu and assistive technology, and its tooltip. The item keeps
1702 /// its native widget, its action and its place.
1703 Label {
1704 item: String,
1705 label: String,
1706 tooltip: Option<String>,
1707 },
1708 /// Replace a search item's empty-state prompt (docs/search.md), in the live field.
1709 Placeholder { item: String, text: String },
1710}
1711
1712impl ToolbarPatch {
1713 /// The id of the item this patch addresses.
1714 pub fn item(&self) -> &str {
1715 match self {
1716 ToolbarPatch::Focus { item }
1717 | ToolbarPatch::Text { item, .. }
1718 | ToolbarPatch::On { item, .. }
1719 | ToolbarPatch::Selected { item, .. }
1720 | ToolbarPatch::Enabled { item, .. }
1721 | ToolbarPatch::Suggestions { item, .. }
1722 | ToolbarPatch::Label { item, .. }
1723 | ToolbarPatch::Placeholder { item, .. } => item,
1724 }
1725 }
1726
1727 /// Write this patch's value into `items`, the model of a bar. `false` when no item there
1728 /// takes it (an unknown id, or a kind the value does not apply to).
1729 pub fn apply_to(&self, items: &mut [ToolbarItem]) -> bool {
1730 let Some(it) = items.iter_mut().find(|i| i.id == self.item()) else {
1731 return false;
1732 };
1733 match (self, &mut it.kind) {
1734 (ToolbarPatch::Focus { .. }, ToolbarItemKind::Search { .. }) => (),
1735 (ToolbarPatch::Text { text, .. }, ToolbarItemKind::Search { text: t, .. }) => {
1736 *t = text.clone()
1737 }
1738 (
1739 ToolbarPatch::Suggestions { list, .. },
1740 ToolbarItemKind::Search { suggestions, .. },
1741 ) => *suggestions = list.clone(),
1742 (ToolbarPatch::On { on, .. }, ToolbarItemKind::Toggle { on: o }) => *o = *on,
1743 (
1744 ToolbarPatch::Selected { index, .. },
1745 ToolbarItemKind::Segmented { segments, selected },
1746 ) if *index < segments.len() => *selected = *index,
1747 (ToolbarPatch::Enabled { on, .. }, _) => it.enabled = *on,
1748 (ToolbarPatch::Label { label, tooltip, .. }, _) => {
1749 it.label = label.clone();
1750 it.tooltip = tooltip.clone();
1751 }
1752 (
1753 ToolbarPatch::Placeholder { text, .. },
1754 ToolbarItemKind::Search { placeholder, .. },
1755 ) => *placeholder = text.clone(),
1756 _ => return false,
1757 }
1758 true
1759 }
1760}
1761
1762/// One step of an edit to a window's toolbar (docs/toolbars.md).
1763///
1764/// Day hands a backend its bar as edits, never as a whole new model to rebuild, for the same
1765/// reason the view tree arrives as `insert`/`remove` rather than as a fresh tree: an item the
1766/// edit does not name keeps its native widget, and with it the keyboard focus, the caret, a
1767/// menu that is open. A value (search text, a toggle) never travels as an edit; it is a
1768/// [`ToolbarPatch`] on the live item.
1769///
1770/// An edit lists every [`ToolbarOp::Remove`] first, then every [`ToolbarOp::Insert`] in
1771/// ascending `index`, so applying them in order to the bar's current items (a
1772/// [`ToolbarMirror`] does exactly that) produces the new bar. Items keep their relative order
1773/// across an edit: an item that moves arrives as a remove and an insert, like one whose
1774/// presentation changed.
1775#[derive(Clone, Debug, PartialEq)]
1776pub enum ToolbarOp {
1777 /// The item with this id leaves the bar.
1778 Remove { id: String },
1779 /// `item` joins the bar at `index`, its position once this edit is complete.
1780 Insert { index: usize, item: ToolbarItem },
1781}
1782
1783impl ToolbarOp {
1784 /// Apply this op to `items`, a bar's model in order.
1785 pub fn apply_to(&self, items: &mut Vec<ToolbarItem>) {
1786 match self {
1787 ToolbarOp::Remove { id } => items.retain(|i| i.id != *id),
1788 ToolbarOp::Insert { index, item } => {
1789 items.insert((*index).min(items.len()), item.clone())
1790 }
1791 }
1792 }
1793}
1794
1795/// A backend's copy of one window's toolbar, kept in step with the [`ToolbarOp`]s and
1796/// [`ToolbarPatch`]es that reach it, and the one place a backend works out where a new item
1797/// goes (docs/toolbars.md).
1798///
1799/// Every backend lays its bar out as a few groups (the leading and trailing ends of a header
1800/// bar, the columns of a split window, the primary and overflow commands of a command bar) and
1801/// keeps model order within each. So an inserted item always goes right after
1802/// [`ToolbarMirror::prev_where`] its own group, or first in the group when that is `None`, and
1803/// nothing already on the bar moves.
1804#[derive(Clone, Debug, Default)]
1805pub struct ToolbarMirror {
1806 items: Vec<ToolbarItem>,
1807}
1808
1809impl ToolbarMirror {
1810 /// The bar's items, in model order.
1811 pub fn items(&self) -> &[ToolbarItem] {
1812 &self.items
1813 }
1814
1815 pub fn is_empty(&self) -> bool {
1816 self.items.is_empty()
1817 }
1818
1819 /// The item with this id.
1820 pub fn get(&self, id: &str) -> Option<&ToolbarItem> {
1821 self.items.iter().find(|i| i.id == id)
1822 }
1823
1824 /// The item dispatching `action`: how a backend whose native bar reports only an action
1825 /// id (a menu tap) finds what was tapped.
1826 pub fn by_action(&self, action: u64) -> Option<&ToolbarItem> {
1827 self.items
1828 .iter()
1829 .find(|i| i.action == action && action != 0)
1830 }
1831
1832 /// Take the item with `id` out, returning it.
1833 pub fn remove(&mut self, id: &str) -> Option<ToolbarItem> {
1834 let at = self.items.iter().position(|i| i.id == id)?;
1835 Some(self.items.remove(at))
1836 }
1837
1838 /// Put `item` at `index` (clamped to the end).
1839 pub fn insert(&mut self, index: usize, item: ToolbarItem) {
1840 let at = index.min(self.items.len());
1841 self.items.insert(at, item);
1842 }
1843
1844 /// Apply one op to the model: what a backend that repaints its whole native bar from the
1845 /// model (a menu of actions) does with each.
1846 pub fn apply(&mut self, op: &ToolbarOp) {
1847 op.apply_to(&mut self.items);
1848 }
1849
1850 /// Write a value patch into the model. `false` when no item takes it.
1851 pub fn patch(&mut self, patch: &ToolbarPatch) -> bool {
1852 patch.apply_to(&mut self.items)
1853 }
1854
1855 /// The nearest item before `index` that `same_group` accepts: the native item a new one at
1856 /// `index` goes right after, in that group. `None` = it goes first in the group.
1857 pub fn prev_where(
1858 &self,
1859 index: usize,
1860 same_group: impl Fn(&ToolbarItem) -> bool,
1861 ) -> Option<&ToolbarItem> {
1862 self.items[..index.min(self.items.len())]
1863 .iter()
1864 .rev()
1865 .find(|i| same_group(i))
1866 }
1867}
1868
1869#[derive(Clone, Debug, PartialEq)]
1870pub struct KeyEvent {
1871 /// The key's name, in the web `KeyboardEvent.key` vocabulary every platform can map onto:
1872 /// the four arrows ("ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown") and the ten digits
1873 /// ("0" through "9", from the main row or the numeric keypad) everywhere, plus
1874 /// "Delete" and "Backspace" on backends with no menu bar ([`Cap::AppMenu`] unsupported),
1875 /// where no accelerator can own those keys. A focused piece claims every key the route
1876 /// carries, so offering them on a menu-bar platform would let a canvas swallow the Delete
1877 /// its own Edit menu was about to act on (docs/menus.md). The two delete keys keep the
1878 /// names the platform gives the physical keys (a Mac's ⌫ is "Backspace" and its ⌦ is
1879 /// "Delete"), so a handler that means "remove this" takes both. A digit arrives only while
1880 /// neither [`KeyEvent::PRIMARY`] nor [`KeyEvent::ALT`] (nor a Mac's Control) is held: ⌘1
1881 /// and Ctrl+1 are accelerators, and a canvas claiming them would starve the menu. Most
1882 /// backends name the digit the keypress types, so a layout whose number row needs Shift for
1883 /// digits reports "1" with [`KeyEvent::SHIFT`] set; XAML and ArkUI read the physical key.
1884 /// Backends emit `Event::Key` only while no text widget has focus; a field's own editing
1885 /// keys never surface here.
1886 ///
1887 /// A piece that declared `Decorate::keyboard()` takes the full route instead: every key
1888 /// the platform delivers while it is focused. A key that types nothing is named by its
1889 /// web name ([`KeyEvent::NAMED`]: "Enter", "Tab", "Escape", "Backspace", "Delete", "Home",
1890 /// "End", "PageUp", "PageDown", "Insert", the arrows and "F1" through "F12"); a key that
1891 /// types is named by its unmodified character ("a", "A" under Shift, "8", "ü" on a layout
1892 /// that has one), and what it typed rides in [`KeyEvent::text`]. Under Control or Alt the
1893 /// name stays that character ("c" with [`KeyEvent::CONTROL`] set, never the control code
1894 /// it would type). Text an input method commits (a dead-key accent, a Japanese phrase,
1895 /// the soft keyboard's word) arrives with the text alone and an empty name: no single
1896 /// key is behind it. Only the platform's command chords stay out: ⌘ on Apple platforms
1897 /// and the browser's own shortcuts belong to the menu and the browser, so a terminal's
1898 /// ⌘C still copies. [`KeyEvent::typed`] is the question a text consumer asks.
1899 pub key: String,
1900 /// A [`KeyEvent::SHIFT`]/[`KeyEvent::PRIMARY`]/[`KeyEvent::ALT`]/[`KeyEvent::CONTROL`]
1901 /// mask.
1902 pub modifiers: u8,
1903 /// The text this press committed, on the full route: what the key typed ("a", "A", "é"
1904 /// after a dead key, the whole string an input method committed at once), or `None` for
1905 /// a key that typed nothing (a named key, a Control or Alt chord, a composition still in
1906 /// progress). Separate from [`KeyEvent::key`] so that a committed "Enter" is text and the
1907 /// Enter key is a key, whatever the input method sends. Always `None` on the short route.
1908 pub text: Option<String>,
1909}
1910
1911impl KeyEvent {
1912 pub const SHIFT: u8 = 1;
1913 /// The platform's command key: ⌘ on Apple platforms, Ctrl elsewhere (the
1914 /// [`Shortcut::primary`] convention).
1915 pub const PRIMARY: u8 = 2;
1916 pub const ALT: u8 = 4;
1917 /// The Control key itself, wherever it sits: on Apple platforms it is a different key from
1918 /// [`KeyEvent::PRIMARY`] (⌘), elsewhere the same one, so a Ctrl+C on Linux sets both.
1919 /// Carried on the full route only (`Decorate::keyboard`).
1920 pub const CONTROL: u8 = 8;
1921
1922 /// The ten digit key names, indexed by value.
1923 pub const DIGITS: [&'static str; 10] = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"];
1924
1925 /// Every name the full route gives a key that types nothing (the web `KeyboardEvent.key`
1926 /// vocabulary). A key outside this list is named by the text it types.
1927 pub const NAMED: [&'static str; 26] = [
1928 "ArrowLeft",
1929 "ArrowRight",
1930 "ArrowUp",
1931 "ArrowDown",
1932 "Enter",
1933 "Tab",
1934 "Escape",
1935 "Backspace",
1936 "Delete",
1937 "Home",
1938 "End",
1939 "PageUp",
1940 "PageDown",
1941 "Insert",
1942 "F1",
1943 "F2",
1944 "F3",
1945 "F4",
1946 "F5",
1947 "F6",
1948 "F7",
1949 "F8",
1950 "F9",
1951 "F10",
1952 "F11",
1953 "F12",
1954 ];
1955
1956 /// The text this press typed ([`KeyEvent::text`]), or `None` for a key that typed nothing.
1957 pub fn typed(&self) -> Option<&str> {
1958 self.text.as_deref()
1959 }
1960
1961 /// A key that types nothing (one of [`KeyEvent::NAMED`], or a chord's character under
1962 /// Control or Alt), on either route.
1963 pub fn named(key: impl Into<String>, modifiers: u8) -> KeyEvent {
1964 KeyEvent {
1965 key: key.into(),
1966 modifiers,
1967 text: None,
1968 }
1969 }
1970
1971 /// Text a press committed on the full route. The key is named by the text when the text
1972 /// is one character (the press typed it), and left empty for a longer commit, which no
1973 /// single key is behind.
1974 pub fn typed_text(text: impl Into<String>, modifiers: u8) -> KeyEvent {
1975 let text = text.into();
1976 let mut chars = text.chars();
1977 let key = match (chars.next(), chars.next()) {
1978 (Some(_), None) => text.clone(),
1979 _ => String::new(),
1980 };
1981 KeyEvent {
1982 key,
1983 modifiers,
1984 text: Some(text),
1985 }
1986 }
1987
1988 /// Text a press committed on the full route, named by the key that produced it
1989 /// (`key`, in the vocabulary above) when the backend knows it.
1990 pub fn typed_by(key: impl Into<String>, text: impl Into<String>, modifiers: u8) -> KeyEvent {
1991 KeyEvent {
1992 key: key.into(),
1993 modifiers,
1994 text: Some(text.into()),
1995 }
1996 }
1997
1998 /// The web name for the function key `F<n>`, `1..=12`.
1999 pub fn function_name(n: u8) -> Option<&'static str> {
2000 match n {
2001 1..=12 => Some(Self::NAMED[13 + n as usize]),
2002 _ => None,
2003 }
2004 }
2005
2006 /// The key name for a typed character when it is one of the ten digits: what a backend
2007 /// reports for a keypress that types `0`–`9`.
2008 pub fn digit_name(c: char) -> Option<&'static str> {
2009 c.to_digit(10).map(|d| Self::DIGITS[d as usize])
2010 }
2011
2012 /// The value of a digit key, or `None` for every other key.
2013 pub fn digit(&self) -> Option<u8> {
2014 match self.key.as_bytes() {
2015 [d @ b'0'..=b'9'] => Some(d - b'0'),
2016 _ => None,
2017 }
2018 }
2019
2020 pub fn shift(&self) -> bool {
2021 self.modifiers & Self::SHIFT != 0
2022 }
2023 pub fn primary(&self) -> bool {
2024 self.modifiers & Self::PRIMARY != 0
2025 }
2026 pub fn alt(&self) -> bool {
2027 self.modifiers & Self::ALT != 0
2028 }
2029 pub fn control(&self) -> bool {
2030 self.modifiers & Self::CONTROL != 0
2031 }
2032}
2033
2034#[cfg(test)]
2035mod key_event_tests {
2036 use super::KeyEvent;
2037
2038 #[test]
2039 fn digit_names_read_back_as_values() {
2040 for (value, c) in ('0'..='9').enumerate() {
2041 let name = KeyEvent::digit_name(c).expect("an ASCII digit names itself");
2042 let key = KeyEvent::named(name, 0);
2043 assert_eq!(key.digit(), Some(value as u8));
2044 }
2045 // Only the ASCII digits: a letter, an Arabic-Indic three, and a named key are not.
2046 assert_eq!(KeyEvent::digit_name('a'), None);
2047 assert_eq!(KeyEvent::digit_name('٣'), None);
2048 let arrow = KeyEvent::named("ArrowUp", 0);
2049 assert_eq!(arrow.digit(), None);
2050 }
2051
2052 #[test]
2053 fn typed_text_is_told_from_named_keys() {
2054 let a = KeyEvent::typed_text("a", 0);
2055 assert_eq!((a.key.as_str(), a.typed()), ("a", Some("a")));
2056 let space = KeyEvent::typed_text(" ", 0);
2057 assert_eq!((space.key.as_str(), space.typed()), (" ", Some(" ")));
2058 assert_eq!(KeyEvent::typed_text("7", 0).digit(), Some(7));
2059 // A longer commit has no key behind it.
2060 let phrase = KeyEvent::typed_text("こんにちは", 0);
2061 assert_eq!(
2062 (phrase.key.as_str(), phrase.typed()),
2063 ("", Some("こんにちは"))
2064 );
2065 // Text that spells a key name is still text, and the key is still a key.
2066 for name in KeyEvent::NAMED {
2067 assert_eq!(
2068 KeyEvent::named(name, 0).typed(),
2069 None,
2070 "{name} types nothing"
2071 );
2072 assert_eq!(KeyEvent::typed_text(name, 0).typed(), Some(name));
2073 }
2074 let accent = KeyEvent::typed_by("e", "é", 0);
2075 assert_eq!((accent.key.as_str(), accent.typed()), ("e", Some("é")));
2076 assert_eq!(KeyEvent::function_name(1), Some("F1"));
2077 assert_eq!(KeyEvent::function_name(12), Some("F12"));
2078 assert_eq!(KeyEvent::function_name(13), None);
2079 let chord = KeyEvent::named("c", KeyEvent::CONTROL | KeyEvent::SHIFT);
2080 assert!(chord.control() && chord.shift() && !chord.primary());
2081 assert_eq!(chord.typed(), None);
2082 }
2083
2084 #[test]
2085 fn a_declaration_claims_nothing_without_a_handler() {
2086 let node = super::NodeId(0xdead_0001);
2087 super::keys::mark_text(node);
2088 assert!(!super::keys::text(node), "no handler, no claim");
2089 super::keys::mark(node);
2090 assert!(super::keys::text(node) && super::keys::handled(node));
2091 super::keys::forget(node);
2092 assert!(!super::keys::text(node) && !super::keys::handled(node));
2093 }
2094}
2095
2096#[derive(Clone, Copy, Debug, PartialEq)]
2097pub struct PointerEvent {
2098 pub position: Point,
2099 pub down: bool,
2100}
2101
2102/// The event sink: enqueue-only. It may be invoked re-entrantly from inside any Toolkit method;
2103/// day-core drains queued events at safe points, each as a fresh batch (§3.3).
2104pub type EventSink = Box<dyn Fn(NodeId, Event)>;
2105
2106/// The synchronous row-pull closures for recycling lists (docs/list.md, §10). day-core injects one
2107/// per `LIST` host via [`Toolkit::attach_list`]; a recycling backend stores it and calls it from
2108/// its native data-source (on the UI thread, outside any day-core borrow). Each closure re-enters
2109/// day-core, so, unlike [`EventSink`], these run to completion synchronously (`bind_row` even
2110/// flushes + lays out the row before returning, so the host can measure the cell immediately).
2111#[derive(Clone)]
2112pub struct ListSource {
2113 /// Report the first actually visible row (exclude overscan). Enqueue-only; optional,
2114 /// so hosts without a viewport binding incur no app event work.
2115 pub first_visible: Option<std::rc::Rc<dyn Fn(usize)>>,
2116 /// Current row count.
2117 pub len: std::rc::Rc<dyn Fn() -> usize>,
2118 /// Present on a sectioned list (`ListProps::sections`, docs/list.md "Sections"): whether
2119 /// row `index` is a section header. Every row index the host sees counts headers, and
2120 /// day-core translates to the app's items. A header row is not selectable, activatable or
2121 /// swipeable; the host draws it in its platform's group-header style, sized to its content
2122 /// even in a `Uniform` list, and floats it where the platform does (macOS group rows,
2123 /// UIKit plain-table section headers).
2124 pub is_header: Option<std::rc::Rc<dyn Fn(usize) -> bool>>,
2125 /// Stable identity token for the row at `index` (for native diffing / animation).
2126 pub token_at: std::rc::Rc<dyn Fn(usize) -> u64>,
2127 /// Build (first use of this cell) or rebind (recycled cell) row `index` into the native cell.
2128 pub bind_row: std::rc::Rc<dyn Fn(usize, RawHandle)>,
2129 /// A host that emulates `Cap::ListSections` binds the header it pins over the top of the
2130 /// list with this instead of `bind_row` (docs/list.md "Sections"): the same build or
2131 /// rebind, but the copy carries no element ids, so a dayscript or accessibility lookup of a
2132 /// header finds the header row in the list, never its pinned copy.
2133 pub bind_pinned: std::rc::Rc<dyn Fn(usize, RawHandle)>,
2134 /// The native cell left the viewport; Day may drop per-cell bookkeeping (optional).
2135 pub recycle: std::rc::Rc<dyn Fn(RawHandle)>,
2136 /// The native host is done with this cell for good (a `GtkListItemFactory::teardown`, a
2137 /// `UITableViewCell` deallocating): Day disposes the row it built there, its scope, nodes
2138 /// and element ids. Without this a host that discards cells, as every pool does on a far
2139 /// jump, leaves one dead row behind in day-core per discarded cell. Safe inside a day-core
2140 /// borrow (the work is held for the borrow's end) and for a cell Day never saw.
2141 pub release: std::rc::Rc<dyn Fn(RawHandle)>,
2142 /// Re-lay the row bound to this cell at `width`, called from the cell's own native layout
2143 /// pass, the hook [`TreeSource::layout_cell`] already gives trees. day-core lays a row at the
2144 /// `LIST`'s width first, which is right wherever the cell is the row itself; a backend
2145 /// whose native row wraps the cell in chrome (GtkListView's themed `row` node pads it)
2146 /// corrects it here, so the row fits the cell the platform gave it instead of holding the
2147 /// whole list wider than its frame. Skips quietly when called inside a day-core borrow (a
2148 /// snapshot pass).
2149 pub layout_cell: std::rc::Rc<dyn Fn(RawHandle, f64)>,
2150 /// The height day-core last laid the row bound to this cell at: the row's own height,
2151 /// padding included, as `RowHeight` resolves it. A backend whose cell measures itself
2152 /// (GtkListView's `DayCell`) reports it as the cell's height, so a padded row keeps its
2153 /// bottom padding rather than the height of its last child's frame. `0.0` before the row's
2154 /// first layout, or inside a day-core borrow.
2155 pub cell_height: std::rc::Rc<dyn Fn(RawHandle) -> f64>,
2156 /// Drag-to-reorder closures, present when `ListProps::reorderable` (docs/list.md). `None` on
2157 /// non-reorderable lists; backends must not enable their drag machinery without it.
2158 pub reorder: Option<ListReorder>,
2159 /// Swipe-to-delete closures, present when `ListProps::deletable` (docs/list.md). `None` on
2160 /// non-deletable lists; backends must not offer their delete affordance without it.
2161 pub delete: Option<ListDelete>,
2162 /// Swipe-actions closures, present when `ListProps::swipe_actions` (docs/list.md). `None` on
2163 /// lists that declared none; backends must not install their row-action machinery
2164 /// without it.
2165 pub swipe: Option<ListSwipe>,
2166}
2167
2168/// The synchronous drag-to-reorder half of [`ListSource`] (docs/list.md). Both closures follow
2169/// `bind_row`'s discipline: called on the UI thread from inside native drag callbacks, outside
2170/// any day-core borrow, and they run to completion synchronously.
2171#[derive(Clone)]
2172pub struct ListReorder {
2173 /// May row `from` drop at row `to`? Called from the native validate/hover hook so the
2174 /// affordance (gap, insertion mark, forbidden cursor) reflects the app's answer live.
2175 /// Returns the accepted target index: `to` itself to allow, another index to retarget the
2176 /// drop, or `-1` to deny.
2177 pub can_move: std::rc::Rc<dyn Fn(usize, usize) -> i64>,
2178 /// Commit: row `from` dropped at row `to` (an index `can_move` accepted). Rotates Day's row
2179 /// snapshot before returning (so `len`/`token_at`/`bind_row` reflect the new order while the
2180 /// native move animates) and defers the app's own callback to the next event drain.
2181 pub move_row: std::rc::Rc<dyn Fn(usize, usize)>,
2182}
2183
2184/// The synchronous swipe-to-delete half of [`ListSource`] (docs/list.md), shaped exactly like
2185/// [`ListReorder`]: both closures are called on the UI thread from inside native swipe callbacks,
2186/// outside any day-core borrow, and run to completion synchronously.
2187///
2188/// Each platform spells the gesture its own way (a trailing swipe action on iOS, an
2189/// `ItemTouchHelper` swipe on Android, a `ListItem` swipe action on ArkUI), but all three ask the
2190/// same two questions, so this struct is one pair of closures rather than three shapes.
2191#[derive(Clone)]
2192pub struct ListDelete {
2193 /// May row `index` be deleted? Called before the affordance is offered, so a row the app
2194 /// protects shows no delete action at all rather than one that fails on use.
2195 pub can_delete: std::rc::Rc<dyn Fn(usize) -> bool>,
2196 /// Commit: delete row `index`. Removes it from Day's row snapshot before returning (so
2197 /// `len`/`token_at`/`bind_row` already reflect the shorter list while the native row-removal
2198 /// animates) and defers the app's own callback to the next event drain.
2199 pub delete_row: std::rc::Rc<dyn Fn(usize)>,
2200}
2201
2202/// Which edge of a row a swipe action rides (docs/list.md). Semantic, not geometric:
2203/// `Leading` follows the reading direction (the left edge in LTR, the right in RTL), the
2204/// mapping every platform's swipe API already makes.
2205#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2206pub enum SwipeEdge {
2207 Leading,
2208 Trailing,
2209}
2210
2211/// One offered swipe action (docs/list.md): pure data. The pieces layer keeps the handlers;
2212/// the backend answers a tap through [`ListSwipe::perform`] by index into the offer.
2213#[derive(Clone, Debug, PartialEq)]
2214pub struct ListSwipeAction {
2215 /// The word on the button, already localized (a toolkit cannot translate).
2216 pub label: String,
2217 /// Destructive styling: the platform's red.
2218 pub destructive: bool,
2219 /// Explicit button color; `None` = the platform's default for the style.
2220 pub tint: Option<Color>,
2221 /// A glyph for the button where the platform draws one: above the label on macOS, in
2222 /// place of it on iOS (docs/list.md).
2223 pub symbol: Option<Symbol>,
2224}
2225
2226/// The synchronous swipe-actions half of [`ListSource`] (docs/list.md), the generalized
2227/// sibling of [`ListDelete`]: reveal-as-you-swipe buttons on either row edge. The offer is
2228/// pulled per row at gesture time, so labels follow row state ("Mark Read" on an unread row,
2229/// "Mark Unread" on a read one); the commit defers to the event drain like every closure here.
2230#[derive(Clone)]
2231pub struct ListSwipe {
2232 /// The offer: the actions for row `index` on `edge`, called inside the platform's swipe
2233 /// callback, so keep it pure. Empty = no affordance for that row and edge. The first action
2234 /// is the full-swipe action where the platform activates one at the far edge.
2235 pub actions_at: std::rc::Rc<dyn Fn(usize, SwipeEdge) -> Vec<ListSwipeAction>>,
2236 /// The commit: the user activated action `action` (an index into the offer) on row
2237 /// `index`, `edge`. Unlike a delete this never reshapes the row snapshot; the app's
2238 /// handler is deferred to the next event drain, never run inside the native callback.
2239 pub perform: std::rc::Rc<dyn Fn(usize, SwipeEdge, usize)>,
2240}
2241
2242/// The synchronous row-pull closures for hierarchical trees (docs/tree.md): [`ListSource`]'s
2243/// shape, addressed by token instead of row index, because expanding a row renumbers every
2244/// index below it while tokens hold still. day-core injects one per `TREE` host via
2245/// [`Toolkit::attach_tree`]; the backend answers its native data-source from it. The same
2246/// synchronous discipline as [`ListSource`]: UI thread, outside any day-core borrow;
2247/// `bind_row` flushes and lays the row out before returning.
2248#[derive(Clone)]
2249pub struct TreeSource {
2250 /// How many children `parent` has (`None` = the root level).
2251 pub children_len: std::rc::Rc<dyn Fn(Option<u64>) -> usize>,
2252 /// The i-th child of `parent`: the stable token every backend keys its rows by.
2253 pub child_token: std::rc::Rc<dyn Fn(Option<u64>, usize) -> u64>,
2254 /// Whether this token can hold children at all: what draws (or omits) the disclosure.
2255 pub expandable: std::rc::Rc<dyn Fn(u64) -> bool>,
2256 /// Non-selectable section heading, separate from a navigation destination.
2257 pub section_header: std::rc::Rc<dyn Fn(u64) -> bool>,
2258 /// Current desired expansion, including restoration before the first native reload.
2259 pub expanded: std::rc::Rc<dyn Fn(u64) -> bool>,
2260 /// Build (first use of this cell) or rebind (recycled cell) the row for `token` into the
2261 /// native cell.
2262 pub bind_row: std::rc::Rc<dyn Fn(u64, RawHandle)>,
2263 /// The native cell left the viewport; Day may drop per-cell bookkeeping (optional).
2264 pub recycle: std::rc::Rc<dyn Fn(RawHandle)>,
2265 /// Re-lay the row bound to this cell at `width`, called from the cell's own native
2266 /// layout pass. Trees need this where lists don't: indentation makes every cell's
2267 /// content width per-row, so the host-width layout `bind_row` did is only a first
2268 /// approximation. Skips quietly when called inside a day-core borrow (a snapshot pass).
2269 pub layout_cell: std::rc::Rc<dyn Fn(RawHandle, f64)>,
2270 /// Native bounds for controls whose group headers have a different height from leaves.
2271 /// Overrides the initial row-height estimate and preserves the native height on rebind.
2272 pub layout_cell_size: std::rc::Rc<dyn Fn(RawHandle, Size)>,
2273 /// The height day-core last laid this cell's row at (see [`ListSource::cell_height`]).
2274 pub cell_height: std::rc::Rc<dyn Fn(RawHandle) -> f64>,
2275 /// The row's type-ahead string (docs/tree.md): what native type-select matches against.
2276 pub type_select_text: std::rc::Rc<dyn Fn(u64) -> String>,
2277 /// The row's context menu, built when the menu is summoned (docs/menus.md "Dynamic context
2278 /// menus"), called on the UI thread from the platform's own menu callback, outside any
2279 /// day-core borrow, like every closure here. `None` = rows carry no menu; an empty
2280 /// result suppresses the menu for that row.
2281 pub row_menu: Option<std::rc::Rc<dyn Fn(u64) -> Vec<MenuItem>>>,
2282 /// Drag-to-move closures, present when `TreeProps::movable` (docs/tree.md). `None` on
2283 /// immovable trees; backends must not enable their drag machinery without it.
2284 pub moves: Option<TreeMoves>,
2285}
2286
2287/// The synchronous drag half of [`TreeSource`] (docs/tree.md). Both closures follow
2288/// `bind_row`'s discipline: called on the UI thread from inside native drag callbacks.
2289#[derive(Clone)]
2290pub struct TreeMoves {
2291 /// The live verdict, consulted while the drag is over a target: may `token` land under
2292 /// `parent` at `index`? `index: None` means "dropped onto the parent" (append). Pure, since
2293 /// it runs inside the platform's drag-validate callback.
2294 #[allow(clippy::type_complexity)]
2295 pub can_move: std::rc::Rc<dyn Fn(u64, Option<u64>, Option<usize>) -> MoveVerdict>,
2296 /// Commit an accepted drop. Defers the app's `on_move` through the event queue
2297 /// ([`Event::TreeMove`]); the app's own data write drives the reload.
2298 #[allow(clippy::type_complexity)]
2299 pub move_node: std::rc::Rc<dyn Fn(u64, Option<u64>, Option<usize>)>,
2300}
2301
2302/// A summon-time context-menu provider (docs/menus.md): local-point in, menu out.
2303pub type ContextMenuFn = std::rc::Rc<dyn Fn(Point) -> Vec<MenuItem>>;
2304
2305/// A tree move guard's verdict (docs/tree.md). No `Retarget` yet: the drop vocabulary is
2306/// already positional, so a guard that wants a different target denies and the user drops
2307/// where it is allowed.
2308#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2309pub enum MoveVerdict {
2310 Allow,
2311 Deny,
2312}
2313
2314/// One addressable widget within a composite native backing (docs/tree.md,
2315/// docs/tweaks.md), Qt's name for the concept (`QStyle::SubControl`). A `list`'s or
2316/// `tree`'s node handle is its scroller; `Subcontrol::Content` is the widget inside it.
2317/// Backends resolve an unknown subcontrol to `None`, never to the host.
2318#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
2319pub enum Subcontrol {
2320 /// The node's own handle: what every tweak accessor reached before subcontrols existed.
2321 Host,
2322 /// The content widget inside the scroller (`NSOutlineView`, `NSTableView`, …).
2323 Content,
2324 /// The header view, where the widget has one. Day's lists and trees ship headerless, so
2325 /// this answers `None` until a kind grows a header.
2326 Header,
2327}
2328
2329// ---------------------------------------------------------------------------
2330// Capabilities, animation, a11y
2331// ---------------------------------------------------------------------------
2332
2333/// What to show on the app's icon in the Dock, launcher, home screen, or taskbar (docs/badge.md).
2334///
2335/// Distinct from `NavItem::badge`, which annotates a sidebar row inside the window. This one
2336/// decorates the application itself and is drawn by the shell, not by Day.
2337///
2338/// What each payload needs is asked separately (`Cap::AppBadgeCount`, `AppBadgeText`,
2339/// `AppBadgeDot`) because the platforms differ in what they accept more than in whether they have
2340/// a badge at all: macOS takes arbitrary text, iOS and the web take a number, Android takes nothing.
2341#[derive(Clone, Debug, PartialEq, Eq, Default)]
2342pub enum AppBadge {
2343 /// Clear the badge.
2344 #[default]
2345 None,
2346 /// A count. Zero clears it, matching every platform's own convention.
2347 Count(u32),
2348 /// Short arbitrary text (`"99+"`, `"beta"`). Only macOS renders it; probe `Cap::AppBadgeText`.
2349 Text(String),
2350 /// An indicator with no value.
2351 Dot,
2352}
2353
2354/// How wide a window is, in coarse buckets (docs/size-classes.md).
2355///
2356/// The breakpoints are Android's window size classes, in density-independent points, and they are
2357/// used verbatim on every backend rather than per-platform. One table means one answer: a 700pt
2358/// window is [`WidthClass::Medium`] on a Mac, in a browser, and on a tablet, so an app that lays
2359/// out from the class gets the same layout at the same size everywhere. Apple publishes only two
2360/// buckets (compact/regular); those map onto this table rather than replacing it, with
2361/// [`WidthClass::Compact`] the compact one and everything above it regular.
2362#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug, Default)]
2363pub enum WidthClass {
2364 /// `< 600dp`: a phone in portrait. One pane at a time.
2365 #[default]
2366 Compact,
2367 /// `600–839dp`: a tablet in portrait, a narrow desktop window.
2368 Medium,
2369 /// `840–1199dp`: a tablet in landscape, a typical desktop window.
2370 Expanded,
2371 /// `1200–1599dp`: a large desktop window.
2372 Large,
2373 /// `≥ 1600dp`: a maximized window on a big display.
2374 ExtraLarge,
2375}
2376
2377/// How tall a window is (docs/size-classes.md). Consulted far less than [`WidthClass`]: it is
2378/// what tells a phone in landscape (wide enough for two panes, too short for a tall list) that
2379/// it should not grow vertical chrome.
2380#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug, Default)]
2381pub enum HeightClass {
2382 /// `< 480dp`: a phone in landscape.
2383 #[default]
2384 Compact,
2385 /// `480–899dp`: a phone in portrait, a tablet in landscape.
2386 Medium,
2387 /// `≥ 900dp`: a tablet in portrait, most desktop windows.
2388 Expanded,
2389}
2390
2391/// A window's size class (docs/size-classes.md), reported by the backend and read by apps
2392/// through `day::size_class()`.
2393///
2394/// Per-window, not per-app: two windows of one process can sit in different classes at the same
2395/// time (a narrow and a wide window side by side, iPadOS Stage Manager, Android split-screen), and
2396/// an app that keyed off a single global would lay the second window out for the first one's size.
2397#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
2398pub struct SizeClass {
2399 pub width: WidthClass,
2400 pub height: HeightClass,
2401}
2402
2403impl SizeClass {
2404 /// The `Compact`/`Medium` width boundary in dp: the narrowest window where a second
2405 /// pane starts to fit. Backends that hand an adaptive container its pane widths derive
2406 /// them from this (Android's list + minimum-detail widths sum to it), so the platform's
2407 /// measure-time decision and this table agree by construction (docs/size-classes.md).
2408 pub const SPLIT_MIN_WIDTH: f64 = 600.0;
2409
2410 /// Bucket a window's size in points. The one place the breakpoint numbers appear.
2411 pub fn from_size(width: f64, height: f64) -> Self {
2412 SizeClass {
2413 width: match width {
2414 w if w >= 1600.0 => WidthClass::ExtraLarge,
2415 w if w >= 1200.0 => WidthClass::Large,
2416 w if w >= 840.0 => WidthClass::Expanded,
2417 w if w >= Self::SPLIT_MIN_WIDTH => WidthClass::Medium,
2418 _ => WidthClass::Compact,
2419 },
2420 height: match height {
2421 h if h >= 900.0 => HeightClass::Expanded,
2422 h if h >= 480.0 => HeightClass::Medium,
2423 _ => HeightClass::Compact,
2424 },
2425 }
2426 }
2427
2428 /// Whether a two-pane presentation fits. The rule behind an automatic
2429 /// [`props::NavPresentation`]: anything wider than compact gets both panes.
2430 pub fn prefers_split(self) -> bool {
2431 self.width > WidthClass::Compact
2432 }
2433}
2434
2435#[derive(Clone, Copy, PartialEq, Eq, Debug)]
2436pub enum Cap {
2437 /// Standard searchfield control.
2438 SearchField,
2439 /// Standard combobox control.
2440 ComboBox,
2441 /// Standard stepper control.
2442 Stepper,
2443 /// Standard datetime control.
2444 DateTimePicker,
2445 /// Standard colorpicker control.
2446 ColorPicker,
2447 /// Standard pullrefresh control.
2448 PullRefresh,
2449 /// Standard pager control.
2450 Pager,
2451 /// User-driven pull recognition, separate from a refresh indicator.
2452 PullRefreshGesture,
2453
2454 /// Native data-transfer source and destination callbacks.
2455 DragDrop,
2456 /// Transfers between independent native applications (inbound).
2457 DragExternalImport,
2458 /// Transfers to independent native applications, including arbitrary binary MIME data.
2459 DragExternalExport,
2460 /// Lossless ordered items and alternatives between Day applications.
2461 DragMultipleItems,
2462 /// Existing native file references, distinct from promised/generated files.
2463 DragFileReferences,
2464 /// Native result can wait for asynchronous data receipt.
2465 DragDeferredReceipt,
2466 /// Generated files supplied to a destination after dropping.
2467 DragFilePromises,
2468 /// External move acknowledgment safe for source deletion.
2469 DragExternalMove,
2470 ListRecycling,
2471 /// The toolkit fronts the app's undo stack with the platform's own undo system
2472 /// ([`Toolkit::set_undo_state`] + `Event::Undo`): `Native` where one exists
2473 /// (`NSUndoManager` on macOS/iOS, `QUndoStack`), `Unsupported` everywhere else, where
2474 /// Day's menu items and accelerators drive the stack directly and nothing platform-owned
2475 /// needs mirroring (docs/model.md).
2476 UndoBridge,
2477 /// The toolkit routes the platform's standard Cut/Copy/Paste to the app's edit bridge
2478 /// ([`Toolkit::set_edit_state`] + `Event::Edit`): the same menu items, shortcuts, and
2479 /// responder precedence the platform's text editing uses; a focused text widget keeps
2480 /// its own clipboard behavior, everything else reaches the app (docs/menus.md).
2481 /// `Native` where a system route exists (the responder chain, the browser's clipboard
2482 /// events), `Emulated` where Day's own menu items dispatch it, `Unsupported` elsewhere.
2483 EditBridge,
2484 /// The toolkit realizes `ListProps::reorderable` as drag-to-reorder rows: `Native` when the
2485 /// platform's own mechanism drives it (NSTableView drag/drop, UITableView drag delegates,
2486 /// ItemTouchHelper, …), `Emulated` for a pointer-tracked fake (web-dom). `Unsupported` ⇒ the
2487 /// list renders normally but rows cannot be dragged (docs/list.md).
2488 ListReorder,
2489 /// Sidebar destinations can be dragged to reorder (`NavBuilder::reorder_items`) and between
2490 /// sections (`NavBuilder::regroup_items`). `Native` when the toolkit's own sidebar drags them
2491 /// (`NavMenuProps::movable`, and across headers under `NavMenuProps::regroup`); `Emulated`
2492 /// when Day stands a reorderable list in for the sidebar. Independent of `ListReorder`: UIKit
2493 /// supports draggable content lists but retains its native navigation collection for
2494 /// sidebars.
2495 NavReorder,
2496 /// The toolkit realizes `ListProps::deletable` as the platform's delete gesture:
2497 /// `Native` where the platform ships one (UIKit's trailing swipe actions, Android's
2498 /// `ItemTouchHelper`, ArkUI's `ListItem.swipeAction`), `Unsupported` on the desktop toolkits,
2499 /// whose lists have no swipe idiom and where deletion belongs to a menu or a button
2500 /// (docs/list.md).
2501 ListDelete,
2502 /// The toolkit realizes `ListProps::swipe_actions` as edge swipe actions: buttons
2503 /// that reveal as the row tracks the swipe, with the far edge activating the first one
2504 /// (docs/list.md). `Native` where the platform ships the affordance: macos-appkit
2505 /// (`NSTableView` row actions, Mail's own machinery) and ios-uikit
2506 /// (`UISwipeActionsConfiguration`). `Unsupported` everywhere else: the affordance is
2507 /// absent, and the app's command lives in its explicit controls.
2508 ListSwipeActions,
2509 /// The toolkit realizes `ListProps::editing` as the platform's list editing mode: rows
2510 /// show their delete controls and reorder grips while the list is editing (docs/list.md).
2511 /// `Native` on ios-uikit (`UITableView` editing). `Unsupported` everywhere else, where a
2512 /// list has no separate editing mode: its rows already drag, swipe and open menus as they
2513 /// are, and the list renders as if `editing` were off.
2514 ListEditing,
2515 /// The toolkit realizes `kinds::LIST_ITEM` as its own list row content (docs/list.md "List
2516 /// items"): `Native` where the platform has a standard row it draws itself (UIKit's
2517 /// `UIListContentConfiguration`, a Material list item, AppKit's image-and-text table cell,
2518 /// a GTK row box), so the row takes the platform's fonts, icon size, spacing, secondary
2519 /// colors and check mark. `Unsupported` ⇒ the `list_item` piece composes the same content
2520 /// from plain pieces. Apps have no reason to probe this; the piece does.
2521 ListItem,
2522 /// The toolkit realizes `kinds::TREE` as a hierarchical tree view (docs/tree.md):
2523 /// `Native` where a platform tree widget hosts Day-built rows (NSOutlineView, the UIKit
2524 /// sidebar list, GtkListView+TreeListModel, WinUI TreeView, ArkTS TreeView), `Emulated`
2525 /// where Day flattens the tree onto its list machinery, `Unsupported` where neither
2526 /// exists yet. An app gates its tree UI on this answer rather than showing a placeholder.
2527 Tree,
2528 /// The toolkit realizes `TreeProps::movable` as drag-to-reparent/restack rows
2529 /// (docs/tree.md). A strictly smaller set than [`Cap::Tree`]: a backend can render a
2530 /// tree it cannot yet drag within.
2531 TreeMove,
2532 /// Native two-level section headers; general trees may still be composed.
2533 TreeSections,
2534 /// The toolkit answers [`Toolkit::first_baseline`], so rows can align text on its baseline
2535 /// rather than on the middle of its box (docs/baseline.md). `Native` where the platform
2536 /// reports the baseline itself (`NSView.firstBaselineOffsetFromTop`, `View.getBaseline`,
2537 /// `gtk_widget_measure`), `Emulated` where Day derives it from the widget's font metrics,
2538 /// `Unsupported` ⇒ baseline-aligned rows fall back to centering and look exactly as they do
2539 /// today.
2540 BaselineAlignment,
2541 /// The toolkit draws a label's [`TextRun`]s: bold, italic, color or a monospace face within
2542 /// one wrapping paragraph (docs/text-runs.md). `Unsupported` ⇒ the label renders its text
2543 /// uniformly, which reads correctly and loses only the emphasis.
2544 TextRuns,
2545 /// The toolkit makes a run carrying [`TextRun::link`] activatable, emitting
2546 /// [`Event::LinkActivated`]. A strictly smaller set than [`Cap::TextRuns`]: several toolkits
2547 /// draw a link run in link colors but have no way to hit-test it, and one (Android) can do
2548 /// links or selection but not both (docs/text-runs.md).
2549 TextLinks,
2550 Lottie,
2551 NativeSymbols,
2552 /// The toolkit can rasterize its window and hand back the pixels
2553 /// (`Toolkit::snapshot_window`): what the dayscript `screenshot` step captures in-process
2554 /// and what `day::window_image()` offers the app (docs/window-image.md). `Unsupported` where
2555 /// a backend cannot draw itself into a bitmap: web-dom, which would need a rasterizer
2556 /// shipped with it. Probe it before offering a "save a screenshot" affordance, rather than
2557 /// offering one that fails when pressed.
2558 Snapshot,
2559 /// The toolkit can present `nav()` as sidebar+detail split panes, a statement about the
2560 /// toolkit, not about the window it is currently drawing. Whether a given host is split right
2561 /// now follows from its [`SizeClass`]: the pieces layer resolves an automatic
2562 /// [`props::NavPresentation`] against both, and re-resolves on every class change. A backend
2563 /// with no split container answers `Unsupported` and stays stacked at every size.
2564 NavSplit,
2565 /// The toolkit can draw a navigation host's rows as its own chrome: a tab bar
2566 /// ([`props::NavPresentation::Tabs`]) and, where it has one, a rail
2567 /// ([`props::NavPresentation::Rail`]). Like [`Self::NavSplit`] this is a statement about the
2568 /// toolkit, not about the window it is drawing right now.
2569 ///
2570 /// This is what `NavStyle::Automatic` resolves against (docs/navigation.md): a backend
2571 /// answering `Unsupported` gets the sidebar resolver instead (`Split` ↔ `Stack`), which is
2572 /// what every backend did before adaptive navigation existed. So an unimplemented backend
2573 /// degrades to its previous behavior rather than to a hole.
2574 ///
2575 /// `Emulated` means the rows are composed from other widgets rather than drawn by a native
2576 /// tab container (Qt, web-dom). `Native` means a real one (`UITabBarController`, a Material
2577 /// `NavigationBarView`, `NavigationView`).
2578 NavTabs,
2579 /// A narrow window should become a tab bar here, a separate question from [`Self::NavTabs`],
2580 /// which only says the toolkit *can* draw one.
2581 ///
2582 /// The two differ on every desktop. macOS, GNOME, Qt and Windows can all draw a tab bar, and
2583 /// must, because an app is free to pin `NavStyle::Tabs`; but none of them grows one when
2584 /// its window is dragged narrow. A narrow Mail.app hides its sidebar and pushes; it does not
2585 /// sprout a bottom tab bar, and an app that did would look like a port. The phones and the web
2586 /// are the opposite: those are the surfaces whose window size ranges from a phone to a
2587 /// desktop, and a tab bar is what their users expect at the narrow end.
2588 ///
2589 /// So this is a statement about the platform's idiom, not about its widget set:
2590 ///
2591 /// - `Native`/`Emulated`: `NavStyle::Automatic` may resolve to
2592 /// [`props::NavPresentation::Tabs`] on a compact window (ios-uikit, android-material,
2593 /// harmony-arkui, web-dom).
2594 /// - `Unsupported`: it may not; a compact window collapses to
2595 /// [`props::NavPresentation::Stack`] instead, exactly as `NavStyle::Sidebar` has always
2596 /// done (macos-appkit, linux-gtk, linux-qt, windows-winui).
2597 ///
2598 /// [`props::NavPresentation::Rail`] is not gated by this. A narrow sidebar is an ordinary
2599 /// desktop shape (on Windows it is what `NavigationView` does at that width on its own), so
2600 /// the rail rung stays available everywhere `Cap::NavSplit` is.
2601 NavTabsAdaptive,
2602 /// How a navigation host's presentation follows the window (docs/size-classes.md). All three
2603 /// answers mean something different here, and the difference is who decides:
2604 ///
2605 /// - `Native`: **Day tells the toolkit.** The pieces layer resolves the presentation from
2606 /// the [`SizeClass`], re-resolves on every change, and sends
2607 /// [`props::NavPatch::Presentation`]; the toolkit rebuilds its chrome and re-homes the
2608 /// pages it already has. The desktops and web-dom.
2609 /// - `Emulated`: **the toolkit tells Day.** Its own adaptive container owns the decision
2610 /// (`UISplitViewController` collapsing as a Pro Max iPhone rotates, `SlidingPaneLayout`
2611 /// measuring whether both panes fit), so Day must not push a presentation into it: that
2612 /// would be a second decision racing the platform's own animation. The toolkit
2613 /// reports what it did with [`Event::NavPresentationChanged`] and Day reconciles.
2614 /// - `Unsupported`: nobody re-presents. The presentation is resolved once, from
2615 /// [`Cap::NavSplit`] alone, and the window's size never enters into it. A toolkit that
2616 /// cannot change presentation must not have it decided by something that can, or a window
2617 /// launched narrow would be stuck stacked with no way back.
2618 NavRepresent,
2619 /// The toolkit places a navigation host's content-list page ([`props::Pane::List`]) in its
2620 /// own pane between the sidebar and the detail, the Mail shape: mailboxes, message list,
2621 /// message (docs/navigation.md). The three answers differ on what happens when the host
2622 /// leaves the split:
2623 ///
2624 /// - `Native`: the pane exists at every presentation. A narrow window collapses the
2625 /// sidebar but keeps the list beside the detail, exactly as a narrow Mail.app does
2626 /// (macos-appkit: a `contentList` `NSSplitViewItem`).
2627 /// - `Emulated`: the pane exists while split and merges into the navigation stack when
2628 /// the host collapses (ios-uikit: `UISplitViewController` triple-column). The pieces
2629 /// layer then interposes the list between the sidebar root and the detail
2630 /// ([`props::NavPatch::ListInStack`]) and gates the detail push on the app's
2631 /// `detail_visible` binding.
2632 /// - `Unsupported`: the backend never sees [`props::Pane::List`] or
2633 /// [`props::NavProps::list_width`]; the nav piece composes the pane beside (split)
2634 /// or in place of (stacked) the destination content itself.
2635 NavContentList,
2636 /// The toolkit shows the current destination's title in a native header/bar, so a page
2637 /// needn't repeat it in its own content. `Native` on XAML (the NavigationView header),
2638 /// UIKit (`UINavigationBar`), Android (`MaterialToolbar`), and ArkUI (`NavDestination`
2639 /// title bars). The desktop custom back-headers (AppKit/Qt/web) show a title only in
2640 /// stack mode, so those backends stay `Unsupported` (docs/navigation.md).
2641 NavHeader,
2642 /// The toolkit applies a runtime appearance override (`set_appearance`): native widgets
2643 /// restyle in place and `dark_mode` answers the override. Probe before showing a theme
2644 /// picker; on `Unsupported` backends the call is ignored.
2645 Appearance,
2646 /// The toolkit renders an application menu bar (docs/menus.md), so `app_menu` is visible to
2647 /// the user, and `register_preferences` gets its automatic Settings… item.
2648 ///
2649 /// The question an app asks before deciding where a command lives. Settings is the usual
2650 /// case: on a platform with a menu bar it belongs in the App menu and putting it in the
2651 /// navigation as well is clutter; on one without, the menu is a no-op and a Settings row is
2652 /// the only way in. Distinct from `Cap::Toolbar`: web-dom draws a window toolbar and has no
2653 /// menu bar at all, so keying off the toolbar strands Settings there.
2654 AppMenu,
2655 /// The toolkit can present native alert/confirm/sheet/prompt modals (docs/dialogs.md).
2656 Dialogs,
2657 /// The toolkit can present native open/save file pickers (docs/files.md).
2658 FileDialogs,
2659 /// The toolkit can present a native folder chooser (`PresentSpec::OpenFolder`,
2660 /// docs/files.md). `Native` on the four desktop toolkits (AppKit, GTK, Qt, WinUI); the
2661 /// phone and web backends answer `Unsupported` and resolve the request as `Dismissed`, so
2662 /// an app hides its "Add Folder…" command where this is not `Native`.
2663 FolderDialog,
2664 /// The toolkit runs backend-executed animation for `AnimSpec` intents on
2665 /// `update`/`set_frame`/`set_opacity`/`set_transform` (§8.4). `Unsupported` ⇒ animated calls
2666 /// apply instantly (still correct, just not animated).
2667 Animation,
2668 /// The toolkit presents a `kinds::COVER` node as a native fullscreen modal surface
2669 /// (docs/cover.md). `Unsupported` ⇒ the `cover` piece's content never shows.
2670 Cover,
2671 /// The toolkit presents a `.sheet()` cover as a native modal sheet (AppKit's window sheet,
2672 /// UIKit's page sheet) over the page it covers (docs/cover.md "Modal sheet"). `Unsupported`
2673 /// ⇒ the `cover` piece composes the sheet itself: on a window wider than compact, a card
2674 /// centered over the dimmed page; on a compact one, the full window.
2675 CoverSheet,
2676 /// The toolkit can hide the system status bar while a `status_bar_hidden` subtree is
2677 /// mounted (`Toolkit::set_status_bar_hidden`, docs/cover.md). `Native` on the phone and
2678 /// tablet backends; desktop and web have no status bar, so a setting that offers to hide
2679 /// it should be offered only where this is not `Unsupported`.
2680 StatusBarHidden,
2681 /// The toolkit's `text_area` can be made read-only (`TextAreaProps::editable = false`).
2682 TextEditable,
2683 /// The toolkit's `text_area` selectability can be toggled (`TextAreaProps::selectable`).
2684 /// `Unsupported` where selection is always on (GTK); `Emulated` where the backend
2685 /// collapses native selections itself (XAML, ArkUI).
2686 TextSelectable,
2687 /// The toolkit's `text_area` has built-in spell-check/autocorrect (`TextAreaProps::spellcheck`).
2688 /// `Unsupported` where the toolkit ships none (GTK, Qt, ArkUI).
2689 TextSpellCheck,
2690 /// The toolkit can open additional native OS windows (`Toolkit::open_window`,
2691 /// docs/windows.md). `Native` on the desktop backends and on mobile backends whose
2692 /// platform has a real secondary-window surface (iPad scenes, Android document
2693 /// activities, OHOS multiton abilities). On `Unsupported` backends
2694 /// `day_core::open_window` still works; the content presents as a fullscreen cover in
2695 /// the primary window instead. Probe it to adapt chrome: an `Unsupported` tier has no
2696 /// native title bar or close button, so window content should carry its own close
2697 /// affordance.
2698 MultiWindow,
2699 /// The toolkit can put a count on the app icon (`Toolkit::set_app_badge`, docs/badge.md).
2700 /// `Emulated` where the call is made but the shell may ignore it: desktop Linux, where the
2701 /// Unity launcher protocol is honored by Plasma and Dash-to-Dock but not by stock GNOME.
2702 AppBadgeCount,
2703 /// The toolkit renders `AppBadge::Text` as written. macOS only: `NSDockTile.badgeLabel` is an
2704 /// arbitrary string, while every other platform's badge is a number or nothing.
2705 AppBadgeText,
2706 /// The toolkit can show a valueless indicator (`AppBadge::Dot`).
2707 AppBadgeDot,
2708 /// The toolkit gives a window chrome that persists across pages
2709 /// (`Toolkit::edit_toolbar`, docs/toolbars.md): `Native` on the desktop backends and the
2710 /// phones, `Emulated` on web-dom, `Unsupported` where the only chrome belongs to a page.
2711 ///
2712 /// It no longer decides whether a command can be shown at all: a toolbar item declared on a
2713 /// piece rides that piece's own chrome everywhere. Probe it only for a layout decision that
2714 /// turns on a persistent bar existing.
2715 Toolbar,
2716 /// The window toolbar can hold a search field (docs/search.md): `Native` on the desktop
2717 /// backends, `Emulated` on web-dom. `Unsupported` on the phones, whose bar is a row of actions
2718 /// (an Android app-bar menu, iOS bar buttons, ArkUI title-bar menus): their field goes on the
2719 /// navigation surface instead, so `SearchPlacement::Toolbar` resolves to `Inline` there.
2720 ToolbarSearch,
2721 /// The toolkit realizes `kinds::INSPECTOR` as its own trailing-pane container
2722 /// (docs/inspector.md): an `NSSplitView` inspector pane, a `GtkPaned` with the panel as
2723 /// its end child, a `QDockWidget`, a XAML `SplitView` right pane. `Unsupported` ⇒ the
2724 /// `inspector` piece composes the pane from plain containers instead (same panel, same
2725 /// signal, no native divider), so an unimplemented backend degrades to a drawn pane, not
2726 /// to a hole. Apps normally have no reason to probe this; the piece does.
2727 Inspector,
2728 /// The toolkit realizes `kinds::SPLIT` as its own splitter (docs/split.md): an
2729 /// `NSSplitView`, a `GtkPaned`, a `QSplitter`, each side by side or stacked and with the
2730 /// divider the user drags. `Unsupported` ⇒ the `split` piece composes the two panes and
2731 /// draws and drags the divider itself (the web, the mobile toolkits, XAML), so the piece
2732 /// behaves the same everywhere and only the divider's look is the toolkit's. Apps have no
2733 /// reason to probe this; the piece does.
2734 Split,
2735 /// The toolkit shapes the pointer over a node from the `.cursor()` decorator
2736 /// ([`Toolkit::set_cursor`], docs/cursor.md). `Native` where the platform draws the requested
2737 /// shape from its own set (AppKit, GTK, the DOM, Android's `PointerIcon`), `Emulated` where
2738 /// some shapes map to a nearest neighbor (Qt, XAML) or the platform draws pointer effects
2739 /// rather than shapes (iPadOS), `Unsupported` where nothing changes: a touch-only toolkit,
2740 /// or one whose pointer API Day does not reach yet. Apps ask before offering an affordance
2741 /// that only a cursor reveals, such as a resize handle with no other visual.
2742 Cursor,
2743 /// The toolkit can enumerate the platform's font families with the faces each ships
2744 /// ([`Toolkit::font_families`], docs/fonts.md). `Native` where an OS font database answers
2745 /// (NSFontManager, UIFont, Pango, QFontDatabase, Android's `fonts.xml`,
2746 /// `OH_Drawing_FontMgr`, DirectWrite); `Emulated` where the list is composed rather than
2747 /// read: web-dom answers the CSS generic families plus the bundled `document.fonts`, since
2748 /// a browser exposes no local font list without a permission prompt; `Unsupported` means
2749 /// the list is empty and an app should offer only the default face. Measurement
2750 /// ([`Toolkit::measure_text`]) has no probe: a `None` answer degrades to
2751 /// [`TextMetrics::approximate`]. Probe this before offering a font menu, not before
2752 /// drawing; a [`CanvasFont`] draws everywhere.
2753 FontList,
2754 /// The toolkit reads the user's reduce-motion setting ([`Toolkit::reduce_motion`],
2755 /// docs/accessibility.md) and reports when it changes. `Native` where the platform has the
2756 /// switch and Day reaches it; `Unsupported` where Day reaches none (the app then animates as
2757 /// it would with the setting off, and `DAY_REDUCE_MOTION=1` still forces it on).
2758 ReduceMotion,
2759 /// The toolkit can speak a sentence through the screen reader without moving its focus
2760 /// ([`Toolkit::announce`], docs/accessibility.md): "Saved", "3 results", "Upload failed".
2761 /// `Native` where the platform has an announcement request (`NSAccessibility`'s
2762 /// announcement notification, `UIAccessibility`'s, Android's accessibility event, GTK
2763 /// 4.14's `gtk_accessible_announce`, a WinUI notification event); `Emulated` on the web,
2764 /// where an ARIA live region carries it; `Unsupported` where Day reaches no announcement
2765 /// API yet. An app with a visible status label needs no announcement: screen readers read
2766 /// what changes on screen only when told to, so this is for the change the user cannot
2767 /// otherwise learn about.
2768 Announce,
2769 /// The toolkit can turn encoded image bytes into a native image
2770 /// ([`Toolkit::decode_image`], docs/images.md): what `image(bytes)`, a pasted screenshot and
2771 /// a canvas image all rest on. `Native` wherever the platform decoder takes a buffer;
2772 /// `Unsupported` means only staged asset names draw, so an app should not offer "open an
2773 /// image" at all. Every backend that decodes also answers [`Toolkit::image_info`], so pixel
2774 /// size needs no probe of its own.
2775 ImageDecode,
2776 /// The toolkit can encode a decoded image back to bytes ([`Toolkit::encode_image`]).
2777 /// Which formats it encodes is [`Toolkit::encode_formats`], the same shape as
2778 /// [`Cap::FontList`]/[`Toolkit::font_families`], because "can encode" and "can encode WebP"
2779 /// are different questions and only the second one needs a list.
2780 ImageEncode,
2781 /// The toolkit can read an image's metadata beyond its pixels: EXIF orientation, DPI,
2782 /// capture time ([`Toolkit::image_properties`]). `Native` where a platform metadata reader
2783 /// is already linked (WinRT's `BitmapPropertiesView`, Android's `ExifInterface`);
2784 /// `Unsupported` where reading it would mean shipping a parser or a new framework, which is
2785 /// most places. An app that wants orientation must handle `None`.
2786 ImageProperties,
2787 /// The toolkit can replay a canvas drawing into an offscreen bitmap
2788 /// ([`Toolkit::render_bitmap`], docs/canvas.md "Exporting"): what `Drawing::to_bitmap` and
2789 /// `Drawing::to_png` rest on. `Native` where the toolkit's own canvas painter can target an
2790 /// image surface (a `CGBitmapContext`, a cairo image surface, a `QImage`, an android
2791 /// `Bitmap`, an `OH_Drawing_Bitmap`, a detached `<canvas>`); `Unsupported` where the
2792 /// on-screen canvas has no painter to retarget (WinUI builds XAML shapes instead).
2793 CanvasBitmap,
2794 /// The toolkit can replay canvas drawings into a PDF document ([`Toolkit::render_pdf`],
2795 /// docs/canvas.md "Exporting"), with vector shapes and the platform's own font embedding.
2796 /// `Native` only where the platform ships a PDF writer the canvas painter can draw into
2797 /// (Core Graphics on AppKit and UIKit, cairo on GTK, `QPdfWriter` on Qt, `PdfDocument` on
2798 /// Android); `Unsupported` on ArkUI, the web and WinUI, which have none.
2799 CanvasPdf,
2800 /// The toolkit minimizes, zooms, hides and restores a window on request
2801 /// ([`WindowChange::State`], [`WindowChange::Visible`], docs/windows.md) and reports what the
2802 /// user does through [`Event::WindowStateChanged`]. `Native` on the desktop backends;
2803 /// `Unsupported` on the phones and the web, whose windows the OS sizes.
2804 WindowStates,
2805 /// The toolkit takes a window fullscreen on request and reports when it enters and leaves
2806 /// ([`WindowState::Fullscreen`]). `Native` on the desktops, on Android (system bars hidden
2807 /// through `WindowInsetsController`), on HarmonyOS and on the web (the Fullscreen API, which
2808 /// browsers allow only during a user gesture); `Emulated` on iOS, which hides the status bar
2809 /// and lets the home indicator fade but always keeps the app full-screen anyway.
2810 WindowFullscreen,
2811 /// The toolkit keeps a window out of screenshots, recordings and screen sharing
2812 /// ([`WindowChange::ContentProtected`]). `Native` on macOS (`NSWindowSharingNone`), Windows
2813 /// (`WDA_EXCLUDEFROMCAPTURE`), Android (`FLAG_SECURE`) and HarmonyOS (privacy mode);
2814 /// `Emulated` on iOS, which has no switch for it: Day covers the content while the screen is
2815 /// being recorded or mirrored, but a screenshot still captures it. `Unsupported` on Linux
2816 /// and the web.
2817 ContentProtection,
2818 /// The toolkit honors [`WindowOptions::tabbing`]: macOS window tabs. `Unsupported` everywhere
2819 /// else, where no system window tabs exist.
2820 WindowTabbing,
2821 /// The toolkit shows a Dock menu ([`Toolkit::set_dock_menu`], docs/menus.md): the app's
2822 /// shortcuts and `dock_menu(..)` entries above the system's own items. macOS only.
2823 DockMenu,
2824 /// The toolkit resizes a window and bounds its size on request ([`WindowChange::Frame`]'s
2825 /// size, [`WindowChange::Limits`], [`WindowChange::Resizable`]).
2826 WindowGeometry,
2827 /// The toolkit moves a window to a requested position ([`WindowChange::Frame`]'s origin).
2828 /// `Unsupported` on GTK 4, which removed window positioning, and wherever the compositor owns
2829 /// placement (Wayland).
2830 WindowPosition,
2831 /// The toolkit changes how a window stacks ([`WindowChange::Level`],
2832 /// [`WindowChange::OnAllWorkspaces`], [`WindowChange::SkipTaskbar`]).
2833 WindowLevel,
2834 /// The toolkit gives one window its own light/dark appearance ([`WindowChange::Appearance`]).
2835 /// Where it cannot, the app-wide [`Toolkit::set_appearance`] still applies to every window.
2836 WindowAppearance,
2837 /// The toolkit asks for the user's attention on request ([`WindowChange::RequestAttention`]):
2838 /// a Dock bounce, a flashing taskbar button.
2839 RequestAttention,
2840 /// The toolkit opens a window with no title bar or frame ([`WindowChrome::Frameless`],
2841 /// docs/window-chrome.md). Desktop backends only.
2842 FramelessWindow,
2843 /// The toolkit runs a window's content under its title bar with the window controls kept
2844 /// ([`WindowChrome::Overlay`]) and reports the bar's height as the safe-area top inset.
2845 OverlayTitleBar,
2846 /// The toolkit opens a window whose unpainted pixels show the desktop
2847 /// ([`WindowBackground::Transparent`]).
2848 TransparentWindow,
2849 /// The toolkit puts a translucent system material behind a window
2850 /// ([`WindowBackground::Material`]): macOS's visual-effect materials, Windows 11's Mica and
2851 /// Acrylic. `Emulated` where an approximation stands in.
2852 WindowMaterial,
2853 /// The toolkit lets a piece move its window like a title bar does
2854 /// ([`Toolkit::set_drag_region`], `.window_drag_region()`). `Emulated` on the web, where
2855 /// only an installed app with a window-controls overlay honors it.
2856 DragRegion,
2857 /// The toolkit shows status items ([`Toolkit::set_status_items`], docs/status-item.md): the
2858 /// macOS menu bar, the Windows notification area, a Linux tray. On Linux the answer depends
2859 /// on the desktop: `Native` while a StatusNotifierItem host is running (KDE Plasma, most
2860 /// panels, GNOME with the AppIndicator extension), `Unsupported` without one (stock GNOME),
2861 /// so an app can keep a window instead of vanishing into a tray nobody shows.
2862 StatusItem,
2863 /// The toolkit shows progress on the app's Dock or taskbar icon
2864 /// ([`Toolkit::set_app_progress`]). `Emulated` on Linux, where the Unity launcher protocol is
2865 /// honored by KDE Plasma and Dash to Dock but not by every dock.
2866 AppProgress,
2867 /// The toolkit can hide the app's Dock icon while it runs ([`Toolkit::set_dock_visible`]).
2868 /// macOS only.
2869 DockVisibility,
2870 /// The toolkit lists the displays and their work areas ([`Toolkit::monitors`]). `Emulated`
2871 /// where the one screen the app runs on is reported (a phone, the web).
2872 Monitors,
2873 /// The toolkit shows launcher shortcuts the app sets while it runs
2874 /// ([`Toolkit::set_launcher_shortcuts`]).
2875 DynamicShortcuts,
2876 /// How the toolkit draws a sectioned list's headers (`ListProps::sections`, docs/list.md
2877 /// "Sections"). `Native` where the platform's list has group headers that pin to the top
2878 /// while their section scrolls under them: macos-appkit (`NSTableView` group rows with
2879 /// `floatsGroupRows`) and ios-uikit (plain-style `UITableView` section headers).
2880 /// `Emulated` where the host pins a copy of the current header over the top of the list
2881 /// itself. Headers are unselectable rows on every toolkit, so an app needs this only to
2882 /// describe the difference, never to decide whether to call `.sections`.
2883 ListSections,
2884}
2885
2886impl Cap {
2887 /// Every capability, in declaration order: what a conformance run asks the toolkit about,
2888 /// so the evidence can be held against the declared coverage matrix (docs/testing.md).
2889 pub const ALL: [Cap; 90] = [
2890 Cap::DragDrop,
2891 Cap::DragExternalImport,
2892 Cap::DragExternalExport,
2893 Cap::DragMultipleItems,
2894 Cap::DragFileReferences,
2895 Cap::DragDeferredReceipt,
2896 Cap::DragFilePromises,
2897 Cap::DragExternalMove,
2898 Cap::ListRecycling,
2899 Cap::UndoBridge,
2900 Cap::EditBridge,
2901 Cap::ListReorder,
2902 Cap::NavReorder,
2903 Cap::ListDelete,
2904 Cap::ListSwipeActions,
2905 Cap::Tree,
2906 Cap::TreeMove,
2907 Cap::BaselineAlignment,
2908 Cap::TextRuns,
2909 Cap::TextLinks,
2910 Cap::Lottie,
2911 Cap::NativeSymbols,
2912 Cap::Snapshot,
2913 Cap::NavSplit,
2914 Cap::NavTabs,
2915 Cap::NavTabsAdaptive,
2916 Cap::NavRepresent,
2917 Cap::NavContentList,
2918 Cap::NavHeader,
2919 Cap::Appearance,
2920 Cap::AppMenu,
2921 Cap::Dialogs,
2922 Cap::FileDialogs,
2923 Cap::Animation,
2924 Cap::Cover,
2925 Cap::StatusBarHidden,
2926 Cap::TextEditable,
2927 Cap::TextSelectable,
2928 Cap::TextSpellCheck,
2929 Cap::MultiWindow,
2930 Cap::AppBadgeCount,
2931 Cap::AppBadgeText,
2932 Cap::AppBadgeDot,
2933 Cap::Toolbar,
2934 Cap::ToolbarSearch,
2935 Cap::Inspector,
2936 Cap::Cursor,
2937 Cap::FontList,
2938 Cap::ReduceMotion,
2939 Cap::Announce,
2940 Cap::ImageDecode,
2941 Cap::ImageEncode,
2942 Cap::ImageProperties,
2943 Cap::WindowStates,
2944 Cap::WindowFullscreen,
2945 Cap::ContentProtection,
2946 Cap::WindowTabbing,
2947 Cap::DockMenu,
2948 Cap::WindowGeometry,
2949 Cap::WindowPosition,
2950 Cap::WindowLevel,
2951 Cap::WindowAppearance,
2952 Cap::RequestAttention,
2953 Cap::FramelessWindow,
2954 Cap::OverlayTitleBar,
2955 Cap::TransparentWindow,
2956 Cap::WindowMaterial,
2957 Cap::DragRegion,
2958 Cap::StatusItem,
2959 Cap::AppProgress,
2960 Cap::DockVisibility,
2961 Cap::Monitors,
2962 Cap::DynamicShortcuts,
2963 Cap::Split,
2964 Cap::TreeSections,
2965 Cap::CoverSheet,
2966 Cap::ListEditing,
2967 Cap::ListItem,
2968 Cap::CanvasBitmap,
2969 Cap::CanvasPdf,
2970 Cap::SearchField,
2971 Cap::ComboBox,
2972 Cap::Stepper,
2973 Cap::DateTimePicker,
2974 Cap::ColorPicker,
2975 Cap::PullRefresh,
2976 Cap::Pager,
2977 Cap::PullRefreshGesture,
2978 Cap::FolderDialog,
2979 Cap::ListSections,
2980 ];
2981
2982 /// The capability's place in [`Cap::ALL`]. Exhaustive, so a new variant fails to compile
2983 /// here until it is given one, and the unit test below then holds `ALL` to it.
2984 pub const fn ordinal(self) -> usize {
2985 match self {
2986 Cap::DragDrop => 0,
2987 Cap::DragExternalImport => 1,
2988 Cap::DragExternalExport => 2,
2989 Cap::DragMultipleItems => 3,
2990 Cap::DragFileReferences => 4,
2991 Cap::DragDeferredReceipt => 5,
2992 Cap::DragFilePromises => 6,
2993 Cap::DragExternalMove => 7,
2994 Cap::ListRecycling => 8,
2995 Cap::UndoBridge => 9,
2996 Cap::EditBridge => 10,
2997 Cap::ListReorder => 11,
2998 Cap::NavReorder => 12,
2999 Cap::ListDelete => 13,
3000 Cap::ListSwipeActions => 14,
3001 Cap::Tree => 15,
3002 Cap::TreeMove => 16,
3003 Cap::BaselineAlignment => 17,
3004 Cap::TextRuns => 18,
3005 Cap::TextLinks => 19,
3006 Cap::Lottie => 20,
3007 Cap::NativeSymbols => 21,
3008 Cap::Snapshot => 22,
3009 Cap::NavSplit => 23,
3010 Cap::NavTabs => 24,
3011 Cap::NavTabsAdaptive => 25,
3012 Cap::NavRepresent => 26,
3013 Cap::NavContentList => 27,
3014 Cap::NavHeader => 28,
3015 Cap::Appearance => 29,
3016 Cap::AppMenu => 30,
3017 Cap::Dialogs => 31,
3018 Cap::FileDialogs => 32,
3019 Cap::Animation => 33,
3020 Cap::Cover => 34,
3021 Cap::StatusBarHidden => 35,
3022 Cap::TextEditable => 36,
3023 Cap::TextSelectable => 37,
3024 Cap::TextSpellCheck => 38,
3025 Cap::MultiWindow => 39,
3026 Cap::AppBadgeCount => 40,
3027 Cap::AppBadgeText => 41,
3028 Cap::AppBadgeDot => 42,
3029 Cap::Toolbar => 43,
3030 Cap::ToolbarSearch => 44,
3031 Cap::Inspector => 45,
3032 Cap::Cursor => 46,
3033 Cap::FontList => 47,
3034 Cap::ReduceMotion => 48,
3035 Cap::Announce => 49,
3036 Cap::ImageDecode => 50,
3037 Cap::ImageEncode => 51,
3038 Cap::ImageProperties => 52,
3039 Cap::WindowStates => 53,
3040 Cap::WindowFullscreen => 54,
3041 Cap::ContentProtection => 55,
3042 Cap::WindowTabbing => 56,
3043 Cap::DockMenu => 57,
3044 Cap::WindowGeometry => 58,
3045 Cap::WindowPosition => 59,
3046 Cap::WindowLevel => 60,
3047 Cap::WindowAppearance => 61,
3048 Cap::RequestAttention => 62,
3049 Cap::FramelessWindow => 63,
3050 Cap::OverlayTitleBar => 64,
3051 Cap::TransparentWindow => 65,
3052 Cap::WindowMaterial => 66,
3053 Cap::DragRegion => 67,
3054 Cap::StatusItem => 68,
3055 Cap::AppProgress => 69,
3056 Cap::DockVisibility => 70,
3057 Cap::Monitors => 71,
3058 Cap::DynamicShortcuts => 72,
3059 Cap::Split => 73,
3060 Cap::TreeSections => 74,
3061 Cap::CoverSheet => 75,
3062 Cap::ListEditing => 76,
3063 Cap::ListItem => 77,
3064 Cap::CanvasBitmap => 78,
3065 Cap::CanvasPdf => 79,
3066 Cap::SearchField => 80,
3067 Cap::ComboBox => 81,
3068 Cap::Stepper => 82,
3069 Cap::DateTimePicker => 83,
3070 Cap::ColorPicker => 84,
3071 Cap::PullRefresh => 85,
3072 Cap::Pager => 86,
3073 Cap::PullRefreshGesture => 87,
3074 Cap::FolderDialog => 88,
3075 Cap::ListSections => 89,
3076 }
3077 }
3078}
3079
3080// ---------------------------------------------------------------------------
3081// Raster images (docs/images.md): the currency shared by the `image` piece, the canvas, and
3082// the decode/metadata/encode duties below.
3083// ---------------------------------------------------------------------------
3084
3085/// A decoded image the toolkit holds, addressed by an id day-core mints.
3086///
3087/// Opaque, because what sits behind it is an `NSImage`, a `UIImage`, a `GdkTexture`, a
3088/// `QPixmap`, a `BitmapImage`, an android `Bitmap` or an `ImageBitmap`, and none of those cross
3089/// the boundary. The id is released through [`Toolkit::release_image`] when the app's handle
3090/// drops, so a backend's side table never outlives the app's interest in it.
3091#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
3092pub struct BitmapId(pub u64);
3093
3094/// An encoded image format: what [`BitmapInfo::format`] reports and [`EncodeSpec::format`] asks
3095/// for. Not every backend encodes every one: ask [`Toolkit::encode_formats`] (the
3096/// [`Cap::ImageEncode`] pair of [`Toolkit::font_families`]/[`Cap::FontList`]) rather than
3097/// assuming.
3098#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default)]
3099pub enum ImageFormat {
3100 #[default]
3101 Png,
3102 Jpeg,
3103 Webp,
3104 Gif,
3105 Bmp,
3106 Tiff,
3107 /// HEIF/HEIC, Apple's camera format; decodable on the Apple backends and Android, and
3108 /// encodable almost nowhere.
3109 Heif,
3110 /// Decoded from bytes whose magic numbers [`ImageFormat::sniff`] does not know. A backend may
3111 /// still decode it: the platform decoders read more formats than Day names.
3112 Unknown,
3113}
3114
3115impl ImageFormat {
3116 /// The IANA media type, which is also the string the ArkUI packer, GDI+ and the browser's
3117 /// `toBlob` take. `Unknown` answers `application/octet-stream`.
3118 pub fn mime(self) -> &'static str {
3119 match self {
3120 ImageFormat::Png => "image/png",
3121 ImageFormat::Jpeg => "image/jpeg",
3122 ImageFormat::Webp => "image/webp",
3123 ImageFormat::Gif => "image/gif",
3124 ImageFormat::Bmp => "image/bmp",
3125 ImageFormat::Tiff => "image/tiff",
3126 ImageFormat::Heif => "image/heif",
3127 ImageFormat::Unknown => "application/octet-stream",
3128 }
3129 }
3130
3131 /// The pixel size the encoded bytes declare, read from the container's own header
3132 /// (docs/images.md).
3133 ///
3134 /// Every backend that decodes natively reports its own dimensions; this exists for the one
3135 /// that cannot. The XAML backend's (`windows-winui`) `BitmapImage` learns its size
3136 /// asynchronously, only once the element has been shown, so a synchronous `image_info` there
3137 /// would have nothing to say.
3138 /// Reading the header instead gives the same answer the decoder would, before any decoding.
3139 ///
3140 /// `None` when the header is absent, truncated, or a container this does not parse.
3141 pub fn dimensions(bytes: &[u8]) -> Option<(u32, u32)> {
3142 let be16 = |i: usize| -> Option<u32> {
3143 Some(u32::from(u16::from_be_bytes([
3144 *bytes.get(i)?,
3145 *bytes.get(i + 1)?,
3146 ])))
3147 };
3148 let le16 = |i: usize| -> Option<u32> {
3149 Some(u32::from(u16::from_le_bytes([
3150 *bytes.get(i)?,
3151 *bytes.get(i + 1)?,
3152 ])))
3153 };
3154 let be32 = |i: usize| -> Option<u32> {
3155 Some(u32::from_be_bytes([
3156 *bytes.get(i)?,
3157 *bytes.get(i + 1)?,
3158 *bytes.get(i + 2)?,
3159 *bytes.get(i + 3)?,
3160 ]))
3161 };
3162 let le32 = |i: usize| -> Option<u32> {
3163 Some(u32::from_le_bytes([
3164 *bytes.get(i)?,
3165 *bytes.get(i + 1)?,
3166 *bytes.get(i + 2)?,
3167 *bytes.get(i + 3)?,
3168 ]))
3169 };
3170 match Self::sniff(bytes)? {
3171 // IHDR is always the first chunk: 8-byte signature, 4-byte length, 4-byte type.
3172 ImageFormat::Png => Some((be32(16)?, be32(20)?)),
3173 // The logical screen descriptor follows the 6-byte version stamp, little-endian.
3174 ImageFormat::Gif => Some((le16(6)?, le16(8)?)),
3175 // The DIB header's width/height are signed; a negative height is a top-down bitmap.
3176 ImageFormat::Bmp => Some((
3177 le32(18)?.cast_signed().unsigned_abs(),
3178 le32(22)?.cast_signed().unsigned_abs(),
3179 )),
3180 // Walk the segment chain to the frame header. Every SOF marker carries the size at
3181 // the same offsets; the arithmetic-coded and progressive ones are SOFs too, which is
3182 // why this matches the whole range rather than SOF0 alone. DNL/DHP (0xC4, 0xC8,
3183 // 0xCC) are not frame headers and are skipped like any other segment.
3184 ImageFormat::Jpeg => {
3185 let mut i = 2usize;
3186 // `<=`, not `<`: a frame header that ends the buffer is still a frame header, and
3187 // the size sits in its last four bytes.
3188 while i + 9 <= bytes.len() {
3189 if bytes[i] != 0xFF {
3190 i += 1;
3191 continue;
3192 }
3193 let marker = bytes[i + 1];
3194 // Padding fill bytes and the standalone markers carry no length.
3195 if marker == 0xFF || (0xD0..=0xD9).contains(&marker) || marker == 0x01 {
3196 i += 1;
3197 continue;
3198 }
3199 let is_sof = (0xC0..=0xCF).contains(&marker)
3200 && marker != 0xC4
3201 && marker != 0xC8
3202 && marker != 0xCC;
3203 if is_sof {
3204 // [marker][len:2][precision:1][height:2][width:2]
3205 return Some((be16(i + 7)?, be16(i + 5)?));
3206 }
3207 i += 2 + be16(i + 2)? as usize;
3208 }
3209 None
3210 }
3211 // RIFF: a 12-byte header, then a chunk id. VP8X states the size minus one in 24-bit
3212 // little-endian; lossy VP8 hides it in the 14 low bits after the start code; lossless
3213 // VP8L packs width-1 and height-1 into 14 bits each across four bytes.
3214 ImageFormat::Webp => match bytes.get(12..16)? {
3215 b"VP8X" => {
3216 let w = u32::from(*bytes.get(24)?)
3217 | u32::from(*bytes.get(25)?) << 8
3218 | u32::from(*bytes.get(26)?) << 16;
3219 let h = u32::from(*bytes.get(27)?)
3220 | u32::from(*bytes.get(28)?) << 8
3221 | u32::from(*bytes.get(29)?) << 16;
3222 Some((w + 1, h + 1))
3223 }
3224 b"VP8 " => Some((le16(26)? & 0x3FFF, le16(28)? & 0x3FFF)),
3225 b"VP8L" => {
3226 let bits = le32(21)?;
3227 Some(((bits & 0x3FFF) + 1, ((bits >> 14) & 0x3FFF) + 1))
3228 }
3229 _ => None,
3230 },
3231 // TIFF's IFD is a pointer chase and HEIF's is a box tree; neither is worth parsing
3232 // here, because every backend that reads them decodes natively and answers for itself.
3233 ImageFormat::Tiff | ImageFormat::Heif | ImageFormat::Unknown => None,
3234 }
3235 }
3236
3237 /// The format `bytes` begins with, by magic number: enough to fill [`BitmapInfo::format`]
3238 /// on every backend, including the ones whose decoder never says what it decoded.
3239 ///
3240 /// Hand-rolled rather than a crate: it is a dozen byte comparisons against fixed prefixes,
3241 /// and the alternative is an image-decoding dependency in the one crate that must stay
3242 /// dependency-free.
3243 pub fn sniff(bytes: &[u8]) -> Option<ImageFormat> {
3244 let starts = |sig: &[u8]| bytes.len() >= sig.len() && &bytes[..sig.len()] == sig;
3245 if starts(&[0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a]) {
3246 return Some(ImageFormat::Png);
3247 }
3248 if starts(&[0xff, 0xd8, 0xff]) {
3249 return Some(ImageFormat::Jpeg);
3250 }
3251 if starts(b"GIF87a") || starts(b"GIF89a") {
3252 return Some(ImageFormat::Gif);
3253 }
3254 if starts(b"BM") {
3255 return Some(ImageFormat::Bmp);
3256 }
3257 if starts(&[0x49, 0x49, 0x2a, 0x00]) || starts(&[0x4d, 0x4d, 0x00, 0x2a]) {
3258 return Some(ImageFormat::Tiff);
3259 }
3260 // RIFF....WEBP and ....ftypheic/heix/mif1 both carry their tag past a 4-byte prefix.
3261 if starts(b"RIFF") && bytes.len() >= 12 && &bytes[8..12] == b"WEBP" {
3262 return Some(ImageFormat::Webp);
3263 }
3264 if bytes.len() >= 12 && &bytes[4..8] == b"ftyp" {
3265 let brand = &bytes[8..12];
3266 if brand == b"heic" || brand == b"heix" || brand == b"mif1" || brand == b"msf1" {
3267 return Some(ImageFormat::Heif);
3268 }
3269 }
3270 None
3271 }
3272}
3273
3274/// What a decoded image is, in the terms every backend can answer
3275/// ([`Toolkit::image_info`], docs/images.md).
3276///
3277/// `pixels` is the image's own pixel size, not the points it draws at: an asset that stages at
3278/// 2× reports twice its point size and a `scale` of 2, so an app sizing a frame divides. Bytes
3279/// carry no density, so a decoded buffer always answers `scale: 1.0`.
3280#[derive(Clone, Copy, Debug, Default, PartialEq)]
3281pub struct BitmapInfo {
3282 pub pixels: Size,
3283 /// Pixels per point (1.0 for decoded bytes; 2 or 3 for a catalog/drawable asset that staged
3284 /// a density variant).
3285 pub scale: f64,
3286 /// The encoded format it came from, where the backend knows or [`ImageFormat::sniff`] said.
3287 pub format: Option<ImageFormat>,
3288 pub has_alpha: bool,
3289}
3290
3291/// What [`Toolkit::encode_image`] should produce (docs/images.md).
3292///
3293/// A struct rather than three positional arguments, per docs/api-style.md: the call site reads
3294/// `EncodeSpec { format: ImageFormat::Jpeg, quality: Some(0.8), ..Default::default() }`.
3295#[derive(Clone, Copy, Debug, PartialEq)]
3296pub struct EncodeSpec {
3297 pub format: ImageFormat,
3298 /// Lossy quality in `0.0..=1.0`. `None` takes the platform's default; a lossless format
3299 /// ignores it.
3300 pub quality: Option<f64>,
3301 /// Scale the longest side down to fit this box first (aspect preserved). `None` encodes at
3302 /// the image's own size.
3303 pub fit: Option<Size>,
3304}
3305
3306impl Default for EncodeSpec {
3307 fn default() -> Self {
3308 EncodeSpec {
3309 format: ImageFormat::Png,
3310 quality: None,
3311 fit: None,
3312 }
3313 }
3314}
3315
3316/// The metadata an image file carries beyond its pixels ([`Toolkit::image_properties`]).
3317///
3318/// Sparse by construction: every field is what the platform's own reader answered, and a
3319/// backend with no metadata reader at all answers `None` to the whole call rather than an empty
3320/// struct. Probe [`Cap::ImageProperties`] before offering an affordance that depends on it.
3321#[derive(Clone, Debug, Default, PartialEq)]
3322pub struct ImageProperties {
3323 /// The EXIF orientation tag (1–8), where one was recorded.
3324 pub orientation: Option<u16>,
3325 /// Pixels per inch, where the file records a resolution.
3326 pub dpi: Option<f64>,
3327 /// The capture timestamp as the file spells it (no parsing: the formats disagree).
3328 pub created: Option<String>,
3329 /// Everything else the platform reader named, in its own vocabulary. Keys are the
3330 /// platform's, so read them defensively.
3331 pub extra: Vec<(String, String)>,
3332}
3333
3334/// Why an image operation could not answer.
3335#[derive(Clone, Copy, Debug, PartialEq, Eq)]
3336pub enum ImageError {
3337 /// The bytes are not an image this platform decodes.
3338 Decode,
3339 /// The image decoded, but this backend cannot encode the format asked for. `encode_formats`
3340 /// says which it can.
3341 Encode,
3342 /// The backend has no path for this at all (probe [`Cap::ImageDecode`] /
3343 /// [`Cap::ImageEncode`]).
3344 Unsupported,
3345 /// The id named no live image: released already, or never decoded.
3346 Gone,
3347}
3348
3349impl std::fmt::Display for ImageError {
3350 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3351 match self {
3352 ImageError::Decode => write!(f, "the bytes are not a decodable image"),
3353 ImageError::Encode => write!(f, "this backend cannot encode that format"),
3354 ImageError::Unsupported => write!(f, "image support is unavailable on this backend"),
3355 ImageError::Gone => write!(f, "the image was released"),
3356 }
3357 }
3358}
3359
3360impl std::error::Error for ImageError {}
3361
3362// ---------------------------------------------------------------------------
3363// Canvas export (docs/canvas.md "Exporting"): a recorded drawing replayed into an offscreen
3364// bitmap or a PDF by the same painter the on-screen canvas uses.
3365// ---------------------------------------------------------------------------
3366
3367/// The largest side, in pixels, a rendered bitmap may have (docs/canvas.md "Exporting").
3368/// day-core answers [`ExportError::TooLarge`] above it before any toolkit allocates.
3369pub const EXPORT_MAX_SIDE: u32 = 16_384;
3370
3371/// The most pixels a rendered bitmap may hold in total: 64 megapixels, 256 MB at four bytes a
3372/// pixel, which is already more than the tightest per-app heap (Android's) comfortably holds.
3373pub const EXPORT_MAX_PIXELS: u64 = 64 * 1024 * 1024;
3374
3375/// The pixel size a drawing of `size` points renders to at `scale` pixels per point: each side
3376/// rounded up, so a drawing never loses its last partial pixel. Shared by day-core's limit
3377/// check and every backend, so the bitmap a backend allocates is the one day-core approved.
3378pub fn export_pixels(size: Size, scale: f64) -> (u32, u32) {
3379 let side = |v: f64| (v * scale).ceil().clamp(0.0, u32::MAX as f64) as u32;
3380 (side(size.width), side(size.height))
3381}
3382
3383/// One page of a PDF [`Toolkit::render_pdf`] writes: the page size in PDF points (1/72 inch,
3384/// the same unit as canvas points) and the ops to replay onto it, origin top-left.
3385#[derive(Clone, Debug, PartialEq)]
3386pub struct PdfPage {
3387 pub size: Size,
3388 pub ops: Vec<DrawOp>,
3389}
3390
3391/// The document information a PDF carries. A backend whose writer has no metadata API (Android's
3392/// `PdfDocument`) ignores it.
3393#[derive(Clone, Debug, Default, PartialEq)]
3394pub struct PdfInfo {
3395 pub title: Option<String>,
3396 pub author: Option<String>,
3397}
3398
3399/// Why a canvas export could not answer (docs/canvas.md "Exporting").
3400#[derive(Clone, Debug, PartialEq)]
3401pub enum ExportError {
3402 /// This toolkit has no path for the export (probe [`Cap::CanvasBitmap`] /
3403 /// [`Cap::CanvasPdf`]).
3404 Unsupported,
3405 /// The bitmap would exceed [`EXPORT_MAX_SIDE`] or [`EXPORT_MAX_PIXELS`]; checked in
3406 /// day-core before the toolkit runs. The size is the one that was refused, in pixels.
3407 TooLarge { width: u32, height: u32 },
3408 /// A zero, negative or non-finite size or scale, or a PDF with no pages.
3409 Invalid,
3410 /// The platform refused (out of memory, a writer error); the text is the platform's.
3411 Failed(String),
3412}
3413
3414impl std::fmt::Display for ExportError {
3415 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3416 match self {
3417 ExportError::Unsupported => write!(f, "this export is unavailable on this backend"),
3418 ExportError::TooLarge { width, height } => {
3419 write!(
3420 f,
3421 "a {width} × {height} pixel bitmap is too large to render"
3422 )
3423 }
3424 ExportError::Invalid => write!(f, "the drawing has no size or the PDF has no pages"),
3425 ExportError::Failed(why) => write!(f, "rendering failed: {why}"),
3426 }
3427 }
3428}
3429
3430impl std::error::Error for ExportError {}
3431
3432/// Where a raster image's pixels come from (docs/images.md).
3433///
3434/// One currency for both halves of the same question: `Named` is the staged asset every
3435/// `image(res::images::…)` has always drawn, `Bytes` is an encoded PNG/JPEG the app already
3436/// holds (a download, a file the user picked, a clipboard paste), and `Decoded` names an image
3437/// the toolkit decoded once so several nodes (and the canvas) share it.
3438#[derive(Clone)]
3439pub enum ImageSource {
3440 /// A staged asset name, resolved through the backend's own pipeline (§18.2).
3441 Named(String),
3442 /// Encoded bytes (PNG/JPEG/…) the app owns, decoded by the platform's own decoder. Shared
3443 /// rather than copied: handing over a new buffer is a refcount bump.
3444 Bytes(std::sync::Arc<Vec<u8>>),
3445 /// An image already decoded through [`Toolkit::decode_image`].
3446 Decoded(BitmapId),
3447}
3448
3449impl Default for ImageSource {
3450 fn default() -> Self {
3451 ImageSource::Named(String::new())
3452 }
3453}
3454
3455/// Bytes compare by identity, not content.
3456///
3457/// This is the equality a binding gates on (§4.2), so it runs on every evaluation, and
3458/// comparing two multi-megabyte buffers byte by byte would cost far more than the redundant
3459/// decode it saves. Handing over a distinct buffer holding the same pixels therefore re-decodes,
3460/// which is the same trade `Arc::ptr_eq` makes wherever else Day carries shared buffers.
3461impl PartialEq for ImageSource {
3462 fn eq(&self, other: &Self) -> bool {
3463 match (self, other) {
3464 (ImageSource::Named(a), ImageSource::Named(b)) => a == b,
3465 (ImageSource::Bytes(a), ImageSource::Bytes(b)) => std::sync::Arc::ptr_eq(a, b),
3466 (ImageSource::Decoded(a), ImageSource::Decoded(b)) => a == b,
3467 _ => false,
3468 }
3469 }
3470}
3471
3472/// Logs the buffer's length, never its contents: a `Debug` that dumped a megabyte of pixels
3473/// into a trace line would make the trace useless and slow.
3474impl std::fmt::Debug for ImageSource {
3475 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3476 match self {
3477 ImageSource::Named(n) => f.debug_tuple("Named").field(n).finish(),
3478 ImageSource::Bytes(b) => f.debug_tuple("Bytes").field(&b.len()).finish(),
3479 ImageSource::Decoded(id) => f.debug_tuple("Decoded").field(&id.0).finish(),
3480 }
3481 }
3482}
3483
3484impl From<BitmapId> for ImageSource {
3485 fn from(id: BitmapId) -> Self {
3486 ImageSource::Decoded(id)
3487 }
3488}
3489
3490/// A staged asset name is a source, so `image(res::images::cover)` keeps compiling unchanged.
3491///
3492/// There is no `From<&str>` here, for the same reason [`resource::ImageName`] has none:
3493/// `image("typo")` must stay a compile error rather than a blank view at runtime (resource.rs).
3494/// A path or URL string is not a source either: read the bytes and hand those over.
3495impl From<resource::ImageName> for ImageSource {
3496 fn from(name: resource::ImageName) -> Self {
3497 ImageSource::Named(name.as_str().to_owned())
3498 }
3499}
3500
3501impl From<resource::VectorName> for ImageSource {
3502 fn from(name: resource::VectorName) -> Self {
3503 ImageSource::Named(name.as_str().to_owned())
3504 }
3505}
3506
3507impl From<std::sync::Arc<Vec<u8>>> for ImageSource {
3508 fn from(bytes: std::sync::Arc<Vec<u8>>) -> Self {
3509 ImageSource::Bytes(bytes)
3510 }
3511}
3512
3513/// An owned string is a name, not bytes: the same conversion [`resource::ImageName`] offers for
3514/// a name computed at runtime, and the reason `image(some_string)` keeps compiling. A `&str`
3515/// still converts nowhere, so `image("typo")` stays a compile error (resource.rs).
3516impl From<String> for ImageSource {
3517 fn from(name: String) -> Self {
3518 ImageSource::Named(name)
3519 }
3520}
3521
3522impl From<Vec<u8>> for ImageSource {
3523 fn from(bytes: Vec<u8>) -> Self {
3524 ImageSource::Bytes(std::sync::Arc::new(bytes))
3525 }
3526}
3527
3528#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
3529pub enum Support {
3530 Native,
3531 Emulated,
3532 /// The default: what an unimplemented capability answers everywhere.
3533 #[default]
3534 Unsupported,
3535}
3536
3537/// What a text field collects (`text_field(..).input_purpose(_)`, docs/textfield.md).
3538///
3539/// One word for everything a platform keys off the kind of text: the on-screen keyboard's
3540/// layout, capitalization and correction, and the credential or contact the system offers to
3541/// fill in. A backend applies the parts its toolkit has: a desktop toolkit with no on-screen
3542/// keyboard still takes the autofill and correction half.
3543///
3544/// Purpose is independent of [`InputTraits::secure`]: a numeric PIN is `Number` and secure.
3545#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
3546pub enum InputPurpose {
3547 /// Free text: the default keyboard, with the platform's own capitalization and correction.
3548 #[default]
3549 Text,
3550 /// A person's name: words capitalized, never corrected.
3551 Name,
3552 /// An email address: the `@` keyboard, never capitalized or corrected.
3553 Email,
3554 /// A web address: the URL keyboard, never capitalized or corrected.
3555 Url,
3556 /// A telephone number: the phone pad.
3557 Phone,
3558 /// A whole number: the digit pad.
3559 Number,
3560 /// A number with a fractional part: the digit pad with a decimal separator.
3561 Decimal,
3562 /// An account name: never capitalized or corrected, and offered to the password manager.
3563 Username,
3564 /// An existing password, offered to the password manager for filling.
3565 Password,
3566 /// A password being chosen, so the password manager offers to make and save one.
3567 NewPassword,
3568 /// A code sent by message or mail, which the keyboard offers as it arrives. The keyboard
3569 /// stays the text one, since a code can carry letters.
3570 OneTimeCode,
3571}
3572
3573/// The on-screen keyboard's action key (`text_field(..).submit_label(_)`, docs/textfield.md).
3574///
3575/// The key always fires the field's `on_submit`; this names what it promises. A toolkit with
3576/// no on-screen keyboard ignores it.
3577#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
3578pub enum SubmitLabel {
3579 /// The platform's own key (Return).
3580 #[default]
3581 Return,
3582 Done,
3583 Go,
3584 Next,
3585 Search,
3586 Send,
3587}
3588
3589/// How a text field takes its text (docs/textfield.md): the whole set travels together through
3590/// [`Toolkit::set_input_traits`], so a backend that has to rebuild the widget for one member
3591/// has every other member in hand to dress the replacement.
3592#[derive(Clone, Debug, Default, PartialEq, Eq)]
3593pub struct InputTraits {
3594 /// Hide the characters (a password field).
3595 pub secure: bool,
3596 /// Show and select the text, take no edits.
3597 pub read_only: bool,
3598 pub purpose: InputPurpose,
3599 pub submit_label: SubmitLabel,
3600 /// The most characters (Unicode scalar values) the field takes; `None` is unbounded.
3601 /// day-pieces holds the bound on every backend. A toolkit applies its native limit as well
3602 /// only where that limit counts the same unit (GTK): one that counts UTF-16 units would
3603 /// refuse characters the bound allows.
3604 pub max_length: Option<u32>,
3605}
3606
3607/// The pointer's shape over a piece (the `.cursor()` decorator, docs/cursor.md).
3608///
3609/// The named variants are the CSS cursor vocabulary: the largest set any toolkit accepts as it
3610/// is (GTK and the DOM take the names verbatim), and every other toolkit's set is a subset of it
3611/// or maps onto it. A backend draws its own shape for each name, or the nearest one it has, and
3612/// answers [`Cap::Cursor`] with how faithful that is. [`Cursor::Native`] reaches a shape only one
3613/// toolkit names; the `day::cursor::<toolkit>` modules carry those as constants, gated on that
3614/// toolkit's feature, and every other backend ignores a name it does not know.
3615///
3616/// A cursor applies to the node and its descendants until a descendant sets its own.
3617/// [`Cursor::Default`] hands the shape back to the platform rather than pinning an arrow, so a
3618/// reactive cursor can release what it took.
3619#[derive(Clone, Debug, PartialEq, Eq, Hash, Default)]
3620pub enum Cursor {
3621 /// The platform default (an arrow), and the value that releases a node's cursor.
3622 #[default]
3623 Default,
3624 /// A pointing hand: links and other tap-to-activate content.
3625 Pointer,
3626 /// An I-beam over editable or selectable text.
3627 Text,
3628 /// An I-beam for vertical text.
3629 VerticalText,
3630 Crosshair,
3631 /// Four-way move.
3632 Move,
3633 /// An open hand: content that can be dragged.
3634 Grab,
3635 /// A closed hand: content being dragged.
3636 Grabbing,
3637 NotAllowed,
3638 /// The app is busy and cannot take input.
3639 Wait,
3640 /// The app is busy but still takes input.
3641 Progress,
3642 Help,
3643 ContextMenu,
3644 /// A drop will copy.
3645 Copy,
3646 /// A drop will link.
3647 Alias,
3648 /// A table cell.
3649 Cell,
3650 ZoomIn,
3651 ZoomOut,
3652 /// No pointer at all.
3653 None,
3654 /// Vertical (north–south) resize.
3655 NsResize,
3656 /// Horizontal (east–west) resize.
3657 EwResize,
3658 /// Diagonal resize, north-east to south-west.
3659 NeswResize,
3660 /// Diagonal resize, north-west to south-east.
3661 NwseResize,
3662 ColResize,
3663 RowResize,
3664 /// A toolkit's own named cursor, resolved by that backend's lookup and ignored by every
3665 /// other. Prefer the `day::cursor::<toolkit>` constants, which are gated on the toolkit.
3666 Native(std::borrow::Cow<'static, str>),
3667}
3668
3669impl Cursor {
3670 /// A toolkit-specific cursor by its native name (see [`Cursor::Native`]).
3671 pub const fn native(name: &'static str) -> Self {
3672 Cursor::Native(std::borrow::Cow::Borrowed(name))
3673 }
3674
3675 /// The CSS keyword for a named cursor, which GTK and the DOM take as it is. A native cursor
3676 /// answers its own name, so a backend keyed on CSS names may still recognize it.
3677 pub fn css_name(&self) -> &str {
3678 match self {
3679 Cursor::Default => "default",
3680 Cursor::Pointer => "pointer",
3681 Cursor::Text => "text",
3682 Cursor::VerticalText => "vertical-text",
3683 Cursor::Crosshair => "crosshair",
3684 Cursor::Move => "move",
3685 Cursor::Grab => "grab",
3686 Cursor::Grabbing => "grabbing",
3687 Cursor::NotAllowed => "not-allowed",
3688 Cursor::Wait => "wait",
3689 Cursor::Progress => "progress",
3690 Cursor::Help => "help",
3691 Cursor::ContextMenu => "context-menu",
3692 Cursor::Copy => "copy",
3693 Cursor::Alias => "alias",
3694 Cursor::Cell => "cell",
3695 Cursor::ZoomIn => "zoom-in",
3696 Cursor::ZoomOut => "zoom-out",
3697 Cursor::None => "none",
3698 Cursor::NsResize => "ns-resize",
3699 Cursor::EwResize => "ew-resize",
3700 Cursor::NeswResize => "nesw-resize",
3701 Cursor::NwseResize => "nwse-resize",
3702 Cursor::ColResize => "col-resize",
3703 Cursor::RowResize => "row-resize",
3704 Cursor::Native(name) => name,
3705 }
3706 }
3707
3708 /// Every named cursor, in declaration order, what a gallery or a test walks.
3709 pub const NAMED: [Cursor; 25] = [
3710 Cursor::Default,
3711 Cursor::Pointer,
3712 Cursor::Text,
3713 Cursor::VerticalText,
3714 Cursor::Crosshair,
3715 Cursor::Move,
3716 Cursor::Grab,
3717 Cursor::Grabbing,
3718 Cursor::NotAllowed,
3719 Cursor::Wait,
3720 Cursor::Progress,
3721 Cursor::Help,
3722 Cursor::ContextMenu,
3723 Cursor::Copy,
3724 Cursor::Alias,
3725 Cursor::Cell,
3726 Cursor::ZoomIn,
3727 Cursor::ZoomOut,
3728 Cursor::None,
3729 Cursor::NsResize,
3730 Cursor::EwResize,
3731 Cursor::NeswResize,
3732 Cursor::NwseResize,
3733 Cursor::ColResize,
3734 Cursor::RowResize,
3735 ];
3736}
3737
3738/// A set of screen edges, for the `defers_system_gestures` modifier (docs/cover.md). Mirrors
3739/// SwiftUI's `Edge.Set`: on iOS these map to `UIRectEdge` for
3740/// `preferredScreenEdgesDeferringSystemGestures`; on Android any non-empty set enters
3741/// swipe-to-reveal immersive mode (the closest platform analogue).
3742#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
3743pub struct Edges(pub u8);
3744
3745impl Edges {
3746 pub const NONE: Edges = Edges(0);
3747 pub const TOP: Edges = Edges(1);
3748 pub const BOTTOM: Edges = Edges(2);
3749 pub const LEADING: Edges = Edges(4);
3750 pub const TRAILING: Edges = Edges(8);
3751 pub const ALL: Edges = Edges(15);
3752
3753 pub fn contains(self, other: Edges) -> bool {
3754 self.0 & other.0 == other.0
3755 }
3756 pub fn union(self, other: Edges) -> Edges {
3757 Edges(self.0 | other.0)
3758 }
3759 pub fn is_empty(self) -> bool {
3760 self.0 == 0
3761 }
3762}
3763
3764impl std::ops::BitOr for Edges {
3765 type Output = Edges;
3766 fn bitor(self, rhs: Edges) -> Edges {
3767 self.union(rhs)
3768 }
3769}
3770
3771/// The timing curve of an animation (§8.4). Native backends map each variant onto their own
3772/// easing (`CAMediaTimingFunction`, `QEasingCurve`, ArkUI `ARKUI_CURVE_*`, spring animators); the
3773/// canvas/self-driven path samples it via [`Curve::fraction`]. `Spring` matches SwiftUI's
3774/// `.spring(response:dampingFraction:)`.
3775#[derive(Clone, Copy, Debug, PartialEq)]
3776pub enum Curve {
3777 Linear,
3778 EaseIn,
3779 EaseOut,
3780 EaseInOut,
3781 /// `response` = approximate settling period (seconds); `damping` = damping ratio (1.0 =
3782 /// critically damped, `<1` = bouncy overshoot).
3783 Spring {
3784 response: f64,
3785 damping: f64,
3786 },
3787}
3788
3789impl Curve {
3790 /// Fraction of the transition complete at `elapsed` seconds (0 at start, reaching 1, or
3791 /// overshooting it for an under-damped spring). Easing curves clamp to `duration`; springs
3792 /// evaluate their analytic unit-step response and use `duration` only as a settle cap. Drives
3793 /// the self-driven/canvas path; native backends interpolate on their own compositor instead.
3794 pub fn fraction(self, elapsed: f64, duration: f64) -> f64 {
3795 match self {
3796 Curve::Spring { response, damping } => spring_step(response, damping, elapsed),
3797 _ => {
3798 let t = if duration <= 0.0 {
3799 1.0
3800 } else {
3801 (elapsed / duration).clamp(0.0, 1.0)
3802 };
3803 self.ease(t)
3804 }
3805 }
3806 }
3807
3808 /// Eased progress for normalized `t` in `0.0..=1.0` (springs pass through; use [`Self::fraction`]).
3809 #[inline]
3810 pub fn ease(self, t: f64) -> f64 {
3811 match self {
3812 Curve::Linear | Curve::Spring { .. } => t,
3813 Curve::EaseIn => t * t,
3814 Curve::EaseOut => 1.0 - (1.0 - t) * (1.0 - t),
3815 Curve::EaseInOut => t * t * (3.0 - 2.0 * t), // smoothstep
3816 }
3817 }
3818
3819 /// Whether the transition has settled, so the canvas frame clock can stop ticking it.
3820 pub fn is_settled(self, elapsed: f64, duration: f64) -> bool {
3821 match self {
3822 Curve::Spring { response, damping } => {
3823 let cap = response.max(0.0) * 4.0 + 0.2;
3824 if elapsed >= cap {
3825 return true;
3826 }
3827 (spring_step(response, damping, elapsed) - 1.0).abs() < 0.001
3828 && elapsed > response * 0.5
3829 }
3830 _ => elapsed >= duration.max(0.0),
3831 }
3832 }
3833}
3834
3835/// Unit-step response of a second-order spring (`response` = period seconds, `damping` = ratio),
3836/// evaluated at `t` seconds. Under-damped rings and overshoots; critically/over-damped eases in.
3837fn spring_step(response: f64, damping: f64, t: f64) -> f64 {
3838 if response <= 0.0 || t <= 0.0 {
3839 return if t <= 0.0 { 0.0 } else { 1.0 };
3840 }
3841 let omega0 = std::f64::consts::TAU / response;
3842 let zeta = damping.max(0.0);
3843 if zeta < 1.0 {
3844 let omega_d = omega0 * (1.0 - zeta * zeta).sqrt();
3845 let e = (-zeta * omega0 * t).exp();
3846 1.0 - e * ((omega_d * t).cos() + (zeta * omega0 / omega_d) * (omega_d * t).sin())
3847 } else {
3848 let e = (-omega0 * t).exp();
3849 1.0 - e * (1.0 + omega0 * t)
3850 }
3851}
3852
3853/// Animation intent (§8.4). Native-widget backends map it onto their own animator (Core Animation,
3854/// `ViewPropertyAnimator`, XAML Composition, `OH_ArkUI_AnimateTo`, …); the canvas/self-driven path
3855/// samples `curve` via [`Curve::fraction`]. Threaded through `Toolkit::update`/`set_frame`/
3856/// `set_opacity`/`set_transform`.
3857#[derive(Clone, Copy, Debug, PartialEq)]
3858pub struct AnimSpec {
3859 pub duration_ms: u32,
3860 pub delay_ms: u32,
3861 pub curve: Curve,
3862 /// Repeat count beyond the first play (`0` = play once); `u32::MAX` = repeat forever.
3863 pub repeat: u32,
3864 pub autoreverse: bool,
3865}
3866
3867impl Default for AnimSpec {
3868 /// The default feel: a smooth spring (SwiftUI's modern default).
3869 fn default() -> Self {
3870 AnimSpec {
3871 duration_ms: 350,
3872 delay_ms: 0,
3873 curve: Curve::Spring {
3874 response: 0.4,
3875 damping: 0.8,
3876 },
3877 repeat: 0,
3878 autoreverse: false,
3879 }
3880 }
3881}
3882
3883impl AnimSpec {
3884 /// A smooth spring: `response` = settling period (s), `damping` = ratio (1.0 = no bounce, `<1`
3885 /// bouncy). `duration_ms` is a nominal cap for backends that need a duration; spring backends
3886 /// use `response`/`damping` directly.
3887 pub fn spring(response: f64, damping: f64) -> Self {
3888 AnimSpec {
3889 // `response` is the animation's duration: every backend maps a spring to a
3890 // fixed-duration overshoot curve over exactly `duration_ms`, so timing is identical
3891 // across toolkits (a physics spring's settle time would vary per platform).
3892 duration_ms: (response * 1000.0).max(50.0) as u32,
3893 delay_ms: 0,
3894 curve: Curve::Spring { response, damping },
3895 repeat: 0,
3896 autoreverse: false,
3897 }
3898 }
3899 pub fn linear(duration_ms: u32) -> Self {
3900 Self::timed(duration_ms, Curve::Linear)
3901 }
3902 pub fn ease_in(duration_ms: u32) -> Self {
3903 Self::timed(duration_ms, Curve::EaseIn)
3904 }
3905 pub fn ease_out(duration_ms: u32) -> Self {
3906 Self::timed(duration_ms, Curve::EaseOut)
3907 }
3908 pub fn ease_in_out(duration_ms: u32) -> Self {
3909 Self::timed(duration_ms, Curve::EaseInOut)
3910 }
3911 fn timed(duration_ms: u32, curve: Curve) -> Self {
3912 AnimSpec {
3913 duration_ms,
3914 delay_ms: 0,
3915 curve,
3916 repeat: 0,
3917 autoreverse: false,
3918 }
3919 }
3920 /// Delay before the animation starts (builder).
3921 pub fn delay(mut self, ms: u32) -> Self {
3922 self.delay_ms = ms;
3923 self
3924 }
3925 /// Repeat `count` extra times (builder); `autoreverse` ping-pongs each cycle.
3926 pub fn repeat(mut self, count: u32, autoreverse: bool) -> Self {
3927 self.repeat = count;
3928 self.autoreverse = autoreverse;
3929 self
3930 }
3931 /// Repeat forever (builder), e.g. a pulsing indicator.
3932 pub fn repeat_forever(mut self, autoreverse: bool) -> Self {
3933 self.repeat = u32::MAX;
3934 self.autoreverse = autoreverse;
3935 self
3936 }
3937 #[inline]
3938 pub fn duration_secs(&self) -> f64 {
3939 self.duration_ms as f64 / 1000.0
3940 }
3941 #[inline]
3942 pub fn delay_secs(&self) -> f64 {
3943 self.delay_ms as f64 / 1000.0
3944 }
3945}
3946
3947#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
3948pub enum Role {
3949 #[default]
3950 None,
3951 Button,
3952 Toggle,
3953 Slider,
3954 TextInput,
3955 Heading(u8),
3956 Image,
3957 Meter,
3958 Group,
3959 /// A hierarchical tree container (docs/tree.md): `role="tree"`, `AXOutline`.
3960 Tree,
3961 /// One row of a tree: `role="treeitem"`, with level/expanded state where the platform
3962 /// carries them (docs/tree.md).
3963 TreeItem,
3964 /// One tab in a strip of peers (`role="tab"`, `AXTabButton`): the composed document
3965 /// strip's title buttons. Pair it with [`A11yProps::selected`] for the current one.
3966 Tab,
3967 /// The strip holding tabs (`role="tablist"`, `AXTabGroup`).
3968 TabList,
3969}
3970
3971impl Role {
3972 /// The a11y role a built-in piece kind reports natively, the audit's *expectation* when the
3973 /// user hasn't set an explicit `.role()`. Native controls already expose these, so Day records
3974 /// them for `a11y_audit` (§14.2) rather than overriding the widget; only canvas/custom pieces
3975 /// need Day to apply a role. Returns `None` for kinds with no inherent control role.
3976 pub fn for_kind(kind: PieceKind) -> Role {
3977 match kind {
3978 kinds::BUTTON => Role::Button,
3979 kinds::TOGGLE => Role::Toggle,
3980 kinds::SLIDER => Role::Slider,
3981 kinds::TEXT_FIELD => Role::TextInput,
3982 kinds::IMAGE => Role::Image,
3983 kinds::PROGRESS => Role::Meter,
3984 kinds::TREE => Role::Tree,
3985 _ => Role::None,
3986 }
3987 }
3988}
3989
3990#[derive(Clone, Debug, Default, PartialEq)]
3991pub struct A11yProps {
3992 pub label: Option<String>,
3993 pub hint: Option<String>,
3994 pub value: Option<String>,
3995 pub role: Role,
3996 pub identifier: Option<String>,
3997 pub hidden: bool,
3998 pub decorative: bool,
3999 /// Whether the element is the selected one among its peers (a tab, a row): the
4000 /// platform's selected state, read aloud as such. `None` leaves the widget's own answer.
4001 pub selected: Option<bool>,
4002}
4003
4004impl A11yProps {
4005 /// Merge another set of annotations onto this one: any field `other` sets (a `Some`, a
4006 /// non-`None` role, or a `true` flag) overrides ours; unset fields are left intact. Lets a
4007 /// node accumulate its `.a11y()`, `.id()`, and piece defaults into one stored result, so
4008 /// each `set_a11y` re-applies the full picture and `a11y_audit` has the complete expectation.
4009 pub fn merge(&mut self, other: &A11yProps) {
4010 if other.label.is_some() {
4011 self.label = other.label.clone();
4012 }
4013 if other.hint.is_some() {
4014 self.hint = other.hint.clone();
4015 }
4016 if other.value.is_some() {
4017 self.value = other.value.clone();
4018 }
4019 if other.role != Role::None {
4020 self.role = other.role;
4021 }
4022 if other.identifier.is_some() {
4023 self.identifier = other.identifier.clone();
4024 }
4025 self.hidden |= other.hidden;
4026 self.decorative |= other.decorative;
4027 if other.selected.is_some() {
4028 self.selected = other.selected;
4029 }
4030 }
4031
4032 /// The role to *expect* for a node of `kind` carrying these annotations: an explicit
4033 /// `.role()` wins, otherwise the kind's native default (`Role::for_kind`).
4034 pub fn resolved_role(&self, kind: PieceKind) -> Role {
4035 if self.role != Role::None {
4036 self.role
4037 } else {
4038 Role::for_kind(kind)
4039 }
4040 }
4041}
4042
4043/// A widget's actual native state, read back from the platform by `Toolkit::read_native`
4044/// (docs/testing.md): what the widget itself shows and reports, independently of Day's tree,
4045/// so `a11y_audit` and `assert_native` (§14.2) can diff it against Day's expectation.
4046///
4047/// Two groups. The accessibility fields (`role`, `label`, `value`, `identifier`) are read
4048/// together and `found` says whether they were: `found = false` means the backend cannot read
4049/// its accessibility tree, and the audit skips the node. Every other field is read on its own,
4050/// and `None` means "not read": the backend cannot read it, or it does not apply to this kind.
4051/// A reader never reports a field it did not take from the widget, so a `None` is a recorded
4052/// gap rather than a pass.
4053#[derive(Clone, Debug, Default, PartialEq)]
4054pub struct NativeSnapshot {
4055 /// The accessibility fields below were read.
4056 pub found: bool,
4057 /// The native role mapped back to Day's `Role` (best-effort).
4058 pub role: Role,
4059 /// The accessibility label the platform reports.
4060 pub label: Option<String>,
4061 /// The accessibility value the platform reports.
4062 pub value: Option<String>,
4063 /// The automation identifier, which Day sets from `.id()`.
4064 pub identifier: Option<String>,
4065 /// The text the widget displays: a label's string, a button's title, a text field's or
4066 /// text area's contents, without markup or mnemonic markers. `None` for a secure field
4067 /// that masks it.
4068 pub text: Option<String>,
4069 /// A slider's or progress indicator's value, in the range Day gave it.
4070 pub number: Option<f64>,
4071 /// A toggle's state, or a button's selected state (`ButtonProps::selected`).
4072 pub checked: Option<bool>,
4073 /// Whether the widget takes input.
4074 pub enabled: Option<bool>,
4075 /// Whether the widget is shown: not hidden itself, nor by an ancestor.
4076 pub visible: Option<bool>,
4077 /// The widget's frame in points, relative to the window's content area, origin top left.
4078 pub frame: Option<Rect>,
4079}
4080
4081// ---------------------------------------------------------------------------
4082// Canvas display list (§11): full op set lands with M8a; the types are v1.
4083// ---------------------------------------------------------------------------
4084
4085#[derive(Clone, Debug, PartialEq)]
4086pub enum Shape {
4087 Rect(Rect),
4088 RoundedRect(Rect, f64),
4089 Ellipse(Rect),
4090 /// Arc within `rect`'s inscribed ellipse; angles in degrees, 0 = +x axis, clockwise.
4091 Arc {
4092 rect: Rect,
4093 start_deg: f64,
4094 sweep_deg: f64,
4095 },
4096 Line(Point, Point),
4097 Polygon(Vec<Point>),
4098 /// An arbitrary path: curves, several contours, and a fill rule (docs/canvas.md).
4099 ///
4100 /// [`Shape::Polygon`] is the straight-line, single-contour special case, kept because it is
4101 /// what most drawing code wants and it encodes far more compactly.
4102 Path(Path),
4103}
4104
4105impl Shape {
4106 /// A rectangle rounded corner by corner (docs/canvas.md "Rounded corners"), as the simplest
4107 /// shape that draws it: a plain [`Shape::Rect`] when every corner is square, a
4108 /// [`Shape::RoundedRect`] (each toolkit's own rounded rectangle) when the corners agree, and a
4109 /// path ([`rounded_rect_segs`]) otherwise. The radii are [fitted](CornerRadii::fitted) first.
4110 ///
4111 /// ```
4112 /// use day_spec::{CornerRadii, Rect, Shape};
4113 ///
4114 /// // A bar standing on its axis: rounded on top, square where it meets the baseline.
4115 /// let bar = Shape::rounded_rect(Rect::new(0.0, 0.0, 20.0, 80.0), CornerRadii::top(6.0));
4116 /// assert!(matches!(bar, Shape::Path(_)));
4117 /// ```
4118 pub fn rounded_rect(rect: Rect, radii: CornerRadii) -> Shape {
4119 let r = radii.fitted(rect.size);
4120 if r.is_zero() || rect.size.width <= 0.0 || rect.size.height <= 0.0 {
4121 Shape::Rect(rect)
4122 } else if r.is_uniform() {
4123 Shape::RoundedRect(rect, r.top_left)
4124 } else {
4125 Shape::Path(Path {
4126 segs: rounded_rect_segs(rect, r),
4127 rule: FillRule::NonZero,
4128 })
4129 }
4130 }
4131
4132 /// The same shape moved by `(dx, dy)`.
4133 ///
4134 /// What a [`Stamp`] means by "the template translated by one point", and the one definition of
4135 /// it: a backend builds each copy of a batch with this rather than reaching for its own
4136 /// platform transform, so every toolkit stamps to the same coordinates.
4137 pub fn translated(&self, dx: f64, dy: f64) -> Shape {
4138 let r = |r: &Rect| {
4139 Rect::new(
4140 r.origin.x + dx,
4141 r.origin.y + dy,
4142 r.size.width,
4143 r.size.height,
4144 )
4145 };
4146 let p = |p: &Point| Point::new(p.x + dx, p.y + dy);
4147 match self {
4148 Shape::Rect(rect) => Shape::Rect(r(rect)),
4149 Shape::RoundedRect(rect, rad) => Shape::RoundedRect(r(rect), *rad),
4150 Shape::Ellipse(rect) => Shape::Ellipse(r(rect)),
4151 Shape::Arc {
4152 rect,
4153 start_deg,
4154 sweep_deg,
4155 } => Shape::Arc {
4156 rect: r(rect),
4157 start_deg: *start_deg,
4158 sweep_deg: *sweep_deg,
4159 },
4160 Shape::Line(a, b) => Shape::Line(p(a), p(b)),
4161 Shape::Polygon(pts) => Shape::Polygon(pts.iter().map(p).collect()),
4162 Shape::Path(path) => Shape::Path(Path {
4163 segs: path
4164 .segs
4165 .iter()
4166 .map(|seg| match seg {
4167 PathSeg::Move(a) => PathSeg::Move(p(a)),
4168 PathSeg::Line(a) => PathSeg::Line(p(a)),
4169 PathSeg::Quad(c, a) => PathSeg::Quad(p(c), p(a)),
4170 PathSeg::Cubic(c1, c2, a) => PathSeg::Cubic(p(c1), p(c2), p(a)),
4171 PathSeg::Close => PathSeg::Close,
4172 })
4173 .collect(),
4174 rule: path.rule,
4175 }),
4176 }
4177 }
4178
4179 /// The shape's bounding rectangle: the box gradient [`UnitPoint`]s resolve against.
4180 pub fn bounds(&self) -> Rect {
4181 match self {
4182 Shape::Rect(r) | Shape::RoundedRect(r, _) | Shape::Ellipse(r) => *r,
4183 Shape::Arc { rect, .. } => *rect,
4184 Shape::Line(a, b) => points_bounds(&[*a, *b]),
4185 Shape::Polygon(pts) => points_bounds(pts),
4186 Shape::Path(p) => p.bounds(),
4187 }
4188 }
4189}
4190
4191/// One step of a [`Path`]. Points are absolute, in the canvas's coordinate space.
4192#[derive(Clone, Copy, Debug, PartialEq)]
4193pub enum PathSeg {
4194 /// Start a new contour at this point.
4195 Move(Point),
4196 Line(Point),
4197 /// Quadratic bezier: one control point, then the end point.
4198 Quad(Point, Point),
4199 /// Cubic bezier: two control points, then the end point.
4200 Cubic(Point, Point, Point),
4201 /// Close the current contour back to its `Move`.
4202 Close,
4203}
4204
4205/// Which points count as inside when a path's contours overlap (docs/canvas.md).
4206///
4207/// This matters the moment a shape has a hole: the counter of an "o", a washer, a ring chart. It
4208/// is a property of the fill, so stroking ignores it.
4209#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
4210pub enum FillRule {
4211 /// Direction-sensitive: a hole needs its contour wound the opposite way. Every 2-D API's
4212 /// default, and what a font's glyph outlines assume.
4213 #[default]
4214 NonZero,
4215 /// Parity: any contour inside another cuts a hole regardless of winding. What PDF's `f*`
4216 /// operator and SVG's `fill-rule: evenodd` mean.
4217 EvenOdd,
4218}
4219
4220/// An arbitrary 2-D path: any number of contours, straight or curved, with a fill rule.
4221#[derive(Clone, Debug, PartialEq, Default)]
4222pub struct Path {
4223 pub segs: Vec<PathSeg>,
4224 pub rule: FillRule,
4225}
4226
4227impl Path {
4228 /// A conservative bounding box: the hull of every point including control points, which
4229 /// contains the true curve bounds (a bezier stays inside its control hull). Used only to
4230 /// resolve gradient unit points, where being slightly generous costs nothing and computing
4231 /// exact curve extrema would not.
4232 pub fn bounds(&self) -> Rect {
4233 let mut pts: Vec<Point> = Vec::with_capacity(self.segs.len() * 3);
4234 for seg in &self.segs {
4235 match seg {
4236 PathSeg::Move(p) | PathSeg::Line(p) => pts.push(*p),
4237 PathSeg::Quad(c, p) => pts.extend_from_slice(&[*c, *p]),
4238 PathSeg::Cubic(c1, c2, p) => pts.extend_from_slice(&[*c1, *c2, *p]),
4239 PathSeg::Close => {}
4240 }
4241 }
4242 points_bounds(&pts)
4243 }
4244}
4245
4246/// A radius for each corner of a rectangle, clockwise from the top left (docs/canvas.md "Rounded
4247/// corners"). The shape a bar in a chart wants (rounded at its value end, square against its
4248/// axis), a tab (rounded on top), or a card joined to its neighbor.
4249///
4250/// Radii are in points and never negative. [`CornerRadii::fitted`] shrinks them the way CSS
4251/// does when two radii on one side would overlap, which is what a caller animating a radius or
4252/// drawing a short bar needs to not think about.
4253#[derive(Clone, Copy, Debug, PartialEq, Default)]
4254pub struct CornerRadii {
4255 pub top_left: f64,
4256 pub top_right: f64,
4257 pub bottom_right: f64,
4258 pub bottom_left: f64,
4259}
4260
4261impl CornerRadii {
4262 /// The same radius on every corner: what [`Shape::RoundedRect`] draws.
4263 pub fn uniform(r: f64) -> Self {
4264 CornerRadii {
4265 top_left: r,
4266 top_right: r,
4267 bottom_right: r,
4268 bottom_left: r,
4269 }
4270 }
4271 /// Rounded along the top edge, square along the bottom: a bar standing on its axis.
4272 pub fn top(r: f64) -> Self {
4273 CornerRadii {
4274 top_left: r,
4275 top_right: r,
4276 ..Default::default()
4277 }
4278 }
4279 /// Rounded along the bottom edge: a bar hanging below its axis.
4280 pub fn bottom(r: f64) -> Self {
4281 CornerRadii {
4282 bottom_right: r,
4283 bottom_left: r,
4284 ..Default::default()
4285 }
4286 }
4287 /// Rounded along the left edge: a bar growing leftward from its axis.
4288 pub fn left(r: f64) -> Self {
4289 CornerRadii {
4290 top_left: r,
4291 bottom_left: r,
4292 ..Default::default()
4293 }
4294 }
4295 /// Rounded along the right edge: a bar growing rightward from its axis.
4296 pub fn right(r: f64) -> Self {
4297 CornerRadii {
4298 top_right: r,
4299 bottom_right: r,
4300 ..Default::default()
4301 }
4302 }
4303
4304 /// The four radii, clockwise from the top left.
4305 pub fn to_array(self) -> [f64; 4] {
4306 [
4307 self.top_left,
4308 self.top_right,
4309 self.bottom_right,
4310 self.bottom_left,
4311 ]
4312 }
4313
4314 /// Whether every corner is square.
4315 pub fn is_zero(self) -> bool {
4316 self.to_array().iter().all(|r| *r <= 0.0)
4317 }
4318
4319 /// Whether every corner has the same radius, so the rectangle is a [`Shape::RoundedRect`].
4320 pub fn is_uniform(self) -> bool {
4321 let [a, b, c, d] = self.to_array();
4322 a == b && b == c && c == d
4323 }
4324
4325 /// These radii made to fit a `size` rectangle, the rule CSS uses for `border-radius`: a
4326 /// negative or non-finite radius is square, and when the two radii along any side add up to
4327 /// more than that side, every radius is scaled down by the same factor until none overlap.
4328 /// Scaling all four together keeps the corners in proportion, where clamping each one alone
4329 /// would turn a pill into a lopsided shape.
4330 pub fn fitted(self, size: Size) -> Self {
4331 let clean = |r: f64| if r.is_finite() && r > 0.0 { r } else { 0.0 };
4332 let [tl, tr, br, bl] = self.to_array().map(clean);
4333 let (w, h) = (size.width.max(0.0), size.height.max(0.0));
4334 let factor = [(w, tl + tr), (w, bl + br), (h, tl + bl), (h, tr + br)]
4335 .into_iter()
4336 .filter(|(_, sum)| *sum > 0.0)
4337 .map(|(side, sum)| side / sum)
4338 .fold(1.0f64, f64::min);
4339 CornerRadii {
4340 top_left: tl * factor,
4341 top_right: tr * factor,
4342 bottom_right: br * factor,
4343 bottom_left: bl * factor,
4344 }
4345 }
4346}
4347
4348/// The point `angle_deg` round a circle: degrees, `0` = the +x axis, positive clockwise in device
4349/// space (y down), the convention [`Shape::Arc`] and every arc helper here use.
4350pub fn arc_point(center: Point, radius: f64, angle_deg: f64) -> Point {
4351 let a = angle_deg.to_radians();
4352 Point::new(center.x + radius * a.cos(), center.y + radius * a.sin())
4353}
4354
4355/// A circular arc as cubic beziers: `sweep_deg` of a circle of `radius` about `center`, from
4356/// `start_deg` ([`arc_point`]'s convention). The segments start *from* the arc's first point, which
4357/// the caller reaches itself (a move or a line); nothing for a zero or non-finite radius or sweep.
4358///
4359/// The arc is split into quarter turns at most, where a cubic tracks a circle best: the radial
4360/// error peaks at 2.7 × 10⁻⁴ of the radius, a quarter of a pixel on a circle a thousand points
4361/// across (docs/canvas.md "Paths"). The same beziers on every backend mean the same pixels on
4362/// every backend, which an arc op interpreted by nine rasterizers would not.
4363pub fn arc_cubics(center: Point, radius: f64, start_deg: f64, sweep_deg: f64) -> Vec<PathSeg> {
4364 let (start, sweep) = (start_deg.to_radians(), sweep_deg.to_radians());
4365 if !radius.is_finite() || radius <= 0.0 || !sweep.is_finite() || sweep == 0.0 {
4366 return Vec::new();
4367 }
4368 let at = |a: f64| Point::new(center.x + radius * a.cos(), center.y + radius * a.sin());
4369 let steps = (sweep.abs() / std::f64::consts::FRAC_PI_2).ceil() as usize;
4370 let delta = sweep / steps as f64;
4371 // The exact control-handle length for a circular arc of this sweep. Negative for a negative
4372 // sweep, which is what turns the handles around for a counter-clockwise arc.
4373 let k = 4.0 / 3.0 * (delta / 4.0).tan() * radius;
4374 (0..steps)
4375 .map(|i| {
4376 let a = start + delta * i as f64;
4377 let b = a + delta;
4378 let (p0, p1) = (at(a), at(b));
4379 PathSeg::Cubic(
4380 Point::new(p0.x - k * a.sin(), p0.y + k * a.cos()),
4381 Point::new(p1.x + k * b.sin(), p1.y - k * b.cos()),
4382 p1,
4383 )
4384 })
4385 .collect()
4386}
4387
4388/// The closed contour of a rectangle rounded corner by corner, clockwise from the top left, with
4389/// the radii [fitted](CornerRadii::fitted) first. A square corner is a sharp point, not a
4390/// zero-length curve.
4391pub fn rounded_rect_segs(rect: Rect, radii: CornerRadii) -> Vec<PathSeg> {
4392 let r = radii.fitted(rect.size);
4393 let (x0, y0) = (rect.origin.x, rect.origin.y);
4394 let (x1, y1) = (x0 + rect.size.width, y0 + rect.size.height);
4395 // Each corner: the point where its curve starts, then the quarter turn round its center.
4396 let corners = [
4397 (
4398 Point::new(x0 + r.top_left, y0 + r.top_left),
4399 r.top_left,
4400 180.0,
4401 ),
4402 (
4403 Point::new(x1 - r.top_right, y0 + r.top_right),
4404 r.top_right,
4405 270.0,
4406 ),
4407 (
4408 Point::new(x1 - r.bottom_right, y1 - r.bottom_right),
4409 r.bottom_right,
4410 0.0,
4411 ),
4412 (
4413 Point::new(x0 + r.bottom_left, y1 - r.bottom_left),
4414 r.bottom_left,
4415 90.0,
4416 ),
4417 ];
4418 let mut segs = Vec::with_capacity(14);
4419 for (i, (center, radius, start)) in corners.into_iter().enumerate() {
4420 let first = arc_point(center, radius, start);
4421 segs.push(if i == 0 {
4422 PathSeg::Move(first)
4423 } else {
4424 PathSeg::Line(first)
4425 });
4426 segs.extend(arc_cubics(center, radius, start, 90.0));
4427 }
4428 segs.push(PathSeg::Close);
4429 segs
4430}
4431
4432/// How a stroked line ends (docs/canvas.md). Names match PDF's `J`, SVG's `stroke-linecap`, and
4433/// every native 2-D API.
4434#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
4435pub enum LineCap {
4436 #[default]
4437 Butt,
4438 Round,
4439 Square,
4440}
4441
4442/// How two stroked segments meet (docs/canvas.md). Matches PDF's `j` and SVG's
4443/// `stroke-linejoin`.
4444#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
4445pub enum LineJoin {
4446 #[default]
4447 Miter,
4448 Round,
4449 Bevel,
4450}
4451
4452/// Everything about a stroke except its paint.
4453///
4454/// [`StrokeStyle::width`] and `From<f64>` keep the common "just a width" case a single
4455/// argument, so plain `stroke(shape, color, 2.0)` call sites read the same as they always did.
4456#[derive(Clone, Debug, PartialEq)]
4457pub struct StrokeStyle {
4458 pub width: f64,
4459 pub cap: LineCap,
4460 pub join: LineJoin,
4461 /// Ignored unless `join` is [`LineJoin::Miter`]. The 2-D convention: past this ratio of miter
4462 /// length to line width the join falls back to a bevel.
4463 pub miter_limit: f64,
4464 /// On/off run lengths, repeating. Empty means solid.
4465 pub dash: Vec<f64>,
4466 /// How far into the dash pattern the line starts.
4467 pub dash_phase: f64,
4468}
4469
4470impl Default for StrokeStyle {
4471 fn default() -> Self {
4472 // 10.0 is the miter limit PDF, PostScript, SVG and Cairo all default to.
4473 StrokeStyle {
4474 width: 1.0,
4475 cap: LineCap::Butt,
4476 join: LineJoin::Miter,
4477 miter_limit: 10.0,
4478 dash: Vec::new(),
4479 dash_phase: 0.0,
4480 }
4481 }
4482}
4483
4484impl StrokeStyle {
4485 /// A solid stroke of `width`, everything else default.
4486 pub fn width(width: f64) -> Self {
4487 StrokeStyle {
4488 width,
4489 ..Default::default()
4490 }
4491 }
4492 /// A dashed stroke: `dash` is on/off run lengths, repeating.
4493 pub fn dashed(width: f64, dash: Vec<f64>) -> Self {
4494 StrokeStyle {
4495 width,
4496 dash,
4497 ..Default::default()
4498 }
4499 }
4500 /// Rounded ends and joins, the shape a data line usually wants.
4501 pub fn round(width: f64) -> Self {
4502 StrokeStyle {
4503 width,
4504 cap: LineCap::Round,
4505 join: LineJoin::Round,
4506 ..Default::default()
4507 }
4508 }
4509 /// Is this the plain width-only stroke every pre-existing call site asks for? Backends use
4510 /// it to skip setting dash/cap/join state they would only have to set back.
4511 pub fn is_plain(&self) -> bool {
4512 self.cap == LineCap::Butt
4513 && self.join == LineJoin::Miter
4514 && self.dash.is_empty()
4515 && self.miter_limit == 10.0
4516 }
4517}
4518
4519impl From<f64> for StrokeStyle {
4520 fn from(width: f64) -> Self {
4521 StrokeStyle::width(width)
4522 }
4523}
4524
4525fn points_bounds(pts: &[Point]) -> Rect {
4526 let (mut x0, mut y0, mut x1, mut y1) = (f64::MAX, f64::MAX, f64::MIN, f64::MIN);
4527 for p in pts {
4528 x0 = x0.min(p.x);
4529 y0 = y0.min(p.y);
4530 x1 = x1.max(p.x);
4531 y1 = y1.max(p.y);
4532 }
4533 if pts.is_empty() {
4534 return Rect::ZERO;
4535 }
4536 Rect::new(x0, y0, x1 - x0, y1 - y0)
4537}
4538
4539/// A point in the unit space of a shape's bounding box: (0,0) = top-leading, (1,1) =
4540/// bottom-trailing. Gradient geometry is expressed in unit points so one paint value works for
4541/// any shape size (docs/shapes.md §3.2).
4542#[derive(Clone, Copy, Debug, PartialEq)]
4543pub struct UnitPoint {
4544 pub x: f64,
4545 pub y: f64,
4546}
4547
4548impl UnitPoint {
4549 pub const fn new(x: f64, y: f64) -> Self {
4550 UnitPoint { x, y }
4551 }
4552 pub const TOP: UnitPoint = UnitPoint::new(0.5, 0.0);
4553 pub const BOTTOM: UnitPoint = UnitPoint::new(0.5, 1.0);
4554 pub const LEADING: UnitPoint = UnitPoint::new(0.0, 0.5);
4555 pub const TRAILING: UnitPoint = UnitPoint::new(1.0, 0.5);
4556 pub const TOP_LEADING: UnitPoint = UnitPoint::new(0.0, 0.0);
4557 pub const TOP_TRAILING: UnitPoint = UnitPoint::new(1.0, 0.0);
4558 pub const BOTTOM_LEADING: UnitPoint = UnitPoint::new(0.0, 1.0);
4559 pub const BOTTOM_TRAILING: UnitPoint = UnitPoint::new(1.0, 1.0);
4560 pub const CENTER: UnitPoint = UnitPoint::new(0.5, 0.5);
4561
4562 /// Resolve to an absolute point within `rect`.
4563 pub fn resolve(&self, rect: Rect) -> Point {
4564 Point::new(
4565 rect.origin.x + self.x * rect.size.width,
4566 rect.origin.y + self.y * rect.size.height,
4567 )
4568 }
4569}
4570
4571/// A linear gradient (docs/shapes.md §3.2 / §7): color stops along the line from `start` to
4572/// `end`, both in the unit space of the filled shape's bounding box. Stops are
4573/// `(offset 0..=1, color)`, ascending.
4574#[derive(Clone, Debug, PartialEq)]
4575pub struct LinearGradient {
4576 pub start: UnitPoint,
4577 pub end: UnitPoint,
4578 pub stops: Vec<(f64, Color)>,
4579}
4580
4581impl LinearGradient {
4582 pub fn new(start: UnitPoint, end: UnitPoint, stops: Vec<(f64, Color)>) -> Self {
4583 LinearGradient { start, end, stops }
4584 }
4585 /// Top-to-bottom between two colors: the everyday sky/backdrop case.
4586 pub fn vertical(top: Color, bottom: Color) -> Self {
4587 LinearGradient::new(
4588 UnitPoint::TOP,
4589 UnitPoint::BOTTOM,
4590 vec![(0.0, top), (1.0, bottom)],
4591 )
4592 }
4593 /// Leading-to-trailing between two colors.
4594 pub fn horizontal(leading: Color, trailing: Color) -> Self {
4595 LinearGradient::new(
4596 UnitPoint::LEADING,
4597 UnitPoint::TRAILING,
4598 vec![(0.0, leading), (1.0, trailing)],
4599 )
4600 }
4601}
4602
4603/// A radial gradient (docs/shapes.md §3.2 / §7): color stops from `center` outward. Both the
4604/// center and the radius live in the unit space of the filled shape's bounding box, so the
4605/// gradient stretches into an ellipse when the bounds aren't square (the XAML relative-brush
4606/// behavior; the other backends reproduce it with a local matrix on a circular gradient). A
4607/// `radius` of `0.5` from the default center touches the edge midpoints of the bounds.
4608#[derive(Clone, Debug, PartialEq)]
4609pub struct RadialGradient {
4610 pub center: UnitPoint,
4611 pub radius: f64,
4612 pub stops: Vec<(f64, Color)>,
4613}
4614
4615impl RadialGradient {
4616 pub fn new(center: UnitPoint, radius: f64, stops: Vec<(f64, Color)>) -> Self {
4617 RadialGradient {
4618 center,
4619 radius,
4620 stops,
4621 }
4622 }
4623 /// Centered, edge-touching (radius 0.5) between two colors: the everyday glow case.
4624 pub fn centered(inner: Color, outer: Color) -> Self {
4625 RadialGradient::new(UnitPoint::CENTER, 0.5, vec![(0.0, inner), (1.0, outer)])
4626 }
4627}
4628
4629/// The payload of [`DrawOp::Stamp`]: one shape drawn at every position in `at`.
4630///
4631/// A scatter plot is the case this exists for. Drawn as individual ops, fifty thousand points are
4632/// fifty thousand `DrawOp`s, rebuilt, compared and cloned on every frame that re-records, before
4633/// a backend draws anything. As one `Stamp` they are one op and a flat array of coordinates, and
4634/// a backend can put every copy into one path and hand the rasterizer a single fill.
4635///
4636/// Every copy shares the shape, the size and the paint. Varying any of those means more than one
4637/// stamp: group by what varies, which for a chart is usually the series color.
4638#[derive(Clone, Debug, PartialEq)]
4639pub struct Stamp {
4640 /// The template, authored around the origin: each copy is this shape translated by one point.
4641 /// A 6-point dot is `Shape::Ellipse(Rect::new(-3.0, -3.0, 6.0, 6.0))`.
4642 pub shape: Shape,
4643 /// Where the copies go. Order is the drawing order, so later points paint over earlier ones.
4644 pub at: Vec<Point>,
4645 pub paint: Paint,
4646 /// `None` fills each copy; `Some` strokes it with this style.
4647 pub stroke: Option<StrokeStyle>,
4648}
4649
4650/// A fill source: a solid color, or a linear/radial gradient (docs/shapes.md §3.2; angular and
4651/// semantic tokens are later phases). `From<Color>` keeps every existing `fill(shape, color)`
4652/// call site compiling unchanged.
4653#[derive(Clone, Debug, PartialEq)]
4654pub enum Paint {
4655 Solid(Color),
4656 Linear(LinearGradient),
4657 Radial(RadialGradient),
4658}
4659
4660impl From<Color> for Paint {
4661 fn from(c: Color) -> Self {
4662 Paint::Solid(c)
4663 }
4664}
4665
4666impl From<LinearGradient> for Paint {
4667 fn from(g: LinearGradient) -> Self {
4668 Paint::Linear(g)
4669 }
4670}
4671
4672impl From<RadialGradient> for Paint {
4673 fn from(g: RadialGradient) -> Self {
4674 Paint::Radial(g)
4675 }
4676}
4677
4678/// Where `at` sits vertically. `Top`, `Middle` and `Bottom` are edges of the line box (ascent +
4679/// descent at the font's size, the box [`Toolkit::measure_text`] reports); `Baseline` is the
4680/// typographic baseline itself.
4681#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
4682pub enum TextVAlign {
4683 /// `at` is the top of the line box.
4684 #[default]
4685 Top,
4686 /// `at` is the vertical middle of the line box.
4687 Middle,
4688 /// `at` is the baseline itself: what every native 2-D text call takes, and what a run of labels
4689 /// sharing a line should align on rather than their individual boxes.
4690 Baseline,
4691 /// `at` is the bottom of the line box.
4692 Bottom,
4693}
4694
4695/// How canvas text hangs on its `at` point: one placement per axis (docs/canvas.md "Text").
4696///
4697/// Two axes rather than a list of named positions, because that is the shape of the problem and
4698/// of every native API underneath: `NSAttributedString` drawing, Pango extents,
4699/// `QFontMetricsF`, `Paint.Align`, Canvas2D's `textAlign`/`textBaseline`. The alignment is done
4700/// by the backend, which is both cheaper and more accurate than doing it in app code: it already
4701/// has the laid-out metrics, where an app has to ask for them through
4702/// [`Toolkit::measure_text`] first.
4703///
4704/// [`TextAnchor::LEADING`] and [`TextAnchor::CENTERED`] name the two placements that used to be
4705/// this type's only variants.
4706#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
4707pub struct TextAnchor {
4708 /// The horizontal placement: the same three-way leading/center/trailing a wrapped label's
4709 /// lines take ([`props::TextAlign`]), because it is the same question with the same RTL rule.
4710 /// `Trailing` is what an axis label right-aligned against its axis wants, and the reason the
4711 /// horizontal axis is settable at all: emulating it in app code costs a
4712 /// [`Toolkit::measure_text`] call per label, where the backend already holds the width it is
4713 /// about to draw with.
4714 pub h: props::TextAlign,
4715 pub v: TextVAlign,
4716}
4717
4718impl TextAnchor {
4719 /// The top-leading corner of the line box, the default.
4720 pub const LEADING: TextAnchor = TextAnchor {
4721 h: props::TextAlign::Leading,
4722 v: TextVAlign::Top,
4723 };
4724 /// The center of the line box, both ways.
4725 pub const CENTERED: TextAnchor = TextAnchor {
4726 h: props::TextAlign::Center,
4727 v: TextVAlign::Middle,
4728 };
4729 /// The top-trailing corner of the line box.
4730 pub const TRAILING: TextAnchor = TextAnchor {
4731 h: props::TextAlign::Trailing,
4732 v: TextVAlign::Top,
4733 };
4734
4735 /// Where the text's top-leading corner goes, as an offset from `at`, given the line box this
4736 /// text measures to. The single definition of what an anchor means: every backend that draws
4737 /// in Rust calls this, and the C++/Java/JS shims repeat exactly this arithmetic.
4738 ///
4739 /// `height` is the line box (ascent + descent) and `ascent` the baseline's offset from its
4740 /// top, the two numbers [`TextMetrics`] carries.
4741 pub fn offset(self, width: f64, height: f64, ascent: f64) -> (f64, f64) {
4742 let dx = match self.h {
4743 props::TextAlign::Leading => 0.0,
4744 props::TextAlign::Center => -width / 2.0,
4745 props::TextAlign::Trailing => -width,
4746 };
4747 let dy = match self.v {
4748 TextVAlign::Top => 0.0,
4749 TextVAlign::Middle => -height / 2.0,
4750 TextVAlign::Baseline => -ascent,
4751 TextVAlign::Bottom => -height,
4752 };
4753 (dx, dy)
4754 }
4755
4756 /// The anchor as one number, for the numeric op stream the serializing backends share:
4757 /// `h * 4 + v`, so it still occupies the single slot the two-variant enum did.
4758 pub fn pack(self) -> f64 {
4759 (self.h as u8 * 4 + self.v as u8) as f64
4760 }
4761
4762 /// Inverse of [`TextAnchor::pack`]. An unrecognized code answers the default rather than
4763 /// failing: a stream is only ever written by a matching encoder, and a drawing with text in
4764 /// the wrong corner beats one that panics inside a native draw callback.
4765 pub fn unpack(code: f64) -> TextAnchor {
4766 let c = code.round().clamp(0.0, 11.0) as u8;
4767 let h = match c / 4 {
4768 1 => props::TextAlign::Center,
4769 2 => props::TextAlign::Trailing,
4770 _ => props::TextAlign::Leading,
4771 };
4772 let v = match c % 4 {
4773 1 => TextVAlign::Middle,
4774 2 => TextVAlign::Baseline,
4775 3 => TextVAlign::Bottom,
4776 _ => TextVAlign::Top,
4777 };
4778 TextAnchor { h, v }
4779 }
4780}
4781
4782#[derive(Clone, Debug, PartialEq)]
4783pub enum DrawOp {
4784 Fill(Shape, Paint),
4785 /// Stroke `shape`. The paint may be a gradient, and [`StrokeStyle`] carries width, dash, cap
4786 /// and join; `Draw::stroke` builds the plain width-only case.
4787 Stroke(Shape, Paint, StrokeStyle),
4788 /// One line of text. `size` is absolute canvas points (no accessibility scale: canvas
4789 /// text is a label inside a drawing, docs/canvas.md); `font` picks the family, weight and
4790 /// slant, and its default is the platform's own UI face.
4791 Text {
4792 text: String,
4793 at: Point,
4794 size: f64,
4795 color: Color,
4796 anchor: TextAnchor,
4797 font: CanvasFont,
4798 },
4799 /// Draw one shape at many positions, the batched form of [`DrawOp::Fill`]/[`DrawOp::Stroke`]
4800 /// (docs/canvas.md "Stamping").
4801 ///
4802 /// Boxed because the payload is wider than the largest other op, and a bigger `DrawOp` would
4803 /// cost every op in every drawing, the exact thing this variant exists to stop paying.
4804 Stamp(Box<Stamp>),
4805 /// Draw an image into `rect` (docs/images.md).
4806 ///
4807 /// The source is a [`BitmapId`] and never bytes: a canvas re-records on every tracked read,
4808 /// so carrying a buffer here would hand the backend a megabyte to compare, and re-decode, on
4809 /// every frame. The app decodes once with `day::decode_image` and draws the handle.
4810 ///
4811 /// `opacity` multiplies the image's own alpha. A backend that cannot draw a bitmap at all
4812 /// draws nothing rather than a placeholder rectangle, the same way an unknown op is skipped.
4813 Image {
4814 image: BitmapId,
4815 rect: Rect,
4816 opacity: f64,
4817 },
4818 /// Intersect the clip with `shape`; everything drawn afterwards is confined to it.
4819 ///
4820 /// Scoped by [`DrawOp::Save`]/[`DrawOp::Restore`], which is the only way to widen a clip
4821 /// again; every native 2-D context works this way, so there is no "unclip".
4822 Clip(Shape),
4823 /// Push the current transform + clip (§11, shapes). Backends map to save/restore of the
4824 /// native 2-D context; `Concat` multiplies an affine onto the CTM (shape rotate/scale/offset).
4825 Save,
4826 Restore,
4827 Concat(day_geometry::Affine),
4828}
4829
4830// ---------------------------------------------------------------------------
4831// Built-in piece descriptors: full props (realize) + sparse patches (update).
4832// One binding = one attribute = one patch value: sparseness by construction (§8.1).
4833// ---------------------------------------------------------------------------
4834
4835/// A semantic (logical) text style. Each maps to the platform's native text style where the
4836/// toolkit has one: `UIFont`/`NSFont.preferredFont(forTextStyle:)` on Apple (Dynamic Type), the
4837/// `*TextBlockStyle` resources on XAML. A Day app thus matches the OS's own typography and
4838/// inherits its accessibility text scaling with no extra work. Backends without semantic styles
4839/// (GTK/Qt/Android) approximate with sizes that still track the platform's text-scale /
4840/// font-scale accessibility setting.
4841///
4842/// The set mirrors SwiftUI `Font.TextStyle` (largest → smallest).
4843#[derive(Clone, Copy, Debug, PartialEq, Default)]
4844pub enum Font {
4845 LargeTitle,
4846 Title,
4847 Title2,
4848 Title3,
4849 Headline,
4850 Subheadline,
4851 #[default]
4852 Body,
4853 Callout,
4854 Footnote,
4855 Caption,
4856 Caption2,
4857 /// A custom point size. Backends scale it by the platform's accessibility text-scale (iOS via
4858 /// `UIFontMetrics`, Android via `sp`, GTK via text-scaling-factor) so it stays legible.
4859 System(f64),
4860 /// A bundled custom font by **family name**, at a point size (`Font::Custom("Pacifico",
4861 /// 24.0)`). The family must ship in the project's `fonts/` directory; `day build` stages the
4862 /// file into each platform's native font store and the backend registers it at startup
4863 /// (§18.4). The name is the family name baked into the font file (what Font Book /
4864 /// fontconfig report), not the file name. The size scales with the platform accessibility
4865 /// text-scale exactly like [`Font::System`]; weight/italic apply only where the family ships
4866 /// (or the platform synthesizes) such a face. An unknown family falls back to the system font
4867 /// of the same size, with a warning in the log.
4868 Custom(&'static str, f64),
4869}
4870
4871impl Font {
4872 /// A bundled custom font by **typed family**, at a point size, the checked form of
4873 /// [`Font::Custom`]. Pass a generated `res::fonts::…` constant
4874 /// (`Font::custom(res::fonts::pacifico, 24.0)`), which exists only if the family ships in the
4875 /// project's `fonts/` directory, so the font is guaranteed bundled. For a family name known
4876 /// another way, the untyped [`Font::Custom`] variant is the escape hatch.
4877 pub const fn custom(family: FontFamily, size: f64) -> Font {
4878 Font::Custom(family.as_str(), size)
4879 }
4880}
4881
4882/// Font weight, matching `UIFont.Weight` / SwiftUI `Font.Weight` (lightest → heaviest).
4883/// Ordered by heaviness, so backends can e.g. map `>= Semibold` to a synthesized bold face.
4884#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
4885pub enum FontWeight {
4886 UltraLight,
4887 Thin,
4888 Light,
4889 Regular,
4890 Medium,
4891 Semibold,
4892 Bold,
4893 Heavy,
4894 Black,
4895}
4896
4897impl FontWeight {
4898 /// Every rung, lightest first.
4899 pub const ALL: [FontWeight; 9] = [
4900 FontWeight::UltraLight,
4901 FontWeight::Thin,
4902 FontWeight::Light,
4903 FontWeight::Regular,
4904 FontWeight::Medium,
4905 FontWeight::Semibold,
4906 FontWeight::Bold,
4907 FontWeight::Heavy,
4908 FontWeight::Black,
4909 ];
4910
4911 /// The CSS / OpenType numeric weight (100 … 900), the one number every platform font API
4912 /// also speaks (`Typeface.create(base, weight, italic)`, `QFont::Weight`,
4913 /// `DWRITE_FONT_WEIGHT`, `OH_Drawing_FontWeight`), and what the canvas wire carries.
4914 pub const fn css(self) -> u16 {
4915 match self {
4916 FontWeight::UltraLight => 100,
4917 FontWeight::Thin => 200,
4918 FontWeight::Light => 300,
4919 FontWeight::Regular => 400,
4920 FontWeight::Medium => 500,
4921 FontWeight::Semibold => 600,
4922 FontWeight::Bold => 700,
4923 FontWeight::Heavy => 800,
4924 FontWeight::Black => 900,
4925 }
4926 }
4927
4928 /// The nearest rung to a CSS weight (ties round heavier, like CSS font matching); anything
4929 /// outside 100 … 900 clamps.
4930 pub fn from_css(n: u16) -> FontWeight {
4931 let n = n.clamp(100, 900);
4932 let idx = (usize::from(n) + 50) / 100; // 100 → 1 … 900 → 9
4933 FontWeight::ALL[idx.clamp(1, 9) - 1]
4934 }
4935
4936 /// The English face name for a rung ("Semibold"), for platforms whose enumeration names
4937 /// no face (see [`FontFace::synthesized_name`]).
4938 pub const fn name(self) -> &'static str {
4939 match self {
4940 FontWeight::UltraLight => "Ultra Light",
4941 FontWeight::Thin => "Thin",
4942 FontWeight::Light => "Light",
4943 FontWeight::Regular => "Regular",
4944 FontWeight::Medium => "Medium",
4945 FontWeight::Semibold => "Semibold",
4946 FontWeight::Bold => "Bold",
4947 FontWeight::Heavy => "Heavy",
4948 FontWeight::Black => "Black",
4949 }
4950 }
4951}
4952
4953/// One face a font family ships (docs/fonts.md): its display name ("Bold Italic"), weight and
4954/// slant. What [`FontFamilyInfo::faces`] lists and what a font menu's style picker offers.
4955#[derive(Clone, Debug, PartialEq, Eq)]
4956pub struct FontFace {
4957 pub name: String,
4958 pub weight: FontWeight,
4959 pub italic: bool,
4960}
4961
4962impl FontFace {
4963 /// A display name from weight + slant ("Semibold Italic") for platforms whose enumeration
4964 /// API names no face (Android's `fonts.xml`, the CSS generic families).
4965 pub fn synthesized_name(weight: FontWeight, italic: bool) -> String {
4966 if italic {
4967 format!("{} Italic", weight.name())
4968 } else {
4969 weight.name().to_string()
4970 }
4971 }
4972}
4973
4974/// A platform (or bundled) font family and the faces it can draw canvas text in
4975/// ([`Toolkit::font_families`], docs/fonts.md).
4976#[derive(Clone, Debug, PartialEq, Eq)]
4977pub struct FontFamilyInfo {
4978 pub family: String,
4979 pub faces: Vec<FontFace>,
4980}
4981
4982impl FontFamilyInfo {
4983 /// Whether any face is [`FontWeight::Bold`] or heavier.
4984 pub fn has_bold(&self) -> bool {
4985 self.faces.iter().any(|f| f.weight >= FontWeight::Bold)
4986 }
4987 /// Whether any face is italic.
4988 pub fn has_italic(&self) -> bool {
4989 self.faces.iter().any(|f| f.italic)
4990 }
4991 /// The nearest face: an exact slant match preferred, then the smallest weight distance
4992 /// (ties go heavier, like CSS font matching). `None` only when the family lists no faces.
4993 pub fn face_for(&self, weight: FontWeight, italic: bool) -> Option<&FontFace> {
4994 let want = i32::from(weight.css());
4995 self.faces.iter().min_by_key(|f| {
4996 let slant = i32::from(f.italic != italic);
4997 let dist = (i32::from(f.weight.css()) - want).abs();
4998 // Heavier wins a tie: subtracting the bool sorts the heavier face first.
4999 (slant, dist, i32::from(i32::from(f.weight.css()) < want))
5000 })
5001 }
5002}
5003
5004/// Single-line text measurement in canvas points ([`Toolkit::measure_text`], docs/fonts.md).
5005///
5006/// Two boxes, and the difference between them matters. `width`/`height` is the **line box**: the
5007/// typographic slot the text occupies, the same for every string in a face at a size, and what
5008/// [`TextAnchor`] positions. [`ink`](TextMetrics::ink) is the **ink box**: where the glyphs
5009/// put marks. A line of digits leaves the descender space of its line box empty, so the
5010/// two disagree, and which one is wanted depends on the question: laying text out in a column
5011/// wants the line box, and centering it on a rule or keeping it clear of a mark wants the ink.
5012#[derive(Clone, Copy, Debug, PartialEq)]
5013pub struct TextMetrics {
5014 /// The advance width of the whole string.
5015 pub width: f64,
5016 /// The line box: ascent + descent at this size (plus the line gap where the engine reports
5017 /// one), which is the box [`TextAnchor`] positions.
5018 pub height: f64,
5019 /// The baseline's offset from the top of the line box.
5020 pub ascent: f64,
5021 /// The face's cap height at this size: baseline to the top of a capital.
5022 ///
5023 /// A property of the font, not of this string, reported here because it is what optical
5024 /// centering needs and asking for it separately would be a second measurement. Text made of
5025 /// capitals and digits looks centered on a rule when its cap box straddles it, not its line
5026 /// box: the line box reserves descender room that digits never use, so centering by it sits
5027 /// every label a little low. The cap middle is `ascent - cap_height / 2.0` below the line
5028 /// box's top.
5029 pub cap_height: f64,
5030 /// The ink box, the tight bounds of what is drawn, with its origin relative to the line
5031 /// box's top-leading corner, so `ink.origin` is where the marks start inside the slot.
5032 ///
5033 /// Empty (zero-size) for text that draws nothing, a space included. Where a toolkit cannot
5034 /// report ink it answers the whole line box, which is a superset: an overlap test against it
5035 /// can only be too cautious, never wrong.
5036 pub ink: Rect,
5037}
5038
5039impl TextMetrics {
5040 /// The portable guess `day::measure_text` falls back to when a toolkit cannot measure:
5041 /// 0.6 × size per character, 1.2 × size tall, the baseline at 0.9 × size, caps at 0.7 × size.
5042 /// Its ink is the whole line box, the safe direction to be wrong in (see
5043 /// [`ink`](TextMetrics::ink)).
5044 pub fn approximate(text: &str, size: f64) -> TextMetrics {
5045 let (width, height) = (0.6 * size * text.chars().count() as f64, 1.2 * size);
5046 TextMetrics {
5047 width,
5048 height,
5049 ascent: 0.9 * size,
5050 cap_height: 0.7 * size,
5051 ink: Rect::new(0.0, 0.0, width, height),
5052 }
5053 }
5054
5055 /// Read the eight-slot form the serializing backends (qt, xaml, arkui, web) fill across their
5056 /// C ABI: advance, line height, ascent, cap height, then the ink box relative to the line
5057 /// box's top-leading corner. One definition so four shims cannot drift from each other.
5058 pub fn from_slots(out: &[f64; 8]) -> TextMetrics {
5059 TextMetrics {
5060 width: out[0],
5061 height: out[1],
5062 ascent: out[2],
5063 cap_height: out[3],
5064 ink: Rect::new(out[4], out[5], out[6], out[7]),
5065 }
5066 }
5067
5068 /// The line box's top-leading corner, given a baseline-relative measurement, the shape every
5069 /// backend's metrics come in. `ink_*` are relative to the drawing origin on the baseline
5070 /// (`ink_top` negative above it), the convention Skia, Core Text and Qt all report in.
5071 pub fn from_baseline(
5072 width: f64,
5073 ascent: f64,
5074 descent: f64,
5075 cap_height: f64,
5076 ink: Rect,
5077 ) -> TextMetrics {
5078 TextMetrics {
5079 width,
5080 height: ascent + descent,
5081 ascent,
5082 cap_height,
5083 // Baseline-relative to line-box-relative is one shift by the ascent.
5084 ink: Rect::new(
5085 ink.origin.x,
5086 ink.origin.y + ascent,
5087 ink.size.width,
5088 ink.size.height,
5089 ),
5090 }
5091 }
5092}
5093
5094/// What canvas text is drawn with beyond its size (docs/canvas.md "Text"): a family, a weight and
5095/// a slant. The default is the platform's own UI face, regular, upright, which is what every
5096/// backend drew before the field existed, so a default font encodes to nothing on the wire.
5097#[derive(Clone, Debug, PartialEq, Eq, Default)]
5098pub struct CanvasFont {
5099 /// A platform or bundled family name (as [`Toolkit::font_families`] lists it); `None` =
5100 /// the platform's default UI face.
5101 pub family: Option<String>,
5102 /// `None` = Regular.
5103 pub weight: Option<FontWeight>,
5104 pub italic: bool,
5105}
5106
5107impl CanvasFont {
5108 /// The family name to send over the wire, empty for the default.
5109 pub fn family_str(&self) -> &str {
5110 self.family.as_deref().unwrap_or("")
5111 }
5112 /// The CSS weight to send over the wire, 0 for the default.
5113 pub fn css_weight(&self) -> u16 {
5114 self.weight.map(FontWeight::css).unwrap_or(0)
5115 }
5116}
5117
5118/// Field separator inside one family of the shim-side font list ([`parse_font_list`]).
5119pub const FONT_LIST_FIELD: char = '\u{1f}';
5120/// Family separator of the shim-side font list ([`parse_font_list`]).
5121pub const FONT_LIST_FAMILY: char = '\u{1e}';
5122
5123/// Decode the text a non-Rust font enumerator hands back (the Qt, XAML and ArkUI shims, the
5124/// Android bridge, the web shim all produce this one format): families separated by U+001E;
5125/// inside a family, U+001F-separated fields: the family name, then one (name, CSS weight,
5126/// italic `0`/`1`) triple per face. Tolerant: a malformed face or family is skipped, an empty
5127/// face name is synthesized from its weight and slant, and a family with no faces is kept
5128/// with none (the caller decides what a face-less family means).
5129pub fn parse_font_list(s: &str) -> Vec<FontFamilyInfo> {
5130 let mut out = Vec::new();
5131 for fam in s.split(FONT_LIST_FAMILY) {
5132 let mut fields = fam.split(FONT_LIST_FIELD);
5133 let Some(family) = fields.next().map(str::trim).filter(|f| !f.is_empty()) else {
5134 continue;
5135 };
5136 let rest: Vec<&str> = fields.collect();
5137 let mut faces = Vec::new();
5138 for face in rest.chunks(3) {
5139 let [name, weight, italic] = face else {
5140 continue;
5141 };
5142 let Ok(weight) = weight.trim().parse::<u16>() else {
5143 continue;
5144 };
5145 let weight = FontWeight::from_css(weight);
5146 let italic = matches!(italic.trim(), "1" | "true");
5147 let name = name.trim();
5148 let name = if name.is_empty() {
5149 FontFace::synthesized_name(weight, italic)
5150 } else {
5151 name.to_string()
5152 };
5153 if !faces
5154 .iter()
5155 .any(|f: &FontFace| f.weight == weight && f.italic == italic)
5156 {
5157 faces.push(FontFace {
5158 name,
5159 weight,
5160 italic,
5161 });
5162 }
5163 }
5164 out.push(FontFamilyInfo {
5165 family: family.to_string(),
5166 faces,
5167 });
5168 }
5169 out
5170}
5171
5172/// The full font descriptor a label carries: a semantic (or custom) [`Font`] style plus an optional
5173/// weight override, an italic flag, and the tabular-figures request. Backends resolve this to one
5174/// native font.
5175#[derive(Clone, Copy, Debug, PartialEq)]
5176pub struct FontSpec {
5177 pub style: Font,
5178 pub weight: Option<FontWeight>,
5179 pub italic: bool,
5180 /// Ask for tabular (monospaced) figures: every digit takes the same advance, so a number that
5181 /// changes stops changing width.
5182 ///
5183 /// In a proportional system font `1` is narrower than `8`, so a readout beside a slider
5184 /// wobbles as the value changes even when the digit count is fixed. Every platform ships this
5185 /// as a font feature, so Day asks for the platform's own rather than substituting a monospaced
5186 /// family: the text keeps the system face, and only the digits change metrics.
5187 ///
5188 /// Reserving space (`Decorate::reserving`) and tabular figures solve the two halves of the
5189 /// same problem (reservation stops the box resizing, tabular stops the glyphs shifting inside
5190 /// it), and a numeric readout usually wants both.
5191 ///
5192 /// This rides the existing label realize/patch path rather than adding a Toolkit method, so it
5193 /// is not a backend duty and has no duty-matrix row. Every in-tree backend honors it: AppKit
5194 /// and UIKit re-pick the system face (`monospacedDigitSystemFont`), GTK and Qt and ArkUI set
5195 /// the `tnum` OpenType feature, Android `setFontFeatureSettings`, XAML the `Typography`
5196 /// NumeralAlignment property, and web-dom `font-variant-numeric`. A font with no `tnum` table,
5197 /// or an SDK predating the attribute, renders the stock proportional figures.
5198 pub tabular: bool,
5199 /// Ask for the platform's monospaced face at this style's size, what `` `code` `` in a
5200 /// markdown run needs (docs/text-runs.md).
5201 ///
5202 /// A flag rather than a `Font::Monospace(pt)` variant so the run keeps its semantic style:
5203 /// code inside a `Footnote` paragraph must stay footnote-sized and keep tracking the
5204 /// reader's text-size setting, which a fixed point size would throw away.
5205 ///
5206 /// Like [`Self::tabular`], this rides the label realize/patch path and is not a backend duty:
5207 /// every toolkit has a system monospace face (`monospacedSystemFont`, Pango's `monospace`
5208 /// family, `QFontDatabase::FixedFont`, `Typeface.MONOSPACE`, CSS `monospace`).
5209 pub monospace: bool,
5210 /// Multiply the resolved size. `1.0` is the style's own size, `1.6` a heading against a body
5211 /// paragraph, `0.8` a caption inside one.
5212 ///
5213 /// Relative rather than an absolute point size, so that an editor's font-size control can
5214 /// move this while text a person reads for an hour still tracks the platform's
5215 /// accessibility text-scale. `Font::System(pt)` remains the absolute escape hatch, and it
5216 /// is where an imported document's `\fs28` or `font-size: 14px` lands (docs/texteditor.md):
5217 /// faithful to the file, and no longer responsive to the reader, which is the trade that
5218 /// form makes.
5219 ///
5220 /// Three toolkits take it directly (`GtkTextTag::scale`, Android's `RelativeSizeSpan`, CSS
5221 /// `em`); the rest multiply it into the size they already compute.
5222 pub scale: f64,
5223}
5224
5225impl Default for FontSpec {
5226 fn default() -> Self {
5227 FontSpec {
5228 style: Font::Body,
5229 weight: None,
5230 italic: false,
5231 tabular: false,
5232 monospace: false,
5233 scale: 1.0,
5234 }
5235 }
5236}
5237
5238impl From<Font> for FontSpec {
5239 fn from(style: Font) -> Self {
5240 FontSpec {
5241 style,
5242 ..FontSpec::default()
5243 }
5244 }
5245}
5246
5247impl FontSpec {
5248 /// The plain descriptor for a style: no weight override, no italic, scale 1.0.
5249 pub fn new(style: Font) -> Self {
5250 FontSpec::from(style)
5251 }
5252 /// This descriptor at a different relative size (see [`FontSpec::scale`]).
5253 pub fn scaled(mut self, scale: f64) -> Self {
5254 self.scale = scale;
5255 self
5256 }
5257 /// The point size this descriptor resolves to, given the size the platform assigns its
5258 /// semantic style. The one place `scale` is applied, so every backend's font resolver
5259 /// multiplies the same way.
5260 pub fn resolved_points(&self, style_points: f64) -> f64 {
5261 let base = match self.style {
5262 Font::System(pt) | Font::Custom(_, pt) => pt,
5263 _ => style_points,
5264 };
5265 (base * self.scale).max(1.0)
5266 }
5267}
5268
5269/// One styled span of a label's text (docs/text-runs.md).
5270///
5271/// `range` is a byte range into the label's `text`. Bytes, not chars: every backend that takes a
5272/// structured attributed string wants UTF-16 or byte offsets, `str` slicing is byte-based, and a
5273/// char count would have to be converted at every boundary. Ranges must be non-overlapping and
5274/// ascending; a gap between them is unstyled text, drawn with the label's own font.
5275///
5276/// A run says only what differs. `font` is the whole descriptor rather than a delta because a
5277/// bold run inside a Body paragraph is `FontSpec { style: Body, weight: Some(Bold), .. }`. The
5278/// style has to travel with the weight or the run loses its semantic size.
5279#[derive(Clone, Debug, PartialEq)]
5280pub struct TextRun {
5281 pub range: std::ops::Range<usize>,
5282 pub font: FontSpec,
5283 pub color: Option<Color>,
5284 /// A highlight painted behind the glyphs. Every native text editor carries this attribute
5285 /// (docs/texteditor.md), and search hits and review comments are the two things an app is
5286 /// asked for the moment it has styled text at all.
5287 pub background: Option<Color>,
5288 /// A line under the text.
5289 pub underline: Underline,
5290 /// A line through the text. Separate from `FontSpec` because it is a decoration, not a face:
5291 /// no platform expresses it by picking a different font.
5292 pub strikethrough: bool,
5293 /// Makes this run a link to the given target. Rendering it is [`Cap::TextRuns`]; making it
5294 /// activatable is [`Cap::TextLinks`], which is a smaller set (see the docs).
5295 pub link: Option<String>,
5296}
5297
5298impl Default for TextRun {
5299 fn default() -> Self {
5300 TextRun {
5301 range: 0..0,
5302 font: FontSpec::default(),
5303 color: None,
5304 background: None,
5305 underline: Underline::None,
5306 strikethrough: false,
5307 link: None,
5308 }
5309 }
5310}
5311
5312impl TextRun {
5313 /// A run that only changes the font, the common case for emphasis.
5314 pub fn font(range: std::ops::Range<usize>, font: FontSpec) -> Self {
5315 TextRun {
5316 range,
5317 font,
5318 ..TextRun::default()
5319 }
5320 }
5321
5322 /// This run's attributes without its range: what a selection's style is compared against
5323 /// and what an editor's toolbar toggles (docs/texteditor.md).
5324 pub fn style(&self) -> RunStyle {
5325 RunStyle {
5326 font: self.font,
5327 color: self.color,
5328 background: self.background,
5329 underline: self.underline,
5330 strikethrough: self.strikethrough,
5331 link: self.link.clone(),
5332 }
5333 }
5334
5335 /// A run of `style` over `range`.
5336 pub fn styled(range: std::ops::Range<usize>, style: RunStyle) -> Self {
5337 TextRun {
5338 range,
5339 font: style.font,
5340 color: style.color,
5341 background: style.background,
5342 underline: style.underline,
5343 strikethrough: style.strikethrough,
5344 link: style.link,
5345 }
5346 }
5347}
5348
5349/// Serialize a label's text + runs as markup, for the two backends whose text widgets take a
5350/// string in their own dialect rather than a structured attributed string: GTK (Pango markup)
5351/// and Qt (its HTML subset). Shared so the escaping is written and tested once: a translated
5352/// string containing `&` or `<` corrupts the whole label otherwise, and it will be a translated
5353/// string that finds the bug.
5354///
5355/// `dialect` decides the spelling: Pango wants `<span foreground="#rrggbb"
5356/// font_family="monospace">`, Qt wants `<span style="color:#rrggbb">` with `<code>`. Both accept
5357/// `<b>`, `<i>`, `<u>`, `<s>` and `<a href>`, which is why one function can serve them.
5358///
5359/// `base_points` is the size the label itself resolved to. Only a relative-size run
5360/// ([`FontSpec::scale`]) needs it, and only in the Qt dialect: Pango markup takes a percentage
5361/// directly, while Qt's CSS subset understands `pt` and `px` and ignores `%`.
5362pub fn runs_to_markup(
5363 text: &str,
5364 runs: &[TextRun],
5365 dialect: MarkupDialect,
5366 base_points: f64,
5367) -> String {
5368 let mut out = String::with_capacity(text.len() + runs.len() * 24);
5369 let mut at = 0usize;
5370 for r in runs {
5371 // Skip a run whose range does not address this string, without advancing `at`: dropping
5372 // the run loses styling, but advancing past it would drop the rest of the sentence.
5373 // `runs_are_valid` rejects these upstream; this keeps the failure cheap if one slips by.
5374 let Some(styled) = text.get(r.range.clone()) else {
5375 continue;
5376 };
5377 if r.range.start > at
5378 && let Some(plain) = text.get(at..r.range.start)
5379 {
5380 escape_markup_in(plain, &mut out, dialect);
5381 }
5382 open_run(r, dialect, base_points, &mut out);
5383 escape_markup_in(styled, &mut out, dialect);
5384 close_run(r, dialect, &mut out);
5385 at = r.range.end;
5386 }
5387 if let Some(tail) = text.get(at..) {
5388 escape_markup_in(tail, &mut out, dialect);
5389 }
5390 out
5391}
5392
5393impl Symbol {
5394 /// A 24×24 outline path for this symbol, Day's own drawing of it.
5395 ///
5396 /// The platform's icon comes first on every backend that has one (SF Symbols, the freedesktop
5397 /// icon theme, Fluent's glyph font). This is the fallback for when that lookup finds nothing,
5398 /// which is not an edge case: `view-filter-symbolic` exists on a GNOME desktop and nowhere
5399 /// else, so a GTK or Qt app run off that desktop drew a toolbar item with no icon at all.
5400 /// One table here means the same fallback shape everywhere instead of a gap per platform.
5401 ///
5402 /// `None` for a variant with no drawing yet: `Symbol` is `#[non_exhaustive]`, so a new one
5403 /// degrades to a label rather than failing to compile.
5404 pub fn outline_path(self) -> Option<&'static str> {
5405 use Symbol as S;
5406 // The wildcard is unreachable today (every variant is drawn below) and it is here for
5407 // the next one, which should degrade to a label rather than fail to compile.
5408 #[allow(unreachable_patterns)]
5409 Some(match self {
5410 S::Add => "M11 5h2v6h6v2h-6v6h-2v-6H5v-2h6z",
5411 S::Remove => "M5 11h14v2H5z",
5412 S::Delete => "M9 3h6l1 2h4v2H4V5h4zM6 8h12l-1 13H7z",
5413 S::Edit => {
5414 "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"
5415 }
5416 S::New => "M13 2H6v20h12V7h-5zm2 .5L19.5 7H15z",
5417 S::Open => "M2 5h7l2 2h11v12H2z",
5418 S::Save => "M3 3h13l5 5v13H3zm5 0h7v6H8zm-1 11h10v7H7z",
5419 S::Print => "M7 3h10v4H7zM4 8h16v8h-3v6H7v-6H4z",
5420 S::Refresh => "M12 4V1L8 5l4 4V6a6 6 0 1 1-6 6H4a8 8 0 1 0 8-8z",
5421 S::Search => {
5422 "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"
5423 }
5424 S::Share => "M12 3l5 5h-3v7h-4V8H7zM5 17h14v4H5z",
5425 // An eight-tooth gear, round about the center (radius 10 at the teeth, 7.6 at the
5426 // roots) with a 3.2 hole: square in its box, so it sits in a row's 24-point icon
5427 // slot at the same size as its neighbors.
5428 S::Settings => {
5429 "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"
5430 }
5431 S::Info => "M12 2a10 10 0 1 0 0 20 10 10 0 0 0 0-20m-1 5h2v2h-2zm0 4h2v6h-2z",
5432 S::Star => {
5433 "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"
5434 }
5435 S::Bookmark => "M6 2h12v20l-6-4-6 4z",
5436 S::Back => "M15.4 5.4L14 4l-8 8 8 8 1.4-1.4L8.8 12z",
5437 S::Forward => "M8.6 5.4L10 4l8 8-8 8-1.4-1.4L15.2 12z",
5438 S::Up => "M5.4 15.4L4 14l8-8 8 8-1.4 1.4L12 8.8z",
5439 S::Down => "M5.4 8.6L4 10l8 8 8-8-1.4-1.4L12 15.2z",
5440 S::Home => "M12 3l9 8h-3v10h-5v-6h-2v6H6V11H3z",
5441 S::Sidebar => "M3 4h18v16H3zm2 2v12h4V6zm6 0v12h8V6z",
5442 S::Filter => "M3 5h18l-7 8v6l-4 2v-8z",
5443 S::Sort => "M8 4v12H4l4 4 4-4H10V4zM14 6h7v2h-7zm0 4h5v2h-5zm0 4h3v2h-3z",
5444 S::More => {
5445 "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"
5446 }
5447 S::Play => "M8 5l11 7-11 7z",
5448 S::Pause => "M7 5h3v14H7zm7 0h3v14h-3z",
5449 S::Stop => "M6 6h12v12H6z",
5450 S::Camera => {
5451 "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"
5452 }
5453 S::Code => {
5454 "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"
5455 }
5456 S::Light => {
5457 "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"
5458 }
5459 S::Dark => "M12 3a9 9 0 1 0 9 9 7 7 0 0 1-9-9",
5460 // "Automatic": the half-filled circle every platform uses: the left half solid, the
5461 // right half an outline, which `evenodd` below turns into the ring it should be.
5462 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",
5463 S::ZoomIn => {
5464 "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"
5465 }
5466 S::ZoomOut => {
5467 "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"
5468 }
5469 // The ZoomIn lens with a numeral 1 in it, "back to actual size".
5470 S::ZoomReset => {
5471 "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"
5472 }
5473 S::Undo => "M12 5V2L7 7l5 5V9a5 5 0 1 1 0 10H8v2h4a7 7 0 0 0 0-14z",
5474 S::Redo => "M12 5V2l5 5-5 5V9a5 5 0 1 0 0 10h4v2h-4a7 7 0 0 1 0-14z",
5475 S::Copy => "M8 2h10v14H8zM4 6h2v14h12v2H4z",
5476 S::Cut => {
5477 "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"
5478 }
5479 S::Paste => "M9 2h6v2h3v18H6V4h3zm0 2v2h6V4z",
5480 S::Mail => "M2 5h20v14H2zm2 3.2V17h16V8.2l-8 5z",
5481 S::Folder => "M2 5h7l2 2h11v12H2z",
5482 S::Document => "M14 2H6v20h12V6zm.5.8L17.2 6H14.5z",
5483 S::Check => "M9 16.2L4.8 12l-1.4 1.4L9 19 21 7l-1.4-1.4z",
5484 S::Close => {
5485 "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"
5486 }
5487 S::Warning => "M12 2l10 19H2zm-1 7h2v6h-2zm0 8h2v2h-2z",
5488 // Shape outlines, stroked as a 2-unit band (an even-odd ring), so they read as
5489 // outlines at any size rather than filled blocks.
5490 S::Rectangle => "M3 5h18v14H3zm2 2v10h14V7z",
5491 S::Oval => {
5492 "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"
5493 }
5494 // A circular ring (even-odd: outer disc minus inner) and its filled twin.
5495 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",
5496 S::CircleFilled => "M12 4a8 8 0 1 0 0 16 8 8 0 0 0 0-16z",
5497 S::Line => "M4.7 17.9l13.2-13.2 1.4 1.4L6.1 19.3z",
5498 // Group: a solid square stacked on another (the visible L of the back one);
5499 // Ungroup: the same two squares pulled apart.
5500 S::Group => "M8 4h12v12h-4V8H8zM4 8h12v12H4z",
5501 S::Ungroup => "M3 3h8v8H3zM13 13h8v8h-8z",
5502 // `Symbol` is `#[non_exhaustive]`: a variant added upstream draws nothing here rather
5503 // than failing to compile, and its item keeps its label.
5504 _ => return None,
5505 })
5506 }
5507
5508 /// [`Self::outline_path`] wrapped as a standalone SVG document.
5509 pub fn outline_svg(self) -> Option<String> {
5510 self.outline_path().map(|d| {
5511 format!(
5512 "<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 24 24\">\
5513 <path fill-rule=\"evenodd\" d=\"{d}\"/></svg>"
5514 )
5515 })
5516 }
5517}
5518
5519/// Which markup dialect [`runs_to_markup`] should emit.
5520#[derive(Clone, Copy, Debug, PartialEq, Eq)]
5521pub enum MarkupDialect {
5522 /// Pango markup (GTK).
5523 Pango,
5524 /// Qt's rich-text HTML subset.
5525 QtHtml,
5526}
5527
5528/// XML-escape a run of plain text into `out`. `&` first, or the escapes escape each other.
5529///
5530/// Newlines are dialect-specific. Pango lays a literal `\n` out as a line break, but Qt's rich
5531/// text is HTML, where any run of whitespace collapses to one space, which silently ran a
5532/// two-paragraph body together into a single block. `<br>` is what says "break here" in HTML, so
5533/// the same string wraps the same way on both.
5534fn escape_markup_in(s: &str, out: &mut String, dialect: MarkupDialect) {
5535 for c in s.chars() {
5536 match c {
5537 '&' => out.push_str("&"),
5538 '<' => out.push_str("<"),
5539 '>' => out.push_str(">"),
5540 '"' => out.push_str("""),
5541 '\'' => out.push_str("'"),
5542 '\n' if dialect == MarkupDialect::QtHtml => out.push_str("<br>"),
5543 _ => out.push(c),
5544 }
5545 }
5546}
5547
5548/// [`escape_markup_in`] for the URL slot, where a newline cannot appear.
5549fn escape_markup(s: &str, out: &mut String) {
5550 escape_markup_in(s, out, MarkupDialect::Pango);
5551}
5552
5553fn hex(c: Color) -> String {
5554 format!(
5555 "#{:02x}{:02x}{:02x}",
5556 (c.r.clamp(0.0, 1.0) * 255.0) as u8,
5557 (c.g.clamp(0.0, 1.0) * 255.0) as u8,
5558 (c.b.clamp(0.0, 1.0) * 255.0) as u8
5559 )
5560}
5561
5562/// Does this run need a `<span>` in `dialect`, or do the plain tags cover it?
5563fn needs_span(r: &TextRun, dialect: MarkupDialect) -> bool {
5564 let extras = r.color.is_some() || r.background.is_some() || r.font.scale != 1.0;
5565 match dialect {
5566 // Pango expresses the monospace family as a span attribute; Qt cannot (see below).
5567 MarkupDialect::Pango => extras || r.font.monospace,
5568 MarkupDialect::QtHtml => extras,
5569 }
5570}
5571
5572fn open_run(r: &TextRun, dialect: MarkupDialect, base_points: f64, out: &mut String) {
5573 if let Some(url) = r.link.as_deref() {
5574 out.push_str("<a href=\"");
5575 escape_markup(url, out);
5576 out.push_str("\">");
5577 }
5578 // The span carries the attributes that have no tag: colors, relative size, and (on Pango)
5579 // the monospace family. Bold/italic/strike/underline are tags in both dialects, which keeps
5580 // the attribute string short and the escaping trivial.
5581 let color = r.color.map(hex);
5582 let background = r.background.map(hex);
5583 let mono = r.font.monospace;
5584 if needs_span(r, dialect) {
5585 match dialect {
5586 MarkupDialect::Pango => {
5587 out.push_str("<span");
5588 if let Some(c) = &color {
5589 out.push_str(&format!(" foreground=\"{c}\""));
5590 }
5591 if let Some(c) = &background {
5592 out.push_str(&format!(" background=\"{c}\""));
5593 }
5594 if mono {
5595 out.push_str(" font_family=\"monospace\"");
5596 }
5597 if r.font.scale != 1.0 {
5598 // Absolute, in Pango units (1/1024 pt), not the `font_scale`/`size="N%"`
5599 // pair: those are Pango 1.50 attributes, and a Pango that does not know an
5600 // attribute fails the whole markup parse, which renders the label empty
5601 // rather than merely unscaled. A point size still tracks the desktop's text
5602 // scaling, since Pango resolves points through the Xft DPI.
5603 let pts = r.font.resolved_points(base_points);
5604 out.push_str(&format!(" size=\"{}\"", (pts * 1024.0).round() as i64));
5605 }
5606 out.push('>');
5607 }
5608 MarkupDialect::QtHtml => {
5609 // Color only. Qt's rich text does not resolve the generic `monospace` family
5610 // from a style attribute (it rendered proportional), so the fixed face comes
5611 // from the `<code>` tag below, which Qt maps to its own fixed font.
5612 out.push_str("<span style=\"");
5613 if let Some(c) = &color {
5614 out.push_str(&format!("color:{c};"));
5615 }
5616 if let Some(c) = &background {
5617 out.push_str(&format!("background-color:{c};"));
5618 }
5619 if r.font.scale != 1.0 {
5620 // Points, not a percentage: Qt's rich-text CSS subset understands `pt` and
5621 // `px` and silently ignores `%`, which is why a scaled run rendered at the
5622 // base size here while every other backend scaled it.
5623 let pt = r.font.resolved_points(base_points);
5624 out.push_str(&format!("font-size:{pt}pt;"));
5625 }
5626 out.push_str("\">");
5627 }
5628 }
5629 }
5630 if dialect == MarkupDialect::QtHtml && mono {
5631 out.push_str("<code>");
5632 }
5633 if r.font.weight.is_some_and(|w| w >= FontWeight::Semibold) {
5634 out.push_str("<b>");
5635 }
5636 if r.font.italic {
5637 out.push_str("<i>");
5638 }
5639 if r.underline.is_on() {
5640 out.push_str("<u>");
5641 }
5642 if r.strikethrough {
5643 out.push_str("<s>");
5644 }
5645}
5646
5647fn close_run(r: &TextRun, dialect: MarkupDialect, out: &mut String) {
5648 if r.strikethrough {
5649 out.push_str("</s>");
5650 }
5651 if r.underline.is_on() {
5652 out.push_str("</u>");
5653 }
5654 if r.font.italic {
5655 out.push_str("</i>");
5656 }
5657 if r.font.weight.is_some_and(|w| w >= FontWeight::Semibold) {
5658 out.push_str("</b>");
5659 }
5660 if dialect == MarkupDialect::QtHtml && r.font.monospace {
5661 out.push_str("</code>");
5662 }
5663 if needs_span(r, dialect) {
5664 out.push_str("</span>");
5665 }
5666 if r.link.is_some() {
5667 out.push_str("</a>");
5668 }
5669}
5670
5671/// Are these runs well formed for `text`: ascending, non-overlapping, inside the string, and on
5672/// character boundaries?
5673///
5674/// Checked once in the pieces layer rather than in eight backends. A backend handed overlapping
5675/// ranges would produce a different wrong answer per platform, and a range splitting a multi-byte
5676/// character would panic on `str` slicing in some and render mojibake in others.
5677pub fn runs_are_valid(text: &str, runs: &[TextRun]) -> Result<(), String> {
5678 let mut prev_end = 0usize;
5679 for (i, r) in runs.iter().enumerate() {
5680 if r.range.start < prev_end {
5681 return Err(format!(
5682 "run {i} starts at {} but the previous run ends at {prev_end} — runs must be \
5683 ascending and non-overlapping",
5684 r.range.start
5685 ));
5686 }
5687 if r.range.end > text.len() {
5688 return Err(format!(
5689 "run {i} ends at {} but the text is {} bytes",
5690 r.range.end,
5691 text.len()
5692 ));
5693 }
5694 if r.range.start > r.range.end {
5695 return Err(format!("run {i} has an inverted range {:?}", r.range));
5696 }
5697 if !text.is_char_boundary(r.range.start) || !text.is_char_boundary(r.range.end) {
5698 return Err(format!(
5699 "run {i} range {:?} splits a multi-byte character",
5700 r.range
5701 ));
5702 }
5703 prev_end = r.range.end;
5704 }
5705 Ok(())
5706}
5707
5708pub mod props {
5709 use super::*;
5710
5711 #[derive(Clone, Debug, Default, PartialEq)]
5712 pub struct ContainerProps {
5713 pub background: Option<Color>,
5714 pub corner_radius: f64,
5715 pub clips: bool,
5716 /// Semantic, theme-adaptive surface, mapped by each backend to a native material that
5717 /// follows the platform's light/dark appearance automatically (unlike the fixed-RGBA
5718 /// `background`, which it overrides when set).
5719 pub role: Option<super::SurfaceRole>,
5720 }
5721 /// Reactive surface update for a `background(..)` decorator whose color is a signal/closure:
5722 /// the backend re-applies the fill on the container's native backing view. Corner radius and
5723 /// clipping are fixed at realize (the `corner_radius(r)` decorator takes a plain `f64`).
5724 #[derive(Clone, Debug, PartialEq)]
5725 pub enum ContainerPatch {
5726 Background(Option<Color>),
5727 }
5728
5729 /// Realize props for a `scroll` container: which axis it scrolls. Backends create the matching
5730 /// native scroll view (vertical `UIScrollView`/`ScrollView`, horizontal
5731 /// `HorizontalScrollView`, etc.).
5732 #[derive(Clone, Debug, Default, PartialEq)]
5733 pub struct ScrollProps {
5734 pub horizontal: bool,
5735 }
5736
5737 #[derive(Clone, Debug, Default, PartialEq)]
5738 pub struct LabelProps {
5739 pub text: String,
5740 pub font: FontSpec,
5741 pub color: Option<Color>,
5742 /// What the text means, for the color the platform gives it (docs/text.md).
5743 ///
5744 /// Semantic the way [`crate::Font`] is semantic: an app says "this is secondary text"
5745 /// and each platform answers with its own answer: `secondaryLabelColor` on Apple,
5746 /// `?android:textColorSecondary`, GTK's `dim-label`. That is the only way a de-emphasized
5747 /// label stays correct in both appearances, since a literal grey that reads well on white
5748 /// is wrong on black. An explicit [`Self::color`] still wins; a backend that has no such
5749 /// color renders primary, which is legible and correct, just not dimmed.
5750 pub role: TextRole,
5751 pub wraps: bool,
5752 /// Maximum rendered lines; zero is unlimited. Apple and Android plain labels truncate
5753 /// the last line. Other backends may retain their ordinary wrapping behavior.
5754 pub max_lines: u32,
5755 /// How the label's lines sit within its own width. Only observable on a label that
5756 /// wraps or carries explicit newlines: a single line fills its box, so its alignment is
5757 /// the container's business, not the label's.
5758 ///
5759 /// `Leading` is the default and is what running text wants; `Center` is for the short,
5760 /// centered block a welcome screen or an empty state uses. A backend that cannot set
5761 /// it renders leading-aligned, which is legible and correct, just not centered.
5762 pub align: TextAlign,
5763 /// Styled spans within `text` (docs/text-runs.md). Empty is the overwhelmingly common
5764 /// case and means exactly what a label has always meant: one font, one color. A backend
5765 /// that cannot draw runs ignores this and renders `text` uniformly, which is legible and
5766 /// correct, just unstyled.
5767 pub runs: Vec<crate::TextRun>,
5768 }
5769 /// What a label's text means, for the color the platform gives it (`LabelProps::role`).
5770 #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
5771 pub enum TextRole {
5772 /// Ordinary text, in the platform's primary label color.
5773 #[default]
5774 Primary,
5775 /// De-emphasized text: a caption, a hint, the "nothing selected" line an empty detail
5776 /// pane shows. Rendered in the platform's secondary label color.
5777 Secondary,
5778 }
5779
5780 /// How a wrapped label's lines sit within its width (`LabelProps::align`).
5781 ///
5782 /// There is no `Justified` variant because no toolkit in Day's set agrees on how to justify
5783 /// the last line, and the ones that can do it at all need a paragraph style the others have
5784 /// no equivalent for.
5785 #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
5786 pub enum TextAlign {
5787 /// Left in a left-to-right locale, right in an RTL one (docs/localization.md).
5788 #[default]
5789 Leading,
5790 Center,
5791 Trailing,
5792 }
5793
5794 #[derive(Clone, Debug, PartialEq)]
5795 pub enum LabelPatch {
5796 Text(String),
5797 Color(Option<Color>),
5798 Font(FontSpec),
5799 /// New text and its runs together. One patch, not two: a run's byte range is only
5800 /// meaningful against a particular string, so applying them separately would leave the
5801 /// widget briefly holding ranges that point into the wrong text.
5802 Runs(String, Vec<crate::TextRun>),
5803 }
5804
5805 /// A button's native styling tier. `Automatic` is the toolkit's stock look; `Bordered`
5806 /// asks for a visually contained button where the stock look is borderless (iOS's plain
5807 /// system button reads as a link); `Prominent` asks for the platform's accent-filled /
5808 /// default-action affordance. Toolkits whose stock buttons are already contained treat
5809 /// `Bordered` as `Automatic`.
5810 // `Eq` is gone with the `Tinted` color: `Color` holds floats. `PartialEq` is what the
5811 // props diff uses, and that is unaffected.
5812 #[derive(Clone, Copy, Debug, Default, PartialEq)]
5813 pub enum ButtonStyleSpec {
5814 #[default]
5815 Automatic,
5816 Bordered,
5817 Prominent,
5818 /// A filled button in an app-chosen color, still drawn by the native control: the
5819 /// platform keeps its own pressed, hover, focus and disabled rendering, its button role,
5820 /// and its keyboard activation. The label color is not carried; each backend picks the
5821 /// readable one for the fill (see [`ButtonStyleSpec::on_tint`]), the same call the
5822 /// platform's own tinted buttons make.
5823 ///
5824 /// A backend with no way to recolor its button ignores this and draws its ordinary
5825 /// button. That is the trade: a plain button everywhere beats a colored
5826 /// rectangle that is no longer a button on the platforms that cannot.
5827 Tinted(Color),
5828 /// A button no wider than its title asks for (a one-glyph "−" or "+" in a stepper,
5829 /// a "×" on a chip) on toolkits whose stock button carries a minimum width and wide
5830 /// insets (Material's 88 dp button turns a two-button stepper into 240 dp). The native
5831 /// control stays: only its minimum width and horizontal padding are reduced. A toolkit
5832 /// whose buttons already hug their title (AppKit, UIKit's plain button, Qt) draws its
5833 /// ordinary button.
5834 Compact,
5835 /// Borderless native action button; compact horizontal insets on Material.
5836 Plain,
5837 }
5838
5839 impl ButtonStyleSpec {
5840 /// The label color to draw on a [`ButtonStyleSpec::Tinted`] fill: whichever of black or
5841 /// white contrasts better against it, by WCAG's contrast ratio.
5842 ///
5843 /// Comparing the two ratios rather than thresholding the luminance is the difference
5844 /// between right and nearly right. A mid amber (`#F0A64C`) has a relative luminance of
5845 /// 0.44; under a "brighter than half" test it reads as dark and takes white text, at a
5846 /// hopeless 2.2:1. Its contrast against black is 9.7:1. The two ratios cross at a
5847 /// luminance of 0.179, not 0.5, and everything between those two numbers is a button
5848 /// nobody can read.
5849 pub fn on_tint(fill: Color) -> Color {
5850 // WCAG relative luminance: sRGB channels linearized, then weighted by the eye's
5851 // sensitivity to each.
5852 let lin = |c: f64| {
5853 let c = c.clamp(0.0, 1.0);
5854 if c <= 0.04045 {
5855 c / 12.92
5856 } else {
5857 ((c + 0.055) / 1.055).powf(2.4)
5858 }
5859 };
5860 let l = 0.2126 * lin(fill.r) + 0.7152 * lin(fill.g) + 0.0722 * lin(fill.b);
5861 // Contrast ratio is (lighter + 0.05) / (darker + 0.05); white is 1.0, black is 0.0.
5862 let against_white = 1.05 / (l + 0.05);
5863 let against_black = (l + 0.05) / 0.05;
5864 if against_black >= against_white {
5865 Color::BLACK
5866 } else {
5867 Color::WHITE
5868 }
5869 }
5870 }
5871
5872 #[derive(Clone, Debug, Default, PartialEq)]
5873 /// The visible content and accessible title of a button with an icon.
5874 pub struct ButtonContent {
5875 /// Also serves as the accessible name when only the icon is visible.
5876 pub title: String,
5877 pub icon: Option<Icon>,
5878 pub icon_only: bool,
5879 }
5880 #[derive(Clone, Debug, Default, PartialEq)]
5881 pub struct ButtonProps {
5882 pub title: String,
5883 pub icon: Option<Icon>,
5884 pub icon_only: bool,
5885 pub enabled: bool,
5886 pub style: ButtonStyleSpec,
5887 /// The button stands for the current choice among its siblings (a document tab, a
5888 /// view switcher): the platform's own checked or selected rendering, which keeps the
5889 /// button enabled, focusable and activatable, and tells assistive tech it is selected.
5890 /// A click never toggles it natively; only the app's next patch changes it.
5891 pub selected: bool,
5892 }
5893 #[derive(Clone, Debug, PartialEq)]
5894 pub enum ButtonPatch {
5895 Title(String),
5896 /// Update an icon button's label and icon together. Plain buttons still use `Title`.
5897 Content(ButtonContent),
5898 Enabled(bool),
5899 /// The selected state (see [`ButtonProps::selected`]).
5900 Selected(bool),
5901 /// A live style change: what a reactive `.tint(…)` sends, so a button can recolor with
5902 /// app state without being torn down and realized again.
5903 Style(ButtonStyleSpec),
5904 }
5905
5906 #[derive(Clone, Debug, Default, PartialEq)]
5907 pub struct ToggleProps {
5908 pub on: bool,
5909 pub enabled: bool,
5910 }
5911 #[derive(Clone, Debug, PartialEq)]
5912 pub enum TogglePatch {
5913 On(bool),
5914 Enabled(bool),
5915 }
5916
5917 #[derive(Clone, Debug, PartialEq)]
5918 pub struct SliderProps {
5919 pub value: f64,
5920 pub min: f64,
5921 pub max: f64,
5922 pub step: Option<f64>,
5923 pub enabled: bool,
5924 }
5925 impl Default for SliderProps {
5926 fn default() -> Self {
5927 SliderProps {
5928 value: 0.0,
5929 min: 0.0,
5930 max: 1.0,
5931 step: None,
5932 enabled: true,
5933 }
5934 }
5935 }
5936 #[derive(Clone, Debug, PartialEq)]
5937 pub enum SliderPatch {
5938 Value(f64),
5939 Enabled(bool),
5940 }
5941
5942 /// SwiftUI's `pickerStyle` analogue (kinds::PICKER). Each maps to a distinct native
5943 /// control per toolkit (docs/picker.md).
5944 #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
5945 pub enum PickerStyle {
5946 /// A dropdown/pop-up menu (NSPopUpButton / GtkDropDown / QComboBox / UIButton+UIMenu / Spinner).
5947 #[default]
5948 Menu,
5949 /// A horizontal segmented control (NSSegmentedControl / UISegmentedControl / linked toggles / …).
5950 Segmented,
5951 /// A vertical radio-button group laid out inline (NSButton radios / GtkCheckButton group / …).
5952 Inline,
5953 }
5954
5955 /// Full picker props (realize). `style` is set once at build; `options`, `selected` and
5956 /// `enabled` patch (via [`PickerPatch`]).
5957 #[derive(Clone, Debug, PartialEq)]
5958 pub struct PickerProps {
5959 /// Decorative boundaries before option indexes (not selectable options). Native menu
5960 /// grouping on AppKit/UIKit; ignored by other backends and non-menu styles.
5961 pub separators_before: Vec<usize>,
5962 pub options: Vec<String>,
5963 pub selected: usize,
5964 pub style: PickerStyle,
5965 /// Whether the picker takes input. Default `true`.
5966 pub enabled: bool,
5967 }
5968 impl Default for PickerProps {
5969 fn default() -> Self {
5970 PickerProps {
5971 separators_before: Vec::new(),
5972 options: Vec::new(),
5973 selected: 0,
5974 style: PickerStyle::default(),
5975 enabled: true,
5976 }
5977 }
5978 }
5979
5980 #[derive(Clone, Debug, PartialEq)]
5981 pub enum PickerPatch {
5982 Selected(usize),
5983 /// New option labels, for a picker whose choices come from data (a document list, a
5984 /// live count). The backend rebuilds its items and keeps the selected index where it
5985 /// still exists, clamping to the last option otherwise; a fresh
5986 /// [`PickerPatch::Selected`] follows whenever the app's own binding disagrees.
5987 Options(Vec<String>),
5988 /// Enable or disable the whole control, every style alike.
5989 Enabled(bool),
5990 }
5991
5992 /// Full text-area props (realize, kinds::TEXT_AREA; docs/textarea.md). `text` seeds the
5993 /// editor; `min_lines`/`max_lines` bound the auto-growing height in text lines
5994 /// (`max_lines == 0` = unbounded). `editable`/`selectable`/`spellcheck` control the native
5995 /// editor attributes (all default `true`); a backend that can't honor one answers
5996 /// `Cap::Text{Editable,Selectable,SpellCheck}` = `Unsupported`. `text` and the three attributes
5997 /// change after build (via [`TextAreaPatch`]); the rest are build-only.
5998 #[derive(Clone, Debug, PartialEq)]
5999 pub struct TextAreaProps {
6000 pub text: String,
6001 pub placeholder: String,
6002 pub min_lines: u32,
6003 pub max_lines: u32,
6004 /// Whether the user can edit the text (`false` = read-only). Default `true`.
6005 pub editable: bool,
6006 /// Whether the text can be selected (and copied). Default `true`.
6007 pub selectable: bool,
6008 /// Whether spell-check / autocorrect highlighting is on. Default `true`.
6009 pub spellcheck: bool,
6010 /// Plain Enter emits `Event::Submitted` instead of inserting a newline (Shift+Enter
6011 /// still inserts one where the platform can distinguish). Chat composers. Default
6012 /// `false`.
6013 pub submit_on_enter: bool,
6014 }
6015
6016 impl Default for TextAreaProps {
6017 fn default() -> Self {
6018 TextAreaProps {
6019 text: String::new(),
6020 placeholder: String::new(),
6021 min_lines: 1,
6022 max_lines: 0,
6023 editable: true,
6024 selectable: true,
6025 spellcheck: true,
6026 submit_on_enter: false,
6027 }
6028 }
6029 }
6030
6031 /// Imperative text-area updates: replace the text (programmatic sync), or flip one of the
6032 /// live attributes.
6033 #[derive(Clone, Debug, PartialEq)]
6034 pub enum TextAreaPatch {
6035 SetText(String),
6036 SetEditable(bool),
6037 SetSelectable(bool),
6038 SetSpellCheck(bool),
6039 }
6040
6041 #[derive(Clone, Debug, Default, PartialEq)]
6042 pub struct TextFieldProps {
6043 pub text: String,
6044 pub placeholder: String,
6045 pub enabled: bool,
6046 }
6047 #[derive(Clone, Debug, PartialEq)]
6048 pub enum TextFieldPatch {
6049 /// Origin-tagged write (§4.4): `from_native` suppresses the echo back into the widget.
6050 Text {
6051 text: String,
6052 from_native: bool,
6053 },
6054 Placeholder(String),
6055 Enabled(bool),
6056 }
6057
6058 /// How an image is scaled to fill its frame (§18.3). Maps to each toolkit's native scaling.
6059 #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
6060 pub enum ContentMode {
6061 /// Scale to fit entirely inside the frame, preserving aspect ratio (letterboxed). The
6062 /// default: an image never stretches unless asked. SwiftUI's `.scaledToFit`.
6063 #[default]
6064 Fit,
6065 /// Scale to fill the frame, preserving aspect ratio and cropping the overflow. SwiftUI's
6066 /// `.scaledToFill`.
6067 Fill,
6068 /// Stretch to fill the frame exactly, ignoring aspect ratio.
6069 Stretch,
6070 }
6071
6072 #[derive(Clone, Debug, Default, PartialEq)]
6073 pub struct ImageProps {
6074 /// Which pixels to draw: a staged asset name, encoded bytes, or an already-decoded
6075 /// image ([`ImageSource`], docs/images.md). A name resolves through the backend's own
6076 /// pipeline (§18.2); bytes and decoded ids need [`Cap::ImageDecode`], and a backend
6077 /// without it draws nothing rather than guessing.
6078 pub source: ImageSource,
6079 pub decorative: bool,
6080 /// How the image scales within its frame (default [`ContentMode::Fit`], no stretching).
6081 pub content_mode: ContentMode,
6082 /// Optional width:height ratio the view is constrained to (e.g. `16.0/9.0`). `None` lets the
6083 /// image take its allocated frame.
6084 pub aspect_ratio: Option<f64>,
6085 /// Monochrome tint for a template/vector glyph (docs/vectors.md): backends that can,
6086 /// recolor natively (template rendering on Apple, drawable tint on Android, pixel
6087 /// recolor on GTK); backends that can't yet ignore it and draw the source colors.
6088 /// `None` (the default, and every raster `image(…)`) means "as authored".
6089 pub tint: Option<Color>,
6090 /// A monochrome template glyph (docs/vectors.md "Template"): with no `tint`, it draws
6091 /// in the foreground of the surface it sits on — the theme's label color on the
6092 /// desktops, the cell's tint on UIKit, `currentColor` on the web — and follows a
6093 /// theme switch. What a sidebar row's untinted icon is: a tinted glyph recolors the
6094 /// same way with or without this, and `false` (the default) draws an untinted glyph as
6095 /// authored. [`ImagePatch::Tint`]`(None)` on a template returns to that foreground,
6096 /// not to the authored colors.
6097 pub template: bool,
6098 }
6099
6100 /// A list row's standard content (`kinds::LIST_ITEM`, docs/list.md "List items"). Empty
6101 /// text means the part is absent.
6102 #[derive(Clone, Debug, Default, PartialEq)]
6103 pub struct ListItemProps {
6104 pub title: String,
6105 /// A second line under the title, in the platform's secondary style.
6106 pub subtitle: String,
6107 /// Trailing text (a count, a value), in the platform's secondary style.
6108 pub detail: String,
6109 /// The leading glyph: a symbol or a bundled image.
6110 pub icon: Option<crate::Icon>,
6111 /// The glyph's color; `None` takes the platform's own (template glyphs follow the
6112 /// foreground, the tint color on UIKit).
6113 pub icon_tint: Option<Color>,
6114 /// A trailing check mark: the platform's selected-option mark (UIKit's checkmark
6115 /// accessory, a Material check icon), announced as checked.
6116 pub checked: bool,
6117 }
6118
6119 /// A live change to a realized list item; every part changes in place.
6120 #[derive(Clone, Debug, PartialEq)]
6121 pub enum ListItemPatch {
6122 Title(String),
6123 Subtitle(String),
6124 Detail(String),
6125 Icon(Option<crate::Icon>),
6126 IconTint(Option<Color>),
6127 Checked(bool),
6128 }
6129
6130 /// A live change to a realized image or vector glyph.
6131 ///
6132 /// `content_mode` and the rest still describe which art this is and how it fills its frame,
6133 /// which a rebuild expresses better than a patch. Two things do want to follow a signal: the
6134 /// tint (a glyph that recolors with the selection or the theme should repaint, not be torn
6135 /// down and realized again, docs/vectors.md "Tint") and the source, now that it can be a
6136 /// buffer the app swaps (a download landing, a new photo picked, docs/images.md). Replacing
6137 /// the pixels of a view that is already on screen is what a patch is for; realizing a second
6138 /// view would flash.
6139 #[derive(Clone, Debug, PartialEq)]
6140 pub enum ImagePatch {
6141 /// Recolor the glyph, or `None` to draw the authored colors again.
6142 Tint(Option<Color>),
6143 /// Draw different pixels in the same view. A backend that cannot decode the new source
6144 /// (bytes where [`Cap::ImageDecode`] is `Unsupported`) leaves what it was drawing.
6145 Source(ImageSource),
6146 }
6147
6148 #[derive(Clone, Debug, Default, PartialEq)]
6149 pub struct CanvasProps {
6150 pub ops: Vec<DrawOp>,
6151 }
6152
6153 /// Progress indicator. `value` is the completed fraction in `0.0..=1.0`; `None` means
6154 /// indeterminate (an animated spinner / busy bar, no known extent). Backends map this to
6155 /// their native determinate/indeterminate widgets (docs/progress.md).
6156 #[derive(Clone, Debug, PartialEq)]
6157 pub struct ProgressProps {
6158 pub value: Option<f64>,
6159 /// Whether an indeterminate indicator animates; ignored for a determinate bar.
6160 pub animating: bool,
6161 /// The platform's large indicator size.
6162 pub large: bool,
6163 }
6164 impl Default for ProgressProps {
6165 fn default() -> Self {
6166 Self {
6167 value: None,
6168 animating: true,
6169 large: false,
6170 }
6171 }
6172 }
6173 #[derive(Clone, Debug, PartialEq)]
6174 pub enum ProgressPatch {
6175 Animating(bool),
6176 /// New completed fraction, or `None` to switch to indeterminate.
6177 Value(Option<f64>),
6178 }
6179
6180 /// A rule between neighbors (`divider()`): a hairline across the width it is offered, or,
6181 /// with `vertical`, down the height it is offered (`divider().vertical()`, between a
6182 /// row's panes). A toolkit measures both the same way, as a horizontal rule, because the
6183 /// pieces layer swaps the axes of a vertical one's proposal and answer; realization is
6184 /// where the orientation matters, for the few widgets that draw a horizontal line
6185 /// regardless of their frame.
6186 #[derive(Clone, Debug, Default, PartialEq)]
6187 pub struct DividerProps {
6188 pub vertical: bool,
6189 }
6190
6191 /// How a navigation host lays its panes out (docs/navigation.md).
6192 ///
6193 /// This is the resolved presentation, what the toolkit must draw right now. The app asks for
6194 /// one through `Nav::presentation`, where leaving it unset means "automatic": the pieces
6195 /// layer resolves it from the window's [`SizeClass`] and the toolkit's `Cap::NavSplit`, and
6196 /// re-resolves it whenever the class changes. There is no `Auto` variant here because a
6197 /// backend can only ever draw a concrete one, so the undecided state stays on the app's side
6198 /// of the boundary where it can still be decided.
6199 #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
6200 pub enum NavPresentation {
6201 /// Sidebar beside detail, both visible (`NSSplitViewController`, nested `GtkPaned`s,
6202 /// a `NavigationView`). The sidebar pane gets its own container.
6203 Split,
6204 /// One page at a time, back-navigable. The sidebar pane becomes the stack's root.
6205 #[default]
6206 Stack,
6207 /// The rows drawn as a tab bar, one page's content beside it, no back stack: what a
6208 /// phone-shaped window wants from a one-of-N surface (`UITabBarController`, a Material
6209 /// `NavigationBarView`, `NavigationView.PaneDisplayMode = Top`). The `Pane::Sidebar` page
6210 /// is not drawn at all: its rows are the chrome.
6211 Tabs,
6212 /// The rows drawn as a narrow icon strip beside the content, the `Medium`-width answer
6213 /// between [`Self::Tabs`] and [`Self::Split`] (a Material `NavigationRailView`,
6214 /// `PaneDisplayMode = LeftCompact`, an ArkUI vertical `Tabs`).
6215 ///
6216 /// A backend with no rail rounds it to a neighbor of its own choosing rather than
6217 /// failing: UIKit answers `Tabs` (which is what iPadOS does at that width), GTK the same.
6218 /// Rounding is expected and correct; this variant is a request, not a contract.
6219 Rail,
6220 }
6221
6222 impl NavPresentation {
6223 /// `true` for [`NavPresentation::Split`], the shape most backend code wants.
6224 pub fn is_split(self) -> bool {
6225 self == NavPresentation::Split
6226 }
6227
6228 /// `true` when the rows are the chrome rather than a drawn page: [`Self::Tabs`] and
6229 /// [`Self::Rail`]. Both hide the `Pane::Sidebar` page and render its rows themselves, so
6230 /// backend code that only cares about that distinction asks this instead of matching both.
6231 pub fn rows_are_chrome(self) -> bool {
6232 matches!(self, NavPresentation::Tabs | NavPresentation::Rail)
6233 }
6234 }
6235
6236 /// Navigation host (docs/navigation.md).
6237 #[derive(Clone, Debug, Default, PartialEq)]
6238 pub struct NavProps {
6239 /// Document-tab chrome, independent of navigation destinations.
6240 pub documents: Option<DocumentTabsConfig>,
6241 pub title: String,
6242 /// The presentation to draw now; re-presented in place by [`NavPatch::Presentation`].
6243 pub presentation: NavPresentation,
6244 /// The app left the presentation automatic (`NavStyle::Automatic`, or a `Sidebar`
6245 /// nav host with no `.presentation(…)` pin), so it is free to follow the window.
6246 ///
6247 /// Only a toolkit answering `Cap::NavRepresent = Emulated` needs this: its own adaptive
6248 /// container owns the morph, and it must know whether the app asked for one at all before
6249 /// building it. With two presentations that bit could be inferred from a lowered `Split`;
6250 /// with four it cannot, so it is carried explicitly rather than encoded.
6251 ///
6252 /// `Native` re-presenters ignore it (they are told each presentation as it is resolved),
6253 /// and so do toolkits that cannot re-present.
6254 pub adaptive: bool,
6255 /// Draw the platform's own show/hide-sidebar affordance on this host's chrome
6256 /// (docs/toolbars.md). `true` for every `nav(Sidebar)` unless the app opted out:
6257 /// the toolkit owns both the button and the behavior
6258 /// (`NSToolbarToggleSidebarItemIdentifier`, the split view's collapse on GTK,
6259 /// `NavigationView.IsPaneOpen` on XAML), so an app that once declared the item by hand
6260 /// now declares nothing. Hosts with no sidebar ignore it.
6261 pub sidebar_toggle: bool,
6262 /// Search over this navigation surface (`Nav::searchable`, docs/search.md).
6263 /// `None` = the surface is not searchable and no field is rendered anywhere.
6264 pub search: Option<SearchProps>,
6265 /// `Some(width)` = this host has a content-list pane ([`Pane::List`]) at this preferred
6266 /// width in points, between the sidebar and the detail (docs/navigation.md). Read at
6267 /// realize, because a backend that builds a different container for a three-pane host
6268 /// (UIKit's triple-column style is init-only) needs to know before it builds. `None` on
6269 /// every host without one, including all of them on backends answering
6270 /// [`crate::Cap::NavContentList`] `Unsupported`: the pieces layer composes there and
6271 /// the prop is never set.
6272 pub list_width: Option<f64>,
6273 /// Whether that pane is showing for the destination the host opens on
6274 /// (`Nav::content_list_for`). Read at realize, like `list_width`, and for a
6275 /// related reason: a backend whose pane is a real split item can only honor a
6276 /// collapsed state reliably by setting it before the item joins the split. Told
6277 /// afterwards (by `NavPatch::ListVisible`, on a window that has not been displayed
6278 /// yet), AppKit reports the item collapsed and then lays it back out from its holding
6279 /// priorities, and the app opens with a list beside a page that does not own one.
6280 /// `true` on every host whose first destination has a list, and on hosts with no pane
6281 /// at all, where it means nothing.
6282 pub list_visible: bool,
6283 }
6284
6285 /// Switch only tab chrome; resident contents must retain their native identity.
6286 #[derive(Clone, Copy, Debug, PartialEq)]
6287 pub struct DocumentTabsPatch {
6288 pub native: bool,
6289 }
6290
6291 /// Localized document-tab chrome. Native callbacks emit stable route keys.
6292 #[derive(Clone, Debug, Default, PartialEq)]
6293 pub struct DocumentTabsConfig {
6294 pub new_label: String,
6295 pub close_label: String,
6296 pub can_add: bool,
6297 }
6298
6299 /// Where a searchable surface's field should be drawn.
6300 ///
6301 /// A preference, not an instruction: a backend that cannot honor the request falls back to
6302 /// whatever its platform does, exactly as SwiftUI's `searchable(placement:)` does ("depending
6303 /// on the containing view hierarchy and platform, the requested placement may not be able to
6304 /// be fulfilled"). `Automatic` is the one to reach for: it is what lets the field live in the
6305 /// window toolbar on a wide window and move into the navigation list on a narrow one.
6306 #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
6307 pub enum SearchPlacement {
6308 /// The platform decides, from the window's size class and its own convention.
6309 #[default]
6310 Automatic,
6311 /// In the window's toolbar (`NSSearchToolbarItem`, an `AdwHeaderBar` entry, a
6312 /// `CommandBar` `AutoSuggestBox`). `Inline` where the toolbar cannot hold a search field
6313 /// (`Cap::ToolbarSearch`).
6314 Toolbar,
6315 /// Attached to the navigation surface itself: above the sidebar list, or in the
6316 /// navigation bar's search drawer on the phones.
6317 Inline,
6318 }
6319
6320 /// Search over a navigation surface (docs/search.md). The query itself stays an app-owned
6321 /// signal; this carries only what the toolkit must draw, so moving the field between
6322 /// placements never moves the state.
6323 #[derive(Clone, Debug, Default, PartialEq)]
6324 pub struct SearchProps {
6325 /// Current text. Two-way: the user typing emits [`Event::SearchChanged`], and the app's
6326 /// own writes arrive as [`SearchPatch::Text`].
6327 pub text: String,
6328 /// Empty-state prompt.
6329 pub prompt: String,
6330 pub placement: SearchPlacement,
6331 /// Opt into native scrolling search/title chrome on mobile. Default false keeps
6332 /// the field pinned. Desktop toolbar search is unchanged.
6333 pub hides_on_scroll: bool,
6334 /// Start the UIKit navigation search drawer collapsed, with a compact toolbar title.
6335 /// Implies scrolling search on UIKit; ignored by other backends. Default false.
6336 pub initially_hidden: bool,
6337 /// Scope titles, empty = no scope bar. One-of-N: a `UISearchBar` scope bar, a Material
6338 /// `ChipGroup` of single-selection filter chips, an ArkUI `SegmentButtonV2`, an
6339 /// `NSSegmentedControl` (docs/search.md has the per-backend table).
6340 pub scopes: Vec<String>,
6341 /// Index into `scopes`; meaningless when `scopes` is empty.
6342 pub scope: usize,
6343 /// Completions offered for the current text. On a navigation surface these complete the
6344 /// field rather than replacing the list: the list is already the result set, so an
6345 /// overlay of results would cover the thing it is filtering.
6346 pub suggestions: Vec<String>,
6347 }
6348
6349 /// A targeted update to a live search field, the path a bound signal writes through, so
6350 /// syncing text never rebuilds (and refocuses) the field mid-word.
6351 #[derive(Clone, Debug, PartialEq)]
6352 pub enum SearchPatch {
6353 Focus,
6354 Text(String),
6355 Scope(usize),
6356 Suggestions(Vec<String>),
6357 }
6358 /// Applied to the nav host after a page child is attached / before it is removed;
6359 /// the toolkit animates its native presentation accordingly.
6360 #[derive(Clone, Debug, PartialEq)]
6361 pub enum NavPatch {
6362 /// The just-attached last page child became the top of the stack. `immersive` marks a
6363 /// page that keeps the floating transparent chrome on backends with an immersive nav
6364 /// mode (day-toolkit-material edge-to-edge today; ignored elsewhere). Unmarked pages get the
6365 /// standard opaque bar.
6366 Pushed { title: String, immersive: bool },
6367 /// The top page is about to be removed; present its predecessor.
6368 Popped,
6369 /// Current top-of-stack title changed.
6370 Title(String),
6371 /// The top page has a back guard (`NavStack::on_back`, docs/navigation.md): while `true`,
6372 /// the toolkit must not auto-pop on a native back gesture/button but route it to
6373 /// Day as `Event::NavBack { already_popped: false }` so the app's guard decides. On
6374 /// backends whose back already routes through Day (AppKit/Qt/XAML/web custom headers)
6375 /// this is a no-op; iOS disables the swipe, Android holds its callback, GTK sets the
6376 /// page `can-pop=false`, ArkUI consumes `onBackPressed`.
6377 GuardTop(bool),
6378 /// Re-present the host: the window's size class crossed a breakpoint, or the app wrote a
6379 /// new `presentation`. The page children do not change: the toolkit rebuilds its
6380 /// chrome and re-homes the pages it already has, each one landing by its
6381 /// [`NavPageProps::pane`]. Rebuilding them instead would drop scroll offsets, field
6382 /// focus, and every native animation in flight, which is why this is a patch and not
6383 /// a rebuild.
6384 ///
6385 /// Backends with no split container ignore it and stay stacked.
6386 Presentation(NavPresentation),
6387 /// Show the resident [`Pane::Detail`] page at this index, counting the host's detail
6388 /// children in attach order. The counterpart to [`Self::Pushed`]/[`Self::Popped`] for the
6389 /// presentations where pages are resident rather than stacked
6390 /// ([`NavPresentation::rows_are_chrome`]): a tab bar switches between pages that all stay
6391 /// alive, so there is nothing to push and nothing to pop.
6392 ///
6393 /// Applied without re-emitting [`crate::Event::SelectionChanged`], per the from-native
6394 /// echo rule: this is the programmatic-sync direction.
6395 ///
6396 /// A backend drawing a stacked presentation never receives it; the pieces layer sends
6397 /// push/pop there instead.
6398 Select(usize),
6399 /// Reorder resident detail pages by their previous indices without rebuilding them.
6400 Reorder(Vec<usize>),
6401 /// Show or collapse the content-list pane ([`Pane::List`]), the per-destination
6402 /// visibility switch (`Nav::content_list_for`, docs/navigation.md): a nav host
6403 /// section that spans the whole detail area (a settings page) collapses the pane, and
6404 /// selecting a list-backed section brings it back. Only sent to hosts whose
6405 /// [`NavProps::list_width`] is set. Applied directly, not through an animator proxy:
6406 /// the screenshot step captures the instant the patch returns (the sidebar-toggle rule).
6407 ListVisible(bool),
6408 /// Stacked presentations on a merged-pane backend ([`crate::Cap::NavContentList`]
6409 /// `Emulated`) only: the resident [`Pane::List`] page joins (`true`) or leaves
6410 /// (`false`) the navigation stack directly above the sidebar root. The pieces layer
6411 /// sends it as the selection gains or loses a list-backed destination; the backend
6412 /// realizes the membership change through its platform's navigation APIs (UIKit:
6413 /// `showColumn(.supplementary)` / a pop to the root; never a manual splice, which
6414 /// destroys the split's collapse bookkeeping). Never sent to `Native` backends (their
6415 /// pane persists through every presentation) nor while split.
6416 ListInStack(bool),
6417 }
6418
6419 /// Which pane of a navigation host a page belongs to (docs/navigation.md).
6420 ///
6421 /// A page's pane is a fact about the model, not about how the host currently draws it: a
6422 /// nav host's list page is [`Pane::Sidebar`] whether the toolkit is showing a sidebar beside
6423 /// a detail or stacking the two. What the presentation decides is where each pane lands:
6424 /// its own splitter pane in [`NavPresentation::Split`], the root of the stack in
6425 /// [`NavPresentation::Stack`]. Keeping the two separate is what lets a host re-present on a
6426 /// size-class change (`NavPatch::Presentation`) by re-homing the pages it already has,
6427 /// instead of tearing the tree down and rebuilding it.
6428 #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
6429 pub enum Pane {
6430 /// The list / master pane of a nav host. At most one page per host.
6431 Sidebar,
6432 /// The content-list pane between the sidebar and the detail, Mail's message list
6433 /// (`Nav::content_list`, docs/navigation.md). At most one page per host, and only
6434 /// on hosts whose [`NavProps::list_width`] is set; a backend answering
6435 /// [`crate::Cap::NavContentList`] `Unsupported` never sees one.
6436 List,
6437 /// A destination page. Every page of a `nav_stack` presentation is one of these.
6438 #[default]
6439 Detail,
6440 }
6441
6442 /// One destination's native container.
6443 #[derive(Clone, Debug, Default, PartialEq)]
6444 pub struct NavPageProps {
6445 pub title: String,
6446 pub pane: Pane,
6447 }
6448
6449 /// The largest a modal sheet grows on a desktop, in points: the window less a margin up to
6450 /// this (docs/cover.md "Modal sheet"). AppKit's native sheet and the composed card share it.
6451 pub const SHEET_MAX: crate::Size = crate::Size::new(640.0, 620.0);
6452 /// The largest a [`CoverProps::large`] sheet grows (docs/cover.md "Large sheet").
6453 pub const LARGE_SHEET_MAX: crate::Size = crate::Size::new(1040.0, 880.0);
6454
6455 /// A fullscreen cover's content container (docs/cover.md). Realized detached and hidden;
6456 /// `CoverPatch::Present` shows it over the whole window.
6457 #[derive(Clone, Debug, Default, PartialEq)]
6458 pub struct CoverProps {
6459 /// Prefer a native sheet; toolkits without sheet presentation keep their modal cover.
6460 pub sheet: bool,
6461 /// A half-height sheet rising from the bottom edge, the window content above it
6462 /// staying on show and, where the platform allows, interactive: an inspector over the
6463 /// canvas it describes. Implies `sheet`. The toolkit reports the sheet's own content
6464 /// size through `FrameChanged`, as for any cover (docs/cover.md "Half sheet").
6465 pub half: bool,
6466 /// A large sheet: most of the window, less a margin, for a document or web page that
6467 /// needs the room (docs/cover.md "Large sheet"). Implies `sheet`.
6468 pub large: bool,
6469 }
6470
6471 /// Applied to a `kinds::COVER` node as its bound signal opens and closes it.
6472 #[derive(Clone, Debug, PartialEq)]
6473 pub enum CoverPatch {
6474 /// Present the cover fullscreen (slide up where the platform animates modals).
6475 /// `background` paints the whole surface edge-to-edge (under the status bar / home
6476 /// indicator); the content container is inset to the safe area within it.
6477 /// `dismiss_disabled` = the user must not be able to dismiss it interactively
6478 /// (system back / sheet gestures); programmatic dismissal still works.
6479 Present {
6480 background: Option<Color>,
6481 dismiss_disabled: bool,
6482 },
6483 /// The `interactive_dismiss_disabled` state changed while presented.
6484 DismissDisabled(bool),
6485 /// Dismiss the cover. When the hide transition finishes the backend emits
6486 /// [`crate::Event::CoverHidden`] on the node (trampoline backends send
6487 /// `BridgeKind::CoverHidden`), letting the piece dispose the content only after it
6488 /// left the screen.
6489 Dismiss,
6490 }
6491
6492 /// A `kinds::INSPECTOR` split (docs/inspector.md): content beside a trailing inspector
6493 /// pane. The pane's visibility is Day-owned state (the piece's bound signal), so the
6494 /// props carry the value to draw and [`InspectorPatch::Visible`] keeps it current;
6495 /// a native affordance hiding the pane (a dock close button, a dragged-shut divider)
6496 /// reports back with [`crate::Event::InspectorChanged`].
6497 #[derive(Clone, Debug, PartialEq)]
6498 pub struct InspectorProps {
6499 /// Whether the pane is showing now.
6500 pub visible: bool,
6501 /// The pane's preferred width in points. A backend with a user-draggable divider
6502 /// treats it as the initial width; one without draws it at exactly this.
6503 pub width: f64,
6504 /// Which side of the content the pane sits on. `Trailing` is the classic inspector;
6505 /// `Leading` is a utility pane like a layer panel (docs/tree.md).
6506 pub edge: PaneEdge,
6507 }
6508
6509 /// Which side an inspector pane occupies (docs/inspector.md).
6510 #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
6511 pub enum PaneEdge {
6512 #[default]
6513 Trailing,
6514 Leading,
6515 }
6516
6517 /// Applied to a `kinds::INSPECTOR` node as its bound signal changes.
6518 #[derive(Clone, Debug, PartialEq)]
6519 pub enum InspectorPatch {
6520 /// Show or hide the pane (animated where the platform animates panes). The
6521 /// programmatic-sync direction: applying it must not re-emit
6522 /// [`crate::Event::InspectorChanged`], per the from-native echo rule.
6523 Visible(bool),
6524 }
6525
6526 /// One pane of a `kinds::INSPECTOR` split (docs/inspector.md).
6527 #[derive(Clone, Debug, Default, PartialEq)]
6528 pub struct InspectorPaneProps {
6529 /// `true` for the inspector panel itself, `false` for the content pane.
6530 pub panel: bool,
6531 }
6532
6533 /// How a `kinds::SPLIT` lays its two panes (docs/split.md): beside each other, the divider
6534 /// standing, or stacked, the divider lying. Named by where the panes go, since that is
6535 /// what an app's "layout" toggle means; the divider runs the other way.
6536 #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
6537 pub enum SplitAxis {
6538 /// The panes side by side (first leading), the divider vertical.
6539 #[default]
6540 Horizontal,
6541 /// The panes stacked (first on top), the divider horizontal.
6542 Vertical,
6543 }
6544
6545 /// A `kinds::SPLIT` (docs/split.md): two panes with a divider the user drags. The first
6546 /// pane's share is Day-owned state (the piece's bound signal): the props carry the value
6547 /// to draw, [`SplitPatch::Fraction`] keeps it current, and a divider the user moved
6548 /// reports back as [`crate::Event::ValueChanged`] with the new share, which applying the
6549 /// patch must never re-emit (the from-native echo rule).
6550 #[derive(Clone, Debug, PartialEq)]
6551 pub struct SplitProps {
6552 pub axis: SplitAxis,
6553 /// The first pane's share of the split's length along `axis`, `0.0..=1.0`.
6554 pub fraction: f64,
6555 /// The least length either pane may be dragged to, in points.
6556 pub min_pane: f64,
6557 }
6558
6559 /// Applied to a `kinds::SPLIT` node as its bound signals change.
6560 #[derive(Clone, Debug, PartialEq)]
6561 pub enum SplitPatch {
6562 /// Turn the split the other way, keeping the share.
6563 Axis(SplitAxis),
6564 /// Move the divider so the first pane takes this share. The programmatic-sync
6565 /// direction: applying it must not re-emit [`crate::Event::ValueChanged`].
6566 Fraction(f64),
6567 }
6568
6569 /// One pane of a `kinds::SPLIT` (docs/split.md).
6570 #[derive(Clone, Debug, Default, PartialEq)]
6571 pub struct SplitPaneProps {
6572 /// `false` for the first pane, `true` for the second.
6573 pub second: bool,
6574 }
6575
6576 /// Native navigation item list. `items` are display titles in route order;
6577 /// `selected` highlights the active route (split presentation; None on mobile roots).
6578 /// `icons` (parallel to `items`, `None` = no icon) are bundled image names resolved by each
6579 /// backend via `resource::resolve_image_file`; a backend that can't decorate its rows just
6580 /// ignores them.
6581 #[derive(Clone, Debug, Default, PartialEq)]
6582 pub struct NavMenuProps {
6583 /// Stable document identities, parallel to items; empty for ordinary navigation.
6584 pub document_keys: Vec<String>,
6585 pub items: Vec<String>,
6586 pub icons: Vec<Option<String>>,
6587 /// A trailing accessory per row: an unread count, a status. Rendered right-aligned and
6588 /// de-emphasized, opposite the label. Parallel to `items`; `None` draws nothing.
6589 pub badges: Vec<Option<String>>,
6590 /// A trailing symbol accessory per row, in the same slot as [`Self::badges`] and drawn
6591 /// after it: a bundled image name resolved the way [`Self::icons`] is. This is what a
6592 /// row-level status glyph rides on (a starred page's star) where `badges` carries only
6593 /// text. Parallel to `items`; `None` draws nothing.
6594 pub badge_icons: Vec<Option<String>>,
6595 /// The tint for [`Self::badge_icons`], parallel to `items`. `None` leaves the glyph at
6596 /// the backend's neutral template tint; a status glyph that means something (a yellow
6597 /// star) names its own color here, exactly as [`Self::tints`] does for the leading icon.
6598 pub badge_tints: Vec<Option<Color>>,
6599 /// A per-row icon tint (docs/vectors.md): the row's glyph recolored to this instead of
6600 /// the backend's neutral template tint. Parallel to `items`; `None` keeps the default.
6601 pub tints: Vec<Option<Color>>,
6602 /// A section header introducing the row at the same index. `Some` opens a new group
6603 /// before that row; `None` continues the current one. Parallel to `items`, so adding a
6604 /// header never shifts the selection indices the rows are addressed by.
6605 pub sections: Vec<Option<String>>,
6606 /// A per-row context menu (docs/menus.md): shown on secondary-click / long-press on
6607 /// that row, the same [`crate::MenuItem`] model as everywhere else: items carry
6608 /// registered action ids, so a chosen entry dispatches [`crate::Event::MenuAction`]
6609 /// exactly like a piece context menu. Parallel to `items`; empty = no menu.
6610 pub menus: Vec<Vec<crate::MenuItem>>,
6611 /// Which rows drag to reorder (docs/navigation.md "Reordering sidebar destinations"),
6612 /// parallel to `items`; empty when the sidebar does not reorder. A row moves only
6613 /// within the run of movable rows around it, which a section header or a fixed row
6614 /// ends. A toolkit whose `Cap::NavReorder` is `Native` drags the rows in its own
6615 /// sidebar and reports a drop as [`crate::Event::ListReorder`] in item indices: `from`
6616 /// is the moved row, `to` the row whose position it takes, in the order before the move.
6617 pub movable: Vec<bool>,
6618 /// The sidebar regroups (docs/navigation.md "Moving rows between sections"): a movable
6619 /// row may also cross section headers, into any section whose rows are all movable. A
6620 /// toolkit whose `Cap::NavReorder` is `Native` offers those drops too and reports every
6621 /// drop as [`crate::Event::NavRegroup`] instead of [`crate::Event::ListReorder`]. `false`
6622 /// keeps [`Self::movable`]'s run rule.
6623 pub regroup: bool,
6624 /// Which movable rows keep the app's sorted order within their own section, parallel to
6625 /// `items`; empty when the sidebar does not regroup. Under [`Self::regroup`], a sorted
6626 /// row drops only into another section: no gap in its own section is offered.
6627 pub sorted: Vec<bool>,
6628 pub selected: Option<usize>,
6629 }
6630 #[derive(Clone, Debug, PartialEq)]
6631 // `Items` carries every row array; a patch travels boxed (`Box<dyn Any>`) and lives for one
6632 // update, so the variants' size difference costs nothing worth an indirection.
6633 #[allow(clippy::large_enum_variant)]
6634 pub enum NavMenuPatch {
6635 /// Active icon overlays by row index: None spins, Some(0..=1) fills a circle.
6636 /// Rows absent from this complete snapshot have no overlay. Does not relayout rows.
6637 /// Currently rendered by AppKit/UIKit; other backends may ignore this decoration.
6638 IconProgress(Vec<(usize, Option<f64>)>),
6639 /// Programmatic highlight sync: toolkits apply without re-emitting
6640 /// SelectionChanged (the TextField from_native echo rule).
6641 Selected(Option<usize>),
6642 /// The item set changed (data-driven `nav().items(signal, …)`): rebuild the rows
6643 /// from these labels/icons, then apply `selected` (docs/navigation.md). Applied without
6644 /// re-emitting SelectionChanged.
6645 ///
6646 /// `rows_changed` is `Some` when the rows themselves are the ones already shown (same
6647 /// keys, sections and row menus) and only these rows' title, icon, tint or badge moved:
6648 /// a count ticking, a language change. A backend updates those rows in place (a tab's
6649 /// badge, a menu item's title) rather than rebuilding, which on most platforms re-lays
6650 /// the bar and replays its selection animation; one that cannot rebuilds as for `None`.
6651 Items {
6652 rows_changed: Option<Box<[usize]>>,
6653 document_keys: Box<[String]>,
6654 items: Vec<String>,
6655 icons: Vec<Option<String>>,
6656 badges: Vec<Option<String>>,
6657 badge_icons: Vec<Option<String>>,
6658 badge_tints: Vec<Option<Color>>,
6659 sections: Vec<Option<String>>,
6660 tints: Vec<Option<Color>>,
6661 menus: Vec<Vec<crate::MenuItem>>,
6662 /// [`NavMenuProps::movable`] for the new rows.
6663 movable: Vec<bool>,
6664 /// [`NavMenuProps::sorted`] for the new rows ([`NavMenuProps::regroup`] holds for
6665 /// the sidebar's life).
6666 sorted: Vec<bool>,
6667 selected: Option<usize>,
6668 },
6669 }
6670
6671 /// How a recycling list sizes its rows (docs/list.md).
6672 #[derive(Clone, Copy, Debug, PartialEq, Default)]
6673 pub enum RowHeight {
6674 /// Every row is this tall, a true layout boundary; the fastest path.
6675 Uniform(f64),
6676 /// Rows self-size from their content (host re-measures on change; slower).
6677 #[default]
6678 Automatic,
6679 }
6680
6681 /// Configure a navigation sidebar's native pull-to-refresh control. Not a synthetic pan:
6682 /// supported toolkits own gesture arbitration and the progress indicator. A false state
6683 /// ends a pull, including a request the application declines. Never emits an event.
6684 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
6685 pub struct RefreshPatch {
6686 pub refreshing: bool,
6687 }
6688
6689 /// Native recycling list (docs/list.md). The host owns scrolling + cell reuse; Day supplies
6690 /// row content on demand through the injected `ListSource` (see `Toolkit::attach_list`).
6691 #[derive(Clone, Debug, Default, PartialEq)]
6692 pub struct ListProps {
6693 /// Whether the app handles row activation. Do not claim activation keys when false.
6694 pub activatable: bool,
6695 pub row_height: RowHeight,
6696 /// Whether the native list reports row selection (`Event::SelectionChanged` with the row).
6697 pub selectable: bool,
6698 /// Whether the native list allows selecting several rows at once. Where honored
6699 /// (docs/list.md has the matrix), every selection change reports the full set via
6700 /// `Event::SelectionSet`; single-selection backends keep reporting
6701 /// `Event::SelectionChanged` and treat this as `selectable`.
6702 pub multi_select: bool,
6703 /// Whether rows can be drag-reordered. The toolkit enables its native drag machinery and
6704 /// drives `ListSource::reorder` (validate via `can_move`, commit via `move_row`);
6705 /// probe `Cap::ListReorder` for per-backend support (docs/list.md).
6706 pub reorderable: bool,
6707 /// Whether rows can be deleted by the platform's own delete gesture: a trailing swipe on
6708 /// iOS and ArkUI, an `ItemTouchHelper` swipe on Android. The toolkit drives
6709 /// `ListSource::delete` (offer via `can_delete`, commit via `delete_row`); probe
6710 /// `Cap::ListDelete` for per-backend support (docs/list.md). Desktop toolkits have no such
6711 /// gesture and answer `Unsupported`; an app that must delete everywhere pairs this with an
6712 /// explicit control (a menu item, a button) rather than relying on the swipe.
6713 pub deletable: bool,
6714 /// The label on that affordance, already localized by the app. A toolkit cannot invent
6715 /// translated text (it has no access to the app's catalog), so the string arrives with
6716 /// the props. Empty means "no text": each backend falls back to its platform's own
6717 /// wordless idiom (a trash glyph), which works in every language.
6718 pub delete_label: String,
6719 /// The rows offer edge swipe actions (docs/list.md) through the injected
6720 /// `ListSource::swipe` (offer via `actions_at`, commit via `perform`); probe
6721 /// [`crate::Cap::ListSwipeActions`] for per-backend support. A backend without the
6722 /// affordance never shows one; an app that must offer the command everywhere
6723 /// pairs the swipe with an explicit control, exactly as `deletable` documents.
6724 pub swipe_actions: bool,
6725 /// Row separators, drawn by the host at the row boundary (docs/list.md), so they
6726 /// align with the native selection and ride the platform's own row animations (a
6727 /// macOS/iOS swipe slides the row content past a stationary separator, exactly as
6728 /// Mail's does). `None` keeps each platform's own default (iOS draws them, the
6729 /// desktops don't); `Some(true)`/`Some(false)` forces. A backend without a separator
6730 /// mechanism ignores a force (the matrix in docs/list.md says which); rows there
6731 /// separate by their pitch alone.
6732 pub separators: Option<bool>,
6733 /// The list starts in the platform's editing mode (docs/list.md): delete controls on
6734 /// the rows `deletable` offers, reorder grips on the rows `reorderable` moves, and a
6735 /// tap that still activates. Later changes arrive as [`ListPatch::Editing`]. Probe
6736 /// [`crate::Cap::ListEditing`]; a backend without an editing mode ignores it.
6737 pub editing: bool,
6738 /// The rows fall into sections, each opened by a header row (docs/list.md
6739 /// "Sections"): `ListSource::is_header` says which rows. Probe
6740 /// [`crate::Cap::ListSections`] for whether headers float natively.
6741 pub sections: bool,
6742 }
6743
6744 /// One row-level result-set change. Indexes are sequential (each delta describes the
6745 /// set as the previous ones left it), so a host applies them one at a time (or falls back
6746 /// to a reload; the source's snapshot already holds the final state either way).
6747 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
6748 pub enum RowDelta {
6749 Insert(usize),
6750 Remove(usize),
6751 Move(usize, usize),
6752 }
6753
6754 /// Immutable-at-realize props of a `kinds::TREE` host (docs/tree.md). Everything that
6755 /// changes after realize flows through [`TreePatch`] or the injected `TreeSource`.
6756 #[derive(Clone, Debug, PartialEq)]
6757 pub struct TreeProps {
6758 /// Two-level sectioned list: root branches are non-selectable headings.
6759 pub section_headers: bool,
6760 pub row_height: RowHeight,
6761 /// Rows highlight and report selection ([`crate::Event::TreeSelection`]).
6762 pub selectable: bool,
6763 /// Several rows may be selected at once; every change reports the full token set.
6764 pub multi_select: bool,
6765 /// Rows drag to a new parent/position through the platform's own mechanism, driving
6766 /// `TreeSource::moves`. Probe [`crate::Cap::TreeMove`] for support.
6767 pub movable: bool,
6768 /// Indentation per depth level, in points. `None` = the platform's default step.
6769 pub indent: Option<f64>,
6770 }
6771
6772 /// Post-realize changes to a `kinds::TREE` host (docs/tree.md). Token-addressed
6773 /// throughout; see [`crate::TreeSource`] for why indices cannot address tree rows.
6774 #[derive(Clone, Debug, PartialEq)]
6775 pub enum TreePatch {
6776 /// The node set changed (count/order/parentage/content): the host re-queries its
6777 /// `TreeSource`. Expansion and selection survive by token (docs/tree.md).
6778 Reload,
6779 /// Programmatically disclose (`true`) or collapse (`false`) one row. Applied without
6780 /// re-emitting [`crate::Event::TreeExpanded`] (the from-native echo rule).
6781 Expand(u64, bool),
6782 /// Programmatic selection sync (tokens; empty = clear), applied without re-emitting
6783 /// [`crate::Event::TreeSelection`].
6784 Selected(Vec<u64>),
6785 /// Scroll this row into view, realizing it if needed. The piece has already expanded
6786 /// the row's ancestors (through the app's expansion signal) before issuing this.
6787 Reveal(u64),
6788 }
6789
6790 #[derive(Clone, Debug, PartialEq)]
6791 pub enum ListPatch {
6792 /// The row set changed (count/order/content): the host re-queries its `ListSource`.
6793 Reload,
6794 /// The row set changed by exactly these deltas: a host that can, animates each row
6795 /// in, out, or across; one that cannot treats this as [`ListPatch::Reload`]. The
6796 /// data source answers with the final state throughout.
6797 Splice(Vec<RowDelta>),
6798 /// An `Automatic`-height row was re-laid at a new height after its first layout (its
6799 /// text changed, a wrapped line appeared, the backend corrected its width): the host
6800 /// gives the row bound to physical cell `cell` (the handle `ListSource::bind_row` got,
6801 /// as `usize`) the new `height`, padding included, the same value
6802 /// `ListSource::cell_height` now answers for it.
6803 ///
6804 /// Sent from inside a day-core layout pass, with the tree borrowed: a host applies it
6805 /// after the pass (posted to its main loop), never by asking the source anything
6806 /// synchronously, which would read a `0.0` height (docs/list.md "Row heights").
6807 RowSizeInvalidated { cell: usize, height: f64 },
6808 /// Imperatively scroll the native list so its last row is fully visible (a chat timeline
6809 /// sticking to the newest message). No-op when the list is empty (docs/list.md).
6810 ScrollToEnd,
6811 /// Imperatively scroll the native list so this row is visible, realizing it if needed
6812 /// (docs/list.md). Clamped to the row count; no-op when the list is empty.
6813 ScrollToRow(usize),
6814 /// Programmatic selection sync (row indices; empty = clear): toolkits apply without
6815 /// re-emitting a selection event, like every other programmatic sync.
6816 Selected(Vec<usize>),
6817 /// Enter (`true`) or leave (`false`) the platform's list editing mode, animated
6818 /// (docs/list.md, [`ListProps::editing`]). Ignored where `Cap::ListEditing` is
6819 /// `Unsupported`.
6820 Editing(bool),
6821 }
6822}
6823
6824// ---------------------------------------------------------------------------
6825// Imperative presentation (docs/dialogs.md)
6826// ---------------------------------------------------------------------------
6827
6828pub mod present {
6829 /// A dialog button's semantic role: styling + default/cancel placement on each toolkit.
6830 #[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
6831 pub enum ButtonRole {
6832 #[default]
6833 Default,
6834 Cancel,
6835 Destructive,
6836 }
6837
6838 #[derive(Clone, Debug, PartialEq)]
6839 pub struct PresentButton {
6840 pub label: String,
6841 pub role: ButtonRole,
6842 }
6843
6844 /// A named group of file extensions for a file dialog (e.g. "Text" → `["txt", "md"]`).
6845 /// An empty `extensions` list means "all files".
6846 #[derive(Clone, Debug, PartialEq, Default)]
6847 pub struct FileFilter {
6848 pub name: String,
6849 pub extensions: Vec<String>,
6850 }
6851
6852 /// What a backend should present for a `req`. Kept toolkit-agnostic; the pieces layer
6853 /// maps a chosen button index back to a typed payload.
6854 #[derive(Clone, Debug, PartialEq)]
6855 pub enum PresentSpec {
6856 /// Alert / confirmation / action sheet: title + optional message + ordered buttons.
6857 /// `sheet` = present from the bottom on mobile (desktop falls back to an alert).
6858 Dialog {
6859 title: String,
6860 message: Option<String>,
6861 buttons: Vec<PresentButton>,
6862 sheet: bool,
6863 },
6864 /// A dialog with a single text field.
6865 Prompt {
6866 title: String,
6867 message: Option<String>,
6868 placeholder: String,
6869 initial: String,
6870 ok: String,
6871 cancel: String,
6872 },
6873 /// Native "open file" picker (docs/files.md). The backend must answer with
6874 /// `PresentResult::Files` whose entries are **readable local paths**: desktop returns
6875 /// the chosen path directly; iOS/Android copy the selection into app storage first, so
6876 /// the pieces layer can read it with `std::fs` regardless of platform. `multiple` lets
6877 /// the user pick several files at once; the answer then carries every chosen path, in
6878 /// the picker's order. A backend that cannot select more than one file still answers
6879 /// with the single pick.
6880 OpenFile {
6881 title: String,
6882 filters: Vec<FileFilter>,
6883 multiple: bool,
6884 },
6885 /// Native "choose folder" picker (docs/files.md). The backend answers with
6886 /// `PresentResult::Files` holding the one chosen directory path, or `Dismissed`. Only
6887 /// backends answering [`Cap::FolderDialog`](crate::Cap::FolderDialog) as `Native` show a
6888 /// chooser; the others resolve the request as `Dismissed` at once, so the await never hangs.
6889 OpenFolder { title: String },
6890 /// Native "save file" picker (docs/files.md). `src_path` is a Day-written temp file
6891 /// holding the bytes to save; iOS/Android deliver it to the chosen destination natively,
6892 /// and the pieces layer best-effort copies it to a chosen local path otherwise.
6893 SaveFile {
6894 title: String,
6895 suggested_name: String,
6896 src_path: String,
6897 filters: Vec<FileFilter>,
6898 },
6899 }
6900
6901 /// The user's answer to a presentation.
6902 #[derive(Clone, Debug, PartialEq)]
6903 pub enum PresentResult {
6904 /// A dialog button at `index` (in spec order) was chosen.
6905 Button(i64),
6906 /// A prompt was confirmed with `text`.
6907 Text(String),
6908 /// One or more file locators chosen from an open/save picker (docs/files.md). Each is a
6909 /// local filesystem path or, on Android save, a `content://` URI.
6910 Files(Vec<String>),
6911 /// Dismissed without choosing (tap-outside / Esc / cancel gesture).
6912 Dismissed,
6913 }
6914
6915 /// The unit-separator that joins string lists across the C ABI (Qt shim / Android JNI), the
6916 /// same encoding the nav menu, combobox, and dialog-button shims use.
6917 pub const UNIT_SEP: char = '\u{1f}';
6918
6919 std::thread_local! {
6920 /// An app-writable scratch directory. Backends whose OS temp dir isn't app-writable
6921 /// (Android → `getCacheDir()`) set this at startup; elsewhere it stays `None` and callers
6922 /// fall back to `std::env::temp_dir()`.
6923 // False positive, and only when checking an android target: the initializer already is
6924 // the `const` block the lint asks for. Android's TLS model makes the macro expand to a
6925 // form clippy reads as lazy, so the suggestion is unfollowable as well as unneeded.
6926 #[allow(clippy::missing_const_for_thread_local)]
6927 static APP_TEMP_DIR: std::cell::RefCell<Option<std::path::PathBuf>> =
6928 const { std::cell::RefCell::new(None) };
6929 }
6930
6931 /// Record an app-writable scratch directory (see [`app_temp_dir`]). Called by a backend at
6932 /// startup when the OS temp dir isn't writable by the app (Android).
6933 pub fn set_app_temp_dir(dir: impl Into<std::path::PathBuf>) {
6934 APP_TEMP_DIR.with(|d| *d.borrow_mut() = Some(dir.into()));
6935 }
6936
6937 /// An app-writable scratch directory: the backend-supplied one, else `std::env::temp_dir()`.
6938 /// Used by the file-save flow (docs/files.md) to stage bytes before the native save picker.
6939 pub fn app_temp_dir() -> std::path::PathBuf {
6940 APP_TEMP_DIR.with(|d| {
6941 d.borrow().clone().unwrap_or_else(|| {
6942 #[cfg(target_arch = "wasm32")]
6943 {
6944 // A browser has no filesystem and std's `temp_dir()` panics on wasm. A
6945 // nominal path keeps join/display plumbing alive; actual reads and writes
6946 // fail with ordinary io errors the file flows already surface.
6947 std::path::PathBuf::from("/day-tmp")
6948 }
6949 #[cfg(not(target_arch = "wasm32"))]
6950 std::env::temp_dir()
6951 })
6952 })
6953 }
6954
6955 /// The web build's file bytes (wasm32-unknown-unknown only): a browser has no filesystem,
6956 /// so the open/save flows carry bytes through this per-page store instead of `std::fs`:
6957 /// day-toolkit-dom writes a picked file's bytes here and answers with its virtual path; the pieces
6958 /// layer stages save bytes here for the shim to download. Paths are plain strings under
6959 /// `/day-web/`; lifetimes are one picker round-trip (the flows remove what they stage).
6960 #[cfg(all(target_family = "wasm", target_os = "unknown"))]
6961 pub mod web_files {
6962 std::thread_local! {
6963 static FILES: std::cell::RefCell<std::collections::HashMap<String, Vec<u8>>> =
6964 std::cell::RefCell::new(std::collections::HashMap::new());
6965 }
6966
6967 /// Store `bytes` under `path` (replacing any prior content).
6968 pub fn write(path: &str, bytes: Vec<u8>) {
6969 FILES.with(|f| f.borrow_mut().insert(path.to_string(), bytes));
6970 }
6971
6972 /// The bytes at `path`, if present.
6973 pub fn read(path: &str) -> Option<Vec<u8>> {
6974 FILES.with(|f| f.borrow().get(path).cloned())
6975 }
6976
6977 /// Drop `path`'s bytes.
6978 pub fn remove(path: &str) {
6979 FILES.with(|f| {
6980 f.borrow_mut().remove(path);
6981 });
6982 }
6983 }
6984
6985 impl PresentResult {
6986 /// Flat wire tag for the C ABI (Qt shim / Android JNI): 0 dismissed, 1 button, 2 text,
6987 /// 3 files (`text` is the chosen locators joined by the unit separator).
6988 pub fn decode(tag: i32, index: i64, text: String) -> PresentResult {
6989 match tag {
6990 1 => PresentResult::Button(index),
6991 2 => PresentResult::Text(text),
6992 3 => PresentResult::Files(
6993 text.split(UNIT_SEP)
6994 .filter(|s| !s.is_empty())
6995 .map(str::to_string)
6996 .collect(),
6997 ),
6998 _ => PresentResult::Dismissed,
6999 }
7000 }
7001 }
7002
7003 impl PresentSpec {
7004 /// Backend-facing flattening for the C ABI: `(title, message, button labels, button
7005 /// roles as ints, sheet-or-prompt fields)`. Pure-Rust backends read the enum directly.
7006 pub fn title(&self) -> &str {
7007 match self {
7008 PresentSpec::Dialog { title, .. }
7009 | PresentSpec::Prompt { title, .. }
7010 | PresentSpec::OpenFile { title, .. }
7011 | PresentSpec::OpenFolder { title }
7012 | PresentSpec::SaveFile { title, .. } => title,
7013 }
7014 }
7015 pub fn message(&self) -> Option<&str> {
7016 match self {
7017 PresentSpec::Dialog { message, .. } | PresentSpec::Prompt { message, .. } => {
7018 message.as_deref()
7019 }
7020 _ => None,
7021 }
7022 }
7023 /// Button labels joined with [`UNIT_SEP`], the encoding the nav menu and combobox
7024 /// shims already use for string lists.
7025 pub fn buttons_joined(&self) -> String {
7026 match self {
7027 PresentSpec::Dialog { buttons, .. } => buttons
7028 .iter()
7029 .map(|b| b.label.as_str())
7030 .collect::<Vec<_>>()
7031 .join(&UNIT_SEP.to_string()),
7032 PresentSpec::Prompt { ok, cancel, .. } => format!("{ok}{UNIT_SEP}{cancel}"),
7033 _ => String::new(),
7034 }
7035 }
7036 /// Button roles as ints (0 default, 1 cancel, 2 destructive), joined with commas.
7037 pub fn roles_joined(&self) -> String {
7038 let roles: Vec<i32> = match self {
7039 PresentSpec::Dialog { buttons, .. } => {
7040 buttons.iter().map(|b| b.role as i32).collect()
7041 }
7042 PresentSpec::Prompt { .. } => {
7043 vec![ButtonRole::Default as i32, ButtonRole::Cancel as i32]
7044 }
7045 _ => vec![],
7046 };
7047 roles
7048 .iter()
7049 .map(|r| r.to_string())
7050 .collect::<Vec<_>>()
7051 .join(",")
7052 }
7053
7054 // --- file-dialog accessors (docs/files.md) ---
7055
7056 /// The file filters, if this is a file dialog.
7057 pub fn filters(&self) -> &[FileFilter] {
7058 match self {
7059 PresentSpec::OpenFile { filters, .. } | PresentSpec::SaveFile { filters, .. } => {
7060 filters
7061 }
7062 _ => &[],
7063 }
7064 }
7065 /// Whether an open-file dialog lets the user pick several files (`false` for every
7066 /// other spec).
7067 pub fn multiple(&self) -> bool {
7068 matches!(self, PresentSpec::OpenFile { multiple: true, .. })
7069 }
7070 /// The suggested file name for a save dialog (empty otherwise).
7071 pub fn suggested_name(&self) -> &str {
7072 match self {
7073 PresentSpec::SaveFile { suggested_name, .. } => suggested_name,
7074 _ => "",
7075 }
7076 }
7077 /// The Day-written temp source path for a save dialog (empty otherwise).
7078 pub fn src_path(&self) -> &str {
7079 match self {
7080 PresentSpec::SaveFile { src_path, .. } => src_path,
7081 _ => "",
7082 }
7083 }
7084 /// Filters flattened for the C ABI: each filter is `name|ext1,ext2`, joined by
7085 /// [`UNIT_SEP`]. A trailing `|` (no extensions) means "all files". Empty when unfiltered.
7086 pub fn filters_joined(&self) -> String {
7087 self.filters()
7088 .iter()
7089 .map(|f| format!("{}|{}", f.name, f.extensions.join(",")))
7090 .collect::<Vec<_>>()
7091 .join(&UNIT_SEP.to_string())
7092 }
7093 }
7094}
7095
7096// ---------------------------------------------------------------------------
7097// App directories (docs/fs.md "Where files live")
7098// ---------------------------------------------------------------------------
7099
7100/// Where an app keeps its own files: its data, cache and configuration directories, each a
7101/// folder named after the app id in the place its platform sets aside for that kind of file
7102/// (docs/fs.md "Where files live"). Every Day crate that stores files resolves them here, so an
7103/// app's database, documents, caches, settings file and remembered window frames sit together
7104/// and apart from every other app's.
7105///
7106/// These only resolve paths; nothing is created until something is written. Each is `None` where
7107/// the platform has no such directory: the web, or an Android or HarmonyOS process whose host
7108/// passed none.
7109pub mod storage {
7110 use std::path::PathBuf;
7111
7112 /// The app's id, `[app] id` from Day.toml: `DAY_APP_ID` from `day launch`, else the value
7113 /// `day build` baked in, else the executable's name (a test binary or a bare `cargo run`).
7114 /// Made safe as a single folder name.
7115 pub fn app_id() -> String {
7116 std::env::var("DAY_APP_ID")
7117 .ok()
7118 .filter(|id| !id.is_empty())
7119 .or_else(|| {
7120 option_env!("DAY_APP_ID")
7121 .filter(|id| !id.is_empty())
7122 .map(str::to_owned)
7123 })
7124 .or_else(|| {
7125 let exe = std::env::current_exe().ok()?;
7126 exe.file_stem()?.to_str().map(str::to_owned)
7127 })
7128 .map(|id| folder_name(&id))
7129 .unwrap_or_else(|| "day-app".to_owned())
7130 }
7131
7132 /// The app's data directory, for what it cannot recreate: databases, documents, downloads
7133 /// the user kept. Application Support on Apple platforms (inside the container when
7134 /// sandboxed), `%LOCALAPPDATA%` on Windows, `$XDG_DATA_HOME` on Linux, the app's files
7135 /// directory on Android and HarmonyOS. `DAY_DATA_DIR` replaces it.
7136 pub fn data_dir() -> Option<PathBuf> {
7137 resolve(Dir::Data, Os::HOST, &app_id(), &env_path)
7138 }
7139
7140 /// [`data_dir`] for the app `app_id` rather than this process's own: a host that keeps a
7141 /// folder per hosted app (a day-lite superapp, a crash reporter's store), or a tool finding
7142 /// where an app it launched writes. On Android and HarmonyOS, where the host's directory is
7143 /// already the one app's, the id changes nothing.
7144 pub fn data_dir_for(app_id: &str) -> Option<PathBuf> {
7145 resolve(Dir::Data, Os::HOST, &folder_name(app_id), &env_path)
7146 }
7147
7148 /// The app's cache directory, for what it can fetch or compute again: the system may clear
7149 /// it, and backups skip it. Caches on Apple platforms, `%LOCALAPPDATA%\<id>\cache` on
7150 /// Windows, `$XDG_CACHE_HOME` on Linux, the app's cache directory on Android and HarmonyOS.
7151 /// `DAY_CACHE_DIR` replaces it; with only `DAY_DATA_DIR` set it is that directory's `cache`.
7152 pub fn cache_dir() -> Option<PathBuf> {
7153 resolve(Dir::Cache, Os::HOST, &app_id(), &env_path)
7154 }
7155
7156 /// The app's configuration directory, for small settings files: Application Support on
7157 /// Apple platforms (whose preferences proper are the user defaults), the roaming
7158 /// `%APPDATA%` on Windows, `$XDG_CONFIG_HOME` on Linux. With `DAY_DATA_DIR` set (as the
7159 /// Android and HarmonyOS hosts do) it is that directory's `config`.
7160 pub fn config_dir() -> Option<PathBuf> {
7161 resolve(Dir::Config, Os::HOST, &app_id(), &env_path)
7162 }
7163
7164 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
7165 enum Dir {
7166 Data,
7167 Cache,
7168 Config,
7169 }
7170
7171 /// The platform families whose conventions differ.
7172 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
7173 enum Os {
7174 /// macOS and iOS: `~/Library`, which is the app's container when sandboxed.
7175 Apple,
7176 Windows,
7177 /// Android and HarmonyOS: the host passes the app's private directories.
7178 Hosted,
7179 /// Linux and the BSDs: the XDG base directories.
7180 Unix,
7181 Web,
7182 }
7183
7184 impl Os {
7185 const HOST: Os = if cfg!(any(target_os = "macos", target_os = "ios")) {
7186 Os::Apple
7187 } else if cfg!(target_os = "windows") {
7188 Os::Windows
7189 } else if cfg!(any(target_os = "android", target_env = "ohos")) {
7190 Os::Hosted
7191 } else if cfg!(target_family = "wasm") {
7192 Os::Web
7193 } else {
7194 Os::Unix
7195 };
7196 }
7197
7198 /// An environment variable naming a directory: set, non-empty and absolute, else ignored.
7199 fn env_path(name: &str) -> Option<PathBuf> {
7200 let path = PathBuf::from(std::env::var_os(name)?);
7201 path.is_absolute().then_some(path)
7202 }
7203
7204 /// One folder name: no separators, no `.`/`..`, nothing a filesystem rejects.
7205 fn folder_name(id: &str) -> String {
7206 let name: String = id
7207 .chars()
7208 .map(|c| match c {
7209 '/' | '\\' | ':' | '*' | '?' | '"' | '<' | '>' | '|' => '_',
7210 c if c.is_control() => '_',
7211 c => c,
7212 })
7213 .collect();
7214 match name.trim() {
7215 "" | "." | ".." => "day-app".to_owned(),
7216 name => name.to_owned(),
7217 }
7218 }
7219
7220 /// The pure resolution, over a platform and an environment, so every platform's rules are
7221 /// testable on any host.
7222 fn resolve(
7223 dir: Dir,
7224 os: Os,
7225 id: &str,
7226 var: &dyn Fn(&str) -> Option<PathBuf>,
7227 ) -> Option<PathBuf> {
7228 // The explicit overrides: a mobile host's own directories, or a test's scratch root.
7229 if dir == Dir::Cache
7230 && let Some(cache) = var("DAY_CACHE_DIR")
7231 {
7232 return Some(cache);
7233 }
7234 if let Some(data) = var("DAY_DATA_DIR") {
7235 return Some(match dir {
7236 Dir::Data => data,
7237 Dir::Cache => data.join("cache"),
7238 Dir::Config => data.join("config"),
7239 });
7240 }
7241 let home = || var("HOME");
7242 match os {
7243 // One expression serves sandboxed and unsandboxed apps: inside the App Sandbox,
7244 // and always on iOS, `HOME` is the container's Data folder, so the same Library
7245 // path lands inside it. Apple asks for a bundle-id folder within Application
7246 // Support and Caches either way. XDG variables are ignored here: a Finder launch
7247 // never sees a shell's, so honoring them would split one app's data across two
7248 // places depending on how it was started.
7249 Os::Apple => {
7250 let library = home()?.join("Library");
7251 let base = match dir {
7252 Dir::Data | Dir::Config => library.join("Application Support"),
7253 Dir::Cache => library.join("Caches"),
7254 };
7255 Some(base.join(id))
7256 }
7257 // Local for data and caches: a database or cache roams badly, and a DPAPI-sealed
7258 // file cannot be read on another machine. Roaming for the small settings files.
7259 Os::Windows => {
7260 let profile = |leaf: &str| Some(var("USERPROFILE")?.join("AppData").join(leaf));
7261 let local = || var("LOCALAPPDATA").or_else(|| profile("Local"));
7262 match dir {
7263 Dir::Data => Some(local()?.join(id)),
7264 Dir::Cache => Some(local()?.join(id).join("cache")),
7265 Dir::Config => Some(var("APPDATA").or_else(|| profile("Roaming"))?.join(id)),
7266 }
7267 }
7268 Os::Unix => {
7269 let (xdg, fallback) = match dir {
7270 Dir::Data => ("XDG_DATA_HOME", ".local/share"),
7271 Dir::Cache => ("XDG_CACHE_HOME", ".cache"),
7272 Dir::Config => ("XDG_CONFIG_HOME", ".config"),
7273 };
7274 Some(var(xdg).or_else(|| Some(home()?.join(fallback)))?.join(id))
7275 }
7276 Os::Hosted | Os::Web => None,
7277 }
7278 }
7279
7280 #[cfg(test)]
7281 mod tests {
7282 use super::*;
7283 use std::collections::HashMap;
7284
7285 /// The resolved path as text. `Path::join` uses the host's separator, so on a Windows host
7286 /// another platform's path comes back with `\` between the joined parts; the expectations
7287 /// are that platform's own, so its separators are compared as `/`.
7288 fn at(os: Os, dir: Dir, vars: &[(&str, &str)]) -> Option<String> {
7289 let vars: HashMap<&str, &str> = vars.iter().copied().collect();
7290 let var = |name: &str| vars.get(name).map(PathBuf::from);
7291 resolve(dir, os, "dev.example.notes", &var).map(|p| {
7292 let text = p.display().to_string();
7293 if os == Os::Windows {
7294 text
7295 } else {
7296 text.replace('\\', "/")
7297 }
7298 })
7299 }
7300
7301 #[test]
7302 fn apple_uses_library_folders_named_for_the_app() {
7303 let home = [("HOME", "/Users/ada"), ("XDG_DATA_HOME", "/Users/ada/.xdg")];
7304 let support = "/Users/ada/Library/Application Support/dev.example.notes";
7305 assert_eq!(at(Os::Apple, Dir::Data, &home).as_deref(), Some(support));
7306 assert_eq!(at(Os::Apple, Dir::Config, &home).as_deref(), Some(support));
7307 assert_eq!(
7308 at(Os::Apple, Dir::Cache, &home).as_deref(),
7309 Some("/Users/ada/Library/Caches/dev.example.notes")
7310 );
7311 // A sandboxed app's HOME is its container, so its folders land inside it.
7312 let container = [(
7313 "HOME",
7314 "/Users/ada/Library/Containers/dev.example.notes/Data",
7315 )];
7316 assert_eq!(
7317 at(Os::Apple, Dir::Data, &container).as_deref(),
7318 Some(
7319 "/Users/ada/Library/Containers/dev.example.notes/Data/Library/Application Support/dev.example.notes"
7320 )
7321 );
7322 }
7323
7324 #[test]
7325 fn windows_keeps_data_local_and_settings_roaming() {
7326 let vars = [
7327 ("LOCALAPPDATA", r"C:\Users\ada\AppData\Local"),
7328 ("APPDATA", r"C:\Users\ada\AppData\Roaming"),
7329 ];
7330 let data = at(Os::Windows, Dir::Data, &vars).unwrap_or_default();
7331 assert!(data.starts_with(r"C:\Users\ada\AppData\Local"), "{data}");
7332 assert!(data.ends_with("dev.example.notes"), "{data}");
7333 let cache = at(Os::Windows, Dir::Cache, &vars).unwrap_or_default();
7334 assert!(cache.ends_with("cache"), "{cache}");
7335 let config = at(Os::Windows, Dir::Config, &vars).unwrap_or_default();
7336 assert!(
7337 config.starts_with(r"C:\Users\ada\AppData\Roaming"),
7338 "{config}"
7339 );
7340 }
7341
7342 #[test]
7343 fn unix_follows_xdg_then_home() {
7344 let xdg = [
7345 ("HOME", "/home/ada"),
7346 ("XDG_DATA_HOME", "/data"),
7347 ("XDG_CACHE_HOME", "/cache"),
7348 ("XDG_CONFIG_HOME", "/config"),
7349 ];
7350 assert_eq!(
7351 at(Os::Unix, Dir::Data, &xdg).as_deref(),
7352 Some("/data/dev.example.notes")
7353 );
7354 assert_eq!(
7355 at(Os::Unix, Dir::Cache, &xdg).as_deref(),
7356 Some("/cache/dev.example.notes")
7357 );
7358 assert_eq!(
7359 at(Os::Unix, Dir::Config, &xdg).as_deref(),
7360 Some("/config/dev.example.notes")
7361 );
7362 let home = [("HOME", "/home/ada")];
7363 assert_eq!(
7364 at(Os::Unix, Dir::Data, &home).as_deref(),
7365 Some("/home/ada/.local/share/dev.example.notes")
7366 );
7367 assert_eq!(
7368 at(Os::Unix, Dir::Cache, &home).as_deref(),
7369 Some("/home/ada/.cache/dev.example.notes")
7370 );
7371 assert_eq!(
7372 at(Os::Unix, Dir::Config, &home).as_deref(),
7373 Some("/home/ada/.config/dev.example.notes")
7374 );
7375 }
7376
7377 #[test]
7378 fn hosts_and_tests_override_every_platform() {
7379 let host = [
7380 ("DAY_DATA_DIR", "/data/user/0/dev.example.notes/files"),
7381 ("DAY_CACHE_DIR", "/data/user/0/dev.example.notes/cache"),
7382 ];
7383 for os in [Os::Hosted, Os::Apple, Os::Windows, Os::Unix] {
7384 assert_eq!(
7385 at(os, Dir::Data, &host).as_deref(),
7386 Some("/data/user/0/dev.example.notes/files")
7387 );
7388 assert_eq!(
7389 at(os, Dir::Cache, &host).as_deref(),
7390 Some("/data/user/0/dev.example.notes/cache")
7391 );
7392 }
7393 let scratch = [("HOME", "/Users/ada"), ("DAY_DATA_DIR", "/tmp/run")];
7394 assert_eq!(
7395 at(Os::Apple, Dir::Cache, &scratch).as_deref(),
7396 Some("/tmp/run/cache")
7397 );
7398 assert_eq!(
7399 at(Os::Apple, Dir::Config, &scratch).as_deref(),
7400 Some("/tmp/run/config")
7401 );
7402 // Without a host directory there is nowhere to put anything.
7403 assert_eq!(at(Os::Hosted, Dir::Data, &[("HOME", "/")]), None);
7404 assert_eq!(at(Os::Web, Dir::Data, &[("HOME", "/")]), None);
7405 }
7406
7407 #[test]
7408 fn app_ids_become_one_folder_name() {
7409 assert_eq!(folder_name("dev.daybrite.news"), "dev.daybrite.news");
7410 assert_eq!(folder_name("a/b\\c:d"), "a_b_c_d");
7411 assert_eq!(folder_name(".."), "day-app");
7412 assert_eq!(folder_name(""), "day-app");
7413 }
7414 }
7415}
7416
7417// ---------------------------------------------------------------------------
7418// The Toolkit trait (§8.1)
7419// ---------------------------------------------------------------------------
7420
7421/// Timing supplied by a native display scheduler. Seconds on a monotonic clock; its epoch
7422/// is platform-specific. `target_timestamp` is absent when the platform cannot predict presentation.
7423#[derive(Clone, Copy, Debug, PartialEq)]
7424pub struct FrameStamp {
7425 pub timestamp: f64,
7426 pub target_timestamp: Option<f64>,
7427}
7428impl FrameStamp {
7429 pub fn new(timestamp: f64) -> Self {
7430 Self {
7431 timestamp,
7432 target_timestamp: None,
7433 }
7434 }
7435}
7436/// A one-shot native frame callback, always delivered asynchronously on the UI thread.
7437pub type FrameCallback = Box<dyn FnOnce(FrameStamp)>;
7438/// Cancels a pending callback and releases its native registration. UI-thread only, idempotent
7439/// in effect, and safe during/after delivery. Dropping without calling is allowed after delivery.
7440pub type CancelFrame = Box<dyn FnOnce()>;
7441
7442/// The margins and minimum height a native list gives each row ([`Toolkit::list_row_metrics`],
7443/// docs/list.md "Row metrics"): a `UITableView` cell's layout margins, a Material list item's
7444/// 16dp sides and 56dp height.
7445#[derive(Clone, Copy, Debug, Default, PartialEq)]
7446pub struct RowMetrics {
7447 /// Space between the row's edges and its content.
7448 pub insets: Insets,
7449 /// The least height a row takes, margins included; content centers vertically in it.
7450 pub min_height: f64,
7451}
7452
7453pub trait Toolkit: Sized + 'static {
7454 // `'static` so a handle clone can cross the object-safe TreeOps boundary boxed as `Any`
7455 // (`node_handle_any`, the tweaks door, docs/tweaks.md).
7456 type Handle: Clone + 'static;
7457
7458 /// Request one frame for the window containing `host`. Never call inline. Each native source
7459 /// must stop after delivery unless requested again; no polling timer. Hidden/unmapped windows
7460 /// may defer delivery until visible. Native callbacks must reach the UI thread before calling
7461 /// Rust. The returned closure cancels safely, including when the window has closed.
7462 /// The mock intentionally stays pending: tests inject a manual scheduler in day-core.
7463 fn request_frame(&mut self, _host: &Self::Handle, _cb: FrameCallback) -> CancelFrame {
7464 Box::new(|| {})
7465 }
7466
7467 fn capability(&self, _cap: Cap) -> Support {
7468 Support::Unsupported
7469 }
7470
7471 // node lifecycle
7472 fn realize(&mut self, kind: PieceKind, props: &dyn Any, id: NodeId) -> Self::Handle;
7473 fn update(
7474 &mut self,
7475 h: &Self::Handle,
7476 kind: PieceKind,
7477 patch: &dyn Any,
7478 anim: Option<&AnimSpec>,
7479 );
7480 /// Called from the turn-boundary release queue; backends may defer destruction further.
7481 fn release(&mut self, h: Self::Handle);
7482 /// Give a satellite piece a chance to drop its own per-view state, immediately before
7483 /// [`release`](Toolkit::release) frees `h` (§15.2).
7484 ///
7485 /// A backend that hosts third-party pieces implements this by looking `kind` up in its renderer
7486 /// registry and calling that piece's `release` hook. Defaulted to nothing: a backend with no
7487 /// registry has nothing to dispatch, and one that has not wired this yet leaves piece
7488 /// teardown unrun rather than failing to build.
7489 fn release_piece(&mut self, _kind: PieceKind, _h: &Self::Handle) {}
7490
7491 // tree
7492 fn insert(&mut self, parent: &Self::Handle, child: &Self::Handle, index: usize);
7493 fn remove(&mut self, parent: &Self::Handle, child: &Self::Handle);
7494 /// Put `child` at index `to` among `parent`'s native children: day's z-order resync, which
7495 /// walks the whole sibling row and asks for every position in turn. A child already at `to`
7496 /// must therefore cost nothing: a backend that re-parents unconditionally pays for the
7497 /// untouched siblings too, and where re-parenting means detach-then-add (no ViewGroup move
7498 /// primitive on Android) the detach resigns the focus of everything inside the subtree,
7499 /// which is how a text field being typed into loses the keyboard (docs/focus.md).
7500 fn move_child(&mut self, parent: &Self::Handle, child: &Self::Handle, to: usize);
7501
7502 // geometry (§7): frames are in the nearest realized native ancestor's space, in points.
7503 fn measure(&mut self, h: &Self::Handle, kind: PieceKind, p: Proposal) -> Size;
7504 /// Distance from the top of the widget's frame to its first text baseline, in points, when
7505 /// the widget is `size` (docs/baseline.md). `None` ⇒ it has no text baseline (an image, a
7506 /// slider, a bare container) and a baseline-aligned row falls back to box alignment for it.
7507 ///
7508 /// This is a measurement, not a layout mode: day places every frame itself (§7.1) and never
7509 /// hands a row to a native baseline-aligning container, so what it needs from the toolkit is
7510 /// where the text sits inside the box. Backends that cannot answer keep the default and rows
7511 /// stay centered, which is what every row did before this existed.
7512 fn first_baseline(&mut self, _h: &Self::Handle, _kind: PieceKind, _size: Size) -> Option<f64> {
7513 None
7514 }
7515 fn set_frame(&mut self, h: &Self::Handle, frame: Rect, anim: Option<&AnimSpec>);
7516
7517 // animatable visual channels (§8.4): cheap per-node opacity + transform that don't relayout.
7518 // Defaulted no-ops so backends adopt them incrementally; `anim = Some` ⇒ animate to the value
7519 // on the toolkit's own compositor, `None` ⇒ set instantly.
7520 fn set_opacity(&mut self, _h: &Self::Handle, _opacity: f64, _anim: Option<&AnimSpec>) {}
7521 fn set_transform(
7522 &mut self,
7523 _h: &Self::Handle,
7524 _t: Transform,
7525 _size: Size,
7526 _anim: Option<&AnimSpec>,
7527 ) {
7528 }
7529
7530 // text selection (docs/text.md): make this node's text user-selectable (copy/drag). Applied
7531 // once from the `.selectable()` modifier (day-pieces) to the widget it wraps (a `label`'s
7532 // native text view, most usefully). Unmanaged: Day sets it here and never patches it, so it
7533 // survives text updates. The default no-op means a backend without a selection affordance
7534 // silently leaves the text unselectable.
7535 //
7536 // Returns `Some(replacement)` when the toolkit had to rebuild the widget as a different
7537 // native class to gain a selection affordance (UIKit: `UILabel` has none, so the label
7538 // becomes a read-only `UITextView`); day-core re-points the node's handle at the
7539 // replacement, so later patches and layout reach the widget that is actually on screen.
7540 // Every property-flip backend returns `None`.
7541 fn set_selectable(&mut self, _h: &Self::Handle, _selectable: bool) -> Option<Self::Handle> {
7542 None
7543 }
7544
7545 // text entry (docs/textfield.md): how a `text_field` takes its text: hidden characters,
7546 // read-only, the keyboard and autofill purpose, the action key, the length bound. Called
7547 // once after `realize` when a field asks for anything but the defaults, and again with the
7548 // whole set whenever a reactive member changes, so the setter is idempotent.
7549 //
7550 // Returns `Some(replacement)` when hiding the characters takes a different native class
7551 // (AppKit: `NSSecureTextField`; WinUI: `PasswordBox`), the same contract as
7552 // `set_selectable`: the backend carries the text, the placeholder and its own event wiring
7553 // over, takes the old widget's place in the native tree, and day-core re-points the node's
7554 // handle. Required, with no default: a backend that left this out would show a password in
7555 // the clear. A member the toolkit has no notion of (an action key on a desktop) is ignored.
7556 fn set_input_traits(&mut self, h: &Self::Handle, traits: &InputTraits) -> Option<Self::Handle>;
7557
7558 // pointer shape (docs/cursor.md): the cursor to show while the pointer is over this node
7559 // and its descendants, from the `.cursor()` modifier. Called again whenever a reactive
7560 // cursor changes, so the setter is idempotent and cheap; `Cursor::Default` releases the
7561 // node. The default no-op is a backend with no pointer API to reach (`Cap::Cursor`
7562 // answers `Unsupported` there).
7563 fn set_cursor(&mut self, _h: &Self::Handle, _cursor: Cursor) {}
7564
7565 /// Show or hide a retained subtree, including its input and accessibility participation.
7566 /// The layout and reactive scope stay alive while hidden.
7567 fn set_presented(&mut self, _h: &Self::Handle, _visible: bool) {}
7568
7569 /// Attach overscroll delivery to a refresh host; the caller owns the mounted scope.
7570 fn attach_refresh(&mut self, _h: &Self::Handle, _host: NodeId) {}
7571
7572 // scroll (§7.6)
7573 fn set_scroll_content(&mut self, _h: &Self::Handle, _content: Size) {}
7574 // The room a classic (non-overlay) scroll bar takes out of a scroll view's content area
7575 // while the content overflows along `vertical`'s axis: its width for a vertical scroll, its
7576 // height for a horizontal one (docs/scroll.md). Day lays overflowing content out that much
7577 // narrower, so it fits beside the bar instead of reaching under it. 0 — the default — is
7578 // every backend whose bars overlay the content (AppKit, GTK, UIKit, Android, XAML, DOM).
7579 fn scroll_bar_inset(&mut self, _h: &Self::Handle, _vertical: bool) -> f64 {
7580 0.0
7581 }
7582 // The margins and minimum height the platform's own list gives a row (docs/list.md "Row
7583 // metrics"), asked of list `h` each time day-core lays a row. Day insets the row's content by
7584 // the margins and keeps it at least that tall, so a row reads at the platform's size without
7585 // the app padding it per platform. Zero — the default — leaves the row to its content.
7586 fn list_row_metrics(&mut self, _h: &Self::Handle) -> RowMetrics {
7587 RowMetrics::default()
7588 }
7589 fn scroll_to(&mut self, _h: &Self::Handle, _target: Rect, _animated: bool) {}
7590 /// Scroll a native navigation menu to its top or bottom without changing selection.
7591 /// The widget owns its content extent. Return false when the handle is unsupported.
7592 fn nav_scroll_to_edge(&mut self, _h: &Self::Handle, _bottom: bool) -> bool {
7593 false
7594 }
7595 fn scroll_offset(&mut self, _h: &Self::Handle) -> Point {
7596 Point::ZERO
7597 }
7598
7599 // events: one trampoline, node-id keyed; enqueue-only contract (§8.3).
7600 fn set_event_sink(&mut self, sink: EventSink);
7601
7602 // gestures (docs/shapes.md): attach a native recognizer for `kind` to `h`, emitting
7603 // `Event::Tap/LongPress/Drag` for `node` (enqueue-only). Default no gesture; a piece opts in
7604 // when it has a handler. Idempotent per (handle, kind).
7605 fn enable_gesture(&mut self, _h: &Self::Handle, _node: NodeId, _kind: GestureKind) {}
7606
7607 // focus (docs/focus.md): move native keyboard focus to (or away from) this control.
7608 // `focused = true` requests focus (on mobile this also raises the soft keyboard for text
7609 // inputs); `false` resigns it (dismissing the keyboard; platforms without a "focus nothing"
7610 // state resign to a focusable root). Backends report the resulting state, user- or
7611 // programmatic, with `Event::FocusChanged(bool)` through the sink; a request that cannot
7612 // be honored (unfocusable, unmounted) produces no event. The default no-op means a
7613 // backend without focus support neither moves nor reports focus.
7614 fn focus(&mut self, _h: &Self::Handle, _node: NodeId, _focused: bool) {}
7615
7616 // focusability (docs/focus.md): opt this container into the platform's focus system, the
7617 // canvas contract generalized (`Decorate::focusable`). A focusable container accepts focus,
7618 // takes it on a press (before the press reaches its gesture recognizers), reports both
7619 // directions with `Event::FocusChanged`, and delivers the non-text keys it hears while
7620 // focused as `Event::Key` for `node` (gated on `keys::handled`, like a canvas). The default
7621 // no-op means the piece renders normally but never joins the focus order: `.focused(…)`
7622 // bindings stay quiet and `.on_key(…)` never fires, the same graceful silence unfocusable
7623 // controls already have. Idempotent; only `true` is ever sent today (a piece opts in at
7624 // build, it does not opt back out).
7625 fn set_focusable(&mut self, _h: &Self::Handle, _node: NodeId, _focusable: bool) {}
7626
7627 // recycling list (docs/list.md, §10): day-core hands the `LIST` host its row-pull `source`
7628 // once, right after realize. A recycling backend stores it and calls it from its native
7629 // data-source; the default no-op means a backend without list support renders nothing.
7630 fn attach_list(&mut self, _host: &Self::Handle, _source: ListSource) {}
7631
7632 // hierarchical tree (docs/tree.md): day-core hands the `TREE` host its token-addressed
7633 // row-pull `source` once, right after realize. A backend with a native tree stores it and
7634 // answers its data-source from it; the default no-op means a backend without tree support
7635 // renders nothing (`Cap::Tree` answers `Unsupported`, and apps gate on that).
7636 fn attach_tree(&mut self, _host: &Self::Handle, _source: TreeSource) {}
7637
7638 // routes (docs/navigation.md): day-core reports the app's current route path here whenever
7639 // it changes ("" = everything at its root), so a backend with a native notion of location
7640 // can mirror it: web-dom writes the URL hash (`#controls`), and browser back/forward or a
7641 // hand-edited hash comes back as `Event::RouteRequested`. Default no-op: most toolkits
7642 // have nowhere to put a route.
7643 fn set_route(&mut self, _route: &str) {}
7644
7645 // undo bridge (docs/model.md): mirror the app's undo stack into the platform's own undo
7646 // objects, so the stock Edit menu retitles and enables itself and the platform's gestures
7647 // land: the native front of one Day-owned history. The state flows down whenever it
7648 // changes; the user's invocation comes back up as `Event::Undo`. Default no-op: a backend
7649 // without a native undo system answers `Cap::UndoBridge` `Unsupported`, and the app's own
7650 // affordances (menu items, buttons, accelerators) drive the stack instead.
7651 fn set_undo_state(&mut self, _state: &UndoState) {}
7652
7653 // edit bridge (docs/menus.md): mirror what the app's standard-edit handlers can do, so
7654 // the platform's own menu validation enables Cut/Copy/Paste exactly as it does for text
7655 // widgets; invocations come back up as `Event::Edit`. Default no-op: a backend without
7656 // a native edit-command route answers `Cap::EditBridge` accordingly.
7657 fn set_edit_state(&mut self, _state: &EditState) {}
7658
7659 // ambient modifiers (docs/menus.md): the keyboard modifiers held right now, for
7660 // interactions whose meaning they change (shift-click multi-select). Pull-based: the
7661 // platforms expose exactly this query (NSEvent.modifierFlags, the shim's tracked mask).
7662 // Touch-only backends keep the all-false default.
7663 fn modifiers(&mut self) -> Modifiers {
7664 Modifiers::default()
7665 }
7666
7667 // Dynamic context menu (docs/menus.md): the menu is built when it is summoned. The provider
7668 // is called synchronously from the platform's own menu callback (UI thread, outside any
7669 // day-core borrow) with the location in the node's local coordinates, and its result is
7670 // shown. The static `set_context_menu` below stays the simple path; this one exists for
7671 // surfaces whose menu depends on what is under the pointer (a canvas selection,
7672 // docs/tree.md). Default no-op: a backend without the affordance shows nothing.
7673 fn set_drag_source(&mut self, _h: &Self::Handle, _source: transfer::Source) {}
7674 fn set_drop_target(&mut self, _h: &Self::Handle, _target: transfer::Target) {}
7675
7676 fn set_context_menu_fn(&mut self, _h: &Self::Handle, _node: NodeId, _f: ContextMenuFn) {}
7677
7678 // menus (§ menus): render `items` with the backend's native menu affordance, firing
7679 // `Event::MenuAction(id)` (enqueue-only) for each id'd item; `role` items use the native standard
7680 // command. Default no-op: a toolkit without a menu bar / context menu shows nothing.
7681 /// The application menu (macOS/Windows/Linux menu bar; the app-bar overflow on Android; the
7682 /// UIMenuBuilder main menu on iPadOS/Catalyst). Replaces any previous app menu.
7683 fn set_app_menu(&mut self, _items: &[MenuItem]) {}
7684 /// A context menu for `h`, shown on secondary-click (desktop) or long-press (mobile). Passing an
7685 /// empty slice removes it.
7686 fn set_context_menu(&mut self, _h: &Self::Handle, _node: NodeId, _items: &[MenuItem]) {}
7687
7688 // toolbars (docs/toolbars.md): a window's native toolbar: NSToolbar, AdwHeaderBar, QToolBar,
7689 // CommandBar. `h` is the window root's handle (the same handle `open_window` returned, or the
7690 // primary root's); the backend walks from it to the window it belongs to. Default no-op: a
7691 // toolkit with no toolbar shows nothing rather than a drawn imitation, and reports
7692 // `Cap::Toolbar` as `Unsupported` so an app can put the command somewhere else.
7693 /// Edit the window's toolbar (docs/toolbars.md): the [`ToolbarOp`]s, removals first, then
7694 /// insertions in ascending position. The bar starts empty, and becomes empty again when every
7695 /// item has been removed, at which point the backend takes it off the window.
7696 ///
7697 /// An item no op names must keep its native widget untouched, which is what keeps a search
7698 /// field focused while the page around it changes. Day sends an edit only when the bar
7699 /// changed, at most once per turn, and an item keeps its [`ToolbarItem::action`] for as long
7700 /// as its window shows an item with that id, so a native item's handler never needs
7701 /// repointing. Keep a [`ToolbarMirror`] and place each new item after
7702 /// [`ToolbarMirror::prev_where`] its group.
7703 ///
7704 /// Returns whether the edit was applied. `false` (the window has no bar to edit yet) makes
7705 /// Day send the whole bar again at the next change rather than assume this one landed.
7706 fn edit_toolbar(&mut self, _h: &Self::Handle, _ops: &[ToolbarOp]) -> bool {
7707 true
7708 }
7709 /// Apply a targeted change to one live toolbar item, the path a bound signal writes through,
7710 /// so syncing a search field does not rebuild the bar. No-op if the item is not present.
7711 fn update_toolbar(&mut self, _h: &Self::Handle, _patch: &ToolbarPatch) {}
7712
7713 // lifecycle (docs/lifecycle.md): does this backend deliver `phase`? The default answers "yes" for
7714 // the universal phases (launch/activation/termination) and "no" for the mobile-only ones. Backends
7715 // that wire up more (the mobile ones) override this; it must agree with the crate's
7716 // `const fn lifecycle_supported`, which drives compile-time guards in `day::require_lifecycle!`.
7717 fn supports_lifecycle(&self, phase: Lifecycle) -> bool {
7718 phase.is_universal()
7719 }
7720
7721 // pillars
7722 /// Apply a node's accessibility annotations (docs/accessibility.md): the label, hint and
7723 /// value the screen reader speaks, an explicit role, whether the node is hidden from
7724 /// assistive technology, and the automation identifier. Called with the node's whole
7725 /// accumulated set each time any of it changes, so every member is written on every call.
7726 /// Only an explicit role is applied: a native control reports its own.
7727 fn set_a11y(&mut self, _h: &Self::Handle, _a11y: &A11yProps) {}
7728 /// Speak `text` through the screen reader without moving its focus (docs/accessibility.md;
7729 /// probe [`Cap::Announce`]). `urgent` interrupts what is being read; otherwise the sentence
7730 /// waits its turn. Nothing happens when no screen reader is running. The default is a
7731 /// backend that reaches no announcement API.
7732 fn announce(&mut self, _text: &str, _urgent: bool) {}
7733 /// Read a widget's native state back from the platform for `a11y_audit` and
7734 /// `assert_native` (§14.2, docs/testing.md) to diff against Day's expectation. Default:
7735 /// nothing read; the audit skips the node and `assert_native` records each field as unread.
7736 fn read_native(&self, _h: &Self::Handle) -> NativeSnapshot {
7737 NativeSnapshot::default()
7738 }
7739 fn replay(&mut self, _h: &Self::Handle, _ops: &[DrawOp], _size: Size) {}
7740
7741 /// Every family this toolkit can draw canvas text in, with the faces each ships
7742 /// (docs/fonts.md; probe [`Cap::FontList`]). Default: none. `day::font_families` calls
7743 /// this once per process and caches the answer: enumeration is slow on every platform
7744 /// (fontconfig, a DirectWrite collection, an XML parse on Android) and the set does not
7745 /// change under a running app.
7746 fn font_families(&mut self) -> Vec<FontFamilyInfo> {
7747 Vec::new()
7748 }
7749
7750 /// Measure one line of canvas text at `size` points in `font`, in the same engine
7751 /// [`Toolkit::replay`] draws [`DrawOp::Text`] with, so a `TextAnchor::LEADING` anchor plus
7752 /// the returned `ascent` lands on the drawn baseline. `None` = cannot measure; the facade
7753 /// then answers [`TextMetrics::approximate`].
7754 fn measure_text(&mut self, _text: &str, _size: f64, _font: &CanvasFont) -> Option<TextMetrics> {
7755 None
7756 }
7757 // --- raster images (docs/images.md) -------------------------------------------------
7758 //
7759 // Request-id shaped rather than blocking, because one backend can never answer
7760 // synchronously: a browser decodes through `createImageBitmap`, which is a promise. Every
7761 // other backend decodes inline and raises the completion before returning, so the shape
7762 // costs them nothing but a line, and the app-facing API can be one thing everywhere
7763 // instead of two (docs/async.md rule 3: a callback and a future, never a runtime).
7764
7765 /// Decode encoded image bytes (PNG/JPEG/…) into a native image, answering `req` with
7766 /// [`Event::ImageDecoded`].
7767 ///
7768 /// The id in that event is minted by the caller (day-core), not the backend: the backend
7769 /// keeps its own side table from that id to whatever it decoded.
7770 ///
7771 /// The default does nothing because a default body cannot reach the event sink
7772 /// (it is installed per backend by [`Toolkit::set_event_sink`], not reachable through this
7773 /// trait), so there is no way for it to answer. day-core asks [`Cap::ImageDecode`] first and
7774 /// resolves the request as [`ImageError::Unsupported`] itself, which is why a backend with
7775 /// no decoder needs no code here at all.
7776 fn decode_image(&mut self, _req: u64, _id: BitmapId, _bytes: &[u8]) {}
7777
7778 /// What a decoded image is: pixel size, scale, format, alpha ([`BitmapInfo`]).
7779 ///
7780 /// Synchronous: every backend that decoded the image already holds these facts. `None` means
7781 /// the id names nothing live.
7782 fn image_info(&mut self, _id: BitmapId) -> Option<BitmapInfo> {
7783 None
7784 }
7785
7786 /// The metadata beyond the pixels: EXIF orientation, DPI, capture time
7787 /// ([`ImageProperties`], probe [`Cap::ImageProperties`]). `None` where the backend has no
7788 /// metadata reader, which is most of them.
7789 fn image_properties(&mut self, _id: BitmapId) -> Option<ImageProperties> {
7790 None
7791 }
7792
7793 /// Encode a decoded image back to bytes per `spec`, answering `req` with
7794 /// [`Event::ImageEncoded`]. A format outside [`Self::encode_formats`] answers
7795 /// [`ImageError::Encode`] rather than silently substituting another one.
7796 ///
7797 /// Defaulted to nothing for the same reason as [`Self::decode_image`]: day-core probes
7798 /// [`Cap::ImageEncode`] and answers `Unsupported` without ever calling this.
7799 fn encode_image(&mut self, _req: u64, _id: BitmapId, _spec: &EncodeSpec) {}
7800
7801 /// Which formats [`Self::encode_image`] can write, the [`Cap::ImageEncode`]
7802 /// counterpart of [`Self::font_families`]/[`Cap::FontList`]. Empty by default.
7803 fn encode_formats(&mut self) -> Vec<ImageFormat> {
7804 Vec::new()
7805 }
7806
7807 /// Drop a decoded image and everything the backend cached for it. Called when the app's
7808 /// last handle to it goes away; an id the backend never saw is a no-op.
7809 fn release_image(&mut self, _id: BitmapId) {}
7810
7811 // --- canvas export (docs/canvas.md "Exporting") --------------------------------------
7812 //
7813 // Request-id shaped like the image duties above, for the same reason: the browser's
7814 // `createImageBitmap` is a promise. Every other backend renders inline and raises the
7815 // completion before returning. day-core validates sizes, enforces the pixel limits and
7816 // probes the caps first, so a backend sees only requests it can attempt.
7817
7818 /// Replay `ops` into a new offscreen bitmap of `size` points at `scale` pixels per point
7819 /// ([`export_pixels`] gives the pixel size), with a transparent background and the
7820 /// canvas's top-left origin. Store it under `id` in the same table [`Self::decode_image`]
7821 /// fills, so `image_info`, `encode_image`, `release_image`, the `image` piece and
7822 /// [`DrawOp::Image`] all take it, then answer `req` with [`Event::BitmapRendered`] (its
7823 /// [`BitmapInfo::scale`] is `scale`).
7824 ///
7825 /// The painter must be the one [`Self::replay`] uses, so text, gradients, clips and stamps
7826 /// match the screen. Defaulted to nothing: day-core probes [`Cap::CanvasBitmap`] and answers
7827 /// [`ExportError::Unsupported`] itself.
7828 fn render_bitmap(
7829 &mut self,
7830 _req: u64,
7831 _id: BitmapId,
7832 _ops: &[DrawOp],
7833 _size: Size,
7834 _scale: f64,
7835 ) {
7836 }
7837
7838 /// Replay each page into one PDF document and answer `req` with [`Event::PdfRendered`].
7839 /// Units are PDF points, top-left origin; shapes and text stay vector, and images embed at
7840 /// their pixel size. `pages` is never empty. Defaulted to nothing: day-core probes
7841 /// [`Cap::CanvasPdf`] first.
7842 fn render_pdf(&mut self, _req: u64, _pages: &[PdfPage], _info: &PdfInfo) {}
7843
7844 fn snapshot_window(&mut self) -> Result<Vec<u8>, String> {
7845 Err("snapshot unsupported".into())
7846 }
7847 /// Where `root`, the primary window's root container, sits in [`Self::snapshot_window`]'s
7848 /// image, in points from its top-left. A reader of the capture (dayscript `sample_pixel`)
7849 /// maps Day's frames into it with this; it matters where the capture spans more than Day's
7850 /// content on more than one side, as Android's edge-to-edge content does (status bar
7851 /// above, navigation bar below).
7852 ///
7853 /// Defaulted to `None`, which the reader takes as "any rows beyond Day's content are
7854 /// above it", true where the only extra area is a title bar.
7855 fn snapshot_origin(&mut self, _root: &Self::Handle) -> Option<Point> {
7856 None
7857 }
7858 /// Establish a fresh screenshot checkpoint after reactive work and native transitions.
7859 /// `revision` is stable across retries and unique to the request; `host` selects a
7860 /// secondary window, or None for the primary. Never block the UI thread waiting for
7861 /// a frame. Pending requests are retried within the dayscript deadline.
7862 ///
7863 /// Ready means the platform render checkpoint completed, not that a vsync callback
7864 /// proves pixels were displayed. OnCapture delegates freshness to snapshot_window.
7865 fn prepare_snapshot(
7866 &mut self,
7867 _host: Option<&Self::Handle>,
7868 _revision: u32,
7869 ) -> Result<capture::Readiness, String> {
7870 // Compatible with external toolkits predating this hook: their synchronous
7871 // snapshot owns freshness, and no external-capture acknowledgment is fabricated.
7872 Ok(capture::Readiness::OnCapture)
7873 }
7874
7875 /// The same capture with the window's own chrome: title bar, toolbar, whatever the platform
7876 /// draws around the content (docs/window-image.md).
7877 ///
7878 /// Defaulted to [`Self::snapshot_window`]: a backend that cannot separate the two
7879 /// (or has no chrome to speak of, a phone) answers with the content shot rather than an
7880 /// error, so an app asking for chrome degrades to "what there was" instead of failing. The
7881 /// dayscript `screenshot` step never calls this, which is what keeps every captured gallery
7882 /// baseline byte-identical to before it existed.
7883 fn snapshot_window_chrome(&mut self) -> Result<Vec<u8>, String> {
7884 self.snapshot_window()
7885 }
7886 /// Show/hide the sidebar pane of the navigation host `host`, which is what the sidebar
7887 /// affordance a `nav(Sidebar)` contributes for itself drives ([`SIDEBAR_TOGGLE_ID`]).
7888 /// `false` when `host` has no pane to toggle (a stack, a tab bar, no sidebar concept at all).
7889 ///
7890 /// Per host, not per process: a second window's button collapses that window's sidebar
7891 /// and not the first's. The item's own action makes the call, and dayscript's `toolbar:`
7892 /// step presses the item like any other, so a walkthrough drives exactly the path a click
7893 /// takes. Defaulted, so a backend with no sidebar needs no code. docs/toolbars.md,
7894 /// docs/navigation.md.
7895 fn toggle_sidebar(&mut self, _host: &Self::Handle) -> bool {
7896 false
7897 }
7898 /// Press the platform's own back affordance (the navigation bar's back button on iOS,
7899 /// the system back on Android) on the innermost navigation host that has something to
7900 /// pop. What `nav_back()` does not do: that is Day's rail, which pops the model and lets the
7901 /// backend follow, while this runs the native path first (the bar's `shouldPop`, the
7902 /// dispatcher's callbacks, the pop itself) and lets the backend report it to Day as a user
7903 /// back, guard and all. dayscript's `nav_back: { native: true }` drives it, so a walkthrough
7904 /// can cover the code that a real tap runs and Day's rail never reaches. `false` when this
7905 /// toolkit has no native back or nothing is popped by it. Defaulted, so a desktop needs no
7906 /// code. docs/navigation.md.
7907 fn native_back(&mut self) -> bool {
7908 false
7909 }
7910 /// Whether the UI has settled, with no native transition (modal present/dismiss, nav push)
7911 /// still animating. The dayscript `screenshot` step polls this before capturing so shots
7912 /// never catch a half-faded dialog or half-pushed page. Backends without async
7913 /// transitions (or without a way to know) report `true`.
7914 fn ui_idle(&mut self) -> bool {
7915 true
7916 }
7917
7918 // imperative presentation (docs/dialogs.md): show a native modal for request `req`;
7919 // the backend answers by enqueuing `Event::PresentResult { req, .. }`. `dismiss` is
7920 // used only when Day resolves programmatically (dayscript) while the modal is still up.
7921 fn present(&mut self, _req: u64, _spec: &present::PresentSpec) {}
7922 fn dismiss(&mut self, _req: u64) {}
7923
7924 /// Open `url` in the platform's default handler: the system browser for `http(s)`, the mail
7925 /// client for `mailto:`, etc. Backs the [`link`](/api/day_pieces/fn.link.html) piece. Fire and
7926 /// forget: there is no result, and an unopenable URL is ignored. The default no-ops so a
7927 /// backend that hasn't wired it up still compiles.
7928 fn open_url(&mut self, _url: &str) {}
7929
7930 /// Whether a native share chooser is available. Does not probe installed share targets.
7931 fn share_support(&self) -> Support {
7932 Support::Unsupported
7933 }
7934 /// Present the system share chooser. True means presentation started, not that sharing
7935 /// completed. Never sends data without the user's choice of a target.
7936 fn share_url(&mut self, _url: &str, _title: &str) -> bool {
7937 false
7938 }
7939
7940 /// Read current OS associations. Unsupported platforms must not fabricate a default.
7941 fn application_handlers(
7942 &mut self,
7943 _query: &applications::HandlerQuery,
7944 ) -> Result<applications::ApplicationHandlers, applications::ApplicationError> {
7945 Err(applications::ApplicationError::Unsupported)
7946 }
7947
7948 /// Open with an opaque application identifier returned by `application_handlers`.
7949 fn open_url_with_application(
7950 &mut self,
7951 _url: &str,
7952 _application: &str,
7953 completion: applications::OpenApplicationCompletion,
7954 ) {
7955 completion(Err(applications::ApplicationError::Unsupported));
7956 }
7957
7958 /// Ask the OS to require a second swipe for its edge gestures on `edges` (docs/cover.md):
7959 /// the union requested by every mounted `defers_system_gestures` modifier, re-sent whenever
7960 /// that set changes (`Edges::NONE` when the last one unmounts). iOS defers the home
7961 /// indicator / notification edges; Android enters swipe-to-reveal immersive mode while
7962 /// non-empty. The default no-ops (desktop has no system edge gestures).
7963 fn defer_system_gestures(&mut self, _edges: Edges) {}
7964
7965 /// Hide (`true`) or show the system status bar (docs/cover.md): whether any mounted
7966 /// `status_bar_hidden` modifier currently asks for it hidden, re-sent whenever that answer
7967 /// may have changed (`false` when the last request unmounts). iOS answers the root and
7968 /// cover view controllers' `prefersStatusBarHidden`; Android and HarmonyOS hide the status
7969 /// bar through their window inset controls. The default no-ops (desktop and web have no
7970 /// status bar); report `Cap::StatusBarHidden` alongside an implementation.
7971 fn set_status_bar_hidden(&mut self, _hidden: bool) {}
7972
7973 /// Whether the platform is rendering in dark appearance right now. Apps painting
7974 /// custom surfaces (opaque overlay panels, scrims) branch on this so their fills track
7975 /// the theme the default text colors already follow; hardcoding either theme's
7976 /// surface produces dark-on-dark or light-on-light text on the other. Queried at
7977 /// build time (a piece rebuilt after a theme change re-queries). The default honors a
7978 /// `DAY_THEME` launch override and otherwise answers light.
7979 fn dark_mode(&mut self) -> bool {
7980 std::env::var("DAY_THEME").ok().as_deref() == Some("dark")
7981 }
7982 /// Whether the user asked the system for less motion (docs/accessibility.md; probe
7983 /// [`Cap::ReduceMotion`]): macOS and iOS "Reduce Motion", Android "Remove animations" (an
7984 /// animator duration scale of zero), GTK's `gtk-enable-animations` off, Windows "Show
7985 /// animations" off, the web's `prefers-reduced-motion`. Read at launch; a backend that
7986 /// watches the setting calls `day_core::note_motion_changed` when it flips. Day then applies
7987 /// every finite animation at its destination and keeps only indeterminate motion. The default
7988 /// is a backend that reads no such setting.
7989 fn reduce_motion(&mut self) -> bool {
7990 false
7991 }
7992
7993 /// App-level appearance override: `Some(true)` forces dark, `Some(false)` forces light,
7994 /// `None` returns to following the system. Backends restyle their native widgets in
7995 /// place and answer the override from [`dark_mode`](Self::dark_mode); app-painted
7996 /// surfaces pick it up on their next rebuild. `Cap::Appearance` reports whether the
7997 /// backend honors this; the default ignores the call.
7998 fn set_appearance(&mut self, _dark: Option<bool>) {}
7999
8000 /// Put `badge` on the app's icon in the Dock / launcher / home screen (docs/badge.md).
8001 ///
8002 /// Fire-and-forget, like `set_appearance`: a payload this toolkit cannot render is ignored, and
8003 /// the app probes `Cap::AppBadge{Count,Text,Dot}` before choosing one. Never substitute: a
8004 /// backend that turned `Text("beta")` into `Count(1)` would put a wrong number on a user's
8005 /// icon, which is worse than showing nothing. The default ignores every call.
8006 fn set_app_badge(&mut self, _badge: &AppBadge) {}
8007
8008 // app lifecycle (mobile; desktop backends no-op)
8009 fn on_suspend(&mut self) {}
8010 fn on_resume(&mut self) {}
8011 fn on_memory_warning(&mut self) {}
8012
8013 // adoption of foreign native handles (polyglot pieces, §15.3)
8014 fn adopt(&mut self, _raw: RawHandle) -> Self::Handle {
8015 unimplemented!("this toolkit does not adopt foreign handles yet")
8016 }
8017
8018 // secondary windows (docs/windows.md)
8019
8020 /// Open a native OS window per `options` + `kind`: create and show the window, wire its
8021 /// events to `id` (`WindowResized` with the content size in points, `WindowClosed` after
8022 /// the native close, `WindowFocused` on key/active changes), and answer with its content
8023 /// container handle, the same contract as the `ready` root container. Backends whose
8024 /// window creation is asynchronous (a scene, an activity, an ability) answer
8025 /// [`WindowOpenReply::Pending`] and complete later through
8026 /// `day_core::finish_window_open(id, raw, size)`, which goes through [`Toolkit::adopt`].
8027 /// The default answers `Unsupported`; day-core then presents the content as a
8028 /// fullscreen cover in the primary window instead.
8029 fn open_window(
8030 &mut self,
8031 _id: NodeId,
8032 _options: &WindowOptions,
8033 _kind: WindowKind,
8034 ) -> WindowOpenReply<Self::Handle> {
8035 WindowOpenReply::Unsupported
8036 }
8037
8038 /// Close the native window whose content container is `host` (a handle `open_window`
8039 /// produced). Asynchronous: the platform confirms with `Event::WindowClosed` on the
8040 /// window's root node, and only then does day-core tear the subtree down. Idempotent; unknown
8041 /// hosts are ignored. Never called with the primary window's container.
8042 fn close_window(&mut self, _host: &Self::Handle) {}
8043
8044 /// End the application: the last window with [`WindowRole::Primary`] has closed
8045 /// (docs/windows.md). day-core decides when, since it owns the window registry and the role
8046 /// each window carries; the backend supplies only the platform's exit:
8047 /// `NSApplication.terminate`, `QCoreApplication::quit`, `GtkApplication.quit`,
8048 /// `PostQuitMessage`. Everything day-core wanted to happen first (secondary windows
8049 /// disposed, `WillTerminate` delivered) already has by the time this is called.
8050 ///
8051 /// The default does nothing, which is right for the backends whose process lifetime is
8052 /// not theirs to end: a browser tab, an Android activity, an iOS scene.
8053 fn quit_app(&mut self) {}
8054
8055 /// Bring the window whose content container is `host` to front and make it key/active:
8056 /// the focus half of open-or-focus singleton windows. Default no-op.
8057 fn focus_window(&mut self, _host: &Self::Handle) {}
8058
8059 /// Retitle the window whose content container is `host`. Default no-op.
8060 fn set_window_title(&mut self, _host: &Self::Handle, _title: &str) {}
8061
8062 /// Resize the window whose content container is `host` to fit `size` of content, and pin it
8063 /// there: what `WindowOptions::size_to_fit` asks for (docs/windows.md).
8064 ///
8065 /// `size` is the content size Day measured, not the window's outer frame: the backend adds
8066 /// its chrome. A settings panel is the case this exists for, and every desktop platform
8067 /// sizes one to its content rather than to a number the app guessed; a fixed height either
8068 /// clips the last row or leaves a band of empty panel under it, and which one you get depends
8069 /// on the user's text size.
8070 ///
8071 /// Default no-op, so a toolkit that cannot resize a live window keeps the size it was
8072 /// opened at, which is what every backend did before this existed.
8073 fn fit_window(&mut self, _host: &Self::Handle, _size: Size) {}
8074
8075 /// Snapshot the window whose content container is `host` (the dayscript `screenshot`
8076 /// step's `window:` target). The default answers the primary snapshot, so backends that
8077 /// never open windows stay correct without changes.
8078 fn snapshot_window_of(&mut self, _host: &Self::Handle) -> Result<Vec<u8>, String> {
8079 self.snapshot_window()
8080 }
8081
8082 /// Apply one property change to the window whose content container is `host`
8083 /// (docs/windows.md "Window properties"). The primary window arrives with its root container,
8084 /// like [`set_window_title`](Self::set_window_title).
8085 ///
8086 /// Fire-and-forget, like [`set_app_badge`](Self::set_app_badge): a change this toolkit cannot
8087 /// make is ignored, and the app probes the matching `Cap` (named on each [`WindowChange`]
8088 /// variant) before relying on it. A change the platform completes later (a fullscreen
8089 /// transition, a zoom animation) reports its outcome through
8090 /// [`Event::WindowStateChanged`], never by assuming the request took. The default ignores
8091 /// every change.
8092 fn apply_window(&mut self, _host: &Self::Handle, _change: &WindowChange) {}
8093
8094 /// True OS window groups, as distinct from native tab widgets.
8095 fn native_window_tabs(&self) -> bool {
8096 false
8097 }
8098 /// Native in-window document/section tab control; OS grouping is reported separately.
8099 fn native_document_tabs(&self) -> bool {
8100 false
8101 }
8102 /// Join/reorder these windows in an OS tab group. Content remains window-owned.
8103 fn group_windows(&mut self, _hosts: &[Self::Handle]) {}
8104 /// Current native order of the group containing this window, including detached groups.
8105 fn window_tab_order(&self, _host: &Self::Handle) -> Vec<NodeId> {
8106 Vec::new()
8107 }
8108
8109 /// Install the app's Dock menu (docs/menus.md "Dock menu"): the items macOS shows above
8110 /// its own when the user right-clicks the app's Dock icon, built from the app's
8111 /// `[[shortcuts]]` and its `dock_menu(..)` entries. Same item model and dispatch as
8112 /// [`set_app_menu`](Self::set_app_menu); an empty slice removes the menu. `Cap::DockMenu`
8113 /// reports support; the default ignores the call.
8114 fn set_dock_menu(&mut self, _items: &[MenuItem]) {}
8115
8116 /// Make the node at `h` move its window when the user drags it, as a title bar does
8117 /// (`.window_drag_region()`, docs/window-chrome.md): the region's own background starts a
8118 /// native window drag (with the platform's snapping and edge tiling), a double click does
8119 /// what the user's title-bar double-click setting says, and controls inside the region keep
8120 /// receiving their own clicks. `false` releases it. `Cap::DragRegion`; the default ignores
8121 /// the call, so on a phone the region is an ordinary view.
8122 fn set_drag_region(&mut self, _h: &Self::Handle, _drag: bool) {}
8123
8124 /// Show these status items, replacing the previous set (docs/status-item.md): add the
8125 /// ones whose `id` is new, update the ones that changed, remove the ones no longer listed.
8126 /// A click on an item runs its `activate` action or opens its menu; menu choices dispatch
8127 /// [`Event::MenuAction`] like the app menu's. `Cap::StatusItem`; the default ignores the
8128 /// call, which is what a phone and the web do.
8129 fn set_status_items(&mut self, _items: &[StatusItemSpec]) {}
8130
8131 /// Show `progress` on the app's Dock or taskbar icon (docs/status-item.md).
8132 /// `Cap::AppProgress`; the default ignores it.
8133 fn set_app_progress(&mut self, _progress: AppProgress) {}
8134
8135 /// Show or hide the app's Dock icon while it runs: a menu-bar app hides it and lives in its
8136 /// status item (macOS activation policy). `Cap::DockVisibility`; the default ignores it.
8137 fn set_dock_visible(&mut self, _visible: bool) {}
8138
8139 /// Keep the process running when its last window closes (docs/windows.md "Keeping the app
8140 /// running"). When `true`, the backend must not end the app on its own as windows close: it
8141 /// reports every close, the first window's included, as `Event::WindowClosed`, and day-core
8142 /// decides whether to call [`quit_app`](Self::quit_app). When `false`, the backend keeps its
8143 /// platform's own rule. A backend whose process lifetime is not its own (a phone, a browser
8144 /// tab) ignores it, which is the default.
8145 fn set_keep_running(&mut self, _keep: bool) {}
8146
8147 /// The displays attached now (docs/windows.md "Monitors"). `Cap::Monitors`; the default
8148 /// answers none, and day-core then describes the primary window's own size as one display.
8149 fn monitors(&self) -> Vec<Monitor> {
8150 Vec::new()
8151 }
8152
8153 /// The outer frame of the window whose content container is `host`, in points on the
8154 /// desktop's coordinate space (top-left origin), or `None` where the platform does not say
8155 /// (a phone, Wayland's positions). Read when the app asks for it and when day-core saves a
8156 /// remembered frame (`WindowOptions::remember_frame`).
8157 fn window_frame(&self, _host: &Self::Handle) -> Option<Rect> {
8158 None
8159 }
8160
8161 /// Replace the launcher shortcuts the app set while running (docs/deep-links.md "Launcher
8162 /// shortcuts"), shown beside the ones Day.toml declares: iOS Home Screen quick actions,
8163 /// Android dynamic shortcuts, the macOS Dock menu. Each opens its route through the deep-link
8164 /// intake. `Cap::DynamicShortcuts`; the default ignores the call.
8165 fn set_launcher_shortcuts(&mut self, _shortcuts: &[LauncherShortcut]) {}
8166}
8167
8168/// What a secondary window is, so backends can apply platform conventions (docs/windows.md).
8169#[derive(Clone, Copy, PartialEq, Eq, Debug)]
8170pub enum WindowKind {
8171 /// A regular document/tool window: resizable, miniaturizable, platform-default tabbing.
8172 Normal,
8173 /// A settings/preferences window: singleton by convention; macOS disallows window
8174 /// tabbing and drops the resize/minimize chrome, mobile presents it modally. Pairs with
8175 /// day-core's key-singleton reopen (`open_window` with a key).
8176 Preferences,
8177 /// The About window (docs/settings.md): the same fixed, centered, untabbed panel chrome
8178 /// as [`Self::Preferences`] (every desktop treats the two alike), presented modally on
8179 /// mobile. Singleton under day-core's `day.about` key.
8180 About,
8181}
8182
8183impl WindowKind {
8184 /// Whether this is a panel (settings or About) rather than a document window: the kinds
8185 /// every desktop draws fixed-size, centered and out of the Window menu, and mobile presents
8186 /// as a cover.
8187 pub fn is_panel(self) -> bool {
8188 !matches!(self, WindowKind::Normal)
8189 }
8190}
8191
8192/// Whether a window keeps the app alive (docs/windows.md close policy).
8193///
8194/// A separate axis from [`WindowKind`], which describes chrome. They correlate (a
8195/// preferences panel is the archetypal window that should not hold an app open), but they are
8196/// not the same question, and conflating them would leave no way to say "an ordinary-looking
8197/// tool window that shouldn't outlive the documents".
8198///
8199/// Note the word "secondary" is overloaded around windows: elsewhere in day it means "a window
8200/// other than the first one opened". Here it means "does not keep the app alive", which is
8201/// about lifetime, not about order of creation.
8202#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
8203pub enum WindowRole {
8204 /// Closing the last one of these ends the app.
8205 #[default]
8206 Primary,
8207 /// Never keeps the app alive: when the last `Primary` closes, the app exits and takes
8208 /// these with it, however many are open.
8209 Secondary,
8210}
8211
8212impl From<WindowKind> for WindowRole {
8213 /// The default pairing: an ordinary window holds the app open, a preferences panel does
8214 /// not. An app that needs a different answer sets the role itself.
8215 fn from(kind: WindowKind) -> WindowRole {
8216 match kind {
8217 WindowKind::Normal => WindowRole::Primary,
8218 WindowKind::Preferences | WindowKind::About => WindowRole::Secondary,
8219 }
8220 }
8221}
8222
8223/// A backend's answer to [`Toolkit::open_window`] (docs/windows.md).
8224pub enum WindowOpenReply<H> {
8225 /// The window exists now; here is its content container (desktop backends).
8226 Open(H),
8227 /// Native creation started but completes asynchronously (a scene, an activity, an
8228 /// ability); the backend will call `day_core::finish_window_open` when the content
8229 /// container exists. day-core parks the window record until then.
8230 Pending,
8231 /// This toolkit cannot open windows (`Cap::MultiWindow` = `Unsupported`); day-core
8232 /// falls back to presenting the content as a fullscreen cover in the primary window.
8233 Unsupported,
8234}
8235
8236/// How a window is shown (docs/windows.md "Window properties"): what the window's `state()`
8237/// signal holds and what [`WindowChange::State`] asks for.
8238#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
8239pub enum WindowState {
8240 /// On screen at its own size: neither minimized, maximized nor fullscreen.
8241 #[default]
8242 Normal,
8243 /// Minimized to the Dock, taskbar or shelf. `Cap::WindowStates`.
8244 Minimized,
8245 /// Zoomed to fill the screen's work area, keeping its chrome. `Cap::WindowStates`.
8246 Maximized,
8247 /// Covering the whole screen with no window chrome; on a phone, the system bars hidden.
8248 /// `Cap::WindowFullscreen`.
8249 Fullscreen,
8250}
8251
8252impl WindowState {
8253 /// The wire code of [`bridge::BridgeKind::WindowStateChanged`].
8254 pub const fn code(self) -> i32 {
8255 match self {
8256 WindowState::Normal => 0,
8257 WindowState::Minimized => 1,
8258 WindowState::Maximized => 2,
8259 WindowState::Fullscreen => 3,
8260 }
8261 }
8262
8263 /// The state a wire code names; an unknown code reads as `Normal`.
8264 pub const fn from_code(code: i32) -> WindowState {
8265 match code {
8266 1 => WindowState::Minimized,
8267 2 => WindowState::Maximized,
8268 3 => WindowState::Fullscreen,
8269 _ => WindowState::Normal,
8270 }
8271 }
8272}
8273
8274/// How a window stacks against other apps' windows ([`WindowChange::Level`], `Cap::WindowLevel`).
8275#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
8276pub enum WindowLevel {
8277 /// Ordinary stacking: the focused app's windows come forward.
8278 #[default]
8279 Normal,
8280 /// Stays above other apps' ordinary windows: a palette, a timer, a video peek.
8281 Floating,
8282}
8283
8284/// How strongly a window asks for the user's attention ([`WindowChange::RequestAttention`]).
8285#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
8286pub enum Attention {
8287 /// Once: one Dock bounce, a taskbar button that flashes a few times.
8288 #[default]
8289 Informational,
8290 /// Until the user switches to the app.
8291 Critical,
8292}
8293
8294/// One change to one window (docs/windows.md "Window properties"), carried by
8295/// [`Toolkit::apply_window`]. Each variant names the `Cap` that reports whether the running
8296/// toolkit makes it.
8297#[derive(Clone, Debug, PartialEq)]
8298pub enum WindowChange {
8299 /// Minimize, zoom, take fullscreen, or return to normal. `Cap::WindowStates` for the
8300 /// first two, `Cap::WindowFullscreen` for fullscreen. The outcome comes back as
8301 /// [`Event::WindowStateChanged`].
8302 State(WindowState),
8303 /// Keep the window's content out of screenshots, recordings and screen sharing.
8304 /// `Cap::ContentProtection`.
8305 ContentProtected(bool),
8306 /// Move and/or resize. `origin` is the outer frame's top-left corner in points on the
8307 /// desktop's coordinate space (top-left origin, `Cap::WindowPosition`); `size` is the size Day
8308 /// lays the content out at, in points, the same size `WindowResized` reports
8309 /// (`Cap::WindowGeometry`): the backend adds its own chrome around it.
8310 Frame {
8311 origin: Option<Point>,
8312 size: Option<Size>,
8313 },
8314 /// The content size the user can resize the window to. `None` lifts that bound.
8315 /// `Cap::WindowGeometry`.
8316 Limits {
8317 min: Option<Size>,
8318 max: Option<Size>,
8319 },
8320 /// Stacking against other apps' windows. `Cap::WindowLevel`.
8321 Level(WindowLevel),
8322 /// Show the window on every virtual desktop / Space. `Cap::WindowLevel`.
8323 OnAllWorkspaces(bool),
8324 /// Leave the window out of the taskbar and the window switcher. `Cap::WindowLevel`.
8325 SkipTaskbar(bool),
8326 /// Whether the user can resize the window. `Cap::WindowGeometry`.
8327 Resizable(bool),
8328 /// Whether the window offers a minimize control. `Cap::WindowStates`.
8329 Minimizable(bool),
8330 /// Whether the window offers a maximize / zoom control. `Cap::WindowStates`.
8331 Maximizable(bool),
8332 /// Whether the window offers a close control. `Cap::WindowStates`.
8333 Closable(bool),
8334 /// Hide the window without closing it, or show it again. `Cap::WindowStates`.
8335 Visible(bool),
8336 /// This window's light/dark override over the app-wide [`Toolkit::set_appearance`].
8337 /// `Cap::WindowAppearance`.
8338 Appearance(Option<bool>),
8339 /// Bounce the Dock icon, flash the taskbar button. `Cap::RequestAttention`.
8340 RequestAttention(Attention),
8341}
8342
8343/// The frame a window wears (docs/window-chrome.md), set once when it opens.
8344#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
8345pub enum WindowChrome {
8346 /// The platform's title bar and frame.
8347 #[default]
8348 Standard,
8349 /// The content runs to the window's top edge, under the title bar, and the platform's own
8350 /// window controls (close, minimize, zoom) stay where they are. For a custom title bar: the
8351 /// backend reports the bar's height as the window's safe-area top inset (`day::safe_area()`),
8352 /// so the app pads its content by it and paints its background under it. Mark the draggable
8353 /// part with `.window_drag_region()`. `Cap::OverlayTitleBar`; where unsupported the window
8354 /// keeps its standard bar.
8355 Overlay,
8356 /// No title bar and no frame: a splash screen, a heads-up panel, a borderless utility. The
8357 /// window still resizes from its edges when resizable; mark the part that moves it with
8358 /// `.window_drag_region()`. `Cap::FramelessWindow`; where unsupported the window keeps its
8359 /// standard frame.
8360 Frameless,
8361}
8362
8363/// What shows behind a window's content (docs/window-chrome.md).
8364#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
8365pub enum WindowBackground {
8366 /// The platform's window background.
8367 #[default]
8368 Opaque,
8369 /// Nothing: pixels the content leaves unpainted show the desktop through the window. For
8370 /// rounded or shaped splash screens and overlays. `Cap::TransparentWindow`.
8371 Transparent,
8372 /// A translucent system material that blurs what is behind the window.
8373 /// `Cap::WindowMaterial`; where unsupported the window stays opaque.
8374 Material(WindowMaterial),
8375}
8376
8377/// The system materials a window background can use ([`WindowBackground::Material`]).
8378#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
8379pub enum WindowMaterial {
8380 /// The main-window material: macOS's window background, Windows 11's Mica.
8381 Window,
8382 /// A sidebar or source list: macOS's sidebar material, Windows 11's Mica Alt (tabbed).
8383 Sidebar,
8384 /// A transient surface (a popover, a menu-like panel, a heads-up display): macOS's popover
8385 /// material, Windows 11's Acrylic.
8386 Transient,
8387}
8388
8389/// Where a window opens ([`WindowOptions::placement`]).
8390#[derive(Clone, Copy, Debug, Default, PartialEq)]
8391pub enum WindowPlacement {
8392 /// The platform's choice: macOS cascades, Windows and Linux let the window manager decide.
8393 #[default]
8394 Automatic,
8395 /// Centered on the screen with the active window.
8396 Centered,
8397 /// The outer frame's top-left corner at this point, in points on the desktop's coordinate
8398 /// space (top-left origin). Falls back to `Automatic` without `Cap::WindowPosition`.
8399 At(Point),
8400}
8401
8402/// A small runtime RGBA image for a status item: charts, meters, or a grid of results.
8403///
8404/// Rows run top to bottom; samples are tightly packed, non-premultiplied sRGB RGBA8.
8405/// `scale` is pixels per logical point (2 for Retina). This owns its bytes, independent of
8406/// any window or decoded-image registry. Currently rendered by AppKit; other backends use
8407/// [`StatusItemSpec::icon`] as a fallback. See docs/status-item.md.
8408#[derive(Clone, PartialEq)]
8409pub struct StatusImage {
8410 width: u32,
8411 height: u32,
8412 scale: f64,
8413 rgba: std::sync::Arc<[u8]>,
8414}
8415
8416impl StatusImage {
8417 /// Validate a runtime image. Rejects empty/mismatched pixels, invalid scales, and images
8418 /// exceeding 16 MiB or 4096 logical points on either axis. No platform allocation occurs.
8419 pub fn rgba(
8420 width: u32,
8421 height: u32,
8422 scale: f64,
8423 pixels: impl Into<std::sync::Arc<[u8]>>,
8424 ) -> Option<Self> {
8425 let rgba = pixels.into();
8426 let expected = (width as usize)
8427 .checked_mul(height as usize)?
8428 .checked_mul(4)?;
8429 if width == 0
8430 || height == 0
8431 || expected > 16 * 1024 * 1024
8432 || rgba.len() != expected
8433 || !scale.is_finite()
8434 || scale <= 0.0
8435 || f64::from(width) / scale > 4096.0
8436 || f64::from(height) / scale > 4096.0
8437 {
8438 return None;
8439 }
8440 Some(Self {
8441 width,
8442 height,
8443 scale,
8444 rgba,
8445 })
8446 }
8447
8448 pub fn width(&self) -> u32 {
8449 self.width
8450 }
8451 pub fn height(&self) -> u32 {
8452 self.height
8453 }
8454 pub fn scale(&self) -> f64 {
8455 self.scale
8456 }
8457 pub fn pixels(&self) -> &[u8] {
8458 &self.rgba
8459 }
8460 pub fn size(&self) -> Size {
8461 Size::new(
8462 f64::from(self.width) / self.scale,
8463 f64::from(self.height) / self.scale,
8464 )
8465 }
8466}
8467
8468impl std::fmt::Debug for StatusImage {
8469 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
8470 f.debug_struct("StatusImage")
8471 .field("width", &self.width)
8472 .field("height", &self.height)
8473 .field("scale", &self.scale)
8474 .field("bytes", &self.rgba.len())
8475 .finish()
8476 }
8477}
8478
8479#[cfg(test)]
8480mod status_image_tests {
8481 use super::*;
8482
8483 #[test]
8484 fn validates_pixel_layout_and_logical_size() {
8485 let image = StatusImage::rgba(120, 36, 2.0, vec![255; 120 * 36 * 4]).unwrap();
8486 assert_eq!(image.size(), Size::new(60.0, 18.0));
8487 assert_eq!(image.clone(), image);
8488 assert!(StatusImage::rgba(0, 1, 1.0, vec![]).is_none());
8489 assert!(StatusImage::rgba(1, 1, 1.0, vec![0; 3]).is_none());
8490 assert!(StatusImage::rgba(u32::MAX, u32::MAX, 1.0, vec![]).is_none());
8491 for scale in [0.0, -1.0, f64::NAN, f64::INFINITY, 0.00001] {
8492 assert!(StatusImage::rgba(1, 1, scale, vec![0; 4]).is_none());
8493 }
8494 }
8495}
8496
8497/// One status item: an icon in the menu bar (macOS), the notification area (Windows) or a
8498/// StatusNotifierItem host's tray (Linux), with a menu (docs/status-item.md).
8499#[derive(Clone, Debug, PartialEq)]
8500pub struct StatusItemSpec {
8501 /// The app's name for the item, stable across updates: what a backend diffs by.
8502 pub id: String,
8503 /// The glyph. `None` shows the title alone (macOS) or the app's icon (elsewhere).
8504 pub icon: Option<Icon>,
8505 /// A runtime image. AppKit prefers this over `icon`, preserving aspect ratio and point
8506 /// size up to 18pt high; other backends ignore it and show `icon`/`title` as before.
8507 pub raster: Option<StatusImage>,
8508 /// Draw the icon as a template: its shape only, in the menu bar's or panel's own color, so
8509 /// it reads in light and dark. Symbols are always templates.
8510 pub template: bool,
8511 /// Text beside the icon where the platform shows one (the macOS menu bar). Empty: icon only.
8512 pub title: String,
8513 /// The hover text.
8514 pub tooltip: String,
8515 /// The menu the item opens. Same model and dispatch as the app menu.
8516 pub menu: Vec<MenuItem>,
8517 /// A dispatch id (the [`Event::MenuAction`] registry) run when the user clicks the item
8518 /// itself, where the platform separates a click from opening the menu (a left click on macOS
8519 /// and Windows, the host's "activate" on Linux). 0: a click opens the menu.
8520 pub activate: u64,
8521}
8522
8523/// One display (docs/windows.md "Monitors"), in points on the desktop's coordinate space:
8524/// top-left origin at the primary display's top-left corner.
8525#[derive(Clone, Debug, PartialEq)]
8526pub struct Monitor {
8527 /// Stable for the display across launches where the platform offers it (a display UUID, a
8528 /// connector name); an index otherwise.
8529 pub id: String,
8530 /// The display's name, for a picker ("Built-in Retina Display", "DELL U2720Q").
8531 pub name: String,
8532 /// The display's whole area.
8533 pub frame: Rect,
8534 /// The part windows should use: the frame minus the menu bar, Dock, taskbar or panels.
8535 pub work_area: Rect,
8536 /// Device pixels per point.
8537 pub scale: f64,
8538 /// The display the desktop's menu bar or primary taskbar is on.
8539 pub primary: bool,
8540}
8541
8542/// A launcher shortcut the app sets while it runs (docs/deep-links.md "Launcher shortcuts"): a
8543/// route to open and the label the launcher shows, already localized.
8544#[derive(Clone, Debug, PartialEq, Eq)]
8545pub struct LauncherShortcut {
8546 /// The route the shortcut opens, through the deep-link intake.
8547 pub route: String,
8548 /// What the launcher shows.
8549 pub label: String,
8550}
8551
8552/// A progress indicator on the app's Dock or taskbar icon ([`Toolkit::set_app_progress`],
8553/// docs/status-item.md).
8554#[derive(Clone, Copy, Debug, Default, PartialEq)]
8555pub enum AppProgress {
8556 /// No indicator.
8557 #[default]
8558 None,
8559 /// Work of unknown length.
8560 Indeterminate,
8561 /// A fraction done, 0.0 to 1.0.
8562 Value(f64),
8563 /// A fraction done, paused. Platforms without a paused state show `Value`.
8564 Paused(f64),
8565 /// A fraction done when the work failed. Platforms without an error state show `Value`.
8566 Error(f64),
8567}
8568
8569/// Whether and how a window joins macOS window tabs ([`WindowOptions::tabbing`],
8570/// `Cap::WindowTabbing`). Other platforms have no system window tabs and ignore it.
8571#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
8572pub enum WindowTabbing {
8573 /// The platform default for the window's kind: an ordinary window tabs with the app's other
8574 /// ordinary windows when the user's "Prefer tabs" setting says so; preferences never tab.
8575 #[default]
8576 Automatic,
8577 /// Tab only with windows of the same group, following the user's setting. The tab bar's
8578 /// "+" opens the builder registered for this group (`register_new_window_for`).
8579 Group(String),
8580 /// Always open as a tab of an existing window of the same group, whatever the setting.
8581 Preferred(String),
8582 /// Never become a tab.
8583 Disallowed,
8584}
8585
8586/// An app's generated locale catalog: `(DEFAULT, CATALOG)`, exactly what `day-build` emits as
8587/// `res::locales::{DEFAULT, CATALOG}` (§18.5). Carried in [`WindowOptions::locales`] so the
8588/// framework can install it at the one moment that is correct.
8589pub type AppLocales = (&'static str, &'static [(&'static str, &'static str)]);
8590
8591#[derive(Clone, Debug)]
8592pub struct WindowOptions {
8593 pub title: String,
8594 pub size: Size,
8595 pub min_size: Option<Size>,
8596 /// Create and mount the window without showing it or activating the app. Supported on
8597 /// AppKit; other backends currently ignore this option. Defaults to false.
8598 ///
8599 /// Menu-bar apps can keep their initial host hidden and open Preferences on demand.
8600 /// The window still exists and can be shown with `WindowHandle::set_visible(true)`;
8601 /// this does not change the app's keep-running policy.
8602 pub start_hidden: bool,
8603 /// Ask the backend to size this window to its content once it has been built and laid out,
8604 /// rather than keeping [`Self::size`] (docs/windows.md). `size` still decides the width and
8605 /// acts as the height ceiling, so a panel with more content than fits the screen scrolls
8606 /// instead of growing past it.
8607 ///
8608 /// What a preferences panel wants on every desktop. Ignored by backends that cannot resize a
8609 /// live window, and by the ones with no windows at all.
8610 pub size_to_fit: bool,
8611 /// The app's display name for the standard application menu / About (macOS). `None` falls back
8612 /// to `title`; set it when `title` carries extra decoration you don't want in `About <name>`
8613 /// (e.g. the showcase's window title is "Day Showcase (AppKit)" but its app name is "Showcase").
8614 pub app_name: Option<String>,
8615 /// The app's locale catalog, installed by `day::launch` (docs/localization.md).
8616 ///
8617 /// The order is why this is the framework's job: the OS's languages reach day-localization from the
8618 /// live backend, and the catalog has to be registered after that hint and before the first
8619 /// localized string is read. An app that installs it itself (before `launch`, where there
8620 /// is no backend yet) registers against an empty hint list and resolves to `DEFAULT`, so a
8621 /// French device opens an English window.
8622 pub locales: Option<AppLocales>,
8623 /// The title, computed once the catalog above is installed: how a window title comes from
8624 /// the catalog rather than a literal. Takes precedence over [`Self::title`], which stays the
8625 /// fallback for the moment before (and for apps with nothing to translate).
8626 ///
8627 /// A plain `fn` rather than a closure: this struct is `Clone`, and the callers are a
8628 /// non-capturing `|| res::str::app_title().format()`, which coerces.
8629 pub title_fn: Option<fn() -> String>,
8630 /// The app's version, for Day's exit line (`Clean exit for <app> v<version> …`,
8631 /// docs/lifecycle.md): `env!("CARGO_PKG_VERSION")` in the app crate, which the scaffold's
8632 /// `window()` sets. `None` falls back to the `DAY_APP_VERSION` the `day` CLI sets on a launch.
8633 pub version: Option<String>,
8634 /// macOS window tabbing for this window (`Cap::WindowTabbing`); ignored elsewhere.
8635 pub tabbing: WindowTabbing,
8636 /// The window's frame: standard, a title bar the content runs under, or none
8637 /// (docs/window-chrome.md). Desktop only; phones and the web ignore it.
8638 pub chrome: WindowChrome,
8639 /// What shows behind the content: the window background, nothing, or a system material.
8640 pub background: WindowBackground,
8641 /// Whether the window casts the platform's drop shadow. A transparent, shaped window often
8642 /// wants none.
8643 pub shadow: bool,
8644 /// Whether the user can resize the window by its edges.
8645 pub resizable: bool,
8646 /// Where the window opens.
8647 pub placement: WindowPlacement,
8648 /// The largest content size the user can resize the window to (`Cap::WindowGeometry`).
8649 pub max_size: Option<Size>,
8650 /// Remember this window's size, position and maximized state under this key, and reopen it
8651 /// that way next launch (docs/windows.md "Remembered frames"). A position that no attached
8652 /// display shows any more is dropped, so a window never reopens off-screen.
8653 pub remember_frame: Option<String>,
8654 /// The logical window this opens (docs/windows.md): `open_window` focuses an already-open
8655 /// window with the same key instead of opening a second (the preferences pattern). `None`
8656 /// always opens a new one.
8657 pub key: Option<String>,
8658 /// The kind of window: a regular one, a preferences panel, an About panel.
8659 pub kind: WindowKind,
8660}
8661
8662impl WindowOptions {
8663 /// The window title. Replaces a [`title_fn`](Self::title_fn) set earlier (the generated
8664 /// `res::window_options()` sets one), so the last title named wins.
8665 pub fn title(mut self, title: impl Into<String>) -> Self {
8666 self.title = title.into();
8667 self.title_fn = None;
8668 self
8669 }
8670 /// The content size the window opens at (desktop; phones fill the screen).
8671 pub fn size(mut self, width: f64, height: f64) -> Self {
8672 self.size = Size::new(width, height);
8673 self
8674 }
8675 /// The smallest content size the user can resize to.
8676 pub fn min_size(mut self, width: f64, height: f64) -> Self {
8677 self.min_size = Some(Size::new(width, height));
8678 self
8679 }
8680 /// The largest content size the user can resize to (`Cap::WindowGeometry`).
8681 pub fn max_size(mut self, width: f64, height: f64) -> Self {
8682 self.max_size = Some(Size::new(width, height));
8683 self
8684 }
8685 /// Create and mount the window without showing it; see [`Self::start_hidden`].
8686 pub fn start_hidden(mut self) -> Self {
8687 self.start_hidden = true;
8688 self
8689 }
8690 /// Size the window to its content once built; see [`Self::size_to_fit`].
8691 pub fn size_to_fit(mut self) -> Self {
8692 self.size_to_fit = true;
8693 self
8694 }
8695 /// The app's display name for the application menu and About; see [`Self::app_name`].
8696 pub fn app_name(mut self, name: impl Into<String>) -> Self {
8697 self.app_name = Some(name.into());
8698 self
8699 }
8700 /// The app's locale catalog, as `res::locales::{DEFAULT, CATALOG}`; see [`Self::locales`].
8701 pub fn locales(
8702 mut self,
8703 default: &'static str,
8704 catalog: &'static [(&'static str, &'static str)],
8705 ) -> Self {
8706 self.locales = Some((default, catalog));
8707 self
8708 }
8709 /// The title, computed once the catalog is installed; see [`Self::title_fn`].
8710 pub fn title_fn(mut self, f: fn() -> String) -> Self {
8711 self.title_fn = Some(f);
8712 self
8713 }
8714 /// The app's version, for Day's exit line; see [`Self::version`].
8715 pub fn version(mut self, version: impl Into<String>) -> Self {
8716 self.version = Some(version.into());
8717 self
8718 }
8719 /// macOS window tabbing for this window; see [`Self::tabbing`].
8720 pub fn tabbing(mut self, tabbing: WindowTabbing) -> Self {
8721 self.tabbing = tabbing;
8722 self
8723 }
8724 /// The window's frame; see [`Self::chrome`].
8725 pub fn chrome(mut self, chrome: WindowChrome) -> Self {
8726 self.chrome = chrome;
8727 self
8728 }
8729 /// What shows behind the content; see [`Self::background`].
8730 pub fn background(mut self, background: WindowBackground) -> Self {
8731 self.background = background;
8732 self
8733 }
8734 /// No drop shadow, for a transparent or shaped window; see [`Self::shadow`].
8735 pub fn no_shadow(mut self) -> Self {
8736 self.shadow = false;
8737 self
8738 }
8739 /// A window the user cannot resize; see [`Self::resizable`].
8740 pub fn fixed_size(mut self) -> Self {
8741 self.resizable = false;
8742 self
8743 }
8744 /// Where the window opens; see [`Self::placement`].
8745 pub fn placement(mut self, placement: WindowPlacement) -> Self {
8746 self.placement = placement;
8747 self
8748 }
8749 /// Remember and restore this window's frame under `key`; see [`Self::remember_frame`].
8750 pub fn remember_frame(mut self, key: impl Into<String>) -> Self {
8751 self.remember_frame = Some(key.into());
8752 self
8753 }
8754 /// The logical window this opens; see [`Self::key`].
8755 pub fn key(mut self, key: impl Into<String>) -> Self {
8756 self.key = Some(key.into());
8757 self
8758 }
8759 /// The kind of window; see [`Self::kind`].
8760 pub fn kind(mut self, kind: WindowKind) -> Self {
8761 self.kind = kind;
8762 self
8763 }
8764}
8765
8766impl Default for WindowOptions {
8767 fn default() -> Self {
8768 WindowOptions {
8769 title: "Day".into(),
8770 size: Size::new(480.0, 640.0),
8771 min_size: None,
8772 start_hidden: false,
8773 size_to_fit: false,
8774 app_name: None,
8775 locales: None,
8776 title_fn: None,
8777 version: None,
8778 tabbing: WindowTabbing::Automatic,
8779 chrome: WindowChrome::Standard,
8780 background: WindowBackground::Opaque,
8781 shadow: true,
8782 resizable: true,
8783 placement: WindowPlacement::Automatic,
8784 max_size: None,
8785 remember_frame: None,
8786 key: None,
8787 kind: WindowKind::Normal,
8788 }
8789 }
8790}
8791
8792/// A platform backend: owns the native main loop and exactly one window in v1 (§8.1).
8793///
8794/// `run` sets up the native app + window, installs the reactive scheduler + main poster,
8795/// then hands `(self, root_container, content_size)` to `ready` (which mounts the tree and
8796/// takes ownership of the backend), and finally runs the native main loop.
8797pub trait Platform: Toolkit {
8798 /// The process-constant target id, e.g. `"macos-appkit"`.
8799 const TARGET: &'static str;
8800 /// The toolkit half of the target, e.g. `"appkit"`.
8801 const TOOLKIT: &'static str;
8802 /// Whether [`Platform::run`] returning means the app is over. True for a backend that
8803 /// drives the native loop itself until the app quits (GTK, Qt, XAML; AppKit's never
8804 /// returns). False where the host owns the loop and `run` hands back at once, with the
8805 /// app still to come (ArkUI's ability, Android's activity, the web page, the mock's test):
8806 /// their `DidExit` is the host's last callback, not the return (docs/lifecycle.md).
8807 const RUN_ENDS_APP: bool = true;
8808
8809 fn run(self, options: WindowOptions, ready: Box<dyn FnOnce(Self, Self::Handle, Size)>);
8810
8811 /// Post a closure onto the native main loop. Callable from any thread; this is the
8812 /// single door the reactive scheduler and `Setter` deliveries ride (§3.3).
8813 fn post(f: Box<dyn FnOnce() + Send>);
8814
8815 /// Post `f` onto the native main loop after (at least) `ms` milliseconds: the timer
8816 /// door behind `day::sleep` (docs/async.md). Every shipped backend overrides it with the
8817 /// loop's own timer (`dispatch_after`, `Handler.postDelayed`, `g_timeout_add`,
8818 /// `QTimer::singleShot`, `SetTimer`, `setTimeout`), so a sleep costs no thread. The
8819 /// default is the fallback for a backend without one: a helper thread that sleeps the
8820 /// whole delay and rides [`Platform::post`] home. It is correct, but a thread per sleep
8821 /// adds up under a ticking loop, so the first use says so once in the log.
8822 fn post_delayed(ms: u32, f: Box<dyn FnOnce() + Send>) {
8823 static SAID: std::sync::Once = std::sync::Once::new();
8824 SAID.call_once(|| {
8825 log::warn!(
8826 "day: {} has no native timer door; `day::sleep` falls back to a helper thread \
8827 per delay (implement `Platform::post_delayed`)",
8828 Self::TARGET
8829 );
8830 });
8831 std::thread::spawn(move || {
8832 std::thread::sleep(std::time::Duration::from_millis(u64::from(ms)));
8833 Self::post(f);
8834 });
8835 }
8836
8837 /// Ordered OS locale preference list (BCP-47), for fluent-langneg (§12.2).
8838 fn locale_hints(&self) -> Vec<String> {
8839 Vec::new()
8840 }
8841}
8842
8843// ---------------------------------------------------------------------------
8844// Open renderer registry (§8.2)
8845// ---------------------------------------------------------------------------
8846
8847/// The scale a window snapshot is rendered at, when a scripted run states one
8848/// (`DAY_CAPTURE_SCALE=2`, set by `day launch --script` from Day.toml `[screenshots]`).
8849///
8850/// For the backends that render their own snapshot (GTK, Qt): the capture then measures
8851/// window points times this, whatever display the host has, which is what makes a CI capture
8852/// under a 1x xvfb the same 2560x1600 pixels a HiDPI laptop produces. A backend that reads the
8853/// compositor's pixels back (AppKit, XAML) captures at the display's own scale and ignores it.
8854/// `None` when unset or unparseable: capture at the backend's natural scale.
8855pub fn capture_scale() -> Option<f64> {
8856 std::env::var("DAY_CAPTURE_SCALE")
8857 .ok()
8858 .and_then(|v| v.trim().parse::<f64>().ok())
8859 .filter(|s| s.is_finite() && (0.5..=4.0).contains(s))
8860}
8861
8862/// Seconds on a monotonic clock since the first call: the frame timestamp for a backend that
8863/// does not expose a native timestamp (§8.4). The origin is arbitrary. Not for the web
8864/// build, where `Instant` is unavailable and `requestAnimationFrame` stamps the frame itself.
8865pub fn frame_timestamp() -> f64 {
8866 static ORIGIN: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new();
8867 ORIGIN
8868 .get_or_init(std::time::Instant::now)
8869 .elapsed()
8870 .as_secs_f64()
8871}
8872
8873/// The user's language preference from the POSIX environment, newest-first, as BCP-47 tags.
8874///
8875/// `LANGUAGE` is the GNU multi-language list (`fr:en`); `LC_ALL`, `LC_MESSAGES` and `LANG` each
8876/// carry one locale in POSIX form (`fr_FR.UTF-8`), which becomes `fr-FR`. Shared by the backends
8877/// whose platform has no richer API to ask (§12.2, docs/localization.md).
8878pub fn posix_locale_hints() -> Vec<String> {
8879 let mut out: Vec<String> = Vec::new();
8880 let mut push = |tag: &str| {
8881 // "C" and "POSIX" are the absence of a preference, not a language.
8882 let tag = tag.split('.').next().unwrap_or(tag).replace('_', "-");
8883 if tag.is_empty() || tag == "C" || tag == "POSIX" {
8884 return;
8885 }
8886 if !out.contains(&tag) {
8887 out.push(tag);
8888 }
8889 };
8890 if let Ok(list) = std::env::var("LANGUAGE") {
8891 for tag in list.split(':') {
8892 push(tag);
8893 }
8894 }
8895 for key in ["LC_ALL", "LC_MESSAGES", "LANG"] {
8896 if let Ok(v) = std::env::var(key) {
8897 push(&v);
8898 }
8899 }
8900 out
8901}
8902
8903/// Optional custom measure for a third-party piece (§8.2).
8904pub type MeasureFn<B> = fn(&mut B, &<B as Toolkit>::Handle, Proposal) -> Size;
8905
8906/// A third-party piece's per-toolkit implementation. `make` receives the concrete backend
8907/// (public helper surface) and returns a native handle the backend then owns like any built-in.
8908pub struct Renderer<B: Toolkit> {
8909 pub kind: PieceKind,
8910 pub make: fn(&mut B, &dyn Any, NodeId) -> B::Handle,
8911 pub update: fn(&mut B, &B::Handle, &dyn Any),
8912 pub measure: Option<MeasureFn<B>>,
8913 /// Teardown, run from the release queue just before [`Toolkit::release`] frees the handle.
8914 ///
8915 /// A piece that keeps per-view state (a retained delegate, a session map, a native
8916 /// observer) has no other place to drop it: `make`/`update` are the only other hooks, and a
8917 /// disposed node never calls them again. Without this a piece leaks one entry per realized
8918 /// view, and any map keyed by the handle's address can go on to answer for a later view that
8919 /// the allocator hands the same address.
8920 ///
8921 /// `None` for the pieces that own nothing (most of them).
8922 pub release: Option<fn(&mut B, &B::Handle)>,
8923}
8924
8925pub struct Registry<B: Toolkit> {
8926 map: HashMap<PieceKind, Renderer<B>>,
8927}
8928
8929impl<B: Toolkit> Default for Registry<B> {
8930 fn default() -> Self {
8931 Registry {
8932 map: HashMap::new(),
8933 }
8934 }
8935}
8936
8937impl<B: Toolkit> Registry<B> {
8938 pub fn register(&mut self, r: Renderer<B>) {
8939 let kind = r.kind;
8940 if self.map.insert(kind, r).is_some() {
8941 // Two pieces claiming one kind is last-linked-wins in link order, effectively
8942 // nondeterministic. Fail loudly in debug; in release, say so once at boot rather
8943 // than render the wrong widget silently.
8944 debug_assert!(
8945 false,
8946 "duplicate renderer registered for piece kind {kind:?}"
8947 );
8948 log::warn!("duplicate renderer for piece kind {kind:?} — later registration wins");
8949 }
8950 }
8951 pub fn get(&self, kind: PieceKind) -> Option<&Renderer<B>> {
8952 self.map.get(kind)
8953 }
8954 pub fn kinds(&self) -> impl Iterator<Item = PieceKind> + '_ {
8955 self.map.keys().copied()
8956 }
8957}
8958
8959/// The canvas wire op codes (§11, §15.3): slot 0 of every 9-number record in
8960/// [`encode_ops`]'s output. The numeric values are the frozen wire contract: the JNI, C++,
8961/// and JS decoders each hand-write these as constants, so a value here may never be reused
8962/// or renumbered; new ops append. `ALL` drives the density test that keeps this enum and
8963/// the encoder in step.
8964#[derive(Clone, Copy, Debug, PartialEq, Eq)]
8965#[repr(i32)]
8966pub enum OpCode {
8967 /// Fill a rect (a,b=origin, c,d=size).
8968 FillRect = 0,
8969 /// Stroke a rect (g=width).
8970 StrokeRect = 1,
8971 /// Fill a rounded rect (e=radius).
8972 FillRrect = 2,
8973 /// Fill an ellipse in a rect.
8974 FillEllipse = 3,
8975 /// Stroke an ellipse (g=width).
8976 StrokeEllipse = 4,
8977 /// Stroke an arc (e=start°, f=sweep°, g=width). `Fill(Shape::Arc)` also encodes as
8978 /// this with width 0, the known asymmetry; see [`encode_ops`].
8979 StrokeArc = 5,
8980 /// Line a,b → c,d (g=width).
8981 Line = 6,
8982 /// Text at a,b (e=size, f=anchor: 0 leading / 1 centered); the string rides the texts
8983 /// channel.
8984 Text = 7,
8985 /// Save the graphics state.
8986 Save = 8,
8987 /// Restore the graphics state.
8988 Restore = 9,
8989 /// Concat an affine transform (a..f).
8990 Concat = 10,
8991 /// Fill a polygon; points ride the texts channel as "x,y x,y …" (closed automatically).
8992 /// `a` = the [`geometry_key`] of those points, or 0 for none.
8993 FillPolygon = 11,
8994 /// Stroke a polygon (g=width); points and key as [`OpCode::FillPolygon`].
8995 StrokePolygon = 12,
8996 /// Stroke a rounded rect (e=radius, g=width).
8997 StrokeRrect = 13,
8998 /// Set a gradient for the next shape record (f=type: 0 linear with a,b=start / c,d=end
8999 /// unit points; 1 radial with a,b=center unit point, c=unit radius; e=stop count).
9000 /// Stops ride the texts channel as "offset,aarrggbb offset,aarrggbb …". Unit geometry
9001 /// resolves against the shape's bounding box.
9002 SetGradient = 14,
9003 /// Fill a path (f=fill rule: 0 non-zero / 1 even-odd); segments ride the texts channel
9004 /// (see [`encode_path`]). `a` = the [`geometry_key`] of those segments, or 0 for none.
9005 ///
9006 /// The key is a cache handle, not a payload: a decoder that recognizes it may keep the
9007 /// native geometry it built last time and skip re-parsing the segments, but it must still
9008 /// consume the texts entry either way, because that channel is positional and a skipped
9009 /// entry desynchronizes every record after it.
9010 FillPath = 15,
9011 /// Stroke a path (g=width); segments and key as [`OpCode::FillPath`].
9012 StrokePath = 16,
9013 /// Clip to a shape (f=shape kind: 0 rect / 1 rrect(e=radius) / 2 ellipse / 3 path
9014 /// (e=fill rule) / 4 polygon; a..d=geometry; path/polygon payloads ride the texts
9015 /// channel).
9016 ///
9017 /// For the two payload-bearing kinds (3 and 4) there is no geometry in the slots, so `a`
9018 /// carries the [`geometry_key`] instead and b..d stay 0. The other three kinds put real
9019 /// geometry in a..d and have nothing to cache.
9020 Clip = 17,
9021 /// Stroke style for the next stroke record (a=cap, b=join, c=miter limit, d=dash
9022 /// phase, e=dash count; the dash array rides the texts channel).
9023 StrokeStyle = 18,
9024 /// Font for the next text record (a=CSS weight 100 … 900, 0 = default; b=italic 0/1); the
9025 /// family name rides the texts channel, `""` = the platform's default face. Like
9026 /// [`OpCode::SetGradient`] and [`OpCode::StrokeStyle`] it is consumed by the record that
9027 /// follows and then cleared; a default [`CanvasFont`] emits no record at all, so a drawing
9028 /// without fonts encodes exactly as it did before this op existed.
9029 SetFont = 19,
9030 /// The next shape record is a template, drawn once per stamped position rather than once
9031 /// (docs/canvas.md "Stamping"). `a` = how many positions follow. Like [`OpCode::SetGradient`],
9032 /// [`OpCode::StrokeStyle`] and [`OpCode::SetFont`] it is a prefix, consumed by the record it
9033 /// applies to and then cleared.
9034 ///
9035 /// Between this and that template record come `ceil(a / 4)` [`OpCode::StampPoints`] records
9036 /// carrying the coordinates. A drawing with no stamps encodes exactly as it did before.
9037 Stamp = 20,
9038 /// Four stamped positions, filling the record edge to edge: `[op, x0, y0, x1, y1, x2, y2,
9039 /// x3, y3]`, the one record that uses its last slot for geometry instead of a color, because
9040 /// it carries no color of its own. The final record of a run is padded; the count in the
9041 /// [`OpCode::Stamp`] header says how many of the pairs are real.
9042 StampPoints = 21,
9043 /// Draw a decoded image: `a,b` = origin, `c,d` = size, `e` = the [`BitmapId`], `f` = opacity
9044 /// in `0.0..=1.0` (docs/images.md).
9045 ///
9046 /// The id rides the numeric channel because it is a number, and an `f64` carries a `u64` id
9047 /// exactly up to 2^53; ids are minted from 1 per process, so that ceiling is unreachable.
9048 /// Nothing rides the texts channel for this op.
9049 Image = 22,
9050}
9051
9052impl OpCode {
9053 /// Every code, in wire order. The density test iterates this so a new variant that
9054 /// forgets to join fails loudly.
9055 pub const ALL: [OpCode; 23] = [
9056 OpCode::FillRect,
9057 OpCode::StrokeRect,
9058 OpCode::FillRrect,
9059 OpCode::FillEllipse,
9060 OpCode::StrokeEllipse,
9061 OpCode::StrokeArc,
9062 OpCode::Line,
9063 OpCode::Text,
9064 OpCode::Save,
9065 OpCode::Restore,
9066 OpCode::Concat,
9067 OpCode::FillPolygon,
9068 OpCode::StrokePolygon,
9069 OpCode::StrokeRrect,
9070 OpCode::SetGradient,
9071 OpCode::FillPath,
9072 OpCode::StrokePath,
9073 OpCode::Clip,
9074 OpCode::StrokeStyle,
9075 OpCode::SetFont,
9076 OpCode::Stamp,
9077 OpCode::StampPoints,
9078 OpCode::Image,
9079 ];
9080
9081 /// The code back from a wire number (a decoder-side aid and the round-trip test's
9082 /// reference); `None` for anything outside the table.
9083 pub fn from_wire(n: f64) -> Option<OpCode> {
9084 OpCode::ALL.into_iter().find(|c| *c as i32 as f64 == n)
9085 }
9086}
9087
9088/// Flat numeric encoding of a display list for shim/JNI boundaries (§11, §15.3): per op
9089/// 9 numbers [kind, a, b, c, d, e, f, g, rgba-bits]; text payloads ride separately in order.
9090/// The kind slot carries an [`OpCode`]; its doc comments are the per-slot contract.
9091///
9092/// Transports join `texts` with the unit separator U+001F (one entry per text-carrying
9093/// record, in order), so text payloads must not contain U+001F. Known asymmetry:
9094/// `Fill(Shape::Arc)` encodes as [`OpCode::StrokeArc`] with width 0. Filled arcs render
9095/// only on the direct-replay backends (AppKit/UIKit); use a polygon fan if a filled arc
9096/// must be portable.
9097/// Serialize a path for the `texts` side-channel: one space-separated token per segment,
9098/// `M x y` / `L x y` / `Q cx cy x y` / `C c1x c1y c2x c2y x y` / `Z`.
9099///
9100/// Text rather than numbers because that is the channel the encoder already has for
9101/// variable-length payloads, and every decoder (JS, Java, C++) can already split a string. The
9102/// numeric channel is a flat `[f64; 9]`-per-record array with no length prefix, so a path could
9103/// not ride it without changing the record shape for every backend at once.
9104/// A content key for a shape's variable-length geometry: the handle a backend caches decoded
9105/// native geometry under (a `Path2D`, a `QPainterPath`, an `android.graphics.Path`) so an
9106/// unchanged path is rebuilt once instead of re-parsed out of the texts channel every frame.
9107///
9108/// It hashes the geometry, not the op's position or its identity, so that a draw closure that
9109/// rebuilds its `PathBuilder` chain from scratch on every frame (which is what canvas consumers
9110/// do) produces an equal path, hashes the same and hits the same entry. An identity would miss
9111/// every time.
9112///
9113/// Two different paths that collided would draw each other, so the width matters: FNV-1a over the
9114/// IEEE bits, masked to the 53 bits an `f64` wire slot carries exactly. `0.0` is reserved for "no
9115/// key": a decoder seeing it must decode the payload as it always did, which is also what every
9116/// decoder written before this key existed does with the slot.
9117pub fn geometry_key(shape: &Shape) -> f64 {
9118 fn mix(h: &mut u64, v: f64) {
9119 for byte in v.to_bits().to_le_bytes() {
9120 *h ^= u64::from(byte);
9121 *h = h.wrapping_mul(0x0000_0100_0000_01b3);
9122 }
9123 }
9124 fn mix_point(h: &mut u64, p: Point) {
9125 mix(h, p.x);
9126 mix(h, p.y);
9127 }
9128 let mut h: u64 = 0xcbf2_9ce4_8422_2325;
9129 match shape {
9130 Shape::Polygon(pts) => {
9131 // The discriminant joins the hash so a polygon and a path of the same points can
9132 // never share an entry: they decode to different geometry.
9133 mix(&mut h, 11.0);
9134 for p in pts {
9135 mix_point(&mut h, *p);
9136 }
9137 }
9138 Shape::Path(path) => {
9139 mix(&mut h, 15.0);
9140 mix(&mut h, rule_bits(path.rule));
9141 for seg in &path.segs {
9142 match seg {
9143 PathSeg::Move(a) => {
9144 mix(&mut h, 0.0);
9145 mix_point(&mut h, *a);
9146 }
9147 PathSeg::Line(a) => {
9148 mix(&mut h, 1.0);
9149 mix_point(&mut h, *a);
9150 }
9151 PathSeg::Quad(c, a) => {
9152 mix(&mut h, 2.0);
9153 mix_point(&mut h, *c);
9154 mix_point(&mut h, *a);
9155 }
9156 PathSeg::Cubic(c1, c2, a) => {
9157 mix(&mut h, 3.0);
9158 mix_point(&mut h, *c1);
9159 mix_point(&mut h, *c2);
9160 mix_point(&mut h, *a);
9161 }
9162 PathSeg::Close => mix(&mut h, 4.0),
9163 }
9164 }
9165 }
9166 // Everything else puts its whole geometry in the record's own slots, so there is nothing
9167 // to parse and nothing worth caching.
9168 _ => return 0.0,
9169 }
9170 let masked = h & ((1u64 << 53) - 1);
9171 // 0 means "no key", so the one hash that lands there borrows its neighbor.
9172 if masked == 0 { 1.0 } else { masked as f64 }
9173}
9174
9175pub fn encode_path(path: &Path) -> String {
9176 let mut out = String::with_capacity(path.segs.len() * 16);
9177 for seg in &path.segs {
9178 if !out.is_empty() {
9179 out.push(' ');
9180 }
9181 match seg {
9182 PathSeg::Move(p) => out.push_str(&format!("M {} {}", p.x, p.y)),
9183 PathSeg::Line(p) => out.push_str(&format!("L {} {}", p.x, p.y)),
9184 PathSeg::Quad(c, p) => out.push_str(&format!("Q {} {} {} {}", c.x, c.y, p.x, p.y)),
9185 PathSeg::Cubic(a, b, p) => out.push_str(&format!(
9186 "C {} {} {} {} {} {}",
9187 a.x, a.y, b.x, b.y, p.x, p.y
9188 )),
9189 PathSeg::Close => out.push('Z'),
9190 }
9191 }
9192 out
9193}
9194
9195/// `FillRule` as a wire number: 0 non-zero, 1 even-odd.
9196fn rule_bits(rule: FillRule) -> f64 {
9197 match rule {
9198 FillRule::NonZero => 0.0,
9199 FillRule::EvenOdd => 1.0,
9200 }
9201}
9202
9203pub fn encode_ops(ops: &[DrawOp]) -> (Vec<f64>, Vec<String>) {
9204 fn color_bits(c: Color) -> f64 {
9205 let r = (c.r.clamp(0.0, 1.0) * 255.0) as u32;
9206 let g = (c.g.clamp(0.0, 1.0) * 255.0) as u32;
9207 let b = (c.b.clamp(0.0, 1.0) * 255.0) as u32;
9208 let a = (c.a.clamp(0.0, 1.0) * 255.0) as u32;
9209 ((a << 24) | (r << 16) | (g << 8) | b) as f64
9210 }
9211 #[allow(clippy::too_many_arguments)]
9212 fn push(
9213 k: OpCode,
9214 a: f64,
9215 b: f64,
9216 c: f64,
9217 d: f64,
9218 e: f64,
9219 f: f64,
9220 g: f64,
9221 col: Color,
9222 nums: &mut Vec<f64>,
9223 ) {
9224 nums.extend_from_slice(&[k as i32 as f64, a, b, c, d, e, f, g, color_bits(col)]);
9225 }
9226 /// The kind-18 prefix a non-plain stroke style emits, applying to the next stroke record,
9227 /// the same "modifier record" rule the gradient and font records follow. A plain style emits
9228 /// nothing, so a drawing without dashes or caps encodes exactly as it always did.
9229 fn stroke_style_record(style: &StrokeStyle, nums: &mut Vec<f64>, texts: &mut Vec<String>) {
9230 if style.is_plain() {
9231 return;
9232 }
9233 push(
9234 OpCode::StrokeStyle,
9235 match style.cap {
9236 LineCap::Butt => 0.0,
9237 LineCap::Round => 1.0,
9238 LineCap::Square => 2.0,
9239 },
9240 match style.join {
9241 LineJoin::Miter => 0.0,
9242 LineJoin::Round => 1.0,
9243 LineJoin::Bevel => 2.0,
9244 },
9245 style.miter_limit,
9246 style.dash_phase,
9247 style.dash.len() as f64,
9248 0.0,
9249 0.0,
9250 Color::CLEAR,
9251 nums,
9252 );
9253 texts.push(
9254 style
9255 .dash
9256 .iter()
9257 .map(|d| d.to_string())
9258 .collect::<Vec<_>>()
9259 .join(" "),
9260 );
9261 }
9262
9263 /// One shape record (the fill/stroke kinds shared by both ops).
9264 fn shape_record(
9265 stroke: bool,
9266 shape: &Shape,
9267 w: f64,
9268 col: Color,
9269 nums: &mut Vec<f64>,
9270 texts: &mut Vec<String>,
9271 ) {
9272 match shape {
9273 Shape::Rect(r) => push(
9274 if stroke {
9275 OpCode::StrokeRect
9276 } else {
9277 OpCode::FillRect
9278 },
9279 r.origin.x,
9280 r.origin.y,
9281 r.size.width,
9282 r.size.height,
9283 0.0,
9284 0.0,
9285 w,
9286 col,
9287 nums,
9288 ),
9289 Shape::RoundedRect(r, rad) => push(
9290 if stroke {
9291 OpCode::StrokeRrect
9292 } else {
9293 OpCode::FillRrect
9294 },
9295 r.origin.x,
9296 r.origin.y,
9297 r.size.width,
9298 r.size.height,
9299 *rad,
9300 0.0,
9301 w,
9302 col,
9303 nums,
9304 ),
9305 Shape::Ellipse(r) => push(
9306 if stroke {
9307 OpCode::StrokeEllipse
9308 } else {
9309 OpCode::FillEllipse
9310 },
9311 r.origin.x,
9312 r.origin.y,
9313 r.size.width,
9314 r.size.height,
9315 0.0,
9316 0.0,
9317 w,
9318 col,
9319 nums,
9320 ),
9321 Shape::Arc {
9322 rect,
9323 start_deg,
9324 sweep_deg,
9325 } => push(
9326 OpCode::StrokeArc,
9327 rect.origin.x,
9328 rect.origin.y,
9329 rect.size.width,
9330 rect.size.height,
9331 *start_deg,
9332 *sweep_deg,
9333 w,
9334 col,
9335 nums,
9336 ),
9337 Shape::Line(p1, p2) => {
9338 push(OpCode::Line, p1.x, p1.y, p2.x, p2.y, 0.0, 0.0, w, col, nums)
9339 }
9340 Shape::Polygon(pts) => {
9341 // Variable-length points ride the texts side-channel ("x,y x,y …"),
9342 // consumed in record order exactly like text payloads.
9343 push(
9344 if stroke {
9345 OpCode::StrokePolygon
9346 } else {
9347 OpCode::FillPolygon
9348 },
9349 geometry_key(shape),
9350 0.0,
9351 0.0,
9352 0.0,
9353 0.0,
9354 0.0,
9355 w,
9356 col,
9357 nums,
9358 );
9359 texts.push(
9360 pts.iter()
9361 .map(|p| format!("{},{}", p.x, p.y))
9362 .collect::<Vec<_>>()
9363 .join(" "),
9364 );
9365 }
9366 Shape::Path(path) => {
9367 // Same side-channel as Polygon, one token per segment (see `encode_path`).
9368 // The fill rule rides slot f; stroking ignores it.
9369 push(
9370 if stroke {
9371 OpCode::StrokePath
9372 } else {
9373 OpCode::FillPath
9374 },
9375 geometry_key(shape),
9376 0.0,
9377 0.0,
9378 0.0,
9379 0.0,
9380 rule_bits(path.rule),
9381 w,
9382 col,
9383 nums,
9384 );
9385 texts.push(encode_path(path));
9386 }
9387 }
9388 }
9389 /// A gradient applies to the next shape record, fill or stroke. Geometry per type rides
9390 /// slots a..d and the type discriminant slot f: one record shape, so every decoder keeps a
9391 /// single gradient code path.
9392 fn gradient_record(
9393 geo: [f64; 4],
9394 kind: f64,
9395 stops: &[(f64, Color)],
9396 nums: &mut Vec<f64>,
9397 texts: &mut Vec<String>,
9398 ) {
9399 push(
9400 OpCode::SetGradient,
9401 geo[0],
9402 geo[1],
9403 geo[2],
9404 geo[3],
9405 stops.len() as f64,
9406 kind,
9407 0.0,
9408 Color::CLEAR,
9409 nums,
9410 );
9411 texts.push(
9412 stops
9413 .iter()
9414 .map(|(o, c)| format!("{o},{:08x}", color_bits(*c) as u32))
9415 .collect::<Vec<_>>()
9416 .join(" "),
9417 );
9418 }
9419 let mut nums = Vec::with_capacity(ops.len() * 9);
9420 let mut texts = Vec::new();
9421 for op in ops {
9422 match op {
9423 DrawOp::Fill(shape, paint) => {
9424 // A gradient emits one kind-14 set-gradient record before its shape record;
9425 // the stops ride the texts channel as "offset,aarrggbb offset,aarrggbb …".
9426 // Geometry per type rides slots a..d, the type discriminant slot f: one
9427 // record shape, so every decoder keeps a single gradient code path.
9428 let col = match paint {
9429 Paint::Solid(c) => *c,
9430 Paint::Linear(g) => {
9431 gradient_record(
9432 [g.start.x, g.start.y, g.end.x, g.end.y],
9433 0.0,
9434 &g.stops,
9435 &mut nums,
9436 &mut texts,
9437 );
9438 // The gradient replaces the shape record's color, but it must be
9439 // opaque, not clear: Skia-based decoders (Android Paint, OH_Drawing)
9440 // modulate a shader by the paint alpha, so a clear slot would render
9441 // the whole gradient invisible.
9442 Color::WHITE
9443 }
9444 Paint::Radial(g) => {
9445 gradient_record(
9446 [g.center.x, g.center.y, g.radius, 0.0],
9447 1.0,
9448 &g.stops,
9449 &mut nums,
9450 &mut texts,
9451 );
9452 Color::WHITE
9453 }
9454 };
9455 shape_record(false, shape, 0.0, col, &mut nums, &mut texts);
9456 }
9457 DrawOp::Stamp(st) => {
9458 // No copies means no drawing. Some native decoders use an empty point
9459 // buffer to mean an ordinary (unstamped) template, so omit the entire op.
9460 if st.at.is_empty() {
9461 continue;
9462 }
9463 // A prefix record, then the coordinates, then the template shape record: the
9464 // "applies to the next record" rule the gradient, stroke style and font records
9465 // already follow, so a decoder needs no new kind of state, only one more slot in
9466 // the state it keeps. The template goes last because a decoder has to hold the
9467 // points before it can draw with them.
9468 //
9469 // The points are numbers on the numeric channel, not the texts channel a
9470 // polygon's points ride: this op exists for tens of thousands of them, and
9471 // formatting that many floats into a string every frame would cost more than
9472 // the individual ops it replaces.
9473 let col = match &st.paint {
9474 Paint::Solid(c) => *c,
9475 Paint::Linear(g) => {
9476 gradient_record(
9477 [g.start.x, g.start.y, g.end.x, g.end.y],
9478 0.0,
9479 &g.stops,
9480 &mut nums,
9481 &mut texts,
9482 );
9483 Color::WHITE
9484 }
9485 Paint::Radial(g) => {
9486 gradient_record(
9487 [g.center.x, g.center.y, g.radius, 0.0],
9488 1.0,
9489 &g.stops,
9490 &mut nums,
9491 &mut texts,
9492 );
9493 Color::WHITE
9494 }
9495 };
9496 push(
9497 OpCode::Stamp,
9498 st.at.len() as f64,
9499 0.0,
9500 0.0,
9501 0.0,
9502 0.0,
9503 0.0,
9504 0.0,
9505 Color::CLEAR,
9506 &mut nums,
9507 );
9508 for chunk in st.at.chunks(4) {
9509 // Written directly rather than through `push`: this is the one record whose
9510 // last slot is a coordinate rather than a color, which is what lets four
9511 // points fit with nothing wasted.
9512 let mut rec = [
9513 OpCode::StampPoints as i32 as f64,
9514 0.0,
9515 0.0,
9516 0.0,
9517 0.0,
9518 0.0,
9519 0.0,
9520 0.0,
9521 0.0,
9522 ];
9523 for (i, p) in chunk.iter().enumerate() {
9524 rec[1 + i * 2] = p.x;
9525 rec[2 + i * 2] = p.y;
9526 }
9527 nums.extend_from_slice(&rec);
9528 }
9529 match &st.stroke {
9530 None => shape_record(false, &st.shape, 0.0, col, &mut nums, &mut texts),
9531 Some(style) => {
9532 stroke_style_record(style, &mut nums, &mut texts);
9533 shape_record(true, &st.shape, style.width, col, &mut nums, &mut texts);
9534 }
9535 }
9536 }
9537 DrawOp::Stroke(shape, paint, style) => {
9538 // A styled stroke emits one kind-18 record first, applying to the next stroke
9539 // only, the same "modifier record" shape the gradient uses, so decoders keep
9540 // one rule: consume, apply to the next shape record, reset.
9541 stroke_style_record(style, &mut nums, &mut texts);
9542 let col = match paint {
9543 Paint::Solid(c) => *c,
9544 Paint::Linear(g) => {
9545 gradient_record(
9546 [g.start.x, g.start.y, g.end.x, g.end.y],
9547 0.0,
9548 &g.stops,
9549 &mut nums,
9550 &mut texts,
9551 );
9552 Color::WHITE
9553 }
9554 Paint::Radial(g) => {
9555 gradient_record(
9556 [g.center.x, g.center.y, g.radius, 0.0],
9557 1.0,
9558 &g.stops,
9559 &mut nums,
9560 &mut texts,
9561 );
9562 Color::WHITE
9563 }
9564 };
9565 shape_record(true, shape, style.width, col, &mut nums, &mut texts);
9566 }
9567 DrawOp::Clip(shape) => {
9568 // One record for every clip shape, with the shape kind in slot f and the
9569 // geometry in a..e; a path or polygon puts its points on the texts channel.
9570 // Encoding clips as a variant of `shape_record` instead would need a third
9571 // kind code per shape, which is five more numbers every decoder must learn.
9572 let (kind, geo, extra, payload): (f64, [f64; 4], f64, Option<String>) = match shape
9573 {
9574 Shape::Rect(r) => (
9575 0.0,
9576 [r.origin.x, r.origin.y, r.size.width, r.size.height],
9577 0.0,
9578 None,
9579 ),
9580 Shape::RoundedRect(r, rad) => (
9581 1.0,
9582 [r.origin.x, r.origin.y, r.size.width, r.size.height],
9583 *rad,
9584 None,
9585 ),
9586 Shape::Ellipse(r) => (
9587 2.0,
9588 [r.origin.x, r.origin.y, r.size.width, r.size.height],
9589 0.0,
9590 None,
9591 ),
9592 // Slot a carries the geometry key for these two sub-kinds only. The other
9593 // three put real geometry there, which is why the key rides the same slot
9594 // the payload-bearing kinds leave empty.
9595 Shape::Path(p) => (
9596 3.0,
9597 [geometry_key(shape), 0.0, 0.0, 0.0],
9598 rule_bits(p.rule),
9599 Some(encode_path(p)),
9600 ),
9601 Shape::Polygon(pts) => (
9602 4.0,
9603 [geometry_key(shape), 0.0, 0.0, 0.0],
9604 0.0,
9605 Some(
9606 pts.iter()
9607 .map(|p| format!("{},{}", p.x, p.y))
9608 .collect::<Vec<_>>()
9609 .join(" "),
9610 ),
9611 ),
9612 // A clip to a line or an arc has no interior to clip to. Clipping to an
9613 // empty region would blank everything after it, so clip to the shape's
9614 // bounds instead: wrong in the same direction as no clip at all.
9615 Shape::Line(..) | Shape::Arc { .. } => {
9616 let r = shape.bounds();
9617 (
9618 0.0,
9619 [r.origin.x, r.origin.y, r.size.width, r.size.height],
9620 0.0,
9621 None,
9622 )
9623 }
9624 };
9625 push(
9626 OpCode::Clip,
9627 geo[0],
9628 geo[1],
9629 geo[2],
9630 geo[3],
9631 extra,
9632 kind,
9633 0.0,
9634 Color::CLEAR,
9635 &mut nums,
9636 );
9637 if let Some(s) = payload {
9638 texts.push(s);
9639 }
9640 }
9641 DrawOp::Text {
9642 text,
9643 at,
9644 size,
9645 color,
9646 anchor,
9647 font,
9648 } => {
9649 if *font != CanvasFont::default() {
9650 push(
9651 OpCode::SetFont,
9652 f64::from(font.css_weight()),
9653 f64::from(u8::from(font.italic)),
9654 0.0,
9655 0.0,
9656 0.0,
9657 0.0,
9658 0.0,
9659 Color::CLEAR,
9660 &mut nums,
9661 );
9662 texts.push(
9663 font.family_str()
9664 .replace([FONT_LIST_FIELD, FONT_LIST_FAMILY], " "),
9665 );
9666 }
9667 push(
9668 OpCode::Text,
9669 at.x,
9670 at.y,
9671 0.0,
9672 0.0,
9673 *size,
9674 anchor.pack(),
9675 0.0,
9676 *color,
9677 &mut nums,
9678 );
9679 texts.push(text.clone());
9680 }
9681 DrawOp::Image {
9682 image,
9683 rect,
9684 opacity,
9685 } => push(
9686 OpCode::Image,
9687 rect.origin.x,
9688 rect.origin.y,
9689 rect.size.width,
9690 rect.size.height,
9691 image.0 as f64,
9692 *opacity,
9693 0.0,
9694 Color::CLEAR,
9695 &mut nums,
9696 ),
9697 DrawOp::Save => push(
9698 OpCode::Save,
9699 0.0,
9700 0.0,
9701 0.0,
9702 0.0,
9703 0.0,
9704 0.0,
9705 0.0,
9706 Color::CLEAR,
9707 &mut nums,
9708 ),
9709 DrawOp::Restore => push(
9710 OpCode::Restore,
9711 0.0,
9712 0.0,
9713 0.0,
9714 0.0,
9715 0.0,
9716 0.0,
9717 0.0,
9718 Color::CLEAR,
9719 &mut nums,
9720 ),
9721 DrawOp::Concat(m) => push(
9722 OpCode::Concat,
9723 m.a,
9724 m.b,
9725 m.c,
9726 m.d,
9727 m.tx,
9728 m.ty,
9729 0.0,
9730 Color::CLEAR,
9731 &mut nums,
9732 ),
9733 }
9734 }
9735 (nums, texts)
9736}
9737
9738#[cfg(test)]
9739mod font_list_tests {
9740 use super::*;
9741
9742 #[test]
9743 fn css_weights_round_trip_and_snap_to_the_nearest_rung() {
9744 for w in FontWeight::ALL {
9745 assert_eq!(FontWeight::from_css(w.css()), w);
9746 }
9747 assert_eq!(FontWeight::from_css(0), FontWeight::UltraLight);
9748 assert_eq!(FontWeight::from_css(350), FontWeight::Regular); // ties go heavier
9749 assert_eq!(FontWeight::from_css(649), FontWeight::Semibold);
9750 assert_eq!(FontWeight::from_css(1200), FontWeight::Black);
9751 }
9752
9753 fn sans() -> FontFamilyInfo {
9754 FontFamilyInfo {
9755 family: "Day Sans".into(),
9756 faces: vec![
9757 FontFace {
9758 name: "Regular".into(),
9759 weight: FontWeight::Regular,
9760 italic: false,
9761 },
9762 FontFace {
9763 name: "Bold".into(),
9764 weight: FontWeight::Bold,
9765 italic: false,
9766 },
9767 FontFace {
9768 name: "Light Italic".into(),
9769 weight: FontWeight::Light,
9770 italic: true,
9771 },
9772 ],
9773 }
9774 }
9775
9776 #[test]
9777 fn face_for_prefers_the_slant_then_the_nearest_weight() {
9778 let f = sans();
9779 assert!(f.has_bold() && f.has_italic());
9780 assert_eq!(f.face_for(FontWeight::Bold, false).unwrap().name, "Bold");
9781 assert_eq!(
9782 f.face_for(FontWeight::Semibold, false).unwrap().name,
9783 "Bold"
9784 );
9785 assert_eq!(
9786 f.face_for(FontWeight::Medium, false).unwrap().name,
9787 "Regular"
9788 );
9789 let tie = FontFamilyInfo {
9790 family: "Tie".into(),
9791 faces: vec![
9792 FontFace {
9793 name: "Light".into(),
9794 weight: FontWeight::Light,
9795 italic: false,
9796 },
9797 FontFace {
9798 name: "Bold".into(),
9799 weight: FontWeight::Bold,
9800 italic: false,
9801 },
9802 ],
9803 };
9804 // Medium sits 200 from both; the heavier face wins the tie.
9805 assert_eq!(
9806 tie.face_for(FontWeight::Medium, false).unwrap().name,
9807 "Bold"
9808 );
9809 assert_eq!(
9810 f.face_for(FontWeight::Black, true).unwrap().name,
9811 "Light Italic"
9812 );
9813 let none = FontFamilyInfo {
9814 family: "Empty".into(),
9815 faces: vec![],
9816 };
9817 assert!(none.face_for(FontWeight::Regular, false).is_none());
9818 assert!(!none.has_bold());
9819 }
9820
9821 #[test]
9822 fn the_shim_list_format_decodes_tolerantly() {
9823 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\
9824 \u{1e}\u{1e}Day Mono\u{1f}Regular\u{1f}400\u{1f}0\u{1e}Faceless";
9825 let list = parse_font_list(s);
9826 assert_eq!(list.len(), 3);
9827 assert_eq!(list[0].family, "Day Sans");
9828 assert_eq!(list[0].faces.len(), 2, "the bad weight is skipped");
9829 assert_eq!(list[0].faces[1].name, "Bold Italic"); // synthesized from 700 + italic
9830 assert_eq!(list[1].family, "Day Mono");
9831 assert_eq!(list[2].family, "Faceless");
9832 assert!(list[2].faces.is_empty());
9833 }
9834
9835 #[test]
9836 fn approximate_metrics_scale_with_size_and_length() {
9837 let m = TextMetrics::approximate("abc", 10.0);
9838 assert_eq!((m.width, m.height, m.ascent), (18.0, 12.0, 9.0));
9839 assert_eq!(TextMetrics::approximate("", 10.0).width, 0.0);
9840 }
9841
9842 #[test]
9843 fn a_default_canvas_font_is_the_platform_face() {
9844 let f = CanvasFont::default();
9845 assert_eq!((f.family_str(), f.css_weight(), f.italic), ("", 0, false));
9846 }
9847}
9848
9849#[cfg(test)]
9850mod image_header_tests {
9851 use super::*;
9852
9853 /// A 4×2 PNG: signature, then an IHDR whose width and height are big-endian.
9854 fn png(w: u32, h: u32) -> Vec<u8> {
9855 let mut v = vec![0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a];
9856 v.extend(13u32.to_be_bytes());
9857 v.extend(b"IHDR");
9858 v.extend(w.to_be_bytes());
9859 v.extend(h.to_be_bytes());
9860 v
9861 }
9862
9863 /// A JPEG whose frame header sits behind one other segment, so the walk has to skip it.
9864 fn jpeg(w: u16, h: u16) -> Vec<u8> {
9865 let mut v = vec![0xFF, 0xD8]; // SOI
9866 v.extend([0xFF, 0xE0, 0x00, 0x04, 0x00, 0x00]); // APP0, length 4
9867 v.extend([0xFF, 0xC0, 0x00, 0x11, 0x08]); // SOF0, length 17, precision 8
9868 v.extend(h.to_be_bytes());
9869 v.extend(w.to_be_bytes());
9870 v
9871 }
9872
9873 #[test]
9874 fn a_header_states_the_size_before_anything_decodes() {
9875 assert_eq!(ImageFormat::dimensions(&png(512, 512)), Some((512, 512)));
9876 assert_eq!(ImageFormat::dimensions(&png(1, 65535)), Some((1, 65535)));
9877 // The JPEG walk must step over the APP0 segment to reach the frame header.
9878 assert_eq!(ImageFormat::dimensions(&jpeg(640, 480)), Some((640, 480)));
9879
9880 let mut gif = b"GIF89a".to_vec();
9881 gif.extend(320u16.to_le_bytes());
9882 gif.extend(240u16.to_le_bytes());
9883 assert_eq!(ImageFormat::dimensions(&gif), Some((320, 240)));
9884
9885 // A top-down BMP states its height as a negative number; the size is still positive.
9886 let mut bmp = b"BM".to_vec();
9887 bmp.resize(18, 0);
9888 bmp.extend(64i32.to_le_bytes());
9889 bmp.extend((-32i32).to_le_bytes());
9890 assert_eq!(ImageFormat::dimensions(&bmp), Some((64, 32)));
9891 }
9892
9893 #[test]
9894 fn a_truncated_or_unknown_header_answers_nothing_rather_than_a_guess() {
9895 assert_eq!(ImageFormat::dimensions(&[]), None);
9896 // The signature is there but the IHDR is not.
9897 assert_eq!(ImageFormat::dimensions(&png(8, 8)[..12]), None);
9898 // Not an image at all.
9899 assert_eq!(ImageFormat::dimensions(b"not an image"), None);
9900 // A JPEG that never reaches a frame header must not loop or invent a size.
9901 assert_eq!(
9902 ImageFormat::dimensions(&[0xFF, 0xD8, 0xFF, 0xE0, 0x00, 0x04, 0, 0]),
9903 None
9904 );
9905 }
9906}
9907
9908#[cfg(test)]
9909mod encode_ops_tests {
9910 use super::*;
9911
9912 /// The wire codes are a frozen dense table: any gap, duplicate, or variant missing from
9913 /// `ALL` breaks a decoder somewhere, so it must break here first.
9914 #[test]
9915 fn op_codes_are_dense_and_round_trip() {
9916 for (i, code) in OpCode::ALL.into_iter().enumerate() {
9917 assert_eq!(code as i32, i as i32, "{code:?} broke wire density");
9918 assert_eq!(OpCode::from_wire(i as f64), Some(code));
9919 }
9920 assert_eq!(OpCode::from_wire(OpCode::ALL.len() as f64), None);
9921 assert_eq!(OpCode::from_wire(-1.0), None);
9922 assert_eq!(OpCode::from_wire(0.5), None);
9923 }
9924
9925 /// Reference decode of a display list covering every op arm: the record stream must be
9926 /// whole 9-slot records of known codes, and the texts channel must carry exactly one
9927 /// entry per text-carrying record, in order: the contract every shim decoder assumes.
9928 #[test]
9929 fn encode_ops_emits_whole_records_and_matched_text_payloads() {
9930 let r = Rect::new(1.0, 2.0, 3.0, 4.0);
9931 let red = Color::rgb(1.0, 0.0, 0.0);
9932 let ops = vec![
9933 DrawOp::Fill(Shape::Rect(r), Paint::Solid(red)),
9934 DrawOp::Stroke(Shape::Rect(r), Paint::Solid(red), StrokeStyle::round(2.0)),
9935 DrawOp::Fill(Shape::RoundedRect(r, 5.0), Paint::Solid(red)),
9936 DrawOp::Fill(Shape::Ellipse(r), Paint::Solid(red)),
9937 // The documented asymmetry: a filled arc encodes as StrokeArc with width 0.
9938 DrawOp::Fill(
9939 Shape::Arc {
9940 rect: r,
9941 start_deg: 0.0,
9942 sweep_deg: 90.0,
9943 },
9944 Paint::Solid(red),
9945 ),
9946 DrawOp::Stroke(
9947 Shape::Line(Point::new(0.0, 0.0), Point::new(9.0, 9.0)),
9948 Paint::Solid(red),
9949 StrokeStyle::width(1.0),
9950 ),
9951 DrawOp::Fill(
9952 Shape::Polygon(vec![
9953 Point::new(0.0, 0.0),
9954 Point::new(4.0, 0.0),
9955 Point::new(2.0, 3.0),
9956 ]),
9957 Paint::Solid(red),
9958 ),
9959 DrawOp::Fill(
9960 Shape::Path(Path {
9961 segs: vec![
9962 PathSeg::Move(Point::new(0.0, 0.0)),
9963 PathSeg::Line(Point::new(5.0, 5.0)),
9964 PathSeg::Close,
9965 ],
9966 rule: FillRule::EvenOdd,
9967 }),
9968 Paint::Linear(LinearGradient::new(
9969 UnitPoint::new(0.0, 0.0),
9970 UnitPoint::new(1.0, 1.0),
9971 vec![(0.0, red), (1.0, Color::WHITE)],
9972 )),
9973 ),
9974 DrawOp::Clip(Shape::Rect(r)),
9975 DrawOp::Clip(Shape::Polygon(vec![
9976 Point::new(0.0, 0.0),
9977 Point::new(1.0, 0.0),
9978 Point::new(0.0, 1.0),
9979 ])),
9980 DrawOp::Text {
9981 text: "hi".into(),
9982 at: Point::new(7.0, 8.0),
9983 size: 12.0,
9984 color: red,
9985 anchor: TextAnchor::LEADING,
9986 font: CanvasFont::default(),
9987 },
9988 DrawOp::Text {
9989 text: "bold".into(),
9990 at: Point::new(7.0, 8.0),
9991 size: 12.0,
9992 color: red,
9993 anchor: TextAnchor::CENTERED,
9994 font: CanvasFont {
9995 family: Some("Day Sans".into()),
9996 weight: Some(FontWeight::Bold),
9997 italic: true,
9998 },
9999 },
10000 DrawOp::Save,
10001 DrawOp::Concat(Affine::IDENTITY),
10002 DrawOp::Restore,
10003 DrawOp::Image {
10004 image: BitmapId(7),
10005 rect: r,
10006 opacity: 0.5,
10007 },
10008 ];
10009 let (nums, texts) = encode_ops(&ops);
10010 assert_eq!(nums.len() % 9, 0, "partial record on the wire");
10011
10012 let mut expected_texts = 0usize;
10013 let mut decoded = Vec::new();
10014 for rec in nums.chunks(9) {
10015 let code = OpCode::from_wire(rec[0])
10016 .unwrap_or_else(|| panic!("unknown op code {} on the wire", rec[0]));
10017 decoded.push(code);
10018 expected_texts += match code {
10019 OpCode::Text
10020 | OpCode::FillPolygon
10021 | OpCode::StrokePolygon
10022 | OpCode::SetGradient
10023 | OpCode::FillPath
10024 | OpCode::StrokePath
10025 | OpCode::StrokeStyle
10026 | OpCode::SetFont => 1,
10027 // Clip carries a payload only for its path (3) / polygon (4) sub-kinds.
10028 OpCode::Clip => usize::from(rec[6] == 3.0 || rec[6] == 4.0),
10029 _ => 0,
10030 };
10031 }
10032 assert_eq!(
10033 texts.len(),
10034 expected_texts,
10035 "texts channel out of step with the records that consume it"
10036 );
10037 // No payload may carry the transport separator.
10038 assert!(texts.iter().all(|t| !t.contains('\u{1f}')));
10039
10040 let expected = {
10041 use OpCode::*;
10042 vec![
10043 FillRect,
10044 StrokeStyle, // ::round(2.0) is not plain, so the style modifier precedes
10045 StrokeRect,
10046 FillRrect,
10047 FillEllipse,
10048 StrokeArc, // the filled arc's stroke encoding…
10049 Line,
10050 FillPolygon,
10051 SetGradient, // gradient precedes its shape record
10052 FillPath,
10053 Clip,
10054 Clip,
10055 Text,
10056 SetFont, // a non-default font precedes its text record…
10057 Text,
10058 Save,
10059 Concat,
10060 Restore,
10061 Image,
10062 ]
10063 };
10064 assert_eq!(decoded, expected);
10065 // The bitmap id rides the numeric channel intact (an f64 holds a u64 id exactly well
10066 // past any id this process will mint), and nothing of an image reaches the texts channel.
10067 let img = nums
10068 .chunks(9)
10069 .find(|r| r[0] == OpCode::Image as i32 as f64)
10070 .expect("Image record");
10071 assert_eq!(&img[1..7], &[1.0, 2.0, 3.0, 4.0, 7.0, 0.5]);
10072 // …carrying the CSS weight and the slant, with the family on the texts channel.
10073 let font_rec = nums
10074 .chunks(9)
10075 .find(|r| r[0] == OpCode::SetFont as i32 as f64)
10076 .expect("SetFont record");
10077 assert_eq!(&font_rec[1..3], &[700.0, 1.0]);
10078 assert_eq!(texts.iter().filter(|t| *t == "Day Sans").count(), 1);
10079 // …with width 0, per the documented asymmetry.
10080 let arc = nums
10081 .chunks(9)
10082 .find(|r| r[0] == OpCode::StrokeArc as i32 as f64);
10083 assert_eq!(arc.map(|r| r[7]), Some(0.0));
10084 // A gradient-filled shape's color slot is opaque white, never clear (Skia decoders
10085 // modulate the shader by it).
10086 let path_rec = nums
10087 .chunks(9)
10088 .find(|r| r[0] == OpCode::FillPath as i32 as f64);
10089 assert_eq!(
10090 path_rec.map(|r| r[8] as u32),
10091 Some(0xFFFF_FFFF),
10092 "gradient shape record must carry opaque white"
10093 );
10094 }
10095
10096 #[test]
10097 fn variable_length_geometry_carries_a_content_key() {
10098 let path = |x: f64| {
10099 Shape::Path(Path {
10100 segs: vec![
10101 PathSeg::Move(Point::new(x, 0.0)),
10102 PathSeg::Cubic(
10103 Point::new(1.0, 1.0),
10104 Point::new(2.0, 2.0),
10105 Point::new(3.0, 3.0),
10106 ),
10107 PathSeg::Close,
10108 ],
10109 rule: FillRule::NonZero,
10110 })
10111 };
10112 let poly = Shape::Polygon(vec![
10113 Point::new(0.0, 0.0),
10114 Point::new(1.0, 0.0),
10115 Point::new(0.0, 1.0),
10116 ]);
10117
10118 // Equal geometry keys equal though the two were built separately. The key exists for
10119 // this: a draw closure rebuilds its paths from scratch on every frame.
10120 assert_eq!(geometry_key(&path(0.0)), geometry_key(&path(0.0)));
10121 assert_ne!(geometry_key(&path(0.0)), geometry_key(&path(1.0)));
10122 // The fill rule decides what the path draws, so it belongs to the key.
10123 let even_odd = Shape::Path(Path {
10124 segs: match path(0.0) {
10125 Shape::Path(p) => p.segs,
10126 _ => unreachable!(),
10127 },
10128 rule: FillRule::EvenOdd,
10129 });
10130 assert_ne!(geometry_key(&path(0.0)), geometry_key(&even_odd));
10131 // A polygon and a path decode to different geometry and never share an entry.
10132 assert_ne!(geometry_key(&poly), geometry_key(&path(0.0)));
10133 // Fixed-size shapes keep 0: their geometry rides the record's own slots.
10134 assert_eq!(
10135 geometry_key(&Shape::Rect(Rect::new(0.0, 0.0, 1.0, 1.0))),
10136 0.0
10137 );
10138 // And a key survives an f64 wire slot exactly, which is what the 53-bit mask buys.
10139 let k = geometry_key(&path(0.0));
10140 assert!(
10141 k > 0.0 && k < (1u64 << 53) as f64 && k.fract() == 0.0,
10142 "{k}"
10143 );
10144
10145 // It reaches the wire in slot a, for exactly the ops whose payload rides the texts
10146 // channel, and never displaces geometry that is already there.
10147 let (nums, _) = encode_ops(&[
10148 DrawOp::Fill(path(0.0), Paint::Solid(Color::WHITE)),
10149 DrawOp::Fill(poly.clone(), Paint::Solid(Color::WHITE)),
10150 DrawOp::Clip(path(0.0)),
10151 DrawOp::Clip(Shape::Rect(Rect::new(1.0, 2.0, 3.0, 4.0))),
10152 ]);
10153 let slot_a = |code: OpCode| {
10154 nums.chunks(9)
10155 .find(|r| r[0] == code as i32 as f64)
10156 .unwrap_or_else(|| panic!("no {code:?} record"))[1]
10157 };
10158 assert_eq!(slot_a(OpCode::FillPath), geometry_key(&path(0.0)));
10159 assert_eq!(slot_a(OpCode::FillPolygon), geometry_key(&poly));
10160 let clips: Vec<&[f64]> = nums
10161 .chunks(9)
10162 .filter(|r| r[0] == OpCode::Clip as i32 as f64)
10163 .collect();
10164 assert_eq!(clips[0][1], geometry_key(&path(0.0)), "path clip keys");
10165 assert_eq!(
10166 &clips[1][1..5],
10167 &[1.0, 2.0, 3.0, 4.0],
10168 "a rect clip still puts its geometry in a..d"
10169 );
10170 }
10171}
10172
10173#[cfg(test)]
10174mod markup_tests {
10175 use super::*;
10176
10177 fn bold(range: std::ops::Range<usize>) -> TextRun {
10178 TextRun::font(
10179 range,
10180 FontSpec {
10181 style: Font::Body,
10182 weight: Some(FontWeight::Bold),
10183 ..Default::default()
10184 },
10185 )
10186 }
10187
10188 #[test]
10189 fn plain_text_is_escaped_in_both_dialects() {
10190 // The case a translated string will find: markup metacharacters in the content.
10191 let text = "5 < 6 & \"quoted\" <b>not bold</b>";
10192 for d in [MarkupDialect::Pango, MarkupDialect::QtHtml] {
10193 let m = runs_to_markup(text, &[], d, 16.0);
10194 assert!(!m.contains("<b>"), "content tag survived into markup: {m}");
10195 assert!(m.contains("<b>"), "{m}");
10196 assert!(m.contains("&"), "{m}");
10197 assert!(m.contains("5 < 6"), "{m}");
10198 }
10199 }
10200
10201 #[test]
10202 fn a_styled_run_is_wrapped_and_its_text_escaped() {
10203 let text = "a <b> c";
10204 let m = runs_to_markup(text, &[bold(2..5)], MarkupDialect::Pango, 16.0);
10205 assert_eq!(m, "a <b><b></b> c");
10206 }
10207
10208 #[test]
10209 fn color_and_monospace_differ_per_dialect() {
10210 let text = "code";
10211 let run = TextRun {
10212 range: 0..4,
10213 font: FontSpec {
10214 style: Font::Body,
10215 monospace: true,
10216 ..Default::default()
10217 },
10218 color: Some(Color::rgb(1.0, 0.0, 0.0)),
10219 ..TextRun::default()
10220 };
10221 let pango = runs_to_markup(text, std::slice::from_ref(&run), MarkupDialect::Pango, 16.0);
10222 assert!(pango.contains("foreground=\"#ff0000\""), "{pango}");
10223 assert!(pango.contains("font_family=\"monospace\""), "{pango}");
10224 let qt = runs_to_markup(
10225 text,
10226 std::slice::from_ref(&run),
10227 MarkupDialect::QtHtml,
10228 16.0,
10229 );
10230 assert!(qt.contains("color:#ff0000"), "{qt}");
10231 // Qt takes its fixed face from <code>: a `font-family:monospace` style attribute
10232 // renders proportional (observed on Qt 6.11).
10233 assert!(qt.contains("<code>") && qt.contains("</code>"), "{qt}");
10234 }
10235
10236 #[test]
10237 fn the_new_attributes_reach_both_dialects() {
10238 let run = TextRun {
10239 range: 0..2,
10240 font: FontSpec::default().scaled(1.5),
10241 background: Some(Color::rgb(0.0, 1.0, 0.0)),
10242 underline: Underline::Single,
10243 ..TextRun::default()
10244 };
10245 let pango = runs_to_markup("hi", std::slice::from_ref(&run), MarkupDialect::Pango, 16.0);
10246 assert!(pango.contains("background=\"#00ff00\""), "{pango}");
10247 // Pango takes an absolute size in 1/1024 pt (16 pt base × 1.5 = 24 pt), because the
10248 // relative attributes are Pango 1.50's and an unknown attribute empties the whole label.
10249 assert!(pango.contains("size=\"24576\""), "{pango}");
10250 assert!(pango.contains("<u>hi</u>"), "{pango}");
10251 let qt = runs_to_markup(
10252 "hi",
10253 std::slice::from_ref(&run),
10254 MarkupDialect::QtHtml,
10255 16.0,
10256 );
10257 assert!(qt.contains("background-color:#00ff00"), "{qt}");
10258 // Qt takes points: 16 pt base × 1.5 (observed; its CSS subset ignores a percentage).
10259 assert!(qt.contains("font-size:24pt"), "{qt}");
10260 assert!(qt.contains("<u>hi</u>"), "{qt}");
10261 }
10262
10263 #[test]
10264 fn a_link_target_is_escaped_too() {
10265 // A URL carrying `&` between query parameters is ordinary, and unescaped it truncates
10266 // the attribute and swallows the rest of the label.
10267 let text = "docs";
10268 let run = TextRun {
10269 range: 0..4,
10270 link: Some("https://x.dev/?a=1&b=2".into()),
10271 ..TextRun::default()
10272 };
10273 let m = runs_to_markup(text, &[run], MarkupDialect::Pango, 16.0);
10274 assert!(m.contains("a=1&b=2"), "{m}");
10275 }
10276
10277 #[test]
10278 fn tags_nest_and_close_in_reverse() {
10279 let run = TextRun {
10280 range: 0..2,
10281 font: FontSpec {
10282 style: Font::Body,
10283 weight: Some(FontWeight::Bold),
10284 italic: true,
10285 ..Default::default()
10286 },
10287 strikethrough: true,
10288 link: Some("u".into()),
10289 ..TextRun::default()
10290 };
10291 let m = runs_to_markup("hi", &[run], MarkupDialect::Pango, 16.0);
10292 assert_eq!(m, "<a href=\"u\"><b><i><s>hi</s></i></b></a>");
10293 }
10294
10295 #[test]
10296 fn runs_out_of_bounds_are_skipped_not_panicked() {
10297 // `runs_are_valid` rejects these upstream; this is the belt-and-braces path.
10298 let m = runs_to_markup("hi", &[bold(0..99)], MarkupDialect::Pango, 16.0);
10299 assert_eq!(m, "hi");
10300 }
10301
10302 #[test]
10303 fn validation_catches_the_four_ways_runs_go_wrong() {
10304 let text = "héllo";
10305 assert!(runs_are_valid(text, &[bold(0..1)]).is_ok());
10306 // Overlapping.
10307 assert!(runs_are_valid(text, &[bold(0..3), bold(2..4)]).is_err());
10308 // Past the end.
10309 assert!(runs_are_valid(text, &[bold(0..99)]).is_err());
10310 // Inverted. Built from parts, since a literal `3..1` is a clippy error in its own right.
10311 let (hi, lo) = (3, 1);
10312 assert!(runs_are_valid(text, &[bold(hi..lo)]).is_err());
10313 // Splitting the 2-byte `é`.
10314 assert!(runs_are_valid(text, &[bold(0..2)]).is_err());
10315 }
10316}
10317
10318#[cfg(test)]
10319mod route_of_url_tests {
10320 use super::route_of_url;
10321
10322 #[test]
10323 fn strips_the_scheme_and_keeps_route_and_params() {
10324 assert_eq!(
10325 route_of_url("notes://mail/inbox?hint=x"),
10326 "mail/inbox?hint=x"
10327 );
10328 assert_eq!(route_of_url("notes://home"), "home");
10329 // No scheme: already a route, unchanged.
10330 assert_eq!(route_of_url("mail/inbox"), "mail/inbox");
10331 assert_eq!(route_of_url(""), "");
10332 // Percent-encoding passes through; the route parser decodes, not this mapping.
10333 assert_eq!(route_of_url("n://a/b%2Fc?q=1%202"), "a/b%2Fc?q=1%202");
10334 }
10335}
10336
10337#[cfg(test)]
10338mod builtin_kind_tests {
10339 use super::*;
10340
10341 /// Every built-in round-trips through its wire key, and the keys are unique. Guards the
10342 /// `builtin_kinds!` expansion: a copy-paste slip in the table would alias two kinds.
10343 #[test]
10344 fn keys_round_trip_and_are_unique() {
10345 let mut seen = std::collections::HashSet::new();
10346 for &b in Builtin::ALL {
10347 assert_eq!(Builtin::from_key(b.key()), Some(b), "{b:?} key round-trip");
10348 assert!(seen.insert(b.key()), "duplicate key {:?}", b.key());
10349 assert!(
10350 b.key().starts_with("day."),
10351 "built-in {b:?} must use the reserved `day.` prefix"
10352 );
10353 }
10354 }
10355
10356 /// The `kinds::*` constants are the enum's keys, so the two spellings cannot drift.
10357 #[test]
10358 fn kinds_constants_match_the_enum() {
10359 assert_eq!(kinds::LABEL, Builtin::Label.key());
10360 assert_eq!(kinds::LIST_CELL, Builtin::ListCell.key());
10361 assert_eq!(kinds::COVER, Builtin::Cover.key());
10362 assert_eq!(kinds::INSPECTOR, Builtin::Inspector.key());
10363 assert_eq!(kinds::TREE, Builtin::Tree.key());
10364 // 19 after `Tabs`/`TabsPage` retired (the tab bar is a NAV presentation, not a kind),
10365 // +2 for the inspector split and its panes (docs/inspector.md), +1 for the tree
10366 // (docs/tree.md).
10367 assert_eq!(Builtin::ALL.len(), 25);
10368 }
10369
10370 /// An extension piece's kind is not a built-in.
10371 #[test]
10372 fn extension_kinds_are_not_builtin() {
10373 assert_eq!(Builtin::from_key("acme.combobox"), None);
10374 assert_eq!(Builtin::from_key("day.not_a_real_kind"), None);
10375 }
10376}
10377
10378#[cfg(test)]
10379mod locale_tests {
10380 /// POSIX locale strings are not BCP-47 tags, and "C" is not a language; that difference is
10381 /// the job of `posix_locale_hints` (§12.2).
10382 #[test]
10383 fn posix_hints_parse_and_drop_the_c_locale() {
10384 // The parsing is exercised through the same normalization the function applies.
10385 let normalize = |v: &str| v.split('.').next().unwrap_or(v).replace('_', "-");
10386 assert_eq!(normalize("fr_FR.UTF-8"), "fr-FR");
10387 assert_eq!(normalize("en_US"), "en-US");
10388 assert_eq!(normalize("C"), "C");
10389 // A real read never panics whatever this host's environment holds.
10390 let hints = super::posix_locale_hints();
10391 assert!(
10392 hints
10393 .iter()
10394 .all(|h| !h.is_empty() && h != "C" && h != "POSIX")
10395 );
10396 }
10397}
10398
10399#[cfg(test)]
10400mod sidetable_tests {
10401 use super::sidetable::{SideTable, sweep};
10402 use std::cell::Cell;
10403 use std::rc::Rc;
10404
10405 /// The registry exists so that one `sweep(key)` clears every table without any
10406 /// table needing its own line in a backend's `release()`.
10407 #[test]
10408 fn sweep_clears_every_registered_table_and_runs_teardowns() {
10409 let torn = Rc::new(Cell::new(0u32));
10410 let t2 = torn.clone();
10411 let plain: SideTable<&'static str> = SideTable::new();
10412 let hooked: SideTable<u32> = SideTable::with_teardown(move |_| t2.set(t2.get() + 1));
10413
10414 plain.insert(7, "a");
10415 hooked.insert(7, 1);
10416 hooked.insert(8, 2);
10417 sweep(7);
10418 assert!(!plain.contains(7));
10419 assert!(!hooked.contains(7), "swept from every table");
10420 assert!(hooked.contains(8), "other keys untouched");
10421 assert_eq!(torn.get(), 1, "teardown ran for the swept value");
10422
10423 // remove() runs the teardown too; take() bypasses it for ownership transfer.
10424 hooked.remove(8);
10425 assert_eq!(torn.get(), 2);
10426 hooked.insert(9, 3);
10427 assert_eq!(hooked.take(9), Some(3));
10428 assert_eq!(torn.get(), 2, "take() skips the hook");
10429 }
10430
10431 #[test]
10432 fn contain_returns_default_on_panic() {
10433 let ok = super::ffi_guard::contain(0i32, || 5);
10434 assert_eq!(ok, 5);
10435 let prev = std::panic::take_hook();
10436 std::panic::set_hook(Box::new(|_| {}));
10437 let contained = super::ffi_guard::contain(-1i32, || panic!("boom"));
10438 std::panic::set_hook(prev);
10439 assert_eq!(contained, -1, "the panic must not escape the guard");
10440 }
10441}
10442
10443#[cfg(test)]
10444mod cursor_tests {
10445 use super::Cursor;
10446
10447 /// Every named cursor has a distinct CSS keyword, and `NAMED` lists each exactly once: the
10448 /// gallery and every backend's table key on the keyword.
10449 #[test]
10450 fn named_cursors_have_distinct_css_names() {
10451 let mut seen = std::collections::BTreeSet::new();
10452 for c in Cursor::NAMED.iter() {
10453 assert!(
10454 seen.insert(c.css_name().to_string()),
10455 "duplicate: {}",
10456 c.css_name()
10457 );
10458 assert!(!matches!(c, Cursor::Native(_)));
10459 }
10460 assert_eq!(seen.len(), Cursor::NAMED.len());
10461 assert_eq!(Cursor::native("dragCopy").css_name(), "dragCopy");
10462 assert_eq!(Cursor::default(), Cursor::Default);
10463 }
10464}
10465
10466#[cfg(test)]
10467mod text_anchor_tests {
10468 /// The anchor arithmetic every backend repeats. A drawing whose text lands in the wrong
10469 /// corner is a per-backend bug that only a screenshot catches, so the shared definition is
10470 /// pinned here and each shim is written to match it.
10471 #[test]
10472 fn text_anchor_offsets_place_the_line_box() {
10473 use crate::props::TextAlign;
10474 use crate::{TextAnchor, TextVAlign};
10475 // A 40-wide, 20-tall line box whose baseline sits 16 below its top.
10476 let (w, h, asc) = (40.0, 20.0, 16.0);
10477 let at = |ha, va| TextAnchor { h: ha, v: va }.offset(w, h, asc);
10478
10479 // The default is the drawing origin itself, every backend's native "draw here".
10480 assert_eq!(at(TextAlign::Leading, TextVAlign::Top), (0.0, 0.0));
10481 assert_eq!(TextAnchor::default(), TextAnchor::LEADING);
10482 // Horizontal: the box's leading edge, its middle, its trailing edge.
10483 assert_eq!(at(TextAlign::Center, TextVAlign::Top).0, -20.0);
10484 assert_eq!(at(TextAlign::Trailing, TextVAlign::Top).0, -40.0);
10485 // Vertical: top, middle, the baseline itself, bottom.
10486 assert_eq!(at(TextAlign::Leading, TextVAlign::Middle).1, -10.0);
10487 assert_eq!(at(TextAlign::Leading, TextVAlign::Baseline).1, -16.0);
10488 assert_eq!(at(TextAlign::Leading, TextVAlign::Bottom).1, -20.0);
10489 // The two named placements are the ones the two-variant enum used to have.
10490 assert_eq!(TextAnchor::CENTERED.offset(w, h, asc), (-20.0, -10.0));
10491 assert_eq!(TextAnchor::TRAILING.offset(w, h, asc), (-40.0, 0.0));
10492 }
10493
10494 /// The wire code the serializing backends (qt, xaml, arkui, android, web) decode by hand.
10495 #[test]
10496 fn text_anchor_packs_into_one_slot_and_round_trips() {
10497 use crate::props::TextAlign;
10498 use crate::{TextAnchor, TextVAlign};
10499 let mut seen = std::collections::BTreeSet::new();
10500 for h in [TextAlign::Leading, TextAlign::Center, TextAlign::Trailing] {
10501 for v in [
10502 TextVAlign::Top,
10503 TextVAlign::Middle,
10504 TextVAlign::Baseline,
10505 TextVAlign::Bottom,
10506 ] {
10507 let a = TextAnchor { h, v };
10508 let code = a.pack();
10509 assert!(
10510 (0.0..=11.0).contains(&code),
10511 "{code} outside the packed range"
10512 );
10513 assert!(seen.insert(code as u64), "two anchors share code {code}");
10514 assert_eq!(TextAnchor::unpack(code), a);
10515 }
10516 }
10517 assert_eq!(seen.len(), 12);
10518 // The shims decode as `h = code / 4`, `v = code % 4` in integer arithmetic.
10519 assert_eq!(TextAnchor::LEADING.pack(), 0.0);
10520 assert_eq!(TextAnchor::CENTERED.pack(), 5.0);
10521 // Junk answers the default rather than failing inside a native draw callback.
10522 assert_eq!(TextAnchor::unpack(-3.0), TextAnchor::LEADING);
10523 assert_eq!(TextAnchor::unpack(99.0), TextAnchor::unpack(11.0));
10524 }
10525
10526 /// The two shapes a backend's own metrics arrive in. Both land on the same contract: the line
10527 /// box's top-leading corner is the origin, and `ink` is relative to it.
10528 #[test]
10529 fn metrics_convert_from_a_backends_own_shape() {
10530 use crate::{Rect, TextMetrics};
10531 // Baseline-relative, y up-negative; Core Text, Skia and Qt all report like this.
10532 let m = TextMetrics::from_baseline(
10533 40.0,
10534 16.0,
10535 4.0,
10536 11.0,
10537 // Ink starting 1 right of the origin, from 11 above the baseline to 2 below it.
10538 Rect::new(1.0, -11.0, 38.0, 13.0),
10539 );
10540 assert_eq!(
10541 (m.width, m.height, m.ascent, m.cap_height),
10542 (40.0, 20.0, 16.0, 11.0)
10543 );
10544 // Shifted down by the ascent: the ink now starts 5 below the line box's top, which is
10545 // where a cap begins in a slot whose baseline is at 16.
10546 assert_eq!(m.ink, Rect::new(1.0, 5.0, 38.0, 13.0));
10547 assert_eq!(m.ascent - m.cap_height, m.ink.origin.y);
10548
10549 // The eight-slot wire form is already line-box-relative and passes straight through.
10550 let w = TextMetrics::from_slots(&[40.0, 20.0, 16.0, 11.0, 1.0, 5.0, 38.0, 13.0]);
10551 assert_eq!(w, m);
10552 }
10553
10554 /// The fallback must be usable, not merely present: a caller frames text with it on a toolkit
10555 /// that cannot measure, and every relation it relies on has to hold.
10556 #[test]
10557 fn the_approximation_is_internally_consistent() {
10558 use crate::TextMetrics;
10559 let m = TextMetrics::approximate("Agy", 20.0);
10560 assert!(m.ascent < m.height, "the baseline sits inside the line box");
10561 assert!(
10562 m.cap_height < m.ascent,
10563 "caps do not reach above the ascent"
10564 );
10565 // The ink box is the whole line box: a superset, so an overlap test using it can only be
10566 // too cautious. Never a claim to be tighter than it knows.
10567 assert_eq!(m.ink.origin.x, 0.0);
10568 assert_eq!(m.ink.origin.y, 0.0);
10569 assert_eq!(m.ink.size.width, m.width);
10570 assert_eq!(m.ink.size.height, m.height);
10571 // Empty text still answers a usable (zero-width, full-height) slot.
10572 let e = TextMetrics::approximate("", 20.0);
10573 assert_eq!(e.width, 0.0);
10574 assert!(e.height > 0.0);
10575 }
10576}
10577
10578#[cfg(test)]
10579mod cap_list_tests {
10580 use super::Cap;
10581
10582 #[test]
10583 fn every_capability_is_listed_once_in_its_place() {
10584 for (i, cap) in Cap::ALL.iter().enumerate() {
10585 assert_eq!(cap.ordinal(), i, "{cap:?} is out of place in Cap::ALL");
10586 }
10587 }
10588}