guido 0.12.0

A reactive Rust GUI library using wgpu for Wayland layer shell widgets
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
use raw_window_handle::{
    DisplayHandle, HandleError, HasDisplayHandle, HasWindowHandle, RawDisplayHandle,
    RawWindowHandle, WaylandDisplayHandle, WaylandWindowHandle, WindowHandle,
};
use rustc_hash::FxHashMap;
use smithay_client_toolkit::reexports::calloop::LoopHandle;
use smithay_client_toolkit::reexports::client::{
    Connection, EventQueue, Proxy, QueueHandle,
    globals::registry_queue_init,
    protocol::{wl_output, wl_surface},
};
use smithay_client_toolkit::{
    compositor::{CompositorHandler, CompositorState, FrameCallbackData, Region},
    data_device_manager::DataDeviceManagerState,
    delegate_registry,
    output::OutputState,
    primary_selection::PrimarySelectionManagerState,
    registry::{ProvidesRegistryState, RegistryState},
    registry_handlers,
    seat::{SeatState, pointer::cursor_shape::CursorShapeManager},
    session_lock::{SessionLockState, SessionLockSurface},
    shell::{
        WaylandSurface,
        wlr_layer::{
            Anchor, KeyboardInteractivity, Layer, LayerShell, LayerShellHandler, LayerSurface,
            LayerSurfaceConfigure,
        },
        xdg::popup::Popup,
    },
};
use wayland_backend::sys::client::ObjectId;
use wayland_protocols::ext::background_effect::v1::client::{
    ext_background_effect_manager_v1::ExtBackgroundEffectManagerV1,
    ext_background_effect_surface_v1::ExtBackgroundEffectSurfaceV1,
};

use std::cell::Cell;

use super::backdrop::Backdrop;
use super::input::InputState;
use super::lock::Lock;
use super::outputs::OutputRegistry;
use super::popups::Popups;
use super::scaling::{Scaling, SurfaceScaling};
use super::selections::Selections;
use crate::outputs::{self};
use crate::region::RegionRect;
use crate::surface::SurfaceId;
use crate::widgets::{Event, Rect};

/// The shell role of a surface: an ordinary layer-shell surface or an
/// ext-session-lock-v1 lock surface. Both share the same widget tree, GPU
/// and input pipeline; only creation, configure, and shell requests differ.
pub enum SurfaceRole {
    Layer(LayerSurface),
    /// Kept alive here — dropping it destroys the protocol object.
    Lock(SessionLockSurface),
    /// An xdg popup anchored to another surface. Kept alive here —
    /// dropping it destroys the xdg objects. The config is retained to
    /// rebuild positioners for repositioning (auto-height growth).
    Popup {
        popup: Popup,
        config: crate::surface::PopupConfig,
        /// The surface this popup is anchored to — used to tear down popup
        /// chains in protocol order (children before parents).
        parent: crate::surface::SurfaceId,
    },
}

/// Events from the session-lock protocol, drained by the main loop.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LockEvent {
    /// The compositor granted the lock; lock surfaces may be created.
    Locked,
    /// The lock ended: denied outright, or unlocked/aborted later.
    Finished,
}

/// Per-surface state for multi-surface support.
pub struct WaylandSurfaceState {
    /// The shell role (layer surface or session-lock surface)
    pub role: SurfaceRole,
    /// The underlying wl_surface
    pub wl_surface: wl_surface::WlSurface,
    /// Whether the surface has been configured
    pub configured: bool,
    /// Logical width of the surface
    pub width: u32,
    /// Logical height of the surface
    pub height: u32,
    /// Scale factor for HiDPI
    pub scale_factor: f32,
    /// The frame callbacks in flight and what the compositor has confirmed —
    /// what the frame-pacing gate is decided from.
    pub(crate) pacing: crate::surface::FramePacing,
    /// Events waiting for the next frame, each with when it happened.
    ///
    /// The instant travels with the event because the two are separated in
    /// time: an event is queued when the compositor sends it and read when the
    /// frame runs, and the gap between those is exactly what a handler reading
    /// the clock for itself would mistake for the event's own time.
    pub pending_events: Vec<(std::time::Instant, Event)>,
    /// Blur proxy for this surface, created lazily on first use (asking the
    /// manager twice for the same surface is a protocol error).
    pub(super) bg_effect_surface: Option<ExtBackgroundEffectSurfaceV1>,
    /// Last blur rects pushed to the compositor. `None` means nothing has
    /// been pushed yet (also reset when the blur capability changes, so the
    /// region is re-sent if it comes back).
    pub(super) blur_region: Option<Vec<RegionRect>>,
    /// Set when the compositor's blur capability changes, so a surface that is
    /// not repainting knows it owes a region — and, the rest of the time, knows
    /// it does not. See
    /// [`take_blur_resync`](WaylandState::take_blur_resync).
    pub(super) blur_resync_owed: bool,
    /// Height sent in an in-flight popup reposition (cleared by the popup
    /// configure), so repeated content measurements don't re-send it.
    pub(super) pending_popup_height: Option<u32>,
    /// Fractional scale and viewport, where the compositor offers both — see
    /// [`super::scaling`]. `None` is a compositor that does not, and the
    /// integer `set_buffer_scale` path.
    pub(super) scaling: Option<SurfaceScaling>,
}

