Skip to main content

day/
lib.rs

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