pax-runtime 0.39.1

Core shared runtime and rendering engine for Pax
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
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
use crate::constants::{PRE_RENDER_HANDLERS, TICK_HANDLERS};
use crate::{
    api::LocalProperty, ExpandedNodeIdentifier, RouteLocation, RuntimePropertiesStackFrame,
    TransformAndBounds, INTERNAL_ROUTE_LOCATION_SYMBOL,
};
use_RefCell!();
use std::collections::{HashMap, HashSet};
use std::rc::Rc;

use pax_message::NativeMessage;
use pax_runtime_api::{
    borrow, pax_value::PaxAny, use_RefCell, Accel, Event, Focus, Gyro, SelectStart, TargetInfo,
    Variable, Viewport, Window, OS,
};

use crate::api::{KeyDown, KeyPress, KeyUp, NodeContext, RenderContext};

use crate::{ComponentInstance, RuntimeContext};
use pax_runtime_api::Platform;

pub mod layer_surface;
pub mod layer_tiling;
pub mod node_interface;
pub mod occlusion;
// TODO move these to not be in engine - make separate crates?
pub mod pax_gpu_render_context;
pub mod piet_render_context;
#[cfg(test)]
mod render_lifecycle_tests;

/// The atomic unit of rendering; also the container for each unique tuple of computed properties.
/// Represents an expanded node, that is "expanded" in the context of computed properties and repeat expansion.
/// For example, a Rectangle inside `for i in 0..3` and a `for j in 0..4` would have 12 expanded nodes representing the 12 virtual Rectangles in the
/// rendered scene graph.
/// `ExpandedNode`s are architecturally "type-blind" — while they store typed data e.g. inside `computed_properties` and `computed_common_properties`,
/// they require coordinating with their "type-aware" [`InstanceNode`] to perform operations on those properties.
mod expanded_node;
pub use expanded_node::{
    ExpandedNode, RuntimeResolvedPropertyColumns, RuntimeResolvedPropertyEntry,
    RuntimeSettingsCondition, RuntimeSettingsLayer, RuntimeSettingsSignatureEntry,
    RuntimeSettingsSource,
};

use self::node_interface::NodeLocal;

fn saturating_u128_to_u64(value: u128) -> u64 {
    value.min(u64::MAX as u128) as u64
}

struct FilteredRenderPlan {
    dirty_nodes: HashSet<ExpandedNodeIdentifier>,
    render_path_nodes: HashSet<ExpandedNodeIdentifier>,
}

fn viewport_info_property(
    viewport_bounds: &LocalProperty<TransformAndBounds<NodeLocal, Window>>,
) -> LocalProperty<Viewport> {
    let cloned_viewport = viewport_bounds.clone();
    let deps = [cloned_viewport.untyped()];
    LocalProperty::computed(
        move || {
            let viewport = cloned_viewport.get();
            Viewport::new(viewport.bounds.0, viewport.bounds.1)
        },
        &deps,
    )
}

fn viewport_number_property(
    viewport: &LocalProperty<Viewport>,
    name: &str,
    accessor: fn(Viewport) -> f64,
) -> LocalProperty<f64> {
    let cloned_viewport = viewport.clone();
    let deps = [cloned_viewport.untyped()];
    LocalProperty::computed_with_name(move || accessor(cloned_viewport.get()), &deps, name)
}

fn viewport_bool_property(
    viewport: &LocalProperty<Viewport>,
    name: &str,
    accessor: fn(Viewport) -> bool,
) -> LocalProperty<bool> {
    let cloned_viewport = viewport.clone();
    let deps = [cloned_viewport.untyped()];
    LocalProperty::computed_with_name(move || accessor(cloned_viewport.get()), &deps, name)
}

#[cfg(feature = "designtime")]
use {crate::InstanceNode, pax_designtime::DesigntimeManager, pax_runtime_api::borrow_mut};

#[derive(Clone)]
/// Engine-wide reactive globals exposed to every component frame.
pub struct Globals {
    pub elapsed_frames: LocalProperty<u64>,
    pub elapsed_millis: LocalProperty<u64>,
    pub viewport: LocalProperty<TransformAndBounds<NodeLocal, Window>>,
    pub gyro: LocalProperty<Gyro>,
    pub accel: LocalProperty<Accel>,
    pub route_location: LocalProperty<RouteLocation>,
    pub browser_allows_scroller_vector_layers: LocalProperty<bool>,
    pub browser_allows_nested_scroller_vector_layers: LocalProperty<bool>,
    pub platform: Platform,
    pub os: OS,
    pub target: TargetInfo,
    #[cfg(feature = "designtime")]
    pub designtime: Rc<RefCell<DesigntimeManager>>,
    pub get_elapsed_millis: Rc<dyn Fn() -> u128>,
}

