masonry_core 0.5.0

Traits and types of the Masonry toolkit.
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
// Copyright 2024 the Xilem Authors
// SPDX-License-Identifier: Apache-2.0

use std::collections::{HashMap, HashSet};

use tracing::{info_span, trace};
use tree_arena::{ArenaMut, ArenaMutList};
use ui_events::pointer::PointerType;

use crate::app::{RenderRoot, RenderRootSignal, RenderRootState};
use crate::core::{
    ClassSetDiff, CursorIcon, DefaultProperties, Ime, PointerEvent, PointerInfo, PropertiesMut,
    PropertiesRef, PropertyArena, PropertyCache, QueryCtx, RegisterCtx, TextEvent, Update,
    UpdateCtx, Widget, WidgetArenaNode, WidgetId, WidgetState,
};
use crate::passes::event::{run_on_pointer_event_pass, run_on_text_event_pass};
use crate::passes::{enter_span, enter_span_if, merge_state_up, recurse_on_children};
use crate::properties::core_property_changed;
use crate::util::ParentLinkedList;

// --- MARK: HELPERS
/// Returns the id path starting from the given widget id and ending at the root.
///
/// If `widget_id` is `None`, returns an empty `Vec`.
fn get_id_path(root: &RenderRoot, widget_id: Option<WidgetId>) -> Vec<WidgetId> {
    let Some(widget_id) = widget_id else {
        return Vec::new();
    };

    root.widget_arena
        .nodes
        .get_id_path(widget_id)
        .iter()
        .map(|&id| WidgetId(id.try_into().unwrap()))
        .collect()
}

fn is_ancestor_of(root: &RenderRoot, ancestor_id: WidgetId, widget_id: Option<WidgetId>) -> bool {
    let Some(id) = widget_id else {
        return false;
    };
    root.widget_arena
        .nodes
        .get_id_path(id)
        .iter()
        .any(|id| *id == ancestor_id.to_raw())
}

/// Make a dummy [`PointerEvent::Cancel`].
fn dummy_pointer_cancel() -> PointerEvent {
    PointerEvent::Cancel(PointerInfo {
        pointer_id: None,
        persistent_device_id: None,
        pointer_type: PointerType::default(),
    })
}

fn run_targeted_update_pass(
    root: &mut RenderRoot,
    target: Option<WidgetId>,
    mut pass_fn: impl FnMut(&mut dyn Widget, &mut UpdateCtx<'_>, &mut PropertiesMut<'_>),
) {
    let mut current_id = target;
    while let Some(widget_id) = current_id {
        let parent_id = root.widget_arena.parent_of(widget_id);
        let node = root.widget_arena.get_node_mut(widget_id);

        let children = node.children;
        let widget = &mut *node.item.widget;
        let state = &mut node.item.state;
        let properties = &mut node.item.properties;
        let class_set = &node.item.class_set;
        let stack = root
            .property_arena
            .get(state.property_stack_id, widget.type_id());

        let mut ctx = UpdateCtx {
            global_state: &mut root.global_state,
            widget_state: state,
            children,
            ancestors: None,
            property_arena: &root.property_arena,
        };
        let mut props = PropertiesMut {
            local: properties,
            default_map: root
                .property_arena
                .default_properties
                .for_widget(widget.type_id()),
            stack,
            class_set,
        };
        pass_fn(widget, &mut ctx, &mut props);

        merge_state_up(&mut root.widget_arena, widget_id);
        current_id = parent_id;
    }
}

pub(crate) fn run_single_update_pass(
    root: &mut RenderRoot,
    target: Option<WidgetId>,
    mut pass_fn: impl FnMut(&mut dyn Widget, &mut UpdateCtx<'_>, &mut PropertiesMut<'_>),
) {
    let Some(target) = target else {
        return;
    };
    if !root.widget_arena.has(target) {
        return;
    }

    let node = root.widget_arena.get_node_mut(target);

    let children = node.children;
    let widget = &mut *node.item.widget;
    let state = &mut node.item.state;
    let properties = &mut node.item.properties;
    let class_set = &node.item.class_set;
    let stack = root
        .property_arena
        .get(state.property_stack_id, widget.type_id());

    let mut ctx = UpdateCtx {
        global_state: &mut root.global_state,
        widget_state: state,
        children,
        ancestors: None,
        property_arena: &root.property_arena,
    };
    let mut props = PropertiesMut {
        local: properties,
        default_map: root
            .property_arena
            .default_properties
            .for_widget(widget.type_id()),
        stack,
        class_set,
    };
    pass_fn(widget, &mut ctx, &mut props);

    let mut current_id = Some(target);
    while let Some(widget_id) = current_id {
        merge_state_up(&mut root.widget_arena, widget_id);
        current_id = root.widget_arena.parent_of(widget_id);
    }
}

