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
#![cfg(free_unix)]

#[cfg(all(not(x11_platform), not(wayland_platform)))]
compile_error!("Please select a feature to build for unix: `x11`, `wayland`");

use std::os::unix::io::{AsFd, AsRawFd, BorrowedFd, RawFd};
use std::sync::Arc;
use std::time::Duration;
use std::{collections::VecDeque, env, fmt};
#[cfg(x11_platform)]
use std::{ffi::CStr, mem::MaybeUninit, os::raw::*, sync::Mutex};

#[cfg(x11_platform)]
use once_cell::sync::Lazy;
use smol_str::SmolStr;

#[cfg(x11_platform)]
use crate::platform::x11::XlibErrorHook;
use crate::{
    dpi::{PhysicalPosition, PhysicalSize, Position, Size},
    error::{EventLoopError, ExternalError, NotSupportedError, OsError as RootOsError},
    event::KeyEvent,
    event_loop::{
        AsyncRequestSerial, ControlFlow, DeviceEvents, EventLoopClosed,
        EventLoopWindowTarget as RootELW,
    },
    icon::Icon,
    keyboard::{Key, PhysicalKey},
    platform::{
        modifier_supplement::KeyEventExtModifierSupplement, pump_events::PumpStatus,
        scancode::PhysicalKeyExtScancode,
    },
    window::{
        ActivationToken, CursorGrabMode, CursorIcon, ImePurpose, ResizeDirection, Theme,
        UserAttentionType, WindowAttributes, WindowButtons, WindowLevel,
    },
};
#[cfg(x11_platform)]
pub use x11::XNotSupported;
#[cfg(x11_platform)]
use x11::{util::WindowType as XWindowType, X11Error, XConnection, XError};

pub(crate) use crate::icon::RgbaIcon as PlatformIcon;
pub(crate) use crate::platform_impl::Fullscreen;

pub mod common;
#[cfg(wayland_platform)]
pub mod wayland;
#[cfg(x11_platform)]
pub mod x11;

#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub(crate) enum Backend {
    #[cfg(x11_platform)]
    X,
    #[cfg(wayland_platform)]
    Wayland,
}

#[derive(Debug, Default, Copy, Clone, PartialEq, Eq, Hash)]
pub(crate) struct PlatformSpecificEventLoopAttributes {
    pub(crate) forced_backend: Option<Backend>,
    pub(crate) any_thread: bool,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ApplicationName {
    pub general: String,
    pub instance: String,
}

impl ApplicationName {
    pub fn new(general: String, instance: String) -> Self {
        Self { general, instance }
    }
}

#[derive(Clone)]
pub struct PlatformSpecificWindowBuilderAttributes {
    pub name: Option<ApplicationName>,
    pub activation_token: Option<ActivationToken>,
    #[cfg(x11_platform)]
    pub x11: X11WindowBuilderAttributes,
}

#[derive(Clone)]
#[cfg(x11_platform)]
pub struct X11WindowBuilderAttributes {
    pub visual_id: Option<x11rb::protocol::xproto::Visualid>,
    pub screen_id: Option<i32>,
    pub base_size: Option<Size>,
    pub override_redirect: bool,
    pub x11_window_types: Vec<XWindowType>,

