masonry_testing 0.5.0

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

//! Tools and infrastructure for testing widgets.
//!
//! # Note on testing philosophy
//!
//! `TestHarness` provides two APIs, so to speak:
//!
//! - A high-level API that mimics user interactions.
//! - A low-level API that mirrors the [`RenderRoot`] API.
//!
//! Developers are encouraged to use the former if possible, and write tests as if
//! they were end users interacting with an application.
//!
//! We don't want users to write `harness.pointer_event(left_click(button_position))`,
//! we want them to write `harness.click_on(button)`, so to speak (actual method names differ).
//!
//! When adding features to `TestHarness`, we should always strive to give them such a high-level API.

use std::cell::Cell;
use std::collections::VecDeque;
use std::fs::File;
use std::io::{BufReader, Cursor};
use std::marker::PhantomData;
use std::path::PathBuf;
use std::rc::Rc;
use std::sync::{Arc, mpsc};
use std::time::UNIX_EPOCH;

use image::{DynamicImage, ImageFormat, ImageReader, Rgba, RgbaImage};
use imaging_vello_cpu::VelloCpuRenderer;
use masonry_core::imaging::record::{Scene, replay_transformed};
use masonry_core::imaging::{ImageRenderer as _, Painter};
use oxipng::{Options, optimize_from_memory};
use tracing::debug;

use masonry_core::accesskit::{
    Action, ActionRequest, Node, NodeId, Role, TreeId, TreeInfo, TreeUpdate,
};
use masonry_core::anymore::AnyDebug;
use masonry_core::app::{
    RenderRoot, RenderRootOptions, RenderRootSignal, VisualLayerKind, VisualLayerPlan,
    WindowSizePolicy, try_init_test_tracing,
};
use masonry_core::core::keyboard::{Code, Key, KeyState, NamedKey};
use masonry_core::core::{
    CursorIcon, DefaultProperties, ErasedAction, FromDynWidget, Handled, Ime, KeyboardEvent,
    Modifiers, NewWidget, PointerButton, PointerButtonEvent, PointerEvent, PointerId, PointerInfo,
    PointerScrollEvent, PointerState, PointerType, PointerUpdate, ScrollDelta, TextEvent, Widget,
    WidgetId, WidgetMut, WidgetRef, WidgetTag, WindowEvent,
};
use masonry_core::dpi::{LogicalPosition, LogicalSize, PhysicalSize};
use masonry_core::kurbo::{Affine, Point, Rect, Vec2};
use masonry_core::peniko::{Blob, Color};
use masonry_core::util::{Duration, Instant};

use crate::screenshots::get_image_diff;
use crate::{Record, Recorder};

/// A [`PointerInfo`] for a primary mouse, for testing.
pub const PRIMARY_MOUSE: PointerInfo = PointerInfo {
    pointer_id: Some(PointerId::PRIMARY),
    persistent_device_id: None,
    pointer_type: PointerType::Mouse,
};

// TODO - Add kittest support
// - Being able to check that the tree has an access node
// - Getting a WidgetRef/WidgetMut to a node from a kittest::Queryable
// - Making a debug snapshot of the access tree
// https://github.com/rerun-io/kittest

// TODO - Re-enable doc test.
// Doc test is currently disabled because it depends on a parent crate.

/// A safe headless environment to test widgets in.
///
/// `TestHarness` is a type that simulates a [`RenderRoot`] for testing.
///
/// # Workflow
///
/// One of the main goals of Masonry is to provide primitives that allow application
/// developers to test their app in a convenient and intuitive way.
/// The basic testing workflow is as follows:
///
/// - Create a harness with some widget.
/// - Send events to the widget as if you were a user interacting with a window.
///   (Rewrite passes are handled automatically.)
/// - Check that the state of the widget graph matches what you expect.
///
/// You can do that last part in a few different ways.
/// You can get a [`WidgetRef`] to a specific widget through methods like [`get_widget`](Self::get_widget).
/// [`WidgetRef`] implements `Debug`, so you can check the state of an entire tree with something like the [`insta`] crate.
///
/// You can also render the widget tree directly with the [`render`](Self::render) method.
/// Masonry also provides the [`assert_render_snapshot`] macro, which performs snapshot testing on the
/// rendered widget tree automatically.
///
/// # Fidelity
///
/// `TestHarness` tries to act like the normal masonry environment. It will run the same passes as the normal app after every user event and animation.
///
/// Timers and animation frames can be simulated with [`advance_time`](Self::advance_time).
///
/// One minor difference is that paint only happens when the user explicitly calls rendering
/// methods, whereas in a normal applications you could reasonably expect multiple paint calls
/// between eg any two clicks.
///
/// # Example
///
/// ```rust,ignore
/// use insta::assert_debug_snapshot;
///
/// use masonry::core::PointerButton;
/// use masonry::core::Action;
/// use masonry::testing::assert_render_snapshot;
/// use masonry::testing::TestHarness;
/// use masonry::testing::TestWidgetExt;
/// use masonry::theme::default_property_set;
/// use masonry::widgets::Button;
/// # /*
/// #[test]
/// # */
/// fn simple_button() {
///     let widget = Button::new("Hello");
///
///     let mut harness = TestHarness::create(default_property_set(), widget);
///     let button_id = harness.root_id();
///
///     # if false {
///     assert_render_snapshot!(harness, "hello");
///     # }
///
///     assert_eq!(harness.pop_action(), None);
///
///     harness.mouse_click_on(button_id);
///     assert_eq!(
///         harness.pop_action(),
///         Some((Action::ButtonPressed(Some(PointerButton::Primary)), button_id))
///     );
/// }
///
/// # simple_button();
/// ```
///
/// [`assert_render_snapshot`]: crate::assert_render_snapshot
/// [`insta`]: https://docs.rs/insta/latest/insta/
#[derive(Debug)]
pub struct TestHarness<W: Widget> {
    signal_receiver: mpsc::Receiver<RenderRootSignal>,
    render_root: RenderRoot,
    root_tag: WidgetTag<W>,
    clock: Rc<Cell<Instant>>,
    access_tree: accesskit_consumer::Tree,
    renderer: Option<VelloCpuRenderer>,
    mouse_state: PointerState,
    window_size: PhysicalSize<u32>,
    root_padding: u32,
    background_color: Color,
    panic_on_rewrite_saturation: bool,
    max_screenshot_size: u32,
    action_queue: VecDeque<(ErasedAction, WidgetId)>,
    root_text_event_queue: VecDeque<TextEvent>,
    has_ime_session: bool,
    ime_rect: (LogicalPosition<f64>, LogicalSize<f64>),
    clipboard: String,
    title: String,
    _marker: PhantomData<W>,
}

