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