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
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
//! The Wayland window.

use std::ffi::c_void;
use std::ptr::NonNull;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};

use sctk::reexports::client::protocol::wl_display::WlDisplay;
use sctk::reexports::client::protocol::wl_surface::WlSurface;
use sctk::reexports::client::{Proxy, QueueHandle};

use sctk::compositor::{CompositorState, Region, SurfaceData};
use sctk::reexports::protocols::xdg::activation::v1::client::xdg_activation_v1::XdgActivationV1;
use sctk::shell::xdg::window::{Window as SctkWindow, WindowDecorations};
use sctk::shell::WaylandSurface;

use tracing::{debug, warn};

use crate::dpi::{LogicalSize, PhysicalPosition, PhysicalSize, Position, Size};
use crate::error::{ExternalError, NotSupportedError, OsError as RootOsError};
use crate::event::{Ime, WindowEvent};
use crate::event_loop::AsyncRequestSerial;
use crate::platform_impl::{
    Fullscreen, MonitorHandle as PlatformMonitorHandle, OsError, PlatformIcon,
};
use crate::window::{
    Cursor, CursorGrabMode, ImePurpose, ResizeDirection, Theme, UserAttentionType,
    WindowAttributes, WindowButtons, WindowLevel,
};

use super::event_loop::sink::EventSink;
use super::output::MonitorHandle;
use super::state::WinitState;
use super::types::xdg_activation::XdgActivationTokenData;
use super::types::xdg_toplevel_icon::WindowToplevelIcon;
use super::{ActiveEventLoop, WaylandError, WindowId};

pub(crate) mod state;

pub use state::WindowState;

/// The Wayland window.
pub struct Window {
    /// Reference to the underlying SCTK window.
    window: SctkWindow,

    /// Window id.
    window_id: WindowId,

    /// The state of the window.
    window_state: Arc<Mutex<WindowState>>,

    /// Compositor to handle WlRegion stuff.
    compositor: Arc<CompositorState>,

    /// The wayland display used solely for raw window handle.
    #[allow(dead_code)]
    display: WlDisplay,

    /// Xdg activation to request user attention.
    xdg_activation: Option<XdgActivationV1>,

    /// Per-window xdg-toplevel-icon setter, if the compositor supports it.
    toplevel_icon: Option<Mutex<WindowToplevelIcon>>,

    /// The state of the requested attention from the `xdg_activation`.
    attention_requested: Arc<AtomicBool>,

    /// Handle to the main queue to perform requests.
    queue_handle: QueueHandle<WinitState>,

    /// Window requests to the event loop.
    window_requests: Arc<WindowRequests>,

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

    /// Source to wake-up the event-loop for window requests.
    event_loop_awakener: calloop::ping::Ping,

    /// The event sink to deliver synthetic events.
    window_events_sink: Arc<Mutex<EventSink>>,

    /// Whether the Halo overlay mode was sent for this surface.
    halo_header_overlay: bool,
}

