telar-embed 0.2.3

Embedding a separately-compiled Telar UI inside a Telar application: the guest half an embedded app exports, and the loader a host drives it through.
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
use super::*;
use crate::guest::GuestInstance;
use layout_core::LayoutStyle;
#[cfg(all(feature = "host", not(target_arch = "wasm32")))]
use platform_core::guest::Lifecycle;
use platform_core::guest::{CWaker, HostServices};
use platform_core::{Key, ModifiersState};
use renderer_core::RectStyle;
#[cfg(all(feature = "host", not(target_arch = "wasm32")))]
use services_core::guest::UpperTable;

struct Stub {
    node: Option<NodeId>,
    seen: usize,
}

impl Stub {
    fn new() -> Self {
        Self {
            node: None,
            seen: 0,
        }
    }
}

impl EmbeddedApp for Stub {
    fn build(&mut self) {
        let (node, _) =
            ui_core::new_leaf(LayoutStyle::new().width(40.0).height(20.0)).expect("leaf");
        self.node = Some(node);
    }
    fn layout_root(&self) -> NodeId {
        self.node.expect("build ran first")
    }
    fn view(&self) -> RenderNode {
        RenderNode::rect(Rect::new(0.0, 0.0, 40.0, 20.0), RectStyle::default())
    }
    fn on_event(&mut self, _event: &Event) -> EventResult {
        self.seen += 1;
        EventResult::Ignored
    }
    fn title(&self) -> String {
        "stub".into()
    }
    fn id(&self) -> String {
        "stub".into()
    }
}

fn shift() -> ModifiersState {
    ModifiersState {
        is_shift: true,
        ..ModifiersState::default()
    }
}

// Expanded here too, so a change that breaks the macro fails this crate's own tests rather than only the fixtures `telar`'s ignored `guest_contract` suite builds.
crate::embed!(|_args: &[String]| -> Box<dyn EmbeddedApp> { Box::new(Stub::new()) });

/// Builds an instance through the exported table, and hands it back with the outcome.
fn create_through_table() -> (CallOutcome, Handle<GuestInstance>) {
    let args = wire_core::encode(&Vec::<String>::new());
    let conventions = wire_core::encode(&SurfaceConventions::default());
    let uri_schemes = wire_core::encode(&UriSchemes::default());
    let mut instance = Handle::NULL;
    let outcome = unsafe {
        (TELAR_EMBED_ENTRIES.create)(
            LentBytes::lend(&args),
            LentBytes::lend(&conventions),
            LentBytes::lend(&uri_schemes),
            &mut instance,
        )
    };
    (outcome, instance)
}

#[test]
fn the_export_macro_builds_a_table_that_answers_in_bytes() {
    let (outcome, instance) = create_through_table();
    assert_eq!(outcome.status(), CallOutcome::RETURNED);
    let mut id = LentBytes::EMPTY;
    let outcome = unsafe { (TELAR_EMBED_ENTRIES.id)(instance, &mut id) };
    assert_eq!(outcome.status(), CallOutcome::RETURNED);
    assert_eq!(unsafe { id.decode() }.expect("the id is a string"), "stub");
    let dark = SystemPreferences {
        color_scheme: Some(platform_core::ColorScheme::Dark),
        reduced_motion: Some(true),
        ..SystemPreferences::default()
    };
    let spelled = wire_core::encode(&dark);
    let outcome = unsafe {
        (TELAR_EMBED_ENTRIES.set_system_preferences)(instance, LentBytes::lend(&spelled))
    };
    assert_eq!(outcome.status(), CallOutcome::RETURNED);
    assert_eq!(
        preferences_core::system_preferences(),
        dark,
        "the whole snapshot crosses, not only the scheme"
    );
    preferences_core::set_system_preferences(SystemPreferences::default());
    let outcome = unsafe { (TELAR_EMBED_ENTRIES.release)(instance) };
    assert_eq!(outcome.status(), CallOutcome::RETURNED);
}

// These deliberately never observe on the caller's behalf, so they fail the moment either observe call leaves `EmbedInstance::on_event`.
#[test]
fn a_guest_records_the_modifiers_it_is_handed() {
    let mut inst = EmbedInstance::new(
        Box::new(Stub::new()),
        SurfaceConventions::default(),
        UriSchemes::default(),
    );
    inst.canvas
        .with_entered(|| assert_eq!(ui_core::modifiers(), ModifiersState::default()));

    inst.on_event(&Event::ModifiersChanged { modifiers: shift() });

    inst.canvas.with_entered(|| {
        assert!(
            ui_core::modifiers().is_shift,
            "a shift-drag inside a guest is indistinguishable from a plain one without this"
        );
    });
}

#[test]
fn an_overlay_event_reaches_the_registry_too() {
    let inst = EmbedInstance::new(
        Box::new(Stub::new()),
        SurfaceConventions::default(),
        UriSchemes::default(),
    );
    inst.dispatch_overlays(&Event::ModifiersChanged { modifiers: shift() });

    inst.canvas.with_entered(|| {
        assert!(
            ui_core::modifiers().is_shift,
            "an overlay event reaches the shared registry"
        );
    })
}

