kas-core 0.17.0

KAS GUI / core
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
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License in the LICENSE-APACHE file or at:
//     https://www.apache.org/licenses/LICENSE-2.0

//! Window types

use super::common::{RunError, WindowSurface};
use super::shared::Shared;
use super::{AppData, GraphicsInstance, Platform};
use crate::cast::{Cast, CastApprox};
use crate::config::{Config, WindowConfig};
use crate::draw::PassType;
use crate::draw::color::Rgba;
use crate::event::{ConfigCx, CursorIcon, EventState};
use crate::geom::{Coord, Offset, Rect, Size};
use crate::layout::SolveCache;
use crate::messages::Erased;
use crate::theme::{DrawCx, SizeCx, Theme, ThemeDraw, Window as _};
use crate::window::{BoxedWindow, Decorations, PopupDescriptor, WindowId, WindowWidget};
use crate::{
    ActionClose, ActionResize, ConfigAction, Id, Layout, Tile, Widget, WindowActions, autoimpl,
};
#[cfg(windows_platform)]
use raw_window_handle::HasWindowHandle;
use std::cell::RefCell;
use std::mem::take;
use std::rc::Rc;
use std::sync::Arc;
use std::time::{Duration, Instant};
use winit::dpi::PhysicalSize;
use winit::event::WindowEvent;
use winit::event_loop::ActiveEventLoop;
use winit::window::{ImeRequest, ImeRequestError, WindowAttributes};

/// Window fields requiring a frame or surface
#[crate::autoimpl(Deref, DerefMut using self.window)]
struct WindowData<G: GraphicsInstance> {
    window: Arc<Box<dyn winit::window::Window>>,
    #[cfg(all(wayland_platform, feature = "clipboard"))]
    wayland_clipboard: Option<smithay_clipboard::Clipboard>,
    surface: G::Surface,
    /// Frame rate counter
    frame_count: (Instant, u32),
    #[cfg(feature = "accesskit")]
    accesskit: accesskit_winit::Adapter,

    // NOTE: cached components could be here or in Window
    window_id: WindowId,
    solve_cache: SolveCache,
    need_redraw: bool,
}

/// Per-window data
#[cfg_attr(not(feature = "internal_doc"), doc(hidden))]
#[cfg_attr(docsrs, doc(cfg(internal_doc)))]
#[autoimpl(Debug ignore self._data, self.widget, self.ev_state, self.theme_and_window)]
pub struct Window<A: AppData, G: GraphicsInstance, T: Theme<G::Shared>> {
    _data: std::marker::PhantomData<A>,
    pub(super) widget: Box<dyn WindowWidget<Data = A>>,
    ev_state: EventState,
    theme_and_window: Option<(T::Window, WindowData<G>)>,
}

// Public functions, for use by the toolkit
impl<A: AppData, G: GraphicsInstance, T: Theme<G::Shared>> Window<A, G, T> {
    /// Construct window state (widget)
    pub fn new(
        config: Rc<RefCell<Config>>,
        platform: Platform,
        window_id: WindowId,
        widget: BoxedWindow<A>,
    ) -> Self {
        let config = WindowConfig::new(config);
        Window {
            _data: std::marker::PhantomData,
            widget: widget.0,
            ev_state: EventState::new(window_id, config, platform),
            theme_and_window: None,
        }
    }

    #[inline]
    pub(super) fn window_id(&self) -> WindowId {
        self.ev_state.window_id
    }

    #[inline]
    pub(super) fn winit_window(&self) -> Option<&dyn winit::window::Window> {
        self.theme_and_window.as_ref().map(|d| &**d.1.window)
    }