impl WaylandSurfaceState {
    /// Create a new surface state.
    pub fn new(
        role: SurfaceRole,
        wl_surface: wl_surface::WlSurface,
        width: u32,
        height: u32,
        scaling: Option<SurfaceScaling>,
    ) -> Self {
        Self {
            role,
            wl_surface,
            configured: false,
            width,
            height,
            scale_factor: 1.0,
            pacing: crate::surface::FramePacing::default(),
            pending_events: Vec::new(),
            bg_effect_surface: None,
            blur_region: None,
            blur_resync_owed: false,
            pending_popup_height: None,
            scaling,
        }
    }

    /// Take all pending events (drains the queue)
    pub fn take_events(&mut self) -> Vec<(std::time::Instant, Event)> {
        std::mem::take(&mut self.pending_events)
    }

    /// Record the scale this surface renders at, and answer whether it moved.
    ///
    /// One writer, because the scale arrives through two events —
    /// `preferred_buffer_scale` for a surface without a viewport and
    /// `wp_fractional_scale_v1.preferred_scale` for one with — and two
    /// spellings of it would be two chances to floor it differently.
    ///
    /// The rule itself is [`crate::surface::adopted_scale`], where a test can
    /// reach it; what is here is the field it writes.
    pub(super) fn adopt_scale(&mut self, scale: f32) -> bool {
        let (scale, moved) = crate::surface::adopted_scale(self.scale_factor, scale);
        self.scale_factor = scale;
        moved
    }
}

thread_local! {
    /// Which surface a [`batch_layer_requests`](WaylandState::batch_layer_requests)
    /// group is open on: its requests hold their commit so the group makes one.
    ///
    /// The *id*, not a flag. The closure is handed a whole `&mut WaylandState`,
    /// so it can address any surface it likes, and a flag suppressed the commit
    /// of every one of them while promising it for exactly one: a request aimed
    /// at another surface stayed double-buffered until something unrelated
    /// committed that surface, which for an idle one is never.
    ///
    /// A dynamic scope rather than a field, because the scope has to survive a
    /// panic. The closure gets `&mut WaylandState`, so a guard restoring a field
    /// could not hold on to it while the closure runs — and a scope left open by
    /// an unwind would be permanent: every later `set_margin` or `set_layer`
    /// would hold its commit for a group that had already ended, and the surface
    /// would stop answering its handle in silence.
    static BATCHING: Cell<Option<SurfaceId>> = const { Cell::new(None) };
}

pub struct WaylandState {
    /// The connection every surface is built on. Held for the same reason as
    /// the queue below it: a target is made from a window handle, and a window
    /// handle is made from this — so a loop that did not hold one could not ask
    /// for a surface without being handed the connection as well.
    pub(crate) connection: Connection,
    /// The queue every protocol request made from here goes onto.
    ///
    /// Held rather than passed: the frame path used to thread a
    /// `&QueueHandle<WaylandState>` through `layout_pass` and
    /// `paint_and_present` for the two or three calls that needed one, which
    /// made every function between here and there name a Wayland type it had
    /// no other use for. The handle is `Clone` and refers to the queue, not to
    /// this state, so owning one costs nothing and closes that seam.
    pub(crate) qh: QueueHandle<WaylandState>,
    pub registry_state: RegistryState,
    pub compositor_state: CompositorState,
    pub output_state: OutputState,
    pub seat_state: SeatState,
    pub layer_shell: LayerShell,

    // Multi-surface tracking
    /// All surfaces indexed by SurfaceId
    pub surfaces: FxHashMap<SurfaceId, WaylandSurfaceState>,
    /// Lookup from wl_surface ObjectId to SurfaceId
    pub surface_lookup: FxHashMap<ObjectId, SurfaceId>,
    /// Which surface currently has pointer focus
    pub current_pointer_surface: Option<SurfaceId>,
    /// Which surface currently has keyboard focus
    pub current_keyboard_surface: Option<SurfaceId>,

    /// Stable identity for the compositor's outputs — see [`super::outputs`].
    pub(super) outputs: OutputRegistry<ObjectId>,

    /// Compositor-side backdrop blur — see [`super::backdrop`].
    pub(super) backdrop: Backdrop,

    /// xdg popups anchored to a surface — see [`super::popups`].
    pub(super) popups: Popups,

    /// Session lock grant and events — see [`super::lock`].
    pub(super) lock: Lock,

    /// Fractional scaling and viewports, where the compositor offers both
    /// globals — see [`super::scaling`].
    pub(super) scaling: Option<Scaling>,

    /// Pointer, touch and keyboard — see [`super::input`].
    pub(super) input: InputState,