#[test]
fn a_press_answers_for_one_frame_and_end_frame_closes_it() {
    let mut inst = EmbedInstance::new(
        Box::new(Stub::new()),
        SurfaceConventions::default(),
        UriSchemes::default(),
    );
    inst.on_event(&Event::KeyPressed {
        key: Key::Char('c'),
        modifiers: ModifiersState::default(),
        unmodified: None,
    });

    inst.canvas.with_entered(|| {
        assert!(
            ui_core::key_pressed(&Key::Char('c')),
            "the press answers for the frame it arrived in"
        );
    });
    inst.end_frame();
    inst.canvas.with_entered(|| {
        assert!(
            !ui_core::key_pressed(&Key::Char('c')),
            "without end_frame the press answers forever, not for its frame"
        );
        assert!(
            ui_core::key_held(&Key::Char('c')),
            "held is not what end_frame clears"
        );
    })
}

#[test]
fn a_guest_paints_and_its_generation_is_stable_between_frames() {
    let mut inst = EmbedInstance::new(
        Box::new(Stub::new()),
        SurfaceConventions::default(),
        UriSchemes::default(),
    );
    inst.relayout(40.0, 20.0);
    assert!(
        !inst.paint().is_empty(),
        "a guest that paints emits commands"
    );
    assert_eq!(inst.generation(), inst.generation());
}

#[test]
fn the_driver_forwards_metadata_from_the_embedded_app() {
    let inst = EmbedInstance::new(
        Box::new(Stub::new()),
        SurfaceConventions::default(),
        UriSchemes::default(),
    );
    assert_eq!(inst.title(), "stub");
    assert_eq!(inst.id(), "stub");
    assert_eq!(inst.clear_color(), None);
}

/// A foreign surface that reports nothing, for a boundary to mark a frame with.
struct Silent;

impl ForeignSurface for Silent {
    fn access_snapshot(&self) -> Vec<platform_core::AccessNode> {
        Vec::new()
    }
    fn perform_access_action(
        &self,
        _id: platform_core::AccessId,
        _action: platform_core::AccessAction,
    ) {
    }
    fn text_input(&self) -> Option<platform_core::TextInput> {
        None
    }
    fn arrive(&self, _backwards: bool) -> bool {
        false
    }
    fn tab(&self, _key: &Event) -> bool {
        false
    }
    fn blur(&self) {}
    fn holds_focus(&self) -> bool {
        false
    }
    fn text_entry_focused(&self) -> bool {
        false
    }
    fn keeps(&self, _keys: platform_core::ConsumedKeys) -> bool {
        false
    }
}

#[test]
fn composite_translates_into_the_sub_rect_clips_to_it_and_marks_the_guests_frame() {
    let rect = Rect::new(10.0, 20.0, 100.0, 50.0);
    let silent: Rc<dyn ForeignSurface> = Rc::new(Silent);
    let boundary = ForeignBoundary::new(&silent);
    let node = composite(
        rect,
        &boundary,
        vec![DrawCommand::Rect {
            rect: Rect::new(0.0, 0.0, 5.0, 5.0),
            style: std::sync::Arc::new(RectStyle::default()),
        }],
    );
    let RenderNode::Clip {
        rect: clip,
        children,
        ..
    } = node
    else {
        panic!("expected the guest's frame to be wrapped in a clip");
    };
    assert_eq!(clip, rect, "clipped to the host's sub-rect");
    let drawn = ui_tree::ComponentList::new(Drawn(RefCell::new(Some(RenderNode::group(children)))))
        .commands()
        .clone();
    assert!(
        drawn.contains(&DrawCommand::PushSurface {
            surface: boundary.key()
        }),
        "the guest's frame is marked as its: {drawn:?}"
    );
}

/// A host's tree that draws one node once.
struct Drawn(RefCell<Option<RenderNode>>);

impl Component for Drawn {
    fn view(&self) -> RenderNode {
        self.0.borrow_mut().take().unwrap_or(RenderNode::Empty)
    }
}

/// A guest's frame crosses as bytes its own encoder lent, and a host decodes it into commands of its own that draw what the guest's canvas holds.
#[test]
fn a_frame_crosses_as_bytes_the_host_decodes_into_its_own_commands() {
    let (_, instance) = create_through_table();
    unsafe { (TELAR_EMBED_ENTRIES.relayout)(instance, 40.0, 20.0) };
    let mut frame = LentBytes::EMPTY;
    let outcome = unsafe { (TELAR_EMBED_ENTRIES.paint)(instance, &mut frame) };
    assert_eq!(outcome.status(), CallOutcome::RETURNED);
    let mut commands = Vec::new();
    renderer_core::wire::FrameDecoder::new()
        .decode(unsafe { frame.as_slice() }, &mut commands, |_| None)
        .expect("the frame decodes");
    assert_eq!(commands.len(), 1, "{commands:?}");
    assert!(matches!(commands[0], DrawCommand::Rect { .. }));
    unsafe { (TELAR_EMBED_ENTRIES.release)(instance) };
}

const DELAY: Duration = Duration::from_millis(500);

/// A guest that schedules a timer as it builds and counts the moves its content hears.
struct Waiting {
    node: Option<NodeId>,
    fired: Rc<std::cell::Cell<bool>>,
    moves: Rc<std::cell::Cell<u32>>,
    timer: Option<reactive_core::Timer>,
}

impl Waiting {
    fn new(fired: &Rc<std::cell::Cell<bool>>, moves: &Rc<std::cell::Cell<u32>>) -> Self {
        Self {
            node: None,
            fired: Rc::clone(fired),
            moves: Rc::clone(moves),
            timer: None,
        }
    }
}