impl Window {
    pub(crate) fn new(
        event_loop_window_target: &ActiveEventLoop,
        attributes: WindowAttributes,
    ) -> Result<Self, RootOsError> {
        let queue_handle = event_loop_window_target.queue_handle.clone();
        let mut state = event_loop_window_target.state.borrow_mut();

        let monitors = state.monitors.clone();

        let surface = state.compositor_state.create_surface(&queue_handle);
        let compositor = state.compositor_state.clone();
        let xdg_activation =
            state.xdg_activation.as_ref().map(|activation_state| activation_state.global().clone());
        let toplevel_icon = state
            .toplevel_icon_manager
            .as_ref()
            .and_then(|manager| manager.icon_for_window(&state.shm))
            .map(Mutex::new);
        let display = event_loop_window_target.connection.display();

        let size: Size = attributes.inner_size.unwrap_or(LogicalSize::new(800., 600.).into());

        // We prefer server side decorations, however to not have decorations we ask for client
        // side decorations instead.
        let default_decorations = if attributes.decorations {
            WindowDecorations::RequestServer
        } else {
            WindowDecorations::RequestClient
        };

        let window =
            state.xdg_shell.create_window(surface.clone(), default_decorations, &queue_handle);

        let mut window_state = WindowState::new(
            event_loop_window_target.connection.clone(),
            &event_loop_window_target.queue_handle,
            &state,
            size,
            window.clone(),
            attributes.preferred_theme,
        );

        // Set transparency hint.
        window_state.set_transparent(attributes.transparent);

        window_state.set_blur(attributes.blur);

        // Set the decorations hint.
        window_state.set_decorate(attributes.decorations);

        // Set the app_id.
        if let Some(name) = attributes.platform_specific.name.map(|name| name.general) {
            window.set_app_id(name);
        }

        // Set the window title.
        window_state.set_title(attributes.title);

        // Set the min and max sizes. We must set the hints upon creating a window, so
        // we use the default `1.` scaling...
        let min_size = attributes.min_inner_size.map(|size| size.to_logical(1.));
        let max_size = attributes.max_inner_size.map(|size| size.to_logical(1.));
        window_state.set_min_inner_size(min_size);
        window_state.set_max_inner_size(max_size);

        // Non-resizable implies that the min and max sizes are set to the same value.
        window_state.set_resizable(attributes.resizable);

        // Set startup mode.
        match attributes.fullscreen.map(Into::into) {
            Some(Fullscreen::Exclusive(_)) => {
                warn!("`Fullscreen::Exclusive` is ignored on Wayland");
            },
            #[cfg_attr(not(x11_platform), allow(clippy::bind_instead_of_map))]
            Some(Fullscreen::Borderless(monitor)) => {
                let output = monitor.and_then(|monitor| match monitor {
                    PlatformMonitorHandle::Wayland(monitor) => Some(monitor.proxy),
                    #[cfg(x11_platform)]
                    PlatformMonitorHandle::X(_) => None,
                });

                window.set_fullscreen(output.as_ref())
            },
            _ if attributes.maximized => window.set_maximized(),
            _ => (),
        };

        match attributes.cursor {
            Cursor::Icon(icon) => window_state.set_cursor(icon),
            Cursor::Custom(cursor) => window_state.set_custom_cursor(cursor),
        }

        // Activate the window when the token is passed.
        if let (Some(xdg_activation), Some(token)) =
            (xdg_activation.as_ref(), attributes.platform_specific.activation_token)
        {
            xdg_activation.activate(token.token, &surface);
        }

        // Parent this window to a foreign toplevel via xdg-foreign, if requested.
        // Used by portal file-chooser dialogs to attach to the requesting app's
        // window, so the compositor places the dialog over it on the right
        // output instead of dropping it on a default output. Must run before the
        // initial commit so the compositor knows the parent at map time.
        if let Some(handle) = attributes.platform_specific.wayland_parent.as_deref() {
            match state.xdg_foreign.as_ref() {
                Some(xdg_foreign) => {
                    let imported = xdg_foreign.import_parent(handle, &surface, &queue_handle);
                    window_state.set_imported_parent(imported);
                },
                None => warn!(
                    "xdg-foreign unsupported by the compositor; cannot parent window to {handle}"
                ),
            }
        }

        // Give the Halo a drag strip over the window's top edge, if asked. The
        // protocol only accepts the mode between the toplevel role and the
        // initial commit, so this is its one chance.
        let halo_header_overlay = attributes.platform_specific.halo_header_overlay
            && match state.halo_header_manager.as_ref() {
                Some(halo) => {
                    halo.set_overlay(&surface);
                    true
                },
                None => {
                    debug!(
                        "kora_halo_header_manager_v1 unsupported by the compositor; no Halo drag \
                         strip"
                    );
                    false
                },
            };

        // XXX Do initial commit.
        window.commit();

        // Add the window and window requests into the state.
        let window_state = Arc::new(Mutex::new(window_state));
        let window_id = super::make_wid(&surface);
        state.windows.get_mut().insert(window_id, window_state.clone());

        let window_requests = WindowRequests {
            redraw_requested: AtomicBool::new(true),
            closed: AtomicBool::new(false),
        };
        let window_requests = Arc::new(window_requests);
        state.window_requests.get_mut().insert(window_id, window_requests.clone());

        // Setup the event sync to insert `WindowEvents` right from the window.
        let window_events_sink = state.window_events_sink.clone();

        let mut wayland_source = event_loop_window_target.wayland_dispatcher.as_source_mut();
        let event_queue = wayland_source.queue();

        // Do a roundtrip.
        event_queue.roundtrip(&mut state).map_err(|error| {
            os_error!(OsError::WaylandError(Arc::new(WaylandError::Dispatch(error))))
        })?;

        // XXX Wait for the initial configure to arrive.
        while !window_state.lock().unwrap().is_configured() {
            event_queue.blocking_dispatch(&mut state).map_err(|error| {
                os_error!(OsError::WaylandError(Arc::new(WaylandError::Dispatch(error))))
            })?;
        }

        // Wake-up event loop, so it'll send initial redraw requested.
        let event_loop_awakener = event_loop_window_target.event_loop_awakener.clone();
        event_loop_awakener.ping();

        Ok(Self {
            window,
            display,
            monitors,
            window_id,
            compositor,
            window_state,
            queue_handle,
            xdg_activation,
            toplevel_icon,
            attention_requested: Arc::new(AtomicBool::new(false)),
            event_loop_awakener,
            window_requests,
            window_events_sink,
            halo_header_overlay,
        })
    }