    /// Clipboard and primary selection — see [`super::selections`].
    pub(super) selections: Selections,
}

/// Why the platform layer could not start or continue.
///
/// These are ordinary environmental conditions (no Wayland session, a
/// compositor without layer-shell such as GNOME, a dropped connection, no GPU
/// to draw a surface with) — they are reported instead of panicking the
/// process.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PlatformError {
    /// Could not connect to a Wayland display (no session / wrong env).
    Connect,
    /// Wayland registry initialization failed.
    Registry,
    /// The compositor does not advertise `wl_compositor`.
    MissingCompositor,
    /// The compositor does not support `zwlr_layer_shell_v1` (e.g. GNOME).
    MissingLayerShell,
    /// The Wayland connection failed while the app was running.
    ConnectionLost,
    /// No Vulkan adapter could draw the surface that asked for one.
    NoGpu,
}

impl std::fmt::Display for PlatformError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Connect => write!(f, "failed to connect to a Wayland display"),
            Self::Registry => write!(f, "failed to initialize the Wayland registry"),
            Self::MissingCompositor => write!(f, "compositor does not advertise wl_compositor"),
            Self::MissingLayerShell => {
                write!(
                    f,
                    "compositor does not support zwlr_layer_shell_v1 (layer shell)"
                )
            }
            Self::ConnectionLost => write!(f, "Wayland connection lost"),
            Self::NoGpu => write!(f, "no usable Vulkan adapter"),
        }
    }
}

impl std::error::Error for PlatformError {}

pub fn create_wayland_app(
    loop_handle: LoopHandle<'static, WaylandState>,
) -> Result<(Connection, EventQueue<WaylandState>, WaylandState), PlatformError> {
    let connection = Connection::connect_to_env().map_err(|e| {
        log::error!("Failed to connect to Wayland: {e}");
        PlatformError::Connect
    })?;
    let (globals, event_queue) = registry_queue_init::<WaylandState>(&connection).map_err(|e| {
        log::error!("Failed to initialize Wayland registry: {e}");
        PlatformError::Registry
    })?;
    let qh = event_queue.handle();

    let compositor_state =
        CompositorState::bind(&globals, &qh).map_err(|_| PlatformError::MissingCompositor)?;
    let layer_shell = LayerShell::bind(&globals, &qh).map_err(|_| {
        log::error!(
            "This compositor does not support the layer shell protocol; \
             guido surfaces cannot be created"
        );
        PlatformError::MissingLayerShell
    })?;
    let output_state = OutputState::new(&globals, &qh);
    let seat_state = SeatState::new(&globals, &qh);
    let session_lock_state = SessionLockState::new(&globals, &qh);

    // xdg shell for popups anchored to layer surfaces — optional
    let wm_base = super::popups::WmBase::bind(&globals, &qh).ok();
    if wm_base.is_none() {
        log::warn!("xdg_wm_base not available - popups will not work");
    }

    // Initialize data device manager for clipboard support
    let data_device_manager = DataDeviceManagerState::bind(&globals, &qh).ok();
    if data_device_manager.is_none() {
        log::warn!("Data device manager not available - clipboard will not work");
    }

    // Primary selection (select-to-copy / middle-click paste) — optional
    let primary_selection_manager = PrimarySelectionManagerState::bind(&globals, &qh).ok();
    if primary_selection_manager.is_none() {
        log::info!("Primary selection manager not available - middle-click paste will not work");
    }

    // Initialize cursor shape manager for cursor changes
    let cursor_shape_manager = CursorShapeManager::bind(&globals, &qh).ok();
    if cursor_shape_manager.is_none() {
        log::warn!("Cursor shape manager not available - cursor changes will not work");
    }

    // Background effect manager (blur) — optional, no-ops when unsupported
    let bg_effect_manager: Option<ExtBackgroundEffectManagerV1> = globals.bind(&qh, 1..=1, ()).ok();
    if bg_effect_manager.is_none() {
        log::info!("ext-background-effect-v1 not available - background blur will not work");
    }

    let state = WaylandState {
        connection: connection.clone(),
        qh: qh.clone(),
        registry_state: RegistryState::new(&globals),
        compositor_state,
        output_state,
        seat_state,
        layer_shell,
        surfaces: FxHashMap::default(),
        surface_lookup: FxHashMap::default(),
        current_pointer_surface: None,
        current_keyboard_surface: None,
        outputs: OutputRegistry::new(),
        backdrop: Backdrop::new(bg_effect_manager),
        popups: Popups::new(wm_base),
        lock: Lock::new(session_lock_state),
        scaling: Scaling::bind(&globals, &qh),
        input: InputState::new(cursor_shape_manager, loop_handle),
        selections: Selections::new(data_device_manager, primary_selection_manager),
    };

    Ok((connection, event_queue, state))
}