    /// The parent window to embed this window into.
    pub embed_window: Option<x11rb::protocol::xproto::Window>,
}

impl Default for PlatformSpecificWindowBuilderAttributes {
    fn default() -> Self {
        Self {
            name: None,
            activation_token: None,
            #[cfg(x11_platform)]
            x11: X11WindowBuilderAttributes {
                visual_id: None,
                screen_id: None,
                base_size: None,
                override_redirect: false,
                x11_window_types: vec![XWindowType::Normal],
                embed_window: None,
            },
        }
    }
}

#[cfg(x11_platform)]
pub(crate) static X11_BACKEND: Lazy<Mutex<Result<Arc<XConnection>, XNotSupported>>> =
    Lazy::new(|| Mutex::new(XConnection::new(Some(x_error_callback)).map(Arc::new)));

#[derive(Debug, Clone)]
pub enum OsError {
    Misc(&'static str),
    #[cfg(x11_platform)]
    XError(Arc<X11Error>),
    #[cfg(wayland_platform)]
    WaylandError(Arc<wayland::WaylandError>),
}

impl fmt::Display for OsError {
    fn fmt(&self, _f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
        match *self {
            OsError::Misc(e) => _f.pad(e),
            #[cfg(x11_platform)]
            OsError::XError(ref e) => fmt::Display::fmt(e, _f),
            #[cfg(wayland_platform)]
            OsError::WaylandError(ref e) => fmt::Display::fmt(e, _f),
        }
    }
}

pub(crate) enum Window {
    #[cfg(x11_platform)]
    X(x11::Window),
    #[cfg(wayland_platform)]
    Wayland(wayland::Window),
}

#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct WindowId(u64);

impl From<WindowId> for u64 {
    fn from(window_id: WindowId) -> Self {
        window_id.0
    }
}

impl From<u64> for WindowId {
    fn from(raw_id: u64) -> Self {
        Self(raw_id)
    }
}

impl WindowId {
    pub const unsafe fn dummy() -> Self {
        Self(0)
    }
}

#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum DeviceId {
    #[cfg(x11_platform)]
    X(x11::DeviceId),
    #[cfg(wayland_platform)]
    Wayland(wayland::DeviceId),
}

impl DeviceId {
    pub const unsafe fn dummy() -> Self {
        #[cfg(wayland_platform)]
        return DeviceId::Wayland(unsafe { wayland::DeviceId::dummy() });
        #[cfg(all(not(wayland_platform), x11_platform))]
        return DeviceId::X(unsafe { x11::DeviceId::dummy() });
    }
}

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub enum MonitorHandle {
    #[cfg(x11_platform)]
    X(x11::MonitorHandle),
    #[cfg(wayland_platform)]
    Wayland(wayland::MonitorHandle),
}

/// `x11_or_wayland!(match expr; Enum(foo) => foo.something())`
/// expands to the equivalent of
/// ```ignore
/// match self {
///    Enum::X(foo) => foo.something(),
///    Enum::Wayland(foo) => foo.something(),
/// }
/// ```
/// The result can be converted to another enum by adding `; as AnotherEnum`
macro_rules! x11_or_wayland {
    (match $what:expr; $enum:ident ( $($c1:tt)* ) => $x:expr; as $enum2:ident ) => {
        match $what {
            #[cfg(x11_platform)]
            $enum::X($($c1)*) => $enum2::X($x),
            #[cfg(wayland_platform)]
            $enum::Wayland($($c1)*) => $enum2::Wayland($x),
        }
    };
    (match $what:expr; $enum:ident ( $($c1:tt)* ) => $x:expr) => {
        match $what {
            #[cfg(x11_platform)]
            $enum::X($($c1)*) => $x,
            #[cfg(wayland_platform)]
            $enum::Wayland($($c1)*) => $x,
        }
    };
}

impl MonitorHandle {
    #[inline]
    pub fn name(&self) -> Option<String> {
        x11_or_wayland!(match self; MonitorHandle(m) => m.name())
    }

    #[inline]
    pub fn native_identifier(&self) -> u32 {
        x11_or_wayland!(match self; MonitorHandle(m) => m.native_identifier())
    }

    #[inline]
    pub fn size(&self) -> PhysicalSize<u32> {
        x11_or_wayland!(match self; MonitorHandle(m) => m.size())
    }

    #[inline]
    pub fn position(&self) -> PhysicalPosition<i32> {
        x11_or_wayland!(match self; MonitorHandle(m) => m.position())
    }

    #[inline]
    pub fn refresh_rate_millihertz(&self) -> Option<u32> {
        x11_or_wayland!(match self; MonitorHandle(m) => m.refresh_rate_millihertz())
    }

    #[inline]
    pub fn scale_factor(&self) -> f64 {
        x11_or_wayland!(match self; MonitorHandle(m) => m.scale_factor() as _)
    }

