nadir-platform 0.4.0

OS layer of the Nadir engine: windows, the event loop, input devices, GL surfaces, audio output and paths.
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
// Copyright 2026 Joseph Anthony Abbott III
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! The window and its events, on X11.
//!
//! The window draws with OpenGL, through EGL ([`super::egl`]). EGL chooses
//! the frame buffer config first, and the window is made with the X visual
//! of that config.
//!
//! Typed text comes from an X input method: the one `XMODIFIERS` names, if
//! it opens, or else Xlib's own, which composes characters from the
//! locale's Compose file. Each event goes to `XFilterEvent` first. A key
//! press that an input method takes (a dead key, a step of a Compose
//! sequence, a press sent to a server) is still reported as a key, but types
//! nothing then; what it composes comes later, as a key press of keycode 0
//! that `Xutf8LookupString` reads. Opening the window takes the C library's
//! character locale from the environment if it is still "C", in which Xlib
//! would type Latin-1 only.
//!
//! What this backend does not do yet, because nothing has needed it:
//!
//! - It shows nothing of a text being composed (an input method's preedit),
//!   and opens the input method only once: if its server exits, nothing is
//!   typed until the game starts again.
//! - It reads the scale factor once, when the window opens, from the
//!   `Xft.dpi` resource. A change of the desktop's scale while the game runs
//!   goes unnoticed. Under XWayland the compositor decides what it tells X
//!   clients, so the value can differ from the compositor's own scale.
//! - It does not notice the window being minimized.
//!
//! One case can leave a key stuck down. While a window manager holds a
//! keyboard grab, for a shortcut of its own, the window gets no key events.
//! A key that goes up during the grab is seen as held until it is pressed
//! again or the window loses the focus.

mod connection;
mod input;

use core::ffi::{CStr, c_int, c_long, c_void};

use nadir_core::UVec2;
use nadir_core::log::{debug, error, warn};
use nadir_sys::linux::x11::{
    Atom, ButtonPressMask, ButtonReleaseMask, Colormap, Cursor, FocusChangeMask, KeyPressMask,
    KeyReleaseMask, PMaxSize, PMinSize, PointerMotionMask, StructureNotifyMask,
    SubstructureNotifyMask, SubstructureRedirectMask, TrueColor, Window, XA_ATOM, XA_STRING,
    XA_WM_NAME, XAspectRatio, XSizeHints,
};

use self::connection::{Connection, VisualFormat};
use self::input::{CloseMessage, Incoming, Translator};
use super::egl::WindowGl;
use super::xresources;
use crate::{Event, GlContext, GlContextId, GpuSurface, ModalFrame, PlatformError, WindowConfig};

/// The events we ask the server for.
const EVENT_MASK: c_long = KeyPressMask
    | KeyReleaseMask
    | ButtonPressMask
    | ButtonReleaseMask
    | PointerMotionMask
    | FocusChangeMask
    | StructureNotifyMask;

/// The widest and tallest window we ask for. The X protocol carries a size
/// in 16 bits, and servers stop at half of that.
const MAX_DIMENSION: u32 = 32767;

/// The first item of a `_NET_WM_STATE` message: take the state away.
/// Extended Window Manager Hints, "_NET_WM_STATE": `_NET_WM_STATE_REMOVE 0`.
const NET_WM_STATE_REMOVE: c_long = 0;

/// The first item of a `_NET_WM_STATE` message: add the state.
/// Extended Window Manager Hints, "_NET_WM_STATE": `_NET_WM_STATE_ADD 1`.
const NET_WM_STATE_ADD: c_long = 1;

/// The fourth item of a `_NET_WM_STATE` message: the sender is an ordinary
/// application. Extended Window Manager Hints, "Source indication".
const SOURCE_APPLICATION: c_long = 1;

/// The atoms we use, looked up once.
struct Atoms {
    wm_protocols: Atom,
    wm_delete_window: Atom,
    net_wm_name: Atom,
    net_wm_state: Atom,
    net_wm_state_fullscreen: Atom,
    utf8_string: Atom,
}