/// An open group of layer-shell requests, held for as long as the group lasts.
///
/// A scope a panic can leave open is not a scope: left open, every later
/// layer-shell request holds its commit for a group that ended and the surface
/// stops answering its handle, in silence. So closing is `Drop`'s, and the
/// commit — which a panicking group has not earned — is
/// [`close_layer_batch`](WaylandState::close_layer_batch)'s.
pub(crate) struct LayerBatch {
    /// The surface this group is for. Held so a caller cannot close one group
    /// while committing another's.
    id: SurfaceId,
    /// What was open before, put back on the way out. Setting `None` instead
    /// would let a nested group close the one containing it, and every request
    /// after it would commit on its own.
    previous: Option<SurfaceId>,
    outermost: bool,
}

impl LayerBatch {
    pub(crate) fn open(id: SurfaceId) -> Self {
        let previous = BATCHING.with(|b| b.replace(Some(id)));
        Self {
            id,
            previous,
            outermost: previous != Some(id),
        }
    }

    pub(crate) fn is_outermost(&self) -> bool {
        self.outermost
    }
}

impl Drop for LayerBatch {
    fn drop(&mut self) {
        BATCHING.with(|b| b.set(self.previous));
    }
}

impl WaylandState {
    /// Ask for a `wl_surface.frame` callback on this surface.
    ///
    /// Requested before presenting so it rides the same commit as the buffer.
    /// The callback's arrival is what lets this surface render its next frame.
    pub fn request_frame_callback(&mut self, id: SurfaceId) {
        if let Some(surface) = self.surfaces.get(&id) {
            surface
                .wl_surface
                .frame(&self.qh, FrameCallbackData(surface.wl_surface.clone()));
        }
    }

    /// Report damaged buffer pixels, in buffer coordinates.
    ///
    /// Set before presenting: `present` attaches the buffer and commits the
    /// surface inside wgpu's Wayland path, so damage pending now is part of
    /// that commit. Damaging afterwards attaches it to an empty second commit
    /// the compositor cannot use.
    pub fn damage_surface(&mut self, id: SurfaceId, x: i32, y: i32, width: i32, height: i32) {
        if let Some(surface) = self.surfaces.get(&id) {
            surface.wl_surface.damage_buffer(x, y, width, height);
        }
    }

    /// The frame callback asked for before present is now committed, and this
    /// surface is gated until it fires.
    pub fn mark_frame_callback_pending(&mut self, id: SurfaceId) {
        if let Some(surface) = self.surfaces.get_mut(&id) {
            surface.pacing.committed();
        }
    }

    /// Build a wl_region from logical-coordinate rects, rounded outward so a
    /// fractional widget bound never loses its edge pixels.
    fn build_region(&self, rects: &[Rect]) -> Option<Region> {
        let region = Region::new(&self.compositor_state)
            .map_err(|e| log::warn!("Failed to create wl_region: {e}"))
            .ok()?;
        for r in rects.iter().copied().filter_map(RegionRect::covering) {
            region.add(r.x, r.y, r.width, r.height);
        }
        Some(region)
    }

    /// Apply an input region to a wl_surface. `None` restores the default
    /// (the whole surface accepts input); an empty slice is fully
    /// click-through.
    ///
    /// The `Region` is dropped (and the wl_region destroyed) right away:
    /// the protocol copies the region state at `set_input_region` time.
    fn apply_input_region(&self, wl_surface: &wl_surface::WlSurface, rects: Option<&[Rect]>) {
        match rects {
            None => wl_surface.set_input_region(None),
            Some(rects) => {
                let Some(region) = self.build_region(rects) else {
                    return;
                };
                wl_surface.set_input_region(Some(region.wl_region()));
            }
        }
    }

    /// Publish where input reaches a surface: the area it takes, then the
    /// declarations the frame made, in the order they were painted.
    ///
    /// `wl_region` is exactly this program — add and subtract — so a rounded
    /// hole cut out of a bar needs no complement computed anywhere.
    ///
    /// Not committed here by default: the request rides the buffer commit
    /// inside the upcoming present, so the region and the frame it was read
    /// off change together. `commit: true` is for the paths that skip
    /// presenting.
    pub(crate) fn sync_input_region(
        &mut self,
        id: SurfaceId,
        request: &crate::region::InputRegionRequest,
        commit: bool,
    ) {
        let Some(surface_state) = self.surfaces.get(&id) else {
            return;
        };
        let Ok(region) = Region::new(&self.compositor_state) else {
            log::warn!("Failed to create wl_region for input");
            return;
        };

        for r in &request.base {
            region.add(r.x, r.y, r.width, r.height);
        }
        for op in &request.ops {
            let r = op.rect;
            if op.takes {
                region.add(r.x, r.y, r.width, r.height);
            } else {
                region.subtract(r.x, r.y, r.width, r.height);
            }
        }
        surface_state
            .wl_surface
            .set_input_region(Some(region.wl_region()));

        log::debug!(
            "Surface {:?} input region: {} base rect(s), {} declaration(s)",
            id,
            request.base.len(),
            request.ops.len()
        );

        if commit {
            surface_state.wl_surface.commit();
        }
    }