impl EmbeddedApp for Waiting {
    fn build(&mut self) {
        let (node, _) =
            ui_core::new_leaf(LayoutStyle::new().width(40.0).height(20.0)).expect("leaf");
        self.node = Some(node);
        let fired = Rc::clone(&self.fired);
        self.timer = Some(reactive_core::run_after(DELAY, move || fired.set(true)));
    }
    fn layout_root(&self) -> NodeId {
        self.node.expect("build ran first")
    }
    fn view(&self) -> RenderNode {
        RenderNode::rect(Rect::new(0.0, 0.0, 40.0, 20.0), RectStyle::default())
    }
    fn on_event(&mut self, event: &Event) -> EventResult {
        if matches!(event, Event::PointerMoved { .. }) {
            self.moves.set(self.moves.get() + 1);
        }
        EventResult::Ignored
    }
    fn title(&self) -> String {
        "waiting".into()
    }
    fn id(&self) -> String {
        "waiting".into()
    }
}

fn waiting() -> (
    EmbedInstance,
    Rc<std::cell::Cell<bool>>,
    Rc<std::cell::Cell<u32>>,
) {
    let fired = Rc::new(std::cell::Cell::new(false));
    let moves = Rc::new(std::cell::Cell::new(0));
    let inst = EmbedInstance::new(
        Box::new(Waiting::new(&fired, &moves)),
        SurfaceConventions::default(),
        UriSchemes::default(),
    );
    (inst, fired, moves)
}

fn run_frame(inst: &mut EmbedInstance, waker: Option<&platform_core::RedrawWaker>) {
    let mut redraw_requested = false;
    let mut ctx = AppCtx::new(&mut redraw_requested, waker, None, None);
    inst.on_frame(&mut ctx);
}

#[test]
fn a_guest_timer_is_reported_until_its_frame_fires_it() {
    let (mut inst, fired, _) = waiting();
    let due = inst
        .next_timer_due()
        .expect("the guest reports its deadline");
    let wait = inst.until_next_timer().expect("and how long until it");
    assert!(wait <= DELAY && wait > DELAY / 2, "{wait:?}");

    run_frame(&mut inst, None);
    assert!(!fired.get(), "not before it is due");
    assert_eq!(inst.next_timer_due(), Some(due), "the deadline holds still");

    reactive_core::advance_timer_clock(DELAY);
    run_frame(&mut inst, None);
    assert!(fired.get(), "the guest's frame runs what came due");
    assert_eq!(inst.until_next_timer(), None);
}

#[test]
fn a_timer_the_guest_schedules_wakes_the_host_loop() {
    let (mut inst, _, _) = waiting();
    let this_thread = std::thread::current().id();
    let wakes = std::sync::Arc::new(std::sync::atomic::AtomicU32::new(0));
    let counting = std::sync::Arc::clone(&wakes);
    // The waker slot is process-wide; counting only this thread's wakes keeps the other tests' timers out of the count.
    let waker = platform_core::RedrawWaker::new(move || {
        if std::thread::current().id() == this_thread {
            counting.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
        }
    });
    let outcome = unsafe { (TELAR_EMBED_ENTRIES.install_task_waker)(CWaker::new(waker.clone())) };
    assert_eq!(outcome.status(), CallOutcome::RETURNED);
    run_frame(&mut inst, Some(&waker));
    let before = wakes.load(std::sync::atomic::Ordering::SeqCst);

    let _sooner = inst
        .canvas
        .with_entered(|| reactive_core::run_after(DELAY / 10, || {}));
    assert!(
        wakes.load(std::sync::atomic::Ordering::SeqCst) > before,
        "a timer due before the one the host sleeps for wakes it"
    );
}

/// A blocking overlay over the whole guest that takes every pointer event.
struct Blanket;

impl ui_tree::OverlaySink for Blanket {
    fn content_rect(&self) -> Rect {
        Rect::new(0.0, 0.0, 40.0, 20.0)
    }
    fn dispatch(&self, _event: &Event) -> EventResult {
        EventResult::Handled
    }
}

#[test]
fn a_move_an_overlay_takes_still_reaches_the_content_under_it() {
    let (inst, _, moves) = waiting();
    let overlay = inst
        .canvas
        .with_entered(|| ui_tree::register_overlay(Rc::new(Blanket)));
    let moved = Event::PointerMoved {
        x: 10.0,
        y: 10.0,
        source: platform_core::PointerSource::Mouse,
    };
    assert!(inst.dispatch_overlays(&moved), "the overlay takes the move");
    assert_eq!(moves.get(), 1, "and the content hears it, covered");

    let pressed = Event::PointerPressed {
        x: 10.0,
        y: 10.0,
        button: platform_core::PointerButton::Primary,
        source: platform_core::PointerSource::Mouse,
    };
    assert!(inst.dispatch_overlays(&pressed));
    assert_eq!(moves.get(), 1, "what else it takes stays its own");

    inst.canvas.with_entered(|| {
        ui_tree::unregister_overlay(overlay);
    })
}

#[cfg(all(feature = "host", not(target_arch = "wasm32")))]
#[test]
fn the_host_follows_a_guest_deadline_without_arming_it_again() {
    let mirror = crate::host::TimerMirror::default();
    let due = web_time::Instant::now() + DELAY;
    mirror.follow(Some(due), Some(DELAY));
    let wait = reactive_core::until_next_timer().expect("the host's loop wakes for it");
    assert!(wait <= DELAY && wait > DELAY / 2, "{wait:?}");

    reactive_core::advance_timer_clock(DELAY / 2);
    mirror.follow(Some(due), Some(DELAY * 4));
    let wait = reactive_core::until_next_timer().expect("still waking for it");
    assert!(
        wait <= DELAY / 2,
        "the same deadline is not armed again: {wait:?}"
    );

    let later = due + DELAY;
    mirror.follow(Some(later), Some(DELAY * 3));
    let wait = reactive_core::until_next_timer().expect("a moved deadline is followed");
    assert!(wait > DELAY * 2, "{wait:?}");

    mirror.follow(None, None);
    assert_eq!(
        reactive_core::until_next_timer(),
        None,
        "nothing left to wake for"
    );
}

