winit-kora 0.30.13

Cross-platform window creation library. (Playtron's Kora fork of winit)
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
use std::cell::RefCell;
use std::sync::atomic::Ordering;
use std::sync::{Arc, Mutex};

use ahash::AHashMap;

use sctk::reexports::calloop::LoopHandle;
use sctk::reexports::client::backend::ObjectId;
use sctk::reexports::client::globals::GlobalList;
use sctk::reexports::client::protocol::wl_output::WlOutput;
use sctk::reexports::client::protocol::wl_surface::WlSurface;
use sctk::reexports::client::{Connection, Proxy, QueueHandle};

use sctk::compositor::{CompositorHandler, CompositorState};
use sctk::output::{OutputHandler, OutputState};
use sctk::registry::{ProvidesRegistryState, RegistryState};
use sctk::seat::pointer::ThemedPointer;
use sctk::seat::SeatState;
use sctk::shell::xdg::popup::{Popup, PopupConfigure, PopupHandler};
use sctk::shell::xdg::window::{Window, WindowConfigure, WindowHandler};
use sctk::shell::xdg::XdgShell;
use sctk::shell::WaylandSurface;
use sctk::shm::slot::SlotPool;
use sctk::shm::{Shm, ShmHandler};
use sctk::subcompositor::SubcompositorState;

use crate::platform_impl::wayland::event_loop::sink::EventSink;
use crate::platform_impl::wayland::output::MonitorHandle;
use crate::platform_impl::wayland::seat::{
    KeyboardShortcutsInhibitState, PointerConstraintsState, RelativePointerState, TextInputState,
    WinitPointerData, WinitPointerDataExt, WinitSeatState,
};
use crate::platform_impl::wayland::types::background_effect::BackgroundEffectManager;
use crate::platform_impl::wayland::types::cosmic_animated_resize::CosmicAnimatedResizeManager;
use crate::platform_impl::wayland::types::cosmic_backdrop_color::CosmicBackdropColorManager;
use crate::platform_impl::wayland::types::cosmic_corner_radius::CosmicCornerRadiusManager;
use crate::platform_impl::wayland::types::cosmic_special_action::CosmicSpecialActionManager;
use crate::platform_impl::wayland::types::cosmic_surface_embed::CosmicSurfaceEmbedManager;
use crate::platform_impl::wayland::types::cosmic_tooltip::CosmicTooltipManager;
use crate::platform_impl::wayland::types::kora_app_commands::AppCommandsManager;
use crate::platform_impl::wayland::types::kora_halo_header::KoraHaloHeaderManager;
use crate::platform_impl::wayland::types::kora_toplevel_identity::IdentityManager;
use crate::platform_impl::wayland::types::kwin_blur::KWinBlurManager;
use crate::platform_impl::wayland::types::layer_shadow::LayerShadowManager;
use crate::platform_impl::wayland::types::wayland_dnd::{DndSessionState, WaylandDndManager};
use crate::platform_impl::wayland::types::wp_fractional_scaling::FractionalScalingManager;
use crate::platform_impl::wayland::types::wp_viewporter::ViewporterState;
use crate::platform_impl::wayland::types::xdg_activation::XdgActivationState;
use crate::platform_impl::wayland::types::xdg_foreign::XdgForeign;
use crate::platform_impl::wayland::types::xdg_popup::{
    plan_destroy_tree, release_dismissed, subtree_leaf_first, DismissedPopup, PopupEvent, PopupId,
    PopupState,
};
use crate::platform_impl::wayland::types::xdg_toplevel_icon::ToplevelIconManager;
use crate::platform_impl::wayland::window::{WindowRequests, WindowState};
use crate::platform_impl::wayland::{WaylandError, WindowId};
use crate::platform_impl::OsError;

/// Winit's Wayland state.
pub struct WinitState {
    /// The WlRegistry.
    pub registry_state: RegistryState,

    /// The state of the WlOutput handling.
    pub output_state: OutputState,

    /// The compositor state which is used to create new windows and regions.
    pub compositor_state: Arc<CompositorState>,

    /// The state of the subcompositor.
    pub subcompositor_state: Option<Arc<SubcompositorState>>,

    /// The seat state responsible for all sorts of input.
    pub seat_state: SeatState,

    /// The shm for software buffers, such as cursors.
    pub shm: Shm,

    /// The pool where custom cursors are allocated.
    pub custom_cursor_pool: Arc<Mutex<SlotPool>>,

    /// The XDG shell that is used for windows.
    pub xdg_shell: XdgShell,

    /// The currently present windows.
    pub windows: RefCell<AHashMap<WindowId, Arc<Mutex<WindowState>>>>,

    /// The requests from the `Window` to EventLoop, such as close operations and redraw requests.
    pub window_requests: RefCell<AHashMap<WindowId, Arc<WindowRequests>>>,

    /// The events that were generated directly from the window.
    pub window_events_sink: Arc<Mutex<EventSink>>,

    /// The update for the `windows` coming from the compositor.
    pub window_compositor_updates: Vec<WindowCompositorUpdate>,

    /// Currently handled seats.
    pub seats: AHashMap<ObjectId, WinitSeatState>,

    /// Currently present cursor surfaces.
    pub pointer_surfaces: AHashMap<ObjectId, Arc<ThemedPointer<WinitPointerData>>>,

    /// The state of the text input on the client.
    pub text_input_state: Option<TextInputState>,

    /// The keyboard-shortcuts-inhibit manager, for capturing compositor-reserved keys.
    pub keyboard_shortcuts_inhibit_state: Option<KeyboardShortcutsInhibitState>,

    /// Observed monitors.
    pub monitors: Arc<Mutex<Vec<MonitorHandle>>>,

    /// Sink to accumulate window events from the compositor, which is latter dispatched in
    /// event loop run.
    pub events_sink: EventSink,

    /// Xdg activation.
    pub xdg_activation: Option<XdgActivationState>,

    /// Relative pointer.
    pub relative_pointer: Option<RelativePointerState>,

    /// Pointer constraints to handle pointer locking and confining.
    pub pointer_constraints: Option<Arc<PointerConstraintsState>>,

    /// Viewporter state on the given window.
    pub viewporter_state: Option<ViewporterState>,

    /// Fractional scaling manager.
    pub fractional_scaling_manager: Option<FractionalScalingManager>,

    /// xdg-toplevel-icon manager (per-window title-bar icon).
    pub toplevel_icon_manager: Option<ToplevelIconManager>,

    /// KWin blur manager.
    pub kwin_blur_manager: Option<KWinBlurManager>,
    /// Compositor-drawn shadow manager.
    pub layer_shadow_manager: Option<LayerShadowManager>,

    /// The standard background-effect protocol. Compositors commonly implement
    /// only one of this and KDE blur, so both are bound and both are set.
    pub background_effect_manager: Option<BackgroundEffectManager>,

    /// COSMIC animated resize manager.
    pub animated_resize_manager: Option<CosmicAnimatedResizeManager>,

    /// COSMIC corner radius manager.
    pub corner_radius_manager: Option<CosmicCornerRadiusManager>,
    /// Routes the device's special key to a registered surface.
    pub special_action_manager: Option<CosmicSpecialActionManager>,

    /// COSMIC backdrop color manager.
    pub backdrop_color_manager: Option<CosmicBackdropColorManager>,

    /// COSMIC exclusive mode manager.

    /// COSMIC surface embed manager.
    pub surface_embed_manager: Option<CosmicSurfaceEmbedManager>,

    /// xdg-foreign importer, for parenting a window to a foreign toplevel
    /// exported by another client (e.g. a portal file-chooser dialog parented
    /// to the requesting application's window).
    pub xdg_foreign: Option<XdgForeign>,

    /// COSMIC tooltip manager.
    pub tooltip_manager: Option<CosmicTooltipManager>,

    /// Kora Halo header manager, for giving the Halo a drag strip over a
    /// window's top edge.
    pub halo_header_manager: Option<KoraHaloHeaderManager>,

    /// Authenticated mapped-window identity lookup.
    pub identity_manager: Option<IdentityManager>,

    /// Publishes windows' commands to the shell.
    pub app_commands_manager: Option<AppCommandsManager>,

    /// Wayland DnD (drag-and-drop) manager.
    pub dnd_manager: Option<WaylandDndManager>,

    /// Per-seat `wl_data_device` for DnD. Stored for lifetime management.
    pub dnd_data_devices: Vec<sctk::reexports::client::protocol::wl_data_device::WlDataDevice>,

    /// Mutable DnD session state (current offer, source, focused window, etc.).
    pub dnd_session: DndSessionState,

    /// Active popup surfaces.
    pub popups: AHashMap<PopupId, PopupState>,

    /// Pending popup events to deliver to the application.
    pub popup_events: Vec<PopupEvent>,

    /// Popups the compositor dismissed, children ahead of parents. Kept alive until their `Done`
    /// has been handled: the app may still present to them, and a destroyed wl_surface is fatal.
    pub dismissed_popups: Vec<DismissedPopup>,

    /// Loop handle to re-register event sources, such as keyboard repeat.
    pub loop_handle: LoopHandle<'static, Self>,

    /// Whether we have dispatched events to the user thus we want to
    /// send `AboutToWait` and normally wakeup the user.
    pub dispatched_events: bool,
}

impl WinitState {
    pub fn new(
        globals: &GlobalList,
        queue_handle: &QueueHandle<Self>,
        loop_handle: LoopHandle<'static, WinitState>,
    ) -> Result<Self, OsError> {
        let registry_state = RegistryState::new(globals);
        let compositor_state =
            CompositorState::bind(globals, queue_handle).map_err(WaylandError::Bind)?;
        let subcompositor_state = match SubcompositorState::bind(
            compositor_state.wl_compositor().clone(),
            globals,
            queue_handle,
        ) {
            Ok(c) => Some(c),
            Err(e) => {
                tracing::warn!("Subcompositor protocol not available, ignoring CSD: {e:?}");
                None
            },
        };

        let output_state = OutputState::new(globals, queue_handle);
        let monitors = output_state.outputs().map(MonitorHandle::new).collect();

        let seat_state = SeatState::new(globals, queue_handle);

        let mut seats = AHashMap::default();
        for seat in seat_state.seats() {
            seats.insert(seat.id(), WinitSeatState::new());
        }

        let (viewporter_state, fractional_scaling_manager) =
            if let Ok(fsm) = FractionalScalingManager::new(globals, queue_handle) {
                (ViewporterState::new(globals, queue_handle).ok(), Some(fsm))
            } else {
                (None, None)
            };

        let shm = Shm::bind(globals, queue_handle).map_err(WaylandError::Bind)?;
        let custom_cursor_pool = Arc::new(Mutex::new(SlotPool::new(2, &shm).unwrap()));

        Ok(Self {
            registry_state,
            compositor_state: Arc::new(compositor_state),
            subcompositor_state: subcompositor_state.map(Arc::new),
            output_state,
            seat_state,
            shm,
            custom_cursor_pool,

            xdg_shell: XdgShell::bind(globals, queue_handle).map_err(WaylandError::Bind)?,
            xdg_activation: XdgActivationState::bind(globals, queue_handle).ok(),

            windows: Default::default(),
            window_requests: Default::default(),
            window_compositor_updates: Vec::new(),
            window_events_sink: Default::default(),
            viewporter_state,
            fractional_scaling_manager,
            toplevel_icon_manager: ToplevelIconManager::new(globals, queue_handle).ok(),
            kwin_blur_manager: KWinBlurManager::new(globals, queue_handle).ok(),
            layer_shadow_manager: LayerShadowManager::new(globals, queue_handle).ok(),
            background_effect_manager: BackgroundEffectManager::new(globals, queue_handle).ok(),
            animated_resize_manager: CosmicAnimatedResizeManager::new(globals, queue_handle).ok(),
            corner_radius_manager: CosmicCornerRadiusManager::new(globals, queue_handle).ok(),
            special_action_manager: CosmicSpecialActionManager::new(globals, queue_handle).ok(),
            backdrop_color_manager: CosmicBackdropColorManager::new(globals, queue_handle).ok(),
            surface_embed_manager: CosmicSurfaceEmbedManager::new(globals, queue_handle).ok(),
            xdg_foreign: XdgForeign::new(globals, queue_handle).ok(),
            tooltip_manager: CosmicTooltipManager::new(globals, queue_handle).ok(),
            halo_header_manager: KoraHaloHeaderManager::new(globals, queue_handle).ok(),
            identity_manager: IdentityManager::new(globals, queue_handle).ok(),
            app_commands_manager: AppCommandsManager::new(globals, queue_handle).ok(),

            dnd_manager: WaylandDndManager::new(globals, queue_handle).ok(),
            dnd_data_devices: Vec::new(),
            dnd_session: DndSessionState::default(),

            popups: Default::default(),
            popup_events: Vec::new(),
            dismissed_popups: Vec::new(),

            seats,
            text_input_state: TextInputState::new(globals, queue_handle).ok(),
            keyboard_shortcuts_inhibit_state: KeyboardShortcutsInhibitState::new(
                globals,
                queue_handle,
            )
            .ok(),

            relative_pointer: RelativePointerState::new(globals, queue_handle).ok(),
            pointer_constraints: PointerConstraintsState::new(globals, queue_handle)
                .map(Arc::new)
                .ok(),
            pointer_surfaces: Default::default(),

            monitors: Arc::new(Mutex::new(monitors)),
            events_sink: EventSink::new(),
            loop_handle,
            // Make it true by default.
            dispatched_events: true,
        })
    }

    pub fn scale_factor_changed(
        &mut self,
        surface: &WlSurface,
        scale_factor: f64,
        is_legacy: bool,
    ) {
        // Check if the cursor surface.
        let window_id = super::make_wid(surface);

        if let Some(window) = self.windows.get_mut().get(&window_id) {
            // Don't update the scaling factor, when legacy method is used.
            if is_legacy && self.fractional_scaling_manager.is_some() {
                return;
            }

            // The scale factor change is for the window.
            let pos = if let Some(pos) = self
                .window_compositor_updates
                .iter()
                .position(|update| update.window_id == window_id)
            {
                pos
            } else {
                self.window_compositor_updates.push(WindowCompositorUpdate::new(window_id));
                self.window_compositor_updates.len() - 1
            };

            // Update the scale factor right away.
            window.lock().unwrap().set_scale_factor(scale_factor);
            self.window_compositor_updates[pos].scale_changed = true;
        } else if let Some(pointer) = self.pointer_surfaces.get(&surface.id()) {
            // Get the window, where the pointer resides right now.
            let focused_window = match pointer.pointer().winit_data().focused_window() {
                Some(focused_window) => focused_window,
                None => return,
            };

            if let Some(window_state) = self.windows.get_mut().get(&focused_window) {
                window_state.lock().unwrap().reload_cursor_style()
            }
        }
    }

    pub fn queue_close(updates: &mut Vec<WindowCompositorUpdate>, window_id: WindowId) {
        let pos = if let Some(pos) = updates.iter().position(|update| update.window_id == window_id)
        {
            pos
        } else {
            updates.push(WindowCompositorUpdate::new(window_id));
            updates.len() - 1
        };

        updates[pos].close_window = true;
    }
}

impl ShmHandler for WinitState {
    fn shm_state(&mut self) -> &mut Shm {
        &mut self.shm
    }
}

impl WindowHandler for WinitState {
    fn request_close(&mut self, _: &Connection, _: &QueueHandle<Self>, window: &Window) {
        let window_id = super::make_wid(window.wl_surface());
        Self::queue_close(&mut self.window_compositor_updates, window_id);
    }

    fn configure(
        &mut self,
        _: &Connection,
        _: &QueueHandle<Self>,
        window: &Window,
        configure: WindowConfigure,
        _serial: u32,
    ) {
        let window_id = super::make_wid(window.wl_surface());

        let pos = if let Some(pos) =
            self.window_compositor_updates.iter().position(|update| update.window_id == window_id)
        {
            pos
        } else {
            self.window_compositor_updates.push(WindowCompositorUpdate::new(window_id));
            self.window_compositor_updates.len() - 1
        };

        // The initial configure must be applied immediately because
        // window creation blocks in blocking_dispatch() waiting for
        // is_configured() (i.e. last_configure.is_some()). Deferring
        // it would deadlock since single_iteration never runs.
        // Subsequent configures during animated resize are deferred so
        // only the latest per dispatch cycle is applied, avoiding
        // hundreds of intermediate set_window_geometry writes that can
        // overflow the Wayland socket buffer.
        let is_initial = !self
            .windows
            .get_mut()
            .get(&window_id)
            .expect("got configure for dead window.")
            .lock()
            .unwrap()
            .is_configured();

        if is_initial {
            tracing::debug!(
                "configure: INITIAL window={:?} size=({:?},{:?}) state={:?}",
                window_id,
                configure.new_size.0.map(|v| v.get()),
                configure.new_size.1.map(|v| v.get()),
                configure.state,
            );
            // Apply immediately for initial configure.
            let mut window = self
                .windows
                .get_mut()
                .get_mut(&window_id)
                .expect("got configure for dead window.")
                .lock()
                .unwrap();
            let resized = window.configure(configure, &self.shm, &self.subcompositor_state);
            let occluded = window.take_occluded();
            drop(window);
            let update = &mut self.window_compositor_updates[pos];
            update.resized |= resized;
            update.occluded = occluded.or(update.occluded);
        } else {
            let had_pending = self.window_compositor_updates[pos].pending_configure.is_some();
            tracing::debug!(
                "configure: DEFERRED window={:?} size=({:?},{:?}) state={:?} had_pending={}",
                window_id,
                configure.new_size.0.map(|v| v.get()),
                configure.new_size.1.map(|v| v.get()),
                configure.state,
                had_pending,
            );
            // Store the latest configure without immediately applying it.
            // During animated resize, cosmic-comp can send many per-pixel
            // configures in a single dispatch cycle. Processing each one would
            // trigger set_window_geometry writes that contribute to socket
            // buffer pressure. By deferring, only the latest configure per
            // dispatch cycle is applied in single_iteration.
            self.window_compositor_updates[pos].pending_configure = Some(configure);
        }

        // NOTE: configure demands wl_surface::commit, however winit doesn't commit on behalf of the
        // users, since it can break a lot of things, thus it'll ask users to redraw instead.
        self.window_requests
            .get_mut()
            .get(&window_id)
            .unwrap()
            .redraw_requested
            .store(true, Ordering::Relaxed);

        // Manually mark that we've got an event, since configure may not generate a resize.
        self.dispatched_events = true;
    }
}

impl OutputHandler for WinitState {
    fn output_state(&mut self) -> &mut OutputState {
        &mut self.output_state
    }

    fn new_output(&mut self, _: &Connection, _: &QueueHandle<Self>, output: WlOutput) {
        self.monitors.lock().unwrap().push(MonitorHandle::new(output));
    }

    fn update_output(&mut self, _: &Connection, _: &QueueHandle<Self>, updated: WlOutput) {
        let mut monitors = self.monitors.lock().unwrap();
        let updated = MonitorHandle::new(updated);
        if let Some(pos) = monitors.iter().position(|output| output == &updated) {
            monitors[pos] = updated
        } else {
            monitors.push(updated)
        }
    }

    fn output_destroyed(&mut self, _: &Connection, _: &QueueHandle<Self>, removed: WlOutput) {
        let mut monitors = self.monitors.lock().unwrap();
        let removed = MonitorHandle::new(removed);
        if let Some(pos) = monitors.iter().position(|output| output == &removed) {
            monitors.remove(pos);
        }
    }
}

impl CompositorHandler for WinitState {
    fn transform_changed(
        &mut self,
        _: &Connection,
        _: &QueueHandle<Self>,
        _: &WlSurface,
        _: wayland_client::protocol::wl_output::Transform,
    ) {
        // TODO(kchibisov) we need to expose it somehow in winit.
    }

    fn surface_enter(
        &mut self,
        _: &Connection,
        _: &QueueHandle<Self>,
        _: &WlSurface,
        _: &WlOutput,
    ) {
    }

    fn surface_leave(
        &mut self,
        _: &Connection,
        _: &QueueHandle<Self>,
        _: &WlSurface,
        _: &WlOutput,
    ) {
    }

    fn scale_factor_changed(
        &mut self,
        _: &Connection,
        _: &QueueHandle<Self>,
        surface: &WlSurface,
        scale_factor: i32,
    ) {
        self.scale_factor_changed(surface, scale_factor as f64, true)
    }

    fn frame(&mut self, _: &Connection, _: &QueueHandle<Self>, surface: &WlSurface, _: u32) {
        let window_id = super::make_wid(surface);
        let window = match self.windows.get_mut().get(&window_id) {
            Some(window) => window,
            None => return,
        };

        // In case we have a redraw requested we must indicate the wake up.
        if self
            .window_requests
            .get_mut()
            .get(&window_id)
            .unwrap()
            .redraw_requested
            .load(Ordering::Relaxed)
        {
            self.dispatched_events = true;
        }

        window.lock().unwrap().frame_callback_received();
    }
}

impl ProvidesRegistryState for WinitState {
    sctk::registry_handlers![OutputState, SeatState];

    fn registry(&mut self) -> &mut RegistryState {
        &mut self.registry_state
    }
}

// The window update coming from the compositor.
#[derive(Debug, Clone)]
pub struct WindowCompositorUpdate {
    /// The id of the window this updates belongs to.
    pub window_id: WindowId,

    /// New window size.
    pub resized: bool,

    /// New scale factor.
    pub scale_changed: bool,

    /// Close the window.
    pub close_window: bool,

    /// The window became hidden (`true`) or visible again (`false`).
    pub occluded: Option<bool>,

    /// Pending configure to apply. When multiple configures arrive in one
    /// dispatch cycle (e.g. during animated resize), only the latest is stored
    /// and applied once, avoiding hundreds of intermediate resize/geometry
    /// writes that can overflow the Wayland socket buffer.
    pub pending_configure: Option<WindowConfigure>,
}

impl WindowCompositorUpdate {
    fn new(window_id: WindowId) -> Self {
        Self {
            window_id,
            resized: false,
            scale_changed: false,
            close_window: false,
            occluded: None,
            pending_configure: None,
        }
    }
}

sctk::delegate_subcompositor!(WinitState);
sctk::delegate_compositor!(WinitState);
sctk::delegate_output!(WinitState);
sctk::delegate_registry!(WinitState);
sctk::delegate_shm!(WinitState);
sctk::delegate_xdg_shell!(WinitState);
sctk::delegate_xdg_window!(WinitState);
sctk::delegate_xdg_popup!(WinitState);

impl PopupHandler for WinitState {
    fn configure(
        &mut self,
        _conn: &Connection,
        _qh: &QueueHandle<Self>,
        popup: &Popup,
        config: PopupConfigure,
    ) {
        // Find the popup by wl_surface
        let popup_id = self
            .popups
            .iter()
            .find(|(_, state)| state.popup.wl_surface() == popup.wl_surface())
            .map(|(id, _)| *id);

        if let Some(id) = popup_id {
            if let Some(state) = self.popups.get_mut(&id) {
                // Don't overwrite size with configure dimensions. The configure
                // returns the *geometry* size (visible content), but we need
                // the full surface size (including shadow) for rendering.
                // state.size was set to the full surface size in create_popup.
                state.configured = true;

                // Set viewport destination to the full surface size for HiDPI.
                // The surface buffer is rendered at the full size (with shadows),
                // not the geometry size returned by configure.
                if let Some(ref viewport) = state.viewport {
                    viewport.set_destination(state.size.width as i32, state.size.height as i32);
                }
            }

            // Use stored full surface size for the event, not configure's
            // geometry size, so iced creates the viewport/surface at the
            // correct rendering dimensions (including shadow padding).
            let (event_width, event_height) = self
                .popups
                .get(&id)
                .map(|s| (s.size.width, s.size.height))
                .unwrap_or((config.width as u32, config.height as u32));

            tracing::debug!(
                "Popup {:?} configured by compositor: position=({}, {}), geometry={}x{}, \
                 surface={}x{}",
                id,
                config.position.0,
                config.position.1,
                config.width,
                config.height,
                event_width,
                event_height,
            );
            self.popup_events.push(PopupEvent::Configure {
                id,
                width: event_width,
                height: event_height,
            });
            self.dispatched_events = true;
        }
    }

    fn done(&mut self, _conn: &Connection, _qh: &QueueHandle<Self>, popup: &Popup) {
        // Find and remove the popup
        let popup_id = self
            .popups
            .iter()
            .find(|(_, state)| state.popup.wl_surface() == popup.wl_surface())
            .map(|(id, _)| *id);

        if let Some(id) = popup_id {
            for (id, state) in self.take_popup_tree(id) {
                self.popup_events.push(PopupEvent::Done { id });
                self.dismissed_popups.push(DismissedPopup { id, state, reported: false });
            }
            self.dispatched_events = true;
        }
    }
}

impl WinitState {
    /// Takes `id` and its live descendants out of `popups`, children ahead of parents, without
    /// dropping them.
    fn take_popup_tree(&mut self, id: PopupId) -> Vec<(PopupId, PopupState)> {
        if !self.popups.contains_key(&id) {
            return Vec::new();
        }
        let order =
            subtree_leaf_first(self.popups.iter().map(|(id, popup)| (*id, popup.parent_popup)), id);
        order.into_iter().filter_map(|id| Some((id, self.popups.remove(&id)?))).collect()
    }

    /// Destroys `id` and every live popup below it, children first: destroying a popup under a
    /// live child is `not_the_topmost_popup`.
    ///
    /// Descendants the compositor already dismissed are left where they are, to finish the grace
    /// window their `Done` opened. Closing the menu is the usual answer to a submenu's `Done`, so
    /// this is the common case rather than a corner of one, and dropping them here would destroy
    /// a wl_surface the app may still be presenting to in the same turn it learned it was gone.
    ///
    /// Returns the live descendants destroyed with it, or `None` if `id` is neither live nor
    /// dismissed.
    pub fn destroy_popup_tree(&mut self, id: PopupId) -> Option<Vec<PopupId>> {
        let dismissed: Vec<PopupId> = self.dismissed_popups.iter().map(|p| p.id).collect();
        if !self.popups.contains_key(&id) && !dismissed.contains(&id) {
            return None;
        }
        let links: Vec<_> = self
            .popups
            .iter()
            .map(|(id, popup)| (*id, popup.parent_popup))
            .chain(self.dismissed_popups.iter().map(|p| (p.id, p.state.parent_popup)))
            .collect();
        let plan = plan_destroy_tree(links, &dismissed, id);
        if !plan.held.is_empty() {
            tracing::debug!("destroy_popup: {:?} stay until their grace window is up", plan.held);
        }
        let mut live_children = Vec::new();
        for popup in plan.destroy {
            if self.popups.remove(&popup).is_some() && popup != id {
                live_children.push(popup);
            }
        }
        Some(live_children)
    }

    /// Drops dismissed popups whose `Done` an earlier take handed out, and marks the rest as
    /// handed out by this one.
    pub fn release_dismissed_popups(&mut self) {
        // Dropped front to back, so children still go ahead of parents.
        drop(release_dismissed(&mut self.dismissed_popups));
    }
}