masonry_winit 0.5.0

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

use std::collections::{HashMap, HashSet};
use std::fmt::Debug;
use std::sync::mpsc::Sender;
use std::sync::{Arc, mpsc};

use accesskit_winit::Adapter;
use copypasta::nop_clipboard::NopClipboardContext;
use copypasta::{ClipboardContext, ClipboardProvider};
use imaging_wgpu::{TextureRenderer, TextureViewTarget};
use masonry_core::app::{RenderRoot, RenderRootSignal, VisualLayerKind};
use masonry_core::core::keyboard::{Key, KeyState};
use masonry_core::core::{DefaultProperties, ErasedAction, TextEvent, WindowEvent};
use masonry_core::imaging::record::{Scene, replay_transformed};
use masonry_core::kurbo::{Affine, Rect};
use masonry_core::util::Instant;
use tracing::{info, info_span, trace};
use ui_events_winit::WindowEventTranslation;
use winit::application::ApplicationHandler;
use winit::dpi::PhysicalSize;
use winit::error::EventLoopError;
use winit::event::{
    DeviceEvent as WinitDeviceEvent, DeviceId, StartCause, WindowEvent as WinitWindowEvent,
};
use winit::event_loop::{ActiveEventLoop, ControlFlow, OwnedDisplayHandle};
use winit::window::{Window as WindowHandle, WindowId as HandleId};

use crate::app::{
    AppDriver, DriverCtx, WgpuContext, WgpuLimits, masonry_resize_direction_to_winit,
    winit_ime_to_masonry,
};
use crate::vello_util::{DeviceHandle, RenderContext, RenderSurface};
use crate::window::{NewWindow, Window, WindowId};

type DynRenderer = Box<dyn TextureRenderer<TextureTarget = TextureViewTarget>>;

/// The state of the Masonry application.
///
/// If you run Masonry from an external Winit event loop, create a
/// `MasonryState` via [`MasonryState::new`] and forward events to it via the appropriate method (e.g.,
/// calling [`handle_window_event`](MasonryState::handle_window_event) in [`window_event`](ApplicationHandler::window_event)).
pub struct MasonryState {
    /// The event loop is suspended when the app is e.g. in the background on Android.
    /// We aren't allowed to have any `Surface`s, and we also don't expect to receive any events.
    /// See [`ApplicationHandler::suspended()`] for details.
    is_suspended: bool,
    render_cx: RenderContext,
    device: Option<DeviceHandle>,
    // TODO - Merge with DeviceHandle?
    renderer: Option<DynRenderer>,
    renderer_factory: Box<dyn Fn(DeviceHandle) -> DynRenderer>,
    // TODO: Winit doesn't seem to let us create these proxies from within the loop
    // The reasons for this are unclear
    event_loop_proxy: EventLoopProxy,
    #[cfg(feature = "tracy")]
    frame: Option<tracing_tracy::client::Frame>,

    window_id_to_handle_id: HashMap<WindowId, HandleId>,

    surfaces: HashMap<HandleId, RenderSurface>,
    windows: HashMap<HandleId, Window>,
    /// On Metal, we need to track the state of resize requests to avoid jitter.
    #[cfg(target_os = "macos")]
    resized_window: Option<HandleId>,

    clipboard_cx: Box<dyn ClipboardProvider>,

    // Is `Some` if the most recently displayed frame was an animation frame.
    last_anim: Option<Instant>,
    signal_receiver: mpsc::Receiver<(WindowId, RenderRootSignal)>,

    signal_sender: Sender<(WindowId, RenderRootSignal)>,
    default_properties: Arc<DefaultProperties>,
    pub(crate) exit: bool,
    /// Windows that are scheduled to be created in the next resumed event.
    new_windows: Vec<NewWindow>,
    need_first_frame: Vec<HandleId>,
}

// TODO - Merge into MasonryState?
struct MainState {
    masonry_state: MasonryState,
    app_driver: Box<dyn AppDriver>,
}

/// The type of the event loop used by Masonry.
///
/// This *will* be changed to allow custom event types, but is implemented this way for expedience
pub type EventLoop = winit::event_loop::EventLoop<MasonryUserEvent>;
/// The type of the event loop builder used by Masonry.
///
/// This *will* be changed to allow custom event types, but is implemented this way for expedience
pub type EventLoopBuilder = winit::event_loop::EventLoopBuilder<MasonryUserEvent>;

/// A proxy used to send events to the event loop
pub type EventLoopProxy = winit::event_loop::EventLoopProxy<MasonryUserEvent>;

/// The custom event type that we inject into winit's [`EventLoop`](winit::event_loop::EventLoop).
///
/// This represents the types that can be emitted during the event loop, but aren't emitted
/// by winit.
#[derive(Debug)]
pub enum MasonryUserEvent {
    /// An accessibility API emitted an event.
    ///
    /// This is how [`accesskit_winit`] routes its events to us.
    AccessKit(HandleId, accesskit_winit::WindowEvent),
    /// An action was emitted by something other than the widget tree.
    ///
    /// Higher-level GUI frameworks may send these to winit from background threads to wake up the event loop.
    AsyncAction(WindowId, ErasedAction),
}