thread_local! {
    static PRESSES_HEARD: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };
    static APPS_DROPPED: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };
}

/// A guest whose press handler panics, as one that writes a signal its own effect still borrows does, and which counts the presses it hears and the times it is dropped.
struct BorrowsTwice {
    stub: Stub,
    panics: bool,
}

impl BorrowsTwice {
    fn new(panics: bool) -> Self {
        Self {
            stub: Stub::new(),
            panics,
        }
    }
}

impl Drop for BorrowsTwice {
    fn drop(&mut self) {
        APPS_DROPPED.with(|dropped| dropped.set(dropped.get() + 1));
    }
}

impl EmbeddedApp for BorrowsTwice {
    fn build(&mut self) {
        self.stub.build();
    }
    fn layout_root(&self) -> NodeId {
        self.stub.layout_root()
    }
    fn view(&self) -> RenderNode {
        self.stub.view()
    }
    fn on_event(&mut self, event: &Event) -> EventResult {
        if matches!(event, Event::PointerPressed { .. }) {
            PRESSES_HEARD.with(|heard| heard.set(heard.get() + 1));
            if self.panics {
                panic!("RUNTIME is already borrowed");
            }
        }
        EventResult::Ignored
    }
    fn title(&self) -> String {
        "borrows twice".into()
    }
    fn id(&self) -> String {
        "borrows-twice".into()
    }
}

fn press() -> Event {
    Event::PointerPressed {
        x: 10.0,
        y: 10.0,
        button: platform_core::PointerButton::Primary,
        source: platform_core::PointerSource::Mouse,
    }
}

fn create_with(
    make: impl FnOnce(&[String]) -> Box<dyn EmbeddedApp>,
) -> (CallOutcome, Handle<GuestInstance>) {
    let args = wire_core::encode(&Vec::<String>::new());
    let conventions = wire_core::encode(&SurfaceConventions::default());
    let uri_schemes = wire_core::encode(&UriSchemes::default());
    let mut instance = Handle::NULL;
    let outcome = unsafe {
        guest::create(
            LentBytes::lend(&args),
            LentBytes::lend(&conventions),
            LentBytes::lend(&uri_schemes),
            &mut instance,
            make,
        )
    };
    (outcome, instance)
}

/// What a panic in the guest's handler hands back instead of unwinding into the host's copy of std, which can only abort on it.
#[test]
fn a_panic_in_a_guest_entry_comes_back_as_its_report() {
    let (built, instance) = create_with(|_| Box::new(BorrowsTwice::new(true)));
    assert_eq!(built.status(), CallOutcome::RETURNED, "the guest builds");
    let pressed = wire_core::encode(&press());
    let mut handled = false;
    let outcome = unsafe {
        (TELAR_EMBED_ENTRIES.on_event)(instance, LentBytes::lend(&pressed), &mut handled)
    };
    let panic = unsafe { outcome.into_result() }.expect_err("the panic is caught");
    assert_eq!(panic.message, "RUNTIME is already borrowed");
    let location = panic.location.as_deref().expect("the hook saw where");
    assert!(location.starts_with(&format!("{}:", file!())), "{location}");
}

#[test]
fn a_guest_whose_build_panics_hands_back_no_instance() {
    let (outcome, instance) = create_with(|_| panic!("the guest could not find its assets"));
    let panic = unsafe { outcome.into_result() }.expect_err("the panic is caught");
    assert_eq!(panic.message, "the guest could not find its assets");
    assert!(instance.is_null());
}

#[cfg(all(feature = "host", not(target_arch = "wasm32")))]
unsafe extern "C" fn create_panicking(
    args: LentBytes<Vec<String>>,
    conventions: LentBytes<SurfaceConventions>,
    uri_schemes: LentBytes<UriSchemes>,
    instance: *mut Handle<GuestInstance>,
) -> CallOutcome {
    unsafe {
        guest::create(args, conventions, uri_schemes, instance, |_| {
            Box::new(BorrowsTwice::new(true))
        })
    }
}

#[cfg(all(feature = "host", not(target_arch = "wasm32")))]
unsafe extern "C" fn create_fixed(
    args: LentBytes<Vec<String>>,
    conventions: LentBytes<SurfaceConventions>,
    uri_schemes: LentBytes<UriSchemes>,
    instance: *mut Handle<GuestInstance>,
) -> CallOutcome {
    unsafe {
        guest::create(args, conventions, uri_schemes, instance, |_| {
            Box::new(BorrowsTwice::new(false))
        })
    }
}

#[cfg(all(feature = "host", not(target_arch = "wasm32")))]
unsafe extern "C" fn create_nothing(
    args: LentBytes<Vec<String>>,
    conventions: LentBytes<SurfaceConventions>,
    uri_schemes: LentBytes<UriSchemes>,
    instance: *mut Handle<GuestInstance>,
) -> CallOutcome {
    unsafe {
        guest::create(args, conventions, uri_schemes, instance, |_| {
            panic!("the guest could not find its assets")
        })
    }
}