impl Atoms {
    fn intern(connection: &Connection) -> Self {
        Self {
            wm_protocols: connection.intern(c"WM_PROTOCOLS"),
            wm_delete_window: connection.intern(c"WM_DELETE_WINDOW"),
            net_wm_name: connection.intern(c"_NET_WM_NAME"),
            net_wm_state: connection.intern(c"_NET_WM_STATE"),
            net_wm_state_fullscreen: connection.intern(c"_NET_WM_STATE_FULLSCREEN"),
            utf8_string: connection.intern(c"UTF8_STRING"),
        }
    }
}

/// The X11 window of the game.
pub(crate) struct Backend {
    // The connection is declared last so that it is dropped last: `Drop`
    // below uses it, and so does `gl`, whose EGL display must be terminated
    // before the connection closes.
    root: Window,
    window: Window,
    /// The colormap of the window's visual.
    colormap: Colormap,
    atoms: Atoms,
    translator: Translator,
    /// The size the window was asked to have, in physical pixels.
    requested_size: UVec2,
    /// The smallest size the user may give the window, in physical pixels.
    /// A zero means no limit in that direction.
    min_size: UVec2,
    resizable: bool,
    fullscreen: bool,
    cursor_visible: bool,
    /// The empty pointer shape, once it has been needed.
    blank_cursor: Option<Cursor>,
    /// The window's OpenGL context, current on this thread.
    gl: WindowGl,
    connection: Connection,
}

impl Backend {
    pub(crate) fn new(config: &WindowConfig) -> Result<Self, PlatformError> {
        let connection = Connection::open()?;
        if !connection.set_detectable_auto_repeat() {
            warn!(
                "the X server has no detectable auto-repeat: a held key will report \
                 releases and presses in place of repeats"
            );
        }
        let scale = xresources::scale_factor(connection.resources().as_deref());
        let requested_size = physical_size(config.size, scale);
        let root = connection.root();
        let atoms = Atoms::intern(&connection);
        // SAFETY: the connection is open, and closes only after `gl` is
        // dropped: here `gl` is declared after it, so it is dropped first,
        // and in the backend it is a field before the connection.
        let gl = unsafe {
            WindowGl::open(connection.display(), |visual| {
                connection
                    .visual_format(visual)
                    .is_some_and(is_opaque_true_color)
            })
        }?;
        let (window, colormap) = connection
            .create_window(root, requested_size, gl.visual())
            .ok_or(PlatformError::CallFailed {
                call: "XGetVisualInfo",
            })?;
        let close = CloseMessage {
            wm_protocols: atoms.wm_protocols,
            wm_delete_window: atoms.wm_delete_window,
        };
        // From here on, dropping `backend` destroys the window.
        let mut backend = Self {
            root,
            window,
            colormap,
            atoms,
            translator: Translator::new(close, requested_size, scale),
            requested_size,
            min_size: physical_min_size(config.min_size, scale),
            resizable: config.resizable,
            fullscreen: config.fullscreen,
            cursor_visible: true,
            blank_cursor: None,
            gl,
            connection,
        };

        let typing = backend.connection.open_text_input(window);
        backend.connection.select_input(window, EVENT_MASK | typing);
        backend.set_title(&config.title);
        let mut protocols = [backend.atoms.wm_delete_window];
        if !backend.connection.set_protocols(window, &mut protocols) {
            return Err(PlatformError::CallFailed {
                call: "XSetWMProtocols",
            });
        }
        backend.apply_size_hints();
        if config.fullscreen {
            // Before the window is shown, the state is a property that the
            // window manager reads when it takes the window on.
            backend.connection.set_atoms(
                window,
                backend.atoms.net_wm_state,
                XA_ATOM,
                &[backend.atoms.net_wm_state_fullscreen],
            );
        }
        // The context is made before the window is shown, so that a failure
        // shows no window.
        // SAFETY: the window is of the connection's display and of the
        // config's visual, and `Drop` releases the context before it destroys
        // the window.
        unsafe { backend.gl.make_current(window, config.vsync) }?;
        backend.connection.map_window(window);
        debug!(
            "opened an X11 window of {}x{} pixels at scale {scale}",
            requested_size.x, requested_size.y
        );
        Ok(backend)
    }