// --- MARK: TREE
fn update_widget_tree(
    global_state: &mut RenderRootState,
    default_properties: &DefaultProperties,
    property_arena: &PropertyArena,
    node: ArenaMut<'_, WidgetArenaNode>,
    ancestors: Option<&ParentLinkedList<'_>>,
) {
    let mut children = node.children;
    let widget = &mut *node.item.widget;
    let state = &mut node.item.state;
    let properties = &mut node.item.properties;
    let class_set = &node.item.class_set;
    let id = state.id;

    let trace = global_state.trace.update_tree;
    let _span = enter_span_if(trace, state);

    if !state.children_changed {
        return;
    }

    register_children(global_state, widget, state, children.reborrow_mut());

    if state.is_new {
        let stack = property_arena.get(state.property_stack_id, widget.type_id());
        let mut ctx = UpdateCtx {
            global_state,
            widget_state: state,
            children: children.reborrow_mut(),
            ancestors,
            property_arena,
        };
        let mut props = PropertiesMut {
            local: properties,
            default_map: default_properties.for_widget(widget.type_id()),
            stack,
            class_set,
        };
        widget.update(&mut ctx, &mut props, &Update::WidgetAdded);
        if trace {
            trace!("{} received Update::WidgetAdded", widget.short_type_name());
        }
        state.accepts_pointer_interaction = widget.accepts_pointer_interaction();
        state.accepts_tooltips = widget.accepts_tooltips();
        state.propagates_pointer_interaction = widget.propagates_pointer_interaction();
        state.accepts_focus = widget.accepts_focus();
        state.accepts_text_input = widget.accepts_text_input();
        state.trace_span = widget.make_trace_span(state.id);
        state.is_new = false;

        if state.children_changed {
            register_children(global_state, widget, state, children.reborrow_mut());
        }
    }

    // We can recurse on this widget's children, because they have already been added
    // to the arena above.
    let parent_state = state;
    recurse_on_children(id, widget, children, |mut node| {
        let ancestors = ParentLinkedList {
            widget,
            id,
            parent: ancestors,
        };
        update_widget_tree(
            global_state,
            default_properties,
            property_arena,
            node.reborrow_mut(),
            Some(&ancestors),
        );
        parent_state.merge_up(&mut node.item.state);
    });
}

