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