/// A guest served by this process's own table, through the same catch and the same bookkeeping a dylib's go through. What stays untested here is the second copy of std a real dylib carries, which `telar`'s `guest_contract` suite loads.
#[cfg(all(feature = "host", not(target_arch = "wasm32")))]
fn embedded(create: CreateInstance) -> Result<LoadedEmbed, GuestStop> {
    LoadedEmbed::start(
        EmbedEntries {
            create,
            ..TELAR_EMBED_ENTRIES
        },
        &[],
        None,
    )
}

/// A panic in an embedded guest's handler used to unwind into the host and abort it. Now the host is told what panicked and where, nothing more of that guest runs, and a fresh one takes its place.
#[cfg(all(feature = "host", not(target_arch = "wasm32")))]
#[test]
fn a_guest_that_panics_is_reported_and_never_called_again() {
    PRESSES_HEARD.with(|heard| heard.set(0));
    APPS_DROPPED.with(|dropped| dropped.set(0));
    let broken = embedded(create_panicking).expect("the guest loads");
    broken.relayout(40.0, 20.0);
    assert_eq!(broken.stopped(), None, "precondition: a guest that runs");
    assert!(
        !broken.paint().is_empty(),
        "precondition: a guest that paints"
    );

    assert!(!broken.on_event(&press()));
    assert_eq!(PRESSES_HEARD.with(std::cell::Cell::get), 1);
    let Some(GuestStop::Panicked(panic)) = broken.stopped() else {
        panic!(
            "the host is told the guest panicked: {:?}",
            broken.stopped()
        );
    };
    assert_eq!(panic.message, "RUNTIME is already borrowed");
    assert!(
        panic
            .location
            .as_deref()
            .is_some_and(|location| location.starts_with(file!())),
        "the report says where: {panic}"
    );

    assert!(!broken.on_event(&press()));
    assert!(!broken.dispatch_overlays(&press()));
    assert!(
        broken.paint().is_empty(),
        "a guest that panicked draws nothing"
    );
    assert_eq!(broken.title(), "");
    run_embedded_frame(&broken);
    assert_eq!(
        PRESSES_HEARD.with(std::cell::Cell::get),
        1,
        "nothing more of the guest that panicked runs"
    );
    drop(broken);
    assert_eq!(
        APPS_DROPPED.with(std::cell::Cell::get),
        0,
        "its instance is kept rather than released by code that already panicked"
    );

    let fresh = embedded(create_fixed).expect("a fresh guest loads");
    fresh.on_event(&press());
    assert_eq!(
        PRESSES_HEARD.with(std::cell::Cell::get),
        2,
        "the fresh guest hears the press"
    );
    assert_eq!(fresh.stopped(), None);
    drop(fresh);
    assert_eq!(
        APPS_DROPPED.with(std::cell::Cell::get),
        1,
        "and is released as usual"
    );
}

#[cfg(all(feature = "host", not(target_arch = "wasm32")))]
#[test]
fn a_guest_whose_build_panics_is_refused_with_the_report() {
    let Some(GuestStop::Panicked(panic)) = embedded(create_nothing).err() else {
        panic!("a guest that cannot build does not load, and says why");
    };
    assert_eq!(panic.message, "the guest could not find its assets");
}

/// The host reads every answer the guest lends into values of its own: its metadata, the commands its title bar queued and the timer it waits on, on the host's clock.
#[cfg(all(feature = "host", not(target_arch = "wasm32")))]
#[test]
fn a_host_reads_what_a_guest_answers_into_its_own_values() {
    let embed = embedded(create_waiting).expect("the guest loads");
    assert_eq!(embed.title(), "waiting");
    assert_eq!(embed.id(), "waiting");
    assert_eq!(embed.icon(), None);
    assert_eq!(embed.clear_color(), None);
    assert!(embed.drain_window_commands().is_empty());
    let wait = embed.until_next_timer().expect("the guest's timer crosses");
    assert!(wait <= DELAY && wait > DELAY / 2, "{wait:?}");
    let due = embed.next_timer_due().expect("and its deadline");
    assert_eq!(
        embed.next_timer_due(),
        Some(due),
        "the same deadline reads the same on the host's clock"
    );
    let from_now = due.saturating_duration_since(Instant::now());
    assert!(from_now <= DELAY && from_now > DELAY / 2, "{from_now:?}");
    assert_eq!(embed.stopped(), None);
}

#[cfg(all(feature = "host", not(target_arch = "wasm32")))]
unsafe extern "C" fn create_waiting(
    args: LentBytes<Vec<String>>,
    conventions: LentBytes<SurfaceConventions>,
    uri_schemes: LentBytes<UriSchemes>,
    instance: *mut Handle<GuestInstance>,
) -> CallOutcome {
    let fired = Rc::new(std::cell::Cell::new(false));
    let moves = Rc::new(std::cell::Cell::new(0));
    unsafe {
        guest::create(args, conventions, uri_schemes, instance, |_| {
            Box::new(Waiting::new(&fired, &moves))
        })
    }
}

#[cfg(all(feature = "host", not(target_arch = "wasm32")))]
fn run_embedded_frame(embed: &LoadedEmbed) {
    let waker = platform_core::RedrawWaker::new(|| panic!("the host's loop is gone"));
    let mut redraw_requested = false;
    let mut ctx = AppCtx::new(&mut redraw_requested, Some(&waker), None, None);
    embed.on_frame(&mut ctx);
}

/// A guest that wakes the host's loop every frame.
#[cfg(all(feature = "host", not(target_arch = "wasm32")))]
struct WakesTheHost(Stub);