fn register_children(
    global_state: &mut RenderRootState,
    widget: &mut (dyn Widget + 'static),
    state: &mut WidgetState,
    mut children: ArenaMutList<'_, WidgetArenaNode>,
) {
    state.children_changed = false;

    let mut ctx = RegisterCtx {
        global_state,
        children: children.reborrow_mut(),
        #[cfg(debug_assertions)]
        registered_ids: Vec::new(),
    };
    // The widget will call `RegisterCtx::register_child` on all its children,
    // which will add the new widgets to the arena.
    widget.register_children(&mut ctx);

    #[cfg(debug_assertions)]
    {
        let children_ids = widget.children_ids();
        for child_id in ctx.registered_ids {
            if !children_ids.contains(&child_id) {
                panic!(
                    "Error in '{}' {}: method register_children() called \
                    RegisterCtx::register_child() on child {}, which isn't \
                    in the list returned by children_ids()",
                    widget.short_type_name(),
                    state.id,
                    child_id
                );
            }
        }
    }

    #[cfg(debug_assertions)]
    for child_id in widget.children_ids() {
        if !children.has(child_id) {
            panic!(
                "Error in '{}' {}: method register_children() did not call \
                RegisterCtx::register_child() on child {} returned by children_ids()",
                widget.short_type_name(),
                state.id,
                child_id
            );
        }
    }
}

/// See the [passes documentation](crate::doc::pass_system#update-tree-pass).
pub(crate) fn run_update_widget_tree_pass(root: &mut RenderRoot) {
    let _span = info_span!("update_new_widgets").entered();

    // INIT TREE
    if root.subwindow_stack.incomplete() {
        let mut ctx = RegisterCtx {
            global_state: &mut root.global_state,
            children: root.widget_arena.nodes.roots_mut(),
            #[cfg(debug_assertions)]
            registered_ids: Vec::new(),
        };
        ctx.register_child(&mut root.subwindow_stack);
    }

    let root_node = root.widget_arena.get_node_mut(root.root_id());
    update_widget_tree(
        &mut root.global_state,
        &root.property_arena.default_properties,
        &root.property_arena,
        root_node,
        None,
    );
}

// ----------------

// --- MARK: DISABLED
/// See the [passes documentation](crate::doc::pass_system#update-passes).
/// See the [disabled status documentation](../doc/06_masonry_concepts.md#disabled).
fn update_disabled_for_widget(
    global_state: &mut RenderRootState,
    default_properties: &DefaultProperties,
    property_arena: &PropertyArena,
    node: ArenaMut<'_, WidgetArenaNode>,
    parent_disabled: bool,
) {
    let mut children = node.children;
    let widget = &mut *node.item.widget;
    let state = &mut node.item.state;
    let properties = &mut node.item.properties;
    let class_set = &node.item.class_set;
    let id = state.id;

    let _span = enter_span(state);

    let disabled = state.is_explicitly_disabled || parent_disabled;
    if !state.needs_update_disabled && disabled == state.is_disabled {
        return;
    }

    if disabled != state.is_disabled {
        let stack = property_arena.get(state.property_stack_id, widget.type_id());
        let mut ctx = UpdateCtx {
            global_state,
            widget_state: state,
            children: children.reborrow_mut(),
            ancestors: None,
            property_arena,
        };
        let mut props = PropertiesMut {
            local: properties,
            default_map: default_properties.for_widget(widget.type_id()),
            stack,
            class_set,
        };
        widget.update(&mut ctx, &mut props, &Update::DisabledChanged(disabled));
        state.is_disabled = disabled;
        state.class_diff.is_disabled = Some(disabled);
        state.request_update_props = true;
        state.needs_update_props = true;
        state.needs_update_focusable = true;
        state.request_accessibility = true;
        state.needs_accessibility = true;
    }

    state.needs_update_disabled = false;

    let parent_state = state;
    recurse_on_children(id, widget, children, |mut node| {
        update_disabled_for_widget(
            global_state,
            default_properties,
            property_arena,
            node.reborrow_mut(),
            disabled,
        );
        parent_state.merge_up(&mut node.item.state);
    });
}

pub(crate) fn run_update_disabled_pass(root: &mut RenderRoot) {
    let _span = info_span!("update_disabled").entered();

    // If a widget was enabled or disabled, the pointer icon may need to change.
    if root.root_state().needs_update_disabled {
        root.global_state.needs_pointer_pass = true;
    }

    let root_node = root.widget_arena.get_node_mut(root.root_id());
    update_disabled_for_widget(
        &mut root.global_state,
        &root.property_arena.default_properties,
        &root.property_arena,
        root_node,
        false,
    );
}

// ----------------

// *Stashed* is for widgets that are no longer "part of the graph". So they can't get keyboard events, don't get painted, etc, but should keep some state.
// Scrolled-out widgets are *not* stashed.

// --- MARK: STASHED
/// See the [passes documentation](crate::doc::pass_system#update-passes).
/// See the [stashed status documentation](../doc/06_masonry_concepts.md#stashed).
fn update_stashed_for_widget(
    global_state: &mut RenderRootState,
    default_properties: &DefaultProperties,
    property_arena: &PropertyArena,
    node: ArenaMut<'_, WidgetArenaNode>,
    parent_stashed: bool,
) {
    let mut children = node.children;
    let widget = &mut *node.item.widget;
    let state = &mut node.item.state;
    let properties = &mut node.item.properties;
    let class_set = &node.item.class_set;
    let id = state.id;

    let _span = enter_span(state);

    let stashed = state.is_explicitly_stashed || parent_stashed;
    if !state.needs_update_stashed && stashed == state.is_stashed {
        return;
    }

    if stashed != state.is_stashed {
        let stack = property_arena.get(state.property_stack_id, widget.type_id());
        let mut ctx = UpdateCtx {
            global_state,
            widget_state: state,
            children: children.reborrow_mut(),
            ancestors: None,
            property_arena,
        };
        let mut props = PropertiesMut {
            local: properties,
            default_map: default_properties.for_widget(widget.type_id()),
            stack,
            class_set,
        };
        widget.update(&mut ctx, &mut props, &Update::StashedChanged(stashed));
        state.is_stashed = stashed;
        state.needs_update_focusable = true;

        // Items may have been changed while they were stashed in ways that require a
        // relayout and a re-render.
        if !stashed {
            state.set_needs_layout(true);
            state.request_layout = true;
            state.request_paint = true;
            state.needs_paint = true;
            state.needs_accessibility = true;
            state.request_accessibility = true;
        }
    }

    state.needs_update_stashed = false;

    let parent_state = state;
    recurse_on_children(id, widget, children, |mut node| {
        update_stashed_for_widget(
            global_state,
            default_properties,
            property_arena,
            node.reborrow_mut(),
            stashed,
        );
        parent_state.merge_up(&mut node.item.state);
    });
}

pub(crate) fn run_update_stashed_pass(root: &mut RenderRoot) {
    let _span = info_span!("update_stashed").entered();

    let root_node = root.widget_arena.get_node_mut(root.root_id());
    update_stashed_for_widget(
        &mut root.global_state,
        &root.property_arena.default_properties,
        &root.property_arena,
        root_node,
        false,
    );
}

// ----------------

// --- MARK: FOCUSABLE

fn update_focusable_for_widget(node: ArenaMut<'_, WidgetArenaNode>) {
    let children = node.children;
    let widget = &mut *node.item.widget;
    let state = &mut node.item.state;
    let id = state.id;

    let _span = enter_span(state);

    if !state.needs_update_focusable {
        return;
    }

    state.descendant_is_focusable = false;

    if state.accepts_focus && !state.is_disabled && !state.is_stashed {
        state.descendant_is_focusable = true;
    }

    let parent_state = &mut *state;
    recurse_on_children(id, widget, children, |mut node| {
        update_focusable_for_widget(node.reborrow_mut());

        if node.item.state.descendant_is_focusable {
            parent_state.descendant_is_focusable = true;
        }
    });

    state.needs_update_focusable = false;
}

pub(crate) fn run_update_focusable_pass(root: &mut RenderRoot) {
    let _span = info_span!("update_focusable").entered();

    let root_node = root.widget_arena.get_node_mut(root.root_id());
    update_focusable_for_widget(root_node);
}

pub(crate) fn find_next_focusable(root: &mut RenderRoot, forward: bool) -> Option<WidgetId> {
    let mut focus_anchor_id = root.global_state.focus_anchor;

    if let Some(id) = focus_anchor_id
        && !root.has_widget(id)
    {
        focus_anchor_id = None;
    }

    // The idea of this algorithm is that we iterate through the entire tree in preorder
    // (or reversed post-order), skipping everything before the ancestors of the anchor.
    // We return the first focusable widget we find that way *except* the anchor widget,
    // which we've temporarily "yanked" out of the search.
    if let Some(id) = focus_anchor_id {
        let anchor_state = root.widget_arena.get_state_mut(id);
        let anchor_was_focusable = anchor_state.accepts_focus;
        let anchor_had_focusable = anchor_state.descendant_is_focusable;
        if forward {
            anchor_state.accepts_focus = false;
        } else {
            anchor_state.descendant_is_focusable = false;
        }

        // The list of items to skip, from the anchor to the root (which we immediately pop).
        let mut anchor_path = get_id_path(root, focus_anchor_id);
        let _ = anchor_path.pop();

        let found = find_first_focusable(root, &anchor_path, root.root_id(), forward);

        // Restore the anchor.
        let anchor_state = root.widget_arena.get_state_mut(id);
        anchor_state.accepts_focus = anchor_was_focusable;
        anchor_state.descendant_is_focusable = anchor_had_focusable;

        if found.is_some() {
            return found;
        }
    }

    // If nothing is focused, or if we haven't found anything after the anchor,
    // we iterate through the entire tree again, this time without the anchor path.
    find_first_focusable(root, &[], root.root_id(), forward)
}

fn find_first_focusable(
    root: &mut RenderRoot,
    anchor_path: &[WidgetId],
    node: WidgetId,
    forward: bool,
) -> Option<WidgetId> {
    let item = root.widget_arena.get_node_mut(node);
    let widget = &mut *item.item.widget;
    let state = &mut item.item.state;
    let accepts_focus = state.accepts_focus;

    if !state.descendant_is_focusable {
        return None;
    }

    let children = widget.children_ids();
    let children = if let Some((anchor, anchor_path)) = anchor_path.split_last() {
        let anchor_idx = children.iter().position(|id| *id == *anchor).unwrap();

        // First we try the anchor
        if let Some(found) = find_first_focusable(root, anchor_path, children[anchor_idx], forward)
        {
            return Some(found);
        }

        // Then everything after, at which point we're outside the anchor path.
        if forward {
            &children[anchor_idx + 1..]
        } else {
            &children[..anchor_idx]
        }
    } else {
        // If our parent didn't get an anchor path,
        // or went past it, just check all children.
        &children[..]
    };

    if forward {
        if anchor_path.is_empty() && accepts_focus {
            return Some(node);
        }
        for child in children.iter() {
            if let Some(found) = find_first_focusable(root, &[], *child, forward) {
                return Some(found);
            }
        }
    } else {
        for child in children.iter().rev() {
            if let Some(found) = find_first_focusable(root, &[], *child, forward) {
                return Some(found);
            }
        }
        if accepts_focus {
            return Some(node);
        }
    }

    None
}

// ----------------

// --- MARK: FOCUS
/// See the [passes documentation](crate::doc::pass_system#update-passes).
/// See the [focus status documentation](../doc/06_masonry_concepts.md#text-focus).
pub(crate) fn run_update_focus_pass(root: &mut RenderRoot) {
    let _span = info_span!("update_focus").entered();
    // If the next-focused widget is disabled, stashed or removed, we set
    // the focused id to None
    if let Some(id) = root.global_state.next_focused_widget
        && !root.is_still_interactive(id)
    {
        root.global_state.next_focused_widget = None;
    }
    // We are more permissive with the anchor.
    if let Some(id) = root.global_state.focus_anchor
        && !root.has_widget(id)
    {
        root.global_state.focus_anchor = None;
    }

    if let Some(id) = root.global_state.focus_fallback
        && !root.is_still_interactive(id)
    {
        root.global_state.focus_fallback = None;
    }

    let prev_focused = root.global_state.focused_widget;
    let was_ime_active = root.global_state.is_ime_active;

    if was_ime_active && prev_focused != root.global_state.next_focused_widget {
        // IME was active, but the next focused widget is going to receive the Ime::Disabled event
        // sent by the platform. Synthesize an `Ime::Disabled` event here and send it to the widget
        // about to be unfocused.

        // HACK: It's not valid to send an event to a non-existent widget, so we check that the "previously"
        // focused widget hasn't just been deleted.
        // This means that if a parent widget was handling IME events, it won't get this event.
        // We know that IME events bubbling is not the correct behaviour, but have chosen to keep it for consistency,
        // as we also are planning to refactor how IME is delivered as we update to use Android View.
        if let Some(prev_focused) = prev_focused
            && root.has_widget(prev_focused)
        {
            run_on_text_event_pass(root, &TextEvent::Ime(Ime::Disabled));
        }

        // Disable the IME, which was enabled specifically for this widget. Note that if the newly
        // focused widget also requires IME, we will request it again - this resets the platform's
        // state, ensuring that partial IME inputs do not "travel" between widgets
        root.global_state.emit_signal(RenderRootSignal::EndIme);

        // Note: handling of the Ime::Disabled event sent above may have changed the next focused
        // widget. In particular, focus may have changed back to the original widget we just
        // disabled IME for.
        //
        // In this unlikely case, the rest of this handler will short-circuit, and IME would not be
        // re-enabled for this widget. Re-enable IME here; the resultant `Ime::Enabled` event sent
        // by the platform will be routed to this widget as it remains the focused widget. We don't
        // handle this as above to avoid loops.
        //
        // First do the disabled, stashed or removed check again.
        if let Some(id) = root.global_state.next_focused_widget
            && !root.is_still_interactive(id)
        {
            root.global_state.next_focused_widget = None;
        }
        if prev_focused == root.global_state.next_focused_widget {
            tracing::warn!(
                id = prev_focused.map(|id| id.trace()),
                "request_focus called whilst handling Ime::Disabled"
            );
            root.global_state.emit_signal(RenderRootSignal::StartIme);
        }
    }

    let next_focused = root.global_state.next_focused_widget;

    // "Focused path" means the focused widget, and all its parents.
    let prev_focused_path = std::mem::take(&mut root.global_state.focused_path);
    let next_focused_path = get_id_path(root, next_focused);

    // We don't just compare `prev_focused` and `next_focused` because
    // they could be the same widget but one of their ancestors could have been reparented.
    // (assuming we ever implement reparenting)
    if prev_focused_path != next_focused_path {
        let mut focused_set = HashSet::new();
        for widget_id in &next_focused_path {
            focused_set.insert(*widget_id);
        }

        trace!("prev_focused_path: {:?}", prev_focused_path);
        trace!("next_focused_path: {:?}", next_focused_path);

        // This is the same algorithm as the one in
        // run_update_pointer_pass
        // See comment in that function.

        fn update_focused_status_of(
            root: &mut RenderRoot,
            widget_id: WidgetId,
            focused_set: &HashSet<WidgetId>,
        ) {
            run_targeted_update_pass(root, Some(widget_id), |widget, ctx, props| {
                let has_focused = focused_set.contains(&ctx.widget_id());

                if ctx.widget_state.has_focus_target != has_focused {
                    widget.update(ctx, props, &Update::ChildFocusChanged(has_focused));
                    ctx.widget_state.class_diff.has_focus_target = Some(has_focused);
                    ctx.widget_state.request_update_props = true;
                    ctx.widget_state.needs_update_props = true;
                }
                ctx.widget_state.has_focus_target = has_focused;
            });
        }

        // TODO - Add unit test to check items are iterated from the bottom up.
        for widget_id in prev_focused_path.iter().copied() {
            if root.widget_arena.has(widget_id)
                && root.widget_arena.get_state_mut(widget_id).has_focus_target
                    != focused_set.contains(&widget_id)
            {
                update_focused_status_of(root, widget_id, &focused_set);
            }
        }
        for widget_id in next_focused_path.iter().copied() {
            if root.widget_arena.has(widget_id)
                && root.widget_arena.get_state_mut(widget_id).has_focus_target
                    != focused_set.contains(&widget_id)
            {
                update_focused_status_of(root, widget_id, &focused_set);
            }
        }
    }

    // Refocus if the focused widget changed.
    if prev_focused != next_focused {
        // We send FocusChange event to widget that lost and the widget that gained focus.
        // We also request accessibility, because build_access_node() depends on the focus state.
        run_single_update_pass(root, prev_focused, |widget, ctx, props| {
            widget.update(ctx, props, &Update::FocusChanged(false));
            ctx.widget_state.request_accessibility = true;
            ctx.widget_state.needs_accessibility = true;
        });
        run_single_update_pass(root, next_focused, |widget, ctx, props| {
            widget.update(ctx, props, &Update::FocusChanged(true));
            ctx.widget_state.request_accessibility = true;
            ctx.widget_state.needs_accessibility = true;
        });

        if let Some(next_focused) = next_focused {
            let widget_state = root.widget_arena.get_state(next_focused);

            root.global_state.is_ime_active = widget_state.accepts_text_input;
            if widget_state.accepts_text_input {
                root.global_state.emit_signal(RenderRootSignal::StartIme);
            }
        } else {
            root.global_state.is_ime_active = false;
        }
    }

    if next_focused.is_some() {
        root.global_state.focus_anchor = next_focused;
    }

    root.global_state.focused_widget = next_focused;
    root.global_state.focused_path = next_focused_path;
}

// ----------------

// --- MARK: SCROLL
// This pass will update scroll positions in cases where a widget has requested to be
// scrolled into view (usually a text input getting text events).
// Each parent that implements scrolling will update its scroll position to ensure the
// child is visible. (If the target area is larger than the parent, the parent will try
// to show the top left of that area.)
/// See the [passes documentation](crate::doc::pass_system#update-passes).
pub(crate) fn run_update_scroll_pass(root: &mut RenderRoot) {
    let _span = info_span!("update_scroll").entered();

    let scroll_request_targets = std::mem::take(&mut root.global_state.scroll_request_targets);
    for (target, rect) in scroll_request_targets {
        // We start with target_rect being in the target's border-box coordinate space.
        let mut target_rect = rect;

        // We run the update pass on the target itself and then its ancestors.
        run_targeted_update_pass(root, Some(target), |widget, ctx, props| {
            // Convert the target_rect from border-box space to content-box space.
            let local_rect = target_rect - ctx.widget_state.border_box_translation();

            let event = Update::RequestPanToChild(local_rect);
            widget.update(ctx, props, &event);

            // TODO - We should run the compose method after this, so
            // translations are updated and the rect passed to parents
            // is more accurate. Until then we don't add scroll_translation
            // at all and only support a single scrolling parent.

            // Before continuing to the parent, we need to convert the target_rect from this
            // widget's border-box coordinate space to the parent's border-box coordinate space.
            let state = &ctx.widget_state;
            target_rect = target_rect + state.origin.to_vec2();
        });
    }
}

// ----------------

// --- MARK: POINTER
/// See the [passes documentation](crate::doc::pass_system#update-passes).
pub(crate) fn run_update_pointer_pass(root: &mut RenderRoot) {
    if !root.global_state.needs_pointer_pass {
        return;
    }
    let _span = info_span!("update_pointer").entered();

    root.global_state.needs_pointer_pass = false;

    let pointer_pos = root
        .global_state
        .last_mouse_pos
        .map(|pos| (pos.x, pos.y).into());

    if root.global_state.inspector_state.is_picking_widget {
        if let Some(pos) = pointer_pos {
            root.global_state.inspector_state.hovered_widget = root
                .get_widget(root.root_id())
                .expect("root widget not in widget tree")
                .find_widget_under_pointer(pos)
                .map(|widget| widget.id());
        }
        root.root_state_mut().needs_paint = true;
        return;
    }

    // Release pointer capture if target can no longer hold it.
    if let Some(id) = root.global_state.pointer_capture_target
        && !root.is_still_interactive(id)
    {
        // The event pass will set pointer_capture_target to None.
        run_on_pointer_event_pass(root, &dummy_pointer_cancel());
    }

    // -- UPDATE ACTIVE --
    // TODO - There's a lot of duplication between this, UPDATE HOVERED
    // and UPDATE FOCUS. It would be nice to find ways to de-duplicate it without making
    // the code overly abstract.

    // "Active path" means the widget which is considered active, and all its parents.
    let prev_active_path = std::mem::take(&mut root.global_state.active_path);
    let prev_active_widget = prev_active_path.first().copied();
    let next_active_widget = root.global_state.pointer_capture_target;
    let next_active_path = get_id_path(root, next_active_widget);

    // We don't just compare `prev_active_widget` and `next_active_widget` because
    // they could be the same widget but one of their ancestors could have been reparented.
    // (assuming we ever implement reparenting)
    if prev_active_path != next_active_path {
        let mut active_set = HashSet::new();
        for widget_id in &next_active_path {
            active_set.insert(*widget_id);
        }

        trace!("prev_active_path: {:?}", prev_active_path);
        trace!("next_active_path: {:?}", next_active_path);

        // This algorithm is written to be resilient to future changes like reparenting and multiple
        // cursors. In theory it's O(Depth² * CursorCount) in the worst case, which isn't too bad
        // (cursor count is usually 1 or 2, depth is usually small), but in practice it's virtually
        // always O(Depth * CursorCount) because we only need to update the active status of the
        // widgets that changed.
        // The above assumes that accessing the widget tree is O(1) for simplicity.

        fn update_active_status_of(
            root: &mut RenderRoot,
            widget_id: WidgetId,
            active_set: &HashSet<WidgetId>,
        ) {
            run_targeted_update_pass(root, Some(widget_id), |widget, ctx, props| {
                let has_active = active_set.contains(&ctx.widget_id());

                if ctx.widget_state.has_active != has_active {
                    widget.update(ctx, props, &Update::ChildActiveChanged(has_active));
                }
                ctx.widget_state.has_active = has_active;
            });
        }

        // TODO - Add unit test to check items are iterated from the bottom up.
        for widget_id in prev_active_path.iter().copied() {
            if root.widget_arena.has(widget_id)
                && root.widget_arena.get_state_mut(widget_id).has_active
                    != active_set.contains(&widget_id)
            {
                update_active_status_of(root, widget_id, &active_set);
            }
        }
        for widget_id in next_active_path.iter().copied() {
            if root.widget_arena.has(widget_id)
                && root.widget_arena.get_state_mut(widget_id).has_active
                    != active_set.contains(&widget_id)
            {
                update_active_status_of(root, widget_id, &active_set);
            }
        }
    }

    if prev_active_widget != next_active_widget {
        run_single_update_pass(root, prev_active_widget, |widget, ctx, props| {
            ctx.widget_state.is_active = false;
            ctx.widget_state.class_diff.is_active = Some(false);
            ctx.widget_state.request_update_props = true;
            ctx.widget_state.needs_update_props = true;
            widget.update(ctx, props, &Update::ActiveChanged(false));
        });
        run_single_update_pass(root, next_active_widget, |widget, ctx, props| {
            ctx.widget_state.is_active = true;
            ctx.widget_state.class_diff.is_active = Some(true);
            ctx.widget_state.request_update_props = true;
            ctx.widget_state.needs_update_props = true;
            widget.update(ctx, props, &Update::ActiveChanged(true));
        });
    }

    // -- UPDATE HOVERED --
    let mut next_hovered_widget = if let Some(pos) = pointer_pos {
        root.get_widget(root.root_id())
            .expect("root widget not in widget tree")
            .find_widget_under_pointer(pos)
            .map(|widget| widget.id())
    } else {
        None
    };
    // If the pointer is captured, it can either hover its capture target or nothing.
    if let Some(capture_target) = root.global_state.pointer_capture_target
        && next_hovered_widget != Some(capture_target)
    {
        if is_ancestor_of(root, capture_target, next_hovered_widget) {
            next_hovered_widget = Some(capture_target);
        } else {
            next_hovered_widget = None;
        }
    }
    // Check if hovered widget is disabled
    if let Some(id) = next_hovered_widget
        && root.widget_arena.get_state(id).is_disabled
    {
        next_hovered_widget = None;
    }

    // "Hovered path" means the widget which is considered hovered, and all its parents.
    let prev_hovered_path = std::mem::take(&mut root.global_state.hovered_path);
    let next_hovered_path = get_id_path(root, next_hovered_widget);
    let prev_hovered_widget = prev_hovered_path.first().copied();

    // We don't just compare `prev_hovered_widget` and `next_hovered_widget`, because
    // they could be the same widget but one of their ancestors could have been reparented.
    // (assuming we ever implement reparenting)
    if prev_hovered_path != next_hovered_path {
        let mut hovered_set = HashSet::new();
        for widget_id in &next_hovered_path {
            hovered_set.insert(*widget_id);
        }

        trace!("prev_hovered_path: {:?}", prev_hovered_path);
        trace!("next_hovered_path: {:?}", next_hovered_path);

        // This algorithm is written to be resilient to future changes like reparenting and multiple
        // cursors. In theory it's O(Depth² * CursorCount) in the worst case, which isn't too bad
        // (cursor count is usually 1 or 2, depth is usually small), but in practice it's virtually
        // always O(Depth * CursorCount) because we only need to update the hovered status of the
        // widgets that changed.
        // The above assumes that accessing the widget tree is O(1) for simplicity.

        fn update_hovered_status_of(
            root: &mut RenderRoot,
            widget_id: WidgetId,
            hovered_set: &HashSet<WidgetId>,
        ) {
            run_targeted_update_pass(root, Some(widget_id), |widget, ctx, props| {
                let has_hovered = hovered_set.contains(&ctx.widget_id());

                if ctx.widget_state.has_hovered != has_hovered {
                    widget.update(ctx, props, &Update::ChildHoveredChanged(has_hovered));
                }
                ctx.widget_state.has_hovered = has_hovered;
            });
        }

        // TODO - Add unit test to check items are iterated from the bottom up.
        for widget_id in prev_hovered_path.iter().copied() {
            if root.widget_arena.has(widget_id)
                && root.widget_arena.get_state_mut(widget_id).has_hovered
                    != hovered_set.contains(&widget_id)
            {
                update_hovered_status_of(root, widget_id, &hovered_set);
            }
        }
        for widget_id in next_hovered_path.iter().copied() {
            if root.widget_arena.has(widget_id)
                && root.widget_arena.get_state_mut(widget_id).has_hovered
                    != hovered_set.contains(&widget_id)
            {
                update_hovered_status_of(root, widget_id, &hovered_set);
            }
        }
    }

    if prev_hovered_widget != next_hovered_widget {
        run_single_update_pass(root, prev_hovered_widget, |widget, ctx, props| {
            ctx.widget_state.is_hovered = false;
            ctx.widget_state.class_diff.is_hovered = Some(false);
            ctx.widget_state.request_update_props = true;
            ctx.widget_state.needs_update_props = true;
            widget.update(ctx, props, &Update::HoveredChanged(false));
        });
        run_single_update_pass(root, next_hovered_widget, |widget, ctx, props| {
            ctx.widget_state.is_hovered = true;
            ctx.widget_state.class_diff.is_hovered = Some(true);
            ctx.widget_state.request_update_props = true;
            ctx.widget_state.needs_update_props = true;
            widget.update(ctx, props, &Update::HoveredChanged(true));
        });

        // If the previously hovered widget is no longer under our pointer,
        // we cancel its tooltip.
        if let Some(id) = root.global_state.tooltip_timer_id {
            root.global_state.tooltip_timer_id = None;
            root.global_state.timers.cancel(id);
        }
        root.global_state.tooltip_already_fired = false;
    }

    // -- UPDATE CURSOR ICON --

    // If the pointer is captured, its icon always reflects the
    // capture target, even when not hovered.
    let icon_source = root
        .global_state
        .pointer_capture_target
        .or(next_hovered_widget);

    let new_icon = if let (Some(icon_source), Some(pos)) = (icon_source, pointer_pos) {
        let root_node = root.widget_arena.get_node(icon_source);
        let children = root_node.children;
        let widget = &*root_node.item.widget;
        let state = &root_node.item.state;
        let properties = &root_node.item.properties;

        let stack = root
            .property_arena
            .get(state.property_stack_id, widget.type_id());
        let ctx = QueryCtx {
            global_state: &root.global_state,
            widget_state: state,
            properties: PropertiesRef {
                local: properties,
                default_map: root
                    .property_arena
                    .default_properties
                    .for_widget(widget.type_id()),
                stack,
                class_set: &root_node.item.class_set,
            },
            children,
            property_arena: &root.property_arena,
        };

        if state.is_disabled {
            CursorIcon::Default
        } else {
            widget.get_cursor(&ctx, pos)
        }
    } else {
        CursorIcon::Default
    };

    if root.global_state.cursor_icon != new_icon {
        root.global_state
            .emit_signal(RenderRootSignal::SetCursor(new_icon));
    }

    root.global_state.cursor_icon = new_icon;
    root.global_state.hovered_path = next_hovered_path;
    root.global_state.active_path = next_active_path;
}

// ----------------

// --- MARK: PROPS
/// See the [passes documentation](crate::doc::pass_system#update-passes).
fn update_props_for_widget(
    global_state: &mut RenderRootState,
    property_arena: &PropertyArena,
    node: ArenaMut<'_, WidgetArenaNode>,
) {
    let widget_type_id = node.item.widget.type_id();
    let stack = property_arena.get(node.item.state.property_stack_id, widget_type_id);

    let mut children = node.children;
    let widget = &mut *node.item.widget;
    let state = &mut node.item.state;
    let class_set = &mut node.item.class_set;
    let id = state.id;

    if !state.needs_update_props {
        return;
    }

    if state.request_update_props {
        let class_diff = std::mem::take(&mut state.class_diff);
        class_set.apply(&class_diff);

        // Check whether to update cache entries before applying the diff.
        let reset_cache = cached_props_changed(&class_diff, &state.property_cache);

        if reset_cache {
            let old_entries = std::mem::take(&mut state.property_cache.entries);
            let mut new_entries = HashMap::with_capacity(old_entries.len());

            // For now we just check the entire cache, which might be expensive
            // if a widget has a lot of properties.
            for (type_id, index) in &old_entries {
                let new_index = stack.resolve_index(class_set, *type_id);

                if new_index != *index || state.property_cache.invalidated {
                    let mut ctx = UpdateCtx {
                        global_state,
                        widget_state: state,
                        children: children.reborrow_mut(),
                        ancestors: None,
                        property_arena,
                    };

                    core_property_changed(&mut ctx, *type_id);
                    widget.property_changed(&mut ctx, *type_id);
                } else {
                    new_entries.insert(*type_id, *index);
                }
            }
            state.property_cache.entries = new_entries;
        }
    }

    state.request_update_props = false;
    state.needs_update_props = false;
    state.property_cache.invalidated = false;

    let parent_state = state;
    recurse_on_children(id, widget, children, |mut node| {
        update_props_for_widget(global_state, property_arena, node.reborrow_mut());
        parent_state.merge_up(&mut node.item.state);
    });
}

/// Returns `true` if any change in `diff` could affect a cached property resolution
/// tracked in `cache`, or if the cache was invalidated.
fn cached_props_changed(diff: &ClassSetDiff, cache: &PropertyCache) -> bool {
    if cache.invalidated {
        return true;
    }
    if !diff.added.is_disjoint(&cache.relevant_classes) {
        return true;
    }
    if !diff.removed.is_disjoint(&cache.relevant_classes) {
        return true;
    }

    (diff.is_hovered.is_some() && cache.relevant_is_hovered)
        || (diff.is_active.is_some() && cache.relevant_is_active)
        || (diff.is_disabled.is_some() && cache.relevant_is_disabled)
        || (diff.has_focus_target.is_some() && cache.relevant_has_focus_target)
}

pub(crate) fn run_update_props_pass(root: &mut RenderRoot) {
    let _span = info_span!("update_props").entered();

    if !root.root_state().needs_update_props {
        return;
    }

    let root_node = root.widget_arena.get_node_mut(root.root_id());
    update_props_for_widget(&mut root.global_state, &root.property_arena, root_node);
}

// ----------------

// --- MARK: FONTS
/// See the [passes documentation](crate::doc::pass_system#update-passes).
fn update_fonts_for_widget(
    global_state: &mut RenderRootState,
    default_properties: &DefaultProperties,
    property_arena: &PropertyArena,
    node: ArenaMut<'_, WidgetArenaNode>,
) {
    let mut children = node.children;
    let widget = &mut *node.item.widget;
    let state = &mut node.item.state;
    let properties = &mut node.item.properties;
    let class_set = &node.item.class_set;
    let id = state.id;

    let _span = enter_span(state);

    let stack = property_arena.get(state.property_stack_id, widget.type_id());
    let mut ctx = UpdateCtx {
        global_state,
        widget_state: state,
        children: children.reborrow_mut(),
        ancestors: None,
        property_arena,
    };
    let mut props = PropertiesMut {
        local: properties,
        default_map: default_properties.for_widget(widget.type_id()),
        stack,
        class_set,
    };
    widget.update(&mut ctx, &mut props, &Update::FontsChanged);

    let parent_state = state;
    recurse_on_children(id, widget, children, |mut node| {
        update_fonts_for_widget(
            global_state,
            default_properties,
            property_arena,
            node.reborrow_mut(),
        );
        parent_state.merge_up(&mut node.item.state);
    });
}

pub(crate) fn run_update_fonts_pass(root: &mut RenderRoot) {
    let _span = info_span!("update_fonts").entered();

    let root_node = root.widget_arena.get_node_mut(root.root_id());
    update_fonts_for_widget(
        &mut root.global_state,
        &root.property_arena.default_properties,
        &root.property_arena,
        root_node,
    );
}

// ----------------