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