day-app 0.7.8

Declarative app development API using native UI toolkits
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
// Copyright © The Daybrite Project
// SPDX-License-Identifier: MPL-2.0

//! Day, the umbrella crate apps depend on. One backend feature per binary (§3.2).

#[cfg(any(
    all(feature = "appkit", feature = "gtk"),
    all(feature = "appkit", feature = "mock"),
    all(feature = "gtk", feature = "mock"),
    all(feature = "qt", feature = "appkit"),
    all(feature = "qt", feature = "gtk"),
    all(feature = "qt", feature = "mock"),
    all(feature = "xaml", feature = "appkit"),
    all(feature = "xaml", feature = "gtk"),
    all(feature = "xaml", feature = "qt"),
    all(feature = "xaml", feature = "mock"),
    all(feature = "dom", feature = "appkit"),
    all(feature = "dom", feature = "gtk"),
    all(feature = "dom", feature = "qt"),
    all(feature = "dom", feature = "xaml"),
    all(feature = "dom", feature = "mock"),
))]
compile_error!("day: enable exactly one backend feature");

pub use day_core::frame;
pub use day_core::{
    AnyPiece, Blocking, BlockingError, BuildCx, Piece, PieceSeq, TaskHandle, blocking_limit,
    blocking_threads, dark_mode, reduce_motion, safe_area, set_app_badge, set_appearance,
    size_class, sleep, spawn_blocking, system_color, task,
};
pub use day_core::{AssetDir, AssetName, FontFamily, ImageName, Resource, VectorName, resource};
/// Raster images from bytes (docs/images.md): decode an encoded PNG or JPEG the app already
/// holds (a download, a file the user picked, a paste) into the platform's image type, then
/// show it with `image(&bitmap)` or draw it with `Draw::image`.
///
/// `Bitmap` is a handle, not the pixels: they live in the toolkit and are released when the last
/// handle drops. Decoding is asynchronous because several backends decode off the main thread.
/// Probe `image_decode_support()` / `image_encode_support()` before offering an affordance that
/// depends on either, and `image_encode_formats()` before offering a format, since every
/// platform here reads more formats than it writes.
pub use day_core::{
    Bitmap, decode_image, decode_image_async, image_decode_support, image_encode_formats,
    image_encode_support,
};
/// Display-synchronized, cancellable frame callbacks for any UI client.
pub use day_core::{ElementId, IntoElementKey, id};
pub use day_core::{application_handlers, default_browser, open_url_with_application};
/// Programmatic navigation on the deep-link rail (docs/deep-links.md, docs/navigation.md):
/// route the app to `route`, buffered before the root is ready and applied after, exactly like
/// a cold launcher shortcut. The route grammar is what `day::routes!` keys and dayscript speak.
pub use day_core::{focus_search, request_route};
/// Tweening for canvas animations (docs/tween.md): `Lerp`, `Timing`, `animate`, `Tweened`.
pub use day_core::{testing, tween};
/// Optional app-local storage, including asynchronous browser storage.
#[cfg(feature = "fs")]
pub use day_part_filesystem as fs;
/// Optional app-controlled runtime permission requests.
#[cfg(feature = "permissions")]
pub use day_part_permissions as permissions;
/// Optional settings declaration and presentation layer.
#[cfg(feature = "settings")]
pub use day_piece_settings as settings;
/// Optional Apple SwiftUI hosting bridge.
#[cfg(feature = "swiftui")]
pub use day_piece_swiftui as swiftui;
/// Optional native styled-text editor.
#[cfg(feature = "text-editor")]
pub use day_piece_text_editor as texteditor;
#[cfg(feature = "text-editor")]
pub use day_piece_text_editor::{TextEditor, TextEditorBuilder, text_editor};
pub use day_pieces::{AsyncImage, AsyncImageBuilder, async_image};
/// Canvas export (docs/canvas.md "Exporting"): render a recorded `Drawing` to a bitmap or a PDF
/// through the toolkit's own painter. `canvas_exports()` says which of the two this target
/// offers; the PDF writer is native on AppKit, UIKit, GTK, Qt and Android only.
pub use day_pieces::{
    CanvasExports, Drawing, PdfDocument, RenderBitmap, RenderPdf, canvas_exports,
};
/// Sharing (docs/sharing.md): `Share::url(…)…present()`, with the app's own chooser actions.
pub use day_pieces::{Share, ShareAction, share_action, share_support};
pub use day_pieces::{colorpicker, combobox, datetime, pager, pullrefresh, searchfield, stepper};
/// The app's own data, cache and configuration directories, each a folder named after the app
/// id where its platform keeps that kind of file (docs/fs.md "Where files live"):
/// `day::storage::data_dir()` for a database or documents, `cache_dir()` for what can be fetched
/// again, `config_dir()` for a small settings file.
pub use day_process::storage;
pub use day_spec::AppBadge;
pub use day_spec::applications::{
    Application, ApplicationError, ApplicationHandlers, HandlerQuery,
};
/// An app-writable scratch directory. The OS temp dir is not app-writable on every target
/// (Android reports `getCacheDir()`), so a backend records the right location at startup and
/// this is how an app asks for it. For derived files an app can rebuild: rendered documents,
/// thumbnails, export staging.
pub use day_spec::present::app_temp_dir;
pub use day_spec::{
    BitmapId, BitmapInfo, EncodeSpec, ImageError, ImageFormat, ImageProperties, ImageSource,
};
pub use day_spec::{EXPORT_MAX_PIXELS, EXPORT_MAX_SIDE, ExportError, PdfInfo, PdfPage};
pub use day_spec::{KeyEvent, Modifiers};
/// The wall clock on every target: milliseconds or seconds since the Unix epoch, for timestamps
/// ("fetched at", "last synced"). `std::time::SystemTime::now()` aborts a web build, so app code
/// reads the time here. For elapsed time use the monotonic `day::frame::now_secs()`.
pub use day_spec::{now_epoch_millis, now_epoch_secs};
// Secondary windows (docs/windows.md): open/find windows, the kind that shapes their
// chrome, and the preferences/new-window registrations behind the auto menu items.
pub use day_core::{
    WindowHandle, check_for_updates, current_window, focused_window, initial_window, open_about,
    open_new_window, open_preferences, open_window, quit, register_about, register_about_window,
    register_check_for_updates, register_new_window, register_new_window_for, register_preferences,
    register_preferences_with, window_by_key, window_title,
};
// The app outside its windows (docs/status-item.md): progress on the Dock or taskbar icon, the
// macOS Dock icon, and whether the app outlives its last window. Status items themselves are
// `status_item(…)` in the prelude.
pub use day_core::{KeepRunning, set_app_progress, set_dock_visible, set_keep_running};
pub use day_spec::{AppProgress, StatusImage};
// Displays (docs/windows.md "Monitors") and launcher shortcuts set while the app runs
// (docs/deep-links.md).
pub use day_core::{monitors, set_launcher_shortcuts};
pub use day_spec::{LauncherShortcut, Monitor, SystemColor};
// Window properties (docs/windows.md) and chrome (docs/window-chrome.md): what a window's
// `state()` signal holds, how it stacks, how it joins macOS window tabs, and the frame and
// background it opens with.
pub use day_spec::{
    Attention, WindowBackground, WindowChrome, WindowKind, WindowLevel, WindowMaterial,
    WindowPlacement, WindowState, WindowTabbing,
};
/// The reactive core, whole (docs/async.md): `day::reactive::{Resource, Load}` for async data
/// loading. Namespaced because the prelude's `Resource` is the asset handle above, a different
/// type that predates the async one.
pub mod reactive {
    pub use day_reactive::*;
}