    /// Open the window and create render surfaces
    pub(super) fn create_surfaces(
        &mut self,
        shared: &mut Shared<A, G, T>,
        data: &A,
        el: &dyn ActiveEventLoop,
        #[allow(unused)] modal_parent: Option<&dyn winit::window::Window>,
    ) -> Result<winit::window::WindowId, RunError> {
        debug_assert!(self.theme_and_window.is_none());

        let time = Instant::now();

        // We use the logical size and scale factor of the largest monitor as
        // an upper bound on window size and guessed scale factor.
        let mut max_physical_size = PhysicalSize::new(800, 600);
        let mut scale_factor = 1.0;
        let mut product = 0;
        for monitor in el.available_monitors() {
            let Some(size) = monitor.current_video_mode().map(|mode| mode.size()) else {
                continue;
            };
            let p = size.width * size.height;
            if p > product {
                product = p;
                max_physical_size = size;
                scale_factor = monitor.scale_factor();
            }
        }
        let max_size = max_physical_size.to_logical::<f64>(scale_factor);

        self.ev_state.update_config(scale_factor.cast_approx());
        let config = self.ev_state.config();
        let mut theme = shared.theme.new_window(config);

        let mut node = self.widget.as_node(data);
        let _: Option<ActionResize> = self.ev_state.full_configure(theme.size(), node.re());

        let mut cx = SizeCx::new(&mut self.ev_state, theme.size());
        let mut solve_cache = SolveCache::default();
        solve_cache.find_constraints(node, &mut cx);

        // Opening a zero-size window causes a crash, so force at least 1x1:
        let min_size = Size(1, 1);
        let mut ideal = solve_cache
            .ideal(true)
            .max(min_size)
            .as_physical()
            .to_logical::<f64>(scale_factor);
        ideal.width = ideal.width.min(max_size.width);
        ideal.height = ideal.height.min(max_size.height);

        let props = self.widget.properties();
        let mut attrs = WindowAttributes::default();
        attrs.surface_size = Some(ideal.into());
        attrs.title = self.widget.title().to_string();
        attrs.visible = false;
        let transparent = props.transparent();
        attrs.transparent = transparent;
        attrs.decorations = props.decorations() == Decorations::Server;
        attrs.window_icon = props.icon();
        let (restrict_min, restrict_max) = props.restrictions();
        if restrict_min {
            let mut min = solve_cache
                .min(true)
                .as_physical()
                .to_logical::<f64>(scale_factor);
            min.width = min.width.min(max_size.width);
            min.height = min.height.min(max_size.height);
            attrs.min_surface_size = Some(min.into());
        } else {
            attrs.min_surface_size = Some(PhysicalSize::new(1, 1).into());
        }
        if restrict_max {
            attrs.max_surface_size = Some(ideal.into());
        }
        let window = el.create_window(attrs)?;
        // TODO: handle modal windows on all platforms: skip taskbar and set owner (not parent) window.
        #[cfg(windows_platform)]
        if let Some(_handle) = modal_parent.and_then(|p| p.window_handle().ok()) {
            use winit::platform::windows::WindowExtWindows;
            window.set_skip_taskbar(true);
        }

        // Now that we have a scale factor, we may need to resize:
        let new_factor = window.scale_factor();
        if new_factor != scale_factor {
            scale_factor = new_factor;
            self.ev_state.update_config(scale_factor as f32);

            let config = self.ev_state.config();
            shared.theme.update_window(&mut theme, config);

            // Update text size which is assigned during configure
            let mut node = self.widget.as_node(data);
            let _: Option<ActionResize> = self.ev_state.full_configure(theme.size(), node.re());

            let mut cx = SizeCx::new(&mut self.ev_state, theme.size());
            solve_cache.find_constraints(node, &mut cx);

            if let Some(mode) = window
                .current_monitor()
                .and_then(|mon| mon.current_video_mode())
            {
                max_physical_size = mode.size();
            }

            let mut ideal = solve_cache.ideal(true).max(min_size).as_physical();
            if ideal.width > max_physical_size.width {
                ideal.width = max_physical_size.width;
            }
            if ideal.height > max_physical_size.height {
                ideal.height = max_physical_size.height;
            }

            if let Some(size) = window.request_surface_size(ideal.into()) {
                debug_assert_eq!(size, window.surface_size());
            } else {
                // We will receive WindowEvent::Resized and resize then.
                // Unfortunately we can't rely on this since some platforms (X11)
                // don't always behave as expected, thus we must resize now.
            }
        }

        let size: Size = window.surface_size().cast();
        log::info!(
            "Window::resume: constructed with physical size {size:?}, scale factor {scale_factor}",
        );

        #[cfg(all(wayland_platform, feature = "clipboard"))]
        use raw_window_handle::{HasDisplayHandle, RawDisplayHandle, WaylandDisplayHandle};
        #[cfg(all(wayland_platform, feature = "clipboard"))]
        let wayland_clipboard = match window.display_handle() {
            Ok(handle) => match handle.as_raw() {
                RawDisplayHandle::Wayland(WaylandDisplayHandle { display, .. }) => {
                    Some(unsafe { smithay_clipboard::Clipboard::new(display.as_ptr()) })
                }
                _ => None,
            },
            _ => None,
        };

        // NOTE: usage of Arc is inelegant, but avoids lots of unsafe code
        let window = Arc::new(window);
        let mut surface = shared.instance.new_surface(window.clone(), transparent)?;
        shared.create_draw_shared(&surface)?;
        surface.configure(&mut shared.draw.as_mut().unwrap().draw, size);

        let winit_id = window.id();

        #[cfg(feature = "accesskit")]
        let accesskit = todo!(); // FIXME: accesskit_winit::Adapter::with_event_loop_proxy(el, &window, el.create_proxy());

        let window = WindowData {
            window,
            #[cfg(all(wayland_platform, feature = "clipboard"))]
            wayland_clipboard,
            surface,
            frame_count: (Instant::now(), 0),

            #[cfg(feature = "accesskit")]
            accesskit,

            window_id: self.ev_state.window_id,
            solve_cache,
            need_redraw: true,
        };
        self.theme_and_window = Some((theme, window));

        self.apply_size(data, true, false);

        log::trace!(target: "kas_perf::wgpu::window", "resume: {}µs", time.elapsed().as_micros());
        Ok(winit_id)
    }