impl Globals {
    /// Build the root stack frame containing built-in globals plus internal engine state.
    pub fn stack_frame(&self) -> Rc<RuntimePropertiesStackFrame> {
        let target = self.target;
        let viewport = viewport_info_property(&self.viewport);

        let target_var = Variable::new_from_typed_property(LocalProperty::new(target));
        let viewport_var = Variable::new_from_typed_property(viewport.clone());
        let gyro_var = Variable::new_from_typed_property(self.gyro.clone());
        let accel_var = Variable::new_from_typed_property(self.accel.clone());
        let elapsed_frames_var = Variable::new_from_typed_property(self.elapsed_frames.clone());
        let elapsed_millis_var = Variable::new_from_typed_property(self.elapsed_millis.clone());
        let route_location_var = Variable::new_from_typed_property(self.route_location.clone());

        let global_scope = vec![
            ("$target".to_string(), target_var),
            ("$viewport".to_string(), viewport_var),
            (
                "$web".to_string(),
                Variable::new_from_typed_property(LocalProperty::new(target.web)),
            ),
            (
                "$native".to_string(),
                Variable::new_from_typed_property(LocalProperty::new(target.native)),
            ),
            (
                "$ios".to_string(),
                Variable::new_from_typed_property(LocalProperty::new(target.ios)),
            ),
            (
                "$iphone".to_string(),
                Variable::new_from_typed_property(LocalProperty::new(target.iphone)),
            ),
            (
                "$ipad".to_string(),
                Variable::new_from_typed_property(LocalProperty::new(target.ipad)),
            ),
            (
                "$macos".to_string(),
                Variable::new_from_typed_property(LocalProperty::new(target.macos)),
            ),
            (
                "$android".to_string(),
                Variable::new_from_typed_property(LocalProperty::new(target.android)),
            ),
            (
                "$windows".to_string(),
                Variable::new_from_typed_property(LocalProperty::new(target.windows)),
            ),
            (
                "$linux".to_string(),
                Variable::new_from_typed_property(LocalProperty::new(target.linux)),
            ),
            (
                "$mobile".to_string(),
                Variable::new_from_typed_property(LocalProperty::new(target.mobile)),
            ),
            (
                "$desktop".to_string(),
                Variable::new_from_typed_property(LocalProperty::new(target.desktop)),
            ),
            (
                "$major".to_string(),
                Variable::new_from_typed_property(viewport_number_property(
                    &viewport,
                    "$major",
                    |viewport| viewport.major,
                )),
            ),
            (
                "$minor".to_string(),
                Variable::new_from_typed_property(viewport_number_property(
                    &viewport,
                    "$minor",
                    |viewport| viewport.minor,
                )),
            ),
            (
                "$aspect".to_string(),
                Variable::new_from_typed_property(viewport_number_property(
                    &viewport,
                    "$aspect",
                    |viewport| viewport.aspect,
                )),
            ),
            (
                "$landscape".to_string(),
                Variable::new_from_typed_property(viewport_bool_property(
                    &viewport,
                    "$landscape",
                    |viewport| viewport.landscape,
                )),
            ),
            (
                "$portrait".to_string(),
                Variable::new_from_typed_property(viewport_bool_property(
                    &viewport,
                    "$portrait",
                    |viewport| viewport.portrait,
                )),
            ),
            (
                "$square".to_string(),
                Variable::new_from_typed_property(viewport_bool_property(
                    &viewport,
                    "$square",
                    |viewport| viewport.square,
                )),
            ),
            ("$gyro".to_string(), gyro_var),
            ("$accel".to_string(), accel_var),
            ("$frames".to_string(), elapsed_frames_var),
            ("$millis".to_string(), elapsed_millis_var),
            (
                INTERNAL_ROUTE_LOCATION_SYMBOL.to_string(),
                route_location_var,
            ),
        ]
        .into_iter()
        .collect();

        let root_env = RuntimePropertiesStackFrame::new(global_scope);
        root_env
    }
}

impl std::fmt::Debug for Globals {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Globals")
            .field("elapsed_frames", &self.elapsed_frames)
            .field("elapsed_millis", &self.elapsed_millis)
            .field("viewport", &self.viewport)
            .field("gyro", &self.gyro)
            .field("accel", &self.accel)
            .field("route_location", &self.route_location)
            .field("target", &self.target)
            .finish_non_exhaustive()
    }
}

/// Singleton struct storing everything related to properties computation & rendering
pub struct PaxEngine {
    pub runtime_context: Rc<RuntimeContext>,
    pub root_expanded_node: Option<Rc<ExpandedNode>>,
    pub scroller_tiling_policy: layer_tiling::ScrollerTilingPolicy,
}

/// Selects the Rust state owner independently of the handler's target `NodeContext`.
pub enum HandlerLocation {
    /// A binding on a template element: use the component that authored the element.
    Inline,
    /// A component's own settings or conventional method: use the target component.
    Component,
}

/// Runtime event handler thunk generated from template bindings.
pub struct Handler {
    pub function: fn(Rc<RefCell<PaxAny>>, &NodeContext, Option<PaxAny>),
    pub location: HandlerLocation,
}

impl Handler {
    /// Build a handler whose `self` is the component that authored the inline binding.
    /// The context still describes the primitive or child component receiving the call.
    pub fn new_inline_handler(
        function: fn(Rc<RefCell<PaxAny>>, &NodeContext, Option<PaxAny>),
    ) -> Self {
        Handler {
            function,
            location: HandlerLocation::Inline,
        }
    }

    /// Build a handler whose `self` and context both belong to the target component.
    pub fn new_component_handler(
        function: fn(Rc<RefCell<PaxAny>>, &NodeContext, Option<PaxAny>),
    ) -> Self {
        Handler {
            function,
            location: HandlerLocation::Component,
        }
    }
}

/// Map from event key to one or more handlers registered on an instance node.
pub struct HandlerRegistry {
    pub handlers: HashMap<String, Vec<Handler>>,
}

impl Default for HandlerRegistry {
    fn default() -> Self {
        HandlerRegistry {
            handlers: HashMap::new(),
        }
    }
}

/// Central instance of the PaxEngine and runtime, intended to be created by a particular chassis.
/// Contains all rendering and runtime logic.
///
impl PaxEngine {
    /// Activates the mounted application exactly once. Candidate hosts defer this
    /// until their revision is committed.
    pub fn activate_application(&self) {
        self.runtime_context.application.activate();
    }

