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