#[cfg(all(feature = "host", not(target_arch = "wasm32")))]
impl EmbeddedApp for WakesTheHost {
    fn build(&mut self) {
        self.0.build();
    }
    fn layout_root(&self) -> NodeId {
        self.0.layout_root()
    }
    fn view(&self) -> RenderNode {
        self.0.view()
    }
    fn on_event(&mut self, event: &Event) -> EventResult {
        self.0.on_event(event)
    }
    fn on_frame(&mut self, ctx: &mut AppCtx) {
        if let Some(waker) = ctx.redraw_waker() {
            waker.wake();
        }
        ctx.request_redraw();
    }
    fn title(&self) -> String {
        "wakes".into()
    }
    fn id(&self) -> String {
        "wakes".into()
    }
}

#[cfg(all(feature = "host", not(target_arch = "wasm32")))]
unsafe extern "C" fn create_waking(
    args: LentBytes<Vec<String>>,
    conventions: LentBytes<SurfaceConventions>,
    uri_schemes: LentBytes<UriSchemes>,
    instance: *mut Handle<GuestInstance>,
) -> CallOutcome {
    unsafe {
        guest::create(args, conventions, uri_schemes, instance, |_| {
            Box::new(WakesTheHost(Stub::new()))
        })
    }
}

/// The waker the guest is handed is host code; a panic in it stays on the host's side instead of unwinding through the guest, and the redraw the guest asks for reaches the host's context.
#[cfg(all(feature = "host", not(target_arch = "wasm32")))]
#[test]
fn a_panic_in_the_host_waker_does_not_reach_the_guest() {
    let embed = embedded(create_waking).expect("the guest loads");
    let waker = platform_core::RedrawWaker::new(|| panic!("the host's loop is gone"));
    let mut redraw_requested = false;
    let mut ctx = AppCtx::new(&mut redraw_requested, Some(&waker), None, None);
    embed.on_frame(&mut ctx);
    assert_eq!(embed.stopped(), None, "the guest kept running");
    assert!(redraw_requested, "its redraw reaches the host");
}

#[cfg(all(feature = "host", not(target_arch = "wasm32")))]
thread_local! {
    static HOST_SERVED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
    static HANDED_BEFORE_BUILD: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
    static SERVED_NOTHING: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) };
}

#[cfg(all(feature = "host", not(target_arch = "wasm32")))]
unsafe extern "C" fn record_services(services: HostServices<UpperTable>) -> CallOutcome {
    HOST_SERVED.set(!services.data.is_null());
    SERVED_NOTHING.set(Some(services.data.is_null()));
    CallOutcome::OK
}

#[cfg(all(feature = "host", unix))]
unsafe extern "C" fn create_after_services(
    args: LentBytes<Vec<String>>,
    conventions: LentBytes<SurfaceConventions>,
    uri_schemes: LentBytes<UriSchemes>,
    instance: *mut Handle<GuestInstance>,
) -> CallOutcome {
    HANDED_BEFORE_BUILD.set(HOST_SERVED.get());
    unsafe {
        guest::create(args, conventions, uri_schemes, instance, |_| {
            Box::new(Stub::new())
        })
    }
}

#[cfg(all(feature = "host", unix))]
extern "C" fn does_nothing() -> CallOutcome {
    CallOutcome::OK
}

/// A guest carries its own copy of every store, which left alone answers for nothing: its build already reads the host's clipboard, preferences and paths.
#[cfg(all(feature = "host", unix))]
#[test]
fn a_guest_is_handed_the_host_services_before_it_is_built() {
    let this_process = libloading::Library::from(libloading::os::unix::Library::this());
    let embed = LoadedEmbed::start(
        EmbedEntries {
            create: create_after_services,
            lifecycle: Lifecycle {
                install_services: record_services,
                loaded: does_nothing,
                unloading: does_nothing,
                quiesce: does_nothing,
                ..TELAR_EMBED_ENTRIES.lifecycle
            },
            ..TELAR_EMBED_ENTRIES
        },
        &[],
        Some(this_process),
    )
    .expect("the guest loads");
    assert!(HOST_SERVED.get());
    assert!(
        HANDED_BEFORE_BUILD.get(),
        "the guest's build already reads the host's stores"
    );
    drop(embed);
}

/// A table this process serves itself already shares every store there is, the one font database included: handed it, its shaper would defer to itself.
#[cfg(all(feature = "host", not(target_arch = "wasm32")))]
#[test]
fn a_guest_of_this_process_is_served_nothing() {
    let embed = LoadedEmbed::start(
        EmbedEntries {
            lifecycle: Lifecycle {
                install_services: record_services,
                ..TELAR_EMBED_ENTRIES.lifecycle
            },
            ..TELAR_EMBED_ENTRIES
        },
        &[],
        None,
    )
    .expect("the guest loads");
    assert_eq!(SERVED_NOTHING.get(), Some(true));
    drop(embed);
}

#[test]
fn the_exported_table_installs_the_values_it_is_handed() {
    platform_core::set_asset_base("https://host.example/assets/");
    let served = services_core::guest::ServedServices::installed(None);
    platform_core::set_asset_base("https://guest.example/");
    let full = served.table();
    let only_the_asset_base = HostServices {
        data: full.data,
        asset_base: full.asset_base,
        ..HostServices::NONE
    };
    let outcome = unsafe { (TELAR_EMBED_ENTRIES.lifecycle.install_services)(only_the_asset_base) };
    assert_eq!(outcome.status(), CallOutcome::RETURNED);
    assert_eq!(
        platform_core::asset_base().as_deref(),
        Some("https://host.example/assets/")
    );
}