    /// Set the input region for a surface at runtime.
    pub fn set_surface_input_region(&mut self, id: SurfaceId, rects: Option<&[Rect]>) {
        if let Some(surface_state) = self.surfaces.get(&id) {
            self.apply_input_region(&surface_state.wl_surface, rects);
            surface_state.wl_surface.commit();
            log::info!(
                "Surface {:?} input region set to {}",
                id,
                match rects {
                    None => "full surface".to_string(),
                    Some(r) => format!("{} rect(s)", r.len()),
                }
            );
        }
    }
    /// Create a layer surface with a specific SurfaceId.
    pub fn create_surface_with_id(
        &mut self,
        id: SurfaceId,
        config: &crate::surface::SurfaceConfig,
    ) {
        let qh = &self.qh;
        // Resolve the requested output; fall back to letting the compositor
        // choose if it was disconnected in the meantime.
        let target_output = config.output.and_then(|oid| {
            let found = self.wl_output_for(oid);
            if found.is_none() {
                log::warn!(
                    "Surface {:?} requested output {:?} which is not connected; \
                     letting the compositor choose",
                    id,
                    oid
                );
            }
            found
        });

        let wl_surface = self.compositor_state.create_surface(qh);
        let layer_surface = self.layer_shell.create_layer_surface(
            qh,
            wl_surface.clone(),
            config.layer,
            Some(config.namespace.clone()),
            target_output.as_ref(),
        );

        layer_surface.set_anchor(config.anchor);

        // When anchored to both edges on an axis, the compositor owns
        // that dimension: set it to 0 so it stretches. Content sizing on
        // such an axis can never take effect — warn loudly.
        crate::surface::warn_content_on_stretched_axis(id, config);
        let declared = crate::surface::initial_declaration(config);
        let (initial_width, initial_height) = declared.believed;

        layer_surface.set_size(declared.asked.0, declared.asked.1);
        layer_surface.set_keyboard_interactivity(config.keyboard_interactivity);
        layer_surface.set_exclusive_zone(declared.exclusive_zone);

        let margin = config.margin;
        if !margin.is_zero() {
            layer_surface.set_margin(margin.top, margin.right, margin.bottom, margin.left);
        }

        if let Some(rects) = &declared.input_region {
            self.apply_input_region(&wl_surface, Some(rects));
        }

        // Before the commit, so the compositor can answer with a scale on the
        // same round trip as the first configure.
        let scaling = self.create_surface_scaling(id, &wl_surface);

        wl_surface.commit();

        // Register in lookup table
        let object_id = wl_surface.id();
        self.surface_lookup.insert(object_id, id);

        // Create and store surface state
        let surface_state = WaylandSurfaceState::new(
            SurfaceRole::Layer(layer_surface),
            wl_surface,
            initial_width,
            initial_height,
            scaling,
        );
        self.surfaces.insert(id, surface_state);

        log::info!(
            "Created surface {:?} with size {}x{}, anchor {:?}, layer {:?}, keyboard {:?}",
            id,
            initial_width,
            initial_height,
            config.anchor,
            config.layer,
            config.keyboard_interactivity
        );
    }

    /// Destroy a surface by its SurfaceId.
    pub fn destroy_surface(&mut self, id: SurfaceId) {
        if let Some(surface_state) = self.surfaces.remove(&id) {
            // Remove from lookup table
            let object_id = surface_state.wl_surface.id();
            self.surface_lookup.remove(&object_id);

            // Destroy the blur proxy before its wl_surface goes away
            if let Some(effect) = surface_state.bg_effect_surface {
                effect.destroy();
            }

            // And the fractional scale and viewport, for the same reason.
            if let Some(scaling) = surface_state.scaling {
                scaling.destroy();
            }

            // Clear pointer/keyboard focus if this surface had it
            if self.current_pointer_surface == Some(id) {
                self.current_pointer_surface = None;
            }
            if self.current_keyboard_surface == Some(id) {
                self.current_keyboard_surface = None;
            }

            // Drop reactive output tracking for the closed surface
            outputs::surface_closed(id);

            // The LayerSurface and WlSurface will be destroyed when dropped
            log::info!("Destroyed surface {:?}", id);
        }
    }

    /// Apply several layer-shell requests as one change.
    ///
    /// `with_layer_surface` commits after each
    /// request, which is right for one on its own and wrong for a group:
    /// re-anchoring sends the anchor, the size and the reservation, and three
    /// commits is two of them showing the compositor a surface halfway between
    /// two configurations — before this, an app animating a dock's margin sent a
    /// redundant pair every frame.
    ///
    /// The commit is the group's, so it is subject to the same rule each request
    /// is: only a layer surface has these properties, and a batch aimed at a
    /// session-lock or popup surface applies nothing. Committing anyway would
    /// send a bare commit to exactly the roles the per-request path refuses to
    /// touch.
    /// Start grouping this surface's layer requests.
    ///
    /// Split from [`batch_layer_requests`](Self::batch_layer_requests) so a
    /// caller that already holds a borrow of this state — the per-surface
    /// handle the frame path uses — can group without handing the whole state
    /// to a closure it cannot produce.
    pub(crate) fn open_layer_batch(&mut self, id: SurfaceId) -> LayerBatch {
        LayerBatch::open(id)
    }