/// Persistent settings (docs/prefs.md): a small key/value string store backed by each platform's
/// native facility: `NSUserDefaults` on Apple, `SharedPreferences` on Android, a file store
/// elsewhere. `day::prefs::{get, set, remove, contains}`, plus `bind` to persist a `Signal` and
/// (with `model`) `bind_json` to persist a keyed store. `day::launch` installs it as the store
/// `.restore(key)` navigation survives a relaunch through (docs/navigation.md).
///
/// Promoted into the facade rather than left a satellite because it is what nearly every app
/// reaches for first, and because it is the one part that lives in the reactive layer. It stays
/// its own crate (`day-part-preferences`), so existing `day_part_preferences::…` paths keep working; this is
/// the same API under a shorter name. Opt out with `default-features = false`.
/// The per-property observable store (docs/model.md): `Store`/`Keyed`/`Elem`/`Field`, the
/// change log, and the `#[derive(Observable)]` accessors' machinery.
#[cfg(feature = "model")]
pub mod model {
    pub use day_model::*;
}

pub use day_core::{install_edit_bridge, invoke_edit};
pub use day_spec::EditState;
/// MIME-typed text and binary clipboard data, with async browser support.
pub mod clipboard {
    pub use day_part_clipboard::*;
}
pub use day_spec::EditOp;

/// Wire a [`model::UndoStack`] to the platform: native fronts (the stock Edit menu, ⌘Z,
/// iOS's three-finger gestures) where the toolkit has them, and the stack's own signals for
/// the app's buttons everywhere (docs/model.md). One call, after the stack exists.
#[cfg(feature = "model")]
pub fn install_undo(stack: &day_model::UndoStack) {
    let s = stack.clone();
    day_core::install_undo_bridge(
        stack.can_undo(),
        stack.can_redo(),
        stack.undo_label(),
        stack.redo_label(),
        move |redo| {
            if redo {
                s.redo();
            } else {
                s.undo();
            }
        },
    );
}

/// Wire the app's shape/object Cut/Copy/Paste to the platform's own edit commands
/// (docs/menus.md): the same menu items, shortcuts, and responder precedence text editing
/// uses. A focused text field keeps its clipboard behavior; everything else reaches these
/// handlers. `can_copy` is a tracked read (drive it from your selection); `copy`/`cut`
/// return the serialized payload (its format is the app's: Day-Sketch uses SVG), which day
/// places on the system clipboard; `paste` receives the text the clipboard holds, falling back
/// to the payload this app last placed there when the platform answers nothing (docs/menus.md).
/// Menu items come from `menu_role(MenuRole::Cut/Copy/Paste)`.
pub fn install_edit_commands(
    can_copy: impl Fn() -> bool + 'static,
    copy: impl Fn() -> Option<String> + 'static,
    cut: impl Fn() -> Option<String> + 'static,
    paste: impl Fn(&str) + 'static,
    select_all: impl Fn() + 'static,
) {
    // What this app last put on the clipboard. Reading the clipboard is a privilege on
    // Android (only the app holding input focus is granted it, docs/clipboard.md), and
    // writing to it raises a system overlay, so a Paste moments after a Copy can be
    // refused the very payload this app just wrote, and `get_text` answers `None`. The
    // platform read is still what a Paste asks first, so a clip from another app always
    // wins; this is only what an app's own Cut/Copy ▸ Paste falls back to when the platform
    // hands back nothing.
    let ours: std::rc::Rc<std::cell::RefCell<Option<String>>> = std::rc::Rc::default();
    let (copied, pasted) = (ours.clone(), ours);
    let place = move |payload: String| {
        let _ = day_part_clipboard::set_text(&payload);
        *copied.borrow_mut() = Some(payload);
    };
    day_core::install_edit_bridge(
        move || {
            let can = can_copy();
            day_spec::EditState {
                can_cut: can,
                can_copy: can,
                can_paste: true,
                can_select_all: true,
            }
        },
        move |op| match op {
            day_spec::EditOp::Copy => {
                if let Some(payload) = copy() {
                    place(payload);
                }
            }
            day_spec::EditOp::Cut => {
                if let Some(payload) = cut() {
                    place(payload);
                }
            }
            day_spec::EditOp::Paste => {
                // An empty read is nothing to paste. It is also how a refusal reaches this
                // layer, since the Android arm answers `""` for a clip it was not allowed to
                // look at.
                let text = day_part_clipboard::get_text()
                    .filter(|t| !t.is_empty())
                    .or_else(|| {
                        let ours = pasted.borrow().clone();
                        if ours.is_some() {
                            log::warn!(
                                "clipboard read came back empty — pasting what this app last \
                                 copied (docs/clipboard.md)"
                            );
                        }
                        ours
                    });
                if let Some(text) = text {
                    paste(&text);
                }
            }
            day_spec::EditOp::SelectAll => select_all(),
        },
    );
}

/// The keyboard modifiers held right now, for interactions whose meaning they change
/// (shift-click adds to a selection instead of replacing it). Touch platforms answer
/// all-false; a dayscript step's declared modifiers take precedence while it dispatches.
#[must_use]
pub fn modifiers() -> day_spec::Modifiers {
    day_core::modifiers()
}

#[cfg(feature = "prefs")]
pub mod prefs {
    pub use day_part_preferences::*;

    /// Install the preferences as the app's navigation-persistence store (docs/navigation.md), so
    /// a `nav` or `nav_stack` marked `.restore(key)` remembers its state across launches (and
    /// across an Android process death, since the store is disk-backed). `day::launch` calls it
    /// when the app has installed no store of its own. Nav keys are namespaced under a `day.nav.`
    /// prefix, so `.restore("mail")` never collides with the app's own [`set`]/[`get`] keys.
    ///
    /// The adapter lives here, where the preferences and the navigation core meet, so the
    /// preferences part itself needs no UI dependency.
    pub fn install_nav_store() {
        struct PrefsNavStore;

        impl day_core::NavStore for PrefsNavStore {
            fn load(&self, key: &str) -> Option<String> {
                get(&format!("day.nav.{key}"))
            }
            fn save(&self, key: &str, value: &str) {
                let _ = set(&format!("day.nav.{key}"), value);
            }
        }

        day_core::set_nav_store(std::rc::Rc::new(PrefsNavStore));
    }

    /// Keep a keyed store in the preferences as one JSON array (docs/prefs.md): seed `store`
    /// from the rows saved under `key` now, then save every later change, an edited field as
    /// well as an insert, removal or move. A missing or unreadable value leaves the store as it
    /// is, and a failed read or write is logged. Call it once, right after creating the store;
    /// the saving reaction lives in the current reactive scope.
    ///
    /// Preferences suit a small list. A larger or relational document belongs in
    /// `day-persistence`.
    ///
    /// ```ignore
    /// let items = Store::new(Keyed::default());
    /// day::prefs::bind_json("app.items", items);
    /// ```
    #[cfg(feature = "model")]
    pub fn bind_json<T>(key: &str, store: day_model::Store<day_model::Keyed<T>>)
    where
        T: day_model::Identified + Clone + serde::Serialize + serde::de::DeserializeOwned,
    {
        use day_model::Source;

        if let Some(json) = get(key) {
            match serde_json::from_str::<Vec<T>>(&json) {
                Ok(rows) => store.update("load", |k| *k = day_model::Keyed::new(rows)),
                Err(error) => log::warn!("could not read `{key}` from preferences: {error}"),
            }
        }
        let key = key.to_owned();
        // Track the whole store, then serialize untracked in the reaction.
        day_reactive::watch(
            move || store.with(|_| ()),
            move |_, _| match store.with_untracked(|k| serde_json::to_string(k.items())) {
                Ok(json) if set(&key, &json) => log::debug!("saved `{key}` to preferences"),
                Ok(_) => log::warn!("could not save `{key}` to preferences"),
                Err(error) => log::warn!("could not encode `{key}`: {error}"),
            },
        );
    }
}
// Localization text source + arg trait (§12) at the crate root so generated `res::str::<key>(…)`
// functions can name `day::LocalizedText` / `day::tr` / `day::IntoFArg` (also in the prelude).
pub use day_core::{lifecycle_supported, on_lifecycle};

/// Pointer shapes for the `.cursor()` decorator (docs/cursor.md).
///
/// [`Cursor`](day_spec::Cursor) itself is in the prelude; this module carries the shapes only
/// one toolkit names, each behind that toolkit's feature, so `day::cursor::appkit::DRAG_COPY`
/// is a compile error in a GTK build rather than a silent arrow. Wrap a use in the same
/// `#[cfg(feature = "…")]` the constant carries. Every constant is a [`Cursor::Native`](day_spec::Cursor::Native) value:
/// the named backend resolves it by its own table and any other backend ignores it.
pub mod cursor {
    pub use day_spec::Cursor;