    pub(crate) fn xdg_toplevel(&self) -> Option<NonNull<c_void>> {
        NonNull::new(self.window.xdg_toplevel().id().as_ptr().cast())
    }

    pub(crate) fn wl_surface_ptr(&self) -> Option<NonNull<c_void>> {
        NonNull::new(self.window.wl_surface().id().as_ptr().cast())
    }
}

impl Window {
    #[inline]
    pub fn id(&self) -> WindowId {
        self.window_id
    }

    #[inline]
    pub fn set_title(&self, title: impl ToString) {
        let new_title = title.to_string();
        self.window_state.lock().unwrap().set_title(new_title);
    }

    #[inline]
    pub fn set_keyboard_shortcuts_inhibit(&self, inhibit: bool) {
        self.window_state.lock().unwrap().set_keyboard_shortcuts_inhibit(inhibit);
        // Wake the loop so the create/destroy request is flushed promptly.
        self.event_loop_awakener.ping();
    }

    #[inline]
    pub fn set_visible(&self, _visible: bool) {
        // Not possible on Wayland.
    }

    #[inline]
    pub fn is_visible(&self) -> Option<bool> {
        None
    }

    #[inline]
    pub fn outer_position(&self) -> Result<PhysicalPosition<i32>, NotSupportedError> {
        Err(NotSupportedError::new())
    }

    #[inline]
    pub fn inner_position(&self) -> Result<PhysicalPosition<i32>, NotSupportedError> {
        Err(NotSupportedError::new())
    }

    #[inline]
    pub fn set_outer_position(&self, _: Position) {
        // Not possible on Wayland.
    }

    #[inline]
    pub fn inner_size(&self) -> PhysicalSize<u32> {
        let window_state = self.window_state.lock().unwrap();
        let scale_factor = window_state.scale_factor();
        super::logical_to_physical_rounded(window_state.inner_size(), scale_factor)
    }

    #[inline]
    pub fn request_redraw(&self) {
        // NOTE: try to not wake up the loop when the event was already scheduled and not yet
        // processed by the loop, because if at this point the value was `true` it could only
        // mean that the loop still haven't dispatched the value to the client and will do
        // eventually, resetting it to `false`.
        if self
            .window_requests
            .redraw_requested
            .compare_exchange(false, true, Ordering::Relaxed, Ordering::Relaxed)
            .is_ok()
        {
            self.event_loop_awakener.ping();
        }
    }

    #[inline]
    pub fn pre_present_notify(&self) {
        self.window_state.lock().unwrap().request_frame_callback();
    }

    #[inline]
    pub fn outer_size(&self) -> PhysicalSize<u32> {
        let window_state = self.window_state.lock().unwrap();
        let scale_factor = window_state.scale_factor();
        super::logical_to_physical_rounded(window_state.outer_size(), scale_factor)
    }

    #[inline]
    pub fn request_inner_size(&self, size: Size) -> Option<PhysicalSize<u32>> {
        let old_size = self.inner_size();
        let mut window_state = self.window_state.lock().unwrap();
        let new_size = window_state.request_inner_size(size);
        drop(window_state);

        // If the size actually changed, queue a resize event so the application knows
        if new_size != old_size {
            tracing::trace!(
                "request_inner_size: size changed from {:?} to {:?}, queuing Resized event",
                old_size,
                new_size
            );
            self.window_events_sink
                .lock()
                .unwrap()
                .push_window_event(WindowEvent::Resized(new_size), self.window_id);
            self.event_loop_awakener.ping();
        }

        self.request_redraw();
        Some(new_size)
    }