    pub(crate) fn pump_events(&mut self, out: &mut Vec<Event>) {
        self.translator.begin_pump(out);
        // `pending` also sends the requests that the other methods queued.
        while self.connection.pending() > 0 {
            let mut event = self.connection.next_event();
            // Read before the input methods see it: Xlib's own sets the
            // keycode of the press that ends a Compose sequence to 0 when it
            // takes it, and sends its text as a copy of that press.
            // SAFETY: Xlib wrote the event, so its type and the member that
            // the type selects are initialized.
            let mut incoming = unsafe { Incoming::decode(&event) };
            // SAFETY: the event came from `next_event`.
            let taken = unsafe { self.connection.filter_event(&mut event) };
            if let Incoming::Key { taken: key, .. } = &mut incoming {
                *key = taken;
            }
            let is_key = matches!(incoming, Incoming::Key { .. });
            // Any other event an input method takes is its own. A key it
            // takes still moved: only what it types is the input method's.
            if taken && !is_key {
                continue;
            }
            self.translator.handle(incoming, out);
            if let Incoming::Key {
                pressed: true,
                state,
                ..
            } = incoming
                && !taken
            {
                // SAFETY: the event came from `next_event`, is a key press,
                // and no input method took it.
                let typed = unsafe { self.connection.lookup_text(&mut event) };
                input::push_typed(typed, state, out);
            }
            if let Some(focused) = input::focus_change(incoming) {
                self.connection.set_text_focus(focused);
            }
        }
    }

    pub(crate) fn window_size(&self) -> UVec2 {
        self.translator.size()
    }

    pub(crate) fn scale_factor(&self) -> f32 {
        self.translator.scale()
    }

    pub(crate) fn set_fullscreen(&mut self, on: bool) {
        if on == self.fullscreen {
            return;
        }
        self.fullscreen = on;
        // A window that may not change its size cannot go fullscreen, so
        // the limits come off first, and go back on afterwards.
        self.apply_size_hints();
        let sent = self.connection.send_to_window_manager(
            self.root,
            self.window,
            self.atoms.net_wm_state,
            fullscreen_request(on, self.atoms.net_wm_state_fullscreen),
            SubstructureNotifyMask | SubstructureRedirectMask,
        );
        if !sent {
            error!("could not ask the window manager for fullscreen: XSendEvent failed");
        }
    }

    pub(crate) fn set_title(&mut self, title: &str) {
        let bytes = title.as_bytes();
        // Current window managers read this one, which is always UTF-8.
        let modern = self.connection.set_bytes(
            self.window,
            self.atoms.net_wm_name,
            self.atoms.utf8_string,
            bytes,
        );
        // Older ones read this one.
        let legacy = self.connection.set_bytes(
            self.window,
            XA_WM_NAME,
            legacy_title_type(title, self.atoms.utf8_string),
            bytes,
        );
        if !(modern && legacy) {
            error!("the window title is too long to set");
        }
    }

    pub(crate) fn set_cursor_visible(&mut self, visible: bool) {
        if visible == self.cursor_visible {
            return;
        }
        if visible {
            self.connection.undefine_cursor(self.window);
        } else {
            if self.blank_cursor.is_none() {
                self.blank_cursor = self.connection.create_blank_cursor(self.window);
            }
            let Some(cursor) = self.blank_cursor else {
                error!("could not hide the pointer: the server made no empty cursor");
                return;
            };
            self.connection.define_cursor(self.window, cursor);
        }
        self.cursor_visible = visible;
    }

    pub(crate) fn set_modal_frame_callback(&mut self, _callback: Box<dyn FnMut(ModalFrame)>) {
        // X11 has no event loop of its own that would keep the pump from
        // returning, so there is nothing to call it for.
    }

    pub(crate) fn gpu_surface(&self) -> GpuSurface<'_> {
        GpuSurface::Gl(self)
    }

    fn apply_size_hints(&self) {
        let hints = size_hints(
            self.requested_size,
            self.min_size,
            self.resizable,
            self.fullscreen,
        );
        self.connection.set_normal_hints(self.window, hints);
    }
}