    /// AppKit's own shapes (`NSCursor`), beyond the shared vocabulary.
    #[cfg(feature = "appkit")]
    pub mod appkit {
        use day_spec::Cursor;
        /// The poof shown when dragging an item somewhere it will be removed.
        pub const DISAPPEARING_ITEM: Cursor = Cursor::native("disappearingItem");
        /// The arrow with a green plus badge shown during a copy drag.
        pub const DRAG_COPY: Cursor = Cursor::native("dragCopy");
        /// The arrow with a link badge shown during an alias drag.
        pub const DRAG_LINK: Cursor = Cursor::native("dragLink");
        /// The arrow with a menu badge, for content with a contextual menu.
        pub const CONTEXTUAL_MENU: Cursor = Cursor::native("contextualMenu");
        /// The I-beam for vertical text layout.
        pub const I_BEAM_VERTICAL: Cursor = Cursor::native("IBeamCursorForVerticalLayout");
    }

    /// Qt's own shapes (`Qt::CursorShape`), beyond the shared vocabulary.
    #[cfg(feature = "qt")]
    pub mod qt {
        use day_spec::Cursor;
        /// The arrow with a question mark (`Qt::WhatsThisCursor`).
        pub const WHATS_THIS: Cursor = Cursor::native("WhatsThisCursor");
        /// The arrow with a spinner beside it (`Qt::BusyCursor`).
        pub const BUSY: Cursor = Cursor::native("BusyCursor");
        /// A plain upward arrow (`Qt::UpArrowCursor`).
        pub const UP_ARROW: Cursor = Cursor::native("UpArrowCursor");
        /// Horizontal splitter (`Qt::SplitHCursor`).
        pub const SPLIT_H: Cursor = Cursor::native("SplitHCursor");
        /// Vertical splitter (`Qt::SplitVCursor`).
        pub const SPLIT_V: Cursor = Cursor::native("SplitVCursor");
    }

    /// Windows' own shapes (`IDC_*`), beyond the shared vocabulary.
    #[cfg(feature = "xaml")]
    pub mod xaml {
        use day_spec::Cursor;
        /// The person cursor (`IDC_PERSON`, Windows 10 1809 and up).
        pub const PERSON: Cursor = Cursor::native("person");
        /// The location-pin cursor (`IDC_PIN`, Windows 10 1809 and up).
        pub const PIN: Cursor = Cursor::native("pin");
        /// A plain upward arrow (`IDC_UPARROW`).
        pub const UP_ARROW: Cursor = Cursor::native("uparrow");
        /// The arrow with a small hourglass (`IDC_APPSTARTING`), Windows' progress shape.
        pub const APP_STARTING: Cursor = Cursor::native("appstarting");
    }

    /// Android's own shapes (`PointerIcon.TYPE_*`), beyond the shared vocabulary.
    #[cfg(feature = "material")]
    pub mod android {
        use day_spec::Cursor;
        /// Four-way scroll (`TYPE_ALL_SCROLL`).
        pub const ALL_SCROLL: Cursor = Cursor::native("all_scroll");
        /// The no-drop shape (`TYPE_NO_DROP`), distinct from not-allowed.
        pub const NO_DROP: Cursor = Cursor::native("no_drop");
        /// Diagonal resize, top-right to bottom-left (`TYPE_TOP_RIGHT_DIAGONAL_DOUBLE_ARROW`).
        pub const TOP_RIGHT_DIAGONAL: Cursor = Cursor::native("top_right_diagonal_double_arrow");
        /// Diagonal resize, top-left to bottom-right (`TYPE_TOP_LEFT_DIAGONAL_DOUBLE_ARROW`).
        pub const TOP_LEFT_DIAGONAL: Cursor = Cursor::native("top_left_diagonal_double_arrow");
    }
}
pub use day_localization_ui::{IntoFArg, IntoNumberFArg, LocalizedText, res, tr};

/// The `log` crate itself, for an app that needs more than the macros (a `LevelFilter`, a custom
/// `log::Log`). Re-exported by name so `use day::prelude::*` is enough, the same rule the model
/// re-export follows.
pub use ::log;
/// Raise or lower the level Day's default logger emits, at runtime. `DAY_LOG` sets it at startup
/// on native targets; the web launch path reads `?DAY_LOG=` from the page URL.
pub use day_core::set_log_level;
/// Logging (docs/logging.md). `day::info!("…")` and friends are the `log` crate's macros,
/// re-exported so an app needs no `log` dependency of its own for the common case. Because they
/// are `log`'s, anything that speaks `log` (`env_logger`, `tracing-log`, a hand-written
/// `log::Log`) works without adapters.
///
/// Day installs a default logger at launch, so these come out with no setup on every platform:
/// stderr natively, the browser console on web-dom. An app that wants something else calls
/// `log::set_logger` (or `env_logger::init()`) before `day::launch` and keeps it.
pub use log::{debug, error, info, log_enabled, trace, warn};

/// A PNG of this window, as the app itself sees it (docs/window-image.md).
///
/// The same capture the dayscript `screenshot` step takes, offered to the app: the window's
/// content (what Day drew) without the platform's chrome around it. [`WindowImage::chrome`]
/// asks for the chrome as well.
///
/// Synchronous, because every backend that can do this at all has a synchronous way to: an
/// offscreen render on the desktop toolkits, `UIGraphicsImageRenderer` on UIKit, `View.draw` on
/// Android, `componentSnapshot.getSync` on ArkUI. Feed the bytes straight to
/// [`save_file`](day_pieces::save_file), which is the async half.
///
/// ```no_run
/// # use day::prelude::*;
/// day::task(async move {
///     if let Ok(png) = day::window_image().capture() {
///         let _ = save_file(png).suggested_name("shot.png").filter("PNG", &["png"]).await;
///     }
/// });
/// ```
///
/// `Err` where the toolkit cannot rasterize its window: today only web-dom, which would need
/// a rasterizer shipped with it. Ask [`window_image_support`] first when the answer decides
/// whether to show a button at all.
pub fn window_image() -> WindowImage {
    WindowImage { chrome: false }
}

/// Whether this toolkit can hand the app a picture of its own window (`Cap::Snapshot`).
#[must_use]
pub fn window_image_support() -> day_spec::Support {
    day_core::with_tree(|t| t.window_image_support())
}

// The platform font list and canvas text measurement (docs/fonts.md): `font_families()` is
// cached for the process, `measure_text()` always answers (approximating where a toolkit
// cannot measure). Probe `Cap::FontList` before offering a font menu.
pub use day_core::{font_families, measure_text};
// The measurement memo (docs/fonts.md "It is cached"): a diagnostic pair. Nothing in day needs
// `clear_text_metrics_cache`; it is for an app that registers a face while running.
pub use day_core::{TextMetricsCacheStats, clear_text_metrics_cache, text_metrics_cache_stats};

/// The request built by [`window_image`].
#[derive(Clone, Copy, Debug)]
pub struct WindowImage {
    chrome: bool,
}

impl WindowImage {
    /// Include the window's chrome: title bar, toolbar, whatever the platform draws around
    /// the content. A backend with nothing to add (or no way to separate the two) answers with
    /// the content capture rather than failing.
    #[must_use]
    pub fn chrome(mut self) -> Self {
        self.chrome = true;
        self
    }

    /// Take the picture.
    ///
    /// # Errors
    ///
    /// Returns the toolkit's message when it cannot capture the window.
    pub fn capture(self) -> Result<Vec<u8>, String> {
        day_core::with_tree(|t| {
            if self.chrome {
                t.snapshot_chrome()
            } else {
                t.snapshot()
            }
        })
    }
}