    #[inline]
    pub fn video_modes(&self) -> Box<dyn Iterator<Item = VideoMode>> {
        x11_or_wayland!(match self; MonitorHandle(m) => Box::new(m.video_modes()))
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum VideoMode {
    #[cfg(x11_platform)]
    X(x11::VideoMode),
    #[cfg(wayland_platform)]
    Wayland(wayland::VideoMode),
}

impl VideoMode {
    #[inline]
    pub fn size(&self) -> PhysicalSize<u32> {
        x11_or_wayland!(match self; VideoMode(m) => m.size())
    }

    #[inline]
    pub fn bit_depth(&self) -> u16 {
        x11_or_wayland!(match self; VideoMode(m) => m.bit_depth())
    }

    #[inline]
    pub fn refresh_rate_millihertz(&self) -> u32 {
        x11_or_wayland!(match self; VideoMode(m) => m.refresh_rate_millihertz())
    }

    #[inline]
    pub fn monitor(&self) -> MonitorHandle {
        x11_or_wayland!(match self; VideoMode(m) => m.monitor(); as MonitorHandle)
    }
}

impl Window {
    #[inline]
    pub(crate) fn new<T>(
        window_target: &EventLoopWindowTarget<T>,
        attribs: WindowAttributes,
        pl_attribs: PlatformSpecificWindowBuilderAttributes,
    ) -> Result<Self, RootOsError> {
        match *window_target {
            #[cfg(wayland_platform)]
            EventLoopWindowTarget::Wayland(ref window_target) => {
                wayland::Window::new(window_target, attribs, pl_attribs).map(Window::Wayland)
            }
            #[cfg(x11_platform)]
            EventLoopWindowTarget::X(ref window_target) => {
                x11::Window::new(window_target, attribs, pl_attribs).map(Window::X)
            }
        }
    }

    pub(crate) fn maybe_queue_on_main(&self, f: impl FnOnce(&Self) + Send + 'static) {
        f(self)
    }

    pub(crate) fn maybe_wait_on_main<R: Send>(&self, f: impl FnOnce(&Self) -> R + Send) -> R {
        f(self)
    }

    #[inline]
    pub fn id(&self) -> WindowId {
        x11_or_wayland!(match self; Window(w) => w.id())
    }

    #[inline]
    pub fn set_title(&self, title: &str) {
        x11_or_wayland!(match self; Window(w) => w.set_title(title));
    }

    #[inline]
    pub fn set_transparent(&self, transparent: bool) {
        x11_or_wayland!(match self; Window(w) => w.set_transparent(transparent));
    }

    #[inline]
    pub fn set_blur(&self, blur: bool) {
        x11_or_wayland!(match self; Window(w) => w.set_blur(blur));
    }

    #[inline]
    pub fn set_visible(&self, visible: bool) {
        x11_or_wayland!(match self; Window(w) => w.set_visible(visible))
    }

    #[inline]
    pub fn is_visible(&self) -> Option<bool> {
        x11_or_wayland!(match self; Window(w) => w.is_visible())
    }

    #[inline]
    pub fn outer_position(&self) -> Result<PhysicalPosition<i32>, NotSupportedError> {
        x11_or_wayland!(match self; Window(w) => w.outer_position())
    }

    #[inline]
    pub fn inner_position(&self) -> Result<PhysicalPosition<i32>, NotSupportedError> {
        x11_or_wayland!(match self; Window(w) => w.inner_position())
    }

    #[inline]
    pub fn set_outer_position(&self, position: Position) {
        x11_or_wayland!(match self; Window(w) => w.set_outer_position(position))
    }

    #[inline]
    pub fn inner_size(&self) -> PhysicalSize<u32> {
        x11_or_wayland!(match self; Window(w) => w.inner_size())
    }

    #[inline]
    pub fn outer_size(&self) -> PhysicalSize<u32> {
        x11_or_wayland!(match self; Window(w) => w.outer_size())
    }

    #[inline]
    pub fn request_inner_size(&self, size: Size) -> Option<PhysicalSize<u32>> {
        x11_or_wayland!(match self; Window(w) => w.request_inner_size(size))
    }

    #[inline]
    pub(crate) fn request_activation_token(&self) -> Result<AsyncRequestSerial, NotSupportedError> {
        x11_or_wayland!(match self; Window(w) => w.request_activation_token())
    }

    #[inline]
    pub fn set_min_inner_size(&self, dimensions: Option<Size>) {
        x11_or_wayland!(match self; Window(w) => w.set_min_inner_size(dimensions))
    }

    #[inline]
    pub fn set_max_inner_size(&self, dimensions: Option<Size>) {
        x11_or_wayland!(match self; Window(w) => w.set_max_inner_size(dimensions))
    }

    #[inline]
    pub fn resize_increments(&self) -> Option<PhysicalSize<u32>> {
        x11_or_wayland!(match self; Window(w) => w.resize_increments())
    }

    #[inline]
    pub fn set_resize_increments(&self, increments: Option<Size>) {
        x11_or_wayland!(match self; Window(w) => w.set_resize_increments(increments))
    }

    #[inline]
    pub fn set_resizable(&self, resizable: bool) {
        x11_or_wayland!(match self; Window(w) => w.set_resizable(resizable))
    }

    #[inline]
    pub fn is_resizable(&self) -> bool {
        x11_or_wayland!(match self; Window(w) => w.is_resizable())
    }

    #[inline]
    pub fn set_enabled_buttons(&self, buttons: WindowButtons) {
        x11_or_wayland!(match self; Window(w) => w.set_enabled_buttons(buttons))
    }

    #[inline]
    pub fn enabled_buttons(&self) -> WindowButtons {
        x11_or_wayland!(match self; Window(w) => w.enabled_buttons())
    }

    #[inline]
    pub fn set_cursor_icon(&self, cursor: CursorIcon) {
        x11_or_wayland!(match self; Window(w) => w.set_cursor_icon(cursor))
    }

    #[inline]
    pub fn set_cursor_grab(&self, mode: CursorGrabMode) -> Result<(), ExternalError> {
        x11_or_wayland!(match self; Window(window) => window.set_cursor_grab(mode))
    }

    #[inline]
    pub fn set_cursor_visible(&self, visible: bool) {
        x11_or_wayland!(match self; Window(window) => window.set_cursor_visible(visible))
    }

    #[inline]
    pub fn drag_window(&self) -> Result<(), ExternalError> {
        x11_or_wayland!(match self; Window(window) => window.drag_window())
    }

    #[inline]
    pub fn drag_resize_window(&self, direction: ResizeDirection) -> Result<(), ExternalError> {
        x11_or_wayland!(match self; Window(window) => window.drag_resize_window(direction))
    }

    #[inline]
    pub fn show_window_menu(&self, position: Position) {
        x11_or_wayland!(match self; Window(w) => w.show_window_menu(position))
    }

    #[inline]
    pub fn set_cursor_hittest(&self, hittest: bool) -> Result<(), ExternalError> {
        x11_or_wayland!(match self; Window(w) => w.set_cursor_hittest(hittest))
    }

    #[inline]
    pub fn scale_factor(&self) -> f64 {
        x11_or_wayland!(match self; Window(w) => w.scale_factor())
    }

    #[inline]
    pub fn set_cursor_position(&self, position: Position) -> Result<(), ExternalError> {
        x11_or_wayland!(match self; Window(w) => w.set_cursor_position(position))
    }

    #[inline]
    pub fn set_maximized(&self, maximized: bool) {
        x11_or_wayland!(match self; Window(w) => w.set_maximized(maximized))
    }

    #[inline]
    pub fn is_maximized(&self) -> bool {
        x11_or_wayland!(match self; Window(w) => w.is_maximized())
    }

    #[inline]
    pub fn set_minimized(&self, minimized: bool) {
        x11_or_wayland!(match self; Window(w) => w.set_minimized(minimized))
    }

    #[inline]
    pub fn is_minimized(&self) -> Option<bool> {
        x11_or_wayland!(match self; Window(w) => w.is_minimized())
    }

    #[inline]
    pub(crate) fn fullscreen(&self) -> Option<Fullscreen> {
        x11_or_wayland!(match self; Window(w) => w.fullscreen())
    }

    #[inline]
    pub(crate) fn set_fullscreen(&self, monitor: Option<Fullscreen>) {
        x11_or_wayland!(match self; Window(w) => w.set_fullscreen(monitor))
    }

    #[inline]
    pub fn set_decorations(&self, decorations: bool) {
        x11_or_wayland!(match self; Window(w) => w.set_decorations(decorations))
    }

    #[inline]
    pub fn is_decorated(&self) -> bool {
        x11_or_wayland!(match self; Window(w) => w.is_decorated())
    }

    #[inline]
    pub fn set_window_level(&self, level: WindowLevel) {
        x11_or_wayland!(match self; Window(w) => w.set_window_level(level))
    }

    #[inline]
    pub fn set_window_icon(&self, window_icon: Option<Icon>) {
        x11_or_wayland!(match self; Window(w) => w.set_window_icon(window_icon.map(|icon| icon.inner)))
    }

    #[inline]
    pub fn set_ime_cursor_area(&self, position: Position, size: Size) {
        x11_or_wayland!(match self; Window(w) => w.set_ime_cursor_area(position, size))
    }

    #[inline]
    pub fn reset_dead_keys(&self) {
        common::xkb_state::reset_dead_keys()
    }

    #[inline]
    pub fn set_ime_allowed(&self, allowed: bool) {
        x11_or_wayland!(match self; Window(w) => w.set_ime_allowed(allowed))
    }

    #[inline]
    pub fn set_ime_purpose(&self, purpose: ImePurpose) {
        x11_or_wayland!(match self; Window(w) => w.set_ime_purpose(purpose))
    }

    #[inline]
    pub fn focus_window(&self) {
        x11_or_wayland!(match self; Window(w) => w.focus_window())
    }
    pub fn request_user_attention(&self, request_type: Option<UserAttentionType>) {
        x11_or_wayland!(match self; Window(w) => w.request_user_attention(request_type))
    }

    #[inline]
    pub fn request_redraw(&self) {
        x11_or_wayland!(match self; Window(w) => w.request_redraw())
    }

    #[inline]
    pub fn pre_present_notify(&self) {
        x11_or_wayland!(match self; Window(w) => w.pre_present_notify())
    }

    #[inline]
    pub fn current_monitor(&self) -> Option<MonitorHandle> {
        Some(x11_or_wayland!(match self; Window(w) => w.current_monitor()?; as MonitorHandle))
    }

    #[inline]
    pub fn available_monitors(&self) -> VecDeque<MonitorHandle> {
        match self {
            #[cfg(x11_platform)]
            Window::X(ref window) => window
                .available_monitors()
                .into_iter()
                .map(MonitorHandle::X)
                .collect(),
            #[cfg(wayland_platform)]
            Window::Wayland(ref window) => window
                .available_monitors()
                .into_iter()
                .map(MonitorHandle::Wayland)
                .collect(),
        }
    }

    #[inline]
    pub fn primary_monitor(&self) -> Option<MonitorHandle> {
        Some(x11_or_wayland!(match self; Window(w) => w.primary_monitor()?; as MonitorHandle))
    }

    #[cfg(feature = "rwh_04")]
    #[inline]
    pub fn raw_window_handle_rwh_04(&self) -> rwh_04::RawWindowHandle {
        x11_or_wayland!(match self; Window(window) => window.raw_window_handle_rwh_04())
    }

    #[cfg(feature = "rwh_05")]
    #[inline]
    pub fn raw_window_handle_rwh_05(&self) -> rwh_05::RawWindowHandle {
        x11_or_wayland!(match self; Window(window) => window.raw_window_handle_rwh_05())
    }

    #[cfg(feature = "rwh_05")]
    #[inline]
    pub fn raw_display_handle_rwh_05(&self) -> rwh_05::RawDisplayHandle {
        x11_or_wayland!(match self; Window(window) => window.raw_display_handle_rwh_05())
    }

    #[cfg(feature = "rwh_06")]
    #[inline]
    pub fn raw_window_handle_rwh_06(&self) -> Result<rwh_06::RawWindowHandle, rwh_06::HandleError> {
        x11_or_wayland!(match self; Window(window) => window.raw_window_handle_rwh_06())
    }

    #[cfg(feature = "rwh_06")]
    #[inline]
    pub fn raw_display_handle_rwh_06(
        &self,
    ) -> Result<rwh_06::RawDisplayHandle, rwh_06::HandleError> {
        x11_or_wayland!(match self; Window(window) => window.raw_display_handle_rwh_06())
    }

    #[inline]
    pub fn set_theme(&self, theme: Option<Theme>) {
        x11_or_wayland!(match self; Window(window) => window.set_theme(theme))
    }

    #[inline]
    pub fn theme(&self) -> Option<Theme> {
        x11_or_wayland!(match self; Window(window) => window.theme())
    }

    pub fn set_content_protected(&self, protected: bool) {
        x11_or_wayland!(match self; Window(window) => window.set_content_protected(protected))
    }

    #[inline]
    pub fn has_focus(&self) -> bool {
        x11_or_wayland!(match self; Window(window) => window.has_focus())
    }

    pub fn title(&self) -> String {
        x11_or_wayland!(match self; Window(window) => window.title())
    }
}

#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub struct KeyEventExtra {
    pub key_without_modifiers: Key,
    pub text_with_all_modifiers: Option<SmolStr>,
}

impl KeyEventExtModifierSupplement for KeyEvent {
    #[inline]
    fn text_with_all_modifiers(&self) -> Option<&str> {
        self.platform_specific
            .text_with_all_modifiers
            .as_ref()
            .map(|s| s.as_str())
    }

