Skip to main content

day/
lib.rs

1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3
4//! Day, the umbrella crate apps depend on. One backend feature per binary (§3.2).
5
6#[cfg(any(
7    all(feature = "appkit", feature = "gtk"),
8    all(feature = "appkit", feature = "mock"),
9    all(feature = "gtk", feature = "mock"),
10    all(feature = "qt", feature = "appkit"),
11    all(feature = "qt", feature = "gtk"),
12    all(feature = "qt", feature = "mock"),
13    all(feature = "xaml", feature = "appkit"),
14    all(feature = "xaml", feature = "gtk"),
15    all(feature = "xaml", feature = "qt"),
16    all(feature = "xaml", feature = "mock"),
17    all(feature = "dom", feature = "appkit"),
18    all(feature = "dom", feature = "gtk"),
19    all(feature = "dom", feature = "qt"),
20    all(feature = "dom", feature = "xaml"),
21    all(feature = "dom", feature = "mock"),
22))]
23compile_error!("day: enable exactly one backend feature");
24
25pub use day_core::frame;
26pub use day_core::{
27    AnyPiece, Blocking, BlockingError, BuildCx, Piece, PieceSeq, TaskHandle, blocking_limit,
28    blocking_threads, dark_mode, reduce_motion, safe_area, set_app_badge, set_appearance,
29    size_class, sleep, spawn_blocking, system_color, task,
30};
31pub use day_core::{AssetDir, AssetName, FontFamily, ImageName, Resource, VectorName, resource};
32/// Raster images from bytes (docs/images.md): decode an encoded PNG or JPEG the app already
33/// holds (a download, a file the user picked, a paste) into the platform's image type, then
34/// show it with `image(&bitmap)` or draw it with `Draw::image`.
35///
36/// `Bitmap` is a handle, not the pixels: they live in the toolkit and are released when the last
37/// handle drops. Decoding is asynchronous because several backends decode off the main thread.
38/// Probe `image_decode_support()` / `image_encode_support()` before offering an affordance that
39/// depends on either, and `image_encode_formats()` before offering a format, since every
40/// platform here reads more formats than it writes.
41pub use day_core::{
42    Bitmap, decode_image, decode_image_async, image_decode_support, image_encode_formats,
43    image_encode_support,
44};
45/// Display-synchronized, cancellable frame callbacks for any UI client.
46pub use day_core::{ElementId, IntoElementKey, id};
47pub use day_core::{application_handlers, default_browser, open_url_with_application};
48/// Programmatic navigation on the deep-link rail (docs/deep-links.md, docs/navigation.md):
49/// route the app to `route`, buffered before the root is ready and applied after, exactly like
50/// a cold launcher shortcut. The route grammar is what `day::routes!` keys and dayscript speak.
51pub use day_core::{focus_search, request_route};
52/// Tweening for canvas animations (docs/tween.md): `Lerp`, `Timing`, `animate`, `Tweened`.
53pub use day_core::{testing, tween};
54/// Optional app-local storage, including asynchronous browser storage.
55#[cfg(feature = "fs")]
56pub use day_part_filesystem as fs;
57/// Optional app-controlled runtime permission requests.
58#[cfg(feature = "permissions")]
59pub use day_part_permissions as permissions;
60/// Optional settings declaration and presentation layer.
61#[cfg(feature = "settings")]
62pub use day_piece_settings as settings;
63/// Optional Apple SwiftUI hosting bridge.
64#[cfg(feature = "swiftui")]
65pub use day_piece_swiftui as swiftui;
66/// Optional native styled-text editor.
67#[cfg(feature = "text-editor")]
68pub use day_piece_text_editor as texteditor;
69#[cfg(feature = "text-editor")]
70pub use day_piece_text_editor::{TextEditor, TextEditorBuilder, text_editor};
71pub use day_pieces::{AsyncImage, AsyncImageBuilder, async_image};
72/// Canvas export (docs/canvas.md "Exporting"): render a recorded `Drawing` to a bitmap or a PDF
73/// through the toolkit's own painter. `canvas_exports()` says which of the two this target
74/// offers; the PDF writer is native on AppKit, UIKit, GTK, Qt and Android only.
75pub use day_pieces::{
76    CanvasExports, Drawing, PdfDocument, RenderBitmap, RenderPdf, canvas_exports,
77};
78/// Sharing (docs/sharing.md): `Share::url(…)…present()`, with the app's own chooser actions.
79pub use day_pieces::{Share, ShareAction, share_action, share_support};
80pub use day_pieces::{colorpicker, combobox, datetime, pager, pullrefresh, searchfield, stepper};
81/// The app's own data, cache and configuration directories, each a folder named after the app
82/// id where its platform keeps that kind of file (docs/fs.md "Where files live"):
83/// `day::storage::data_dir()` for a database or documents, `cache_dir()` for what can be fetched
84/// again, `config_dir()` for a small settings file.
85pub use day_process::storage;
86pub use day_spec::AppBadge;
87pub use day_spec::applications::{
88    Application, ApplicationError, ApplicationHandlers, HandlerQuery,
89};
90/// An app-writable scratch directory. The OS temp dir is not app-writable on every target
91/// (Android reports `getCacheDir()`), so a backend records the right location at startup and
92/// this is how an app asks for it. For derived files an app can rebuild: rendered documents,
93/// thumbnails, export staging.
94pub use day_spec::present::app_temp_dir;
95pub use day_spec::{
96    BitmapId, BitmapInfo, EncodeSpec, ImageError, ImageFormat, ImageProperties, ImageSource,
97};
98pub use day_spec::{EXPORT_MAX_PIXELS, EXPORT_MAX_SIDE, ExportError, PdfInfo, PdfPage};
99pub use day_spec::{KeyEvent, Modifiers};
100/// The wall clock on every target: milliseconds or seconds since the Unix epoch, for timestamps
101/// ("fetched at", "last synced"). `std::time::SystemTime::now()` aborts a web build, so app code
102/// reads the time here. For elapsed time use the monotonic `day::frame::now_secs()`.
103pub use day_spec::{now_epoch_millis, now_epoch_secs};
104// Secondary windows (docs/windows.md): open/find windows, the kind that shapes their
105// chrome, and the preferences/new-window registrations behind the auto menu items.
106pub use day_core::{
107    WindowHandle, check_for_updates, current_window, focused_window, initial_window, open_about,
108    open_new_window, open_preferences, open_window, quit, register_about, register_about_window,
109    register_check_for_updates, register_new_window, register_new_window_for, register_preferences,
110    register_preferences_with, window_by_key, window_title,
111};
112// The app outside its windows (docs/status-item.md): progress on the Dock or taskbar icon, the
113// macOS Dock icon, and whether the app outlives its last window. Status items themselves are
114// `status_item(…)` in the prelude.
115pub use day_core::{KeepRunning, set_app_progress, set_dock_visible, set_keep_running};
116pub use day_spec::{AppProgress, StatusImage};
117// Displays (docs/windows.md "Monitors") and launcher shortcuts set while the app runs
118// (docs/deep-links.md).
119pub use day_core::{monitors, set_launcher_shortcuts};
120pub use day_spec::{LauncherShortcut, Monitor, SystemColor};
121// Window properties (docs/windows.md) and chrome (docs/window-chrome.md): what a window's
122// `state()` signal holds, how it stacks, how it joins macOS window tabs, and the frame and
123// background it opens with.
124pub use day_spec::{
125    Attention, WindowBackground, WindowChrome, WindowKind, WindowLevel, WindowMaterial,
126    WindowPlacement, WindowState, WindowTabbing,
127};
128/// The reactive core, whole (docs/async.md): `day::reactive::{Resource, Load}` for async data
129/// loading. Namespaced because the prelude's `Resource` is the asset handle above, a different
130/// type that predates the async one.
131pub mod reactive {
132    pub use day_reactive::*;
133}
134
135/// Persistent settings (docs/prefs.md): a small key/value string store backed by each platform's
136/// native facility: `NSUserDefaults` on Apple, `SharedPreferences` on Android, a file store
137/// elsewhere. `day::prefs::{get, set, remove, contains}`, plus `bind` to persist a `Signal` and
138/// (with `model`) `bind_json` to persist a keyed store. `day::launch` installs it as the store
139/// `.restore(key)` navigation survives a relaunch through (docs/navigation.md).
140///
141/// Promoted into the facade rather than left a satellite because it is what nearly every app
142/// reaches for first, and because it is the one part that lives in the reactive layer. It stays
143/// its own crate (`day-part-preferences`), so existing `day_part_preferences::…` paths keep working; this is
144/// the same API under a shorter name. Opt out with `default-features = false`.
145/// The per-property observable store (docs/model.md): `Store`/`Keyed`/`Elem`/`Field`, the
146/// change log, and the `#[derive(Observable)]` accessors' machinery.
147#[cfg(feature = "model")]
148pub mod model {
149    pub use day_model::*;
150}
151
152pub use day_core::{install_edit_bridge, invoke_edit};
153pub use day_spec::EditState;
154/// MIME-typed text and binary clipboard data, with async browser support.
155pub mod clipboard {
156    pub use day_part_clipboard::*;
157}
158pub use day_spec::EditOp;
159
160/// Wire a [`model::UndoStack`] to the platform: native fronts (the stock Edit menu, ⌘Z,
161/// iOS's three-finger gestures) where the toolkit has them, and the stack's own signals for
162/// the app's buttons everywhere (docs/model.md). One call, after the stack exists.
163#[cfg(feature = "model")]
164pub fn install_undo(stack: &day_model::UndoStack) {
165    let s = stack.clone();
166    day_core::install_undo_bridge(
167        stack.can_undo(),
168        stack.can_redo(),
169        stack.undo_label(),
170        stack.redo_label(),
171        move |redo| {
172            if redo {
173                s.redo();
174            } else {
175                s.undo();
176            }
177        },
178    );
179}
180
181/// Wire the app's shape/object Cut/Copy/Paste to the platform's own edit commands
182/// (docs/menus.md): the same menu items, shortcuts, and responder precedence text editing
183/// uses. A focused text field keeps its clipboard behavior; everything else reaches these
184/// handlers. `can_copy` is a tracked read (drive it from your selection); `copy`/`cut`
185/// return the serialized payload (its format is the app's: Day-Sketch uses SVG), which day
186/// places on the system clipboard; `paste` receives the text the clipboard holds, falling back
187/// to the payload this app last placed there when the platform answers nothing (docs/menus.md).
188/// Menu items come from `menu_role(MenuRole::Cut/Copy/Paste)`.
189pub fn install_edit_commands(
190    can_copy: impl Fn() -> bool + 'static,
191    copy: impl Fn() -> Option<String> + 'static,
192    cut: impl Fn() -> Option<String> + 'static,
193    paste: impl Fn(&str) + 'static,
194    select_all: impl Fn() + 'static,
195) {
196    // What this app last put on the clipboard. Reading the clipboard is a privilege on
197    // Android (only the app holding input focus is granted it, docs/clipboard.md), and
198    // writing to it raises a system overlay, so a Paste moments after a Copy can be
199    // refused the very payload this app just wrote, and `get_text` answers `None`. The
200    // platform read is still what a Paste asks first, so a clip from another app always
201    // wins; this is only what an app's own Cut/Copy ▸ Paste falls back to when the platform
202    // hands back nothing.
203    let ours: std::rc::Rc<std::cell::RefCell<Option<String>>> = std::rc::Rc::default();
204    let (copied, pasted) = (ours.clone(), ours);
205    let place = move |payload: String| {
206        let _ = day_part_clipboard::set_text(&payload);
207        *copied.borrow_mut() = Some(payload);
208    };
209    day_core::install_edit_bridge(
210        move || {
211            let can = can_copy();
212            day_spec::EditState {
213                can_cut: can,
214                can_copy: can,
215                can_paste: true,
216                can_select_all: true,
217            }
218        },
219        move |op| match op {
220            day_spec::EditOp::Copy => {
221                if let Some(payload) = copy() {
222                    place(payload);
223                }
224            }
225            day_spec::EditOp::Cut => {
226                if let Some(payload) = cut() {
227                    place(payload);
228                }
229            }
230            day_spec::EditOp::Paste => {
231                // An empty read is nothing to paste. It is also how a refusal reaches this
232                // layer, since the Android arm answers `""` for a clip it was not allowed to
233                // look at.
234                let text = day_part_clipboard::get_text()
235                    .filter(|t| !t.is_empty())
236                    .or_else(|| {
237                        let ours = pasted.borrow().clone();
238                        if ours.is_some() {
239                            log::warn!(
240                                "clipboard read came back empty — pasting what this app last \
241                                 copied (docs/clipboard.md)"
242                            );
243                        }
244                        ours
245                    });
246                if let Some(text) = text {
247                    paste(&text);
248                }
249            }
250            day_spec::EditOp::SelectAll => select_all(),
251        },
252    );
253}
254
255/// The keyboard modifiers held right now, for interactions whose meaning they change
256/// (shift-click adds to a selection instead of replacing it). Touch platforms answer
257/// all-false; a dayscript step's declared modifiers take precedence while it dispatches.
258#[must_use]
259pub fn modifiers() -> day_spec::Modifiers {
260    day_core::modifiers()
261}
262
263#[cfg(feature = "prefs")]
264pub mod prefs {
265    pub use day_part_preferences::*;
266
267    /// Install the preferences as the app's navigation-persistence store (docs/navigation.md), so
268    /// a `nav` or `nav_stack` marked `.restore(key)` remembers its state across launches (and
269    /// across an Android process death, since the store is disk-backed). `day::launch` calls it
270    /// when the app has installed no store of its own. Nav keys are namespaced under a `day.nav.`
271    /// prefix, so `.restore("mail")` never collides with the app's own [`set`]/[`get`] keys.
272    ///
273    /// The adapter lives here, where the preferences and the navigation core meet, so the
274    /// preferences part itself needs no UI dependency.
275    pub fn install_nav_store() {
276        struct PrefsNavStore;
277
278        impl day_core::NavStore for PrefsNavStore {
279            fn load(&self, key: &str) -> Option<String> {
280                get(&format!("day.nav.{key}"))
281            }
282            fn save(&self, key: &str, value: &str) {
283                let _ = set(&format!("day.nav.{key}"), value);
284            }
285        }
286
287        day_core::set_nav_store(std::rc::Rc::new(PrefsNavStore));
288    }
289
290    /// Keep a keyed store in the preferences as one JSON array (docs/prefs.md): seed `store`
291    /// from the rows saved under `key` now, then save every later change, an edited field as
292    /// well as an insert, removal or move. A missing or unreadable value leaves the store as it
293    /// is, and a failed read or write is logged. Call it once, right after creating the store;
294    /// the saving reaction lives in the current reactive scope.
295    ///
296    /// Preferences suit a small list. A larger or relational document belongs in
297    /// `day-persistence`.
298    ///
299    /// ```ignore
300    /// let items = Store::new(Keyed::default());
301    /// day::prefs::bind_json("app.items", items);
302    /// ```
303    #[cfg(feature = "model")]
304    pub fn bind_json<T>(key: &str, store: day_model::Store<day_model::Keyed<T>>)
305    where
306        T: day_model::Identified + Clone + serde::Serialize + serde::de::DeserializeOwned,
307    {
308        use day_model::Source;
309
310        if let Some(json) = get(key) {
311            match serde_json::from_str::<Vec<T>>(&json) {
312                Ok(rows) => store.update("load", |k| *k = day_model::Keyed::new(rows)),
313                Err(error) => log::warn!("could not read `{key}` from preferences: {error}"),
314            }
315        }
316        let key = key.to_owned();
317        // Track the whole store, then serialize untracked in the reaction.
318        day_reactive::watch(
319            move || store.with(|_| ()),
320            move |_, _| match store.with_untracked(|k| serde_json::to_string(k.items())) {
321                Ok(json) if set(&key, &json) => log::debug!("saved `{key}` to preferences"),
322                Ok(_) => log::warn!("could not save `{key}` to preferences"),
323                Err(error) => log::warn!("could not encode `{key}`: {error}"),
324            },
325        );
326    }
327}
328// Localization text source + arg trait (§12) at the crate root so generated `res::str::<key>(…)`
329// functions can name `day::LocalizedText` / `day::tr` / `day::IntoFArg` (also in the prelude).
330pub use day_core::{lifecycle_supported, on_lifecycle};
331
332/// Pointer shapes for the `.cursor()` decorator (docs/cursor.md).
333///
334/// [`Cursor`](day_spec::Cursor) itself is in the prelude; this module carries the shapes only
335/// one toolkit names, each behind that toolkit's feature, so `day::cursor::appkit::DRAG_COPY`
336/// is a compile error in a GTK build rather than a silent arrow. Wrap a use in the same
337/// `#[cfg(feature = "…")]` the constant carries. Every constant is a [`Cursor::Native`](day_spec::Cursor::Native) value:
338/// the named backend resolves it by its own table and any other backend ignores it.
339pub mod cursor {
340    pub use day_spec::Cursor;
341
342    /// AppKit's own shapes (`NSCursor`), beyond the shared vocabulary.
343    #[cfg(feature = "appkit")]
344    pub mod appkit {
345        use day_spec::Cursor;
346        /// The poof shown when dragging an item somewhere it will be removed.
347        pub const DISAPPEARING_ITEM: Cursor = Cursor::native("disappearingItem");
348        /// The arrow with a green plus badge shown during a copy drag.
349        pub const DRAG_COPY: Cursor = Cursor::native("dragCopy");
350        /// The arrow with a link badge shown during an alias drag.
351        pub const DRAG_LINK: Cursor = Cursor::native("dragLink");
352        /// The arrow with a menu badge, for content with a contextual menu.
353        pub const CONTEXTUAL_MENU: Cursor = Cursor::native("contextualMenu");
354        /// The I-beam for vertical text layout.
355        pub const I_BEAM_VERTICAL: Cursor = Cursor::native("IBeamCursorForVerticalLayout");
356    }
357
358    /// Qt's own shapes (`Qt::CursorShape`), beyond the shared vocabulary.
359    #[cfg(feature = "qt")]
360    pub mod qt {
361        use day_spec::Cursor;
362        /// The arrow with a question mark (`Qt::WhatsThisCursor`).
363        pub const WHATS_THIS: Cursor = Cursor::native("WhatsThisCursor");
364        /// The arrow with a spinner beside it (`Qt::BusyCursor`).
365        pub const BUSY: Cursor = Cursor::native("BusyCursor");
366        /// A plain upward arrow (`Qt::UpArrowCursor`).
367        pub const UP_ARROW: Cursor = Cursor::native("UpArrowCursor");
368        /// Horizontal splitter (`Qt::SplitHCursor`).
369        pub const SPLIT_H: Cursor = Cursor::native("SplitHCursor");
370        /// Vertical splitter (`Qt::SplitVCursor`).
371        pub const SPLIT_V: Cursor = Cursor::native("SplitVCursor");
372    }
373
374    /// Windows' own shapes (`IDC_*`), beyond the shared vocabulary.
375    #[cfg(feature = "xaml")]
376    pub mod xaml {
377        use day_spec::Cursor;
378        /// The person cursor (`IDC_PERSON`, Windows 10 1809 and up).
379        pub const PERSON: Cursor = Cursor::native("person");
380        /// The location-pin cursor (`IDC_PIN`, Windows 10 1809 and up).
381        pub const PIN: Cursor = Cursor::native("pin");
382        /// A plain upward arrow (`IDC_UPARROW`).
383        pub const UP_ARROW: Cursor = Cursor::native("uparrow");
384        /// The arrow with a small hourglass (`IDC_APPSTARTING`), Windows' progress shape.
385        pub const APP_STARTING: Cursor = Cursor::native("appstarting");
386    }
387
388    /// Android's own shapes (`PointerIcon.TYPE_*`), beyond the shared vocabulary.
389    #[cfg(feature = "material")]
390    pub mod android {
391        use day_spec::Cursor;
392        /// Four-way scroll (`TYPE_ALL_SCROLL`).
393        pub const ALL_SCROLL: Cursor = Cursor::native("all_scroll");
394        /// The no-drop shape (`TYPE_NO_DROP`), distinct from not-allowed.
395        pub const NO_DROP: Cursor = Cursor::native("no_drop");
396        /// Diagonal resize, top-right to bottom-left (`TYPE_TOP_RIGHT_DIAGONAL_DOUBLE_ARROW`).
397        pub const TOP_RIGHT_DIAGONAL: Cursor = Cursor::native("top_right_diagonal_double_arrow");
398        /// Diagonal resize, top-left to bottom-right (`TYPE_TOP_LEFT_DIAGONAL_DOUBLE_ARROW`).
399        pub const TOP_LEFT_DIAGONAL: Cursor = Cursor::native("top_left_diagonal_double_arrow");
400    }
401}
402pub use day_localization_ui::{IntoFArg, IntoNumberFArg, LocalizedText, res, tr};
403
404/// The `log` crate itself, for an app that needs more than the macros (a `LevelFilter`, a custom
405/// `log::Log`). Re-exported by name so `use day::prelude::*` is enough, the same rule the model
406/// re-export follows.
407pub use ::log;
408/// Raise or lower the level Day's default logger emits, at runtime. `DAY_LOG` sets it at startup
409/// on native targets; the web launch path reads `?DAY_LOG=` from the page URL.
410pub use day_core::set_log_level;
411/// Logging (docs/logging.md). `day::info!("…")` and friends are the `log` crate's macros,
412/// re-exported so an app needs no `log` dependency of its own for the common case. Because they
413/// are `log`'s, anything that speaks `log` (`env_logger`, `tracing-log`, a hand-written
414/// `log::Log`) works without adapters.
415///
416/// Day installs a default logger at launch, so these come out with no setup on every platform:
417/// stderr natively, the browser console on web-dom. An app that wants something else calls
418/// `log::set_logger` (or `env_logger::init()`) before `day::launch` and keeps it.
419pub use log::{debug, error, info, log_enabled, trace, warn};
420
421/// A PNG of this window, as the app itself sees it (docs/window-image.md).
422///
423/// The same capture the dayscript `screenshot` step takes, offered to the app: the window's
424/// content (what Day drew) without the platform's chrome around it. [`WindowImage::chrome`]
425/// asks for the chrome as well.
426///
427/// Synchronous, because every backend that can do this at all has a synchronous way to: an
428/// offscreen render on the desktop toolkits, `UIGraphicsImageRenderer` on UIKit, `View.draw` on
429/// Android, `componentSnapshot.getSync` on ArkUI. Feed the bytes straight to
430/// [`save_file`](day_pieces::save_file), which is the async half.
431///
432/// ```no_run
433/// # use day::prelude::*;
434/// day::task(async move {
435///     if let Ok(png) = day::window_image().capture() {
436///         let _ = save_file(png).suggested_name("shot.png").filter("PNG", &["png"]).await;
437///     }
438/// });
439/// ```
440///
441/// `Err` where the toolkit cannot rasterize its window: today only web-dom, which would need
442/// a rasterizer shipped with it. Ask [`window_image_support`] first when the answer decides
443/// whether to show a button at all.
444pub fn window_image() -> WindowImage {
445    WindowImage { chrome: false }
446}
447
448/// Whether this toolkit can hand the app a picture of its own window (`Cap::Snapshot`).
449#[must_use]
450pub fn window_image_support() -> day_spec::Support {
451    day_core::with_tree(|t| t.window_image_support())
452}
453
454// The platform font list and canvas text measurement (docs/fonts.md): `font_families()` is
455// cached for the process, `measure_text()` always answers (approximating where a toolkit
456// cannot measure). Probe `Cap::FontList` before offering a font menu.
457pub use day_core::{font_families, measure_text};
458// The measurement memo (docs/fonts.md "It is cached"): a diagnostic pair. Nothing in day needs
459// `clear_text_metrics_cache`; it is for an app that registers a face while running.
460pub use day_core::{TextMetricsCacheStats, clear_text_metrics_cache, text_metrics_cache_stats};
461
462/// The request built by [`window_image`].
463#[derive(Clone, Copy, Debug)]
464pub struct WindowImage {
465    chrome: bool,
466}
467
468impl WindowImage {
469    /// Include the window's chrome: title bar, toolbar, whatever the platform draws around
470    /// the content. A backend with nothing to add (or no way to separate the two) answers with
471    /// the content capture rather than failing.
472    #[must_use]
473    pub fn chrome(mut self) -> Self {
474        self.chrome = true;
475        self
476    }
477
478    /// Take the picture.
479    ///
480    /// # Errors
481    ///
482    /// Returns the toolkit's message when it cannot capture the window.
483    pub fn capture(self) -> Result<Vec<u8>, String> {
484        day_core::with_tree(|t| {
485            if self.chrome {
486                t.snapshot_chrome()
487            } else {
488                t.snapshot()
489            }
490        })
491    }
492}
493
494/// An app-environment value, portably: the process environment on native targets, the page
495/// URL's query string on web-dom (where a browser sandbox has no process environment;
496/// `day launch --env K=V` forwards each pair as a query parameter, docs/web.md). Prefer this
497/// over `std::env::var` for anything a `--env` flag should be able to set on every target.
498#[must_use]
499pub fn env(key: &str) -> Option<String> {
500    #[cfg(all(target_arch = "wasm32", feature = "dom"))]
501    {
502        day_toolkit_dom::host_env(key)
503    }
504    #[cfg(not(all(target_arch = "wasm32", feature = "dom")))]
505    {
506        std::env::var(key).ok()
507    }
508}
509// Same reason: the generated `res::locales::install()` names `day::install_locales` (§18.5).
510pub use day_localization_ui::install as install_locales;
511pub use day_localization_ui::{Catalog, FArg, format_catalog, register_catalog, tr_in};
512// Locale-aware comparison/sorting (docs/localization.md "Sorting"): icu4x collation, so e.g. a
513// Chinese list sorts by pinyin. `compare` and `sort_localized` track the locale signal.
514pub use day_localization_ui::{compare, compare_in, sort_localized};
515// Locale-aware number formatting (docs/localization.md "Numbers outside a message"): the same
516// icu4x formatter `NUMBER()` uses, for the values that have no message to hang on: an axis label,
517// a table column, a readout. `format_decimal` tracks the locale signal.
518pub use day_localization_ui::{format_decimal, format_decimal_in};
519// Percentages and dates the same way (docs/localization.md "Numbers outside a message", "Dates
520// outside a message"): `format_percent` puts the sign where the locale does (`50 %` in French),
521// `format_date` writes an instant's chosen fields in the locale's own form and hour cycle.
522pub use day_localization_ui::{
523    DateFields, format_date, format_date_in, format_percent, format_percent_in,
524};
525// Search matching (docs/localization.md "Searching"): case-insensitive, at the start of any
526// word, with words found by the locale's own segmentation. `matches_search` tracks the locale.
527pub use day_localization_ui::{matches_search, matches_search_in};
528// The current-locale Signal itself, for apps that show or branch on it (`locale().get()` is a
529// tracked read; `set_locale` in the prelude writes it).
530pub use day_localization_ui::locale;
531// Tweaks (docs/tweaks.md): the realized-node id, the size-invalidation hook for native
532// mutations Day can't see, and the retained ref live in the prelude via day-pieces.
533pub use day_core::{RNode, invalidate_size};
534pub use day_pieces::Command;
535pub use day_pieces::NativeRef;
536// Typed routes (docs/navigation.md): `day::routes! { enum Section { Home => "home", … } }`.
537/// Tests that run inside the built app (docs/testing.md): `#[day::test]`, [`Case`], [`Drive`].
538pub use day_core::conformance;
539pub use day_core::conformance::{Case, Drive, Fail, TestResult};
540/// WASM registration implementation used by `#[day::test]`.
541#[cfg(target_arch = "wasm32")]
542#[doc(hidden)]
543pub use day_core::inventory;
544pub use day_core::linkme;
545/// The link-time registry `day-build`'s generated code adds the app's `[[shortcuts]]` to
546/// (docs/deep-links.md "Launcher shortcuts"); not for app code.
547#[doc(hidden)]
548#[cfg(not(target_arch = "wasm32"))]
549pub use day_core::shortcuts::LAUNCHER_SHORTCUTS;
550/// `#[day::builder(FooBuilder)]`: a piece's builder trait, generated from its inherent impl
551/// (docs/api-style.md "Typed builders and erasure").
552pub use day_macros::builder;
553pub use day_macros::test;
554/// The built-in pieces' own cases and the conformance app's content (docs/testing.md).
555#[cfg(feature = "conformance")]
556pub use day_pieces::conformance as builtin_tests;
557pub use day_pieces::routes;
558/// The root of an app's test build: the app's content, or the driven case's page alone.
559pub use day_pieces::test_host;
560pub use day_spec::{Lifecycle, WindowOptions};
561
562/// dayscript **recording** and **action logging** (docs/dayscript.md "Recording", DESIGN §14.6):
563/// install an observer that sees the user's taps, edits, selections, and navigation.
564/// `day::record::{start, start_into, start_to_file, stop, is_recording, recording_signal, script,
565/// steps, save, clear, exclude_prefix}` captures them into a replayable dayscript; a recorder also
566/// arms headlessly from `day launch --record <file>` (the `DAY_RECORD` env, honored inside
567/// `day_script::init`). What it records is an ordinary dayscript, so it replays cross-toolkit
568/// through [`play_script`] or `day launch -t <target> --script <file>`.
569///
570/// `day::record::log_actions(true)` (or `DAY_LOG_ACTIONS=1`) turns on the narration alone: every
571/// action echoed to stdout in the same vocabulary, keeping nothing:
572///
573/// ```text
574/// dayscript ▸ navigate → dates  "Date & time"
575/// dayscript ▸ tap list-shuffle  "Shuffle"
576/// ```
577pub mod record {
578    pub use day_script::record::*;
579}
580
581/// Replay a dayscript against the running app, in-process (docs/dayscript.md "Recording"): parse
582/// `yaml` and run each step through the embedded engine, on the main thread between flushes, the
583/// same executor `day launch --script` drives. Returns an error while a recording is live (a replay
584/// must not record itself) and on web (no background thread; drive the page over the WebSocket
585/// transport there). See [`record`].
586///
587/// # Errors
588///
589/// Returns a message when a recording is live, a script is already playing, the script does
590/// not parse or has no steps, or the target is web.
591pub fn play_script(yaml: &str) -> Result<(), String> {
592    day_script::play(yaml)
593}
594
595/// The display name of the toolkit compiled into this binary: `"AppKit"`, `"GTK"`, `"Qt"`,
596/// `"UIKit"`, `"Material Components"`, `"XAML"`, `"WinUI"`, `"ArkUI"`, `"DOM"` (or `"Mock"`). Handy for a window
597/// title that names its backend.
598#[must_use]
599pub const fn toolkit_name() -> &'static str {
600    #[cfg(feature = "appkit")]
601    {
602        return "AppKit";
603    }
604    #[cfg(feature = "gtk")]
605    {
606        return "GTK";
607    }
608    #[cfg(feature = "qt")]
609    {
610        return "Qt";
611    }
612    #[cfg(feature = "uikit")]
613    {
614        return "UIKit";
615    }
616    #[cfg(feature = "material")]
617    {
618        return "Material Components";
619    }
620    // `winui` implies `xaml` (same backend), so it is asked first.
621    #[cfg(feature = "winui")]
622    {
623        return "WinUI";
624    }
625    #[cfg(all(feature = "xaml", not(feature = "winui")))]
626    {
627        return "XAML";
628    }
629    #[cfg(feature = "arkui")]
630    {
631        return "ArkUI";
632    }
633    #[cfg(feature = "dom")]
634    {
635        return "DOM";
636    }
637    #[allow(unreachable_code)]
638    {
639        "Mock"
640    }
641}
642
643pub mod prelude {
644    pub use day_core::{ElementId, IntoElementKey, id};
645    pub use day_localization_ui::{
646        LocalizedText, install as install_locales, matches_search, set_locale, sort_localized, tr,
647    };
648    #[cfg(feature = "text-editor")]
649    pub use day_piece_text_editor::{TextEditor, TextEditorBuilder, text_editor};
650    pub use day_pieces::prelude::*;
651    pub use day_spec::{Lifecycle, Size, WindowOptions};
652    // Canvas drawing vocabulary (docs/canvas.md): arbitrary paths and their fill rule, the
653    // stroke style a dashed or round-capped line needs, and per-corner radii for
654    // `Shape::rounded_rect`.
655    pub use day_spec::{CornerRadii, FillRule, LineCap, LineJoin, Path, PathSeg, StrokeStyle};
656    // SVG path data to a `PathBuilder` chain, at compile time (docs/canvas.md).
657    pub use day_macros::build_path;
658    // The observable store (docs/model.md). The crate itself is re-exported by name because the
659    // derive's generated code says `day_model::…`; this is what makes `use day::prelude::*`
660    // enough. day-model's `Path` stays out: the prelude's `Path` is the canvas one.
661    #[cfg(feature = "model")]
662    pub use ::day_model;
663    #[cfg(feature = "model")]
664    #[doc(no_inline)]
665    pub use ::day_model::Uuid;
666    #[cfg(feature = "model")]
667    pub use ::day_model::{Elem, Field, Key, Keyed, ModelId, Source, Store};
668    #[cfg(feature = "model")]
669    pub use day_macros::Observable;
670    pub use day_spec::Point;
671    // Logging (docs/logging.md): `info!`/`warn!`/`error!`/`debug!`/`trace!` with no setup and no
672    // `log` dependency in the app's own Cargo.toml. These are `log`'s macros, so an app that later
673    // installs `env_logger` or `tracing` keeps every call site it already wrote.
674    pub use super::{debug, error, info, log, log_enabled, set_log_level, trace, warn};
675    pub use {super::lifecycle_supported, super::on_lifecycle};
676    // Bundled-resource random-access API (§18.3): `resource("name")` -> `Resource`.
677    pub use day_core::{
678        AssetDir, AssetName, FontFamily, ImageName, Resource, VectorName, resource,
679    };
680    pub use day_spec::present::app_temp_dir;
681    // Toolkit capability probe (docs): lets app/piece content adapt to the backend, e.g. skip a
682    // title the native nav already shows (`Cap::NavHeader`). `capability(cap) -> Support`.
683    pub use day_core::capability;
684    // Safe-area insets (docs/layout.md): zero everywhere except edge-to-edge backends. Pad
685    // content by it where a background runs under the system bars.
686    pub use day_core::safe_area;
687    // The window's size class (docs/size-classes.md): what a `nav()` host resolves its own
688    // presentation from, and what an app lays out from when it wants to make the same call:
689    // two columns on a wide window, one on a narrow one. `None` on a backend that reports no
690    // geometry. Tracked, so a piece reading it rebuilds when the window crosses a breakpoint.
691    pub use day_core::size_class;
692    pub use day_spec::{Cap, Cursor, HeightClass, SizeClass, Support, WidthClass};
693    // Layout direction (docs/localization): `is_rtl()` lets a piece mirror its own drawing under
694    // a right-to-left locale; the layout engine mirrors placement, but a `canvas` owns its
695    // coordinates.
696    pub use day_core::{is_rtl, layout_direction};
697    pub use day_spec::LayoutDirection;
698}
699
700/// App-lifecycle support for the backend compiled into this binary (docs/lifecycle.md).
701///
702/// Register handlers with [`on_lifecycle`]; guard phases a platform may not deliver either at runtime
703/// (`if day::lifecycle::supported(p) { … }`) or at compile time with [`require_lifecycle!`].
704pub mod lifecycle {
705    pub use day_core::{lifecycle_supported, on_lifecycle};
706    pub use day_spec::Lifecycle;
707
708    /// Does the backend compiled into this binary deliver `phase`? A `const fn`, so it drives both a
709    /// runtime guard and the compile-time [`crate::require_lifecycle!`] assertion. Agrees with the
710    /// runtime [`day_core::lifecycle_supported`] once the app is running.
711    #[must_use]
712    pub const fn supported(phase: Lifecycle) -> bool {
713        #[cfg(feature = "appkit")]
714        {
715            return day_toolkit_appkit::lifecycle_supported(phase);
716        }
717        #[cfg(feature = "gtk")]
718        {
719            return day_toolkit_gtk::lifecycle_supported(phase);
720        }
721        #[cfg(feature = "qt")]
722        {
723            return day_toolkit_qt::lifecycle_supported(phase);
724        }
725        #[cfg(all(feature = "uikit", target_os = "ios"))]
726        {
727            return day_toolkit_uikit::lifecycle_supported(phase);
728        }
729        #[cfg(all(feature = "material", target_os = "android"))]
730        {
731            return day_toolkit_material::lifecycle_supported(phase);
732        }
733        #[cfg(all(feature = "xaml", windows))]
734        {
735            return day_toolkit_winui::lifecycle_supported(phase);
736        }
737        #[cfg(all(feature = "arkui", target_env = "ohos"))]
738        {
739            return day_toolkit_arkui::lifecycle_supported(phase);
740        }
741        // No concrete backend (mock, or a mobile backend compiled for the host to check): the
742        // universal phases are always deliverable.
743        #[allow(unreachable_code)]
744        {
745            phase.is_universal()
746        }
747    }
748}
749
750/// Compile-time assert that the backend in this binary delivers `$phase`, else a build error. Use it
751/// to make a hard dependency on a platform-specific phase explicit:
752/// `day::require_lifecycle!(day::Lifecycle::DidEnterBackground);` fails to compile on desktop.
753/// For soft handling, guard with [`lifecycle::supported`] / [`lifecycle_supported`] instead.
754#[macro_export]
755macro_rules! require_lifecycle {
756    ($phase:expr) => {
757        const {
758            ::core::assert!(
759                $crate::lifecycle::supported($phase),
760                "this Day backend does not deliver that lifecycle phase (see docs/lifecycle.md)",
761            )
762        }
763    };
764}
765
766/// Launch through an external toolkit's backend (docs/extending.md "External toolkits"): the
767/// cfg-free counterpart of the feature-gated `launch` entries below, for platform-toolkit pairs
768/// registered via `[package.metadata.day.toolkit]`. Feature-independent because `day build
769/// -t <external>` compiles the app with only the external toolkit's feature, so none of the
770/// launchers below exist in that build. Starts the dayscript engine exactly as they do, which
771/// is what keeps `day launch --script`, `day drive`, and the session registry working on a
772/// backend this repository has never heard of.
773pub fn launch_external<P: day_spec::Platform, R: Piece>(
774    backend: P,
775    options: WindowOptions,
776    root: impl FnOnce() -> R + 'static,
777) {
778    day_script::init();
779    start(backend, options, root);
780}
781
782/// Start `backend`, seeding the ambient locale first.
783///
784/// The order matters: the OS's language preference has to reach day-localization before the app's
785/// `res::locales::install()` runs, and that call lives inside the root builder, so the hints
786/// are read from the live backend here, one step before it is handed the root. Without this
787/// step `Toolkit::locale_hints` is a trait method nobody calls, and every native app opens in its
788/// default language whatever the device is set to (docs/localization.md).
789// Every caller is a `launch` behind its own backend feature (§3.2), so a featureless
790// `cargo check -p day` (which is what a bare workspace check builds) has none of them and would
791// otherwise report this as dead. Listing the backends here instead would be a second copy of the
792// cfg set below, drifting the first time one is added.
793#[allow(dead_code)]
794fn start<P: day_spec::Platform, R: Piece>(
795    backend: P,
796    mut options: WindowOptions,
797    root: impl FnOnce() -> R + 'static,
798) {
799    day_localization_ui::add_launch_locales(&backend.locale_hints());
800    // `.restore(key)` surfaces persist through the preferences unless the app installed a
801    // store of its own (docs/navigation.md).
802    #[cfg(feature = "prefs")]
803    if !day_core::has_nav_store() {
804        prefs::install_nav_store();
805    }
806    // The app's catalog, now that the hints are in: registering it here rather than inside the
807    // root builder is what lets a title, drawn before any piece exists, come out of the
808    // catalog too (docs/localization.md).
809    if let Some((default, catalog)) = options.locales {
810        day_localization_ui::install(default, catalog);
811    }
812    if let Some(f) = options.title_fn {
813        options.title = f();
814    }
815    day_core::launch_with(backend, options, move || AnyPiece::new(root()));
816}
817
818/// Launch the app on the selected backend (blocks; owns the native main loop).
819#[cfg(feature = "appkit")]
820pub fn launch<P: Piece>(options: WindowOptions, root: impl FnOnce() -> P + 'static) {
821    day_script::init();
822    start(day_toolkit_appkit::AppKit::new(), options, root);
823}
824
825#[cfg(feature = "gtk")]
826pub fn launch<P: Piece>(options: WindowOptions, root: impl FnOnce() -> P + 'static) {
827    day_script::init();
828    start(day_toolkit_gtk::Gtk::new(), options, root);
829}
830
831#[cfg(feature = "qt")]
832pub fn launch<P: Piece>(options: WindowOptions, root: impl FnOnce() -> P + 'static) {
833    day_script::init();
834    start(day_toolkit_qt::Qt::new(), options, root);
835}
836
837#[cfg(all(feature = "uikit", target_os = "ios"))]
838pub fn launch<P: Piece>(options: WindowOptions, root: impl FnOnce() -> P + 'static) {
839    day_script::init();
840    start(day_toolkit_uikit::Uikit::new(), options, root);
841}
842
843#[cfg(all(feature = "xaml", windows))]
844pub fn launch<P: Piece>(options: WindowOptions, root: impl FnOnce() -> P + 'static) {
845    day_script::init();
846    start(day_toolkit_winui::Xaml::new(), options, root);
847}
848
849#[cfg(all(feature = "dom", target_arch = "wasm32"))]
850pub fn launch<P: Piece>(options: WindowOptions, root: impl FnOnce() -> P + 'static) {
851    // No day_script::init(): dayscript's TCP transport has no wasm equivalent yet
852    // (a WebSocket transport is planned; see docs/web.md).
853    start(day_toolkit_dom::Dom::new(), options, root);
854}
855
856#[cfg(feature = "mock")]
857pub fn launch<P: Piece>(options: WindowOptions, root: impl FnOnce() -> P + 'static) {
858    let (mock, _probe) = day_mock::MockToolkit::new();
859    start(mock, options, root);
860}
861
862// ---------------------------------------------------------------------------
863// App entry macros (§17.4): the mobile shells bind fixed exported symbols
864// (Runner/main.swift → `day_main`; dev.daybrite.day.bridge.DayBridge → `Java_…` natives).
865// These expand to that glue so an app's lib.rs carries one line per platform.
866// Both emit nothing off their target OS, so apps invoke them unconditionally.
867// ---------------------------------------------------------------------------
868
869/// `options` with [`WindowOptions::version`] set to the calling crate's `CARGO_PKG_VERSION` when
870/// the app left it unset: the version Day's exit line names (docs/lifecycle.md). A macro, because
871/// only code expanded in the app crate can read the app's own package version; the `day_start!`
872/// entries route their options through it, so a mobile host names its version without the app
873/// doing anything.
874#[doc(hidden)]
875#[macro_export]
876macro_rules! with_app_version {
877    ($options:expr) => {{
878        let mut options: $crate::WindowOptions = $options;
879        if options.version.is_none() {
880            options.version =
881                ::core::option::Option::Some(::core::env!("CARGO_PKG_VERSION").into());
882        }
883        options
884    }};
885}
886
887/// One entry point for every platform that needs one: the single line an app's `lib.rs` carries
888/// instead of one macro per platform.
889///
890/// ```ignore
891/// day::day_start!("My App", root);    // or: day::day_start!(root);
892/// ```
893///
894/// It expands to every platform macro below. Each of those is gated on its own target
895/// (`ios` / `macos` / `android` / the `ohos` env / `wasm32`), and those gates are mutually
896/// exclusive, so exactly one survives a given build, and none at all on a plain cargo desktop
897/// build, where `src/main.rs` is the entry instead.
898///
899/// The title reaches the platforms that have nowhere else to get one. Android and HarmonyOS take
900/// their label from the app manifest (`android:label`, `app_name` in `string.json`) rather than
901/// from Rust, so they accept the argument and ignore it; passing it here keeps one call site for
902/// every target instead of making the caller remember which two are different.
903#[macro_export]
904macro_rules! day_start {
905    ($root:expr) => {
906        $crate::day_start!("", $root);
907    };
908    // The full description, shared with `src/main.rs` so both entry points open the same window
909    // and perform the same ceremony: `options: window()` rather than a bare title. The literal
910    // `options:` is what tells this arm apart from the title one below.
911    (options: $options:expr, $root:expr) => {
912        $crate::day_start_ios!(options: $options, $root);
913        $crate::day_start_macos!(options: $options, $root);
914        $crate::day_start_android!(options: $options, $root);
915        $crate::day_start_arkui!(options: $options, $root);
916        $crate::day_start_web!(options: $options, $root);
917    };
918    ($title:expr, $root:expr) => {
919        $crate::day_start_ios!($title, $root);
920        $crate::day_start_macos!($title, $root);
921        $crate::day_start_android!($root);
922        $crate::day_start_arkui!($root);
923        $crate::day_start_web!($title, $root);
924    };
925}
926
927/// Surface the resources `day-build` generated for this crate as `pub mod res` (§18.5).
928///
929/// ```ignore
930/// day::resources!();   // then: res::str::app_title(), res::images::logo, res::locales::CATALOG
931/// ```
932///
933/// Expands to the `include!` of `$OUT_DIR/day_resources.rs`, so the crate needs the `day-build`
934/// build script that writes it; an app with no `build.rs` has no `OUT_DIR` and should not call
935/// this. Kept separate from [`day_start!`] because entry points are per-target `cfg`, while
936/// `res` has to exist on every build, including the desktop one whose entry is `src/main.rs`.
937#[macro_export]
938macro_rules! resources {
939    () => {
940        /// Typed constants for the files under `resource/`, generated at build time by
941        /// `day-build` (§18.5): `res::images::<stem>`, `res::assets::<file>`,
942        /// `res::fonts::<family>`, `res::str::<key>()`, and the `res::locales` catalog.
943        /// Reference bundled resources through these (`image(res::images::logo)`) so a
944        /// typo is a compile error and the resource is guaranteed present. Drop a file into
945        /// `resource/images/` and its constant appears on the next build.
946        pub mod res {
947            include!(concat!(env!("OUT_DIR"), "/day_resources.rs"));
948        }
949    };
950}
951
952/// Expands to the `day_main` C export the iOS Runner's `main.swift` calls
953/// (`@_silgen_name("day_main")`). The optional title is currently unused on
954/// iOS (the window fills the screen bounds); accepted for future window-scene use.
955///
956/// Apps normally reach this through [`day_start!`] rather than calling it directly.
957///
958/// ```ignore
959/// day::day_start_ios!(root);              // or: day::day_start_ios!("My App", root);
960/// ```
961#[macro_export]
962macro_rules! day_start_ios {
963    ($root:expr) => {
964        $crate::day_start_ios!("", $root);
965    };
966    (options: $options:expr, $root:expr) => {
967        /// iOS entry: the Runner's main.swift calls this from the app staticlib (§17.4).
968        #[cfg(target_os = "ios")]
969        #[unsafe(no_mangle)]
970        pub extern "C" fn day_main() {
971            $crate::launch($crate::with_app_version!($options), $root);
972        }
973    };
974    ($title:expr, $root:expr) => {
975        $crate::day_start_ios!(
976            options: $crate::WindowOptions::default().title($title),
977            $root
978        );
979    };
980}
981
982/// Expands to the `day_main` C export the macOS Runner's `main.swift` calls, the
983/// `platform/macos/` Xcode host project's entry (§17.4). The cargo-driven build keeps using
984/// the app's own `src/main.rs`; both paths call the same [`launch`], so the app behaves
985/// identically however it was built.
986///
987/// ```ignore
988/// day::day_start_macos!(root);            // or: day::day_start_macos!("My App", root);
989/// ```
990#[macro_export]
991macro_rules! day_start_macos {
992    ($root:expr) => {
993        $crate::day_start_macos!("", $root);
994    };
995    (options: $options:expr, $root:expr) => {
996        /// macOS entry: the Runner's main.swift calls this from the app staticlib (§17.4).
997        #[cfg(target_os = "macos")]
998        #[unsafe(no_mangle)]
999        pub extern "C" fn day_main() {
1000            $crate::launch($crate::with_app_version!($options), $root);
1001        }
1002    };
1003    ($title:expr, $root:expr) => {
1004        $crate::day_start_macos!(
1005            // The same desktop default the scaffold's src/main.rs uses.
1006            options: $crate::WindowOptions::default().title($title).size(960.0, 640.0),
1007            $root
1008        );
1009    };
1010}
1011
1012/// Expands to the two JNI exports that start the app, `DayBridge.nativeStart` (the primary
1013/// window) and `DayBridge.nativeStartWindow` (a secondary one), wired to the given root piece.
1014/// They live in the app cdylib because they name the app's root; every other native the bridge
1015/// declares is registered by day-toolkit-material's `DayBridge` binding (docs/android-jni.md).
1016///
1017/// ```ignore
1018/// day::day_start_android!(root);
1019/// ```
1020#[macro_export]
1021macro_rules! day_start_android {
1022    ($root:expr) => {
1023        $crate::day_start_android!(
1024            options: $crate::WindowOptions::default(),
1025            $root
1026        );
1027    };
1028    (options: $options:expr, $root:expr) => {
1029        // jni 0.22 native methods receive the FFI-safe `EnvUnowned`; `with_env` upgrades it to the
1030        // real `Env` (sharing the frame's `'local`, so the object args pass straight in) and wraps
1031        // the body in a `catch_unwind` so a panic never unwinds across the JNI boundary.
1032        #[cfg(target_os = "android")]
1033        #[unsafe(no_mangle)]
1034        pub extern "system" fn Java_dev_daybrite_day_bridge_DayBridge_nativeStart<'local>(
1035            mut env: $crate::android::jni::EnvUnowned<'local>,
1036            _class: $crate::android::jni::objects::JClass<'local>,
1037            root: $crate::android::jni::objects::JObject<'local>,
1038            density: $crate::android::jni::sys::jfloat,
1039            w: $crate::android::jni::sys::jint,
1040            h: $crate::android::jni::sys::jint,
1041            autodrive: $crate::android::jni::objects::JString<'local>,
1042            locale: $crate::android::jni::objects::JString<'local>,
1043            env_blob: $crate::android::jni::objects::JString<'local>,
1044        ) {
1045            let _ = env
1046                .with_env(|env| {
1047                    let a = $crate::android::read_jstring(env, &autodrive);
1048                    let l = $crate::android::read_jstring(env, &locale);
1049                    let e = $crate::android::read_jstring(env, &env_blob);
1050                    $crate::android::start(env, root, density, w, h, a, l, e, $crate::with_app_version!($options), $root);
1051                    ::core::result::Result::Ok::<(), $crate::android::jni::errors::Error>(())
1052                })
1053                .into_outcome();
1054        }
1055
1056        #[cfg(target_os = "android")]
1057        #[unsafe(no_mangle)]
1058        pub extern "system" fn Java_dev_daybrite_day_bridge_DayBridge_nativeStartWindow<'local>(
1059            mut env: $crate::android::jni::EnvUnowned<'local>,
1060            _class: $crate::android::jni::objects::JClass<'local>,
1061            root: $crate::android::jni::objects::JObject<'local>,
1062            node: $crate::android::jni::sys::jlong,
1063            _density: $crate::android::jni::sys::jfloat,
1064            w: $crate::android::jni::sys::jint,
1065            h: $crate::android::jni::sys::jint,
1066        ) -> $crate::android::jni::sys::jboolean {
1067            let mut ok = false;
1068            let _ = env
1069                .with_env(|env| {
1070                    ok = $crate::android::window_started(env, root, node, w, h);
1071                    ::core::result::Result::Ok::<(), $crate::android::jni::errors::Error>(())
1072                })
1073                .into_outcome();
1074            ok as $crate::android::jni::sys::jboolean
1075        }
1076    };
1077}
1078
1079/// Android glue (§17.4): the app cdylib's JNI exports forward here.
1080#[cfg(all(feature = "material", target_os = "android"))]
1081pub mod android {
1082    pub use day_toolkit_material::jni;
1083    pub use day_toolkit_material::{mount_settled, read_jstring, window_started};
1084
1085    #[allow(clippy::too_many_arguments)]
1086    pub fn start<R: crate::Piece>(
1087        env: &mut jni::Env,
1088        root: jni::objects::JObject,
1089        density: f32,
1090        w: i32,
1091        h: i32,
1092        autodrive: Option<String>,
1093        locale: Option<String>,
1094        env_blob: Option<String>,
1095        options: crate::WindowOptions,
1096        root_piece: impl FnOnce() -> R + 'static,
1097    ) {
1098        // Before any println!: send stdout/stderr to logcat (Android drops them otherwise).
1099        day_toolkit_material::redirect_stdio_to_logcat();
1100        // A second launch in one process: the activity was recreated (docs/settings.md
1101        // "Appearance on Android"). Two paths do it: a light/dark or language switch calls
1102        // `recreate()` itself, and any configuration change the manifest does not claim
1103        // recreates incidentally. Both re-enter here with day-core already mounted.
1104        //
1105        // Re-mount rather than refuse. Refusing left the process alive with no tree behind the
1106        // new activity: a black, unresponsive window, and (because the dayscript engine socket
1107        // belongs to the process rather than the activity) a walkthrough that stayed green
1108        // against it. Building a second tree over the first was no better; the previous window's
1109        // reactive graph was never disposed, so its navigation host re-registered itself on top
1110        // of the new one.
1111        //
1112        // `prepare_remount` disposes what the last mount built and clears what `root()` is about
1113        // to register again, leaving root-scope state (`Signal::global`, `Ambient::app()`) alone.
1114        let remount = day_core::is_mounted();
1115        if remount {
1116            day_core::prepare_remount();
1117            // The language list is root-scoped, so it outlives the mount, and `crate::start`
1118            // appends the backend's hints to it. A re-mount for a new system language would
1119            // append ["fr-FR", "en-US"] behind the ["en-US"] of the first launch, and English
1120            // would still win. Start the list over; the fresh hints are the whole answer.
1121            day_localization_ui::set_launch_locales(&[]);
1122        }
1123        if let Some(a) = autodrive {
1124            unsafe { std::env::set_var("DAY_AUTODRIVE", a) };
1125        }
1126        if let Some(l) = locale {
1127            unsafe { std::env::set_var("DAY_LOCALE", l) };
1128        }
1129        if let Some(blob) = env_blob {
1130            for line in blob.lines() {
1131                if let Some((k, v)) = line.split_once('=') {
1132                    unsafe { std::env::set_var(k, v) };
1133                }
1134            }
1135        }
1136        day_toolkit_material::init(env, root, density, w, h);
1137        // The dayscript engine belongs to the process, not the activity: its listener survives a
1138        // recreation and keeps serving against whatever tree is mounted. Re-running `init` only
1139        // tried to bind the same port again ("Address already in use"), so the re-mount skips it.
1140        if !remount {
1141            day_script::init();
1142        }
1143        // Through `crate::start`, not `launch_with`: that is where the device's language
1144        // preference is read off the backend and handed to the localization engine, and this
1145        // entry is the app's only door on Android (docs/localization.md).
1146        // The app's description, not a default: it carries the locale catalog, and
1147        // `crate::start` is the only thing that installs it. Handed a default here, every
1148        // localized string on Android rendered as its own key (`⟨welcome_title⟩` on screen)
1149        // because the app stopped calling `res::locales::install()` itself when the catalog
1150        // moved into `WindowOptions` (docs/localization.md). The window fields are inert on
1151        // Android, where the Activity owns the surface and the label comes from the manifest.
1152        crate::start(day_toolkit_material::Material::new(), options, root_piece);
1153        // The tree is up: on a re-mount, bring the app back to the route the previous mount
1154        // saved, then let the activity take its crossfade down.
1155        day_toolkit_material::mount_settled(remount);
1156    }
1157}
1158
1159/// Expands to the `day_arkui_start` C export the HarmonyOS ArkUI shim's `start(...)` NAPI wrapper
1160/// calls (from ArkTS: `import native from 'libday_arkui.so'; native.start(nodeContent, w, h, density)`).
1161/// It mounts the app's `root` piece into the ArkTS `NodeContent` and runs the loop.
1162///
1163/// ```ignore
1164/// day::day_start_arkui!(root);
1165/// ```
1166#[macro_export]
1167macro_rules! day_start_arkui {
1168    ($root:expr) => {
1169        $crate::day_start_arkui!(options: $crate::WindowOptions::default(), $root);
1170    };
1171    (options: $options:expr, $root:expr) => {
1172        /// HarmonyOS entry: the ArkUI shim's NAPI `start` calls this from the app cdylib (§17.4).
1173        #[cfg(target_env = "ohos")]
1174        #[unsafe(no_mangle)]
1175        pub extern "C" fn day_arkui_start(
1176            content: *mut ::core::ffi::c_void,
1177            w: f64,
1178            h: f64,
1179            density: f64,
1180        ) {
1181            $crate::arkui::start(content, w, h, density, $crate::with_app_version!($options), $root);
1182        }
1183
1184        /// Deep-link intake (docs/deep-links.md): day-toolkit-arkui's NAPI `deepLink(uri)` calls this
1185        /// from the app cdylib for cold and warm links alike; `request_route` buffers before
1186        /// launch and navigates on the UI thread after.
1187        ///
1188        /// # Safety
1189        /// `uri` must be null or point to a NUL-terminated string valid for this call.
1190        #[cfg(target_env = "ohos")]
1191        #[unsafe(no_mangle)]
1192        pub unsafe extern "C" fn day_arkui_deeplink(uri: *const ::core::ffi::c_char) {
1193            // SAFETY: forwarded under the caller's string lifetime contract.
1194            unsafe { $crate::arkui::deeplink(uri) };
1195        }
1196    };
1197}
1198
1199/// Expands to the `day_dom_main` C export the web host's `shim.js` calls once the wasm module
1200/// is instantiated (`wasm.day_dom_main()` at the end of `start()` in `crates/day-cli/resources/web/shim.js`).
1201///
1202/// ```ignore
1203/// day::day_start_web!(root);              // or: day::day_start_web!("My App", root);
1204/// ```
1205#[macro_export]
1206macro_rules! day_start_web {
1207    ($root:expr) => {
1208        $crate::day_start_web!("", $root);
1209    };
1210    (options: $options:expr, $root:expr) => {
1211        /// Web entry: the host page's shim calls this from the app cdylib (§17.4).
1212        #[cfg(target_arch = "wasm32")]
1213        #[unsafe(no_mangle)]
1214        pub extern "C" fn day_dom_main() {
1215            $crate::web::start($crate::with_app_version!($options), $root);
1216        }
1217    };
1218    ($title:expr, $root:expr) => {
1219        $crate::day_start_web!(
1220            options: $crate::WindowOptions::default().title($title),
1221            $root
1222        );
1223    };
1224}
1225
1226/// Web glue (§17.4): the app cdylib's `day_dom_main` export forwards here.
1227#[cfg(all(feature = "dom", target_arch = "wasm32"))]
1228pub mod web {
1229    type EmbeddedResources = &'static [(&'static str, &'static [u8])];
1230    static RESOURCES: std::sync::OnceLock<EmbeddedResources> = std::sync::OnceLock::new();
1231
1232    /// Register the generated web resource table before application initialization.
1233    /// Called by day-build's generated bootstrap; names are canonical bundle URLs.
1234    ///
1235    /// # Panics
1236    /// Panics if called more than once for the same Wasm instance.
1237    pub fn install_resources(resources: EmbeddedResources) {
1238        RESOURCES
1239            .set(resources)
1240            .expect("resources already installed");
1241        day_core::set_resource_opener(|name| {
1242            let table = RESOURCES.get()?;
1243            let index = table
1244                .binary_search_by(|(path, _)| {
1245                    path.bytes().cmp("assets/data/".bytes().chain(name.bytes()))
1246                })
1247                .ok()?;
1248            Some(crate::Resource::from_static(table[index].1))
1249        });
1250    }
1251
1252    fn resource_pair(bytes: &[u8]) -> u64 {
1253        ((bytes.len() as u64) << 32) | bytes.as_ptr() as u64
1254    }
1255
1256    /// Number of files in the embedded web bundle (host bootstrap ABI).
1257    #[unsafe(no_mangle)]
1258    pub extern "C" fn day_dom_resources_count() -> usize {
1259        RESOURCES.get().map_or(0, |r| r.len())
1260    }
1261
1262    /// Borrow a bundle URL as a packed pointer and length (host bootstrap ABI).
1263    #[unsafe(no_mangle)]
1264    pub extern "C" fn day_dom_resources_name(index: usize) -> u64 {
1265        RESOURCES
1266            .get()
1267            .and_then(|r| r.get(index))
1268            .map_or(0, |(name, _)| resource_pair(name.as_bytes()))
1269    }
1270
1271    /// Borrow a file's bytes as a packed pointer and length (host bootstrap ABI).
1272    #[unsafe(no_mangle)]
1273    pub extern "C" fn day_dom_resources_bytes(index: usize) -> u64 {
1274        RESOURCES
1275            .get()
1276            .and_then(|r| r.get(index))
1277            .map_or(0, |(_, bytes)| resource_pair(bytes))
1278    }
1279
1280    /// One dayscript request line from the page's WebSocket (docs/web.md). Lives here, not in
1281    /// day-toolkit-dom, because backends depend only on day-spec; the umbrella is where the backend
1282    /// and the engine meet.
1283    #[unsafe(no_mangle)]
1284    pub extern "C" fn day_dom_script_line(ptr: *mut u8, len: usize) {
1285        let line = day_toolkit_dom::take_alloc_string(ptr, len);
1286        day_script::web_line(&line);
1287    }
1288
1289    /// Install the panic hook (panics report through the browser console before the trap),
1290    /// hand the page's locale (`?locale=` else the browser languages) to the localization
1291    /// engine and its URL hash to `request_route`, arm the dayscript web transport when
1292    /// the serving `day launch` session invites it (`?dayscript=` token), and launch `root`
1293    /// into the host page's day root.
1294    pub fn start<P: crate::Piece>(
1295        options: crate::WindowOptions,
1296        root: impl FnOnce() -> P + 'static,
1297    ) {
1298        day_toolkit_dom::install_panic_hook();
1299        // Point the logger at the browser console before anything can log (docs/logging.md).
1300        // Installed here rather than inside day-toolkit-dom because a backend depends only on day-spec;
1301        // the facade is where the toolkit and the core are allowed to meet. Without this every
1302        // line would be silently dropped: std's stdio on wasm32-unknown-unknown takes the bytes
1303        // and discards them.
1304        day_core::set_log_sink(day_toolkit_dom::console_sink);
1305        // `DAY_LOG` has no process environment to live in here; the launch server forwards it as
1306        // a query parameter. `init_logging` (from `launch_with`) sets the default level, so this
1307        // only has to override when the page actually asked.
1308        if let Some(level) = day_toolkit_dom::launch_log_level() {
1309            day_core::set_log_level(level);
1310        }
1311        // `Instant` is unavailable on wasm; timing code reads the page's clock instead.
1312        day_core::frame::install_monotonic_clock(day_toolkit_dom::monotonic_secs);
1313        if let Some(locale) = day_toolkit_dom::launch_locale() {
1314            day_localization_ui::set_launch_locale(&locale);
1315        }
1316        if let Some(url) = day_toolkit_dom::launch_open_url() {
1317            day_core::request_open_url(&url);
1318        }
1319        if let Some(route) = day_toolkit_dom::launch_route() {
1320            day_core::set_launch_deeplink(&route);
1321        }
1322        if let Some(token) = day_toolkit_dom::dayscript_token() {
1323            day_script::web_init(token, day_toolkit_dom::script_send);
1324        }
1325        crate::launch(options, root);
1326    }
1327}
1328
1329/// HarmonyOS ArkUI glue (§17.4): the app cdylib's `day_arkui_start` export forwards here.
1330#[cfg(all(feature = "arkui", target_env = "ohos"))]
1331pub mod arkui {
1332    use core::ffi::c_void;
1333
1334    /// Mount `root` into the ArkTS `NodeContent` and run the loop. `w_vp`/`h_vp` are the content
1335    /// size in vp; `density` is px-per-vp (both passed by the ArkTS host).
1336    pub fn start<R: crate::Piece>(
1337        content: *mut c_void,
1338        w_vp: f64,
1339        h_vp: f64,
1340        density: f64,
1341        options: crate::WindowOptions,
1342        root: impl FnOnce() -> R + 'static,
1343    ) {
1344        day_toolkit_arkui::init(content, w_vp, h_vp, density);
1345        // Point the logger at hilog before anything can log (docs/logging.md): std's stdio
1346        // goes nowhere in an OHOS ability, so without this every `log::` line is dropped.
1347        // The same facade-installed sink rule as web.
1348        day_core::set_log_sink(day_toolkit_arkui::hilog_sink);
1349        day_script::init();
1350        // `crate::start` seeds the device's language preference before the root builds
1351        // (docs/localization.md); ArkUI's own hint list arrives once day-toolkit-arkui implements
1352        // `locale_hints`.
1353        // The app's own description, for the same reason as Android above: the locale catalog
1354        // travels in it, and nothing else installs one.
1355        crate::start(day_toolkit_arkui::ArkUi::new(), options, root);
1356    }
1357
1358    /// A deep link from the ArkTS host (docs/deep-links.md): a cold `want.uri` (delivered
1359    /// before `start`) or a warm `onNewWant` one. `request_route` makes the two the same
1360    /// call, buffered until the first mount and applied on the UI thread after it.
1361    ///
1362    /// # Safety
1363    /// `uri` must be null or point to a NUL-terminated string valid for this call.
1364    pub unsafe fn deeplink(uri: *const core::ffi::c_char) {
1365        if uri.is_null() {
1366            return;
1367        }
1368        // SAFETY: per the caller's contract.
1369        let uri = unsafe { core::ffi::CStr::from_ptr(uri) };
1370        if let Ok(uri) = uri.to_str() {
1371            if uri.starts_with("file://") {
1372                day_core::request_open_files(vec![uri.into()]);
1373            } else {
1374                day_core::request_open_url(uri);
1375            }
1376        }
1377    }
1378}
1379
1380/// Native drag-and-drop data and acceptance policy.
1381pub use day_spec::transfer;
1382
1383/// Receive text shared to the app from the system share sheet (Day.toml `share_target`); a
1384/// shared web link arrives through [`on_open_url`] instead. See docs/deep-links.md.
1385pub use day_core::on_shared_text;
1386/// Receive local document activations from the operating system. See docs/documents.md.
1387pub use day_core::{on_open_files, on_open_url};
1388
1389/// Download an image through the platform HTTP client and display it through the core decoder.
1390/// The request is cancelled when the owning reactive scope is disposed.
1391#[cfg(feature = "http-image")]
1392pub fn http_image(url: impl Into<String>) -> day_pieces::AsyncImage {
1393    let source = day_reactive::Signal::new(None);
1394    let request = day_part_http::Request::get(url);
1395    let task = day_core::task(async move {
1396        if let Ok(response) = day_part_http::fetch_future(request).await
1397            && (200..300).contains(&response.status)
1398        {
1399            source.set(Some(std::sync::Arc::new(response.body)));
1400        }
1401    });
1402    day_reactive::Scope::current().on_cleanup(move || task.abort());
1403    day_pieces::async_image(source)
1404}