    /// End the group, and commit if this was the outermost one.
    pub(crate) fn close_layer_batch(&mut self, batch: LayerBatch) {
        let (id, outermost) = (batch.id, batch.is_outermost());
        drop(batch);
        if outermost
            && let Some(state) = self.surfaces.get(&id)
            && matches!(state.role, SurfaceRole::Layer(_))
        {
            state.wl_surface.commit();
        }
    }

    /// Helper to modify a surface's layer shell properties and commit.
    /// No-ops (with a warning) on session-lock surfaces, which have none.
    fn with_layer_surface<F>(&mut self, id: SurfaceId, f: F)
    where
        F: FnOnce(&LayerSurface),
    {
        // Only for the surface the open group will commit for. Another one's
        // request has nobody to ride with, so it commits for itself.
        let batching = BATCHING.with(|b| b.get()) == Some(id);
        if let Some(surface_state) = self.surfaces.get_mut(&id) {
            match &surface_state.role {
                SurfaceRole::Layer(layer_surface) => {
                    f(layer_surface);
                    if !batching {
                        surface_state.wl_surface.commit();
                    }
                }
                SurfaceRole::Lock(_) | SurfaceRole::Popup { .. } => {
                    log::warn!(
                        "Ignoring layer-shell property change on non-layer surface {:?}",
                        id
                    );
                }
            }
        }
    }

    /// Set the layer for a surface.
    pub fn set_surface_layer(&mut self, id: SurfaceId, layer: Layer) {
        self.with_layer_surface(id, |ls| ls.set_layer(layer));
        log::info!("Surface {:?} layer set to {:?}", id, layer);
    }

    /// Set the keyboard interactivity for a surface.
    pub fn set_surface_keyboard_interactivity(
        &mut self,
        id: SurfaceId,
        mode: KeyboardInteractivity,
    ) {
        self.with_layer_surface(id, |ls| ls.set_keyboard_interactivity(mode));
        log::info!("Surface {:?} keyboard interactivity set to {:?}", id, mode);
    }

    /// Set the anchor edges for a surface.
    pub fn set_surface_anchor(&mut self, id: SurfaceId, anchor: Anchor) {
        self.with_layer_surface(id, |ls| ls.set_anchor(anchor));
        log::info!("Surface {:?} anchor set to {:?}", id, anchor);
    }

    /// Set the size of a surface.
    pub fn set_surface_size(&mut self, id: SurfaceId, width: u32, height: u32) {
        self.with_layer_surface(id, |ls| ls.set_size(width, height));
        log::info!("Surface {:?} size set to {}x{}", id, width, height);
    }

    /// Set the exclusive zone for a surface.
    pub fn set_surface_exclusive_zone(&mut self, id: SurfaceId, zone: i32) {
        self.with_layer_surface(id, |ls| ls.set_exclusive_zone(zone));
        log::info!("Surface {:?} exclusive zone set to {}", id, zone);
    }

    /// Set the margin for a surface.
    pub fn set_surface_margin(&mut self, id: SurfaceId, margin: crate::surface::Margin) {
        self.with_layer_surface(id, |ls| {
            ls.set_margin(margin.top, margin.right, margin.bottom, margin.left)
        });
        log::info!("Surface {:?} margin set to {:?}", id, margin);
    }

    /// Get a surface state by SurfaceId.
    pub fn get_surface(&self, id: SurfaceId) -> Option<&WaylandSurfaceState> {
        self.surfaces.get(&id)
    }

    /// Get a mutable surface state by SurfaceId.
    pub fn get_surface_mut(&mut self, id: SurfaceId) -> Option<&mut WaylandSurfaceState> {
        self.surfaces.get_mut(&id)
    }

    /// Get a surface ID from a wl_surface.
    pub fn surface_id_from_wl_surface(
        &self,
        wl_surface: &wl_surface::WlSurface,
    ) -> Option<SurfaceId> {
        self.surface_lookup.get(&wl_surface.id()).copied()
    }

    /// Check if all surfaces are configured.
    pub fn all_surfaces_configured(&self) -> bool {
        self.surfaces.values().all(|s| s.configured)
    }
}

pub struct WaylandWindowWrapper {
    display: *mut std::ffi::c_void,
    surface: *mut std::ffi::c_void,
}