    /// Application suspended. Clean up temporary state.
    pub(super) fn suspend(
        &mut self,
        shared: &mut Shared<A, G, T>,
        data: &A,
    ) -> Option<ActionClose> {
        if let Some((ref theme, ref mut window)) = self.theme_and_window {
            self.ev_state.suspended(shared);

            let actions = self.ev_state.flush_pending(
                shared,
                theme.size(),
                window,
                self.widget.as_node(data),
            );

            // NOTE: ignore resize, redraw actions
            actions.close
        } else {
            None
        }
    }

    /// Destroy render surface(s)
    pub(super) fn destroy_surfaces(&mut self) {
        self.theme_and_window = None;
    }

    /// Handle an event
    ///
    /// Returns `true` to force polling temporarily.
    pub(super) fn handle_event(
        &mut self,
        shared: &mut Shared<A, G, T>,
        data: &A,
        event: WindowEvent,
    ) -> bool {
        let Some((ref mut theme, ref mut window)) = self.theme_and_window else {
            return false;
        };

        #[cfg(feature = "accesskit")]
        todo!(); // FIXME: window.accesskit.process_event(&window.window, &event);

        let (apply_size, resize, poll) = match event {
            WindowEvent::Moved(_) | WindowEvent::Destroyed => return false,
            WindowEvent::SurfaceResized(size) => {
                if window
                    .surface
                    .configure(&mut shared.draw.as_mut().unwrap().draw, size.cast())
                {
                    self.apply_size(data, false, false);
                }
                (true, false, false)
            }
            WindowEvent::ScaleFactorChanged {
                scale_factor,
                mut surface_size_writer,
            } => {
                // This event is generated when constructing a window but already handled
                if scale_factor as f32 == self.ev_state.config.scale_factor() {
                    return false;
                }

                // Note: API allows us to set new window size here.
                self.ev_state.update_config(scale_factor as f32);

                let config = self.ev_state.config();
                shared.theme.update_window(theme, config);

                // Force a reconfigure to update text objects:
                self.reconfigure(data);

                let Some((ref theme, ref mut window)) = self.theme_and_window else {
                    unreachable!()
                };
                let mut cx = SizeCx::new(&mut self.ev_state, theme.size());
                window
                    .solve_cache
                    .find_constraints(self.widget.as_node(data), &mut cx);
                let min = window.solve_cache.min(true);

                let size = window.surface.size();
                let (restrict_min, _) = self.widget.properties().restrictions();
                let apply = if !restrict_min || size >= min {
                    true
                } else {
                    let size = size.max(min);
                    surface_size_writer
                        .request_surface_size(size.as_physical())
                        .is_err()
                };

                (apply, false, false)
            }
            WindowEvent::RedrawRequested => return self.do_draw(shared, data).is_err(),
            event => {
                let resize = self
                    .ev_state
                    .with(shared, theme.size(), window, |cx| {
                        cx.handle_winit(&mut self.widget, data, event);
                    })
                    .is_some();
                (resize, resize, false)
            }
        };
        if apply_size {
            self.apply_size(data, false, resize);
        }
        poll
    }