    /// Set the minimum inner size for the window.
    #[inline]
    pub fn set_min_inner_size(&self, min_size: Option<Size>) {
        let scale_factor = self.scale_factor();
        let min_size = min_size.map(|size| size.to_logical(scale_factor));
        self.window_state.lock().unwrap().set_min_inner_size(min_size);
        // NOTE: Requires commit to be applied.
        self.request_redraw();
    }

    /// Set the maximum inner size for the window.
    #[inline]
    pub fn set_max_inner_size(&self, max_size: Option<Size>) {
        let scale_factor = self.scale_factor();
        let max_size = max_size.map(|size| size.to_logical(scale_factor));
        self.window_state.lock().unwrap().set_max_inner_size(max_size);
        // NOTE: Requires commit to be applied.
        self.request_redraw();
    }

    #[inline]
    pub fn resize_increments(&self) -> Option<PhysicalSize<u32>> {
        None
    }

    #[inline]
    pub fn set_resize_increments(&self, _increments: Option<Size>) {
        warn!("`set_resize_increments` is not implemented for Wayland");
    }

    #[inline]
    pub fn set_transparent(&self, transparent: bool) {
        self.window_state.lock().unwrap().set_transparent(transparent);
    }

    #[inline]
    pub fn has_focus(&self) -> bool {
        self.window_state.lock().unwrap().has_focus()
    }

    #[inline]
    pub fn is_minimized(&self) -> Option<bool> {
        // XXX clients don't know whether they are minimized or not.
        None
    }

    #[inline]
    pub fn show_window_menu(&self, position: Position) {
        let scale_factor = self.scale_factor();
        let position = position.to_logical(scale_factor);
        self.window_state.lock().unwrap().show_window_menu(position);
    }

    #[inline]
    pub fn drag_resize_window(&self, direction: ResizeDirection) -> Result<(), ExternalError> {
        self.window_state.lock().unwrap().drag_resize_window(direction)
    }

    #[inline]
    pub fn set_resizable(&self, resizable: bool) {
        if self.window_state.lock().unwrap().set_resizable(resizable) {
            // NOTE: Requires commit to be applied.
            self.request_redraw();
        }
    }

    #[inline]
    pub fn is_resizable(&self) -> bool {
        self.window_state.lock().unwrap().resizable()
    }

    #[inline]
    pub fn set_enabled_buttons(&self, _buttons: WindowButtons) {
        // TODO(kchibisov) v5 of the xdg_shell allows that.
    }

    #[inline]
    pub fn enabled_buttons(&self) -> WindowButtons {
        // TODO(kchibisov) v5 of the xdg_shell allows that.
        WindowButtons::all()
    }

    #[inline]
    pub fn scale_factor(&self) -> f64 {
        self.window_state.lock().unwrap().scale_factor()
    }

    #[inline]
    pub fn set_blur(&self, blur: bool) {
        self.window_state.lock().unwrap().set_blur(blur);
    }

    /// Request an animated resize to the target size using the COSMIC protocol.
    ///
    /// Returns `true` if the request was sent, `false` if the protocol is not available.
    #[inline]
    pub fn request_animated_resize(&self, width: i32, height: i32, duration_ms: u32) -> bool {
        self.window_state.lock().unwrap().request_animated_resize(width, height, duration_ms)
    }

    /// Request an animated resize with explicit position using the COSMIC protocol.
    ///
    /// If the window is maximized, the position and size will be stored and used
    /// when the window is restored to normal state.
    ///
    /// Returns `true` if the request was sent, `false` if the protocol is not available.
    #[inline]
    pub fn request_animated_resize_with_position(
        &self,
        x: i32,
        y: i32,
        width: i32,
        height: i32,
        duration_ms: u32,
    ) -> bool {
        self.window_state.lock().unwrap().request_animated_resize_with_position(
            x,
            y,
            width,
            height,
            duration_ms,
        )
    }

    /// Set corner radius for this window using the COSMIC protocol.
    ///
    /// Communicates the corner radius hint to the compositor so it can
    /// draw proper blur outlines and rounded corners.
    ///
    /// Returns `true` if the request was sent, `false` if the protocol is not available.
    #[inline]
    pub fn set_corner_radius(
        &self,
        top_left: u32,
        top_right: u32,
        bottom_right: u32,
        bottom_left: u32,
    ) -> bool {
        self.window_state.lock().unwrap().set_corner_radius(
            top_left,
            top_right,
            bottom_right,
            bottom_left,
        )
    }