/// An app-environment value, portably: the process environment on native targets, the page
/// URL's query string on web-dom (where a browser sandbox has no process environment;
/// `day launch --env K=V` forwards each pair as a query parameter, docs/web.md). Prefer this
/// over `std::env::var` for anything a `--env` flag should be able to set on every target.
#[must_use]
pub fn env(key: &str) -> Option<String> {
    #[cfg(all(target_arch = "wasm32", feature = "dom"))]
    {
        day_toolkit_dom::host_env(key)
    }
    #[cfg(not(all(target_arch = "wasm32", feature = "dom")))]
    {
        std::env::var(key).ok()
    }
}
// Same reason: the generated `res::locales::install()` names `day::install_locales` (§18.5).
pub use day_localization_ui::install as install_locales;
pub use day_localization_ui::{Catalog, FArg, format_catalog, register_catalog, tr_in};
// Locale-aware comparison/sorting (docs/localization.md "Sorting"): icu4x collation, so e.g. a
// Chinese list sorts by pinyin. `compare` and `sort_localized` track the locale signal.
pub use day_localization_ui::{compare, compare_in, sort_localized};
// Locale-aware number formatting (docs/localization.md "Numbers outside a message"): the same
// icu4x formatter `NUMBER()` uses, for the values that have no message to hang on: an axis label,
// a table column, a readout. `format_decimal` tracks the locale signal.
pub use day_localization_ui::{format_decimal, format_decimal_in};
// Percentages and dates the same way (docs/localization.md "Numbers outside a message", "Dates
// outside a message"): `format_percent` puts the sign where the locale does (`50 %` in French),
// `format_date` writes an instant's chosen fields in the locale's own form and hour cycle.
pub use day_localization_ui::{
    DateFields, format_date, format_date_in, format_percent, format_percent_in,
};
// Search matching (docs/localization.md "Searching"): case-insensitive, at the start of any
// word, with words found by the locale's own segmentation. `matches_search` tracks the locale.
pub use day_localization_ui::{matches_search, matches_search_in};
// The current-locale Signal itself, for apps that show or branch on it (`locale().get()` is a
// tracked read; `set_locale` in the prelude writes it).
pub use day_localization_ui::locale;
// The OS's whole ordered language preference, for content an app selects by language
// rather than translates: `locale` above is only the one its catalogs serve.
pub use day_localization_ui::launch_locales;
// Tweaks (docs/tweaks.md): the realized-node id, the size-invalidation hook for native
// mutations Day can't see, and the retained ref live in the prelude via day-pieces.
pub use day_core::{RNode, invalidate_size};
pub use day_pieces::Command;
pub use day_pieces::NativeRef;
// Typed routes (docs/navigation.md): `day::routes! { enum Section { Home => "home", … } }`.
/// Tests that run inside the built app (docs/testing.md): `#[day::test]`, [`Case`], [`Drive`].
pub use day_core::conformance;
pub use day_core::conformance::{Case, Drive, Fail, TestResult};
/// WASM registration implementation used by `#[day::test]`.
#[cfg(target_arch = "wasm32")]
#[doc(hidden)]
pub use day_core::inventory;
pub use day_core::linkme;
/// The link-time registry `day-build`'s generated code adds the app's `[[shortcuts]]` to
/// (docs/deep-links.md "Launcher shortcuts"); not for app code.
#[doc(hidden)]
#[cfg(not(target_arch = "wasm32"))]
pub use day_core::shortcuts::LAUNCHER_SHORTCUTS;
/// `#[day::builder(FooBuilder)]`: a piece's builder trait, generated from its inherent impl
/// (docs/api-style.md "Typed builders and erasure").
pub use day_macros::builder;
pub use day_macros::test;
/// The built-in pieces' own cases and the conformance app's content (docs/testing.md).
#[cfg(feature = "conformance")]
pub use day_pieces::conformance as builtin_tests;
pub use day_pieces::routes;
/// The root of an app's test build: the app's content, or the driven case's page alone.
pub use day_pieces::test_host;
pub use day_spec::{Lifecycle, WindowOptions};

/// dayscript **recording** and **action logging** (docs/dayscript.md "Recording", DESIGN §14.6):
/// install an observer that sees the user's taps, edits, selections, and navigation.
/// `day::record::{start, start_into, start_to_file, stop, is_recording, recording_signal, script,
/// steps, save, clear, exclude_prefix}` captures them into a replayable dayscript; a recorder also
/// arms headlessly from `day launch --record <file>` (the `DAY_RECORD` env, honored inside
/// `day_script::init`). What it records is an ordinary dayscript, so it replays cross-toolkit
/// through [`play_script`] or `day launch -t <target> --script <file>`.
///
/// `day::record::log_actions(true)` (or `DAY_LOG_ACTIONS=1`) turns on the narration alone: every
/// action echoed to stdout in the same vocabulary, keeping nothing:
///
/// ```text
/// dayscript ▸ navigate → dates  "Date & time"
/// dayscript ▸ tap list-shuffle  "Shuffle"
/// ```
pub mod record {
    pub use day_script::record::*;
}

/// Replay a dayscript against the running app, in-process (docs/dayscript.md "Recording"): parse
/// `yaml` and run each step through the embedded engine, on the main thread between flushes, the
/// same executor `day launch --script` drives. Returns an error while a recording is live (a replay
/// must not record itself) and on web (no background thread; drive the page over the WebSocket
/// transport there). See [`record`].
///
/// # Errors
///
/// Returns a message when a recording is live, a script is already playing, the script does
/// not parse or has no steps, or the target is web.
pub fn play_script(yaml: &str) -> Result<(), String> {
    day_script::play(yaml)
}

/// The display name of the toolkit compiled into this binary: `"AppKit"`, `"GTK"`, `"Qt"`,
/// `"UIKit"`, `"Material Components"`, `"XAML"`, `"WinUI"`, `"ArkUI"`, `"DOM"` (or `"Mock"`). Handy for a window
/// title that names its backend.
#[must_use]
pub const fn toolkit_name() -> &'static str {
    #[cfg(feature = "appkit")]
    {
        return "AppKit";
    }
    #[cfg(feature = "gtk")]
    {
        return "GTK";
    }
    #[cfg(feature = "qt")]
    {
        return "Qt";
    }
    #[cfg(feature = "uikit")]
    {
        return "UIKit";
    }
    #[cfg(feature = "material")]
    {
        return "Material Components";
    }
    // `winui` implies `xaml` (same backend), so it is asked first.
    #[cfg(feature = "winui")]
    {
        return "WinUI";
    }
    #[cfg(all(feature = "xaml", not(feature = "winui")))]
    {
        return "XAML";
    }
    #[cfg(feature = "arkui")]
    {
        return "ArkUI";
    }
    #[cfg(feature = "dom")]
    {
        return "DOM";
    }
    #[allow(unreachable_code)]
    {
        "Mock"
    }
}

