day_core/lib.rs
1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3
4//! day-core: the Piece model, realized tree, mounter, layout engine, and event routing
5//! (DESIGN.md §5, §7). Build-once: pieces are constructed exactly once; all dynamism flows
6//! through reactive bindings (day-reactive) writing to the thread-local tree.
7
8/// The linked Day runtime version, for diagnostics from independently versioned extensions.
9pub const VERSION: &str = env!("CARGO_PKG_VERSION");
10
11day_reactive::tls_root! {
12 layout: crate::layout::TlsGroupSlots,
13 ambient: crate::ambient::TlsGroupSlots,
14 anim: crate::anim::TlsGroupSlots,
15 conformance: crate::conformance::TlsGroupSlots,
16 frame: crate::frame::TlsGroupSlots,
17 image: crate::image::TlsGroupSlots,
18 list: crate::list::TlsGroupSlots,
19 lifecycle: crate::lifecycle::TlsGroupSlots,
20 menu: crate::menu::TlsGroupSlots,
21 nav: crate::nav::TlsGroupSlots,
22 present: crate::present::TlsGroupSlots,
23 root: crate::TlsGroupSlots,
24 shield: crate::shield::TlsGroupSlots,
25 shortcuts: crate::shortcuts::TlsGroupSlots,
26 status: crate::status::TlsGroupSlots,
27 toolbar: crate::toolbar::TlsGroupSlots,
28 documents: crate::documents::TlsGroupSlots,
29 urls: crate::urls::TlsGroupSlots,
30 tree: crate::tree::TlsGroupSlots,
31 windows: crate::windows::TlsGroupSlots,
32}
33
34/// The blocking pool (docs/async.md): `spawn_blocking` runs a job on a worker thread and
35/// resolves on the awaiting side; std-only, so it lives in day-async and is re-exported here.
36pub use day_async::{
37 Blocking, BlockingError, blocking_inline, blocking_limit, blocking_threads, spawn_blocking,
38};
39#[cfg(target_arch = "wasm32")]
40#[doc(hidden)]
41pub use day_macros::retain_element_id as __retain_element_id;
42/// Re-exported so every crate above day-core can reach it without taking a direct
43/// day-reactive dependency (see day-reactive for what it does and why Android needs it).
44pub use day_reactive::tls_group;
45#[cfg(target_arch = "wasm32")]
46#[doc(hidden)]
47pub use inventory;
48/// The link-time registry crate `#[day::test]` expands through (docs/testing.md).
49pub use linkme;
50
51mod ambient;
52mod anim;
53mod build;
54pub mod conformance;
55pub mod element_id;
56pub mod frame;
57pub use element_id::{ElementId, IntoElementKey};
58mod frames;
59pub mod image;
60mod layout;
61pub mod lifecycle;
62pub mod list;
63mod memory_profile;
64mod modal_sheet;
65pub use modal_sheet::ComposedSheet;
66pub mod menu;
67mod nav;
68mod present;
69pub mod shield;
70pub mod shortcuts;
71pub mod status;
72pub mod testing;
73pub mod toolbar;
74mod tree;
75pub mod tree_driver;
76pub mod tween;
77pub mod windows;
78
79pub use ambient::{
80 Ambient, app_environment, environment, focused_environment, note_keyboard_overlap,
81 override_size_class, reset_ambient, restore_reported_size_class, safe_area, seed_safe_area,
82 set_safe_area, set_size_class, set_window_safe_area, set_window_size_class, size_class,
83 window_safe_area, window_size_class, window_size_class_untracked, with_environment,
84};
85pub use anim::{current_anim, with_animation};
86pub use build::*;
87pub use frame::{
88 FrameConsumer, add_frame_consumer, frame_consumer_count, install_frame_requester,
89 remove_frame_consumer,
90};
91pub use image::{
92 Bitmap, CanvasExports, RenderBitmap, RenderPdf, canvas_exports, decode as decode_image,
93 decode_async as decode_image_async, image_decode_support, image_encode_formats,
94 image_encode_support, render_bitmap, render_bitmap_async, render_pdf, render_pdf_async,
95 resolve_bitmap_render, resolve_image_decode, resolve_image_encode, resolve_pdf_render,
96};
97pub use layout::*;
98pub use lifecycle::{dispatch_lifecycle, lifecycle_supported, on_lifecycle};
99pub use list::{
100 BuiltRow, ListDeleteDriver, ListDriver, ListReorderDriver, ListSectionsDriver, ListSwipeDriver,
101 install_list, list_reload, list_scroll_to_end, list_scroll_to_row, list_set_editing,
102 list_set_selected, list_splice, list_try_delete, list_try_reorder, list_try_swipe,
103 set_scripted_reorder,
104};
105pub use menu::{
106 dispatch_menu_action, has_app_menu, register_menu_action, register_scoped_menu_action,
107 set_app_menu, set_dock_menu,
108};
109pub use nav::*;
110pub use shortcuts::set_launcher_shortcuts;
111pub use status::{
112 KeepRunning, remove_status_item, set_app_progress, set_dock_visible, set_keep_running,
113 set_status_item, status_items,
114};
115pub mod documents;
116#[doc(hidden)]
117pub use documents::{forward_launch_args, launch_link, take_launch_files};
118mod urls;
119pub use documents::{on_open_files, request_open_files};
120pub use present::*;
121pub use toolbar::{
122 Chrome, chrome_changed, current_chrome, current_page_column, current_page_gate,
123 current_page_window, dispatch_toolbar_value, patch_chrome, patch_toolbar,
124 register_contribution, register_contribution_gated, register_toolbar_value,
125 relabel_contribution, toggle_sidebar, unregister_contribution, update_contribution,
126 window_being_built, with_page, with_page_gated, with_page_in,
127};
128pub use tree_driver::{
129 TreeBuiltRow, TreeDriver, TreeMovesDriver, install_tree, tree_driver, tree_reload, tree_reveal,
130 tree_set_expanded, tree_set_selected, tree_try_move, tree_visible_rows,
131};
132pub use urls::{on_open_url, on_shared_text, request_open_url, request_shared_text};
133// The resource types live in day-spec (backends depend only on day-spec); re-exported for the
134// facade.
135pub use day_spec::resource::{
136 AssetDir, AssetName, FontFamily, ImageName, Resource, ResourceOpener, VectorName, resource,
137 set_resource_opener,
138};
139pub use tree::*;
140pub use windows::{
141 WindowHandle, about_action_id, check_for_updates, check_for_updates_action_id, current_window,
142 finish_window_open, focused_scope, focused_window, initial_window, launch_options, monitors,
143 open_about, open_new_window, open_new_window_for_group, open_preferences, open_window, quit,
144 register_about, register_about_window, register_check_for_updates, register_new_window,
145 register_new_window_for, register_preferences, register_preferences_with, window_by_key,
146 window_title,
147};
148
149/// The app-wide layout direction (docs/localization): mirrors every horizontal placement in
150/// the place pass when [`day_geometry::LayoutDirection::Rtl`]. Resolved lazily from the
151/// `DAY_LOCALE` launch environment (so toolkits can read it before any UI exists);
152/// `set_layout_direction` (called by `install_locales` for the resolved locale) overrides.
153/// Fixed for the life of the process; switching locale at runtime does not re-mirror.
154#[must_use]
155pub fn layout_direction() -> day_geometry::LayoutDirection {
156 DIRECTION.with(|d| {
157 if let Some(dir) = d.get() {
158 return dir;
159 }
160 let dir = std::env::var("DAY_LOCALE").map_or_default(|l| direction_of_locale(&l));
161 d.set(Some(dir));
162 dir
163 })
164}
165
166/// Override the layout direction (normally from `install_locales`). Must be called before the
167/// first layout pass to take effect everywhere.
168pub fn set_layout_direction(dir: day_geometry::LayoutDirection) {
169 DIRECTION.with(|d| d.set(Some(dir)));
170}
171
172/// Whether the app is being rendered right-to-left (docs/localization), a convenience over
173/// [`layout_direction`]. The layout engine already mirrors widget *placement* under an RTL locale,
174/// but a `canvas` draws in its own coordinate space, so a custom drawing that has a reading
175/// direction (a battery that drains one way, an arrow, a progress sweep) can call this to mirror
176/// itself. Fixed for the life of the process, like [`layout_direction`].
177#[must_use]
178pub fn is_rtl() -> bool {
179 layout_direction() == day_geometry::LayoutDirection::Rtl
180}
181
182/// The writing direction a locale implies (language subtag match).
183#[must_use]
184pub fn direction_of_locale(locale: &str) -> day_geometry::LayoutDirection {
185 let lang = locale
186 .split(['-', '_'])
187 .next()
188 .unwrap_or("")
189 .to_ascii_lowercase();
190 match lang.as_str() {
191 "ar" | "he" | "iw" | "fa" | "ur" | "ps" | "sd" | "ug" | "yi" | "dv" | "ku" => {
192 day_geometry::LayoutDirection::Rtl
193 }
194 _ => day_geometry::LayoutDirection::Ltr,
195 }
196}
197
198day_reactive::tls_slots! {
199 root;
200 static SEARCH_HOSTS: std::cell::RefCell<Vec<(RNode, RNode)>> =
201 const { std::cell::RefCell::new(Vec::new()) };
202 static DIRECTION: std::cell::Cell<Option<day_geometry::LayoutDirection>> =
203 const { std::cell::Cell::new(None) };
204
205 static UNDO_INVOKE: std::cell::RefCell<Option<UndoInvoke>> =
206 const { std::cell::RefCell::new(None) };
207
208 /// The dayscript executor's stand-in for held modifiers (a synthetic tap cannot hold a
209 /// real shift key); `None` = ask the toolkit.
210 static MODIFIER_OVERRIDE: std::cell::Cell<Option<day_spec::Modifiers>> =
211 const { std::cell::Cell::new(None) };
212
213 static EDIT_INVOKE: std::cell::RefCell<Option<EditInvoke>> =
214 const { std::cell::RefCell::new(None) };
215
216 static UNDO_ACTION_IDS: std::cell::Cell<(u64, u64)> = const { std::cell::Cell::new((0, 0)) };
217 static EDIT_ACTION_IDS: std::cell::Cell<(u64, u64, u64, u64)> =
218 const { std::cell::Cell::new((0, 0, 0, 0)) };
219
220 static PALETTE_SIGNAL: std::cell::OnceCell<day_reactive::Signal<[day_spec::Color; 5]>> =
221 const { std::cell::OnceCell::new() };
222
223 static DARK_SIGNAL: std::cell::OnceCell<day_reactive::Signal<bool>> =
224 const { std::cell::OnceCell::new() };
225
226 /// The system's reduce-motion answer as last read (docs/accessibility.md), kept beside the
227 /// signal so the animation gates can ask without a tracked read or a tree borrow: they run
228 /// inside the tree.
229 static REDUCE_MOTION: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
230 static REDUCE_MOTION_SIGNAL: std::cell::OnceCell<day_reactive::Signal<bool>> =
231 const { std::cell::OnceCell::new() };
232
233 static FONT_FAMILIES: std::cell::OnceCell<std::rc::Rc<[day_spec::FontFamilyInfo]>> =
234 const { std::cell::OnceCell::new() };
235
236 static TEXT_METRICS: std::cell::RefCell<TextMetricsCache> =
237 std::cell::RefCell::new(TextMetricsCache::new());
238}
239
240use day_spec::{Platform, WindowOptions};
241
242// ---- crash observation (§8.5) --------------------------------------------------------------
243
244/// Observer called after day-core contains a panic at one of its trampoline boundaries
245/// (`contain_posted_panic` here, `tree::pump_events`), on the panicking thread, after the
246/// reactive-runtime reset. A crash reporter (day-piece-crash-reporter, docs/break.md) registers one to
247/// downgrade the report its panic hook just wrote: the panic was caught, the process is not
248/// dying. A plain `fn` (no closure) so the containment path allocates nothing.
249static CONTAINED_PANIC_OBSERVER: std::sync::OnceLock<fn()> = std::sync::OnceLock::new();
250
251/// Register the contained-panic observer. First registration wins; later calls are no-ops
252/// (there is one crash reporter per process).
253pub fn set_contained_panic_observer(f: fn()) {
254 let _ = CONTAINED_PANIC_OBSERVER.set(f);
255}
256
257pub(crate) fn notify_contained_panic() {
258 if let Some(f) = CONTAINED_PANIC_OBSERVER.get() {
259 f();
260 }
261}
262
263/// The compile-time target key of the running backend (`"macos-appkit"`, `"ios-uikit"`, …,
264/// the `Platform::TARGET` string), recorded by [`launch_with`]. `None` before launch.
265pub fn backend_name() -> Option<&'static str> {
266 BACKEND_NAME.get().copied()
267}
268
269static BACKEND_NAME: std::sync::OnceLock<&'static str> = std::sync::OnceLock::new();
270
271/// The toolkit key of the running backend (`"appkit"`, `"gtk"`, …, the `Platform::TOOLKIT`
272/// string), recorded by [`launch_with`]. `None` before launch.
273pub fn toolkit_key() -> Option<&'static str> {
274 TOOLKIT_KEY.get().copied()
275}
276
277static TOOLKIT_KEY: std::sync::OnceLock<&'static str> = std::sync::OnceLock::new();
278
279/// The development tag every window title carries in a debug build:
280/// `(<version>/<toolkit>[/<script>])`, for example `(1.1.0/appkit)`, or
281/// `(1.1.0/gtk/walkthrough.yaml)` while a dayscript is driving. With several apps, toolkits and
282/// scripted runs open at once, the title bar is the only place that says which window is which.
283///
284/// `None` in a release build (this is a development aid and must never ship), and before
285/// [`launch_with`] has named the backend. The version and the script name come from
286/// `DAY_APP_VERSION` and `DAY_SCRIPT`, which the `day` CLI sets on every launch; run the binary
287/// some other way and the tag carries the parts it knows.
288#[must_use]
289pub fn debug_title_tag() -> Option<String> {
290 if !cfg!(debug_assertions) {
291 return None;
292 }
293 let toolkit = toolkit_key()?;
294 // The mock backend has no window and no title bar, so there is nothing for a tag to
295 // disambiguate; it would only corrupt what a headless test asserts about a title.
296 if toolkit == "mock" {
297 return None;
298 }
299 let mut parts = Vec::new();
300 if let Ok(v) = std::env::var("DAY_APP_VERSION")
301 && !v.is_empty()
302 {
303 parts.push(v);
304 }
305 parts.push(toolkit.to_string());
306 if let Ok(s) = std::env::var("DAY_SCRIPT")
307 && !s.is_empty()
308 {
309 parts.push(s);
310 }
311 Some(format!("({})", parts.join("/")))
312}
313
314/// Append [`debug_title_tag`] to a window title. Every title day sets goes through here: the
315/// primary window's, each secondary window's, and every [`crate::windows::WindowHandle::set_title`].
316///
317/// An empty title stays empty: a window the app left untitled should not grow a title bar full
318/// of build metadata. An already-tagged title is left alone, since the same window can be
319/// retitled repeatedly.
320pub(crate) fn decorate_window_title(title: &str) -> String {
321 tag_title(title, debug_title_tag().as_deref())
322}
323
324/// The join rule, split out from the environment so it can be tested.
325fn tag_title(title: &str, tag: Option<&str>) -> String {
326 match tag {
327 Some(tag) if !title.is_empty() && !title.ends_with(tag) => format!("{title} {tag}"),
328 _ => title.to_string(),
329 }
330}
331
332#[cfg(test)]
333mod title_tag_tests {
334 use super::tag_title;
335
336 #[test]
337 fn the_tag_is_appended_once_and_never_to_an_empty_title() {
338 assert_eq!(
339 tag_title("Day Sheets", Some("(0.1.0/appkit)")),
340 "Day Sheets (0.1.0/appkit)"
341 );
342 // A release build has no tag, so the title is the app's own, untouched.
343 assert_eq!(tag_title("Day Sheets", None), "Day Sheets");
344 // An untitled window stays untitled rather than growing a bar of build metadata.
345 assert_eq!(tag_title("", Some("(0.1.0/appkit)")), "");
346 // Retitling an already-tagged window must not stack tags.
347 assert_eq!(
348 tag_title("Day Sheets (0.1.0/appkit)", Some("(0.1.0/appkit)")),
349 "Day Sheets (0.1.0/appkit)"
350 );
351 }
352}
353
354// ---- logging (docs/logging.md) ---------------------------------------------------------------
355
356/// Where a formatted line goes. Unset means the process's own stderr, which is right on every
357/// native target: a terminal on the desktop, Xcode's console on Apple, and logcat on Android
358/// (day-toolkit-material `dup2`s fd 2 into it). `wasm32-unknown-unknown` is the one target where that is
359/// wrong rather than merely different (std's stdio there accepts the bytes and drops them, so
360/// every line vanishes), and day-toolkit-dom installs a sink reaching the browser console instead.
361static LOG_SINK: std::sync::OnceLock<fn(log::Level, &str)> = std::sync::OnceLock::new();
362
363/// Install the line sink. First registration wins (one host per process). Called before launch;
364/// `day::web::start` does it for the browser.
365pub fn set_log_sink(f: fn(log::Level, &str)) {
366 let _ = LOG_SINK.set(f);
367}
368
369/// The width the level column is padded to. Shared by the formatter and the coloring below, which
370/// splits the finished line at exactly this offset.
371const LEVEL_WIDTH: usize = 5;
372
373/// The terminal color for a level: `env_logger`'s palette, so a Day app's output reads like any
374/// other Rust app's, and the same one `day-cli` uses when it re-emits these lines under
375/// `day launch` (day-cli `src/term.rs`).
376#[cfg(not(target_arch = "wasm32"))]
377fn level_style(level: log::Level) -> anstyle::Style {
378 let color = match level {
379 log::Level::Error => anstyle::AnsiColor::Red,
380 log::Level::Warn => anstyle::AnsiColor::Yellow,
381 log::Level::Info => anstyle::AnsiColor::Green,
382 log::Level::Debug => anstyle::AnsiColor::Blue,
383 log::Level::Trace => anstyle::AnsiColor::Cyan,
384 };
385 anstyle::Style::new().fg_color(Some(anstyle::Color::Ansi(color)))
386}
387
388/// Write one already-formatted line to stderr, never panicking. That matters because the
389/// `*println!` macros panic on a failed write, a closed stderr pipe is routine when `day launch`
390/// tears the app down, and a panic raised inside a native trampoline aborts the process.
391///
392/// Only the level column is colored: a fully colored line is noise at `INFO`, and leaving the
393/// message plain keeps it greppable. `anstream` decides whether the escapes survive: they are
394/// stripped when stderr is not a color terminal, which covers the pipe `day launch` gives us
395/// (day-cli re-colors from its own end), logcat, Xcode's console, `NO_COLOR`, and `TERM=dumb`.
396#[cfg(not(target_arch = "wasm32"))]
397fn write_line(level: log::Level, line: &str) {
398 use std::io::Write as _;
399 let style = level_style(level);
400 // The column is ASCII and padded to `LEVEL_WIDTH` by the caller, so this never lands inside a
401 // character; `split_at_checked` keeps even a malformed line from panicking.
402 let (lvl, rest) = line.split_at_checked(LEVEL_WIDTH).unwrap_or((line, ""));
403 let _ = writeln!(anstream::stderr(), "{style}{lvl}{style:#}{rest}");
404}
405
406/// The wasm fallback, used only if no sink was installed; `day::web::start` installs one before
407/// an app's first line. std's stdio on `wasm32-unknown-unknown` accepts these bytes and drops
408/// them, so this writes into nothing; it exists so the logger has a total function.
409#[cfg(target_arch = "wasm32")]
410fn write_line(_level: log::Level, line: &str) {
411 use std::io::Write as _;
412 let _ = writeln!(std::io::stderr(), "{line}");
413}
414
415/// Day's default [`log::Log`].
416///
417/// Not `env_logger` or another off-the-shelf backend, for the reason above: they print through
418/// `*println!`, and a panic on that path is an abort rather than a lost line. An app that wants
419/// one installs it itself; see [`init_logging`].
420struct DayLogger;
421
422impl log::Log for DayLogger {
423 fn enabled(&self, metadata: &log::Metadata<'_>) -> bool {
424 // The level filter is `log::set_max_level`'s job, checked by the macros before they even
425 // format; answering `true` here keeps `log_enabled!` consistent with them for anything
426 // that asks.
427 metadata.level() <= log::max_level()
428 }
429
430 fn log(&self, record: &log::Record<'_>) {
431 if !self.enabled(record.metadata()) {
432 return;
433 }
434 // `WARN day_toolkit_gtk: could not register bundled font …`: the level first so a scan down
435 // the column finds problems, then the emitting crate, which is what says which backend
436 // or piece is unhappy. The old hand-written `day: ` prefixes said only that it was us.
437 let sink = LOG_SINK.get();
438 // Formatted plain: a sink is a structured destination (the browser console, a test
439 // collector, an app's own transport) and wants the text, not terminal escapes. Color is
440 // `write_line`'s business, applied only on the way to a real stderr.
441 let line = format!(
442 "{:<LEVEL_WIDTH$} {}: {}",
443 record.level(),
444 record.target(),
445 record.args()
446 );
447 match sink {
448 Some(f) => f(record.level(), &line),
449 None => write_line(record.level(), &line),
450 }
451 }
452
453 fn flush(&self) {}
454}
455
456/// Install Day's default logger and level, unless the app already installed its own.
457///
458/// Called from [`launch_with`], so logging works with no ceremony at all: an app writes
459/// `log::info!(…)` (or `day::info!`, the same macro re-exported through the prelude) and the line
460/// comes out on every platform. `set_logger` answers `Err` when a logger is already registered;
461/// that is all the customization there is, and why the error is ignored: an app that
462/// called `env_logger::init()` (or installed `tracing`, or its own `log::Log`) before
463/// `day::launch` keeps it, and Day does not fight for the slot.
464///
465/// The default level is `Debug` in a debug build and `Info` in a release one; `DAY_LOG` overrides
466/// it with a level name (`off`/`error`/`warn`/`info`/`debug`/`trace`). Reading an environment
467/// variable is a native-only affordance; on the web there is no process environment, so the
468/// launch path sets the level explicitly from the page's query string instead.
469pub fn init_logging() {
470 let from_env = std::env::var("DAY_LOG")
471 .ok()
472 .and_then(|v| v.parse::<log::LevelFilter>().ok());
473 match from_env {
474 Some(level) => set_log_level(level),
475 // A level the launch path chose before this ran (the web's `?DAY_LOG=`) stands; only an
476 // unset level takes the build's default.
477 None if LOG_LEVEL_SET.load(std::sync::atomic::Ordering::Relaxed) => {}
478 None => set_log_level(if cfg!(debug_assertions) {
479 log::LevelFilter::Debug
480 } else {
481 log::LevelFilter::Info
482 }),
483 }
484 // Err = the app got there first, which is exactly the intended escape hatch.
485 let _ = log::set_logger(&DayLogger);
486}
487
488/// Whether [`set_log_level`] has run, so [`init_logging`] does not undo a level chosen before
489/// launch.
490static LOG_LEVEL_SET: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
491
492/// Set the maximum level that will be emitted. Separate from [`init_logging`] because the web
493/// launch path has to supply the level from the page URL rather than the environment, and because
494/// an app may want to raise or lower it at runtime.
495pub fn set_log_level(level: log::LevelFilter) {
496 LOG_LEVEL_SET.store(true, std::sync::atomic::Ordering::Relaxed);
497 log::set_max_level(level);
498}
499
500/// Run a posted main-thread task, containing any panic (the `pump_events` twin for the poster /
501/// scheduler doors): log the cause and reset the reactive runtime so the app keeps running
502/// (degraded) instead of aborting across the native trampoline's non-unwind boundary.
503pub(crate) fn contain_posted_panic(f: Box<dyn FnOnce() + Send>) {
504 if let Err(payload) = std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)) {
505 let msg = payload
506 .downcast_ref::<&str>()
507 .map(|s| (*s).to_string())
508 .or_else(|| payload.downcast_ref::<String>().cloned())
509 .unwrap_or_else(|| "unknown panic".to_string());
510 log::warn!(
511 "a posted main-thread task panicked and was contained — the app continues, but \
512 reactive/UI state may be inconsistent until the next interaction. Cause: {msg}"
513 );
514 day_reactive::recover_from_panic();
515 notify_contained_panic();
516 }
517}
518
519/// The app's undo/redo entry point as the platform front calls it; `true` means redo.
520/// `Rc` because the invocation clones it out of the cell before running, so the borrow is
521/// released before app code (which may install a new bridge) gets control.
522type UndoInvoke = std::rc::Rc<dyn Fn(bool)>;
523
524/// Wire an undo history to the platform (docs/model.md): the four signals mirror into the
525/// toolkit's native front where one exists (`Cap::UndoBridge`: the stock Edit menu retitles
526/// and enables itself, the platform's gestures land), and every invocation the platform
527/// delivers comes back through `on_invoke(redo)`. On a toolkit without a native undo system
528/// the state goes nowhere and the app's own affordances call the stack directly; installing
529/// the bridge is still harmless. Call once, after launch; installing again replaces the wiring.
530pub fn install_undo_bridge(
531 can_undo: day_reactive::Signal<bool>,
532 can_redo: day_reactive::Signal<bool>,
533 undo_label: day_reactive::Signal<String>,
534 redo_label: day_reactive::Signal<String>,
535 on_invoke: impl Fn(bool) + 'static,
536) {
537 UNDO_INVOKE.with(|u| *u.borrow_mut() = Some(std::rc::Rc::new(on_invoke)));
538 day_reactive::bind(
539 move || day_spec::UndoState {
540 can_undo: can_undo.get(),
541 can_redo: can_redo.get(),
542 undo_label: undo_label.get(),
543 redo_label: redo_label.get(),
544 },
545 |state: &day_spec::UndoState| {
546 let state = state.clone();
547 with_tree(|t| t.set_undo_state(&state));
548 },
549 );
550}
551
552/// The standing dispatch id behind a `MenuRole::Cut`/`Copy`/`Paste` item on a toolkit whose
553/// role items come back as plain menu actions (docs/menus.md): the closure invokes the
554/// installed edit bridge. Durable across menu installs, like the undo pair.
555#[must_use]
556pub fn edit_action_id(op: day_spec::EditOp) -> u64 {
557 use day_spec::EditOp as E;
558 let (c, y, p, a) = EDIT_ACTION_IDS.with(std::cell::Cell::get);
559 let have = match op {
560 E::Cut => c,
561 E::Copy => y,
562 E::Paste => p,
563 E::SelectAll => a,
564 };
565 if have != 0 {
566 return have;
567 }
568 let id = menu::register_menu_action(std::rc::Rc::new(move || dispatch_edit_invoke(op)));
569 EDIT_ACTION_IDS.with(|s| {
570 let (c0, y0, p0, a0) = s.get();
571 s.set(match op {
572 E::Cut => (id, y0, p0, a0),
573 E::Copy => (c0, id, p0, a0),
574 E::Paste => (c0, y0, id, a0),
575 E::SelectAll => (c0, y0, p0, id),
576 });
577 });
578 id
579}
580
581fn dispatch_undo_invoke(redo: bool) {
582 let _ = invoke_undo(redo);
583}
584
585/// Invoke the installed undo bridge (the same handler a native front reaches: ⌘Z, the Edit
586/// menu, a three-finger swipe), returning whether one is installed. The dayscript
587/// `undo:`/`redo:` steps drive history through this, so a walkthrough needs no app-provided
588/// undo button on any target.
589#[must_use]
590pub fn invoke_undo(redo: bool) -> bool {
591 let f = UNDO_INVOKE.with(|u| u.borrow().clone());
592 match f {
593 Some(f) => {
594 day_reactive::batch(|| f(redo));
595 true
596 }
597 None => false,
598 }
599}
600
601type EditInvoke = std::rc::Rc<dyn Fn(day_spec::EditOp)>;
602
603/// The keyboard modifiers held right now, for interactions whose meaning they change
604/// (shift-click adds to a selection). Touch backends answer all-false; a dayscript step's
605/// declared modifiers take precedence while it dispatches.
606#[must_use]
607pub fn modifiers() -> day_spec::Modifiers {
608 if let Some(m) = MODIFIER_OVERRIDE.with(std::cell::Cell::get) {
609 return m;
610 }
611 with_tree(|t| t.modifiers())
612}
613
614/// Scoped modifier stand-in for the dayscript executor: `Some` while a step with declared
615/// modifiers dispatches, back to `None` after.
616pub fn set_modifier_override(m: Option<day_spec::Modifiers>) {
617 MODIFIER_OVERRIDE.with(|o| o.set(m));
618}
619
620/// Wire the app's standard-edit handlers to the platform (docs/menus.md): `state` is a
621/// tracked read whose value mirrors into the toolkit (`Cap::EditBridge`: native menu
622/// validation enables the stock Cut/Copy/Paste exactly as it does for text widgets), and
623/// every invocation a platform route delivers comes back through `on_invoke`. On a toolkit
624/// with no native route, the `menu_role(Cut/Copy/Paste)` items dispatch here instead (the
625/// same standing-id fallback the undo pair uses). Call once, after launch; installing again
626/// replaces the wiring. Most apps want [`day::install_edit_commands`](/api/day/fn.install_edit_commands.html), which adds the
627/// clipboard transport.
628pub fn install_edit_bridge(
629 state: impl Fn() -> day_spec::EditState + 'static,
630 on_invoke: impl Fn(day_spec::EditOp) + 'static,
631) {
632 EDIT_INVOKE.with(|u| *u.borrow_mut() = Some(std::rc::Rc::new(on_invoke)));
633 day_reactive::bind(state, |state: &day_spec::EditState| {
634 let state = *state;
635 with_tree(|t| t.set_edit_state(&state));
636 });
637}
638
639fn dispatch_edit_invoke(op: day_spec::EditOp) {
640 let _ = invoke_edit(op);
641}
642
643/// Invoke the installed edit bridge (the same handler the platform's Cut/Copy/Paste
644/// route reaches, clipboard transport included), returning whether one is installed. An
645/// app's own affordances (a context menu's Cut/Copy) call this rather than duplicating the
646/// clipboard plumbing (docs/menus.md).
647#[must_use]
648pub fn invoke_edit(op: day_spec::EditOp) -> bool {
649 let f = EDIT_INVOKE.with(|u| u.borrow().clone());
650 match f {
651 Some(f) => {
652 day_reactive::batch(|| f(op));
653 true
654 }
655 None => false,
656 }
657}
658
659/// The standing dispatch id behind a `MenuRole::Undo`/`Redo` item on a toolkit with no native
660/// undo responder (docs/menus.md): activating the item comes back as a plain menu action, and
661/// this id's closure invokes the installed undo bridge. Registered once and durable across
662/// menu installs, like the preferences id. Toolkits with a native undo system (appkit) keep
663/// their responder-chain selector instead, so a focused text field's own undo stays ahead of
664/// the app stack there.
665#[must_use]
666pub fn undo_action_id(redo: bool) -> u64 {
667 let (u, r) = UNDO_ACTION_IDS.with(std::cell::Cell::get);
668 let have = if redo { r } else { u };
669 if have != 0 {
670 return have;
671 }
672 let id = menu::register_menu_action(std::rc::Rc::new(move || dispatch_undo_invoke(redo)));
673 UNDO_ACTION_IDS.with(|c| {
674 let (u0, r0) = c.get();
675 c.set(if redo { (u0, id) } else { (id, r0) });
676 });
677 id
678}
679
680/// A runtime route request from the backend (`Event::RouteRequested`: web-dom's URL hash
681/// changing via browser back/forward or a hand-edited hash). Echoes of our own `set_route`
682/// match the current route and are dropped.
683fn handle_route_request(route: &str) {
684 nav::apply_route_request(route);
685}
686
687/// Launch a Day app on the given platform backend: sets up the reactive scheduler and the
688/// cross-thread poster, mounts the root piece into the window's content container, runs the
689/// initial layout, and installs the turn-end layout callback (§3.3). The backend then owns
690/// the native main loop.
691pub fn launch_with<P: Platform>(
692 backend: P,
693 mut options: WindowOptions,
694 root_piece: impl FnOnce() -> AnyPiece + 'static,
695) {
696 // Before anything else that might want to report: from here on `log::warn!` and friends come
697 // out, on every backend, with no app-side setup. An app that installed its own logger first
698 // keeps it (docs/logging.md).
699 init_logging();
700 // Record the backend identity for runtime introspection (crash reports, diagnostics).
701 let _ = BACKEND_NAME.set(P::TARGET);
702 let _ = TOOLKIT_KEY.set(P::TOOLKIT);
703 // Tag the window title with version/toolkit/script in debug builds. Pin the app's display
704 // name to the undecorated title first: backends fall back to `title` for the macOS App menu
705 // and the About panel, which must keep reading "Day Sheets", not "Day Sheets (0.1.0/appkit)".
706 if options.app_name.is_none() && !options.title.is_empty() {
707 options.app_name = Some(options.title.clone());
708 }
709 options.title = decorate_window_title(&options.title);
710 // `DAY_WINDOW=900x700` overrides the app's initial window size, for responsive-layout testing
711 // (scripted runs can exercise a narrow window without a resize gesture). Desktop only in
712 // effect; mobile/web backends size to the screen and ignore `options.size` anyway.
713 if let Ok(v) = std::env::var("DAY_WINDOW")
714 && let Some((w, h)) = v.split_once('x')
715 && let (Ok(w), Ok(h)) = (w.trim().parse::<f64>(), h.trim().parse::<f64>())
716 && w > 0.0
717 && h > 0.0
718 {
719 options.size = day_spec::Size::new(w, h);
720 }
721 // Remember what the app asked for, so File ▸ New Window can open another window of the same
722 // app rather than an untitled one the platform cannot list (docs/windows.md).
723 windows::set_launch_options(&options);
724 // Reactive plumbing rides the platform's main-loop poster. Both doors contain panics (the
725 // `pump_events` rationale, tree.rs): posted closures run inside native main-loop trampolines
726 // (a glib idle, a GCD block) that abort the process on unwind (`panic_cannot_unwind`), so a
727 // panic in a `Setter` write's drain or a scheduled `flush_sync` would SIGABRT the app instead
728 // of surfacing. Contain at this single backend-agnostic boundary and reset the runtime.
729 // Backend FFI trampolines (JNI up-calls, C callbacks, posted closures) contain panics
730 // through day-spec's `ffi_guard`; hand it the recovery hook here (the one layer that
731 // knows day-reactive) so a contained panic can't strand the observer stack or leave a
732 // half-open batch behind. Each door also defers its closure when the tree is borrowed
733 // (`tree::run_posted_or_defer`): a backend pumping its native loop from inside a tree
734 // method would otherwise run the closure on the borrowed tree.
735 day_spec::ffi_guard::set_recovery(day_reactive::recover_from_panic);
736 day_reactive::install_main_poster(|f| {
737 P::post(Box::new(move || tree::run_posted_or_defer(f)));
738 });
739 // The timer door (docs/async.md `day::sleep`): same containment and deferral as the poster.
740 day_reactive::install_delayed_poster(|ms, f| {
741 P::post_delayed(ms, Box::new(move || tree::run_posted_or_defer(f)));
742 });
743 day_reactive::install_scheduler(|| {
744 P::post(Box::new(|| {
745 tree::run_posted_or_defer(Box::new(day_reactive::flush_sync));
746 }));
747 });
748 // The async-spawn door (docs/async.md): day-reactive's `Resource` runs its fetch futures on
749 // this executor; the returned closure aborts (a no-op once the task completed, the contract
750 // Resource's eager-poll ordering relies on).
751 day_reactive::install_spawner(|fut| {
752 let handle = present::task(fut);
753 Box::new(move || handle.abort())
754 });
755 // The frame clock (§8.4): the animation driver re-arms the platform's vsync callback while any
756 // frame consumer (game loop / self-driven animation) is live.
757 frame::install_frame_requester(|root, cb| tree::with_tree(|t| t.request_frame(root, cb)));
758
759 // What the exit line names (docs/lifecycle.md), and when the clock started; and the exit
760 // itself, for a loop that ends the process without returning.
761 #[cfg(not(target_arch = "wasm32"))]
762 if toolkit_key() != Some("mock") {
763 deliver_exit_at_process_exit();
764 }
765 lifecycle::note_launch(
766 options.app_name.clone().unwrap_or_default(),
767 options.version.clone(),
768 );
769
770 // WillLaunch: before the window/UI exists (docs/lifecycle.md). Fired uniformly by day-core so
771 // it is reliable on every backend; handlers must not touch the tree (there isn't one yet).
772 lifecycle::dispatch_lifecycle(day_spec::Lifecycle::WillLaunch);
773
774 P::run(
775 backend,
776 options,
777 Box::new(move |mut toolkit, root_handle, size| {
778 day_spec::Toolkit::set_event_sink(&mut toolkit, Box::new(tree::enqueue_native_event));
779 let tree = Tree::new(toolkit, root_handle, size);
780 let root = tree.root();
781 tree::install_tree(Box::new(tree));
782 // The launch read of the user's motion setting (docs/accessibility.md), before the
783 // root piece builds: its first transitions already land where the user asked.
784 note_motion_changed();
785
786 // Seed the window's size class from the size the backend just reported
787 // (docs/size-classes.md), before the root piece builds below: a nav host resolving
788 // an automatic presentation reads it during its own build. Backends push later
789 // changes themselves; one that never does keeps this launch value.
790 ambient::set_window_size_class(
791 root,
792 day_spec::SizeClass::from_size(size.width, size.height),
793 );
794
795 // The backend is now known: warn about any lifecycle handlers already registered for
796 // phases this platform doesn't deliver (docs/lifecycle.md).
797 lifecycle::warn_unsupported_registrations();
798
799 // Window resize → relayout. Route requests (runtime deep links: web-dom's URL
800 // hash changing under the app via browser back/forward or a hand-edited hash) →
801 // navigate, guarded against echo: the request the backend reflects back after
802 // our own `set_route` matches the current route and is dropped here.
803 with_tree(|t| {
804 let rn = root;
805 t.on_event(
806 rn,
807 std::rc::Rc::new(move |ev| match ev {
808 day_spec::Event::WindowResized(size) => {
809 let s = *size;
810 with_tree(|t| t.set_window_size(s));
811 // Re-bucket the window (docs/size-classes.md). Derived here, from the
812 // geometry every backend already reports, so there is one breakpoint
813 // table rather than one per toolkit, and only a class change
814 // notifies, so dragging an edge within a bucket costs nothing. A
815 // shrink the backend noted as the soft keyboard's keeps the class.
816 ambient::set_window_size_class(rn, ambient::resized_size_class(rn, s));
817 }
818 day_spec::Event::RouteRequested(route) => handle_route_request(route),
819 // A native undo front's invocation (⌘Z through the stock Edit menu, a
820 // three-finger swipe): route to whatever stack the app installed.
821 day_spec::Event::Undo { redo } => dispatch_undo_invoke(*redo),
822 // A platform edit-command route (Edit ▸ Cut/Copy/Paste, the
823 // browser's clipboard events) with no text widget claiming it.
824 day_spec::Event::Edit(op) => dispatch_edit_invoke(*op),
825 _ => {}
826 }),
827 );
828 });
829
830 // The first window is an ordinary primary window (docs/windows.md close policy):
831 // it goes in the registry like any other, so closing it runs the same teardown and
832 // the same "was that the last primary?" question. Its content builds in a child of
833 // the root scope; disposing that on close takes this window's tree and nothing
834 // else, while `Signal::global` state stays on the root scope above it.
835 let win_scope = day_reactive::Scope::root().enter(day_reactive::Scope::child);
836 windows::adopt_initial_window(root, win_scope);
837
838 // Build the root piece under the window container.
839 let piece = root_piece();
840 win_scope.enter(|| {
841 let mut cx = BuildCx::new(root);
842 let _ = piece.build(&mut cx);
843 });
844
845 // Initial layout, then keep laying out at every turn boundary.
846 with_tree(|t| {
847 t.mark_layout_dirty();
848 t.layout_if_needed();
849 });
850 day_reactive::on_turn_end(|| with_tree(|t| t.layout_if_needed()));
851 // The Dock menu lists the app's launcher shortcuts from the start (docs/menus.md),
852 // ahead of whatever `dock_menu(..)` the root just installed.
853 menu::install_dock_menu();
854 // A keep-running policy or a status item set before the tree existed reaches the
855 // backend now (docs/windows.md "Keeping the app running").
856 status::boot_sync();
857
858 #[cfg(not(any(
859 target_arch = "wasm32",
860 target_os = "ios",
861 target_os = "android",
862 target_env = "ohos"
863 )))]
864 documents::request_open_files(documents::take_launch_files());
865 day_reactive::on_main(documents::drain_open_files);
866 if let Ok(url) = std::env::var("DAY_OPEN_URL") {
867 urls::request_open_url(&url);
868 }
869 day_reactive::on_main(urls::drain);
870 nav::install_route_notifier();
871
872 // DidLaunch: the UI is mounted and laid out, the app is about to run (docs/lifecycle.md).
873 lifecycle::dispatch_lifecycle(day_spec::Lifecycle::DidLaunch);
874
875 // Startup deep link (docs/navigation.md): uniform across platforms; desktop
876 // sets `DAY_DEEPLINK` directly, mobile shells forward the launch URL/intent into
877 // it, and web-dom (no process environment) records the URL hash via
878 // `set_launch_deeplink`. Deferred one turn so the first frame mounts before the
879 // destination pushes. The turn-end route sync (`Toolkit::set_route` on change;
880 // web-dom mirrors it into the URL hash) installs in the same deferred closure,
881 // after the deep link resolves, so the launch route is never clobbered by a sync
882 // of the pre-navigation state.
883 day_reactive::on_main(move || {
884 if let Some(route) = nav::launch_deeplink()
885 && !nav::navigate(&route)
886 {
887 log::warn!("launch deep link {route:?} did not match a route");
888 }
889 // Consume the `request_route` buffer the line above may have read: a tap that
890 // cold-started the process has now been applied, and leaving it set would
891 // re-navigate on the next request.
892 let _ = nav::take_requested_route();
893 // First reflection runs eagerly: a launch with no deep link ends no turn.
894 let route = nav::current_route().unwrap_or_default();
895 with_tree(|t| t.set_route(&route));
896 let last = std::cell::RefCell::new(Some(route));
897 day_reactive::on_turn_end(move || {
898 let route = nav::current_route().unwrap_or_default();
899 if last.borrow().as_deref() != Some(route.as_str()) {
900 *last.borrow_mut() = Some(route.clone());
901 with_tree(|t| t.set_route(&route));
902 }
903 });
904 });
905
906 // Verification hook (headless CI / no-input environments): drive the app through
907 // Day's own event path once the native loop starts (delayed past first allocation
908 // so snapshots see a laid-out window). Precursor of dayscript (§14).
909 if let Ok(spec) = std::env::var("DAY_AUTODRIVE") {
910 day_reactive::on_main_delayed(800, move || autodrive(&spec));
911 }
912 }),
913 );
914 // DidExit: the native loop returned, which is the last thing the app runs on the desktop
915 // backends whose loop returns (GTK, Qt, XAML). The backends whose process ends inside the
916 // loop (AppKit's terminate exits) emit it themselves, after WillTerminate, and
917 // `dispatch_lifecycle` delivers it once whichever comes first. Where the host owns the
918 // loop and `run` hands back at once with the app still to come (ArkUI, Android, the web,
919 // the mock's test), the return is no exit at all: DidExit there is the host's own last
920 // callback, and delivering it here would run the exit handlers at launch and leave the
921 // real exit undelivered (`RUN_ENDS_APP`, docs/lifecycle.md).
922 if P::RUN_ENDS_APP {
923 lifecycle::dispatch_lifecycle(day_spec::Lifecycle::DidExit);
924 }
925}
926
927/// Deliver `DidExit` from the C runtime's exit, for the loop that never returns: Qt's macOS
928/// Quit menu item ends the process through `exit()` from inside `exec()`, and any backend or
929/// app that calls `std::process::exit` does the same. `atexit` runs on the exiting thread,
930/// the main one for every such path, with the thread-locals still alive; delivery is once, so
931/// a loop that did return costs nothing here. Registered by `launch_with` on every backend but
932/// the mock and wasm, which have no process exit of their own.
933#[cfg(not(target_arch = "wasm32"))]
934fn deliver_exit_at_process_exit() {
935 unsafe extern "C" {
936 fn atexit(f: extern "C" fn()) -> i32;
937 }
938 extern "C" fn at_exit() {
939 lifecycle::dispatch_lifecycle(day_spec::Lifecycle::DidExit);
940 }
941 // SAFETY: `atexit` takes a plain C function pointer and keeps it for the process's life.
942 unsafe {
943 atexit(at_exit);
944 }
945}
946
947/// `DAY_AUTODRIVE="<id>:press;<id>:text:Ada;<id>:value:80;<id>:toggle:true;<id>:tap;
948/// <id>:drag:40:60;shot:/tmp/x.png"`: synthesized Day events by element id, plus snapshots.
949fn autodrive(spec: &str) {
950 use day_spec::{DragPhase, Event, Point};
951 for step in spec.split(';').filter(|s| !s.is_empty()) {
952 let parts: Vec<&str> = step.splitn(3, ':').collect();
953 if parts[0] == "shot" {
954 let path = parts[1..].join(":");
955 let png = with_tree(|t| t.snapshot());
956 match png {
957 Ok(bytes) => {
958 let _ = std::fs::write(&path, bytes);
959 }
960 Err(e) => log::warn!("day autodrive: snapshot failed: {e}"),
961 }
962 continue;
963 }
964 let node = with_tree(|t| t.find_by_id(parts[0]));
965 let Some(node) = node else {
966 log::warn!("day autodrive: id {:?} not found", parts[0]);
967 continue;
968 };
969 // Gesture drivers (docs/shapes.md): tap fires at the node's local center; drag runs a
970 // Began→Changed→Ended sequence translated by dx,dy, exercising `.on_tap`/`.on_drag`
971 // hit-testing through Day's event path (the native recognizers deliver the same events).
972 if parts.get(1) == Some(&"tap") {
973 if let Some(f) = with_tree(|t| t.node_frame(node)) {
974 let c = Point::new(f.size.width / 2.0, f.size.height / 2.0);
975 tree::enqueue_event(tree::rnode_to_id(node), Event::Tap(c));
976 }
977 continue;
978 }
979 if parts.get(1) == Some(&"drag") {
980 if let Some(f) = with_tree(|t| t.node_frame(node)) {
981 let c = Point::new(f.size.width / 2.0, f.size.height / 2.0);
982 let (dx, dy) = parts
983 .get(2)
984 .and_then(|s| s.split_once(':'))
985 .and_then(|(a, b)| Some((a.parse::<f64>().ok()?, b.parse::<f64>().ok()?)))
986 .unwrap_or((0.0, 0.0));
987 let end = Point::new(c.x + dx, c.y + dy);
988 let id = tree::rnode_to_id(node);
989 tree::enqueue_event(
990 id,
991 Event::Drag {
992 phase: DragPhase::Began,
993 location: c,
994 translation: Point::ZERO,
995 },
996 );
997 tree::enqueue_event(
998 id,
999 Event::Drag {
1000 phase: DragPhase::Changed,
1001 location: end,
1002 translation: Point::new(dx, dy),
1003 },
1004 );
1005 tree::enqueue_event(
1006 id,
1007 Event::Drag {
1008 phase: DragPhase::Ended,
1009 location: end,
1010 translation: Point::new(dx, dy),
1011 },
1012 );
1013 }
1014 continue;
1015 }
1016 if let (Some("text"), Some(v)) = (parts.get(1).copied(), parts.get(2).copied()) {
1017 synthesize_text(node, v.to_string());
1018 continue;
1019 }
1020 let ev = match (parts.get(1).copied(), parts.get(2).copied()) {
1021 (Some("press"), _) => Event::Pressed,
1022 (Some("toggle"), Some(v)) => Event::ToggleChanged(v == "true"),
1023 (Some("value"), Some(v)) => Event::ValueChanged(v.parse().unwrap_or(0.0)),
1024 (Some("select"), Some(v)) => Event::SelectionChanged(v.parse().unwrap_or(-1)),
1025 _ => continue,
1026 };
1027 tree::enqueue_event(tree::rnode_to_id(node), ev);
1028 }
1029}
1030
1031/// Whether the platform is rendering in dark appearance (see `Toolkit::dark_mode`): the
1032/// branch apps take when painting custom opaque surfaces so fills track the theme that the
1033/// default text colors already follow.
1034#[must_use]
1035pub fn dark_mode() -> bool {
1036 dark_signal().get()
1037}
1038
1039/// Resolve an app-wide semantic color, tracking appearance changes. Pass a closure to a
1040/// reactive modifier: `.fill(|| day::system_color(SystemColor::Accent))`.
1041/// A direct call returns a snapshot. Per-window overrides and local control tints are not
1042/// represented. See the styling guide for native mappings and fallback toolkits.
1043pub fn system_color(role: day_spec::SystemColor) -> day_spec::Color {
1044 PALETTE_SIGNAL.with(|cell| {
1045 let signal = cell.get_or_init(|| {
1046 let colors = read_system_palette();
1047 day_reactive::Scope::detached().enter(|| day_reactive::Signal::new(colors))
1048 });
1049 signal.get()[role as usize]
1050 })
1051}
1052
1053fn read_system_palette() -> [day_spec::Color; 5] {
1054 tree::try_with_tree(|t| day_spec::SystemColor::ALL.map(|role| t.system_color(role)))
1055 .unwrap_or_else(|| day_spec::SystemColor::ALL.map(|role| role.fallback(false)))
1056}
1057
1058/// The platform's font families with their faces (docs/fonts.md), enumerated once per
1059/// process through `Toolkit::font_families` and cached: the answer is stable for the process
1060/// (bundled fonts register before the tree exists, and nothing tracks a system font install
1061/// under a running app; the OS font panels cache too), enumeration is expensive, and the
1062/// query is synchronous on the UI thread. Sorted case-insensitively by family, deduplicated,
1063/// and unioned with the bundled fonts (`day_spec::fonts::bundled_fonts`) the toolkit's own
1064/// database did not report, which is how a `res/font/` (Android), `ms-appx` (XAML) or
1065/// `registerFont` (HarmonyOS) family reaches a font menu without each shim parsing sfnt.
1066/// Empty where the toolkit answers `Cap::FontList` = `Unsupported`.
1067#[must_use]
1068pub fn font_families() -> std::rc::Rc<[day_spec::FontFamilyInfo]> {
1069 // Headless (no tree on this thread, i.e. a model unit test): nothing to enumerate, and
1070 // nothing to cache, so the first call with a tree still fills the cache.
1071 if !tree::has_tree() {
1072 return std::rc::Rc::from(Vec::new());
1073 }
1074 FONT_FAMILIES.with(|c| {
1075 c.get_or_init(|| {
1076 let mut list = tree::with_tree(|t| t.font_families());
1077 for path in day_spec::fonts::bundled_fonts() {
1078 let Some(names) = std::fs::read(&path)
1079 .ok()
1080 .and_then(|bytes| day_spec::fonts::parse_font_names(&bytes))
1081 else {
1082 continue;
1083 };
1084 if list
1085 .iter()
1086 .any(|f| f.family.eq_ignore_ascii_case(&names.family))
1087 {
1088 continue;
1089 }
1090 list.push(day_spec::FontFamilyInfo {
1091 family: names.family,
1092 faces: vec![day_spec::FontFace {
1093 name: "Regular".to_string(),
1094 weight: day_spec::FontWeight::Regular,
1095 italic: false,
1096 }],
1097 });
1098 }
1099 list.sort_by_key(|f| f.family.to_lowercase());
1100 list.dedup_by(|a, b| a.family.eq_ignore_ascii_case(&b.family));
1101 list.into()
1102 })
1103 .clone()
1104 })
1105}
1106
1107/// Distinct measurements held per generation. Two generations are live at once, so the cache
1108/// holds up to twice this before the older one is dropped whole.
1109///
1110/// 512 is far more than a drawing measures per frame (a chart with two axes, their titles and a
1111/// legend is around twenty) and small enough that the worst case (a text tool measuring a
1112/// different string every keystroke) costs tens of kilobytes rather than growing without end.
1113const TEXT_METRICS_CAP: usize = 512;
1114
1115/// The `measure_text` cache: a **pure** memo, because every backend's measurement is a function
1116/// of `(text, size, font)` and nothing else. Nothing in a running app changes the answer: canvas
1117/// text takes absolute points, so it carries neither the reader's font-scale setting nor the
1118/// window's scale factor (docs/canvas.md "Text"), which is what makes caching it correct rather
1119/// than merely fast.
1120///
1121/// Two generations rather than an LRU list: a hit in `previous` is promoted into `current`, and
1122/// when `current` fills, `previous` is replaced by it wholesale. That approximates least-recently-
1123/// used closely enough for a working set that repeats every frame, is O(1) amortized with no
1124/// eviction scan, and needs no ordering structure beside the maps.
1125struct TextMetricsCache {
1126 /// Reused so a hit allocates nothing at all: the key is rebuilt into this buffer, compared,
1127 /// and only copied into the map on a miss.
1128 key: String,
1129 current: std::collections::HashMap<String, day_spec::TextMetrics>,
1130 previous: std::collections::HashMap<String, day_spec::TextMetrics>,
1131 hits: u64,
1132 misses: u64,
1133}
1134
1135impl TextMetricsCache {
1136 fn new() -> Self {
1137 TextMetricsCache {
1138 key: String::new(),
1139 current: std::collections::HashMap::new(),
1140 previous: std::collections::HashMap::new(),
1141 hits: 0,
1142 misses: 0,
1143 }
1144 }
1145
1146 /// Write the key for one measurement into the scratch buffer.
1147 ///
1148 /// The family's length is written before the family, so the encoding is injective whatever a
1149 /// family name contains; the alternative, a separator, is only injective while no font is
1150 /// ever named with it in it. `size` goes in as its bit pattern: exact, and two sizes that
1151 /// differ only in representation would measure the same anyway.
1152 fn build_key(&mut self, text: &str, size: f64, font: &day_spec::CanvasFont) {
1153 use std::fmt::Write;
1154 let family = font.family_str();
1155 self.key.clear();
1156 let _ = write!(
1157 self.key,
1158 "{:x}:{}:{}:{}:{family}{text}",
1159 size.to_bits(),
1160 font.css_weight(),
1161 u8::from(font.italic),
1162 family.len(),
1163 );
1164 }
1165
1166 /// A hit promotes an older-generation entry into the current one, so a working set that
1167 /// survives a generation flip is not measured again.
1168 fn lookup(&mut self) -> Option<day_spec::TextMetrics> {
1169 if let Some(m) = self.current.get(&self.key) {
1170 self.hits += 1;
1171 return Some(*m);
1172 }
1173 let m = *self.previous.get(&self.key)?;
1174 self.hits += 1;
1175 self.current.insert(self.key.clone(), m);
1176 Some(m)
1177 }
1178
1179 fn insert(&mut self, m: day_spec::TextMetrics) {
1180 self.misses += 1;
1181 if self.current.len() >= TEXT_METRICS_CAP {
1182 self.previous = std::mem::take(&mut self.current);
1183 }
1184 self.current.insert(self.key.clone(), m);
1185 }
1186}
1187
1188/// What [`measure_text`]'s cache has done on this thread: a diagnostic, for an app that wants to
1189/// see whether its drawing is measuring the same strings over and over (it usually is).
1190#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1191pub struct TextMetricsCacheStats {
1192 /// Measurements answered without asking the toolkit.
1193 pub hits: u64,
1194 /// Measurements that had to cross into the toolkit.
1195 pub misses: u64,
1196 /// Distinct measurements currently held, across both generations.
1197 pub entries: usize,
1198}
1199
1200/// Read the [`measure_text`] cache's counters (docs/fonts.md).
1201#[must_use]
1202pub fn text_metrics_cache_stats() -> TextMetricsCacheStats {
1203 TEXT_METRICS.with(|c| {
1204 let c = c.borrow();
1205 TextMetricsCacheStats {
1206 hits: c.hits,
1207 misses: c.misses,
1208 entries: c.current.len() + c.previous.len(),
1209 }
1210 })
1211}
1212
1213/// Drop every cached measurement (the counters keep running).
1214///
1215/// Nothing in day needs this: a measurement is a pure function of its key, and the font set is
1216/// fixed for the process (see [`font_families`]). It exists for a toolkit or app that registers a
1217/// face at runtime and so does change what a family name measures to.
1218pub fn clear_text_metrics_cache() {
1219 TEXT_METRICS.with(|c| {
1220 let mut c = c.borrow_mut();
1221 c.current.clear();
1222 c.previous.clear();
1223 });
1224}
1225
1226/// Measure one line of canvas text at `size` points in `font` (docs/fonts.md), in the engine
1227/// that draws `DrawOp::Text`; a toolkit that cannot measure answers
1228/// `TextMetrics::approximate`, so a caller always gets a usable box.
1229///
1230/// **Memoized** (`TextMetricsCache`): measuring crosses into the toolkit and lays the text out
1231/// there (around 29 µs a call on AppKit, which builds an `NSString` and an attribute dictionary
1232/// every time), and a drawing measures the same handful of strings on every frame it records. A
1233/// repeat costs a hash of the key and nothing else.
1234pub fn measure_text(text: &str, size: f64, font: &day_spec::CanvasFont) -> day_spec::TextMetrics {
1235 if let Some(m) = TEXT_METRICS.with(|c| {
1236 let mut c = c.borrow_mut();
1237 c.build_key(text, size, font);
1238 c.lookup()
1239 }) {
1240 return m;
1241 }
1242 // The toolkit call happens with no borrow of the cache held: `replay` and a piece's own
1243 // measurement can reach back into day-core, and a borrow spanning the call would panic.
1244 // Headless (no tree on this thread) answers the approximation too, so a model unit test
1245 // that frames text runs without a toolkit.
1246 let Some(m) = tree::try_with_tree(|t| t.measure_text(text, size, font)).flatten() else {
1247 // Not cached. "The toolkit could not answer" is a fact about this moment (Android's
1248 // returns nothing until its VM is up), not about the text, and caching it would
1249 // pin a guess for the life of the process.
1250 return day_spec::TextMetrics::approximate(text, size);
1251 };
1252 TEXT_METRICS.with(|c| {
1253 let mut c = c.borrow_mut();
1254 c.build_key(text, size, font);
1255 c.insert(m);
1256 });
1257 m
1258}
1259
1260/// Whether motion should be reduced (docs/accessibility.md): the user's system setting
1261/// (`Toolkit::reduce_motion`), or a launch that forced it (`DAY_REDUCE_MOTION=1`, and
1262/// `day launch --fast`, whose fast mode is this setting forced on). Day already applies every
1263/// finite animation at its destination under it and keeps only indeterminate motion; this read
1264/// is for the motion an app drives itself, such as a `day::frame` simulation or a decorative
1265/// loop, which the app opts down. Reactive: a closure reading it re-runs when the setting flips.
1266#[must_use]
1267pub fn reduce_motion() -> bool {
1268 reduce_motion_signal().get()
1269}
1270
1271/// [`reduce_motion`] untracked and borrow-free, for the animation gates inside the tree.
1272#[must_use]
1273pub fn reduce_motion_now() -> bool {
1274 testing::forced_reduce_motion() || REDUCE_MOTION.with(std::cell::Cell::get)
1275}
1276
1277/// The reactive backing for [`reduce_motion`], seeded from the current answer.
1278fn reduce_motion_signal() -> day_reactive::Signal<bool> {
1279 REDUCE_MOTION_SIGNAL.with(|c| {
1280 *c.get_or_init(|| {
1281 let seed = reduce_motion_now();
1282 day_reactive::Scope::detached().enter(|| day_reactive::Signal::new(seed))
1283 })
1284 })
1285}
1286
1287/// Re-read the toolkit's reduce-motion setting into [`reduce_motion`]. Backends call this
1288/// when the user flips the setting under a running app; [`launch_with`] calls it once the tree
1289/// stands, which is the launch read. Like [`note_appearance_changed`], it may fire before the
1290/// tree is installed and then does nothing.
1291pub fn note_motion_changed() {
1292 if let Some(system) = tree::try_with_tree(|t| t.reduce_motion()) {
1293 REDUCE_MOTION.with(|c| c.set(system));
1294 let now = reduce_motion_now();
1295 REDUCE_MOTION_SIGNAL.with(|c| {
1296 if let Some(s) = c.get() {
1297 s.set(now);
1298 }
1299 });
1300 }
1301}
1302
1303/// The reactive backing for [`dark_mode`], lazily seeded from the toolkit's answer.
1304fn dark_signal() -> day_reactive::Signal<bool> {
1305 DARK_SIGNAL.with(|c| {
1306 *c.get_or_init(|| {
1307 let seed = tree::with_tree(|t| t.dark_mode());
1308 day_reactive::Scope::detached().enter(|| day_reactive::Signal::new(seed))
1309 })
1310 })
1311}
1312
1313/// Re-read the toolkit's appearance into the reactive [`dark_mode`] signal. Backends call
1314/// this when the system appearance changes under a running app (macOS theme switch, GTK
1315/// style-manager change), and [`set_appearance`] calls it after applying an override, so
1316/// closures reading `dark_mode()` recolor live instead of going stale until a rebuild.
1317pub fn note_appearance_changed() {
1318 // May fire before the tree is installed (GTK's StyleManager emits `dark` notifies while
1319 // `startup` applies a forced DAY_THEME scheme; AppKit's observer dispatches async): no
1320 // tree means no palette closures exist yet, and the signal seeds from the tree on first
1321 // use; skip rather than panic inside a native callback.
1322 if let Some(d) = tree::try_with_tree(|t| t.dark_mode()) {
1323 dark_signal().set(d);
1324 // A system accent can change without a light/dark transition.
1325 PALETTE_SIGNAL.with(|cell| {
1326 if let Some(signal) = cell.get() {
1327 signal.set(read_system_palette());
1328 }
1329 });
1330 }
1331}
1332
1333/// The system text size changed under a running app (iOS Dynamic Type, a desktop's text
1334/// scaling): every text measurement Day holds is stale. Backends call this from the platform's
1335/// notification, once the native text has taken the new size. Day re-measures every node and
1336/// re-lays every bound list row, so a content-sized row (docs/list.md "Row heights") takes its
1337/// new height through `ListPatch::RowSizeInvalidated`. Skipped when the tree is busy or not
1338/// installed yet: a tree built after the change measures at the new size anyway.
1339pub fn note_text_size_changed() {
1340 let _ = tree::try_with_tree(|t| {
1341 t.invalidate_all_measurements();
1342 t.layout_if_needed();
1343 });
1344}
1345
1346// The `.searchable()` hosts whose field is INLINE (docs/search.md), newest last: each has no
1347// `day::search` bar item, so a caller holding that reserved id (dayscript's `toolbar:` step)
1348// resolves it here and delivers `Event::SearchChanged` to the host, as the native field would.
1349/// Record `host` as showing an inline search field. Registered by the host's builder for the
1350/// life of its scope; see [`inline_search_host`].
1351pub fn register_search_host(host: RNode) {
1352 let window = toolbar::current_page_window();
1353 SEARCH_HOSTS.with(|h| {
1354 let mut h = h.borrow_mut();
1355 h.retain(|(_, node)| *node != host);
1356 h.push((window, host));
1357 });
1358}
1359
1360/// Forget `host`, once its scope is disposed.
1361pub fn unregister_search_host(host: RNode) {
1362 SEARCH_HOSTS.with(|h| h.borrow_mut().retain(|(_, node)| *node != host));
1363}
1364
1365/// The inline search host the reserved `day::search` id names when no bar item carries it: the
1366/// most recently shown one in the focused window.
1367#[must_use]
1368pub fn inline_search_host() -> Option<RNode> {
1369 let window = windows::focused_root();
1370 SEARCH_HOSTS.with(|h| {
1371 h.borrow()
1372 .iter()
1373 .rev()
1374 .find(|(root, _)| *root == window)
1375 .map(|(_, host)| *host)
1376 })
1377}
1378
1379/// Activate the focused window's searchable navigation surface (for a Find command).
1380pub fn focus_search() {
1381 if toolbar::focus_toolbar_search() {
1382 return;
1383 }
1384 if let Some(host) = inline_search_host() {
1385 tree::with_tree(|t| t.patch(host, Box::new(day_spec::props::SearchPatch::Focus), false));
1386 }
1387}
1388
1389/// Deliver synthetic typing to a text control (the dayscript `input` step and the autodrive
1390/// string commands both route here): paint the widget via the ordinary app-write patch, then
1391/// enqueue the `TextChanged` event. Both halves are needed: when a real user types, the text
1392/// is already in the native field by the time its change event fires, so the two-way
1393/// binding's echo guard suppresses the write-back (§4.4); a synthesized event
1394/// alone would drive the app's signal while the widget kept showing its old text.
1395pub fn synthesize_text(node: RNode, text: String) {
1396 tree::with_tree(|t| match t.node_kind(node) {
1397 Some(day_spec::kinds::TEXT_FIELD) => t.patch(
1398 node,
1399 Box::new(day_spec::props::TextFieldPatch::Text {
1400 text: text.clone(),
1401 from_native: false,
1402 }),
1403 false,
1404 ),
1405 Some(day_spec::kinds::TEXT_AREA) => t.patch(
1406 node,
1407 Box::new(day_spec::props::TextAreaPatch::SetText(text.clone())),
1408 false,
1409 ),
1410 // Other kinds (external pieces like the combobox) own their display, and hear about the
1411 // text first through [`SYNTHESIZED_TEXT`]: a piece that treats `TextChanged` as the
1412 // view's own report (the styled editor does) paints from that one instead, since the
1413 // view has not seen this text.
1414 _ => tree::enqueue_event(
1415 tree::rnode_to_id(node),
1416 day_spec::Event::custom(SYNTHESIZED_TEXT, text.clone()),
1417 ),
1418 });
1419 tree::enqueue_event(tree::rnode_to_id(node), day_spec::Event::TextChanged(text));
1420}
1421
1422/// The tag of the `Event::Custom` [`synthesize_text`] sends to a piece of a kind day-core does not
1423/// paint itself, carrying the text, just before the `TextChanged` that follows it. A piece whose
1424/// native view owns the characters shows the text on this event and then sees the `TextChanged`
1425/// as the echo it already handles.
1426pub const SYNTHESIZED_TEXT: &str = "day:synthesized-text";
1427
1428mod piece_ops;
1429pub use piece_ops::{
1430 PieceOperationDone, PieceOperationFn, piece_operation, register_piece_operation,
1431};
1432
1433/// Override the app's appearance: `Some(true)` dark, `Some(false)` light, `None` follow the
1434/// system again. On backends reporting `Cap::Appearance` the native widgets restyle in place
1435/// and [`dark_mode`] answers the override; app-painted surfaces pick it up on their next
1436/// rebuild. Other backends ignore the call; probe before offering a theme picker.
1437pub fn set_appearance(dark: Option<bool>) {
1438 tree::with_tree(|t| t.set_appearance(dark));
1439 note_appearance_changed();
1440}
1441
1442/// Put a badge on the app's icon: the Dock, launcher, home screen, or taskbar (docs/badge.md).
1443///
1444/// Fire-and-forget: a payload the running toolkit cannot render is ignored, so probe
1445/// `capability(Cap::AppBadgeCount | AppBadgeText | AppBadgeDot)` first and choose. Nothing is ever
1446/// substituted, because a wrong number on a user's icon is worse than no badge.
1447///
1448/// ```no_run
1449/// # use day_core::{set_app_badge};
1450/// # use day_spec::AppBadge;
1451/// set_app_badge(&AppBadge::Count(7));
1452/// set_app_badge(&AppBadge::None); // clear
1453/// ```
1454///
1455/// An iOS badge belongs to the installed app and survives termination, so an app that sets one
1456/// usually clears it from a `WillTerminate` handler (docs/lifecycle.md); a macOS Dock badge dies
1457/// with the process.
1458pub fn set_app_badge(badge: &day_spec::AppBadge) {
1459 tree::with_tree(|t| t.set_app_badge(badge));
1460}
1461
1462#[cfg(test)]
1463mod posted_panic_tests {
1464 /// A panic inside a posted main-thread task must be contained (logged + runtime reset), never
1465 /// unwind into the native trampoline that posted it (`panic_cannot_unwind` → SIGABRT). This
1466 /// is the poster/scheduler twin of `pump_events`' containment.
1467 #[test]
1468 fn posted_panic_is_contained() {
1469 super::contain_posted_panic(Box::new(|| panic!("boom in a posted task")));
1470 // Reaching here is the assertion: the panic did not propagate. The runtime was reset, so
1471 // subsequent reactive work still runs.
1472 let s = day_reactive::Signal::new(1i32);
1473 s.set(2);
1474 assert_eq!(s.get_untracked(), 2);
1475 }
1476}