    /// Set the compositor-rendered backdrop color for this window.
    ///
    /// Returns `true` if the request was sent, `false` if the protocol is not available.
    #[inline]
    pub fn set_backdrop_color(&self, r: u32, g: u32, b: u32, a: u32) -> bool {
        self.window_state.lock().unwrap().set_backdrop_color(r, g, b, a)
    }

    /// Register this window to receive the device's special key.
    #[inline]
    pub fn register_special_action(&self, is_default: bool) -> bool {
        self.window_state.lock().unwrap().register_special_action(is_default)
    }

    /// Stop receiving the special key.
    #[inline]
    pub fn unregister_special_action(&self) -> bool {
        self.window_state.lock().unwrap().unregister_special_action()
    }

    /// Whether Kora's Halo has a drag strip over this window's top edge.
    #[inline]
    pub fn is_halo_header_overlay(&self) -> bool {
        self.halo_header_overlay
    }

    #[inline]
    pub fn kora_identity(&self) -> Option<crate::window::Identity> {
        self.window_state.lock().unwrap().kora_identity()
    }

    #[inline]
    pub fn set_app_commands(&self, commands: &crate::window::AppCommands) {
        self.window_state.lock().unwrap().set_app_commands(commands);
        self.event_loop_awakener.ping();
    }

    #[inline]
    pub fn request_app_palette(&self) {
        self.window_state.lock().unwrap().request_app_palette();
        self.event_loop_awakener.ping();
    }

    /// Embed a toplevel by process ID into this window's surface.
    ///
    /// Returns an embed ID that can be used to update geometry or remove the embed,
    /// or `None` if the surface embed protocol is not available.
    #[inline]
    // Arity follows the protocol request; a struct would obscure it.
    #[allow(clippy::too_many_arguments)]
    pub fn embed_toplevel_by_pid(
        &self,
        pid: u32,
        app_id: &str,
        x: i32,
        y: i32,
        width: i32,
        height: i32,
        interactive: bool,
    ) -> Option<u64> {
        self.window_state.lock().unwrap().embed_toplevel_by_pid(
            pid,
            app_id,
            x,
            y,
            width,
            height,
            interactive,
        )
    }

    /// Update the geometry of an embedded surface.
    #[inline]
    pub fn set_embed_geometry(
        &self,
        embed_id: u64,
        x: i32,
        y: i32,
        width: i32,
        height: i32,
    ) -> bool {
        self.window_state.lock().unwrap().set_embed_geometry(embed_id, x, y, width, height)
    }

    /// Set anchor-based positioning for an embedded surface.
    #[inline]
    // Arity follows the protocol request; a struct would obscure it.
    #[allow(clippy::too_many_arguments)]
    pub fn set_embed_anchor(
        &self,
        embed_id: u64,
        anchor: u32,
        margin_top: i32,
        margin_right: i32,
        margin_bottom: i32,
        margin_left: i32,
        width: i32,
        height: i32,
    ) -> bool {
        self.window_state.lock().unwrap().set_embed_anchor(
            embed_id,
            anchor,
            margin_top,
            margin_right,
            margin_bottom,
            margin_left,
            width,
            height,
        )
    }

    /// Set corner radius for an embedded surface.
    #[inline]
    pub fn set_embed_corner_radius(
        &self,
        embed_id: u64,
        top_left: u32,
        top_right: u32,
        bottom_right: u32,
        bottom_left: u32,
    ) -> bool {
        self.window_state.lock().unwrap().set_embed_corner_radius(
            embed_id,
            top_left,
            top_right,
            bottom_right,
            bottom_left,
        )
    }

    /// Set interactivity for an embedded surface.
    #[inline]
    pub fn set_embed_interactive(&self, embed_id: u64, interactive: bool) -> bool {
        self.window_state.lock().unwrap().set_embed_interactive(embed_id, interactive)
    }

    /// Remove an embedded surface.
    #[inline]
    pub fn remove_embed(&self, embed_id: u64) -> bool {
        self.window_state.lock().unwrap().remove_embed(embed_id)
    }

    /// Start a Wayland drag-and-drop operation from this window.
    ///
    /// Returns `(true, mime_types, data)` if the drag was started (callers should
    /// store `mime_types` and `data` in the DnD session state), or
    /// `(false, mime_types, data)` if it could not be started.
    ///
    /// `icon` is `(width, height, pixels, buffer_scale)` for HiDPI support.
    #[inline]
    pub fn start_drag(
        &self,
        mime_types: Vec<String>,
        actions: u32,
        data: Vec<Vec<u8>>,
        icon: Option<(u32, u32, Vec<u8>, i32)>,
    ) -> (bool, Vec<String>, Vec<Vec<u8>>) {
        self.window_state.lock().unwrap().start_drag(mime_types, actions, data, icon)
    }