pub mod prelude {
    pub use day_core::{ElementId, IntoElementKey, id};
    pub use day_localization_ui::{
        LocalizedText, install as install_locales, matches_search, set_locale, sort_localized, tr,
    };
    #[cfg(feature = "text-editor")]
    pub use day_piece_text_editor::{TextEditor, TextEditorBuilder, text_editor};
    pub use day_pieces::prelude::*;
    pub use day_spec::{Lifecycle, Size, WindowOptions};
    // Canvas drawing vocabulary (docs/canvas.md): arbitrary paths and their fill rule, the
    // stroke style a dashed or round-capped line needs, and per-corner radii for
    // `Shape::rounded_rect`.
    pub use day_spec::{CornerRadii, FillRule, LineCap, LineJoin, Path, PathSeg, StrokeStyle};
    // SVG path data to a `PathBuilder` chain, at compile time (docs/canvas.md).
    pub use day_macros::build_path;
    // The observable store (docs/model.md). The crate itself is re-exported by name because the
    // derive's generated code says `day_model::…`; this is what makes `use day::prelude::*`
    // enough. day-model's `Path` stays out: the prelude's `Path` is the canvas one.
    #[cfg(feature = "model")]
    pub use ::day_model;
    #[cfg(feature = "model")]
    #[doc(no_inline)]
    pub use ::day_model::Uuid;
    #[cfg(feature = "model")]
    pub use ::day_model::{Elem, Field, Key, Keyed, ModelId, Source, Store};
    #[cfg(feature = "model")]
    pub use day_macros::Observable;
    pub use day_spec::Point;
    // Logging (docs/logging.md): `info!`/`warn!`/`error!`/`debug!`/`trace!` with no setup and no
    // `log` dependency in the app's own Cargo.toml. These are `log`'s macros, so an app that later
    // installs `env_logger` or `tracing` keeps every call site it already wrote.
    pub use super::{debug, error, info, log, log_enabled, set_log_level, trace, warn};
    pub use {super::lifecycle_supported, super::on_lifecycle};
    // Bundled-resource random-access API (§18.3): `resource("name")` -> `Resource`.
    pub use day_core::{
        AssetDir, AssetName, FontFamily, ImageName, Resource, VectorName, resource,
    };
    pub use day_spec::present::app_temp_dir;
    // Toolkit capability probe (docs): lets app/piece content adapt to the backend, e.g. skip a
    // title the native nav already shows (`Cap::NavHeader`). `capability(cap) -> Support`.
    pub use day_core::capability;
    // Safe-area insets (docs/layout.md): zero everywhere except edge-to-edge backends. Pad
    // content by it where a background runs under the system bars.
    pub use day_core::safe_area;
    // The window's size class (docs/size-classes.md): what a `nav()` host resolves its own
    // presentation from, and what an app lays out from when it wants to make the same call:
    // two columns on a wide window, one on a narrow one. `None` on a backend that reports no
    // geometry. Tracked, so a piece reading it rebuilds when the window crosses a breakpoint.
    pub use day_core::size_class;
    pub use day_spec::{Cap, Cursor, HeightClass, SizeClass, Support, WidthClass};
    // Layout direction (docs/localization): `is_rtl()` lets a piece mirror its own drawing under
    // a right-to-left locale; the layout engine mirrors placement, but a `canvas` owns its
    // coordinates.
    pub use day_core::{is_rtl, layout_direction};
    pub use day_spec::LayoutDirection;
}

/// App-lifecycle support for the backend compiled into this binary (docs/lifecycle.md).
///
/// Register handlers with [`on_lifecycle`]; guard phases a platform may not deliver either at runtime
/// (`if day::lifecycle::supported(p) { … }`) or at compile time with [`require_lifecycle!`].
pub mod lifecycle {
    pub use day_core::{lifecycle_supported, on_lifecycle};
    pub use day_spec::Lifecycle;

    /// Does the backend compiled into this binary deliver `phase`? A `const fn`, so it drives both a
    /// runtime guard and the compile-time [`crate::require_lifecycle!`] assertion. Agrees with the
    /// runtime [`day_core::lifecycle_supported`] once the app is running.
    #[must_use]
    pub const fn supported(phase: Lifecycle) -> bool {
        #[cfg(feature = "appkit")]
        {
            return day_toolkit_appkit::lifecycle_supported(phase);
        }
        #[cfg(feature = "gtk")]
        {
            return day_toolkit_gtk::lifecycle_supported(phase);
        }
        #[cfg(feature = "qt")]
        {
            return day_toolkit_qt::lifecycle_supported(phase);
        }
        #[cfg(all(feature = "uikit", target_os = "ios"))]
        {
            return day_toolkit_uikit::lifecycle_supported(phase);
        }
        #[cfg(all(feature = "material", target_os = "android"))]
        {
            return day_toolkit_material::lifecycle_supported(phase);
        }
        #[cfg(all(feature = "xaml", windows))]
        {
            return day_toolkit_winui::lifecycle_supported(phase);
        }
        #[cfg(all(feature = "arkui", target_env = "ohos"))]
        {
            return day_toolkit_arkui::lifecycle_supported(phase);
        }
        // No concrete backend (mock, or a mobile backend compiled for the host to check): the
        // universal phases are always deliverable.
        #[allow(unreachable_code)]
        {
            phase.is_universal()
        }
    }
}

/// Compile-time assert that the backend in this binary delivers `$phase`, else a build error. Use it
/// to make a hard dependency on a platform-specific phase explicit:
/// `day::require_lifecycle!(day::Lifecycle::DidEnterBackground);` fails to compile on desktop.
/// For soft handling, guard with [`lifecycle::supported`] / [`lifecycle_supported`] instead.
#[macro_export]
macro_rules! require_lifecycle {
    ($phase:expr) => {
        const {
            ::core::assert!(
                $crate::lifecycle::supported($phase),
                "this Day backend does not deliver that lifecycle phase (see docs/lifecycle.md)",
            )
        }
    };
}

/// Launch through an external toolkit's backend (docs/extending.md "External toolkits"): the
/// cfg-free counterpart of the feature-gated `launch` entries below, for platform-toolkit pairs
/// registered via `[package.metadata.day.toolkit]`. Feature-independent because `day build
/// -t <external>` compiles the app with only the external toolkit's feature, so none of the
/// launchers below exist in that build. Starts the dayscript engine exactly as they do, which
/// is what keeps `day launch --script`, `day drive`, and the session registry working on a
/// backend this repository has never heard of.
pub fn launch_external<P: day_spec::Platform, R: Piece>(
    backend: P,
    options: WindowOptions,
    root: impl FnOnce() -> R + 'static,
) {
    day_script::init();
    start(backend, options, root);
}

/// Start `backend`, seeding the ambient locale first.
///
/// The order matters: the OS's language preference has to reach day-localization before the app's
/// `res::locales::install()` runs, and that call lives inside the root builder, so the hints
/// are read from the live backend here, one step before it is handed the root. Without this
/// step `Toolkit::locale_hints` is a trait method nobody calls, and every native app opens in its
/// default language whatever the device is set to (docs/localization.md).
// Every caller is a `launch` behind its own backend feature (§3.2), so a featureless
// `cargo check -p day` (which is what a bare workspace check builds) has none of them and would
// otherwise report this as dead. Listing the backends here instead would be a second copy of the
// cfg set below, drifting the first time one is added.
#[allow(dead_code)]
fn start<P: day_spec::Platform, R: Piece>(
    backend: P,
    mut options: WindowOptions,
    root: impl FnOnce() -> R + 'static,
) {
    day_localization_ui::add_launch_locales(&backend.locale_hints());
    // `.restore(key)` surfaces persist through the preferences unless the app installed a
    // store of its own (docs/navigation.md).
    #[cfg(feature = "prefs")]
    if !day_core::has_nav_store() {
        prefs::install_nav_store();
    }
    // The app's catalog, now that the hints are in: registering it here rather than inside the
    // root builder is what lets a title, drawn before any piece exists, come out of the
    // catalog too (docs/localization.md).
    if let Some((default, catalog)) = options.locales {
        day_localization_ui::install(default, catalog);
    }
    if let Some(f) = options.title_fn {
        options.title = f();
    }
    day_core::launch_with(backend, options, move || AnyPiece::new(root()));
}

/// Launch the app on the selected backend (blocks; owns the native main loop).
#[cfg(feature = "appkit")]
pub fn launch<P: Piece>(options: WindowOptions, root: impl FnOnce() -> P + 'static) {
    day_script::init();
    start(day_toolkit_appkit::AppKit::new(), options, root);
}

#[cfg(feature = "gtk")]
pub fn launch<P: Piece>(options: WindowOptions, root: impl FnOnce() -> P + 'static) {
    day_script::init();
    start(day_toolkit_gtk::Gtk::new(), options, root);
}

#[cfg(feature = "qt")]
pub fn launch<P: Piece>(options: WindowOptions, root: impl FnOnce() -> P + 'static) {
    day_script::init();
    start(day_toolkit_qt::Qt::new(), options, root);
}

#[cfg(all(feature = "uikit", target_os = "ios"))]
pub fn launch<P: Piece>(options: WindowOptions, root: impl FnOnce() -> P + 'static) {
    day_script::init();
    start(day_toolkit_uikit::Uikit::new(), options, root);
}

#[cfg(all(feature = "xaml", windows))]
pub fn launch<P: Piece>(options: WindowOptions, root: impl FnOnce() -> P + 'static) {
    day_script::init();
    start(day_toolkit_winui::Xaml::new(), options, root);
}

