Skip to main content

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