impl From<accesskit_winit::Event> for MasonryUserEvent {
    fn from(event: accesskit_winit::Event) -> Self {
        Self::AccessKit(event.window_id, event.window_event)
    }
}

// --- MARK: RUN

/// Runs the app to completion.
///
/// This is usually one of the last functions called in your main function.
#[cfg(feature = "imaging_vello")]
pub fn run(
    new_windows: Vec<NewWindow>,
    app_driver: impl AppDriver + 'static,
    default_properties: DefaultProperties,
) -> Result<(), EventLoopError> {
    let event_loop = EventLoop::with_user_event().build()?;

    run_with::<imaging_vello::VelloRenderer, _>(
        event_loop,
        new_windows,
        app_driver,
        default_properties,
    )
}

/// Runs the app with the provided event loop to completion.
pub fn run_with<
    Renderer: TextureRenderer<TextureTarget = TextureViewTarget> + 'static,
    Driver: AppDriver + 'static,
>(
    // This is passed in mostly to allow configuring the Android app
    event_loop: EventLoop,
    new_windows: Vec<NewWindow>,
    app_driver: Driver,
    default_properties: DefaultProperties,
) -> Result<(), EventLoopError> {
    // 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.
    // By now, we're about to take control of the event loop. The user is unlikely
    // to try to set their own subscriber once the event loop has started.
    let _ = masonry_core::app::try_init_tracing();

    let mut main_state = MainState {
        masonry_state: MasonryState::new::<Renderer>(
            event_loop.create_proxy(),
            event_loop.owned_display_handle(),
            new_windows,
            default_properties,
        ),
        app_driver: Box::new(app_driver),
    };

    event_loop.run_app(&mut main_state)
}

impl ApplicationHandler<MasonryUserEvent> for MainState {
    fn resumed(&mut self, event_loop: &ActiveEventLoop) {
        self.masonry_state
            .handle_resumed(event_loop, &mut *self.app_driver);
    }

    fn suspended(&mut self, event_loop: &ActiveEventLoop) {
        self.masonry_state.handle_suspended(event_loop);
    }

    fn window_event(
        &mut self,
        event_loop: &ActiveEventLoop,
        handle_id: HandleId,
        event: WinitWindowEvent,
    ) {
        self.masonry_state.handle_window_event(
            event_loop,
            handle_id,
            event,
            self.app_driver.as_mut(),
        );
    }

    fn device_event(
        &mut self,
        event_loop: &ActiveEventLoop,
        device_id: DeviceId,
        event: WinitDeviceEvent,
    ) {
        self.masonry_state.handle_device_event(
            event_loop,
            device_id,
            event,
            self.app_driver.as_mut(),
        );
    }

    fn user_event(&mut self, event_loop: &ActiveEventLoop, event: MasonryUserEvent) {
        self.masonry_state
            .handle_user_event(event_loop, event, self.app_driver.as_mut());
    }

    fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) {
        self.masonry_state.handle_about_to_wait(event_loop);
        let wakeup = self.masonry_state.next_timer_wakeup();
        event_loop.set_control_flow(wakeup.map_or(ControlFlow::Wait, ControlFlow::WaitUntil));
    }

    fn new_events(&mut self, event_loop: &ActiveEventLoop, cause: StartCause) {
        self.masonry_state
            .handle_new_events(event_loop, cause, self.app_driver.as_mut());
    }

    fn exiting(&mut self, event_loop: &ActiveEventLoop) {
        self.masonry_state.handle_exiting(event_loop);
    }

    fn memory_warning(&mut self, event_loop: &ActiveEventLoop) {
        self.masonry_state.handle_memory_warning(event_loop);
    }
}

impl Debug for MasonryState {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("MasonryState")
            .field("is_suspended", &self.is_suspended)
            .field("event_loop_proxy", &self.event_loop_proxy)
            .field("window_id_to_handle_id", &self.window_id_to_handle_id)
            .field("surfaces", &self.surfaces)
            .field("windows", &self.windows)
            .field("last_anim", &self.last_anim)
            .field("signal_receiver", &self.signal_receiver)
            .field("signal_sender", &self.signal_sender)
            .field("default_properties", &self.default_properties)
            .field("exit", &self.exit)
            .field("new_windows", &self.new_windows)
            .field("need_first_frame", &self.need_first_frame)
            .finish_non_exhaustive()
    }
}

// --- MARK: MASONRY_STATE

// Note: All ApplicationHandler::foobar() trait methods should have an
// equivalent MasonryState::handle_foobar() method.