#[cfg(all(feature = "dom", target_arch = "wasm32"))]
pub fn launch<P: Piece>(options: WindowOptions, root: impl FnOnce() -> P + 'static) {
    // No day_script::init(): dayscript's TCP transport has no wasm equivalent yet
    // (a WebSocket transport is planned; see docs/web.md).
    start(day_toolkit_dom::Dom::new(), options, root);
}

#[cfg(feature = "mock")]
pub fn launch<P: Piece>(options: WindowOptions, root: impl FnOnce() -> P + 'static) {
    let (mock, _probe) = day_mock::MockToolkit::new();
    start(mock, options, root);
}

// ---------------------------------------------------------------------------
// App entry macros (§17.4): the mobile shells bind fixed exported symbols
// (Runner/main.swift → `day_main`; dev.daybrite.day.bridge.DayBridge → `Java_…` natives).
// These expand to that glue so an app's lib.rs carries one line per platform.
// Both emit nothing off their target OS, so apps invoke them unconditionally.
// ---------------------------------------------------------------------------

/// `options` with [`WindowOptions::version`] set to the calling crate's `CARGO_PKG_VERSION` when
/// the app left it unset: the version Day's exit line names (docs/lifecycle.md). A macro, because
/// only code expanded in the app crate can read the app's own package version; the `day_start!`
/// entries route their options through it, so a mobile host names its version without the app
/// doing anything.
#[doc(hidden)]
#[macro_export]
macro_rules! with_app_version {
    ($options:expr) => {{
        let mut options: $crate::WindowOptions = $options;
        if options.version.is_none() {
            options.version =
                ::core::option::Option::Some(::core::env!("CARGO_PKG_VERSION").into());
        }
        options
    }};
}

/// One entry point for every platform that needs one: the single line an app's `lib.rs` carries
/// instead of one macro per platform.
///
/// ```ignore
/// day::day_start!("My App", root);    // or: day::day_start!(root);
/// ```
///
/// It expands to every platform macro below. Each of those is gated on its own target
/// (`ios` / `macos` / `android` / the `ohos` env / `wasm32`), and those gates are mutually
/// exclusive, so exactly one survives a given build, and none at all on a plain cargo desktop
/// build, where `src/main.rs` is the entry instead.
///
/// The title reaches the platforms that have nowhere else to get one. Android and HarmonyOS take
/// their label from the app manifest (`android:label`, `app_name` in `string.json`) rather than
/// from Rust, so they accept the argument and ignore it; passing it here keeps one call site for
/// every target instead of making the caller remember which two are different.
#[macro_export]
macro_rules! day_start {
    ($root:expr) => {
        $crate::day_start!("", $root);
    };
    // The full description, shared with `src/main.rs` so both entry points open the same window
    // and perform the same ceremony: `options: window()` rather than a bare title. The literal
    // `options:` is what tells this arm apart from the title one below.
    (options: $options:expr, $root:expr) => {
        $crate::day_start_ios!(options: $options, $root);
        $crate::day_start_macos!(options: $options, $root);
        $crate::day_start_android!(options: $options, $root);
        $crate::day_start_arkui!(options: $options, $root);
        $crate::day_start_web!(options: $options, $root);
    };
    ($title:expr, $root:expr) => {
        $crate::day_start_ios!($title, $root);
        $crate::day_start_macos!($title, $root);
        $crate::day_start_android!($root);
        $crate::day_start_arkui!($root);
        $crate::day_start_web!($title, $root);
    };
}

/// Surface the resources `day-build` generated for this crate as `pub mod res` (§18.5).
///
/// ```ignore
/// day::resources!();   // then: res::str::app_title(), res::images::logo, res::locales::CATALOG
/// ```
///
/// Expands to the `include!` of `$OUT_DIR/day_resources.rs`, so the crate needs the `day-build`
/// build script that writes it; an app with no `build.rs` has no `OUT_DIR` and should not call
/// this. Kept separate from [`day_start!`] because entry points are per-target `cfg`, while
/// `res` has to exist on every build, including the desktop one whose entry is `src/main.rs`.
#[macro_export]
macro_rules! resources {
    () => {
        /// Typed constants for the files under `resource/`, generated at build time by
        /// `day-build` (§18.5): `res::images::<stem>`, `res::assets::<file>`,
        /// `res::fonts::<family>`, `res::str::<key>()`, and the `res::locales` catalog.
        /// Reference bundled resources through these (`image(res::images::logo)`) so a
        /// typo is a compile error and the resource is guaranteed present. Drop a file into
        /// `resource/images/` and its constant appears on the next build.
        pub mod res {
            include!(concat!(env!("OUT_DIR"), "/day_resources.rs"));
        }
    };
}

/// Expands to the `day_main` C export the iOS Runner's `main.swift` calls
/// (`@_silgen_name("day_main")`). The optional title is currently unused on
/// iOS (the window fills the screen bounds); accepted for future window-scene use.
///
/// Apps normally reach this through [`day_start!`] rather than calling it directly.
///
/// ```ignore
/// day::day_start_ios!(root);              // or: day::day_start_ios!("My App", root);
/// ```
#[macro_export]
macro_rules! day_start_ios {
    ($root:expr) => {
        $crate::day_start_ios!("", $root);
    };
    (options: $options:expr, $root:expr) => {
        /// iOS entry: the Runner's main.swift calls this from the app staticlib (§17.4).
        #[cfg(target_os = "ios")]
        #[unsafe(no_mangle)]
        pub extern "C" fn day_main() {
            $crate::launch($crate::with_app_version!($options), $root);
        }
    };
    ($title:expr, $root:expr) => {
        $crate::day_start_ios!(
            options: $crate::WindowOptions::default().title($title),
            $root
        );
    };
}

/// Expands to the `day_main` C export the macOS Runner's `main.swift` calls, the
/// `platform/macos/` Xcode host project's entry (§17.4). The cargo-driven build keeps using
/// the app's own `src/main.rs`; both paths call the same [`launch`], so the app behaves
/// identically however it was built.
///
/// ```ignore
/// day::day_start_macos!(root);            // or: day::day_start_macos!("My App", root);
/// ```
#[macro_export]
macro_rules! day_start_macos {
    ($root:expr) => {
        $crate::day_start_macos!("", $root);
    };
    (options: $options:expr, $root:expr) => {
        /// macOS entry: the Runner's main.swift calls this from the app staticlib (§17.4).
        #[cfg(target_os = "macos")]
        #[unsafe(no_mangle)]
        pub extern "C" fn day_main() {
            $crate::launch($crate::with_app_version!($options), $root);
        }
    };
    ($title:expr, $root:expr) => {
        $crate::day_start_macos!(
            // The same desktop default the scaffold's src/main.rs uses.
            options: $crate::WindowOptions::default().title($title).size(960.0, 640.0),
            $root
        );
    };
}