    #[inline]
    fn key_without_modifiers(&self) -> Key {
        self.platform_specific.key_without_modifiers.clone()
    }
}

impl PhysicalKeyExtScancode for PhysicalKey {
    fn from_scancode(scancode: u32) -> PhysicalKey {
        common::keymap::scancode_to_keycode(scancode)
    }

    fn to_scancode(self) -> Option<u32> {
        common::keymap::physicalkey_to_scancode(self)
    }
}

/// Hooks for X11 errors.
#[cfg(x11_platform)]
pub(crate) static mut XLIB_ERROR_HOOKS: Lazy<Mutex<Vec<XlibErrorHook>>> =
    Lazy::new(|| Mutex::new(Vec::new()));

#[cfg(x11_platform)]
unsafe extern "C" fn x_error_callback(
    display: *mut x11::ffi::Display,
    event: *mut x11::ffi::XErrorEvent,
) -> c_int {
    let xconn_lock = X11_BACKEND.lock().unwrap();
    if let Ok(ref xconn) = *xconn_lock {
        // Call all the hooks.
        let mut error_handled = false;
        for hook in unsafe { XLIB_ERROR_HOOKS.lock() }.unwrap().iter() {
            error_handled |= hook(display as *mut _, event as *mut _);
        }

        // `assume_init` is safe here because the array consists of `MaybeUninit` values,
        // which do not require initialization.
        let mut buf: [MaybeUninit<c_char>; 1024] = unsafe { MaybeUninit::uninit().assume_init() };
        unsafe {
            (xconn.xlib.XGetErrorText)(
                display,
                (*event).error_code as c_int,
                buf.as_mut_ptr() as *mut c_char,
                buf.len() as c_int,
            )
        };
        let description =
            unsafe { CStr::from_ptr(buf.as_ptr() as *const c_char) }.to_string_lossy();

        let error = unsafe {
            XError {
                description: description.into_owned(),
                error_code: (*event).error_code,
                request_code: (*event).request_code,
                minor_code: (*event).minor_code,
            }
        };

        // Don't log error.
        if !error_handled {
            error!("X11 error: {:#?}", error);
            // XXX only update the error, if it wasn't handled by any of the hooks.
            *xconn.latest_error.lock().unwrap() = Some(error);
        }
    }
    // Fun fact: this return value is completely ignored.
    0
}

pub enum EventLoop<T: 'static> {
    #[cfg(wayland_platform)]
    Wayland(Box<wayland::EventLoop<T>>),
    #[cfg(x11_platform)]
    X(x11::EventLoop<T>),
}

pub enum EventLoopProxy<T: 'static> {
    #[cfg(x11_platform)]
    X(x11::EventLoopProxy<T>),
    #[cfg(wayland_platform)]
    Wayland(wayland::EventLoopProxy<T>),
}

