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