/// Parameters for creating a [`TestHarness`].
#[derive(Debug, Clone, Copy)]
#[non_exhaustive]
pub struct TestHarnessParams {
    /// The size of the virtual window the harness renders into for snapshot testing.
    /// Defaults to [`TestHarnessParams::DEFAULT_SIZE`].
    pub window_size: LogicalSize<u32>,
    /// The background color of the virtual window.
    /// Defaults to [`TestHarnessParams::DEFAULT_BACKGROUND_COLOR`].
    pub background_color: Color,
    /// Extra padding added to screenshots in [`assert_render_snapshot`].
    ///
    /// Currently defaults to zero, but we plan to change this
    /// to [`TestHarnessParams::ROOT_PADDING`] soon.
    /// This is useful:
    ///
    /// 1) For individual widgets, as they will often be designed with content outside their
    ///    border-box (e.g. drop shadows, focus indicators).
    /// 2) For full apps, as it allows (manual) validation that none of the app content is cut off by
    ///    the window border.
    ///
    /// [`assert_render_snapshot`]: crate::assert_render_snapshot
    pub root_padding: u32,
    /// The scale factor widgets are rendered at.
    /// Defaults to 1.0.
    pub scale_factor: f64,
    /// Whether to panic when we detect a loop in [rewrite passes](masonry_core::doc::pass_system#rewrite-passes).
    ///
    /// A loop means a case where the passes keep running because some passes keep
    /// invalidating flags for previous passes.
    pub panic_on_rewrite_saturation: bool,
    /// The largest size a screenshot file is allowed to be in this test.
    /// Defaults to `8KiB`.
    ///
    /// You can use [`TestHarnessParams::KIBIBYTE`] to help set this.
    /// Keeping screenshot files small avoids clones of this repository taking too long.
    /// Masonry testing uses [oxipng] to optimise the size of screenshots.
    pub max_screenshot_size: u32,
}

/// Assert a snapshot of a rendered frame of your app.
///
/// This macro takes a test harness and a name, renders the current state of the app,
/// and stores the rendered image to `<CRATE-ROOT>/screenshots/<TEST-NAME>.png`.
/// This rendering will have extra padding which would not be present in a real app,
/// as documented in [`TestHarnessParams::root_padding`].
///
/// If a screenshot already exists, the rendered value is compared against this screenshot.
/// The assert passes if both are equal; otherwise, a diff file is created.
/// If the test is run again and the new rendered value matches the old screenshot, the diff file is deleted.
///
/// If a screenshot doesn't exist, the assert will fail; the new screenshot is stored as
/// `<CRATE-ROOT>/screenshots/<TEST-NAME>.new.png`, and must be renamed before the assert will pass.
///
/// You can also run tests with the `MASONRY_TEST_BLESS` flag set to `1` to assume all
/// differences are intended and overwrite all the screenshots with new values.
#[macro_export]
macro_rules! assert_render_snapshot {
    ($test_harness:expr, $name:expr) => {
        $test_harness.check_render_snapshot(env!("CARGO_MANIFEST_DIR"), $name, false)
    };
}

/// Assert a snapshot of a rendered frame of your app, expecting it to fail.
///
/// This macro does essentially the same thing as [`assert_render_snapshot`], but
/// instead of asserting that the rendered frame matches the existing screenshot,
/// it asserts that it does not match.
///
/// This is mostly used internally by Masonry to test that the image diffing does
/// detect changes and regressions.
///
/// This macro is read-only and will not write any new screenshots.
///
/// [`assert_render_snapshot`]: crate::assert_render_snapshot
#[macro_export]
macro_rules! assert_failing_render_snapshot {
    ($test_harness:expr, $name:expr) => {
        $test_harness.check_render_snapshot(env!("CARGO_MANIFEST_DIR"), $name, true)
    };
}

impl TestHarnessParams {
    /// Default test param values.
    pub const DEFAULT: Self = Self {
        window_size: Self::DEFAULT_SIZE,
        background_color: Self::DEFAULT_BACKGROUND_COLOR,
        root_padding: 0,
        scale_factor: 1.0,
        panic_on_rewrite_saturation: true,
        max_screenshot_size: 8 * Self::KIBIBYTE,
    };

    /// Default canvas size for tests.
    pub const DEFAULT_SIZE: LogicalSize<u32> = LogicalSize::new(400, 400);

    /// Default background color for tests.
    pub const DEFAULT_BACKGROUND_COLOR: Color = Color::from_rgb8(0x29, 0x29, 0x29);

    /// Recommended root padding for tests.
    ///
    /// To be set as [`TestHarnessParams::root_padding`]
    pub const ROOT_PADDING: u32 = 5;

    /// One kibibyte. Used in [`TestHarnessParams::max_screenshot_size`].
    pub const KIBIBYTE: u32 = 1024;
}

impl Default for TestHarnessParams {
    fn default() -> Self {
        Self::DEFAULT
    }
}

impl TestHarnessParams {
    /// Returns parameters for a test harness with custom dimensions.
    pub fn size_and_padding(window_size: impl Into<LogicalSize<u32>>, root_padding: u32) -> Self {
        Self {
            window_size: window_size.into(),
            root_padding,
            ..Self::DEFAULT
        }
    }

    /// Builder method to set `window_size`.
    pub fn with_size(self, window_size: impl Into<LogicalSize<u32>>) -> Self {
        Self {
            window_size: window_size.into(),
            ..self
        }
    }

    /// Builder method to set `background_color`.
    pub const fn with_background(self, background_color: Color) -> Self {
        Self {
            background_color,
            ..self
        }
    }