/// Expands to the two JNI exports that start the app, `DayBridge.nativeStart` (the primary
/// window) and `DayBridge.nativeStartWindow` (a secondary one), wired to the given root piece.
/// They live in the app cdylib because they name the app's root; every other native the bridge
/// declares is registered by day-toolkit-material's `DayBridge` binding (docs/android-jni.md).
///
/// ```ignore
/// day::day_start_android!(root);
/// ```
#[macro_export]
macro_rules! day_start_android {
    ($root:expr) => {
        $crate::day_start_android!(
            options: $crate::WindowOptions::default(),
            $root
        );
    };
    (options: $options:expr, $root:expr) => {
        // jni 0.22 native methods receive the FFI-safe `EnvUnowned`; `with_env` upgrades it to the
        // real `Env` (sharing the frame's `'local`, so the object args pass straight in) and wraps
        // the body in a `catch_unwind` so a panic never unwinds across the JNI boundary.
        #[cfg(target_os = "android")]
        #[unsafe(no_mangle)]
        pub extern "system" fn Java_dev_daybrite_day_bridge_DayBridge_nativeStart<'local>(
            mut env: $crate::android::jni::EnvUnowned<'local>,
            _class: $crate::android::jni::objects::JClass<'local>,
            root: $crate::android::jni::objects::JObject<'local>,
            density: $crate::android::jni::sys::jfloat,
            w: $crate::android::jni::sys::jint,
            h: $crate::android::jni::sys::jint,
            autodrive: $crate::android::jni::objects::JString<'local>,
            locale: $crate::android::jni::objects::JString<'local>,
            env_blob: $crate::android::jni::objects::JString<'local>,
        ) {
            let _ = env
                .with_env(|env| {
                    let a = $crate::android::read_jstring(env, &autodrive);
                    let l = $crate::android::read_jstring(env, &locale);
                    let e = $crate::android::read_jstring(env, &env_blob);
                    $crate::android::start(env, root, density, w, h, a, l, e, $crate::with_app_version!($options), $root);
                    ::core::result::Result::Ok::<(), $crate::android::jni::errors::Error>(())
                })
                .into_outcome();
        }

        #[cfg(target_os = "android")]
        #[unsafe(no_mangle)]
        pub extern "system" fn Java_dev_daybrite_day_bridge_DayBridge_nativeStartWindow<'local>(
            mut env: $crate::android::jni::EnvUnowned<'local>,
            _class: $crate::android::jni::objects::JClass<'local>,
            root: $crate::android::jni::objects::JObject<'local>,
            node: $crate::android::jni::sys::jlong,
            _density: $crate::android::jni::sys::jfloat,
            w: $crate::android::jni::sys::jint,
            h: $crate::android::jni::sys::jint,
        ) -> $crate::android::jni::sys::jboolean {
            let mut ok = false;
            let _ = env
                .with_env(|env| {
                    ok = $crate::android::window_started(env, root, node, w, h);
                    ::core::result::Result::Ok::<(), $crate::android::jni::errors::Error>(())
                })
                .into_outcome();
            ok as $crate::android::jni::sys::jboolean
        }
    };
}

/// Android glue (§17.4): the app cdylib's JNI exports forward here.
#[cfg(all(feature = "material", target_os = "android"))]
pub mod android {
    pub use day_toolkit_material::jni;
    pub use day_toolkit_material::{mount_settled, read_jstring, window_started};

    #[allow(clippy::too_many_arguments)]
    pub fn start<R: crate::Piece>(
        env: &mut jni::Env,
        root: jni::objects::JObject,
        density: f32,
        w: i32,
        h: i32,
        autodrive: Option<String>,
        locale: Option<String>,
        env_blob: Option<String>,
        options: crate::WindowOptions,
        root_piece: impl FnOnce() -> R + 'static,
    ) {
        // Before any println!: send stdout/stderr to logcat (Android drops them otherwise).
        day_toolkit_material::redirect_stdio_to_logcat();
        // A second launch in one process: the activity was recreated (docs/settings.md
        // "Appearance on Android"). Two paths do it: a light/dark or language switch calls
        // `recreate()` itself, and any configuration change the manifest does not claim
        // recreates incidentally. Both re-enter here with day-core already mounted.
        //
        // Re-mount rather than refuse. Refusing left the process alive with no tree behind the
        // new activity: a black, unresponsive window, and (because the dayscript engine socket
        // belongs to the process rather than the activity) a walkthrough that stayed green
        // against it. Building a second tree over the first was no better; the previous window's
        // reactive graph was never disposed, so its navigation host re-registered itself on top
        // of the new one.
        //
        // `prepare_remount` disposes what the last mount built and clears what `root()` is about
        // to register again, leaving root-scope state (`Signal::global`, `Ambient::app()`) alone.
        let remount = day_core::is_mounted();
        if remount {
            day_core::prepare_remount();
            // The language list is root-scoped, so it outlives the mount, and `crate::start`
            // appends the backend's hints to it. A re-mount for a new system language would
            // append ["fr-FR", "en-US"] behind the ["en-US"] of the first launch, and English
            // would still win. Start the list over; the fresh hints are the whole answer.
            day_localization_ui::set_launch_locales(&[]);
        }
        if let Some(a) = autodrive {
            unsafe { std::env::set_var("DAY_AUTODRIVE", a) };
        }
        if let Some(l) = locale {
            unsafe { std::env::set_var("DAY_LOCALE", l) };
        }
        if let Some(blob) = env_blob {
            for line in blob.lines() {
                if let Some((k, v)) = line.split_once('=') {
                    unsafe { std::env::set_var(k, v) };
                }
            }
        }
        day_toolkit_material::init(env, root, density, w, h);
        // The dayscript engine belongs to the process, not the activity: its listener survives a
        // recreation and keeps serving against whatever tree is mounted. Re-running `init` only
        // tried to bind the same port again ("Address already in use"), so the re-mount skips it.
        if !remount {
            day_script::init();
        }
        // Through `crate::start`, not `launch_with`: that is where the device's language
        // preference is read off the backend and handed to the localization engine, and this
        // entry is the app's only door on Android (docs/localization.md).
        // The app's description, not a default: it carries the locale catalog, and
        // `crate::start` is the only thing that installs it. Handed a default here, every
        // localized string on Android rendered as its own key (`⟨welcome_title⟩` on screen)
        // because the app stopped calling `res::locales::install()` itself when the catalog
        // moved into `WindowOptions` (docs/localization.md). The window fields are inert on
        // Android, where the Activity owns the surface and the label comes from the manifest.
        crate::start(day_toolkit_material::Material::new(), options, root_piece);
        // The tree is up: on a re-mount, bring the app back to the route the previous mount
        // saved, then let the activity take its crossfade down.
        day_toolkit_material::mount_settled(remount);
    }
}

/// Expands to the `day_arkui_start` C export the HarmonyOS ArkUI shim's `start(...)` NAPI wrapper
/// calls (from ArkTS: `import native from 'libday_arkui.so'; native.start(nodeContent, w, h, density)`).
/// It mounts the app's `root` piece into the ArkTS `NodeContent` and runs the loop.
///
/// ```ignore
/// day::day_start_arkui!(root);
/// ```
#[macro_export]
macro_rules! day_start_arkui {
    ($root:expr) => {
        $crate::day_start_arkui!(options: $crate::WindowOptions::default(), $root);
    };
    (options: $options:expr, $root:expr) => {
        /// HarmonyOS entry: the ArkUI shim's NAPI `start` calls this from the app cdylib (§17.4).
        #[cfg(target_env = "ohos")]
        #[unsafe(no_mangle)]
        pub extern "C" fn day_arkui_start(
            content: *mut ::core::ffi::c_void,
            w: f64,
            h: f64,
            density: f64,
        ) {
            $crate::arkui::start(content, w, h, density, $crate::with_app_version!($options), $root);
        }

        /// Deep-link intake (docs/deep-links.md): day-toolkit-arkui's NAPI `deepLink(uri)` calls this
        /// from the app cdylib for cold and warm links alike; `request_route` buffers before
        /// launch and navigates on the UI thread after.
        ///
        /// # Safety
        /// `uri` must be null or point to a NUL-terminated string valid for this call.
        #[cfg(target_env = "ohos")]
        #[unsafe(no_mangle)]
        pub unsafe extern "C" fn day_arkui_deeplink(uri: *const ::core::ffi::c_char) {
            // SAFETY: forwarded under the caller's string lifetime contract.
            unsafe { $crate::arkui::deeplink(uri) };
        }
    };
}

/// Expands to the `day_dom_main` C export the web host's `shim.js` calls once the wasm module
/// is instantiated (`wasm.day_dom_main()` at the end of `start()` in `crates/day-cli/resources/web/shim.js`).
///
/// ```ignore
/// day::day_start_web!(root);              // or: day::day_start_web!("My App", root);
/// ```
#[macro_export]
macro_rules! day_start_web {
    ($root:expr) => {
        $crate::day_start_web!("", $root);
    };
    (options: $options:expr, $root:expr) => {
        /// Web entry: the host page's shim calls this from the app cdylib (§17.4).
        #[cfg(target_arch = "wasm32")]
        #[unsafe(no_mangle)]
        pub extern "C" fn day_dom_main() {
            $crate::web::start($crate::with_app_version!($options), $root);
        }
    };
    ($title:expr, $root:expr) => {
        $crate::day_start_web!(
            options: $crate::WindowOptions::default().title($title),
            $root
        );
    };
}