#[cfg(all(feature = "host", unix))]
thread_local! {
    static LIFE: std::cell::RefCell<Vec<&'static str>> = const { std::cell::RefCell::new(Vec::new()) };
}

#[cfg(all(feature = "host", unix))]
fn live(call: &'static str) -> CallOutcome {
    LIFE.with_borrow_mut(|calls| calls.push(call));
    CallOutcome::OK
}

#[cfg(all(feature = "host", unix))]
extern "C" fn live_loaded() -> CallOutcome {
    live("loaded")
}

#[cfg(all(feature = "host", unix))]
extern "C" fn live_unloading() -> CallOutcome {
    live("unloading")
}

#[cfg(all(feature = "host", unix))]
extern "C" fn live_quiesce() -> CallOutcome {
    live("quiesce")
}

#[cfg(all(feature = "host", unix))]
extern "C" fn serves_nothing(_services: HostServices<UpperTable>) -> CallOutcome {
    CallOutcome::OK
}

/// Held with this process as its library, so dropping it runs the unload path a built library's does.
#[cfg(all(feature = "host", unix))]
fn embedded_as_loaded(create: CreateInstance) -> Result<LoadedEmbed, GuestStop> {
    LIFE.with_borrow_mut(Vec::clear);
    let this_process = libloading::Library::from(libloading::os::unix::Library::this());
    LoadedEmbed::start(
        EmbedEntries {
            create,
            lifecycle: Lifecycle {
                loaded: live_loaded,
                unloading: live_unloading,
                quiesce: live_quiesce,
                install_services: serves_nothing,
                ..TELAR_EMBED_ENTRIES.lifecycle
            },
            ..TELAR_EMBED_ENTRIES
        },
        &[],
        Some(this_process),
    )
}

#[cfg(all(feature = "host", unix))]
#[test]
fn a_guest_is_released_told_it_is_unloading_then_quiesced_before_its_library_is_closed() {
    APPS_DROPPED.with(|dropped| dropped.set(0));
    drop(embedded_as_loaded(create_fixed).expect("the guest loads"));
    assert_eq!(APPS_DROPPED.with(std::cell::Cell::get), 1);
    assert_eq!(LIFE.take(), ["loaded", "unloading", "quiesce"]);
}

/// Its worker threads may still be running its code, so the one call a guest that panicked still gets is the one that joins them.
#[cfg(all(feature = "host", unix))]
#[test]
fn a_guest_that_panicked_is_still_quiesced_before_its_library_is_closed() {
    APPS_DROPPED.with(|dropped| dropped.set(0));
    let broken = embedded_as_loaded(create_panicking).expect("the guest loads");
    broken.relayout(40.0, 20.0);
    broken.on_event(&press());
    assert!(broken.stopped().is_some(), "precondition: it panicked");
    drop(broken);
    assert_eq!(APPS_DROPPED.with(std::cell::Cell::get), 0);
    assert_eq!(LIFE.take(), ["loaded", "quiesce"]);
}

#[cfg(all(feature = "host", unix))]
#[test]
fn a_guest_whose_build_panics_is_still_quiesced_before_its_library_is_closed() {
    let refused = embedded_as_loaded(create_nothing);
    assert!(refused.is_err(), "precondition: it does not load");
    assert_eq!(LIFE.take(), ["loaded", "quiesce"]);
}

struct PanicsWhenTicked;

impl motion_core::Tickable for PanicsWhenTicked {
    fn tick(&self, _now: Instant, _scale: f32) {
        panic!("an animation callback panicked");
    }
    fn is_settled(&self) -> bool {
        false
    }
}

#[test]
fn an_animation_that_panics_mid_tick_leaves_later_flushes_working() {
    let inst = EmbedInstance::new(
        Box::new(Stub::new()),
        SurfaceConventions::default(),
        UriSchemes::default(),
    );
    let animation: std::rc::Rc<dyn motion_core::Tickable> = std::rc::Rc::new(PanicsWhenTicked);
    inst.canvas.with_entered(|| {
        motion_core::register(motion_core::next_id(), std::rc::Rc::downgrade(&animation))
    });

    let ticked = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
        inst.motion_tick(Instant::now())
    }));
    assert!(ticked.is_err(), "precondition: the tick panicked");
    drop(animation);

    let count = reactive_core::signal(0);
    let seen = std::rc::Rc::new(std::cell::Cell::new(0));
    let into = std::rc::Rc::clone(&seen);
    reactive_core::effect(move || into.set(count.get()));
    count.set(3);
    assert_eq!(
        seen.get(),
        3,
        "the batch the tick opened ended with the unwind, so the write flushed"
    );
}

/// Two 20×20 focusables side by side in the guest's top-left corner.
struct TwoFocusables {
    content: Option<Box<dyn ui_core::LayoutItem>>,
}

impl EmbeddedApp for TwoFocusables {
    fn build(&mut self) {
        let focusable = || {
            Box::new(
                ui_core::StyledContainer::new(
                    LayoutStyle::new().width(20.0).height(20.0),
                    |_| RectStyle::default(),
                    vec![],
                )
                .expect("box")
                .on_focus(|_| {}),
            ) as Box<dyn ui_core::LayoutItem>
        };
        let row = ui_core::Container::new(
            LayoutStyle::new().flex_row().width(100.0).height(100.0),
            vec![focusable(), focusable()],
        )
        .expect("row");
        self.content = Some(Box::new(row));
    }
    fn layout_root(&self) -> NodeId {
        self.content
            .as_ref()
            .expect("build ran first")
            .layout_node()
    }
    fn view(&self) -> RenderNode {
        self.content.as_ref().expect("build ran first").view()
    }
    fn on_event(&mut self, event: &Event) -> EventResult {
        self.content
            .as_mut()
            .expect("build ran first")
            .on_event(event)
    }
    fn title(&self) -> String {
        "focusables".into()
    }
    fn id(&self) -> String {
        "focusables".into()
    }
}