    /// Builder method to set `root_padding`.
    pub const fn with_padding(self, root_padding: u32) -> Self {
        Self {
            root_padding,
            ..self
        }
    }

    /// Builder method to set `scale_factor`.
    pub const fn with_scale(self, scale_factor: f64) -> Self {
        Self {
            scale_factor,
            ..self
        }
    }

    /// Builder method to set `max_screenshot_size`.
    pub const fn with_max_screenshot_size(self, max_screenshot_size: u32) -> Self {
        Self {
            max_screenshot_size,
            ..self
        }
    }
}

/// Roboto is our current test font.
pub const ROBOTO: &[u8] = include_bytes!(concat!(
    env!("CARGO_MANIFEST_DIR"),
    "/resources/fonts/roboto/Roboto-Regular.ttf"
));

impl<W: Widget> TestHarness<W> {
    // -- MARK: CREATE
    /// Builds harness with given root widget.
    ///
    /// Window size will be [`TestHarnessParams::DEFAULT_SIZE`].
    /// Background color will be [`TestHarnessParams::DEFAULT_BACKGROUND_COLOR`].
    pub fn create(default_props: DefaultProperties, root_widget: NewWidget<W>) -> Self {
        Self::create_with(default_props, root_widget, TestHarnessParams::default())
    }

    /// Builds harness with given root widget and window size.
    pub fn create_with_size(
        default_props: DefaultProperties,
        root_widget: NewWidget<W>,
        window_size: impl Into<LogicalSize<u32>>,
    ) -> Self {
        Self::create_with(
            default_props,
            root_widget,
            TestHarnessParams::default().with_size(window_size),
        )
    }

    /// Builds harness with given root widget and additional parameters.
    pub fn create_with(
        default_props: DefaultProperties,
        root_widget: NewWidget<W>,
        params: TestHarnessParams,
    ) -> Self {
        let mouse_state = PointerState::default();
        let window_size = params.window_size.to_physical(params.scale_factor);

        // If no tracing subscriber has been set before, we set our own. If one has
        // already been set, we get an error which we swallow.
        // Having a default subscriber is helpful for tests; swallowing errors means
        // we don't panic if the user has already set one, or a test creates multiple
        // harnesses.
        let _ = try_init_test_tracing();

        let data = Blob::new(Arc::new(ROBOTO));

        let (signal_sender, signal_receiver) = mpsc::channel::<RenderRootSignal>();

        let dummy_tree_update = TreeUpdate {
            tree_id: TreeId::ROOT,
            nodes: vec![(0.into(), Node::new(Role::Window))],
            tree: Some(TreeInfo {
                root: 0.into(),
                toolkit_name: None,
                toolkit_version: None,
            }),
            focus: 0.into(),
        };

        let clock = Rc::new(Cell::new(Instant::now()));
        let root_clock = Rc::clone(&clock);
        let mut render_root = RenderRoot::new_with_clock(
            root_widget,
            move |signal| signal_sender.send(signal).unwrap(),
            RenderRootOptions {
                default_properties: Arc::new(default_props),
                use_system_fonts: false,
                size_policy: WindowSizePolicy::User,
                size: window_size,
                scale_factor: params.scale_factor,
                test_font: Some(data),
            },
            move || root_clock.get(),
        );
        let root_id = render_root.get_subwindow_root(0).id();
        let root_tag = render_root.make_tag_for_widget(root_id);

        let mut harness = Self {
            signal_receiver,
            render_root,
            root_tag,
            clock,
            access_tree: accesskit_consumer::Tree::new(dummy_tree_update, false),
            renderer: None,
            mouse_state,
            window_size,
            background_color: params.background_color,
            root_padding: params.root_padding,
            panic_on_rewrite_saturation: params.panic_on_rewrite_saturation,
            max_screenshot_size: params.max_screenshot_size,
            action_queue: VecDeque::new(),
            root_text_event_queue: VecDeque::new(),
            has_ime_session: false,
            ime_rect: Default::default(),
            clipboard: String::new(),
            title: String::new(),
            _marker: PhantomData,
        };

        // Set up the initial state, and clear invalidation flags.
        harness.process_window_event(WindowEvent::EnableAccessTree);
        harness.animate_ms(0);

        let (_, tree_update) = harness.render_root.redraw();
        let tree_update = tree_update.unwrap();
        harness
            .access_tree
            .update_and_process_changes(tree_update, &mut NoOpTreeChangeHandler);

        harness
    }

    // TODO - Reorder methods. Low-level methods should appear later in the doc than high-level methods.

    // --- MARK: PROCESS EVENTS

    /// Sends a [`WindowEvent`] to the simulated window.
    ///
    /// This will run [rewrite passes](masonry_core::doc::pass_system#rewrite-passes) after the event is processed.
    pub fn process_window_event(&mut self, event: WindowEvent) -> Handled {
        let handled = self.render_root.handle_window_event(event);
        self.process_signals();
        handled
    }

    /// Sends a [`PointerEvent`] to the simulated window.
    ///
    /// This will run [rewrite passes](masonry_core::doc::pass_system#rewrite-passes) after the event is processed.
    pub fn process_pointer_event(&mut self, event: PointerEvent) -> Handled {
        let handled = self.render_root.handle_pointer_event(event);
        self.process_signals();
        handled
    }

    /// Sends a [`TextEvent`] to the simulated window.
    ///
    /// This will run [rewrite passes](masonry_core::doc::pass_system#rewrite-passes) after the event is processed.
    pub fn process_text_event(&mut self, event: TextEvent) -> Handled {
        let handled = self.render_root.handle_text_event(event);
        self.process_signals();
        handled
    }

    /// Sends an [`ActionRequest`] to the simulated window.
    ///
    /// This will run [rewrite passes](masonry_core::doc::pass_system#rewrite-passes) after the event is processed.
    pub fn process_access_event(&mut self, event: ActionRequest) {
        self.render_root.handle_access_event(event);
        self.process_signals();
    }