    /// Handle all pending items before event loop sleeps
    pub(super) fn flush_pending(
        &mut self,
        shared: &mut Shared<A, G, T>,
        data: &A,
    ) -> (WindowActions, Option<Instant>) {
        let Some((ref theme, ref mut window)) = self.theme_and_window else {
            return (WindowActions::default(), None);
        };

        let actions =
            self.ev_state
                .flush_pending(shared, theme.size(), window, self.widget.as_node(data));
        if actions.resize.is_some() {
            self.apply_size(data, false, true);
        }

        if actions.close.is_some() {
            return (actions, None);
        }

        let Some((_, ref mut window)) = self.theme_and_window else {
            unreachable!();
        };
        if actions != WindowActions::default() {
            window.need_redraw = true;
        }

        let resume = match (
            self.ev_state.next_resume(),
            window.surface.common_mut().next_resume(),
        ) {
            (None, None) => None,
            (Some(a), None) => Some(a),
            (None, Some(b)) => Some(b),
            (Some(a), Some(b)) => Some(a.min(b)),
        };

        // NOTE: need_frame_update() does not imply a need to redraw, but other
        // approaches do not yield good frame timing for e.g. kinetic scrolling.
        if window.need_redraw || self.ev_state.need_frame_update() {
            window.request_redraw();
        }

        (actions, resume)
    }

    /// Send an erased message
    pub(super) fn send_erased(&mut self, id: Id, msg: Erased) {
        self.ev_state.send_erased(id, msg);
    }

    /// Handle a configuration update
    pub(super) fn config_update(
        &mut self,
        shared: &mut Shared<A, G, T>,
        data: &A,
        action: ConfigAction,
    ) {
        let Some((ref mut theme, ref mut window)) = self.theme_and_window else {
            return;
        };

        if action.contains(ConfigAction::EVENT) {
            self.ev_state.update_config(window.scale_factor() as f32);
        }

        let resize = if action.contains(ConfigAction::THEME_SWITCH) {
            let config = self.ev_state.config();
            *theme = shared.theme.new_window(config);
            true
        } else if action.contains(ConfigAction::THEME) {
            let config = self.ev_state.config();
            shared.theme.update_window(theme, config)
        } else {
            false
        };

        self.reconfigure(data);
        if resize {
            self.apply_size(data, false, true);
        }
    }

    #[cfg(feature = "accesskit")]
    pub(super) fn accesskit_event(
        &mut self,
        shared: &mut Shared<A, G, T>,
        data: &A,
        event: accesskit_winit::WindowEvent,
    ) {
        let Some((ref theme, ref mut window)) = self.theme_and_window else {
            return;
        };

        use accesskit_winit::WindowEvent as WE;
        match event {
            WE::InitialTreeRequested => window
                .accesskit
                .update_if_active(|| self.ev_state.accesskit_tree_update(&self.widget)),
            WE::ActionRequested(request) => {
                let resize = self.ev_state.with(shared, theme.size(), window, |cx| {
                    cx.handle_accesskit_action(self.widget.as_node(data), request);
                });
                if resize.is_some() {
                    self.apply_size(data, false, true);
                }
            }
            WE::AccessibilityDeactivated => {
                self.ev_state.disable_accesskit();
            }
        }
    }

    pub(super) fn update_timer(
        &mut self,
        shared: &mut Shared<A, G, T>,
        data: &A,
        requested_resume: Instant,
    ) {
        let Some((ref theme, ref mut window)) = self.theme_and_window else {
            return;
        };

        if window.surface.common_mut().immediate_redraw() {
            window.need_redraw = true;
            window.request_redraw();
        }

        let widget = self.widget.as_node(data);

        if Some(requested_resume) == self.ev_state.next_resume() {
            let resize = self.ev_state.with(shared, theme.size(), window, |cx| {
                cx.update_timer(widget);
            });
            if resize.is_some() {
                self.apply_size(data, false, true);
            }
        } else {
            #[allow(clippy::drop_non_drop)]
            drop(widget); // make the borrow checker happy
        }
    }