    /// Accept a MIME type from the current DnD offer.
    #[inline]
    pub fn dnd_accept_mime_type(&self, mime_type: Option<&str>) {
        self.window_state.lock().unwrap().dnd_accept_mime_type(mime_type)
    }

    /// Set the accepted DnD actions and preferred action.
    #[inline]
    pub fn dnd_set_actions(&self, actions: u32, preferred: u32) {
        self.window_state.lock().unwrap().dnd_set_actions(actions, preferred)
    }

    /// Signal that the destination has finished processing the drop.
    #[inline]
    pub fn dnd_finish(&self) {
        self.window_state.lock().unwrap().dnd_finish()
    }

    /// Request data from the current DnD offer for the specified MIME type.
    #[inline]
    pub fn dnd_request_data(&self, mime_type: &str) {
        self.window_state.lock().unwrap().dnd_request_data(mime_type)
    }

    #[inline]
    pub fn set_decorations(&self, decorate: bool) {
        self.window_state.lock().unwrap().set_decorate(decorate)
    }

    #[inline]
    pub fn is_decorated(&self) -> bool {
        self.window_state.lock().unwrap().is_decorated()
    }

    #[inline]
    pub fn set_window_level(&self, _level: WindowLevel) {}

    #[inline]
    pub(crate) fn set_window_icon(&self, window_icon: Option<PlatformIcon>) {
        let Some(toplevel_icon) = self.toplevel_icon.as_ref() else {
            // Compositor doesn't support xdg-toplevel-icon.
            return;
        };
        let icon = window_icon.as_ref().map(|icon| (icon.rgba.as_slice(), icon.width, icon.height));
        toplevel_icon.lock().unwrap().set(self.window.xdg_toplevel(), icon, &self.queue_handle);
    }

    #[inline]
    pub fn set_minimized(&self, minimized: bool) {
        // You can't unminimize the window on Wayland.
        if !minimized {
            warn!("Unminimizing is ignored on Wayland.");
            return;
        }

        self.window.set_minimized();
    }

    #[inline]
    pub fn is_maximized(&self) -> bool {
        self.window_state
            .lock()
            .unwrap()
            .last_configure
            .as_ref()
            .map(|last_configure| last_configure.is_maximized())
            .unwrap_or_default()
    }

    #[inline]
    pub fn set_maximized(&self, maximized: bool) {
        if maximized {
            self.window.set_maximized()
        } else {
            self.window.unset_maximized()
        }
    }

    #[inline]
    pub(crate) fn fullscreen(&self) -> Option<Fullscreen> {
        let is_fullscreen = self
            .window_state
            .lock()
            .unwrap()
            .last_configure
            .as_ref()
            .map(|last_configure| last_configure.is_fullscreen())
            .unwrap_or_default();

        if is_fullscreen {
            let current_monitor = self.current_monitor().map(PlatformMonitorHandle::Wayland);
            Some(Fullscreen::Borderless(current_monitor))
        } else {
            None
        }
    }

    #[inline]
    pub(crate) fn set_fullscreen(&self, fullscreen: Option<Fullscreen>) {
        match fullscreen {
            Some(Fullscreen::Exclusive(_)) => {
                warn!("`Fullscreen::Exclusive` is ignored on Wayland");
            },
            #[cfg_attr(not(x11_platform), allow(clippy::bind_instead_of_map))]
            Some(Fullscreen::Borderless(monitor)) => {
                let output = monitor.and_then(|monitor| match monitor {
                    PlatformMonitorHandle::Wayland(monitor) => Some(monitor.proxy),
                    #[cfg(x11_platform)]
                    PlatformMonitorHandle::X(_) => None,
                });

                self.window.set_fullscreen(output.as_ref())
            },
            None => self.window.unset_fullscreen(),
        }
    }

    #[inline]
    pub fn set_cursor(&self, cursor: Cursor) {
        let window_state = &mut self.window_state.lock().unwrap();

        match cursor {
            Cursor::Icon(icon) => window_state.set_cursor(icon),
            Cursor::Custom(cursor) => window_state.set_custom_cursor(cursor),
        }
    }