    // This should be ran after any operation which runs the rewrite passes
    // (i.e. processing an event, etc.)
    fn process_signals(&mut self) {
        if self.panic_on_rewrite_saturation && self.render_root.needs_rewrite_passes() {
            panic!("Loop detected in rewrite passes");
        }
        while let Some(signal) = self.signal_receiver.try_iter().next() {
            match signal {
                RenderRootSignal::Action(action, widget_id) => {
                    self.action_queue.push_back((action, widget_id));
                }
                RenderRootSignal::StartIme => {
                    self.has_ime_session = true;
                }
                RenderRootSignal::EndIme => {
                    self.has_ime_session = false;
                }
                RenderRootSignal::ImeMoved(position, size) => {
                    self.ime_rect = (position, size);
                }
                RenderRootSignal::ClipboardStore(text) => {
                    self.clipboard = text;
                }
                RenderRootSignal::UnhandledTextEvent(event) => {
                    self.root_text_event_queue.push_back(event);
                }
                RenderRootSignal::RequestRedraw => (),
                RenderRootSignal::RequestAnimFrame => (),
                RenderRootSignal::TakeFocus => (),
                RenderRootSignal::SetCursor(_) => (),
                RenderRootSignal::SetSize(physical_size) => {
                    self.window_size = physical_size;
                    self.process_window_event(WindowEvent::Resize(physical_size));
                }
                RenderRootSignal::SetTitle(title) => {
                    self.title = title;
                }
                RenderRootSignal::DragWindow => (),
                RenderRootSignal::DragResizeWindow(_) => (),
                RenderRootSignal::ToggleMaximized => (),
                RenderRootSignal::Minimize => (),
                RenderRootSignal::Exit => (),
                RenderRootSignal::ShowWindowMenu(_) => (),
                RenderRootSignal::WidgetSelectedInInspector(_) => (),
                RenderRootSignal::NewSubwindow(id, _type, root, pos) => {
                    self.render_root.add_subwindow(id, root, pos);
                }
                RenderRootSignal::RemoveSubwindow(root_id) => {
                    self.render_root.remove_subwindow(root_id);
                }
                RenderRootSignal::RepositionSubwindow(root_id, new_pos) => {
                    self.render_root.reposition_subwindow(root_id, new_pos);
                }
            }
        }
    }

    // --- MARK: RENDER
    /// Renders the window into an image and updates the `accesskit_consumer` tree.
    ///
    /// The returned image contains a bitmap (an array of pixels) as an 8-bits-per-channel RGB image.
    /// The returned image has padding of the [`TestHarnessParams::root_padding`] this harness
    /// was created with on all sides.
    ///
    /// If you just want to run the rendering passes and get the render data without
    /// rastering it into an image, use [`Self::redraw`] instead.
    pub fn render(&mut self) -> RgbaImage {
        let (visual_layers, _tree_update) = self.redraw();

        if std::env::var("SKIP_RENDER_TESTS").is_ok_and(|it| !it.is_empty()) {
            return RgbaImage::from_pixel(1, 1, Rgba([255, 255, 255, 255]));
        }

        let (width, height) = {
            // Avoid having a zero-sized image.
            let width = self.window_size.width.max(1) + self.root_padding * 2;
            let height = self.window_size.height.max(1) + self.root_padding * 2;
            (width, height)
        };

        let mut full_scene = Scene::new();
        {
            let (width, height) = { (f64::from(width), f64::from(height)) };
            let mut painter = Painter::new(&mut full_scene);
            painter.fill_rect(Rect::new(0.0, 0.0, width, height), self.background_color);

            let root_transform =
                Affine::translate((f64::from(self.root_padding), f64::from(self.root_padding)))
                    * Affine::scale(self.render_root.scale_factor());

            for layer in &visual_layers.layers {
                if let VisualLayerKind::Scene(scene) = &layer.kind {
                    replay_transformed(scene, &mut full_scene, root_transform * layer.transform);
                }
            }
        }

        if self.renderer.is_none() {
            self.renderer = Some(VelloCpuRenderer::new(1, 1));
        }
        let renderer = self.renderer.as_mut().unwrap();

        let image = renderer
            .render_source(&mut full_scene, width, height)
            .unwrap();
        RgbaImage::from_vec(image.width, image.height, image.data).expect("failed to create image")
    }

    /// Returns render root of the harness
    pub fn render_root(&mut self) -> &mut RenderRoot {
        &mut self.render_root
    }

    /// Redraws the window.
    ///
    /// If you want to get a bitmap image of the contents, use [`Self::render`] instead.
    pub fn redraw(&mut self) -> (VisualLayerPlan, TreeUpdate) {
        let (visual_layers, tree_update) = self.render_root.redraw();
        let tree_update = tree_update.unwrap();
        self.access_tree
            .update_and_process_changes(tree_update.clone(), &mut NoOpTreeChangeHandler);

        (visual_layers, tree_update)
    }

    /// Returns a reference to the current state of the accessibility tree.
    pub fn access_tree(&self) -> &accesskit_consumer::Tree {
        &self.access_tree
    }