impl MasonryState {
    /// Creates the Masonry application's composition root.
    ///
    /// - `event_loop_proxy`: a queue provided by [`EventLoop::create_proxy`](winit::event_loop::EventLoop::create_proxy) to send custom events (mostly accessibility) to your event loop.
    /// - `display`: the display of your event loop, provided by [`EventLoop::owned_display_handle`](winit::event_loop::EventLoop::owned_display_handle).
    /// - `new_windows`: the initial list of windows.
    /// - `default_properties`: the default properties for all the widgets of the app.
    pub fn new<Renderer: TextureRenderer<TextureTarget = TextureViewTarget> + 'static>(
        event_loop_proxy: EventLoopProxy,
        display: OwnedDisplayHandle,
        new_windows: Vec<NewWindow>,
        default_properties: DefaultProperties,
    ) -> Self {
        // TODO - Include TextureRender typename in trace.
        tracing::debug!("Selected Masonry Winit render backend");

        let render_cx = RenderContext::new(display);

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

        let clipboard_cx =
            ClipboardContext::new().map(|cx| -> Box<dyn ClipboardProvider> { Box::new(cx) });
        let clipboard_cx = if cfg!(target_os = "linux") {
            // If we're running on Linux, we might fail to get the clipboard context because
            // we're using Wayland, so we fall back to NopClipboardContext to be safe.
            clipboard_cx.unwrap_or_else(|_| Box::new(NopClipboardContext))
        } else {
            clipboard_cx.unwrap()
        };

        let renderer_factory = |handle: DeviceHandle| -> DynRenderer {
            Box::new(Renderer::create(handle.adapter, handle.device, handle.queue).unwrap())
        };
        let renderer_factory = Box::new(renderer_factory);

        Self {
            is_suspended: true,
            render_cx,
            device: None,
            renderer: None,
            renderer_factory,
            event_loop_proxy,
            #[cfg(feature = "tracy")]
            frame: None,
            signal_receiver,

            last_anim: None,
            window_id_to_handle_id: HashMap::new(),
            windows: HashMap::new(),
            surfaces: HashMap::new(),
            #[cfg(target_os = "macos")]
            resized_window: None,

            clipboard_cx,

            signal_sender,
            default_properties: Arc::new(default_properties),
            exit: false,
            new_windows,
            need_first_frame: Vec::new(),
        }
    }

    /// Configure how Masonry requests the WGPU device (features and limits).
    ///
    /// This must be called before the first surface/device is created (i.e. before the first
    /// redraw). A good place is [`AppDriver::on_start`].
    ///
    /// `features` is best-effort: Masonry intersects it with `adapter.features()`, so unsupported
    /// feature bits are ignored.
    ///
    /// This method will return `false` if it was called too late and a device had already been
    /// created.
    pub fn set_wgpu_device_options(
        &mut self,
        features: wgpu::Features,
        limits: WgpuLimits,
    ) -> bool {
        if self.device.is_some() {
            return false;
        }
        self.render_cx.set_wgpu_device_options(features, limits);
        true
    }

    /// Add extra WGPU features to request when creating the device.
    ///
    /// This must be called before the first surface/device is created (i.e. before the first
    /// redraw). A good place is [`AppDriver::on_start`].
    ///
    /// This method will return `false` if it was called too late and a device had already been
    /// created.
    pub fn add_wgpu_features(&mut self, features: wgpu::Features) -> bool {
        if self.device.is_some() {
            return false;
        }
        self.render_cx.add_wgpu_features(features);
        true
    }

    /// Configure the WGPU limits strategy used when requesting the device.
    ///
    /// This must be called before the first surface/device is created (i.e. before the first
    /// redraw). A good place is [`AppDriver::on_start`].
    ///
    /// This method will return `false` if it was called too late and a device had already been
    /// created.
    pub fn set_wgpu_limits(&mut self, limits: WgpuLimits) -> bool {
        if self.device.is_some() {
            return false;
        }
        self.render_cx.set_wgpu_limits(limits);
        true
    }

    // --- MARK: RESUMED
    /// Delegate method for [`ApplicationHandler::resumed()`].
    pub fn handle_resumed(&mut self, event_loop: &ActiveEventLoop, app_driver: &mut dyn AppDriver) {
        if !self.is_suspended {
            // Short-circuiting since we have already
            // handled the resumed event before this.
            return;
        }

        self.is_suspended = false;

        // Surfaces for existing windows will be recreated on-demand in the redraw method

        // Create new windows.
        if !self.new_windows.is_empty() {
            for new_window in std::mem::take(&mut self.new_windows) {
                self.create_window(event_loop, new_window);
            }

            // TODO: This is wrong in the case where the driver tries to create a window whilst suspended
            // The on_start would be called twice.
            app_driver.on_start(self);

            // If we have at least one window and we haven't initialized
            // our GPU handles, we initialize them now.
            if let Some((_, window)) = self.windows.iter().next()
                && self.device.is_none()
            {
                let handle = window.handle.clone();
                self.init_device(handle, app_driver);
            }
        }

        self.process_signals(event_loop, app_driver);
    }

    // --- MARK: SUSPENDED
    /// Delegate method for [`ApplicationHandler::suspended()`].
    pub fn handle_suspended(&mut self, _event_loop: &ActiveEventLoop) {
        if self.is_suspended {
            // Short-circuiting since we have already
            // handled the suspended event before this.
            return;
        }

        self.is_suspended = true;

        // All surfaces needs to be cleared when suspended.
        // They will be recreated when resumed.
        self.surfaces.clear();
    }

    fn init_device(&mut self, window_handle: Arc<WindowHandle>, app_driver: &mut dyn AppDriver) {
        assert!(self.device.is_none(), "device already initialized");

        let device_handle = init_device(&mut self.render_cx, window_handle);

        let wgpu = WgpuContext {
            instance: &self.render_cx.instance,
            adapter: &device_handle.adapter,
            device: &device_handle.device,
            queue: &device_handle.queue,
        };
        app_driver.on_wgpu_ready(&wgpu);

        self.renderer = Some((self.renderer_factory)(device_handle.clone()));
        self.device = Some(device_handle);
    }

    pub(crate) fn create_window(&mut self, event_loop: &ActiveEventLoop, new_window: NewWindow) {
        if self.window_id_to_handle_id.contains_key(&new_window.id) {
            panic!(
                "attempted to create a window with id {:?} but a window with that id already exists",
                new_window.id
            );
        }

        if self.is_suspended {
            // Wait until resumed before creating the windows.
            self.new_windows.push(new_window);

            return;
        }

        // TODO: move this check to modification of base_color once winit exposes window transparency state
        if !new_window.attributes.transparent && new_window.base_color.components[3] != 1. {
            tracing::warn!(
                window_id = ?new_window.id,
                "New window with non-opaque base color doesn't support transparency - \
                you should call `.with_transparent(true)` on the new window's `WindowAttributes`."
            );
        }

        let visible = new_window.attributes.visible;
        // We always create the window as invisible so that we can
        // render the first frame before showing it to avoid flashing.
        let handle = event_loop
            .create_window(new_window.attributes.with_visible(false))
            .unwrap();
        if visible {
            // We defer the rendering of the first frame to the handle_signals method because
            // we want to handle any signals caused by the initial layout before we render.
            self.need_first_frame.push(handle.id());
        }

        let adapter =
            Adapter::with_event_loop_proxy(event_loop, &handle, self.event_loop_proxy.clone());
        let handle = Arc::new(handle);

        let handle_id = handle.id();
        let scale_factor = handle.scale_factor();

        // https://github.com/rust-windowing/winit/issues/2308
        #[cfg(target_os = "ios")]
        let size = handle.outer_size();
        #[cfg(not(target_os = "ios"))]
        let size = handle.inner_size();

        let window = Window::new(
            new_window.id,
            handle,
            adapter,
            new_window.root_widget,
            self.signal_sender.clone(),
            self.default_properties.clone(),
            new_window.base_color,
            size,
            scale_factor,
        );

        tracing::debug!(window_id = window.id.trace(), handle=?handle_id, "creating window");
        self.window_id_to_handle_id.insert(window.id, handle_id);
        self.windows.insert(handle_id, window);
    }

    pub(crate) fn close_window(&mut self, window_id: WindowId) {
        tracing::debug!(window_id = window_id.trace(), "closing window");
        let window_id = self
            .window_id_to_handle_id
            .remove(&window_id)
            .unwrap_or_else(|| panic!("could not find window for id {window_id:?}"));
        self.surfaces.remove(&window_id);
        let window = self.windows.remove(&window_id).unwrap();

        // HACK: When we exit, on some systems (known to happen with Wayland on KDE),
        // the IME state gets preserved until the app next opens. We work around this by force-deleting
        // the IME state just before exiting.
        window.handle.set_ime_allowed(false);
    }

    /// Returns the earliest wakeup needed by a pending widget timer.
    ///
    /// Hosts with their own event loop can combine this with their other wakeup
    /// deadlines when choosing control flow in `about_to_wait`.
    pub fn next_timer_wakeup(&self) -> Option<Instant> {
        self.windows
            .values()
            .filter_map(|window| window.render_root.next_timer_deadline())
            .min()
    }

    fn drain_due_timers(&mut self, event_loop: &ActiveEventLoop, app_driver: &mut dyn AppDriver) {
        for window in self.windows.values_mut() {
            window.render_root.handle_timers();
        }

        self.process_signals(event_loop, app_driver);
    }

    // --- MARK: REDRAW
    fn redraw_window(&mut self, handle_id: HandleId) {
        let Some(device) = self.device.as_ref() else {
            tracing::error!("Called MasonryState::redraw before initializing device");
            return;
        };
        let Some(renderer) = self.renderer.as_mut() else {
            tracing::error!("Called MasonryState::redraw before initializing renderer");
            return;
        };

        let _span = info_span!("redraw");

        let window = self.windows.get_mut(&handle_id).unwrap();
        let size = window.render_root.size();
        if size.width == 0 || size.height == 0 {
            // Surface can't have a dimension of zero, remove the stale surface to save memory.
            self.surfaces.remove(&handle_id);
            return;
        }

        // Get the existing surface or create a new one
        let surface = if let Some(surface) = self.surfaces.get_mut(&handle_id) {
            #[cfg(target_os = "macos")]
            if self.resized_window == Some(handle_id) {
                self.render_cx
                    .on_window_resize_state_change(device, surface, true);
            }

            // The window might have been resized, make sure the surface dimensions match.
            if surface.config.width != size.width || surface.config.height != size.height {
                self.render_cx
                    .resize_surface(device, surface, size.width, size.height);
            }
            surface
        } else {
            let surface = create_surface(&mut self.render_cx, device, window.handle.clone(), size);
            self.surfaces.insert(handle_id, surface);
            self.surfaces.get_mut(&handle_id).unwrap()
        };

        let now = Instant::now();
        // TODO: this calculation uses wall-clock time of the paint call, which
        // potentially has jitter.
        //
        // See https://github.com/linebender/druid/issues/85 for discussion.
        let last = self.last_anim.take();
        let elapsed = last.map(|t| now.duration_since(t)).unwrap_or_default();

        window
            .render_root
            .handle_window_event(WindowEvent::AnimFrame(elapsed));

        // If this animation will continue, store the time.
        // If a new animation starts, then it will have zero reported elapsed time.
        let animation_continues = window.render_root.needs_anim();
        self.last_anim = animation_continues.then_some(now);

        #[cfg(target_os = "macos")]
        if self.resized_window == Some(handle_id) {
            self.render_cx
                .on_window_resize_state_change(device, surface, true);
        }

        let (visual_layers, tree_update) = window.render_root.redraw();
        let overlays: Vec<_> = visual_layers
            .overlay_layers()
            .map(|layer| {
                let VisualLayerKind::Scene(scene) = &layer.kind else {
                    unreachable!("overlay_layers only returns scene layers");
                };
                (scene, layer.transform)
            })
            .collect();
        let size = window.render_root.size();
        let root_layer = visual_layers
            .root_layer()
            .expect("paint should always produce a root layer");
        let VisualLayerKind::Scene(root_scene) = &root_layer.kind else {
            unreachable!("root_layer always returns a scene layer");
        };

        let mut composed = Scene::new();
        {
            let mut painter = imaging::Painter::new(&mut composed);
            painter.fill_rect(
                Rect::new(0.0, 0.0, f64::from(size.width), f64::from(size.height)),
                window.base_color,
            );

            let scale = Affine::scale(window.handle.scale_factor());
            replay_transformed(root_scene, &mut composed, scale);
            for (scene, transform) in &overlays {
                replay_transformed(scene, &mut composed, scale * *transform);
            }
        }

        Self::render(
            device,
            surface,
            window,
            composed,
            &self.render_cx,
            renderer,
            size.width,
            size.height,
        );
        #[cfg(feature = "tracy")]
        drop(self.frame.take());
        if let Some(tree_update) = tree_update {
            window.accesskit_adapter.update_if_active(|| tree_update);
        }
    }

    // --- MARK: RENDER
    fn render(
        device_handle: &DeviceHandle,
        surface: &mut RenderSurface,
        window: &mut Window,
        scene: Scene,
        render_cx: &RenderContext,
        renderer: &mut DynRenderer,
        width: u32,
        height: u32,
    ) {
        let device = &device_handle.device;
        let queue = &device_handle.queue;
        let Some(surface_texture) =
            Self::acquire_surface_texture(surface, window, render_cx, device_handle)
        else {
            return;
        };
        let target = TextureViewTarget::new(&surface.target_view, width, height);

        let _render_span = tracing::info_span!("Rendering Masonry window").entered();
        let mut scene = scene;
        if let Err(err) = renderer.render_source_into_texture(&mut scene, target) {
            tracing::error!("Couldn't render Masonry content into target texture: {err}");
            return;
        }
        Self::present_surface(surface, surface_texture, &window.handle, device, queue);
    }

    fn acquire_surface_texture(
        surface: &mut RenderSurface,
        window: &Window,
        render_cx: &RenderContext,
        device_handle: &DeviceHandle,
    ) -> Option<wgpu::SurfaceTexture> {
        use wgpu::CurrentSurfaceTexture;

        let mut reconfigured = false;
        loop {
            match surface.surface.get_current_texture() {
                // TODO: in case of `Suboptimal`, wgpu recommends reconfiguring the surface. We
                // could consider adding a `RenderSurface::needs_reconfigure` flag, set it in
                // case of `Suboptimal`, and reconfigure before the next acquire.
                CurrentSurfaceTexture::Success(texture)
                | CurrentSurfaceTexture::Suboptimal(texture) => return Some(texture),
                CurrentSurfaceTexture::Outdated if !reconfigured => {
                    let size = window.handle.inner_size();
                    render_cx.resize_surface(device_handle, surface, size.width, size.height);
                    reconfigured = true;
                }
                // wgpu recommends skipping the frame in these cases.
                reason @ (CurrentSurfaceTexture::Timeout | CurrentSurfaceTexture::Occluded) => {
                    tracing::debug!(
                        "Skipping frame, swap chain texture not available: '{reason:?}'"
                    );
                    return None;
                }
                other if reconfigured => {
                    // This is a common occurrence on X11 and Xwayland with NVIDIA drivers
                    // when opening and resizing the window.
                    tracing::error!(
                        "Couldn't get swap chain texture after configuring. Cause: '{other:?}'"
                    );
                    return None;
                }
                other => {
                    tracing::error!(
                        "Couldn't get swap chain texture, operation unrecoverable: {other:?}"
                    );
                    return None;
                }
            }
        }
    }

    fn present_surface(
        surface: &RenderSurface,
        surface_texture: wgpu::SurfaceTexture,
        window: &WindowHandle,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
    ) {
        // Copy the new surface content to the surface.
        let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
            label: Some("Surface Blit"),
        });
        surface.blitter.copy(
            device,
            &mut encoder,
            &surface.target_view,
            &surface_texture
                .texture
                .create_view(&wgpu::TextureViewDescriptor::default()),
        );
        queue.submit([encoder.finish()]);
        window.pre_present_notify();
        queue.present(surface_texture);
        {
            let _render_poll_span =
                tracing::info_span!("Waiting for GPU to finish rendering").entered();
            device.poll(wgpu::PollType::wait_indefinitely()).unwrap();
        }
    }

    // --- MARK: WINDOW_EVENT
    /// Delegate method for [`ApplicationHandler::window_event()`].
    pub fn handle_window_event(
        &mut self,
        event_loop: &ActiveEventLoop,
        handle_id: HandleId,
        event: WinitWindowEvent,
        app_driver: &mut dyn AppDriver,
    ) {
        if self.is_suspended {
            tracing::warn!(
                ?event,
                "Got window event whilst suspended or before window created"
            );
            return;
        };

        let Some(window) = self.windows.get_mut(&handle_id) else {
            tracing::warn!(
                ?event,
                "Got window event for unknown window {:?}",
                handle_id
            );
            return;
        };

        #[allow(unused_variables, reason = "Used in MacOS only")]
        let Some(device) = self.device.as_ref() else {
            tracing::error!("Called MasonryState::handle_window_event before initializing device");
            return;
        };

        let _span = info_span!("window_event", window_id = window.id.trace()).entered();
        #[cfg(feature = "tracy")]
        if self.frame.is_none() {
            self.frame = Some(tracing_tracy::client::non_continuous_frame!("Masonry"));
        }
        window
            .accesskit_adapter
            .process_event(&window.handle, &event);

        if !matches!(
            event,
            WinitWindowEvent::KeyboardInput {
                is_synthetic: true,
                ..
            }
        ) && let Some(wet) = window
            .event_reducer
            .reduce(window.handle.scale_factor(), &event)
        {
            match wet {
                WindowEventTranslation::Keyboard(k) => {
                    // TODO - Detect in Masonry code instead
                    let action_mod = if cfg!(target_os = "macos") {
                        k.modifiers.meta()
                    } else {
                        k.modifiers.ctrl()
                    };
                    if let Key::Character(c) = &k.key
                        && c.as_str().eq_ignore_ascii_case("v")
                        && action_mod
                        && k.state == KeyState::Down
                    {
                        match self.clipboard_cx.get_contents() {
                            Ok(text) => {
                                window
                                    .render_root
                                    .handle_text_event(TextEvent::ClipboardPaste(text));
                            }
                            Err(error) => {
                                tracing::warn!(?error, "Unable to read clipboard contents");
                            }
                        }
                    } else {
                        window.render_root.handle_text_event(TextEvent::Keyboard(k));
                    }
                }
                WindowEventTranslation::Pointer(p) => {
                    window.render_root.handle_pointer_event(p);
                }
            }
        }

        // On macOS, interactive resizing needs special presentation behavior on Metal to avoid
        // visible jitter.
        #[cfg(target_os = "macos")]
        match event {
            WinitWindowEvent::Resized(_)
            | WinitWindowEvent::RedrawRequested
            | WinitWindowEvent::Moved(_) => {}
            _ => {
                if let Some(surface) = self
                    .resized_window
                    .take()
                    .and_then(|id| self.surfaces.get_mut(&id))
                {
                    self.render_cx
                        .on_window_resize_state_change(device, surface, false);
                }
            }
        }

        match event {
            WinitWindowEvent::ScaleFactorChanged { scale_factor, .. } => {
                window
                    .render_root
                    .handle_window_event(WindowEvent::Rescale(scale_factor));
            }
            WinitWindowEvent::RedrawRequested => {
                self.redraw_window(handle_id);
            }
            WinitWindowEvent::CloseRequested => {
                app_driver.on_close_requested(window.id, &mut DriverCtx::new(self, event_loop));
            }
            WinitWindowEvent::Resized(size) => {
                #[cfg(target_os = "macos")]
                {
                    self.resized_window = Some(handle_id);
                    if let Some(surface) = self.surfaces.get_mut(&handle_id) {
                        self.render_cx
                            .on_window_resize_state_change(device, surface, true);
                    }
                }

                window
                    .render_root
                    .handle_window_event(WindowEvent::Resize(size));
            }
            WinitWindowEvent::Ime(ime) => {
                let ime = winit_ime_to_masonry(ime);
                window.render_root.handle_text_event(TextEvent::Ime(ime));
            }
            WinitWindowEvent::Focused(new_focus) => {
                window
                    .render_root
                    .handle_text_event(TextEvent::WindowFocusChange(new_focus));
            }
            _ => (),
        }

        self.process_signals(event_loop, app_driver);
        if self.exit {
            event_loop.exit();
        }
    }

    // --- MARK: DEVICE_EVENT
    /// Delegate method for [`ApplicationHandler::device_event()`].
    pub fn handle_device_event(
        &mut self,
        _: &ActiveEventLoop,
        _: DeviceId,
        _: WinitDeviceEvent,
        _: &mut dyn AppDriver,
    ) {
    }

    // --- MARK: USER_EVENT
    /// Delegate method for [`ApplicationHandler::user_event()`].
    pub fn handle_user_event(
        &mut self,
        event_loop: &ActiveEventLoop,
        event: MasonryUserEvent,
        app_driver: &mut dyn AppDriver,
    ) {
        let window = match &event {
            MasonryUserEvent::AccessKit(handle_id, ..) => {
                let Some(state) = self.windows.get_mut(handle_id) else {
                    tracing::warn!(handle = ?handle_id, "Got accesskit user event for unknown window");
                    return;
                };
                state
            }
            MasonryUserEvent::AsyncAction(window_id, ..) => {
                let Some(window_id) = self.window_id_to_handle_id.get(window_id) else {
                    tracing::warn!(id = ?window_id, "Got action user event for unknown window");
                    return;
                };
                self.windows.get_mut(window_id).unwrap()
            }
        };
        match event {
            MasonryUserEvent::AccessKit(_, event) => {
                match event {
                    // Note that this event can be called at any time, even multiple times if
                    // the user restarts their screen reader.
                    accesskit_winit::WindowEvent::InitialTreeRequested => {
                        window
                            .render_root
                            .handle_window_event(WindowEvent::EnableAccessTree);
                    }
                    accesskit_winit::WindowEvent::ActionRequested(action_request) => {
                        window.render_root.handle_access_event(action_request);
                    }
                    accesskit_winit::WindowEvent::AccessibilityDeactivated => {
                        window
                            .render_root
                            .handle_window_event(WindowEvent::DisableAccessTree);
                    }
                }
            }
            MasonryUserEvent::AsyncAction(_, action) => {
                app_driver.on_async_action(
                    window.id,
                    &mut DriverCtx::new(self, event_loop),
                    action,
                );
            }
        }

        self.process_signals(event_loop, app_driver);
    }

    // --- MARK: OTHER WINIT HANDLERS
    /// Delegate method for [`ApplicationHandler::about_to_wait()`].
    ///
    /// Hosts can use [`Self::next_timer_wakeup`] to include widget timers in their
    /// event loop's wakeup policy.
    pub fn handle_about_to_wait(&mut self, _: &ActiveEventLoop) {}

    /// Delegate method for [`ApplicationHandler::new_events()`].
    pub fn handle_new_events(
        &mut self,
        event_loop: &ActiveEventLoop,
        _: StartCause,
        app_driver: &mut dyn AppDriver,
    ) {
        self.drain_due_timers(event_loop, app_driver);
    }

    /// Delegate method for [`ApplicationHandler::exiting()`].
    pub fn handle_exiting(&mut self, _: &ActiveEventLoop) {}

    /// Delegate method for [`ApplicationHandler::memory_warning()`].
    pub fn handle_memory_warning(&mut self, _: &ActiveEventLoop) {}

    // --- MARK: SIGNALS
    fn process_signals(&mut self, event_loop: &ActiveEventLoop, app_driver: &mut dyn AppDriver) {
        if self.is_suspended {
            tracing::warn!("Tried to handle a signal whilst suspended");
            return;
        }

        let mut need_redraw = HashSet::<HandleId>::new();

        loop {
            let Some((window_id, signal)) = self.signal_receiver.try_iter().next() else {
                break;
            };

            let Some(handle_id) = self.window_id_to_handle_id.get(&window_id) else {
                tracing::warn!(id = ?window_id, signal = ?signal, "Got a signal for an unknown window");
                continue;
            };

            let window = self.windows.get_mut(handle_id).unwrap();
            let handle = &window.handle;

            match signal {
                RenderRootSignal::Action(action, widget_id) => {
                    let window_id = window.id;
                    trace!(
                        "Action {:?} on widget {:?}",
                        (*action).type_name(),
                        widget_id
                    );
                    app_driver.on_action(
                        window_id,
                        &mut DriverCtx::new(self, event_loop),
                        widget_id,
                        action,
                    );
                }
                RenderRootSignal::StartIme => {
                    handle.set_ime_allowed(true);
                }
                RenderRootSignal::EndIme => {
                    handle.set_ime_allowed(false);
                }
                RenderRootSignal::ImeMoved(position, size) => {
                    handle.set_ime_cursor_area(position, size);
                }
                RenderRootSignal::ClipboardStore(text) => {
                    self.clipboard_cx.set_contents(text).unwrap();
                }
                RenderRootSignal::UnhandledTextEvent(text_event) => {
                    app_driver.on_root_text_event(
                        window_id,
                        &mut DriverCtx::new(self, event_loop),
                        text_event,
                    );
                }
                RenderRootSignal::RequestRedraw => {
                    need_redraw.insert(*handle_id);
                }
                RenderRootSignal::RequestAnimFrame => {
                    // TODO
                    need_redraw.insert(*handle_id);
                }
                RenderRootSignal::TakeFocus => {
                    handle.focus_window();
                }
                RenderRootSignal::SetCursor(cursor) => {
                    handle.set_cursor(cursor);
                }
                RenderRootSignal::SetSize(size) => {
                    // TODO - Handle return value?
                    let _ = handle.request_inner_size(size);
                }
                RenderRootSignal::SetTitle(title) => {
                    handle.set_title(&title);
                }
                RenderRootSignal::DragWindow => {
                    // TODO - Handle return value?
                    let _ = handle.drag_window();
                }
                RenderRootSignal::DragResizeWindow(direction) => {
                    // TODO - Handle return value?
                    let direction = masonry_resize_direction_to_winit(direction);
                    let _ = handle.drag_resize_window(direction);
                }
                RenderRootSignal::ToggleMaximized => {
                    handle.set_maximized(!handle.is_maximized());
                }
                RenderRootSignal::Minimize => {
                    handle.set_minimized(true);
                }
                RenderRootSignal::Exit => {
                    event_loop.exit();
                }
                RenderRootSignal::ShowWindowMenu(position) => {
                    handle.show_window_menu(position);
                }
                RenderRootSignal::WidgetSelectedInInspector(widget_id) => {
                    let Some(widget) = window.render_root.get_widget(widget_id) else {
                        return;
                    };
                    let widget_name = widget.short_type_name();
                    let display_name = if let Some(debug_text) = widget.get_debug_text() {
                        format!("{widget_name}<{debug_text}>")
                    } else {
                        widget_name.into()
                    };
                    info!("Widget selected in inspector: {widget_id} - {display_name}");
                }
                RenderRootSignal::NewSubwindow(id, _type, root, pos) => {
                    window.render_root.add_subwindow(id, root, pos);
                }
                RenderRootSignal::RemoveSubwindow(id) => {
                    window.render_root.remove_subwindow(id);
                }
                RenderRootSignal::RepositionSubwindow(id, new_pos) => {
                    window.render_root.reposition_subwindow(id, new_pos);
                }
            }
        }

        // If an app creates a visible window, we firstly create it as invisible
        // and then render the first frame before making it visible to avoid flashing.
        for handle_id in std::mem::take(&mut self.need_first_frame) {
            self.redraw_window(handle_id);
            let window = self.windows.get_mut(&handle_id).unwrap();
            window.handle.set_visible(true);
        }

        // If we're processing a lot of actions, we may have a lot of pending redraws.
        // We batch them up to avoid redundant requests.
        for handle_id in need_redraw {
            let window = self.windows.get(&handle_id).unwrap();
            window.handle.request_redraw();
        }
    }

    fn get_handle_id(&self, window_id: WindowId) -> HandleId {
        *self
            .window_id_to_handle_id
            .get(&window_id)
            .unwrap_or_else(|| panic!("could not find window for id {window_id:?}"))
    }

    pub(crate) fn window_mut(&mut self, window_id: WindowId) -> &mut Window {
        let handle_id = self.get_handle_id(window_id);
        self.windows.get_mut(&handle_id).unwrap()
    }

    /// Returns true if app is currently suspended.
    ///
    /// See [`ApplicationHandler::suspended()`] for details.
    ///
    /// Short version: "suspended" is a notion that mostly applies to web and mobile apps,
    /// usually when the app is about to be put in cache.
    /// Suspended apps have no surfaces and receive no events.
    pub fn is_suspended(&self) -> bool {
        self.is_suspended
    }

    // TODO: Remove this method.
    // It's currently used to call register_fonts and set_focus_fallback.
    #[doc(hidden)]
    pub fn roots(&mut self) -> impl Iterator<Item = &mut RenderRoot> {
        self.windows
            .values_mut()
            .map(|window| &mut window.render_root)
    }

    /// Sets how frames are presented to the user.
    ///
    /// This affects what users commonly know as "VSync".
    ///
    /// # Panics
    ///
    /// If the WGPU device hasn't been initialized yet.
    pub fn set_present_mode(&mut self, window_id: WindowId, present_mode: wgpu::PresentMode) {
        let Some(device) = self.device.as_ref() else {
            tracing::error!("Called MasonryState::set_present_mode before initializing device");
            return;
        };

        let handle_id = self.get_handle_id(window_id);
        let surface = self.surfaces.get_mut(&handle_id).unwrap();
        self.render_cx
            .set_present_mode(device, surface, present_mode);
    }
}

fn init_device(render_cx: &mut RenderContext, handle: Arc<WindowHandle>) -> DeviceHandle {
    pollster::block_on(
        // Create device using the window's backing surface
        render_cx.create_device(handle),
    )
    .unwrap()
}

fn create_surface(
    render_cx: &mut RenderContext,
    device_handle: &DeviceHandle,
    handle: Arc<WindowHandle>,
    size: PhysicalSize<u32>,
) -> RenderSurface {
    assert!(
        size.width != 0 && size.height != 0,
        "cannot create a surface with a width or height of zero"
    );
    pollster::block_on(render_cx.create_surface(
        device_handle,
        handle,
        size.width,
        size.height,
        wgpu::PresentMode::AutoVsync,
    ))
    .unwrap()
}