    /// Add or reposition a pop-up
    pub(super) fn add_popup(&mut self, data: &A, id: WindowId, popup: PopupDescriptor) {
        let Some((ref theme, _)) = self.theme_and_window else {
            return;
        };

        let mut cx = SizeCx::new(&mut self.ev_state, theme.size());
        self.widget.add_popup(&mut cx, data, id, popup);
    }

    pub(super) fn send_close(&mut self, id: WindowId) {
        if id == self.ev_state.window_id {
            self.ev_state.close_own_window();
        } else if let Some((ref theme, _)) = self.theme_and_window {
            let widget = &mut self.widget;
            let mut cx = SizeCx::new(&mut self.ev_state, theme.size());
            widget.remove_popup(&mut cx, id);
        }
    }
}

// Internal functions
impl<A: AppData, G: GraphicsInstance, T: Theme<G::Shared>> Window<A, G, T> {
    fn reconfigure(&mut self, data: &A) {
        let time = Instant::now();
        let Some((ref theme, _)) = self.theme_and_window else {
            return;
        };

        let resize: Option<ActionResize> = self
            .ev_state
            .full_configure(theme.size(), self.widget.as_node(data));
        if resize.is_some() {
            self.apply_size(data, false, true);
        }

        log::trace!(target: "kas_perf::wgpu::window", "reconfigure: {}µs", time.elapsed().as_micros());
    }

    pub(super) fn update(&mut self, data: &A) {
        let time = Instant::now();
        let Some((ref theme, ref mut window)) = self.theme_and_window else {
            return;
        };

        let size = theme.size();
        let mut cx = ConfigCx::new(&size, &mut self.ev_state);
        cx.update(self.widget.as_node(data));
        if cx.needs_resize() {
            self.apply_size(data, false, true);
        } else if cx.needs_redraw() {
            window.request_redraw();
        }

        log::trace!(target: "kas_perf::wgpu::window", "update: {}µs", time.elapsed().as_micros());
    }

    /// Solve for size requirements, apply, then update window size bounds
    fn apply_size(&mut self, data: &A, first: bool, resize: bool) {
        let time = Instant::now();
        let Some((ref theme, ref mut window)) = self.theme_and_window else {
            return;
        };
        let rect = Rect::new(Coord::ZERO, window.surface.size());
        log::debug!("apply_size: rect={rect:?}");

        let solve_cache = &mut window.solve_cache;
        let mut cx = SizeCx::new(&mut self.ev_state, theme.size());
        if resize {
            solve_cache.find_constraints(self.widget.as_node(data), &mut cx);
        }
        solve_cache.apply_rect(self.widget.as_node(data), &mut cx, rect, true);
        if first {
            solve_cache.print_widget_heirarchy(self.widget.as_tile());
        }
        debug_assert!(solve_cache.min(false) <= solve_cache.ideal(false));
        self.widget.resize_popups(&mut cx, data);

        // Update window size restrictions: the new width may have changed height requirements
        let (restrict_min, restrict_max) = self.widget.properties().restrictions();
        let min_size = if restrict_min {
            window.solve_cache.min(true).as_physical()
        } else {
            PhysicalSize::new(1, 1)
        };
        window.set_min_surface_size(Some(min_size.into()));
        window.set_max_surface_size(
            restrict_max.then(|| window.solve_cache.ideal(true).as_physical().into()),
        );

        window.set_visible(true);
        window.request_redraw();
        log::trace!(
            target: "kas_perf::wgpu::window",
            "apply_size: {}µs", time.elapsed().as_micros(),
        );
    }