impl Drop for Backend {
    fn drop(&mut self) {
        // The window's surface and its input context go before the window
        // does.
        self.gl.release();
        self.connection.close_text_input();
        if let Some(cursor) = self.blank_cursor.take() {
            self.connection.free_cursor(cursor);
        }
        self.connection.destroy_window(self.window);
        self.connection.free_colormap(self.colormap);
        // The fields drop after this: `gl` terminates the EGL display, and
        // then the connection closes.
    }
}

// SAFETY: a backend exists only once `WindowGl::make_current` has made the
// window's context current on this thread, with the thread's claim, and has
// checked that it is OpenGL 3.3 core. It stays current until the backend is
// dropped, and the functions come from EGL or libOpenGL for it. A backend
// holds raw pointers, so it is neither `Send` nor `Sync`.
unsafe impl GlContext for Backend {
    fn get_proc_address(&self, name: &CStr) -> *const c_void {
        self.gl.get_proc_address(name)
    }

    fn swap_buffers(&self) -> Result<(), PlatformError> {
        self.gl.swap_buffers()
    }

    fn set_swap_interval(&self, interval: i32) -> bool {
        self.gl.set_swap_interval(interval)
    }

    fn drawable_size(&self) -> UVec2 {
        // On X11 the drawable is the inside of the window.
        self.translator.size()
    }

    fn context_id(&self) -> Option<GlContextId> {
        // The claim lives until the backend's fields are dropped, after the
        // context is gone.
        Some(self.gl.id())
    }
}

/// Whether a window of this visual is opaque, in plain 24-bit color. A
/// compositor blends a window of depth 32 with what is behind it, and the
/// colors of a visual of another class depend on a colormap that we leave
/// empty.
fn is_opaque_true_color(format: VisualFormat) -> bool {
    format.depth == 24 && format.class == TrueColor
}

/// Converts a logical window size to physical pixels, within what X can
/// make a window of.
fn physical_size(logical: UVec2, scale: f32) -> UVec2 {
    let dimension = |logical: u32| {
        // The cast saturates, and a NaN gives 0.
        let physical = (logical as f32 * scale).round() as u32;
        physical.clamp(1, MAX_DIMENSION)
    };
    UVec2::new(dimension(logical.x), dimension(logical.y))
}

/// Converts a logical minimum size to physical pixels. A zero stays zero:
/// no limit in that direction.
fn physical_min_size(logical: UVec2, scale: f32) -> UVec2 {
    let dimension = |logical: u32| match logical {
        0 => 0,
        _ => physical_size(UVec2::splat(logical), scale).x,
    };
    UVec2::new(dimension(logical.x), dimension(logical.y))
}

/// Returns what to tell the window manager about the sizes the window
/// accepts. All sizes are in physical pixels.
fn size_hints(size: UVec2, min_size: UVec2, resizable: bool, fullscreen: bool) -> XSizeHints {
    let mut hints = XSizeHints {
        flags: 0,
        x: 0,
        y: 0,
        width: 0,
        height: 0,
        min_width: 0,
        min_height: 0,
        max_width: 0,
        max_height: 0,
        width_inc: 0,
        height_inc: 0,
        min_aspect: XAspectRatio { x: 0, y: 0 },
        max_aspect: XAspectRatio { x: 0, y: 0 },
        base_width: 0,
        base_height: 0,
        win_gravity: 0,
    };
    // Every size here is at most `MAX_DIMENSION`, so none saturates.
    let int = |value: u32| c_int::try_from(value).unwrap_or(c_int::MAX);
    if fullscreen {
        // No limits: the window manager chooses the size.
    } else if !resizable {
        hints.flags = PMinSize | PMaxSize;
        (hints.min_width, hints.min_height) = (int(size.x), int(size.y));
        (hints.max_width, hints.max_height) = (int(size.x), int(size.y));
    } else if min_size != UVec2::ZERO {
        hints.flags = PMinSize;
        // The hint has no "no limit", and one pixel is as good.
        (hints.min_width, hints.min_height) = (int(min_size.x.max(1)), int(min_size.y.max(1)));
    }
    hints
}