/// Web glue (§17.4): the app cdylib's `day_dom_main` export forwards here.
#[cfg(all(feature = "dom", target_arch = "wasm32"))]
pub mod web {
    type EmbeddedResources = &'static [(&'static str, &'static [u8])];
    static RESOURCES: std::sync::OnceLock<EmbeddedResources> = std::sync::OnceLock::new();

    /// Register the generated web resource table before application initialization.
    /// Called by day-build's generated bootstrap; names are canonical bundle URLs.
    ///
    /// # Panics
    /// Panics if called more than once for the same Wasm instance.
    pub fn install_resources(resources: EmbeddedResources) {
        RESOURCES
            .set(resources)
            .expect("resources already installed");
        day_core::set_resource_opener(|name| {
            let table = RESOURCES.get()?;
            let index = table
                .binary_search_by(|(path, _)| {
                    path.bytes().cmp("assets/data/".bytes().chain(name.bytes()))
                })
                .ok()?;
            Some(crate::Resource::from_static(table[index].1))
        });
    }

    fn resource_pair(bytes: &[u8]) -> u64 {
        ((bytes.len() as u64) << 32) | bytes.as_ptr() as u64
    }

    /// Number of files in the embedded web bundle (host bootstrap ABI).
    #[unsafe(no_mangle)]
    pub extern "C" fn day_dom_resources_count() -> usize {
        RESOURCES.get().map_or(0, |r| r.len())
    }

    /// Borrow a bundle URL as a packed pointer and length (host bootstrap ABI).
    #[unsafe(no_mangle)]
    pub extern "C" fn day_dom_resources_name(index: usize) -> u64 {
        RESOURCES
            .get()
            .and_then(|r| r.get(index))
            .map_or(0, |(name, _)| resource_pair(name.as_bytes()))
    }

    /// Borrow a file's bytes as a packed pointer and length (host bootstrap ABI).
    #[unsafe(no_mangle)]
    pub extern "C" fn day_dom_resources_bytes(index: usize) -> u64 {
        RESOURCES
            .get()
            .and_then(|r| r.get(index))
            .map_or(0, |(_, bytes)| resource_pair(bytes))
    }

    /// One dayscript request line from the page's WebSocket (docs/web.md). Lives here, not in
    /// day-toolkit-dom, because backends depend only on day-spec; the umbrella is where the backend
    /// and the engine meet.
    #[unsafe(no_mangle)]
    pub extern "C" fn day_dom_script_line(ptr: *mut u8, len: usize) {
        let line = day_toolkit_dom::take_alloc_string(ptr, len);
        day_script::web_line(&line);
    }

    /// Install the panic hook (panics report through the browser console before the trap),
    /// hand the page's locale (`?locale=` else the browser languages) to the localization
    /// engine and its URL hash to `request_route`, arm the dayscript web transport when
    /// the serving `day launch` session invites it (`?dayscript=` token), and launch `root`
    /// into the host page's day root.
    pub fn start<P: crate::Piece>(
        options: crate::WindowOptions,
        root: impl FnOnce() -> P + 'static,
    ) {
        day_toolkit_dom::install_panic_hook();
        // Point the logger at the browser console before anything can log (docs/logging.md).
        // Installed here rather than inside day-toolkit-dom because a backend depends only on day-spec;
        // the facade is where the toolkit and the core are allowed to meet. Without this every
        // line would be silently dropped: std's stdio on wasm32-unknown-unknown takes the bytes
        // and discards them.
        day_core::set_log_sink(day_toolkit_dom::console_sink);
        // `DAY_LOG` has no process environment to live in here; the launch server forwards it as
        // a query parameter. `init_logging` (from `launch_with`) sets the default level, so this
        // only has to override when the page actually asked.
        if let Some(level) = day_toolkit_dom::launch_log_level() {
            day_core::set_log_level(level);
        }
        // `Instant` is unavailable on wasm; timing code reads the page's clock instead.
        day_core::frame::install_monotonic_clock(day_toolkit_dom::monotonic_secs);
        if let Some(locale) = day_toolkit_dom::launch_locale() {
            day_localization_ui::set_launch_locale(&locale);
        }
        if let Some(url) = day_toolkit_dom::launch_open_url() {
            day_core::request_open_url(&url);
        }
        if let Some(route) = day_toolkit_dom::launch_route() {
            day_core::set_launch_deeplink(&route);
        }
        if let Some(token) = day_toolkit_dom::dayscript_token() {
            day_script::web_init(token, day_toolkit_dom::script_send);
        }
        crate::launch(options, root);
    }
}

/// HarmonyOS ArkUI glue (§17.4): the app cdylib's `day_arkui_start` export forwards here.
#[cfg(all(feature = "arkui", target_env = "ohos"))]
pub mod arkui {
    use core::ffi::c_void;

    /// Mount `root` into the ArkTS `NodeContent` and run the loop. `w_vp`/`h_vp` are the content
    /// size in vp; `density` is px-per-vp (both passed by the ArkTS host).
    pub fn start<R: crate::Piece>(
        content: *mut c_void,
        w_vp: f64,
        h_vp: f64,
        density: f64,
        options: crate::WindowOptions,
        root: impl FnOnce() -> R + 'static,
    ) {
        day_toolkit_arkui::init(content, w_vp, h_vp, density);
        // Point the logger at hilog before anything can log (docs/logging.md): std's stdio
        // goes nowhere in an OHOS ability, so without this every `log::` line is dropped.
        // The same facade-installed sink rule as web.
        day_core::set_log_sink(day_toolkit_arkui::hilog_sink);
        day_script::init();
        // `crate::start` seeds the device's language preference before the root builds
        // (docs/localization.md); ArkUI's own hint list arrives once day-toolkit-arkui implements
        // `locale_hints`.
        // The app's own description, for the same reason as Android above: the locale catalog
        // travels in it, and nothing else installs one.
        crate::start(day_toolkit_arkui::ArkUi::new(), options, root);
    }

    /// A deep link from the ArkTS host (docs/deep-links.md): a cold `want.uri` (delivered
    /// before `start`) or a warm `onNewWant` one. `request_route` makes the two the same
    /// call, buffered until the first mount and applied on the UI thread after it.
    ///
    /// # Safety
    /// `uri` must be null or point to a NUL-terminated string valid for this call.
    pub unsafe fn deeplink(uri: *const core::ffi::c_char) {
        if uri.is_null() {
            return;
        }
        // SAFETY: per the caller's contract.
        let uri = unsafe { core::ffi::CStr::from_ptr(uri) };
        if let Ok(uri) = uri.to_str() {
            if uri.starts_with("file://") {
                day_core::request_open_files(vec![uri.into()]);
            } else {
                day_core::request_open_url(uri);
            }
        }
    }
}

/// Native drag-and-drop data and acceptance policy.
pub use day_spec::transfer;

/// Receive text shared to the app from the system share sheet (Day.toml `share_target`); a
/// shared web link arrives through [`on_open_url`] instead. See docs/deep-links.md.
pub use day_core::on_shared_text;
/// Receive local document activations from the operating system. See docs/documents.md.
pub use day_core::{on_open_files, on_open_url};

/// Download an image through the platform HTTP client and display it through the core decoder.
/// The request is cancelled when the owning reactive scope is disposed.
#[cfg(feature = "http-image")]
pub fn http_image(url: impl Into<String>) -> day_pieces::AsyncImage {
    let source = day_reactive::Signal::new(None);
    let request = day_part_http::Request::get(url);
    let task = day_core::task(async move {
        if let Ok(response) = day_part_http::fetch_future(request).await
            && (200..300).contains(&response.status)
        {
            source.set(Some(std::sync::Arc::new(response.body)));
        }
    });
    day_reactive::Scope::current().on_cleanup(move || task.abort());
    day_pieces::async_image(source)
}