    #[inline]
    pub fn set_cursor_visible(&self, visible: bool) {
        self.window_state.lock().unwrap().set_cursor_visible(visible);
    }

    pub fn request_user_attention(&self, request_type: Option<UserAttentionType>) {
        let xdg_activation = match self.xdg_activation.as_ref() {
            Some(xdg_activation) => xdg_activation,
            None => {
                warn!("`request_user_attention` isn't supported");
                return;
            },
        };

        // Urgency is only removed by the compositor and there's no need to raise urgency when it
        // was already raised.
        if request_type.is_none() || self.attention_requested.load(Ordering::Relaxed) {
            return;
        }

        self.attention_requested.store(true, Ordering::Relaxed);
        let surface = self.surface().clone();
        let data = XdgActivationTokenData::Attention((
            surface.clone(),
            Arc::downgrade(&self.attention_requested),
        ));
        let xdg_activation_token = xdg_activation.get_activation_token(&self.queue_handle, data);
        xdg_activation_token.set_surface(&surface);
        xdg_activation_token.commit();
    }

    pub fn request_activation_token(&self) -> Result<AsyncRequestSerial, NotSupportedError> {
        let xdg_activation = match self.xdg_activation.as_ref() {
            Some(xdg_activation) => xdg_activation,
            None => return Err(NotSupportedError::new()),
        };

        let serial = AsyncRequestSerial::get();

        let data = XdgActivationTokenData::Obtain((self.window_id, serial));
        let xdg_activation_token = xdg_activation.get_activation_token(&self.queue_handle, data);
        xdg_activation_token.set_surface(self.surface());
        xdg_activation_token.commit();

        Ok(serial)
    }

    #[inline]
    pub fn set_cursor_grab(&self, mode: CursorGrabMode) -> Result<(), ExternalError> {
        self.window_state.lock().unwrap().set_cursor_grab(mode)
    }

    #[inline]
    pub fn set_cursor_position(&self, position: Position) -> Result<(), ExternalError> {
        let scale_factor = self.scale_factor();
        let position = position.to_logical(scale_factor);
        self.window_state
            .lock()
            .unwrap()
            .set_cursor_position(position)
            // Request redraw on success, since the state is double buffered.
            .map(|_| self.request_redraw())
    }

    #[inline]
    pub fn drag_window(&self) -> Result<(), ExternalError> {
        self.window_state.lock().unwrap().drag_window()
    }

    #[inline]
    pub fn set_cursor_hittest(&self, hittest: bool) -> Result<(), ExternalError> {
        let surface = self.window.wl_surface();

        if hittest {
            surface.set_input_region(None);
            Ok(())
        } else {
            let region = Region::new(&*self.compositor).map_err(|_| {
                ExternalError::Os(os_error!(OsError::Misc("failed to set input region.")))
            })?;
            region.add(0, 0, 0, 0);
            surface.set_input_region(Some(region.wl_region()));
            Ok(())
        }
    }

    #[inline]
    pub fn set_ime_cursor_area(&self, position: Position, size: Size) {
        let mut window_state = self.window_state.lock().unwrap();
        if window_state.ime_allowed() {
            let scale_factor = window_state.scale_factor();
            let position = position.to_logical(scale_factor);
            let size = size.to_logical(scale_factor);
            window_state.set_ime_cursor_area(position, size);
        }
    }

    #[inline]
    pub fn set_ime_allowed(&self, allowed: bool) {
        let mut window_state = self.window_state.lock().unwrap();

        if window_state.ime_allowed() != allowed && window_state.set_ime_allowed(allowed) {
            let event = WindowEvent::Ime(if allowed { Ime::Enabled } else { Ime::Disabled });
            self.window_events_sink.lock().unwrap().push_window_event(event, self.window_id);
            self.event_loop_awakener.ping();
        }
    }

    #[inline]
    pub fn set_ime_purpose(&self, purpose: ImePurpose) {
        self.window_state.lock().unwrap().set_ime_purpose(purpose);
    }

    #[inline]
    pub fn set_ime_surrounding_text(
        &self,
        surrounding: Option<&crate::platform::wayland::ImeSurroundingText>,
    ) {
        self.window_state.lock().unwrap().set_ime_surrounding_text(surrounding);
    }

    #[inline]
    pub fn focus_window(&self) {}

    #[inline]
    pub fn surface(&self) -> &WlSurface {
        self.window.wl_surface()
    }