impl<T: 'static> Clone for EventLoopProxy<T> {
    fn clone(&self) -> Self {
        x11_or_wayland!(match self; EventLoopProxy(proxy) => proxy.clone(); as EventLoopProxy)
    }
}

impl<T: 'static> EventLoop<T> {
    pub(crate) fn new(
        attributes: &PlatformSpecificEventLoopAttributes,
    ) -> Result<Self, EventLoopError> {
        if !attributes.any_thread && !is_main_thread() {
            panic!(
                "Initializing the event loop outside of the main thread is a significant \
                 cross-platform compatibility hazard. If you absolutely need to create an \
                 EventLoop on a different thread, you can use the \
                 `EventLoopBuilderExtUnix::any_thread` function."
            );
        }

        // NOTE: Wayland first because of X11 could be present under Wayland as well. Empty
        // variables are also treated as not set.
        let backend = match (
            attributes.forced_backend,
            env::var("WAYLAND_DISPLAY")
                .map(|var| !var.is_empty())
                .unwrap_or(false),
            env::var("DISPLAY")
                .map(|var| !var.is_empty())
                .unwrap_or(false),
        ) {
            // User is forcing a backend.
            (Some(backend), _, _) => backend,
            // Wayland is present.
            #[cfg(wayland_platform)]
            (None, true, _) => Backend::Wayland,
            // X11 is present.
            #[cfg(x11_platform)]
            (None, _, true) => Backend::X,
            // No backend is present.
            _ => {
                return Err(EventLoopError::Os(os_error!(OsError::Misc(
                    "neither WAYLAND_DISPLAY nor DISPLAY is set."
                ))));
            }
        };

        // Create the display based on the backend.
        match backend {
            #[cfg(wayland_platform)]
            Backend::Wayland => EventLoop::new_wayland_any_thread().map_err(Into::into),
            #[cfg(x11_platform)]
            Backend::X => EventLoop::new_x11_any_thread().map_err(Into::into),
        }
    }

    #[cfg(wayland_platform)]
    fn new_wayland_any_thread() -> Result<EventLoop<T>, EventLoopError> {
        wayland::EventLoop::new().map(|evlp| EventLoop::Wayland(Box::new(evlp)))
    }

    #[cfg(x11_platform)]
    fn new_x11_any_thread() -> Result<EventLoop<T>, EventLoopError> {
        let xconn = match X11_BACKEND.lock().unwrap().as_ref() {
            Ok(xconn) => xconn.clone(),
            Err(_) => return Err(EventLoopError::NotSupported(NotSupportedError::new())),
        };

        Ok(EventLoop::X(x11::EventLoop::new(xconn)))
    }

    pub fn create_proxy(&self) -> EventLoopProxy<T> {
        x11_or_wayland!(match self; EventLoop(evlp) => evlp.create_proxy(); as EventLoopProxy)
    }

    pub fn run<F>(mut self, callback: F) -> Result<(), EventLoopError>
    where
        F: FnMut(crate::event::Event<T>, &RootELW<T>),
    {
        self.run_on_demand(callback)
    }

    pub fn run_on_demand<F>(&mut self, callback: F) -> Result<(), EventLoopError>
    where
        F: FnMut(crate::event::Event<T>, &RootELW<T>),
    {
        x11_or_wayland!(match self; EventLoop(evlp) => evlp.run_on_demand(callback))
    }

    pub fn pump_events<F>(&mut self, timeout: Option<Duration>, callback: F) -> PumpStatus
    where
        F: FnMut(crate::event::Event<T>, &RootELW<T>),
    {
        x11_or_wayland!(match self; EventLoop(evlp) => evlp.pump_events(timeout, callback))
    }

    pub fn window_target(&self) -> &crate::event_loop::EventLoopWindowTarget<T> {
        x11_or_wayland!(match self; EventLoop(evlp) => evlp.window_target())
    }
}

