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