    #[inline]
    pub fn current_monitor(&self) -> Option<MonitorHandle> {
        let data = self.window.wl_surface().data::<SurfaceData>()?;
        data.outputs().next().map(MonitorHandle::new)
    }

    #[inline]
    pub fn available_monitors(&self) -> Vec<MonitorHandle> {
        self.monitors.lock().unwrap().clone()
    }

    #[inline]
    pub fn primary_monitor(&self) -> Option<MonitorHandle> {
        // XXX there's no such concept on Wayland.
        None
    }

    #[cfg(feature = "rwh_04")]
    #[inline]
    pub fn raw_window_handle_rwh_04(&self) -> rwh_04::RawWindowHandle {
        let mut window_handle = rwh_04::WaylandHandle::empty();
        window_handle.surface = self.window.wl_surface().id().as_ptr() as *mut _;
        window_handle.display = self.display.id().as_ptr() as *mut _;
        rwh_04::RawWindowHandle::Wayland(window_handle)
    }

    #[cfg(feature = "rwh_05")]
    #[inline]
    pub fn raw_window_handle_rwh_05(&self) -> rwh_05::RawWindowHandle {
        let mut window_handle = rwh_05::WaylandWindowHandle::empty();
        window_handle.surface = self.window.wl_surface().id().as_ptr() as *mut _;
        rwh_05::RawWindowHandle::Wayland(window_handle)
    }

    #[cfg(feature = "rwh_05")]
    #[inline]
    pub fn raw_display_handle_rwh_05(&self) -> rwh_05::RawDisplayHandle {
        let mut display_handle = rwh_05::WaylandDisplayHandle::empty();
        display_handle.display = self.display.id().as_ptr() as *mut _;
        rwh_05::RawDisplayHandle::Wayland(display_handle)
    }

    #[cfg(feature = "rwh_06")]
    #[inline]
    pub fn raw_window_handle_rwh_06(&self) -> Result<rwh_06::RawWindowHandle, rwh_06::HandleError> {
        Ok(rwh_06::WaylandWindowHandle::new({
            let ptr = self.window.wl_surface().id().as_ptr();
            std::ptr::NonNull::new(ptr as *mut _).expect("wl_surface will never be null")
        })
        .into())
    }

    #[cfg(feature = "rwh_06")]
    #[inline]
    pub fn raw_display_handle_rwh_06(
        &self,
    ) -> Result<rwh_06::RawDisplayHandle, rwh_06::HandleError> {
        Ok(rwh_06::WaylandDisplayHandle::new({
            let ptr = self.display.id().as_ptr();
            std::ptr::NonNull::new(ptr as *mut _).expect("wl_proxy should never be null")
        })
        .into())
    }

    #[inline]
    pub fn set_theme(&self, theme: Option<Theme>) {
        self.window_state.lock().unwrap().set_theme(theme)
    }

    #[inline]
    pub fn theme(&self) -> Option<Theme> {
        self.window_state.lock().unwrap().theme()
    }

    pub fn set_content_protected(&self, _protected: bool) {}

    #[inline]
    pub fn title(&self) -> String {
        self.window_state.lock().unwrap().title().to_owned()
    }
}

impl Drop for Window {
    fn drop(&mut self) {
        self.window_requests.closed.store(true, Ordering::Relaxed);
        self.event_loop_awakener.ping();
    }
}

/// The request from the window to the event loop.
#[derive(Debug)]
pub struct WindowRequests {
    /// The window was closed.
    pub closed: AtomicBool,

    /// Redraw Requested.
    pub redraw_requested: AtomicBool,
}

impl WindowRequests {
    pub fn take_closed(&self) -> bool {
        self.closed.swap(false, Ordering::Relaxed)
    }

    pub fn take_redraw_requested(&self) -> bool {
        self.redraw_requested.swap(false, Ordering::Relaxed)
    }
}

impl TryFrom<&str> for Theme {
    type Error = ();

    /// ```
    /// use winit::window::Theme;
    ///
    /// assert_eq!("dark".try_into(), Ok(Theme::Dark));
    /// assert_eq!("lIghT".try_into(), Ok(Theme::Light));
    /// ```
    fn try_from(theme: &str) -> Result<Self, Self::Error> {
        if theme.eq_ignore_ascii_case("dark") {
            Ok(Self::Dark)
        } else if theme.eq_ignore_ascii_case("light") {
            Ok(Self::Light)
        } else {
            Err(())
        }
    }
}