impl<T> AsFd for EventLoop<T> {
    fn as_fd(&self) -> BorrowedFd<'_> {
        x11_or_wayland!(match self; EventLoop(evlp) => evlp.as_fd())
    }
}

impl<T> AsRawFd for EventLoop<T> {
    fn as_raw_fd(&self) -> RawFd {
        x11_or_wayland!(match self; EventLoop(evlp) => evlp.as_raw_fd())
    }
}

impl<T: 'static> EventLoopProxy<T> {
    pub fn send_event(&self, event: T) -> Result<(), EventLoopClosed<T>> {
        x11_or_wayland!(match self; EventLoopProxy(proxy) => proxy.send_event(event))
    }
}

pub enum EventLoopWindowTarget<T> {
    #[cfg(wayland_platform)]
    Wayland(wayland::EventLoopWindowTarget<T>),
    #[cfg(x11_platform)]
    X(x11::EventLoopWindowTarget<T>),
}

impl<T> EventLoopWindowTarget<T> {
    #[inline]
    pub fn is_wayland(&self) -> bool {
        match *self {
            #[cfg(wayland_platform)]
            EventLoopWindowTarget::Wayland(_) => true,
            #[cfg(x11_platform)]
            _ => false,
        }
    }

    #[inline]
    pub fn available_monitors(&self) -> VecDeque<MonitorHandle> {
        match *self {
            #[cfg(wayland_platform)]
            EventLoopWindowTarget::Wayland(ref evlp) => evlp
                .available_monitors()
                .map(MonitorHandle::Wayland)
                .collect(),
            #[cfg(x11_platform)]
            EventLoopWindowTarget::X(ref evlp) => {
                evlp.available_monitors().map(MonitorHandle::X).collect()
            }
        }
    }

