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