    /// Draw
    ///
    /// Returns an error when drawing is aborted and further event handling may
    /// be needed before a redraw.
    pub(super) fn do_draw(&mut self, shared: &mut Shared<A, G, T>, data: &A) -> Result<(), ()> {
        let start = Instant::now();
        let Some((ref theme, ref window)) = self.theme_and_window else {
            return Ok(());
        };

        let widget = self.widget.as_node(data);
        let resize = self.ev_state.with(shared, theme.size(), window, |cx| {
            cx.frame_update(widget);
        });
        if resize.is_some() {
            self.apply_size(data, false, true);
        }
        let Some((ref mut theme, ref mut window)) = self.theme_and_window else {
            unreachable!();
        };

        #[cfg(feature = "accesskit")]
        if self.ev_state.accesskit_is_enabled() {
            window
                .accesskit
                .update_if_active(|| self.ev_state.accesskit_tree_update(&self.widget))
        }

        self.ev_state.clear_access_key_bindings();

        {
            let rect = Rect::new(Coord::ZERO, window.surface.size());
            let draw = window.surface.draw_iface(shared.draw.as_mut().unwrap());

            let mut draw = shared.theme.draw(draw, &mut self.ev_state, theme);
            let draw_cx = DrawCx::new(&mut draw, self.widget.id());
            self.widget.draw(draw_cx);

            draw.new_pass(
                rect,
                Offset::ZERO,
                PassType::Clip,
                Box::new(|draw: &mut dyn ThemeDraw| draw.event_state_overlay()),
            );
        }
        let time2 = Instant::now();

        window.need_redraw = window.surface.common_mut().immediate_redraw();
        self.ev_state.action_redraw = None;
        // NOTE: we used to return Err(()) if !action.is_empty() here, e.g. if a
        // widget requested a resize during draw. Likely it's better not to do
        // this even if the frame is imperfect.

        let clear_color = if self.widget.properties().transparent() {
            Rgba::TRANSPARENT
        } else {
            shared.theme.clear_color()
        };
        let time3 = window
            .surface
            .present(&mut shared.draw.as_mut().unwrap().draw, clear_color);

        let text_dur_micros = take(&mut window.surface.common_mut().dur_text);
        let end = Instant::now();
        log::trace!(
            target: "kas_perf::wgpu::window",
            "do_draw: {}μs ({}μs widgets, {}μs text, {}μs render, {}μs present)",
            (end - start).as_micros(),
            (time2 - start).as_micros(),
            text_dur_micros.as_micros(),
            (time3 - time2).as_micros(),
            (end - time2).as_micros()
        );

        const SECOND: Duration = Duration::from_secs(1);
        window.frame_count.1 += 1;
        if window.frame_count.0 + SECOND <= end {
            log::debug!(
                "Window {:?}: {} frames in last second",
                window.window_id,
                window.frame_count.1
            );
            window.frame_count.0 = end;
            window.frame_count.1 = 0;
        }

        Ok(())
    }
}

pub(crate) trait WindowDataErased {
    /// Get the window identifier
    fn window_id(&self) -> WindowId;

    /// Access the wayland clipboard object, if available
    #[cfg(all(wayland_platform, feature = "clipboard"))]
    fn wayland_clipboard(&self) -> Option<&smithay_clipboard::Clipboard>;

    /// Set the mouse pointer icon
    fn set_pointer_icon(&self, icon: CursorIcon);

    /// Enable / update / disable the Input Method Editor
    fn ime_request(&self, request: ImeRequest) -> Result<(), ImeRequestError>;

    /// Directly access Winit Window
    ///
    /// This is a temporary API, allowing e.g. to minimize the window.
    fn winit_window(&self) -> Option<&dyn winit::window::Window>;
}

impl<G: GraphicsInstance> WindowDataErased for WindowData<G> {
    fn window_id(&self) -> WindowId {
        self.window_id
    }

    #[cfg(all(wayland_platform, feature = "clipboard"))]
    fn wayland_clipboard(&self) -> Option<&smithay_clipboard::Clipboard> {
        self.wayland_clipboard.as_ref()
    }

    #[inline]
    fn set_pointer_icon(&self, icon: CursorIcon) {
        self.window.set_cursor(icon.into());
    }

    fn ime_request(&self, request: ImeRequest) -> Result<(), ImeRequestError> {
        self.window.request_ime_update(request)
    }

    #[inline]
    fn winit_window(&self) -> Option<&dyn winit::window::Window> {
        Some(&**self.window)
    }
}