    /// Returns a reference to the current value of a node of the accessibility tree.
    pub fn access_node<W2: Widget + FromDynWidget + ?Sized>(
        &self,
        tag: WidgetTag<W2>,
    ) -> Option<accesskit_consumer::NodeRef<'_>> {
        let id = self.get_widget(tag).id();
        self.access_tree
            .state()
            .node_by_tree_local_id(NodeId::from(id), TreeId::ROOT)
    }

    // --- MARK: EVENT HELPERS

    /// Move an internal mouse state, and send a [`Move`](PointerEvent::Move) event to the window.
    ///
    /// The position is in logical coordinates.
    pub fn mouse_move(&mut self, pos: impl Into<Point>) {
        let Point { x, y } = pos.into();
        let scale_factor = self.render_root.scale_factor();
        self.mouse_state.position = LogicalPosition { x, y }.to_physical(scale_factor);
        self.mouse_state.scale_factor = scale_factor;

        debug!("Harness mouse moved to {x}, {y}");

        self.process_pointer_event(PointerEvent::Move(PointerUpdate {
            pointer: PRIMARY_MOUSE,
            current: self.mouse_state.clone(),
            coalesced: vec![],
            predicted: vec![],
        }));
    }

    /// Sends a [`Down`](PointerEvent::Down) event to the window.
    pub fn mouse_button_press(&mut self, button: Option<PointerButton>) {
        if let Some(button) = button {
            self.mouse_state.buttons.insert(button);
        }
        self.process_pointer_event(PointerEvent::Down(PointerButtonEvent {
            pointer: PRIMARY_MOUSE,
            button,
            state: self.mouse_state.clone(),
        }));
    }

    /// Sends an [`Up`](PointerEvent::Up) event to the window.
    pub fn mouse_button_release(&mut self, button: Option<PointerButton>) {
        if let Some(button) = button {
            self.mouse_state.buttons.remove(button);
        }
        self.process_pointer_event(PointerEvent::Up(PointerButtonEvent {
            pointer: PRIMARY_MOUSE,
            button,
            state: self.mouse_state.clone(),
        }));
    }

    /// Sends a [`Scroll`](PointerEvent::Scroll) event to the window.
    ///
    /// The delta is in logical pixels.
    pub fn mouse_wheel(&mut self, Vec2 { x, y }: Vec2) {
        let scale_factor = self.render_root.scale_factor();
        self.process_pointer_event(PointerEvent::Scroll(PointerScrollEvent {
            pointer: PRIMARY_MOUSE,
            delta: ScrollDelta::PixelDelta(LogicalPosition { x, y }.to_physical(scale_factor)),
            state: self.mouse_state.clone(),
        }));
    }

    /// Sends events that lead to a given widget being clicked.
    ///
    /// Combines [`mouse_move`](Self::mouse_move), [`mouse_button_press`](Self::mouse_button_press), and [`mouse_button_release`](Self::mouse_button_release).
    ///
    /// # Panics
    ///
    /// - If the widget is not found in the tree.
    /// - If the widget is stashed.
    /// - If the widget doesn't accept pointer events.
    /// - If the widget is scrolled out of view.
    #[track_caller]
    pub fn mouse_click_on<W2: Widget + FromDynWidget + ?Sized>(
        &mut self,
        tag: WidgetTag<W2>,
        button: Option<PointerButton>,
    ) {
        self.mouse_move_to(tag);
        self.mouse_button_press(button);
        self.mouse_button_release(button);
    }

    /// Uses [`mouse_move`](Self::mouse_move) to set the internal mouse pos to the center of the given widget.
    ///
    /// # Panics
    ///
    /// - If the widget is not found in the tree.
    /// - If the widget is stashed.
    /// - If the widget doesn't accept pointer events.
    /// - If the widget is scrolled out of view.
    #[track_caller]
    pub fn mouse_move_to<W2: Widget + FromDynWidget + ?Sized>(&mut self, tag: WidgetTag<W2>) {
        let widget = self.get_widget(tag);
        let id = widget.id();
        let local_widget_center = widget.ctx().border_box().center();
        let widget_center = widget.ctx().window_transform() * local_widget_center;

        // TODO - Add reachable_by_pointer() method.
        if !widget.ctx().accepts_pointer_interaction() {
            panic!("Widget {id} doesn't accept pointer events");
        }
        if widget.ctx().is_stashed() {
            panic!("Widget {id} is stashed");
        }
        if self
            .render_root
            .get_subwindow_root(0)
            .find_widget_under_pointer(widget_center)
            .map(|w| w.id())
            != Some(id)
        {
            panic!("Widget {id} is not visible");
        }

        self.mouse_move(widget_center);
    }

    /// Uses [`mouse_move`](Self::mouse_move) to set the internal mouse pos to the center of the given widget.
    ///
    /// This does fewer checks than [`mouse_move_to`](Self::mouse_move_to), which in most cases should be preferred.
    /// However, `mouse_move_to` does not allow moving to non-interactive widgets, which can sometimes be desirable.
    ///
    /// TODO: In the long term, this method should still check if the widget is visible, without requiring it to be interactive.
    /// At that point, it might make sense to rename this to `mouse_move_to`, deleting the distinction.
    ///
    /// # Panics
    ///
    /// - If the widget is not found in the tree.
    /// - If the widget is stashed.
    #[track_caller]
    pub fn mouse_move_to_unchecked<W2: Widget + FromDynWidget + ?Sized>(
        &mut self,
        tag: WidgetTag<W2>,
    ) {
        let widget = self.get_widget(tag);
        let id = widget.id();
        let local_widget_center = widget.ctx().border_box().center();
        let widget_center = widget.ctx().window_transform() * local_widget_center;

        if widget.ctx().is_stashed() {
            panic!("Widget {id} is stashed");
        }

        self.mouse_move(widget_center);
    }

    /// Tries to get the target widget into the viewport.
    ///
    /// This will send an accesskit [`ScrollIntoView`] action to the widget,
    /// which will usually send [`RequestPanToChild`] events to the widget's parents.
    /// If the widget is hidden because it's "scrolled away", this should make it visible again.
    ///
    /// [`RequestPanToChild`]: masonry_core::core::Update::RequestPanToChild
    /// [`ScrollIntoView`]: masonry_core::accesskit::Action::ScrollIntoView
    #[track_caller]
    pub fn scroll_into_view<W2: Widget + FromDynWidget + ?Sized>(&mut self, tag: WidgetTag<W2>) {
        let id = self.get_widget(tag).id();
        self.render_root.handle_access_event(ActionRequest {
            action: Action::ScrollIntoView,
            target_tree: TreeId::ROOT,
            target_node: id.to_raw().into(),
            data: None,
        });
    }

    /// Clicks the given widget.
    ///
    /// This will send an accesskit [`Click`] action to the widget,
    /// which may have different behavior compared to a normal mouse click.
    ///
    /// Unlike [`Self::mouse_click_on`], the event will be routed to the target widget
    /// even if it's not visible, or hidden behind other widgets.
    ///
    /// # Panics
    ///
    /// - If the widget is not found in the tree.
    ///
    /// [`Click`]: masonry_core::accesskit::Action::Click
    #[track_caller]
    pub fn accessibility_click_on<W2: Widget + FromDynWidget + ?Sized>(
        &mut self,
        tag: WidgetTag<W2>,
    ) {
        let id = self.get_widget(tag).id();
        self.render_root.handle_access_event(ActionRequest {
            action: Action::Click,
            target_tree: TreeId::ROOT,
            target_node: id.to_raw().into(),
            data: None,
        });
    }

    // TODO - Handle complicated IME
    // TODO - Mock Winit keyboard events
    /// Sends a [`TextEvent`] for each character in the given string.
    pub fn keyboard_type_chars(&mut self, text: &str) {
        // For each character
        for c in text.split("").filter(|s| !s.is_empty()) {
            let event = TextEvent::Ime(Ime::Commit(c.to_string()));
            self.render_root.handle_text_event(event);
        }
        self.process_signals();
    }

    /// Sends a [`TextEvent`] representing the user pressing the `Tab` key, either with or without the `Shift` key pressed.
    pub fn press_tab_key(&mut self, shift: bool) {
        let modifiers = if shift {
            Modifiers::SHIFT
        } else {
            Modifiers::empty()
        };
        let event = TextEvent::Keyboard(KeyboardEvent {
            state: KeyState::Down,
            key: Key::Named(NamedKey::Tab),
            code: Code::Unidentified,
            modifiers,
            ..KeyboardEvent::default()
        });
        self.render_root.handle_text_event(event);
        self.process_signals();
    }

    /// Sets the [focused widget](masonry_core::doc::masonry_concepts#text-focus)
    /// and the [focus anchor](masonry_core::doc::masonry_concepts#focus-anchor).
    ///
    /// # Panics
    ///
    /// If the widget is not found in the tree or can't be focused.
    #[track_caller]
    pub fn focus_on<W2: Widget + FromDynWidget + ?Sized>(&mut self, tag: WidgetTag<W2>) {
        let widget = self.get_widget(tag);
        let id = widget.id();

        if widget.ctx().is_stashed() {
            panic!("Cannot focus widget {id}: widget is stashed");
        }
        if widget.ctx().is_disabled() {
            panic!("Cannot focus widget {id}: widget is disabled");
        }

        let succeeded = self.render_root.focus_on(Some(id));
        assert!(
            succeeded,
            "RenderRoot::focus_on refused a widget which TestHarness::focus_on accepted."
        );
        self.process_signals();
    }

    /// Sets the [focused widget](masonry_core::doc::masonry_concepts#text-focus) to `None`.
    pub fn clear_focus(&mut self) {
        let _ = self.render_root.focus_on(None);
        self.process_signals();
    }

    /// Sets the [focus fallback](masonry_core::doc::masonry_concepts#focus-fallback).
    pub fn set_focus_fallback<W2: Widget + FromDynWidget + ?Sized>(&mut self, tag: WidgetTag<W2>) {
        let id = self.get_widget(tag).id();
        let _ = self.render_root.set_focus_fallback(Some(id));
    }

    /// Sets the [focus fallback](masonry_core::doc::masonry_concepts#focus-fallback) to `None`.
    pub fn clear_focus_fallback(&mut self) {
        let _ = self.render_root.set_focus_fallback(None);
    }

    /// Advances simulated time by the given number of milliseconds.
    pub fn animate_ms(&mut self, ms: u64) {
        self.advance_time(Duration::from_millis(ms));
    }

    /// Advances the simulated clock by `elapsed`, runs an animation frame,
    /// and delivers timers due at the new time.
    pub fn advance_time(&mut self, elapsed: Duration) {
        self.clock.set(self.clock.get() + elapsed);
        self.render_root
            .handle_window_event(WindowEvent::AnimFrame(elapsed));
        self.render_root.handle_timers();
        self.process_signals();
    }

    /// Helper method to directly enable/disable a widget.
    pub fn set_disabled(&mut self, widget: WidgetTag<impl Widget>, disabled: bool) {
        self.edit_widget(widget, |mut target| {
            target.ctx.set_disabled(disabled);
        });
    }

    // --- MARK: GETTERS

    /// Returns a [`WidgetRef`] to the root widget.
    pub fn root_widget(&self) -> WidgetRef<'_, W> {
        self.render_root.get_subwindow_root(0).downcast().unwrap()
    }

    /// Returns the [`WidgetId`] of the root widget.
    pub fn root_id(&self) -> WidgetId {
        self.render_root.get_subwindow_root(0).id()
    }

    /// Replace the tree-wide default properties at runtime.
    ///
    /// Mirrors [`RenderRoot::set_default_properties`].
    pub fn set_default_properties(&mut self, default_properties: Arc<DefaultProperties>) {
        self.render_root.set_default_properties(default_properties);
    }

    /// Returns a [`WidgetTag`] associated with the root widget.
    pub fn root_tag(&self) -> WidgetTag<W> {
        self.root_tag
    }

    /// Returns a [`WidgetRef`] to the widget with the given tag.
    ///
    /// # Panics
    ///
    /// Panics if no widget with this tag can be found.
    #[track_caller]
    pub fn get_widget<W2: Widget + FromDynWidget + ?Sized>(
        &self,
        tag: WidgetTag<W2>,
    ) -> WidgetRef<'_, W2> {
        self.render_root
            .get_widget_with_tag(tag)
            .unwrap_or_else(|| panic!("could not find widget '{tag}'"))
    }

    /// Returns a [`WidgetRef`] to the widget with the given id.
    ///
    /// # Panics
    ///
    /// Panics if no widget with this id can be found.
    #[track_caller]
    pub fn get_widget_with_id(&self, id: WidgetId) -> WidgetRef<'_, dyn Widget> {
        self.render_root
            .get_widget(id)
            .unwrap_or_else(|| panic!("could not find widget {id}"))
    }

    /// Tries to return a [`WidgetRef`] to the widget with the given id.
    pub fn try_get_widget_with_id(&self, id: WidgetId) -> Option<WidgetRef<'_, dyn Widget>> {
        self.render_root.get_widget(id)
    }

    /// Creates a unique tag for the widget with the given id and returns it.
    #[track_caller]
    pub fn make_tag_for_widget<W2: Widget>(&mut self, id: WidgetId) -> WidgetTag<W2> {
        self.render_root.make_tag_for_widget(id)
    }

    /// Creates a unique type-erased tag for the widget with the given id and returns it.
    // NOTE: Using this method may be a code smell. We should track down
    // its users and think of other ways to cover their use-cases.
    #[track_caller]
    pub fn make_dyn_tag_for_widget(&mut self, id: WidgetId) -> WidgetTag<dyn Widget> {
        self.render_root.make_dyn_tag_for_widget(id)
    }

    /// Drains the events recorded by the [`Recorder`] widget with the given tag.
    ///
    /// # Panics
    ///
    /// Panics if no widget with this tag can be found.
    #[track_caller]
    pub fn take_records_of<W2: Widget>(&self, tag: WidgetTag<Recorder<W2>>) -> Vec<Record> {
        self.get_widget(tag).inner().recording().drain()
    }

    /// Flushes the events recorded by the [`Recorder`] widget with the given tag.
    ///
    /// # Panics
    ///
    /// Panics if no widget with this tag can be found.
    #[track_caller]
    pub fn flush_records_of<W2: Widget>(&self, tag: WidgetTag<Recorder<W2>>) {
        self.get_widget(tag).inner().recording().clear();
    }

    /// Returns a [`WidgetRef`] to the [focused widget](masonry_core::doc::masonry_concepts#text-focus).
    pub fn focused_widget(&self) -> Option<WidgetRef<'_, dyn Widget>> {
        self.render_root
            .get_subwindow_root(0)
            .find_widget_by_id(self.render_root.focused_widget()?)
    }

    /// Returns the id of the [focused widget](masonry_core::doc::masonry_concepts#text-focus).
    pub fn focused_widget_id(&self) -> Option<WidgetId> {
        self.render_root.focused_widget()
    }

    /// Returns a [`WidgetRef`] to the widget which [captures pointer events](masonry_core::doc::masonry_concepts#pointer-capture).
    pub fn pointer_capture_target(&self) -> Option<WidgetRef<'_, dyn Widget>> {
        self.render_root
            .get_widget(self.render_root.pointer_capture_target()?)
    }

    /// Returns the id of the widget which [captures pointer events](masonry_core::doc::masonry_concepts#pointer-capture).
    // TODO - This is kinda redundant with the above
    pub fn pointer_capture_target_id(&self) -> Option<WidgetId> {
        self.render_root.pointer_capture_target()
    }

    /// Calls the provided visitor on every widget in the widget tree.
    pub fn inspect_widgets(&mut self, mut f: impl FnMut(WidgetRef<'_, dyn Widget>)) {
        fn inspect(
            widget: WidgetRef<'_, dyn Widget>,
            f: &mut impl FnMut(WidgetRef<'_, dyn Widget>),
        ) {
            f(widget);
            for child in widget.children() {
                inspect(child, f);
            }
        }

        inspect(self.render_root.get_subwindow_root(0), &mut f);
    }

    /// Returns a [`WidgetMut`] to the root widget.
    ///
    /// Because of how `WidgetMut` works, it can only be passed to a user-provided callback.
    pub fn edit_root_widget<R>(&mut self, f: impl FnOnce(WidgetMut<'_, W>) -> R) -> R {
        let ret = self.render_root.edit_main_subwindow(|mut root| {
            let root = root.downcast::<W>();
            f(root)
        });
        self.process_signals();
        ret
    }

    /// Returns a [`WidgetMut`] to a specific widget.
    ///
    /// Because of how `WidgetMut` works, it can only be passed to a user-provided callback.
    pub fn edit_widget_with_id<R>(
        &mut self,
        id: WidgetId,
        f: impl FnOnce(WidgetMut<'_, dyn Widget>) -> R,
    ) -> R {
        let ret = self.render_root.edit_widget(id, f);
        self.process_signals();
        ret
    }

    /// 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<R, W2: Widget + FromDynWidget + ?Sized>(
        &mut self,
        tag: WidgetTag<W2>,
        f: impl FnOnce(WidgetMut<'_, W2>) -> R,
    ) -> R {
        let ret = self.render_root.edit_widget_with_tag(tag, f);
        self.process_signals();
        ret
    }

    /// Pops the oldest [`ErasedAction`] emitted by the widget tree, downcasting it to `T`.
    ///
    /// # Panics
    ///
    /// If there is an action, but it is not of type `T`.
    #[track_caller]
    pub fn pop_action<T: AnyDebug>(&mut self) -> Option<(T, WidgetId)> {
        let (action, widget) = self.pop_action_erased()?;
        let action = action.downcast().unwrap_or_else(|action| {
            panic!(
                "Expected Action to be of type {}, but got a value of type {} ({action:?}).",
                std::any::type_name::<T>(),
                (*action).type_name()
            )
        });
        Some((*action, widget))
    }

    /// Pops the oldest [`ErasedAction`] emitted by the widget tree.
    pub fn pop_action_erased(&mut self) -> Option<(ErasedAction, WidgetId)> {
        self.action_queue.pop_front()
    }

    // TODO - Use in at least one test
    /// Pops the oldest unhandled [`TextEvent`] emitted by the widget tree.
    pub fn pop_root_text_event(&mut self) -> Option<TextEvent> {
        self.root_text_event_queue.pop_front()
    }

    /// Returns the app's current cursor icon.
    ///
    /// The cursor icon is the icon that would be displayed to indicate the mouse
    /// position in a visual environment.
    pub fn cursor_icon(&self) -> CursorIcon {
        self.render_root.cursor_icon()
    }

    /// Returns whether the app has an IME session in progress.
    ///
    /// This usually means that a widget which [accepts text input](Widget::accepts_text_input) is focused.
    pub fn has_ime_session(&self) -> bool {
        self.has_ime_session
    }

    /// Returns the rectangle of the IME session.
    ///
    /// This is usually the effective border-box rectangle of the focused widget.
    pub fn ime_rect(&self) -> (LogicalPosition<f64>, LogicalSize<f64>) {
        self.ime_rect
    }

    /// Returns the contents of the emulated clipboard.
    ///
    /// This is an empty string by default.
    pub fn clipboard_contents(&self) -> String {
        self.clipboard.clone()
    }

    /// Returns the size of the simulated window.
    pub fn window_size(&self) -> PhysicalSize<u32> {
        self.window_size
    }

    /// Returns the title of the simulated window.
    pub fn title(&self) -> String {
        self.title.clone()
    }

    // --- MARK: SNAPSHOT

    /// Renders the current widget tree to a pixmap, and writes it to a temporary PNG file.
    pub fn save_render_snapshot(&mut self) {
        let image = self.render();

        let mut buffer = Cursor::new(Vec::new());
        image.write_to(&mut buffer, ImageFormat::Png).unwrap();
        let image_data = buffer.into_inner();

        let id = std::time::SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_millis();
        let tmp_path = std::env::temp_dir().join(format!("masonry-{id:016}-screenshot.png"));

        std::fs::write(&tmp_path, image_data).unwrap();
        debug!("Screenshot saved to {}", tmp_path.display());
    }

    /// Method used by [`assert_render_snapshot`] and [`assert_failing_render_snapshot`]. Use these macros, not this method.
    ///
    /// Renders the current widget tree to a pixmap, and compares the pixmap against the
    /// snapshot stored in `<CRATE ROOT>/screenshots/<test_name>.png`.
    ///
    /// * `manifest_dir`: directory where `Cargo.toml` can be found.
    /// * `test_name`: arbitrary name; second argument of [`assert_render_snapshot`].
    /// * `expect_failure`: whether the snapshot is expected to fail to match.
    ///
    /// [`assert_render_snapshot`]: crate::assert_render_snapshot
    #[doc(hidden)]
    #[track_caller]
    pub fn check_render_snapshot(
        &mut self,
        manifest_dir: &str,
        test_name: &str,
        expect_failure: bool,
    ) {
        if std::env::var("SKIP_RENDER_TESTS").is_ok_and(|it| !it.is_empty()) {
            // We still redraw to get some coverage in the paint code.
            let _ = self.render_root.redraw();

            return;
        }
        let max_size = Some(usize::try_from(self.max_screenshot_size).unwrap());

        #[track_caller]
        fn save_image(image: &DynamicImage, path: &PathBuf, max_size: Option<usize>) {
            let mut buffer = Cursor::new(Vec::new());
            image.write_to(&mut buffer, ImageFormat::Png).unwrap();

            let image_data = buffer.into_inner();
            // Whenever we save a file, we optimise it.
            // This avoids cases where people copy the `new` file to the reference path, thus avoiding optimisation
            // (We could skip this for diff images, but that is so far off the hot path that it's not
            // worth a different code path for it.)
            let data =
                optimize_from_memory(image_data.as_slice(), &Options::from_preset(5)).unwrap();
            let saved_len = data.len();
            std::fs::write(path, data).unwrap();
            if let Some(max_size) = max_size
                && saved_len > max_size
            {
                panic!(
                    "New screenshot file ({saved_len} bytes) was larger than the supported file size ({max_size} bytes). \
                        Consider increasing `TestHarnessParams::max_screenshot_size` when creating the test harness.",
                );
            }
        }

        let new_image: DynamicImage = self.render().into();

        let screenshots_folder = PathBuf::from(manifest_dir).join("screenshots");
        std::fs::create_dir_all(&screenshots_folder).unwrap();

        let reference_path = screenshots_folder.join(format!("{test_name}.png"));
        let new_path = screenshots_folder.join(format!("{test_name}.new.png"));
        let diff_path = screenshots_folder.join(format!("{test_name}.diff.png"));

        let bless_test = std::env::var_os("MASONRY_TEST_BLESS").is_some_and(|it| !it.is_empty());

        let Ok(reference_file) = File::open(&reference_path) else {
            if bless_test && !expect_failure {
                let _ = std::fs::remove_file(&new_path);
                let _ = std::fs::remove_file(&diff_path);
                save_image(&new_image, &reference_path, max_size);
                return;
            }

            // Remove '<test_name>.new.png' file if it exists
            let _ = std::fs::remove_file(&new_path);
            save_image(&new_image, &new_path, max_size);
            panic!("Snapshot test '{test_name}' failed: No reference file");
        };
        let reference_size = reference_file.metadata().unwrap().len();

        let reference_file =
            ImageReader::with_format(BufReader::new(reference_file), ImageFormat::Png);

        let ref_image = reference_file.decode().unwrap().to_rgb8();

        if expect_failure {
            if get_image_diff(&ref_image, &new_image.to_rgb8()).is_some() {
                return;
            } else {
                panic!(
                    "Snapshot test '{test_name}' did not fail as expected: Images are identical"
                );
            }
        }

        if let Some(diff_image) = get_image_diff(&ref_image, &new_image.to_rgb8()) {
            if bless_test {
                let _ = std::fs::remove_file(&new_path);
                let _ = std::fs::remove_file(&diff_path);
                save_image(&new_image, &reference_path, max_size);
            } else {
                save_image(&new_image, &new_path, max_size);
                // Don't fail if the diff file is too big!
                save_image(&diff_image.into(), &diff_path, None);
                panic!("Snapshot test '{test_name}' failed: Images are different");
            }
        } else {
            // Remove the vestigial new and diff images
            let _ = std::fs::remove_file(&new_path);
            let _ = std::fs::remove_file(&diff_path);
            if reference_size > u64::from(self.max_screenshot_size) {
                panic!(
                    "Existing file ({reference_size}) was larger than the supported file size ({}). \
                    Consider increasing `TestHarnessParams::max_screenshot_size` when creating the test harness.",
                    self.max_screenshot_size
                );
            }
        }
    }
}

struct NoOpTreeChangeHandler;

impl accesskit_consumer::TreeChangeHandler for NoOpTreeChangeHandler {
    fn node_added(&mut self, _node: &accesskit_consumer::NodeRef<'_>) {}

    fn node_updated(
        &mut self,
        _old_node: &accesskit_consumer::NodeRef<'_>,
        _new_node: &accesskit_consumer::NodeRef<'_>,
    ) {
    }

    fn focus_moved(
        &mut self,
        _old_node: Option<&accesskit_consumer::NodeRef<'_>>,
        _new_node: Option<&accesskit_consumer::NodeRef<'_>>,
    ) {
    }

    fn node_removed(&mut self, _node: &accesskit_consumer::NodeRef<'_>) {}
}