impl WaylandWindowWrapper {
    pub fn new(connection: &Connection, surface: &wl_surface::WlSurface) -> Self {
        // Get raw pointers using wayland-backend's sys module
        // The ObjectId in sys backend has as_ptr() method
        let backend = connection.backend();

        // Get display pointer - this is the wl_display*
        let display_ptr = backend.display_ptr() as *mut std::ffi::c_void;

        // Get surface pointer - need to convert the wayland-client ObjectId to sys ObjectId
        // The surface.id() returns a wayland_backend::client::ObjectId
        // We need to get the raw wl_proxy* pointer from it
        let surface_id = surface.id();
        let surface_ptr = ObjectId::as_ptr(&surface_id) as *mut std::ffi::c_void;

        Self {
            display: display_ptr,
            surface: surface_ptr,
        }
    }
}

unsafe impl Send for WaylandWindowWrapper {}
unsafe impl Sync for WaylandWindowWrapper {}

impl HasDisplayHandle for WaylandWindowWrapper {
    fn display_handle(&self) -> Result<DisplayHandle<'_>, HandleError> {
        let handle = WaylandDisplayHandle::new(
            std::ptr::NonNull::new(self.display).expect("display ptr is null"),
        );
        Ok(unsafe { DisplayHandle::borrow_raw(RawDisplayHandle::Wayland(handle)) })
    }
}

impl HasWindowHandle for WaylandWindowWrapper {
    fn window_handle(&self) -> Result<WindowHandle<'_>, HandleError> {
        let handle = WaylandWindowHandle::new(
            std::ptr::NonNull::new(self.surface).expect("surface ptr is null"),
        );
        Ok(unsafe { WindowHandle::borrow_raw(RawWindowHandle::Wayland(handle)) })
    }
}

impl CompositorHandler for WaylandState {
    fn scale_factor_changed(
        &mut self,
        _conn: &Connection,
        _qh: &QueueHandle<Self>,
        surface: &wl_surface::WlSurface,
        new_factor: i32,
    ) {
        // Find which surface this is for
        if let Some(id) = self.surface_lookup.get(&surface.id()).copied()
            && let Some(surface_state) = self.surfaces.get_mut(&id)
        {
            // `preferred_buffer_scale` is the compositor rounding its real
            // preference up to an integer, because this event has no way to
            // say 1.5. A surface with a fractional scale has already been told
            // the number itself, and its buffer scale must stay 1: the
            // protocol requires it, and a buffer the viewport has already
            // sized would otherwise be multiplied a second time.
            if surface_state.scaling.is_some() {
                log::debug!(
                    "Surface {id:?} ignoring preferred buffer scale {new_factor}: \
                     it is scaled fractionally"
                );
                return;
            }
            if surface_state.adopt_scale(new_factor as f32) {
                log::info!("Surface {:?} scale factor changed to: {}", id, new_factor);
            }
        }

        // Set the buffer scale on the surface for proper HiDPI rendering
        surface.set_buffer_scale(new_factor);
    }

    fn transform_changed(
        &mut self,
        _conn: &Connection,
        _qh: &QueueHandle<Self>,
        _surface: &wl_surface::WlSurface,
        _new_transform: wl_output::Transform,
    ) {
    }

    fn surface_enter(
        &mut self,
        _conn: &Connection,
        _qh: &QueueHandle<Self>,
        surface: &wl_surface::WlSurface,
        output: &wl_output::WlOutput,
    ) {
        if let Some(surface_id) = self.surface_lookup.get(&surface.id()).copied()
            && let Some(output_id) = self.outputs.id_for(&output.id())
        {
            log::debug!("Surface {:?} entered output {:?}", surface_id, output_id);
            outputs::surface_entered_output(surface_id, output_id);
        }
    }

    fn surface_leave(
        &mut self,
        _conn: &Connection,
        _qh: &QueueHandle<Self>,
        surface: &wl_surface::WlSurface,
        output: &wl_output::WlOutput,
    ) {
        if let Some(surface_id) = self.surface_lookup.get(&surface.id()).copied()
            && let Some(output_id) = self.outputs.id_for(&output.id())
        {
            log::debug!("Surface {:?} left output {:?}", surface_id, output_id);
            outputs::surface_left_output(surface_id, output_id);
        }
    }

    fn frame(
        &mut self,
        _conn: &Connection,
        _qh: &QueueHandle<Self>,
        surface: &wl_surface::WlSurface,
        _time: u32,
    ) {
        // The compositor consumed the last frame: this surface may render
        // again. Callbacks are re-armed on every present (see
        // render_surface), so this is the pacing signal for the surface.
        if let Some(id) = self.surface_lookup.get(&surface.id()).copied()
            && let Some(surface_state) = self.surfaces.get_mut(&id)
        {
            surface_state.pacing.callback_done();
            // Wake the loop so a dirty surface renders promptly
            crate::jobs::wake_loop();
        }
    }
}