    #[inline]
    pub fn primary_monitor(&self) -> Option<MonitorHandle> {
        Some(
            x11_or_wayland!(match self; EventLoopWindowTarget(evlp) => evlp.primary_monitor()?; as MonitorHandle),
        )
    }

    #[inline]
    pub fn listen_device_events(&self, allowed: DeviceEvents) {
        x11_or_wayland!(match self; Self(evlp) => evlp.listen_device_events(allowed))
    }

    #[cfg(feature = "rwh_05")]
    #[inline]
    pub fn raw_display_handle_rwh_05(&self) -> rwh_05::RawDisplayHandle {
        x11_or_wayland!(match self; Self(evlp) => evlp.raw_display_handle_rwh_05())
    }

    #[cfg(feature = "rwh_06")]
    #[inline]
    pub fn raw_display_handle_rwh_06(
        &self,
    ) -> Result<rwh_06::RawDisplayHandle, rwh_06::HandleError> {
        x11_or_wayland!(match self; Self(evlp) => evlp.raw_display_handle_rwh_06())
    }

    pub(crate) fn set_control_flow(&self, control_flow: ControlFlow) {
        x11_or_wayland!(match self; Self(evlp) => evlp.set_control_flow(control_flow))
    }

    pub(crate) fn control_flow(&self) -> ControlFlow {
        x11_or_wayland!(match self; Self(evlp) => evlp.control_flow())
    }