    /// Stops new application work, unmounts, then begins retained resource cleanup.
    pub fn shutdown(&mut self, reason: pax_runtime_api::StopReason) {
        let closing = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            self.runtime_context.application.begin_close()
        }));
        if matches!(closing, Ok(false)) {
            return;
        }
        let unmounted = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| self.unmount()));
        let stopped = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            self.runtime_context.application.finish_close(reason);
        }));
        // Teardown can run from Drop and native C entrypoints. Finish the
        // remaining cleanup even if an application hook unwinds.
        if closing.is_err() || unmounted.is_err() || stopped.is_err() {
            log::error!("application teardown panicked; remaining cleanup was attempted");
        }
    }

    #[cfg(not(feature = "designtime"))]
    fn build_globals(
        viewport_size: (f64, f64),
        platform: Platform,
        os: OS,
        get_elapsed_millis: Box<dyn Fn() -> u128>,
    ) -> Globals {
        use crate::api::math::Transform2;
        use pax_runtime_api::{properties, Functions};
        Functions::register_all_functions();

        let elapsed_frames = LocalProperty::new(0);
        let elapsed_millis = LocalProperty::new(saturating_u128_to_u64(get_elapsed_millis()));
        properties::register_time(&elapsed_frames);
        properties::register_millis(&elapsed_millis);
        Globals {
            elapsed_frames,
            elapsed_millis,
            viewport: LocalProperty::new(TransformAndBounds {
                transform: Transform2::identity(),
                bounds: viewport_size,
            }),
            gyro: LocalProperty::new(Gyro::default()),
            accel: LocalProperty::new(Accel::default()),
            route_location: LocalProperty::new(RouteLocation::root()),
            browser_allows_scroller_vector_layers: LocalProperty::new(true),
            browser_allows_nested_scroller_vector_layers: LocalProperty::new(true),
            platform,
            os,
            target: TargetInfo::new(platform, os),
            get_elapsed_millis: Rc::from(get_elapsed_millis),
        }
    }

    #[cfg(feature = "designtime")]
    fn build_globals(
        viewport_size: (f64, f64),
        designtime: Rc<RefCell<DesigntimeManager>>,
        platform: Platform,
        os: OS,
        get_elapsed_millis: Box<dyn Fn() -> u128>,
    ) -> Globals {
        use pax_runtime_api::{math::Transform2, properties, Functions};
        Functions::register_all_functions();

        let elapsed_frames = LocalProperty::new(0);
        let elapsed_millis = LocalProperty::new(saturating_u128_to_u64(get_elapsed_millis()));
        properties::register_time(&elapsed_frames);
        properties::register_millis(&elapsed_millis);
        Globals {
            elapsed_frames,
            elapsed_millis,
            viewport: LocalProperty::new(TransformAndBounds {
                transform: Transform2::identity(),
                bounds: viewport_size,
            }),
            gyro: LocalProperty::new(Gyro::default()),
            accel: LocalProperty::new(Accel::default()),
            route_location: LocalProperty::new(RouteLocation::root()),
            browser_allows_scroller_vector_layers: LocalProperty::new(true),
            browser_allows_nested_scroller_vector_layers: LocalProperty::new(true),
            platform,
            os,
            target: TargetInfo::new(platform, os),
            designtime: designtime.clone(),
            get_elapsed_millis: Rc::from(get_elapsed_millis),
        }
    }

    #[cfg(feature = "designtime")]
    pub fn new_empty_with_designtime(
        viewport_size: (f64, f64),
        designtime: Rc<RefCell<DesigntimeManager>>,
        platform: Platform,
        os: OS,
        get_elapsed_millis: Box<dyn Fn() -> u128>,
        scroller_tiling_policy: layer_tiling::ScrollerTilingPolicy,
    ) -> Self {
        let globals =
            Self::build_globals(viewport_size, designtime, platform, os, get_elapsed_millis);
        let runtime_context = Rc::new(RuntimeContext::new_empty(globals));
        PaxEngine {
            runtime_context,
            root_expanded_node: None,
            scroller_tiling_policy,
        }
    }

    #[cfg(not(feature = "designtime"))]
    pub fn new_empty(
        viewport_size: (f64, f64),
        platform: Platform,
        os: OS,
        get_elapsed_millis: Box<dyn Fn() -> u128>,
        scroller_tiling_policy: layer_tiling::ScrollerTilingPolicy,
    ) -> Self {
        let globals = Self::build_globals(viewport_size, platform, os, get_elapsed_millis);
        let runtime_context = Rc::new(RuntimeContext::new(globals));
        PaxEngine {
            runtime_context,
            root_expanded_node: None,
            scroller_tiling_policy,
        }
    }

    /// Mount a root component tree into an existing runtime kernel.
    pub fn mount_root_component(
        &mut self,
        main_component_instance: Rc<ComponentInstance>,
    ) -> Rc<ExpandedNode> {
        let _graph = self.runtime_context.property_graph.enter();
        self.unmount();
        let root_node = ExpandedNode::initialize_root(
            Rc::clone(&main_component_instance),
            &self.runtime_context,
        );
        self.runtime_context.register_root_expanded_node(&root_node);
        self.root_expanded_node = Some(Rc::clone(&root_node));
        root_node
    }

    /// Detach the mounted root component tree, leaving the runtime kernel empty.
    pub fn unmount(&mut self) {
        let _graph = self.runtime_context.property_graph.enter();
        let Some(root_expanded_node) = self.root_expanded_node.take() else {
            return;
        };

        #[cfg(feature = "designtime")]
        let root_id = root_expanded_node.id;
        root_expanded_node.recurse_unmount(&self.runtime_context);
        self.runtime_context.clear_root_expanded_node();
        self.runtime_context.layer_count.set(0);
        self.runtime_context.clear_layer_scroller_owners();
        self.runtime_context.set_root_scroller_id(None);
        self.runtime_context.clear_visual_viewport_state();

        #[cfg(feature = "designtime")]
        if self
            .runtime_context
            .get_userland_root_expanded_node()
            .as_ref()
            .is_some_and(|node| node.id == root_id)
        {
            self.runtime_context.set_userland_root_expanded_node(None);
        }
    }

    #[cfg(not(feature = "designtime"))]
    pub fn new(
        main_component_instance: Rc<ComponentInstance>,
        viewport_size: (f64, f64),
        platform: Platform,
        os: OS,
        get_elapsed_millis: Box<dyn Fn() -> u128>,
        scroller_tiling_policy: layer_tiling::ScrollerTilingPolicy,
    ) -> Self {
        let mut engine = Self::new_empty(
            viewport_size,
            platform,
            os,
            get_elapsed_millis,
            scroller_tiling_policy,
        );
        engine.mount_root_component(main_component_instance);
        engine
    }

    #[cfg(feature = "designtime")]
    pub fn new_with_designtime(
        userland_main_component_instance: Rc<ComponentInstance>,
        viewport_size: (f64, f64),
        designtime: Rc<RefCell<DesigntimeManager>>,
        platform: Platform,
        os: OS,
        get_elapsed_millis: Box<dyn Fn() -> u128>,
        scroller_tiling_policy: layer_tiling::ScrollerTilingPolicy,
    ) -> Self {
        let mut engine = Self::new_empty_with_designtime(
            viewport_size,
            designtime,
            platform,
            os,
            get_elapsed_millis,
            scroller_tiling_policy,
        );
        engine
            .runtime_context
            .set_userland_root_instance_node(Some(userland_main_component_instance.clone()));
        let root_expanded_node = engine.mount_root_component(userland_main_component_instance);
        engine
            .runtime_context
            .set_userland_root_expanded_node(Some(root_expanded_node));
        engine
    }

    #[cfg(feature = "designtime")]
    pub fn partial_update_expanded_node(&mut self, new_instance: Rc<dyn InstanceNode>) {
        // update the expanded nodes that just got a new instance node
        let unique_id = new_instance
            .base()
            .template_node_identifier
            .clone()
            .expect("new instance node has unique identifier");

        let nodes = self
            .runtime_context
            .get_expanded_nodes_by_global_ids(&unique_id);
        for node in nodes {
            node.recreate_with_new_data(new_instance.clone(), &self.runtime_context);
        }
    }

    #[cfg(feature = "designtime")]
    pub fn full_reload_userland(&mut self, new_userland_instance: Rc<dyn InstanceNode>) {
        let node = borrow!(self.runtime_context.userland_root_expanded_node)
            .as_ref()
            .map(Rc::clone)
            .unwrap();
        *borrow_mut!(self.runtime_context.userland_frame_instance_node) =
            Some(Rc::clone(&new_userland_instance));
        node.fully_recreate_with_new_data(new_userland_instance.clone(), &self.runtime_context);
    }

    // NOTES: this is the order of different things being computed in recurse-expand-nodes
    // - expanded_node instantiated from instance_node.

    /// Workhorse methods of every tick.  Will be executed up to 240 Hz.
    /// Three phases:
    /// 1. Expand nodes & compute properties; recurse entire instance tree and evaluate ExpandedNodes, stitching
    ///    together parent/child relationships between ExpandedNodes along the way.
    /// 2. Compute layout (z-index & TransformAndBounds) by visiting ExpandedNode tree
    ///    in rendering order, writing computed rendering-specific values to ExpandedNodes
    /// 3. Render:
    ///     a. find lowest node (last child of last node)
    ///     b. start rendering, from lowest node on-up, throughout tree
    pub fn tick(&mut self) -> Vec<NativeMessage> {
        if matches!(
            self.runtime_context.application.context().phase(),
            pax_runtime_api::AppPhase::Closing | pax_runtime_api::AppPhase::Closed
        ) {
            return Vec::new();
        }
        let _graph = self.runtime_context.property_graph.enter();
        self.runtime_context.property_graph.import();
        //
        // 1. UPDATE NODES (properties, etc.). This part we should be able to
        // completely remove once reactive properties dirty-dag is a thing.
        //
        if let Some(root_expanded_node) = &self.root_expanded_node {
            root_expanded_node.recurse_update(&self.runtime_context);
            if self.runtime_context.has_import_settings_nodes() {
                root_expanded_node.recurse_sync_import_settings(&self.runtime_context);
            }
        }

        let ctx = &self.runtime_context;
        ctx.drain_node_effects();
        let deliveries = ctx
            .application
            .dispatcher()
            .drain(|| ctx.drain_node_effects());
        if let Err(error) = deliveries {
            log::error!("UI completion panicked: {error}");
            self.shutdown(pax_runtime_api::StopReason::HostClosed);
            return Vec::new();
        }
        self.run_lifecycle_handlers(TICK_HANDLERS, ctx.tick_handler_nodes());
        ctx.drain_node_effects();
        self.run_lifecycle_handlers(PRE_RENDER_HANDLERS, ctx.pre_render_handler_nodes());
        ctx.drain_node_effects();

        let globals = ctx.globals();
        let time = &globals.elapsed_frames;
        time.set(time.get() + 1);
        globals
            .elapsed_millis
            .set(saturating_u128_to_u64((globals.get_elapsed_millis)()));

        ctx.flush_custom_events().unwrap();

        // Advancing the clock or dispatching queued events can switch branches.
        // Settle those effects before final layout and the retained render plan;
        // otherwise a replay can clear the old subtree but omit its replacement.
        ctx.drain_node_effects();
        ctx.prepare_scene_geometry();
        ctx.dispatch_viewport_proximity();
        // Handler mutations settle for drawing, but observation samples at most once
        // per tick. Their invalidations remain pending for the next display tick.
        // Observation uses layout/scroll geometry, not compositing assignments.
        // Finalize occlusion only after handlers settle, so animation plus a
        // proximity callback does not traverse the whole scene twice in one tick.
        ctx.drain_node_effects();
        if ctx.take_occlusion_dirty() {
            if let Some(root) = &self.root_expanded_node {
                occlusion::update_node_occlusion(root, ctx);
            }
            ctx.drain_node_effects();
        }
        ctx.prepare_scene_geometry();
        occlusion::update_native_culling(ctx, self.scroller_tiling_policy);
        let native_messages = ctx.take_native_messages();
        native_messages
    }

    fn run_lifecycle_handlers(&self, handler_key: &str, nodes: Vec<ExpandedNodeIdentifier>) {
        for node_id in nodes {
            if let Some(node) = self.runtime_context.get_expanded_node_by_eid(node_id) {
                node.run_lifecycle_handlers(handler_key, &self.runtime_context);
            }
        }
    }

    fn build_filtered_render_plan(
        &self,
        root: &Rc<ExpandedNode>,
        dirty_node_ids: &[ExpandedNodeIdentifier],
    ) -> Result<FilteredRenderPlan, &'static str> {
        let dirty_nodes: HashSet<_> = dirty_node_ids.iter().copied().collect();
        let mut render_path_nodes = HashSet::new();

        for dirty_node_id in &dirty_nodes {
            let mut node = self
                .runtime_context
                .get_expanded_node_by_eid(*dirty_node_id)
                .ok_or("missing_dirty_node")?;
            let mut local_path = HashSet::new();
            loop {
                if !local_path.insert(node.id) {
                    return Err("render_parent_cycle");
                }
                if node.is_unclippable() {
                    return Err("unclippable_path");
                }
                render_path_nodes.insert(node.id);
                if node.id == root.id {
                    break;
                }
                node = node.render_parent_node().ok_or("missing_render_parent")?;
            }
        }

        if !render_path_nodes.contains(&root.id) {
            return Err("missing_root_path");
        }

        Ok(FilteredRenderPlan {
            dirty_nodes,
            render_path_nodes,
        })
    }

    fn dirty_layer_can_use_targeted_replay_nodes(
        &self,
        layer: usize,
        dirty_node_ids: &[ExpandedNodeIdentifier],
        targeted_node_ids: &HashSet<u32>,
    ) -> bool {
        for dirty_node_id in dirty_node_ids {
            let Some(node) = self
                .runtime_context
                .get_expanded_node_by_eid(*dirty_node_id)
            else {
                return false;
            };
            if node.occlusion.get().render_layer_id != layer
                || borrow!(node.instance_node).base().flags().layer != crate::api::Layer::Canvas
            {
                continue;
            }
            if !targeted_node_ids.contains(&dirty_node_id.to_u32()) {
                return false;
            }
        }
        true
    }

    pub fn render(&mut self, rcs: &mut dyn RenderContext) {
        if matches!(
            self.runtime_context.application.context().phase(),
            pax_runtime_api::AppPhase::Closing | pax_runtime_api::AppPhase::Closed
        ) {
            return;
        }
        let _graph = self.runtime_context.property_graph.enter();
        use crate::render_instrumentation::{Phase, Span};
        let _render_timing = Span::new(Phase::Render);
        self.update_layer_count(rcs);
        self.runtime_context.prepare_scene_geometry();

        if !self.runtime_context.has_canvas_render_work() {
            return;
        }

        let mut removals = self.runtime_context.take_canvas_node_removals();
        // Resizing drops truncated layers and their retained nodes together.
        // Retrying their old removals would keep nonexistent layers dirty forever.
        removals.retain(|(layer, _)| *layer < self.runtime_context.layer_count.get());
        let mut dirty_layers = self.runtime_context.dirty_canvas_layers();
        dirty_layers.extend(removals.iter().map(|(layer, _)| *layer));
        dirty_layers.sort_unstable();
        dirty_layers.dedup();
        let mut lighting_layers = dirty_layers.clone();
        if self.runtime_context.take_scene_lighting_dirty() {
            lighting_layers.extend(0..self.runtime_context.layer_count.get());
            lighting_layers.sort_unstable();
            lighting_layers.dedup();
        }
        for layer in &lighting_layers {
            let collect_timing = Span::new(Phase::Lighting);
            let lighting = self
                .runtime_context
                .collect_scene_lighting_for_layer(*layer);
            drop(collect_timing);
            let _upload_timing = Span::new(Phase::LightingUpload);
            rcs.set_scene_lighting(*layer, &lighting);
        }
        // Slot/scope changes can invalidate node masks during lighting resolution.
        // Value-only changes must not enter the full-canvas clear/replay path.
        dirty_layers.extend(self.runtime_context.dirty_canvas_layers());
        dirty_layers.sort_unstable();
        dirty_layers.dedup();
        let prepare_timing = Span::new(Phase::Prepare);
        let removal_layers: HashSet<_> = removals.iter().map(|(layer, _)| *layer).collect();
        let targeted_replay_node_ids = self.runtime_context.take_targeted_canvas_replay_node_ids();
        let dirty_node_ids_before_expansion = self.runtime_context.dirty_canvas_node_ids();
        let retains_canvas_nodes = rcs.retains_canvas_nodes();
        let mut retained_full_replay_layers = Vec::new();
        if retains_canvas_nodes {
            for layer in &dirty_layers {
                let has_retained_removal = removal_layers.contains(layer);
                let has_targeted_conflict =
                    targeted_replay_node_ids
                        .get(layer)
                        .is_some_and(|targeted_node_ids| {
                            !self.dirty_layer_can_use_targeted_replay_nodes(
                                *layer,
                                &dirty_node_ids_before_expansion,
                                targeted_node_ids,
                            )
                        });
                if has_retained_removal || has_targeted_conflict {
                    rcs.clear_targeted_replay(*layer);
                    self.runtime_context
                        .mark_canvas_nodes_on_layer_dirty(*layer);
                    retained_full_replay_layers.push(*layer);
                }
            }
        }
        if !retains_canvas_nodes && (!dirty_layers.is_empty() || !removals.is_empty()) {
            for layer in &dirty_layers {
                let can_use_targeted_replay_nodes = targeted_replay_node_ids
                    .get(layer)
                    .is_some_and(|targeted_node_ids| {
                        !removal_layers.contains(layer)
                            && self.dirty_layer_can_use_targeted_replay_nodes(
                                *layer,
                                &dirty_node_ids_before_expansion,
                                targeted_node_ids,
                            )
                    });
                if !can_use_targeted_replay_nodes {
                    rcs.clear_targeted_replay(*layer);
                    self.runtime_context
                        .mark_canvas_nodes_on_layer_dirty(*layer);
                }
            }
        }
        let dirty_node_ids = self.runtime_context.dirty_canvas_node_ids();
        let has_dirty_nodes = !dirty_node_ids.is_empty();
        let has_node_removals = !removals.is_empty();
        if !has_dirty_nodes && !has_node_removals {
            for layer in &dirty_layers {
                rcs.clear(*layer);
            }
        } else if !retains_canvas_nodes {
            for layer in &dirty_layers {
                rcs.clear(*layer);
            }
        } else {
            for layer in retained_full_replay_layers {
                rcs.clear(layer);
            }
        }

        let mut failed_removal_layers = Vec::new();
        for (layer, node_id) in removals {
            if !rcs.remove_node(layer, node_id) {
                self.runtime_context
                    .enqueue_canvas_node_removal(layer, node_id);
                failed_removal_layers.push(layer);
            }
        }

        // This is pretty useful during debugging - left it here since I use it often. /Sam
        // crate::api::log(&format!("tree: {:#?}", self.root_node));
        if has_dirty_nodes {
            if let Some(root_expanded_node) = &self.root_expanded_node {
                match self.build_filtered_render_plan(root_expanded_node, &dirty_node_ids) {
                    Ok(plan) => {
                        let mut stats = expanded_node::FilteredRenderStats::default();
                        root_expanded_node.recurse_render_filtered(
                            &self.runtime_context,
                            rcs,
                            &plan.render_path_nodes,
                            &plan.dirty_nodes,
                            &mut stats,
                        );
                        #[cfg(debug_assertions)]
                        log::trace!(
                            "[pax-render-filter] dirty_nodes={} path_nodes={} visited_path_nodes={} dirty_nodes_rendered={} skipped_subtrees={}",
                            plan.dirty_nodes.len(),
                            plan.render_path_nodes.len(),
                            stats.path_nodes_visited,
                            stats.dirty_nodes_rendered,
                            stats.skipped_subtrees,
                        );
                    }
                    Err(_reason) => {
                        #[cfg(debug_assertions)]
                        log::trace!(
                            "[pax-render-filter] fallback={} dirty_nodes={}",
                            _reason,
                            dirty_node_ids.len(),
                        );
                        root_expanded_node.recurse_render_queue(&self.runtime_context, rcs);
                    }
                }
            }
        }
        self.runtime_context.recurse_flush_queued_renders(rcs);

        self.runtime_context.clear_all_dirty_canvases();
        for layer in failed_removal_layers {
            self.runtime_context.set_canvas_dirty(layer);
        }

        drop(prepare_timing);
        let _flush_timing = Span::new(Phase::Flush);
        for layer in lighting_layers {
            rcs.flush(layer, Rc::clone(&self.runtime_context.dirty_canvases));
        }
    }

    pub fn get_expanded_node(&self, id: ExpandedNodeIdentifier) -> Option<Rc<ExpandedNode>> {
        let val = self.runtime_context.get_expanded_node_by_eid(id).clone();
        val.map(|v| v.clone())
    }

    /// Called by chassis when viewport size changes, e.g. with native window resizes
    pub fn set_viewport_size(&mut self, new_viewport_size: (f64, f64)) {
        const VIEWPORT_SIZE_EPSILON: f64 = 0.001;
        let current_viewport_size = self.runtime_context.globals().viewport.get().bounds;
        if (current_viewport_size.0 - new_viewport_size.0).abs() <= VIEWPORT_SIZE_EPSILON
            && (current_viewport_size.1 - new_viewport_size.1).abs() <= VIEWPORT_SIZE_EPSILON
        {
            return;
        }

        self.runtime_context.edit_globals(|globals| {
            globals
                .viewport
                .update(|t_and_b| t_and_b.bounds = new_viewport_size);
        });
        self.runtime_context.invalidate_viewport_presentation();
        self.runtime_context.mark_layer_canvas_plans_dirty();
        self.runtime_context.mark_occlusion_dirty();
    }

    pub fn update_layer_count(&self, rcs: &mut dyn RenderContext) {
        let curr_layer_count = self.runtime_context.layer_count.get();
        // A renderer can be replaced or shared across successive app revisions.
        // Its actual layer set, not process-global history, determines the resize.
        if rcs.layers() != curr_layer_count {
            rcs.resize_layers_to(
                curr_layer_count,
                Rc::clone(&self.runtime_context.dirty_canvases),
            );
        }
        self.runtime_context
            .resize_canvas_layers_to(curr_layer_count);
    }

    pub fn global_dispatch_focus(&self, args: Focus) -> bool {
        let Some(root_expanded_node) = &self.root_expanded_node else {
            return false;
        };
        let mut prevent_default = false;
        root_expanded_node.recurse_visit_postorder(&mut |expanded_node| {
            prevent_default |= expanded_node.dispatch_focus(
                Event::new(args.clone()),
                &self.runtime_context.globals(),
                &self.runtime_context,
            );
        });
        prevent_default
    }

    pub fn global_dispatch_select_start(&self, args: SelectStart) -> bool {
        let Some(root_expanded_node) = &self.root_expanded_node else {
            return false;
        };
        let mut prevent_default = false;
        root_expanded_node.recurse_visit_postorder(&mut |expanded_node| {
            prevent_default |= expanded_node.dispatch_select_start(
                Event::new(args.clone()),
                &self.runtime_context.globals(),
                &self.runtime_context,
            );
        });
        prevent_default
    }

    pub fn global_dispatch_key_down(&self, args: KeyDown) -> bool {
        let Some(root_expanded_node) = &self.root_expanded_node else {
            return false;
        };
        let mut prevent_default = false;
        root_expanded_node.recurse_visit_postorder(&mut |expanded_node| {
            prevent_default |= expanded_node.dispatch_key_down(
                Event::new(args.clone()),
                &self.runtime_context.globals(),
                &self.runtime_context,
            );
        });
        prevent_default
    }

    pub fn global_dispatch_key_up(&self, args: KeyUp) -> bool {
        let Some(root_expanded_node) = &self.root_expanded_node else {
            return false;
        };
        let mut prevent_default = false;
        root_expanded_node.recurse_visit_postorder(&mut |expanded_node| {
            prevent_default |= expanded_node.dispatch_key_up(
                Event::new(args.clone()),
                &self.runtime_context.globals(),
                &self.runtime_context,
            );
        });
        prevent_default
    }

    pub fn global_dispatch_key_press(&self, args: KeyPress) -> bool {
        let Some(root_expanded_node) = &self.root_expanded_node else {
            return false;
        };
        let mut prevent_default = false;
        root_expanded_node.recurse_visit_postorder(&mut |expanded_node| {
            prevent_default |= expanded_node.dispatch_key_press(
                Event::new(args.clone()),
                &self.runtime_context.globals(),
                &self.runtime_context,
            );
        });
        prevent_default
    }

    pub fn global_dispatch_gyro(&self, args: Gyro) -> bool {
        let mut prevent_default = false;
        for node_id in self.runtime_context.gyro_handler_nodes() {
            let Some(expanded_node) = self.runtime_context.get_expanded_node_by_eid(node_id) else {
                continue;
            };
            prevent_default |= expanded_node.dispatch_gyro(
                Event::new(args.clone()),
                &self.runtime_context.globals(),
                &self.runtime_context,
            );
        }
        prevent_default
    }

    pub fn global_dispatch_accel(&self, args: Accel) -> bool {
        let mut prevent_default = false;
        for node_id in self.runtime_context.accel_handler_nodes() {
            let Some(expanded_node) = self.runtime_context.get_expanded_node_by_eid(node_id) else {
                continue;
            };
            prevent_default |= expanded_node.dispatch_accel(
                Event::new(args.clone()),
                &self.runtime_context.globals(),
                &self.runtime_context,
            );
        }
        prevent_default
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::constants::{ACCEL_HANDLERS, GYRO_HANDLERS, PRE_RENDER_HANDLERS, TICK_HANDLERS};
    use crate::{InstanceNode, InstantiationArgs};
    use pax_runtime_api::pax_value::{PaxAny, PaxValue};
    use std::cell::RefCell;
    use std::sync::atomic::{AtomicUsize, Ordering};

    static TICK_CALLS: AtomicUsize = AtomicUsize::new(0);
    static PRE_RENDER_CALLS: AtomicUsize = AtomicUsize::new(0);
    static GYRO_CALLS: AtomicUsize = AtomicUsize::new(0);
    static ACCEL_CALLS: AtomicUsize = AtomicUsize::new(0);

    fn count_tick_handler(
        _properties: Rc<RefCell<PaxAny>>,
        _ctx: &NodeContext,
        _event: Option<PaxAny>,
    ) {
        TICK_CALLS.fetch_add(1, Ordering::SeqCst);
    }

    fn count_pre_render_handler(
        _properties: Rc<RefCell<PaxAny>>,
        _ctx: &NodeContext,
        _event: Option<PaxAny>,
    ) {
        PRE_RENDER_CALLS.fetch_add(1, Ordering::SeqCst);
    }

    fn count_gyro_handler(
        _properties: Rc<RefCell<PaxAny>>,
        _ctx: &NodeContext,
        _event: Option<PaxAny>,
    ) {
        GYRO_CALLS.fetch_add(1, Ordering::SeqCst);
    }

    fn count_accel_handler(
        _properties: Rc<RefCell<PaxAny>>,
        _ctx: &NodeContext,
        _event: Option<PaxAny>,
    ) {
        ACCEL_CALLS.fetch_add(1, Ordering::SeqCst);
    }

    fn empty_component() -> Rc<ComponentInstance> {
        <ComponentInstance as InstanceNode>::instantiate(InstantiationArgs {
            prototypical_common_properties: crate::CommonPropertiesInit::Default,
            prototypical_properties: crate::PropertiesInit::Factory(Box::new(|_, _| {
                Some(Rc::new(RefCell::new(PaxAny::Builtin(PaxValue::default()))))
            })),
            handler_registry: None,
            children: None,
            component_template: None,
            component_settings: None,
            template_node_identifier: None,
            template_node_type_id: None,
            template_node_selector_info: None,
            transition_config: Default::default(),
            properties_scope: crate::PropertiesScopeInit::None,
        })
    }

    fn component_with_lifecycle_handlers() -> Rc<ComponentInstance> {
        let mut registry = HandlerRegistry::default();
        registry.handlers.insert(
            TICK_HANDLERS.to_string(),
            vec![Handler::new_inline_handler(count_tick_handler)],
        );
        registry.handlers.insert(
            PRE_RENDER_HANDLERS.to_string(),
            vec![Handler::new_inline_handler(count_pre_render_handler)],
        );

        <ComponentInstance as InstanceNode>::instantiate(InstantiationArgs {
            prototypical_common_properties: crate::CommonPropertiesInit::Default,
            prototypical_properties: crate::PropertiesInit::Factory(Box::new(|_, _| {
                Some(Rc::new(RefCell::new(PaxAny::Builtin(PaxValue::default()))))
            })),
            handler_registry: Some(Rc::new(RefCell::new(registry))),
            children: None,
            component_template: None,
            component_settings: None,
            template_node_identifier: None,
            template_node_type_id: None,
            template_node_selector_info: None,
            transition_config: Default::default(),
            properties_scope: crate::PropertiesScopeInit::None,
        })
    }

    fn component_with_sensor_handlers() -> Rc<ComponentInstance> {
        let mut registry = HandlerRegistry::default();
        registry.handlers.insert(
            GYRO_HANDLERS.to_string(),
            vec![Handler::new_inline_handler(count_gyro_handler)],
        );
        registry.handlers.insert(
            ACCEL_HANDLERS.to_string(),
            vec![Handler::new_inline_handler(count_accel_handler)],
        );

        <ComponentInstance as InstanceNode>::instantiate(InstantiationArgs {
            prototypical_common_properties: crate::CommonPropertiesInit::Default,
            prototypical_properties: crate::PropertiesInit::Factory(Box::new(|_, _| {
                Some(Rc::new(RefCell::new(PaxAny::Builtin(PaxValue::default()))))
            })),
            handler_registry: Some(Rc::new(RefCell::new(registry))),
            children: None,
            component_template: None,
            component_settings: None,
            template_node_identifier: None,
            template_node_type_id: None,
            template_node_selector_info: None,
            transition_config: Default::default(),
            properties_scope: crate::PropertiesScopeInit::None,
        })
    }

    fn object_field(value: PaxValue, field: &str) -> PaxValue {
        let PaxValue::Object(fields) = value else {
            panic!("expected object value");
        };
        fields
            .into_iter()
            .find_map(|(name, value)| (name == field).then_some(value))
            .unwrap_or_else(|| panic!("expected object field {field}"))
    }

    #[test]
    fn empty_engine_can_tick_and_mount_later() {
        let mut engine = crate::test_support::empty_engine(
            (320.0, 240.0),
            Platform::Web,
            OS::Mac,
            Box::new(|| 0),
            layer_tiling::ScrollerTilingPolicy::default(),
        );

        assert!(engine.root_expanded_node.is_none());
        assert!(engine.runtime_context.get_root_expanded_node().is_none());
        assert!(engine.tick().is_empty());

        let root = engine.mount_root_component(empty_component());
        assert_eq!(
            engine.root_expanded_node.as_ref().map(|node| node.id),
            Some(root.id)
        );
        assert_eq!(
            engine
                .runtime_context
                .get_root_expanded_node()
                .map(|node| node.id),
            Some(root.id)
        );
        let _ = engine.tick();
    }

    #[test]
    fn unmount_clears_registered_root() {
        let mut engine = crate::test_support::empty_engine(
            (320.0, 240.0),
            Platform::Web,
            OS::Mac,
            Box::new(|| 0),
            layer_tiling::ScrollerTilingPolicy::default(),
        );

        engine.mount_root_component(empty_component());
        engine.unmount();

        assert!(engine.root_expanded_node.is_none());
        assert!(engine.runtime_context.get_root_expanded_node().is_none());
    }

    #[test]
    fn globals_expose_sensor_values_to_stack_frame() {
        let engine = crate::test_support::empty_engine(
            (320.0, 240.0),
            Platform::Web,
            OS::Mac,
            Box::new(|| 0),
            layer_tiling::ScrollerTilingPolicy::default(),
        );
        let globals = engine.runtime_context.globals();
        globals.gyro.set(Gyro {
            x: 1.0,
            y: 2.0,
            z: 3.0,
        });
        globals.accel.set(Accel {
            x: 4.0,
            y: 5.0,
            z: 6.0,
        });

        assert_eq!(
            globals
                .stack_frame()
                .resolve_symbol("$gyro")
                .unwrap()
                .get_as_pax_value(),
            PaxValue::Object(
                vec![
                    ("x".to_string(), PaxValue::Numeric(1.0.into())),
                    ("y".to_string(), PaxValue::Numeric(2.0.into())),
                    ("z".to_string(), PaxValue::Numeric(3.0.into())),
                ]
                .into_iter()
                .collect(),
            )
        );
        assert_eq!(
            globals
                .stack_frame()
                .resolve_symbol("$accel")
                .unwrap()
                .get_as_pax_value(),
            PaxValue::Object(
                vec![
                    ("x".to_string(), PaxValue::Numeric(4.0.into())),
                    ("y".to_string(), PaxValue::Numeric(5.0.into())),
                    ("z".to_string(), PaxValue::Numeric(6.0.into())),
                ]
                .into_iter()
                .collect(),
            )
        );
    }

    #[test]
    fn lifecycle_handlers_run_once_per_tick() {
        TICK_CALLS.store(0, Ordering::SeqCst);
        PRE_RENDER_CALLS.store(0, Ordering::SeqCst);
        let mut engine = crate::test_support::empty_engine(
            (320.0, 240.0),
            Platform::Web,
            OS::Mac,
            Box::new(|| 0),
            layer_tiling::ScrollerTilingPolicy::default(),
        );

        engine.mount_root_component(component_with_lifecycle_handlers());
        let _ = engine.tick();

        assert_eq!(TICK_CALLS.load(Ordering::SeqCst), 1);
        assert_eq!(PRE_RENDER_CALLS.load(Ordering::SeqCst), 1);
    }

    #[test]
    fn sensor_handlers_dispatch_through_registered_nodes() {
        GYRO_CALLS.store(0, Ordering::SeqCst);
        ACCEL_CALLS.store(0, Ordering::SeqCst);
        let mut engine = crate::test_support::empty_engine(
            (320.0, 240.0),
            Platform::Web,
            OS::Mac,
            Box::new(|| 0),
            layer_tiling::ScrollerTilingPolicy::default(),
        );

        assert!(!engine.global_dispatch_gyro(Gyro::default()));
        assert!(!engine.global_dispatch_accel(Accel::default()));
        engine.mount_root_component(component_with_sensor_handlers());
        assert!(!engine.global_dispatch_gyro(Gyro::default()));
        assert!(!engine.global_dispatch_accel(Accel::default()));

        assert_eq!(GYRO_CALLS.load(Ordering::SeqCst), 1);
        assert_eq!(ACCEL_CALLS.load(Ordering::SeqCst), 1);
    }

    #[test]
    fn globals_expose_clock_aliases_to_stack_frame() {
        let engine = crate::test_support::empty_engine(
            (320.0, 240.0),
            Platform::Web,
            OS::Mac,
            Box::new(|| 123),
            layer_tiling::ScrollerTilingPolicy::default(),
        );
        let globals = engine.runtime_context.globals();
        let stack = globals.stack_frame();

        assert_eq!(
            stack.resolve_symbol("$frames").unwrap().get_as_pax_value(),
            PaxValue::Numeric(0.into())
        );
        assert_eq!(
            stack.resolve_symbol("$millis").unwrap().get_as_pax_value(),
            PaxValue::Numeric(123.into())
        );
        let old_frames_symbol = format!("{}{}", "$frames", "_elapsed");
        let old_millis_symbol = format!("{}{}", "$elapsed", "_millis");
        assert!(stack.resolve_symbol(&old_frames_symbol).is_none());
        assert!(stack.resolve_symbol(&old_millis_symbol).is_none());
    }

    #[test]
    fn globals_expose_target_aliases_to_stack_frame() {
        let engine = crate::test_support::empty_engine(
            (320.0, 240.0),
            Platform::Native,
            OS::IPad,
            Box::new(|| 0),
            layer_tiling::ScrollerTilingPolicy::default(),
        );
        let globals = engine.runtime_context.globals();
        let stack = globals.stack_frame();

        assert_eq!(
            stack.resolve_symbol("$ios").unwrap().get_as_pax_value(),
            PaxValue::Bool(true)
        );
        assert_eq!(
            stack.resolve_symbol("$ipad").unwrap().get_as_pax_value(),
            PaxValue::Bool(true)
        );
        assert_eq!(
            stack.resolve_symbol("$iphone").unwrap().get_as_pax_value(),
            PaxValue::Bool(false)
        );
        assert_eq!(
            stack.resolve_symbol("$native").unwrap().get_as_pax_value(),
            PaxValue::Bool(true)
        );
        assert_eq!(
            object_field(
                stack.resolve_symbol("$target").unwrap().get_as_pax_value(),
                "ipad"
            ),
            PaxValue::Bool(true)
        );
    }

    #[test]
    fn globals_expose_viewport_orientation_aliases_to_stack_frame() {
        let engine = crate::test_support::empty_engine(
            (320.0, 240.0),
            Platform::Web,
            OS::Mac,
            Box::new(|| 0),
            layer_tiling::ScrollerTilingPolicy::default(),
        );
        let globals = engine.runtime_context.globals();
        let stack = globals.stack_frame();

        assert_eq!(
            stack
                .resolve_symbol("$landscape")
                .unwrap()
                .get_as_pax_value(),
            PaxValue::Bool(true)
        );
        assert_eq!(
            stack.resolve_symbol("$major").unwrap().get_as_pax_value(),
            PaxValue::Numeric(320.0.into())
        );
        assert_eq!(
            object_field(
                stack
                    .resolve_symbol("$viewport")
                    .unwrap()
                    .get_as_pax_value(),
                "minor"
            ),
            PaxValue::Numeric(240.0.into())
        );

        globals.viewport.update(|viewport| {
            viewport.bounds = (240.0, 320.0);
        });

        assert_eq!(
            stack
                .resolve_symbol("$portrait")
                .unwrap()
                .get_as_pax_value(),
            PaxValue::Bool(true)
        );
        assert_eq!(
            stack.resolve_symbol("$minor").unwrap().get_as_pax_value(),
            PaxValue::Numeric(240.0.into())
        );
    }
}

impl Drop for PaxEngine {
    fn drop(&mut self) {
        self.shutdown(pax_runtime_api::StopReason::HostClosed);
    }
}