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
// Copyright 2019 the Xilem Authors and the Druid Authors
// SPDX-License-Identifier: Apache-2.0
use std::any::{Any, TypeId};
use std::collections::HashMap;
use std::sync::Arc;
use accesskit::{ActionRequest, NodeId, TreeId, TreeUpdate};
use dpi::{LogicalPosition, LogicalSize, PhysicalSize};
use kurbo::{Point, Rect, Size};
use parley::fontique::{
Blob, Collection, CollectionOptions, FallbackKey, FamilyId, FontInfo, Script, SourceCache,
};
use parley::{FontContext, LayoutContext};
use smallvec::SmallVec;
use tracing::{debug, info_span, warn};
use tree_arena::{ArenaMut, TreeArena};
use understory_timing::{TimerId, TimerInstant, TimerQueue};
use crate::app::RenderRootSignal::UnhandledTextEvent;
use crate::app::VisualLayerPlan;
use crate::app::subwindow_stack::SubwindowStack;
use crate::core::{
AccessCtx, AccessEvent, BrushIndex, CursorIcon, DefaultProperties, ErasedAction, FromDynWidget,
Handled, Ime, NewWidget, PointerEvent, PropertiesRef, PropertyArena, PropertyStack,
PropertyStackId, QueryCtx, ResizeDirection, SubwindowId, SubwindowType, TextEvent, TimerData,
TimerKey, Widget, WidgetArena, WidgetArenaNode, WidgetId, WidgetMut, WidgetPod, WidgetRef,
WidgetState, WidgetTag, WidgetTagInner, WindowEvent,
};
use crate::imaging::record::Scene;
use crate::passes::accessibility::run_accessibility_pass;
use crate::passes::action::run_action_pass;
use crate::passes::anim::run_update_anim_pass;
use crate::passes::compose::run_compose_pass;
use crate::passes::event::{
run_on_access_event_pass, run_on_pointer_event_pass, run_on_text_event_pass,
};
use crate::passes::layout::run_layout_pass;
use crate::passes::mutate::{mutate_widget, run_mutate_pass};
use crate::passes::paint::run_paint_pass;
use crate::passes::timers::{duration_to_timer_ticks, run_timers_pass};
use crate::passes::update::{
run_update_disabled_pass, run_update_focus_pass, run_update_focusable_pass,
run_update_fonts_pass, run_update_pointer_pass, run_update_props_pass, run_update_scroll_pass,
run_update_stashed_pass, run_update_widget_tree_pass,
};
use crate::passes::{PassTracing, recurse_on_children};
use crate::properties::Dimensions;
use crate::util::{Duration, Instant};
/// We ensure that any valid initial IME area is sent to the platform by storing an invalid initial
/// IME area as the `last_sent_ime_area`.
const INVALID_IME_AREA: Rect = Rect::new(f64::NAN, f64::NAN, f64::NAN, f64::NAN);
// --- MARK: STRUCTS
/// The composition root of Masonry.
///
/// This is the entry point for all user events, and the source of all signals to be sent to
/// winit or similar event loop runners, as well as 2D scenes and accessibility information.
///
/// This is also the type that owns the widget tree.
pub struct RenderRoot {
/// `WidgetPod` handle for the subwindow stack, which holds the root widget of each subwindow.
pub(crate) subwindow_stack: WidgetPod<SubwindowStack>,
/// Property data, including property stacks and per-widget-type default properties.
pub(crate) property_arena: PropertyArena,
/// State passed to context types.
pub(crate) global_state: RenderRootState,
/// The widget tree; stores widgets and their states.
pub(crate) widget_arena: WidgetArena,
}
/// State shared between passes.
pub(crate) struct RenderRootState {
/// Sink for signals to be processed by the event loop.
pub(crate) signal_sink: Box<dyn FnMut(RenderRootSignal)>,
/// The accessibility pass creates a wrapper node for the app with `Role::Window`.
///
/// This is the id of that node.
pub(crate) window_node_id: NodeId,
/// Whether the window size should be determined by the content or the user.
pub(crate) size_policy: WindowSizePolicy,
/// Current size of the window.
pub(crate) size: PhysicalSize<u32>,
/// Last mouse position. Updated by `on_pointer_event` pass, used by other passes.
pub(crate) last_mouse_pos: Option<LogicalPosition<f64>>,
/// Currently focused widget.
pub(crate) focused_widget: Option<WidgetId>,
/// List of ancestors of the currently focused widget.
pub(crate) focused_path: Vec<WidgetId>,
/// Widget that will be focused once the `update_focus` pass is run.
pub(crate) next_focused_widget: Option<WidgetId>,
/// Most recently clicked/focused widget.
///
/// This is used to pick the focused widget on Tab events.
pub(crate) focus_anchor: Option<WidgetId>,
/// Widget which will get text events if no widget is focused.
pub(crate) focus_fallback: Option<WidgetId>,
/// Whether the window is focused.
pub(crate) window_focused: bool,
/// Widgets that have requested to be scrolled into view.
///
/// The `WidgetId` is the id of the widget that made the request.
///
/// The `Rect` is the area it wants to be scrolled into view,
/// in its border-box coordinate space.
pub(crate) scroll_request_targets: Vec<(WidgetId, Rect)>,
/// List of ancestors of the currently hovered widget.
pub(crate) hovered_path: Vec<WidgetId>,
/// List of ancestors of the currently active widget.
pub(crate) active_path: Vec<WidgetId>,
/// Widget that currently has pointer capture.
pub(crate) pointer_capture_target: Option<WidgetId>,
/// Current cursor icon.
pub(crate) cursor_icon: CursorIcon,
/// Cache for Parley font data.
// TODO: move font context out of RenderRootState so that we only have it once per app
pub(crate) font_context: FontContext,
/// Cache for Parley text layout data.
pub(crate) text_layout_context: LayoutContext<BrushIndex>,
/// List of callbacks that will run in the next `mutate` pass.
pub(crate) mutate_callbacks: Vec<MutateCallback>,
/// List of actions that will be handled in the next `action` pass.
pub(crate) actions: Vec<(ErasedAction, WidgetId)>,
/// Whether an IME session is active.
pub(crate) is_ime_active: bool,
/// The cursor area last sent to the platform.
pub(crate) last_sent_ime_area: Rect,
/// Scene cache for the widget tree.
pub(crate) scene_cache: HashMap<WidgetId, (Scene, Scene, Scene)>,
// TODO - Add garbage collection.
/// Map from widget tags to widget ids.
pub(crate) widget_tags: HashMap<WidgetTagInner, WidgetId>,
/// Map of subwindows attached to widgets, keyed by the attached widget id, then the type of the subwindow root.
pub(crate) attached_subwindows: HashMap<WidgetId, HashMap<TypeId, SubwindowId>>,
/// Map of widgets with subwindows attached, keyed by the subwindow id.
pub(crate) attached_subwindows_rev: HashMap<SubwindowId, (TypeId, WidgetId)>,
/// Whether data set in the pointer pass has been invalidated.
pub(crate) needs_pointer_pass: bool,
/// Pass tracing configuration, used to skip tracing to limit overhead.
pub(crate) trace: PassTracing,
/// Internal state of the widget inspector.
pub(crate) inspector_state: InspectorState,
/// Whether the next accessibility pass tree should be updated during `render()`.
pub(crate) access_tree_active: bool,
/// Queue of pending widget timers.
pub(crate) timers: TimerQueue<TimerData>,
/// Current queue ID for each widget's pending timer keys.
pub(crate) timer_ids: HashMap<WidgetId, SmallVec<[(TimerKey, TimerId); 1]>>,
/// Queue ID for the timer that fires for tooltip events.
pub(crate) tooltip_timer_id: Option<TimerId>,
// TODO - Add getter for this value?
/// Delay between hovering on a tooltip and the tooltip showing up.
pub(crate) tooltip_delay: Duration,
/// Don't start another tooltip timer until this is set to false.
pub(crate) tooltip_already_fired: bool,
/// Origin for the nanosecond ticks stored in the timer queue.
pub(crate) timer_origin: Instant,
/// Monotonic time source used for widget timers.
pub(crate) timer_clock: Box<dyn Fn() -> Instant>,
/// DPI scale factor.
///
/// Kurbo coordinates are assumed to be in logical pixels
pub(crate) scale_factor: f64,
/// Whether to paint widget's bounding boxes and other visual helpers.
pub(crate) debug_paint: bool,
}
pub(crate) struct MutateCallback {
pub(crate) id: WidgetId,
pub(crate) callback: Box<dyn FnOnce(WidgetMut<'_, dyn Widget>)>,
}
/// Defines how a window's size is determined.
#[derive(Copy, Clone, Debug, Default, PartialEq)]
pub enum WindowSizePolicy {
/// Measure the content to determine the window size.
///
/// The window size will match the root widget's maximum preferred size.
Content,
/// Use the provided window size.
#[default]
User,
}
/// Options for creating a [`RenderRoot`].
#[derive(Debug)]
pub struct RenderRootOptions {
/// Default values that properties will have if not defined per-widget.
pub default_properties: Arc<DefaultProperties>,
/// If true, `fontique` will provide access to system fonts
/// using platform-specific APIs.
pub use_system_fonts: bool,
/// Defines how the window size should be determined.
pub size_policy: WindowSizePolicy,
/// The size of the window.
pub size: PhysicalSize<u32>,
/// The scale factor to use for rendering.
///
/// Useful for high-DPI displays.
///
/// `1.0` is a sensible default.
pub scale_factor: f64,
/// Add a font from its raw data for use in tests.
/// The font is added to the fallback chain for Latin scripts.
/// This is expected to be used with `use_system_fonts = false`
/// to ensure rendering is consistent cross-platform.
///
/// We expect to develop a much more fully-featured font API in the future, but
/// this is necessary for our testing of Masonry.
pub test_font: Option<Blob<u8>>,
}
/// Objects emitted by the [`RenderRoot`] to signal that something has changed or require external actions.
#[derive(Debug)]
pub enum RenderRootSignal {
/// A widget has emitted an action.
Action(ErasedAction, WidgetId),
/// An IME session has been started.
StartIme,
/// The IME session has ended.
EndIme,
/// The IME area has been moved.
ImeMoved(LogicalPosition<f64>, LogicalSize<f64>),
/// A user interaction has sent something to the clipboard.
ClipboardStore(String),
/// A text event was not handled by any widget.
UnhandledTextEvent(TextEvent),
/// The window needs to be redrawn.
RequestRedraw,
/// The window should be redrawn for an animation frame. Currently this isn't really different from `RequestRedraw`.
RequestAnimFrame,
/// The window should take focus.
TakeFocus,
/// The mouse icon should change.
SetCursor(CursorIcon),
/// The window should be resized.
SetSize(PhysicalSize<u32>),
/// The window title has changed.
SetTitle(String),
/// The user has started dragging the window.
///
/// Masonry should send this event when the user presses the left mouse button while hovering a client-side decoration representing the window title bar or similar.
/// The platform that receives this event should start moving the window around until the mouse button is released.
DragWindow,
/// The user has started drag-resizing the window.
///
/// Masonry should send this event when the user presses the left mouse button while hovering a client-side decoration representing a window resize handle.
/// The platform that receives this event should start resizing the window until the mouse button is released.
DragResizeWindow(ResizeDirection),
/// The window should be maximized.
ToggleMaximized,
/// The window should be minimized.
Minimize,
/// The app should terminate.
Exit,
/// The [window system menu] should be shown.
///
/// There are no guarantees as to what the shown menu will contain, or even if a window menu will be drawn at all.
/// In general, the menu may contain options to maximize, minimize or move the window.
///
/// Some platforms may ignore this.
///
/// See also [the Wayland doc for `xdg_toplevel::show_window_menu`](https://wayland.app/protocols/xdg-shell#xdg_toplevel:request:show_window_menu).
///
/// [Windows system menu]: https://en.wikipedia.org/w/index.php?title=Common_menus_in_Microsoft_Windows&oldid=1285312933#System_menu
ShowWindowMenu(LogicalPosition<f64>),
/// The widget picker has selected this widget.
WidgetSelectedInInspector(WidgetId),
/// A new [subwindow] should be created with the widget as root.
///
/// The given [`Point`] must be in the window's coordinate space.
///
/// [subwindow]: crate::doc::masonry_concepts#subwindows
NewSubwindow(SubwindowId, SubwindowType, NewWidget<dyn Widget>, Point),
/// The subwindow with the given id should be removed.
RemoveSubwindow(SubwindowId),
/// The subwindow with the given id should be repositioned to the specified point.
///
/// The given [`Point`] must be in the parent window's coordinate space.
RepositionSubwindow(SubwindowId, Point),
}
/// State of the widget inspector. Useful for debugging.
///
/// Widget inspector is WIP. It should get its own standalone documentation.
pub(crate) struct InspectorState {
pub(crate) is_picking_widget: bool,
pub(crate) hovered_widget: Option<WidgetId>,
}
impl RenderRoot {
/// Creates a new `RenderRoot` with the given options.
///
/// The provided root widget will always stay the root widget.
/// (It cannot be changed later for another widget, only its children can change.)
/// In case no widget is focused the event pass will target text events
/// at the child of the root widget if it only has one child.
///
/// Note that this doesn't create a window or start an event loop.
/// The `masonry` crate doesn't provide a way to do that:
/// look for `masonry_winit::app::run` instead.
pub fn new(
root_widget: NewWidget<impl Widget + ?Sized>,
signal_sink: impl FnMut(RenderRootSignal) + 'static,
options: RenderRootOptions,
) -> Self {
Self::new_with_clock(root_widget, signal_sink, options, Instant::now)
}
/// Creates a render root with a custom monotonic clock for widget timers.
///
/// Supply a clock that returns nondecreasing values. Tests and hosts that
/// simulate time can use this constructor to control when timers become due.
pub fn new_with_clock(
root_widget: NewWidget<impl Widget + ?Sized>,
signal_sink: impl FnMut(RenderRootSignal) + 'static,
options: RenderRootOptions,
timer_clock: impl Fn() -> Instant + 'static,
) -> Self {
let RenderRootOptions {
default_properties,
use_system_fonts,
size_policy,
size,
scale_factor,
test_font,
} = options;
let debug_paint = std::env::var("MASONRY_DEBUG_PAINT").is_ok_and(|it| !it.is_empty());
// SubwindowStack can't use Dimensions::AUTO because it'll resolve to the window size.
// Instead we want to always measure SubwindowStack, so it can measure its main subwindow.
let subwindow_stack = SubwindowStack::new(root_widget)
.prepare()
.with_props(Dimensions::MAX)
.to_pod();
let mut root = Self {
subwindow_stack,
global_state: RenderRootState {
signal_sink: Box::new(signal_sink),
window_node_id: AccessCtx::next_node_id(),
size_policy,
size,
last_mouse_pos: None,
focused_widget: None,
focused_path: Vec::new(),
next_focused_widget: None,
focus_anchor: None,
focus_fallback: None,
window_focused: true,
scroll_request_targets: Vec::new(),
hovered_path: Vec::new(),
active_path: Vec::new(),
pointer_capture_target: None,
cursor_icon: CursorIcon::Default,
font_context: FontContext {
collection: Collection::new(CollectionOptions {
system_fonts: use_system_fonts,
..Default::default()
}),
source_cache: SourceCache::default(),
},
text_layout_context: LayoutContext::new(),
mutate_callbacks: Vec::new(),
actions: Vec::new(),
is_ime_active: false,
last_sent_ime_area: INVALID_IME_AREA,
scene_cache: HashMap::new(),
widget_tags: HashMap::new(),
attached_subwindows: HashMap::new(),
attached_subwindows_rev: HashMap::new(),
needs_pointer_pass: false,
trace: PassTracing::from_env(),
inspector_state: InspectorState {
is_picking_widget: false,
hovered_widget: None,
},
access_tree_active: false,
timers: TimerQueue::new(),
timer_ids: HashMap::new(),
tooltip_timer_id: None,
tooltip_delay: Duration::from_millis(600),
tooltip_already_fired: false,
timer_origin: timer_clock(),
timer_clock: Box::new(timer_clock),
scale_factor,
debug_paint,
},
property_arena: PropertyArena::new(default_properties),
widget_arena: WidgetArena {
nodes: TreeArena::new(),
},
};
if let Some(test_font_data) = test_font {
// We don't use `register_fonts` here because that requests a global relayout.
// However, because we are not yet fully initialised (we are before the below call
// to `run_rewrite_passes`), `request_layout_all` will panic, as the root hasn't
// been inserted into the arena yet.
let families = root
.global_state
.font_context
.collection
.register_fonts(test_font_data, None);
// Make sure that all of these fonts are in the fallback chain for the Latin script.
// <https://en.wikipedia.org/wiki/Script_(Unicode)#Latn>
root.global_state.font_context.collection.append_fallbacks(
FallbackKey::new(Script::from_bytes(*b"Latn"), None),
families.iter().map(|(family, _)| *family),
);
// Also make test fonts available as the generic families (`system-ui` etc.).
// The tests don't use system fonts, which means generic families in a style's font stack
// wouldn't resolve, and the glyphs then come from fallback. At least in Parley v0.12,
// that causes lines to be sized with synthesized "primary font" metrics.
for &generic in parley::GenericFamily::all() {
root.global_state
.font_context
.collection
.append_generic_families(generic, families.iter().map(|(family, _)| *family));
}
}
// We run a set of passes to initialize the widget tree
root.run_rewrite_passes();
root
}
/// Returns a mutable reference to the `PropertyArena`.
pub fn property_arena(&mut self) -> &mut PropertyArena {
&mut self.property_arena
}
/// Replace the tree-wide default properties at runtime.
///
/// The default property set is normally fixed at construction. This lets
/// a host swap it mid-session, e.g. a light/dark theme toggle that
/// re-colors widgets relying on default `ContentColor` / `Background`.
///
/// This invalidates the computed properties of the entire widget tree,
/// and calls [`Widget::property_changed`] for every property previously
/// resolved by each widget.
pub fn set_default_properties(&mut self, default_properties: Arc<DefaultProperties>) {
self.property_arena.default_properties = default_properties;
// Mark the whole tree for the update-properties pass: `needs_update_props`
// so the pass descends to every node, `request_update_props` to enter the
// cache-eviction branch, and `invalidated` so every cached entry re-fires
// `property_changed` regardless of its (unchanged) resolved index.
fn invalidate_props_all_in(node: ArenaMut<'_, WidgetArenaNode>) {
let children = node.children;
let widget = &mut *node.item.widget;
let state = &mut node.item.state;
state.request_update_props = true;
state.needs_update_props = true;
state.property_cache.invalidated = true;
let id = state.id;
recurse_on_children(id, widget, children, |node| {
invalidate_props_all_in(node);
});
}
let root_node = self.widget_arena.get_node_mut(self.root_id());
invalidate_props_all_in(root_node);
self.run_rewrite_passes();
}
pub(crate) fn root_id(&self) -> WidgetId {
self.subwindow_stack.id()
}
/// `WidgetId` of the given subwindow's root widget.
pub(crate) fn subwindow_root_id(&self, subwindow_idx: usize) -> WidgetId {
let node_ref = self
.widget_arena
.nodes
.find(self.root_id())
.expect("root widget not in widget tree");
let widget = &*node_ref.item.widget;
let stack = (widget as &dyn Any)
.downcast_ref::<SubwindowStack>()
.unwrap();
stack.subwindow_root_id(subwindow_idx)
}
/// Returns the widget ID of each subwindow, in stack order.
///
/// Index 0 is the main subwindow; subsequent entries are overlay subwindows.
pub(crate) fn subwindow_root_ids(&self) -> Vec<WidgetId> {
let node_ref = self
.widget_arena
.nodes
.find(self.root_id())
.expect("root widget not in widget tree");
let widget = &*node_ref.item.widget;
let stack = (widget as &dyn Any)
.downcast_ref::<SubwindowStack>()
.unwrap();
Vec::from_fn(stack.subwindow_count(), |i| stack.subwindow_root_id(i))
}
pub(crate) fn root_state(&self) -> &WidgetState {
&self
.widget_arena
.nodes
.roots()
.item(self.root_id())
.expect("root widget not in widget tree")
.item
.state
}
pub(crate) fn root_state_mut(&mut self) -> &mut WidgetState {
&mut self
.widget_arena
.nodes
.roots_mut()
.into_item_mut(self.subwindow_stack.id())
.expect("root widget not in widget tree")
.item
.state
}
// --- MARK: WINDOW_EVENT
/// Handles a window event.
pub fn handle_window_event(&mut self, event: WindowEvent) -> Handled {
match event {
WindowEvent::Rescale(scale_factor) => {
self.global_state.scale_factor = scale_factor;
self.request_render_all();
Handled::Yes
}
WindowEvent::Resize(size) => {
self.global_state.size = size;
self.root_state_mut().request_layout = true;
self.root_state_mut().set_needs_layout(true);
self.run_rewrite_passes();
Handled::Yes
}
WindowEvent::AnimFrame(duration) => {
run_update_anim_pass(self, duration.as_nanos() as u64);
self.run_rewrite_passes();
Handled::Yes
}
WindowEvent::EnableAccessTree => {
self.global_state.access_tree_active = true;
// AccessKit expects the next update to have include
// a description of every single node.
self.request_access_all();
self.global_state
.emit_signal(RenderRootSignal::RequestRedraw);
Handled::Yes
}
WindowEvent::DisableAccessTree => {
self.global_state.access_tree_active = false;
Handled::Yes
}
}
}
// --- MARK: PUB FUNCTIONS
/// Handles a pointer event.
pub fn handle_pointer_event(&mut self, event: PointerEvent) -> Handled {
let _span = info_span!("pointer_event");
let handled = run_on_pointer_event_pass(self, &event);
self.run_rewrite_passes();
handled
}
/// Handles a text event.
pub fn handle_text_event(&mut self, event: TextEvent) -> Handled {
let _span = info_span!("text_event");
let handled = run_on_text_event_pass(self, &event);
run_update_focus_pass(self);
if matches!(event, TextEvent::Ime(Ime::Enabled)) {
// Reset the last sent IME area, as the platform reset the IME state and may have
// forgotten it.
self.global_state.last_sent_ime_area = INVALID_IME_AREA;
}
self.run_rewrite_passes();
if !handled.is_handled() {
self.global_state.emit_signal(UnhandledTextEvent(event));
}
handled
}
/// Handles an accesskit event.
pub fn handle_access_event(&mut self, event: ActionRequest) {
let _span = info_span!("access_event");
if event.target_tree != TreeId::ROOT {
warn!(
"Received ActionRequest for an unknown tree. {:?}",
event.target_tree
);
return;
}
let Ok(id) = event.target_node.0.try_into() else {
warn!("Received ActionRequest with id 0. This shouldn't be possible.");
return;
};
let event = AccessEvent {
action: event.action,
data: event.data,
};
run_on_access_event_pass(self, &event, WidgetId(id));
self.run_rewrite_passes();
}
/// Delivers pending timers due when this call begins.
///
/// Timers set during delivery are considered on the next call. A callback
/// can cancel or replace another timer whose delivery has yet to begin.
pub fn handle_timers(&mut self) {
run_timers_pass(self);
self.run_rewrite_passes();
}
/// Registers all fonts that exist in the given data.
///
/// Returns a list of pairs each containing the family identifier and fonts
/// added to that family.
pub fn register_fonts(&mut self, data: Blob<u8>) -> Vec<(FamilyId, Vec<FontInfo>)> {
let ret = self
.global_state
.font_context
.collection
.register_fonts(data, None);
run_update_fonts_pass(self);
ret
}
/// Redraws the window.
///
/// Returns the current visual-layer plan and, if accessibility is active, a tree update.
pub fn redraw(&mut self) -> (VisualLayerPlan, Option<TreeUpdate>) {
self.run_rewrite_passes();
let access_tree_active = self.global_state.access_tree_active;
// TODO - Handle invalidation regions
let visual_layers = run_paint_pass(self);
let tree_update = access_tree_active
.then(|| run_accessibility_pass(self, self.global_state.scale_factor));
(visual_layers, tree_update)
}
/// Returns the current icon that the mouse should display.
pub fn cursor_icon(&self) -> CursorIcon {
self.global_state.cursor_icon
}
// --- MARK: ACCESS WIDGETS
/// Returns a [`WidgetRef`] to the root widget of the given [subwindow](crate::doc::masonry_concepts#subwindows).
pub fn get_subwindow_root(&self, subwindow_idx: usize) -> WidgetRef<'_, dyn Widget> {
self.get_widget(self.subwindow_root_id(subwindow_idx))
.expect("subwindow root not in widget tree")
}
/// Returns a [`WidgetRef`] to a specific widget.
pub fn get_widget(&self, id: WidgetId) -> Option<WidgetRef<'_, dyn Widget>> {
let node_ref = self.widget_arena.nodes.find(id)?;
let children = node_ref.children;
let widget = &*node_ref.item.widget;
let state = &node_ref.item.state;
let properties = &node_ref.item.properties;
let class_set = &node_ref.item.class_set;
let stack = self
.property_arena
.get(state.property_stack_id, widget.type_id());
let ctx = QueryCtx {
global_state: &self.global_state,
widget_state: state,
properties: PropertiesRef {
local: properties,
default_map: self
.property_arena
.default_properties
.for_widget(widget.type_id()),
stack,
class_set,
},
children,
property_arena: &self.property_arena,
};
Some(WidgetRef { ctx, widget })
}
/// Returns a [`WidgetRef`] to the widget with the given tag.
pub fn get_widget_with_tag<W: Widget + FromDynWidget + ?Sized>(
&self,
tag: WidgetTag<W>,
) -> Option<WidgetRef<'_, W>> {
let id = self.global_state.widget_tags.get(&tag.inner)?;
let widget_ref = self.get_widget(*id)?;
let widget_ref = widget_ref.downcast().expect("wrong tag type");
Some(widget_ref)
}
/// Checks if a widget with the given id is in the tree.
pub fn has_widget(&self, id: WidgetId) -> bool {
self.widget_arena.has(id)
}
/// Creates a unique tag for the widget with the given id and returns it.
///
/// This will return a unique tag even if called multiple times with the same id.
pub fn make_tag_for_widget<W: Widget>(&mut self, id: WidgetId) -> WidgetTag<W> {
let Some(node_ref) = self.widget_arena.nodes.find(id) else {
panic!("Could not find widget {id} in tree.");
};
let widget = &*node_ref.item.widget;
if widget.type_id() != TypeId::of::<W>() {
panic!(
"Widget {id} does not have type {}.",
std::any::type_name::<W>()
);
}
let new_tag = WidgetTag::unique();
self.global_state.widget_tags.insert(new_tag.inner, id);
new_tag
}
/// Creates a unique type-erased tag for the widget with the given id and returns it.
///
/// This will return a unique tag even if called multiple times with the same id.
pub fn make_dyn_tag_for_widget(&mut self, id: WidgetId) -> WidgetTag<dyn Widget> {
let Some(_) = self.widget_arena.nodes.find(id) else {
panic!("Could not find widget {id} in tree.");
};
let new_tag = WidgetTag::unique();
self.global_state.widget_tags.insert(new_tag.inner, id);
new_tag
}
/// Returns a [`WidgetMut`] to the root widget of the [main subwindow](crate::doc::masonry_concepts#subwindows).
///
/// Because of how `WidgetMut` works, it can only be passed to a user-provided callback.
pub fn edit_main_subwindow<R>(&mut self, f: impl FnOnce(WidgetMut<'_, dyn Widget>) -> R) -> R {
let subwindow_id = self.subwindow_root_id(0);
let res = mutate_widget(self, subwindow_id, f);
self.run_rewrite_passes();
res
}
// TODO - Use SubwindowId?
/// Returns a [`WidgetMut`] to the root widget of the given [subwindow](crate::doc::masonry_concepts#subwindows).
///
/// Because of how `WidgetMut` works, it can only be passed to a user-provided callback.
///
/// # Panics
///
/// Panics if `idx` is out of bounds.
pub fn edit_subwindow<R>(
&mut self,
subwindow_idx: usize,
f: impl FnOnce(WidgetMut<'_, dyn Widget>) -> R,
) -> R {
let subwindow_id = self.subwindow_root_id(subwindow_idx);
let res = mutate_widget(self, subwindow_id, f);
self.run_rewrite_passes();
res
}
/// Returns a [`WidgetMut`] to a specific widget.
///
/// Because of how `WidgetMut` works, it can only be passed to a user-provided callback.
///
/// # Panics
///
/// Panics if there is no widget with the given id in the tree.
#[track_caller]
pub fn edit_widget<R>(
&mut self,
id: WidgetId,
f: impl FnOnce(WidgetMut<'_, dyn Widget>) -> R,
) -> R {
if !self.widget_arena.has(id) {
panic!("Could not find widget {id} in tree.");
}
let res = mutate_widget(self, id, f);
self.run_rewrite_passes();
res
}
/// Returns a [`WidgetMut`] to the widget with the given tag.
///
/// Because of how `WidgetMut` works, it can only be passed to a user-provided callback.
#[track_caller]
pub fn edit_widget_with_tag<R, W: Widget + FromDynWidget + ?Sized>(
&mut self,
tag: WidgetTag<W>,
f: impl FnOnce(WidgetMut<'_, W>) -> R,
) -> R {
let Some(id) = self.global_state.widget_tags.get(&tag.inner).copied() else {
panic!("Could not find widget with tag '{tag}' in widget tree.");
};
let res = mutate_widget(self, id, |mut widget_mut| f(widget_mut.downcast()));
self.run_rewrite_passes();
res
}
/// Adds a new subwindow at the end of the stack, with the given widget as its root, at the given position.
///
/// The given `pos` must be in the window's coordinate space.
pub fn add_subwindow(
&mut self,
id: SubwindowId,
root: NewWidget<impl Widget + ?Sized>,
pos: Point,
) -> SubwindowId {
debug!("added subwindow to stack");
let id = mutate_widget(self, self.root_id(), |mut subwindow_stack| {
let mut subwindow_stack = subwindow_stack.downcast::<SubwindowStack>();
SubwindowStack::add_subwindow(&mut subwindow_stack, id, root, pos)
});
self.run_rewrite_passes();
id
}
/// Removes the subwindow with the given id.
///
/// The main subwindow cannot be removed.
///
/// # Panics
///
/// Panics in debug mode if the intended subwindow is the main subwindow or
/// is not found.
pub fn remove_subwindow(&mut self, id: SubwindowId) {
mutate_widget(self, self.root_id(), |mut subwindow_stack| {
let mut subwindow_stack = subwindow_stack.downcast::<SubwindowStack>();
SubwindowStack::remove_subwindow(&mut subwindow_stack, id);
});
self.run_rewrite_passes();
}
/// Repositions the subwindow with the given id.
///
/// The given `new_origin` must be in the window's coordinate space.
///
/// The main subwindow cannot be repositioned.
///
/// # Panics
///
/// Panics in debug mode if the intended subwindow is the main subwindow or
/// is not found.
pub fn reposition_subwindow(&mut self, id: SubwindowId, new_origin: Point) {
mutate_widget(self, self.root_id(), |mut subwindow_stack| {
let mut subwindow_stack = subwindow_stack.downcast::<SubwindowStack>();
SubwindowStack::reposition_subwindow(&mut subwindow_stack, id, new_origin);
});
self.run_rewrite_passes();
}
/// Returns the current size of the window.
pub fn size(&self) -> PhysicalSize<u32> {
self.global_state.size
}
/// Returns the current DPI scale factor of the window.
///
/// This is the number of physical pixels per logical pixel.
pub fn scale_factor(&self) -> f64 {
self.global_state.scale_factor
}
pub(crate) fn get_kurbo_size(&self) -> Size {
let size = self
.global_state
.size
.to_logical(self.global_state.scale_factor);
Size::new(size.width, size.height)
}
// --- MARK: REWRITE PASSES
/// Runs all rewrite passes on widget tree.
///
/// Rewrite passes are passes which occur after external events, and
/// update flags and internal values to a consistent state.
///
/// See the [passes documentation](crate::doc::pass_system) for details.
pub(crate) fn run_rewrite_passes(&mut self) {
const REWRITE_PASSES_MAX: usize = 4;
for _ in 0..REWRITE_PASSES_MAX {
// Note: this code doesn't do any short-circuiting, because each pass is
// expected to have its own early exits.
// Calling a run_xxx_pass should always be very fast if the pass doesn't need to do anything.
run_mutate_pass(self);
run_action_pass(self);
run_update_widget_tree_pass(self);
run_update_disabled_pass(self);
run_update_stashed_pass(self);
run_update_focusable_pass(self);
run_update_focus_pass(self);
run_layout_pass(self);
run_update_scroll_pass(self);
run_compose_pass(self);
run_update_pointer_pass(self);
run_update_props_pass(self);
if !self.needs_rewrite_passes() {
break;
}
}
if self.needs_rewrite_passes() {
warn!(
"All rewrite passes have run {REWRITE_PASSES_MAX} times, but invalidations are still set"
);
// To avoid an infinite loop, we delay re-running the passes until the next frame.
self.global_state
.emit_signal(RenderRootSignal::RequestRedraw);
}
if self.root_state().needs_anim {
self.global_state
.emit_signal(RenderRootSignal::RequestAnimFrame);
}
// We request a redraw if either the render tree or the accessibility
// tree needs to be rebuilt. Usually both are rebuilt at the same time.
// A redraw will trigger a rebuild of the accessibility tree.
if self.root_state().needs_paint || self.needs_accessibility() {
self.global_state
.emit_signal(RenderRootSignal::RequestRedraw);
}
if self.global_state.is_ime_active {
let widget = self
.global_state
.focused_widget
.expect("IME is active without a focused widget");
let ime_area = self.widget_arena.get_state(widget).get_ime_area();
// Certain desktop environments (primarily KDE on Wayland) re-synchronise IME state
// with the client (this app) in response to the safe area changing.
// Our handling of that ultimately results in us sending the safe area again,
// which causes an infinite loop.
// We break that loop by not re-sending the same safe area again.
if self.global_state.last_sent_ime_area != ime_area {
self.global_state.last_sent_ime_area = ime_area;
self.global_state
.emit_signal(RenderRootSignal::new_ime_moved_signal(ime_area));
}
}
}
// TODO - Factor out into "visit_all" method?
pub(crate) fn request_access_all(&mut self) {
fn request_access_all_in(node: ArenaMut<'_, WidgetArenaNode>) {
let children = node.children;
let widget = &mut *node.item.widget;
let state = &mut node.item.state;
state.needs_accessibility = true;
state.request_accessibility = true;
let id = state.id;
recurse_on_children(id, widget, children, |node| {
request_access_all_in(node);
});
}
let root_node = self.widget_arena.get_node_mut(self.root_id());
request_access_all_in(root_node);
self.global_state
.emit_signal(RenderRootSignal::RequestRedraw);
}
pub(crate) fn request_render_all(&mut self) {
fn request_render_all_in(node: ArenaMut<'_, WidgetArenaNode>) {
let children = node.children;
let widget = &mut *node.item.widget;
let state = &mut node.item.state;
state.needs_paint = true;
state.needs_accessibility = true;
state.request_pre_paint = true;
state.request_paint = true;
state.request_accessibility = true;
state.request_post_paint = true;
let id = state.id;
recurse_on_children(id, widget, children, |node| {
request_render_all_in(node);
});
}
let root_node = self.widget_arena.get_node_mut(self.root_id());
request_render_all_in(root_node);
self.global_state
.emit_signal(RenderRootSignal::RequestRedraw);
}
/// Checks whether the given id points to a widget that is "interactive".
/// i.e. not disabled or stashed.
/// Only interactive widgets can have text focus or pointer capture.
pub(crate) fn is_still_interactive(&self, id: WidgetId) -> bool {
let Some(node) = self.widget_arena.nodes.find(id) else {
return false;
};
let state = &node.item.state;
!state.is_stashed && !state.is_disabled
}
/// Returns the [`WidgetId`] of the [focused widget](crate::doc::masonry_concepts#text-focus).
pub fn focused_widget(&self) -> Option<WidgetId> {
self.global_state.focused_widget
}
/// Returns the [`WidgetId`] of the widget which [captures pointer events](crate::doc::masonry_concepts#pointer-capture).
pub fn pointer_capture_target(&self) -> Option<WidgetId> {
self.global_state.pointer_capture_target
}
/// Sets the [focused widget](crate::doc::masonry_concepts#text-focus)
/// and the [focus anchor](crate::doc::masonry_concepts#focus-anchor).
///
/// Returns false if the widget is not found in the tree or can't be focused.
pub fn focus_on(&mut self, id: Option<WidgetId>) -> bool {
if let Some(id) = id
&& !self.is_still_interactive(id)
{
return false;
}
self.global_state.next_focused_widget = id;
self.global_state.focus_anchor = id;
self.run_rewrite_passes();
true
}
/// Sets the [focus fallback](crate::doc::masonry_concepts#focus-fallback).
///
/// Returns false if the widget is not found in the tree or can't be focused.
pub fn set_focus_fallback(&mut self, id: Option<WidgetId>) -> bool {
if let Some(id) = id
&& !self.is_still_interactive(id)
{
return false;
}
self.global_state.focus_fallback = id;
true
}
/// Returns true if the widget tree is waiting for an animation frame.
pub fn needs_anim(&self) -> bool {
self.root_state().needs_anim
}
/// Returns the next timer deadline on this root's monotonic clock.
pub fn next_timer_deadline(&self) -> Option<Instant> {
let deadline = self.global_state.timers.next_deadline()?;
self.global_state
.timer_origin
.checked_add(Duration::from_nanos(deadline))
}
/// Returns true if the accessibility tree needs to be rebuilt.
///
/// This will be inhibited if `access_tree_active` is false.
pub fn needs_accessibility(&self) -> bool {
self.global_state.access_tree_active && self.root_state().needs_accessibility
}
/// Returns `true` if something requires a rewrite pass or a re-render.
pub fn needs_rewrite_passes(&self) -> bool {
self.root_state().needs_rewrite_passes() || self.global_state.needs_rewrite_passes()
}
// TODO - Remove?
#[doc(hidden)]
pub fn emit_signal(&mut self, signal: RenderRootSignal) {
self.global_state.emit_signal(signal);
}
}
// --- MARK: PROPERTY STACK EDITS
impl RenderRoot {
/// Replace a [`PropertyStack`] to a new one stack.
///
/// # Panics
///
/// Panics if there is no property stack with the given id in the [`PropertyArena`].
pub fn replace_property_stack(
&mut self,
property_stack_id: PropertyStackId,
stack: PropertyStack,
) {
let _ = self.property_arena.arena.insert(property_stack_id, stack);
self.invalidate_property_stack_resolution(property_stack_id);
self.run_rewrite_passes();
}
/// Checks if a property stack with the given id is in the property arena.
pub fn has_property_stack(&self, property_stack_id: PropertyStackId) -> bool {
self.property_arena.arena.contains_key(&property_stack_id)
}
/// Remove a property stack with the given id in the property arena.
///
/// This also invalidate the computed properties of any widget in the entire tree that is linked to that property stack,
/// and calls [`Widget::property_changed`] for every property previously
/// resolved by each widget.
pub fn remove_property_stack(&mut self, stack_id: PropertyStackId) {
// Don't proceed any further if nothing has been removed
if self.property_arena.arena.remove(&stack_id).is_none() {
return;
}
self.invalidate_property_stack_resolution(stack_id);
self.run_rewrite_passes();
}
/// Add a property stack to the [`PropertyArena`] and returns its id.
pub fn insert_property_stack(&mut self, property_stack: PropertyStack) -> PropertyStackId {
self.property_arena.insert(property_stack)
}
/// Mark the node that is linked to this property stack for the update-properties pass: `need_update_props`
fn invalidate_property_stack_resolution(&mut self, stack_id: PropertyStackId) {
// Only mark the node that is linked to this property stack for the update-properties pass: `need_update_props`
fn invalidate_properties_resolution(
node: ArenaMut<'_, WidgetArenaNode>,
stack_id: PropertyStackId,
) {
let children = node.children;
let widget = &mut *node.item.widget;
let state = &mut node.item.state;
// We tell the node state there some props update that needs to be done,
// since we can't tell in advance if its child has the property stack id.
// If not, the property changes will be not visible when we run the rewrite passes.
state.needs_update_props = true;
let is_linked_to_p_stack = state.property_stack_id == Some(stack_id);
if is_linked_to_p_stack {
state.request_update_props = true;
state.property_cache.invalidated = true;
}
let id = state.id;
recurse_on_children(id, widget, children, |node| {
invalidate_properties_resolution(node, stack_id);
});
}
let root_node = self.widget_arena.get_node_mut(self.root_id());
invalidate_properties_resolution(root_node, stack_id);
}
}
impl std::fmt::Debug for RenderRoot {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("RenderRoot")
.field("property_arena", &self.property_arena)
.field(
"widget_arena",
&format!("<{} widgets>", self.widget_arena.nodes.len()),
)
.field("subwindow_stack", &self.subwindow_stack)
.field("global_state", &self.global_state)
.finish_non_exhaustive()
}
}
impl std::fmt::Debug for RenderRootState {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
// TODO - Document fields?
f.debug_struct("RenderRootState").finish_non_exhaustive()
}
}
impl RenderRootState {
/// Sends a signal to the runner of this app, which allows global actions to be triggered by a widget.
pub(crate) fn emit_signal(&mut self, signal: RenderRootSignal) {
(self.signal_sink)(signal);
}
/// Emit a `RemoveSubwindow` signal and perform related cleanups.
pub(crate) fn remove_subwindow(&mut self, id: SubwindowId) {
if let Some((type_id, widget_id)) = self.attached_subwindows_rev.remove(&id)
&& let Some(map) = self.attached_subwindows.get_mut(&widget_id)
{
let _ = map.remove(&type_id);
}
self.emit_signal(RenderRootSignal::RemoveSubwindow(id));
}
pub(crate) fn set_timer(&mut self, target: WidgetId, key: TimerKey, delay: Duration) {
let now = self.timer_ticks();
self.cancel_timer(target, key);
let id = self.timers.schedule_once(
TimerData::WidgetTimer(target, key),
now,
duration_to_timer_ticks(delay),
);
self.timer_ids.entry(target).or_default().push((key, id));
}
pub(crate) fn cancel_timer(&mut self, target: WidgetId, key: TimerKey) {
if let Some(id) = self.take_timer_id(target, key) {
self.timers.cancel(id);
}
}
pub(crate) fn timer_id(&self, target: WidgetId, key: TimerKey) -> Option<TimerId> {
self.timer_ids
.get(&target)?
.iter()
.find_map(|&(candidate, id)| (candidate == key).then_some(id))
}
pub(crate) fn take_timer_id(&mut self, target: WidgetId, key: TimerKey) -> Option<TimerId> {
let keys = self.timer_ids.get_mut(&target)?;
let index = keys.iter().position(|&(candidate, _)| candidate == key)?;
let (_, id) = keys.swap_remove(index);
if keys.is_empty() {
self.timer_ids.remove(&target);
}
Some(id)
}
pub(crate) fn remove_widget_timers(&mut self, target: WidgetId) {
if self.timer_ids.remove(&target).is_some() {
self.timers.retain_pending(|timer| match timer.target() {
TimerData::WidgetTimer(widget_id, _) => *widget_id != target,
TimerData::TooltipHover(_) => true,
});
}
}
pub(crate) fn now(&self) -> Instant {
(self.timer_clock)()
}
pub(crate) fn timer_ticks(&self) -> TimerInstant {
let elapsed = self.now().saturating_duration_since(self.timer_origin);
duration_to_timer_ticks(elapsed)
}
/// Does something in this state indicate that the rewrite passes need to be reran.
///
/// This is checked in conjunction with [`WidgetState::needs_rewrite_passes`] - if
/// either returns true, the fixed point loop of the rewrite passes will be run again.
/// All passes have a fast-path exit check; these together are the union of those checks.
pub(crate) fn needs_rewrite_passes(&self) -> bool {
self.needs_pointer_pass
|| self.focused_widget != self.next_focused_widget
|| !self.mutate_callbacks.is_empty()
|| !self.actions.is_empty()
}
}
impl RenderRootSignal {
pub(crate) fn new_ime_moved_signal(area: Rect) -> Self {
Self::ImeMoved(
LogicalPosition {
x: area.origin().x,
y: area.origin().y,
},
LogicalSize {
width: area.size().width,
height: area.size().height,
},
)
}
}