    pub(crate) fn clear_exit(&self) {
        x11_or_wayland!(match self; Self(evlp) => evlp.clear_exit())
    }

    pub(crate) fn exit(&self) {
        x11_or_wayland!(match self; Self(evlp) => evlp.exit())
    }

    pub(crate) fn exiting(&self) -> bool {
        x11_or_wayland!(match self; Self(evlp) => evlp.exiting())
    }

    fn set_exit_code(&self, code: i32) {
        x11_or_wayland!(match self; Self(evlp) => evlp.set_exit_code(code))
    }

    fn exit_code(&self) -> Option<i32> {
        x11_or_wayland!(match self; Self(evlp) => evlp.exit_code())
    }
}

/// Returns the minimum `Option<Duration>`, taking into account that `None`
/// equates to an infinite timeout, not a zero timeout (so can't just use
/// `Option::min`)
fn min_timeout(a: Option<Duration>, b: Option<Duration>) -> Option<Duration> {
    a.map_or(b, |a_timeout| {
        b.map_or(Some(a_timeout), |b_timeout| Some(a_timeout.min(b_timeout)))
    })
}

#[cfg(target_os = "linux")]
fn is_main_thread() -> bool {
    rustix::thread::gettid() == rustix::process::getpid()
}

#[cfg(any(target_os = "dragonfly", target_os = "freebsd", target_os = "openbsd"))]
fn is_main_thread() -> bool {
    use libc::pthread_main_np;

    unsafe { pthread_main_np() == 1 }
}

#[cfg(target_os = "netbsd")]
fn is_main_thread() -> bool {
    std::thread::current().name() == Some("main")
}