fn primary_press(x: f64, y: f64) -> Event {
    Event::PointerPressed {
        x,
        y,
        button: platform_core::PointerButton::Primary,
        source: platform_core::PointerSource::Mouse,
    }
}

fn tab() -> Event {
    Event::KeyPressed {
        key: Key::Named(platform_core::NamedKey::Tab),
        modifiers: ModifiersState::default(),
        unmodified: None,
    }
}

#[test]
fn a_press_on_nothing_in_a_guest_lets_its_keyboard_go() {
    let mut inst = EmbedInstance::new(
        Box::new(TwoFocusables { content: None }),
        SurfaceConventions::default(),
        UriSchemes::default(),
    );
    inst.relayout(100.0, 100.0);
    let _ = inst.paint();

    inst.on_event(&primary_press(10.0, 10.0));
    assert!(
        inst.canvas.holds_focus(),
        "a press on a focusable takes focus"
    );
    inst.on_event(&primary_press(80.0, 80.0));
    assert!(
        !inst.canvas.holds_focus(),
        "a press on nothing focusable clears focus inside the guest"
    );
}

#[test]
fn tab_past_a_guests_last_focusable_steps_out_to_the_host() {
    let mut inst = EmbedInstance::new(
        Box::new(TwoFocusables { content: None }),
        SurfaceConventions::default(),
        UriSchemes::default(),
    );
    inst.relayout(100.0, 100.0);
    let _ = inst.paint();

    assert!(
        !inst.on_event(&tab()),
        "Tab with nothing focused is the host's to move"
    );
    assert!(inst.canvas.arrive(false));
    assert!(!inst.canvas.tab(&tab()), "Tab walks the guest's focusables");
    assert!(inst.canvas.tab(&tab()), "and past the last one steps out");
    assert!(!inst.canvas.holds_focus());
}

fn on_cells() -> SurfaceConventions {
    SurfaceConventions {
        grid: geometry_core::LayoutGrid::new(8.0, 16.0).expect("a positive, finite step"),
        keyboard: platform_core::KeyboardConvention::Pc,
        smooth_wheel: false,
        focus_boundary: platform_core::FocusBoundary::Release,
    }
}

#[cfg(all(feature = "host", not(target_arch = "wasm32")))]
thread_local! {
    static CONVENTIONS_HANDED: std::cell::Cell<Option<SurfaceConventions>> = const { std::cell::Cell::new(None) };
    static SCHEMES_HANDED: std::cell::RefCell<Option<UriSchemes>> = const { std::cell::RefCell::new(None) };
}

#[cfg(all(feature = "host", not(target_arch = "wasm32")))]
unsafe extern "C" fn create_recording(
    args: LentBytes<Vec<String>>,
    conventions: LentBytes<SurfaceConventions>,
    uri_schemes: LentBytes<UriSchemes>,
    instance: *mut Handle<GuestInstance>,
) -> CallOutcome {
    CONVENTIONS_HANDED.set(Some(unsafe { conventions.read() }));
    SCHEMES_HANDED.set(Some(unsafe { uri_schemes.read() }));
    unsafe {
        guest::create(args, conventions, uri_schemes, instance, |_| {
            Box::new(Stub::new())
        })
    }
}

/// A guest is drawn inside a surface of the host's, so it is built on that surface's conventions rather than on the defaults its own copy starts with.
#[cfg(all(feature = "host", not(target_arch = "wasm32")))]
#[test]
fn a_guest_is_handed_the_conventions_of_the_surface_it_is_drawn_inside() {
    ui_core::set_surface_conventions(on_cells());
    let embed = embedded(create_recording).expect("the guest loads");
    assert_eq!(CONVENTIONS_HANDED.get(), Some(on_cells()));
    drop(embed);
}

fn embed_test_schemes() -> UriSchemes {
    UriSchemes::default().allowing("telar-embed-host").unwrap()
}

/// A guest's links go where the host's surface lets its own go, not where the guest's copy would by itself.
#[cfg(all(feature = "host", not(target_arch = "wasm32")))]
#[test]
fn a_guest_is_handed_the_uri_schemes_of_the_surface_it_is_drawn_inside() {
    ui_core::set_surface_uri_schemes(embed_test_schemes());
    let embed = embedded(create_recording).expect("the guest loads");
    assert_eq!(SCHEMES_HANDED.take(), Some(embed_test_schemes()));
    drop(embed);
}

#[test]
fn an_instance_links_by_the_uri_schemes_it_is_given() {
    let inst = EmbedInstance::new(
        Box::new(Stub::new()),
        SurfaceConventions::default(),
        embed_test_schemes(),
    );
    assert_eq!(
        inst.canvas.with_entered(ui_core::surface_uri_schemes),
        embed_test_schemes()
    );
    assert_eq!(ui_core::surface_uri_schemes(), UriSchemes::default());
}

#[test]
fn an_instance_lays_out_on_the_conventions_it_is_given() {
    let inst = EmbedInstance::new(Box::new(Stub::new()), on_cells(), UriSchemes::default());
    assert_eq!(
        inst.canvas.with_entered(ui_core::surface_conventions),
        on_cells()
    );
    assert_eq!(
        ui_core::surface_conventions(),
        SurfaceConventions::default()
    );
}