impl LayerShellHandler for WaylandState {
    fn closed(&mut self, _conn: &Connection, _qh: &QueueHandle<Self>, layer: &LayerSurface) {
        // O(1) lookup via the wl_surface object id
        let closed_id = self.surface_lookup.get(&layer.wl_surface().id()).copied();

        if let Some(id) = closed_id {
            log::info!("Surface {:?} closed by compositor", id);
            // Route through the normal close command so the managed surface
            // is fully cleaned up (widgets, reactive owner, wgpu surface —
            // dropped BEFORE the wl_surface it borrows). Previously only the
            // Wayland-side state was removed, leaking the widget tree and
            // leaving a zombie surface iterated every frame.
            crate::surface::push_surface_command(crate::surface::SurfaceCommand::Close(id));
        }
    }

    fn configure(
        &mut self,
        _conn: &Connection,
        _qh: &QueueHandle<Self>,
        layer: &LayerSurface,
        configure: LayerSurfaceConfigure,
        _serial: u32,
    ) {
        // O(1) lookup via the wl_surface object id (fires on every resize)
        let surface_id = self.surface_lookup.get(&layer.wl_surface().id()).copied();

        if let Some(id) = surface_id
            && let Some(surface_state) = self.surfaces.get_mut(&id)
        {
            log::info!(
                "Surface {:?} configure: requested size {:?}, current {}x{}",
                id,
                configure.new_size,
                surface_state.width,
                surface_state.height
            );
            if configure.new_size.0 > 0 {
                surface_state.width = configure.new_size.0;
            }
            if configure.new_size.1 > 0 {
                surface_state.height = configure.new_size.1;
            }
            log::info!(
                "Surface {:?} using size: {}x{}",
                id,
                surface_state.width,
                surface_state.height
            );
            surface_state.configured = true;
        }
    }
}

impl ProvidesRegistryState for WaylandState {
    fn registry(&mut self) -> &mut RegistryState {
        &mut self.registry_state
    }

    registry_handlers![OutputState, SeatState];
}

delegate_registry!(WaylandState);

// Every sctk object guido binds, dispatched through the data type sctk
// attaches to it.
smithay_client_toolkit::delegate_dispatch2!(WaylandState);

#[cfg(test)]
mod batching_tests {
    use super::{BATCHING, LayerBatch, SurfaceId};

    /// The guard alone, without a state to commit on.
    fn batching<R>(id: SurfaceId, f: impl FnOnce() -> R) -> (bool, R) {
        let batch = LayerBatch::open(id);
        let outermost = batch.is_outermost();
        (outermost, f())
    }

    /// Distinct ids; the counter is global and the numbers do not matter.
    fn surface() -> SurfaceId {
        SurfaceId::next()
    }

    /// A batch is a scope, and a scope that a panic can leave open is not one.
    /// Left open, every later layer-shell request holds its commit for a group
    /// that ended, and the surface stops answering its handle in silence.
    #[test]
    fn a_panic_inside_a_batch_still_closes_it() {
        let escaped = std::panic::catch_unwind(|| {
            batching(surface(), || panic!("a request went wrong"));
        });
        assert!(escaped.is_err(), "the panic still propagates");
        assert!(
            BATCHING.with(|b| b.get()).is_none(),
            "and the scope closed on its way out"
        );
    }

    /// A nested group ends without ending the one containing it. Setting the
    /// scope to `None` on the way out instead reads the same from inside the
    /// outer group and lets every request after the inner one commit on its
    /// own — which is the state the grouping exists to prevent.
    #[test]
    fn an_inner_batch_leaves_the_outer_one_open() {
        let (a, b) = (surface(), surface());
        let outer = LayerBatch::open(a);
        {
            let _inner = LayerBatch::open(b);
        }
        assert_eq!(
            BATCHING.with(|s| s.get()),
            Some(a),
            "the outer group is still the one open"
        );
        drop(outer);
        assert!(BATCHING.with(|s| s.get()).is_none(), "and then nothing is");
    }

    /// Only the outermost group commits, or a nested batch would commit halfway
    /// through the one containing it.
    #[test]
    fn only_the_outermost_batch_reports_itself() {
        let a = surface();
        let (outermost, inner) = batching(a, || batching(a, || ()).0);
        assert!(outermost, "the outer one opened the scope");
        assert!(!inner, "the inner one found it already open");
        assert!(BATCHING.with(|b| b.get()).is_none());
    }

    /// The scope belongs to a surface, not to the thread. A request aimed at
    /// another surface inside an open group has nobody to ride with: suppressing
    /// its commit leaves it double-buffered until something unrelated commits
    /// that surface, which for an idle one is never.
    #[test]
    fn a_batch_on_one_surface_does_not_hold_another_one_s_commit() {
        let (a, b) = (surface(), surface());
        let mut seen = None;
        let (outer, inner) = batching(a, || {
            seen = Some(BATCHING.with(|s| s.get()));
            batching(b, || ()).0
        });
        assert!(outer, "the group on a commits for a");
        assert!(inner, "and the one on b commits for b, rather than nothing");
        assert_eq!(seen, Some(Some(a)), "inside, the open group is a's");
        assert!(BATCHING.with(|s| s.get()).is_none());
    }
}