/// Returns the data of the `_NET_WM_STATE` message that asks the window
/// manager to turn fullscreen on or off: the action, the state, no second
/// state, who is asking, and an unused item.
fn fullscreen_request(on: bool, net_wm_state_fullscreen: Atom) -> [c_long; 5] {
    let action = if on {
        NET_WM_STATE_ADD
    } else {
        NET_WM_STATE_REMOVE
    };
    // An atom is an `unsigned long` that travels as a `long`.
    let state = net_wm_state_fullscreen as c_long;
    [action, state, 0, SOURCE_APPLICATION, 0]
}

/// Returns the type to give the `WM_NAME` property for this title.
///
/// The property's own type, `STRING`, is Latin-1. A title in plain ASCII is
/// the same bytes in Latin-1 and in UTF-8, so it can have that type. Any
/// other title is marked as UTF-8, which window managers accept here too.
fn legacy_title_type(title: &str, utf8_string: Atom) -> Atom {
    if title.is_ascii() {
        XA_STRING
    } else {
        utf8_string
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn a_logical_size_is_scaled_and_rounded() {
        let size = UVec2::new(640, 360);
        assert_eq!(physical_size(size, 1.0), UVec2::new(640, 360));
        assert_eq!(physical_size(size, 2.0), UVec2::new(1280, 720));
        assert_eq!(physical_size(size, 1.5), UVec2::new(960, 540));
        assert_eq!(physical_size(size, 0.75), UVec2::new(480, 270));
        // 101 * 1.25 = 126.25, and 3 * 1.5 = 4.5, which rounds away from 0.
        assert_eq!(physical_size(UVec2::new(101, 3), 1.25), UVec2::new(126, 4));
        assert_eq!(physical_size(UVec2::new(3, 1), 1.5), UVec2::new(5, 2));
    }

    #[test]
    fn a_physical_size_is_one_that_x_can_make() {
        assert_eq!(physical_size(UVec2::ZERO, 1.0), UVec2::new(1, 1));
        assert_eq!(physical_size(UVec2::new(1, 1), 0.25), UVec2::new(1, 1));
        assert_eq!(
            physical_size(UVec2::new(u32::MAX, 40_000), 1.0),
            UVec2::new(32767, 32767)
        );
        assert_eq!(
            physical_size(UVec2::new(20_000, 100), 2.0),
            UVec2::new(32767, 200)
        );
        // A scale that is no number still gives a window.
        assert_eq!(
            physical_size(UVec2::new(640, 360), f32::NAN),
            UVec2::new(1, 1)
        );
        assert_eq!(
            physical_size(UVec2::new(640, 360), f32::INFINITY),
            UVec2::new(32767, 32767)
        );
    }

    #[test]
    fn a_minimum_size_is_scaled_and_zero_stays_no_limit() {
        assert_eq!(
            physical_min_size(UVec2::new(320, 180), 2.0),
            UVec2::new(640, 360)
        );
        assert_eq!(physical_min_size(UVec2::ZERO, 2.0), UVec2::ZERO);
        assert_eq!(
            physical_min_size(UVec2::new(0, 180), 1.5),
            UVec2::new(0, 270)
        );
        assert_eq!(physical_min_size(UVec2::new(1, 0), 0.25), UVec2::new(1, 0));
    }

    /// The flags and the four limits of some hints.
    fn limits(hints: &XSizeHints) -> (c_long, [c_int; 4]) {
        (
            hints.flags,
            [
                hints.min_width,
                hints.min_height,
                hints.max_width,
                hints.max_height,
            ],
        )
    }

    #[test]
    fn a_window_of_fixed_size_has_equal_limits() {
        let hints = size_hints(UVec2::new(640, 360), UVec2::new(320, 180), false, false);
        assert_eq!(limits(&hints), (PMinSize | PMaxSize, [640, 360, 640, 360]));
    }

    #[test]
    fn a_resizable_window_has_only_its_minimum() {
        let size = UVec2::new(640, 360);
        let hints = size_hints(size, UVec2::new(320, 180), true, false);
        assert_eq!(limits(&hints), (PMinSize, [320, 180, 0, 0]));

        let hints = size_hints(size, UVec2::ZERO, true, false);
        assert_eq!(limits(&hints), (0, [0, 0, 0, 0]));

        // No limit in one direction becomes one pixel.
        let hints = size_hints(size, UVec2::new(0, 180), true, false);
        assert_eq!(limits(&hints), (PMinSize, [1, 180, 0, 0]));
    }

    #[test]
    fn a_fullscreen_window_has_no_limits() {
        for resizable in [false, true] {
            let hints = size_hints(UVec2::new(640, 360), UVec2::new(320, 180), resizable, true);
            assert_eq!(limits(&hints), (0, [0, 0, 0, 0]));
        }
    }

    #[test]
    fn hints_set_nothing_but_the_limits() {
        let hints = size_hints(UVec2::new(640, 360), UVec2::new(320, 180), false, false);
        let rest = [
            hints.x,
            hints.y,
            hints.width,
            hints.height,
            hints.width_inc,
            hints.height_inc,
            hints.min_aspect.x,
            hints.min_aspect.y,
            hints.max_aspect.x,
            hints.max_aspect.y,
            hints.base_width,
            hints.base_height,
            hints.win_gravity,
        ];
        assert_eq!(rest, [0; 13]);
    }

    #[test]
    fn a_fullscreen_request_adds_or_removes_the_state() {
        // The values are those of the Extended Window Manager Hints.
        const FULLSCREEN: Atom = 411;
        assert_eq!(fullscreen_request(true, FULLSCREEN), [1, 411, 0, 1, 0]);
        assert_eq!(fullscreen_request(false, FULLSCREEN), [0, 411, 0, 1, 0]);
    }

    #[test]
    fn only_an_ascii_title_is_a_latin_1_string() {
        const UTF8_STRING: Atom = 400;
        assert_eq!(legacy_title_type("Nadir", UTF8_STRING), XA_STRING);
        assert_eq!(legacy_title_type("", UTF8_STRING), XA_STRING);
        assert_eq!(legacy_title_type("Nadir: level 2!", UTF8_STRING), XA_STRING);
        // Latin-1 could hold the first of these, but not as these bytes.
        assert_eq!(legacy_title_type("Café", UTF8_STRING), UTF8_STRING);
        assert_eq!(legacy_title_type("ナディア", UTF8_STRING), UTF8_STRING);
    }

    #[test]
    fn only_an_opaque_true_color_visual_is_taken() {
        // The classes are those of `X11/X.h`.
        let (true_color, direct_color) = (4, 5);
        let format = |depth, class| VisualFormat { depth, class };
        assert!(is_opaque_true_color(format(24, true_color)));
        assert!(!is_opaque_true_color(format(32, true_color)));
        assert!(!is_opaque_true_color(format(30, true_color)));
        assert!(!is_opaque_true_color(format(24, direct_color)));
    }

    #[test]
    #[ignore = "opens windows: run it with --ignored --test-threads=1 in an X11 or XWayland session"]
    fn a_window_gets_an_opengl_3_3_core_context_each_time() {
        // Three times, because an EGL display that is not terminated before
        // its connection closes breaks a later window (seen on Mesa's iris).
        for _ in 0..3 {
            let config = WindowConfig {
                title: "Nadir test".to_string(),
                size: UVec2::new(320, 180),
                min_size: UVec2::ZERO,
                resizable: true,
                fullscreen: false,
                vsync: true,
            };
            let backend = Backend::new(&config).unwrap();
            let GpuSurface::Gl(gl) = backend.gpu_surface();
            super::super::egl::gl_test::check_context_and_draw(gl);
            assert!(gl.context_id().is_some_and(GlContextId::is_current));
            assert_eq!(gl.drawable_size(), backend.window_size());
            assert!(!gl.set_swap_interval(-1));
            for _ in 0..3 {
                gl.swap_buffers().unwrap();
            }
        }
    }

    #[test]
    #[ignore = "opens a window: run it with --ignored --test-threads=1 in an X11 or XWayland session"]
    fn key_presses_sent_to_the_window_type_text_through_its_input_method() {
        use core::ffi::c_uint;

        // X keycodes: the evdev code plus 8.
        const A: c_uint = 30 + 8;
        const LEFT_SHIFT: c_uint = 42 + 8;
        const LEFT_CONTROL: c_uint = 29 + 8;
        const ENTER: c_uint = 28 + 8;
        const LEFT_ALT: c_uint = 56 + 8;
        /// `X11/X.h`: `#define ShiftMask (1<<0)`
        const SHIFT_MASK: c_uint = 1 << 0;
        const CONTROL_MASK: c_uint = nadir_sys::linux::x11::ControlMask;
        const MOD1_MASK: c_uint = nadir_sys::linux::x11::Mod1Mask;

        let config = WindowConfig {
            title: "Nadir test".to_string(),
            size: UVec2::new(320, 180),
            min_size: UVec2::ZERO,
            resizable: true,
            fullscreen: false,
            vsync: true,
        };
        let mut backend = Backend::new(&config).unwrap();
        assert!(
            backend.connection.has_text_input(),
            "no X input method opened"
        );
        // The focus is the compositor's to give; the input method is told
        // it has it.
        backend.connection.set_text_focus(true);
        let sent = [
            (A, true, 0),
            (A, false, 0),
            (LEFT_SHIFT, true, 0),
            (A, true, SHIFT_MASK),
            (A, false, SHIFT_MASK),
            (LEFT_SHIFT, false, SHIFT_MASK),
            (LEFT_CONTROL, true, 0),
            (A, true, CONTROL_MASK),
            (A, false, CONTROL_MASK),
            (LEFT_CONTROL, false, CONTROL_MASK),
            (LEFT_ALT, true, 0),
            (A, true, MOD1_MASK),
            (A, false, MOD1_MASK),
            (LEFT_ALT, false, MOD1_MASK),
            (ENTER, true, 0),
            (ENTER, false, 0),
        ];
        for (keycode, pressed, state) in sent {
            backend
                .connection
                .send_key(backend.window, keycode, pressed, state);
        }
        // An input method server types after a round trip: pump until both
        // characters came, then a little longer, for any that should not.
        let mut out = Vec::new();
        let typed = |out: &[Event]| -> Vec<(usize, char)> {
            out.iter()
                .enumerate()
                .filter_map(|(at, event)| match *event {
                    Event::Text(typed) => Some((at, typed)),
                    _ => None,
                })
                .collect()
        };
        let start = std::time::Instant::now();
        let mut settled = None;
        while start.elapsed() < std::time::Duration::from_secs(5) {
            backend.pump_events(&mut out);
            if typed(&out).len() >= 2 {
                let since = *settled.get_or_insert_with(std::time::Instant::now);
                if since.elapsed() > std::time::Duration::from_millis(200) {
                    break;
                }
            }
            std::thread::sleep(std::time::Duration::from_millis(10));
        }
        let typed = typed(&out);
        let characters: Vec<char> = typed.iter().map(|&(_, typed)| typed).collect();
        // Control+A, Alt+A and Enter type nothing.
        assert_eq!(characters, ['a', 'A'], "{out:?}");
        // Each character after the press that typed it, and the first before
        // the second press.
        let presses: Vec<usize> = out
            .iter()
            .enumerate()
            .filter(|(_, event)| {
                **event
                    == Event::Key {
                        key: nadir_core::Key::A,
                        pressed: true,
                        repeat: false,
                    }
            })
            .map(|(at, _)| at)
            .collect();
        assert_eq!(presses.len(), 4, "{out:?}");
        assert!(
            presses[0] < typed[0].0 && typed[0].0 < presses[1],
            "{out:?}"
        );
        assert!(presses[1] < typed[1].0, "{out:?}");
    }

    #[test]
    fn the_event_mask_selects_what_the_translator_handles() {
        // The values are those of `X11/X.h`.
        let expected = (1 << 0) | (1 << 1) | (1 << 2) | (1 << 3) | (1 << 6) | (1 << 17) | (1 << 21);
        assert_eq!(EVENT_MASK, expected);
    }
}