crcbl-shell 0.17.1

Crucible windowing shell: own Wayland, X11, Web/canvas and headless backends
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
//! Startup negotiation: which extensions the server has, whether a window
//! manager is running, and what scale the desktop is at.
//!
//! Everything here runs once, in [`X11Shell::open`](super::X11Shell::open), and
//! everything it produces is latched — see
//! [`X11Shell::latch_caps`](super::X11Shell::latch_caps) for why that is not
//! merely a convenience.

use std::ffi::c_int;

use super::{Argb, BASE_DPI, Conn, DEFAULT_SCALE, ffi};

/// Whether `visual` is a 32-bit true-colour visual with an alpha channel: the
/// bits its colour masks leave over.
fn is_argb(depth: u8, visual: &ffi::VisualType) -> bool {
    depth == 32
        && visual.class == ffi::value::TRUE_COLOR
        && visual.red_mask | visual.green_mask | visual.blue_mask != u32::MAX
}

impl Conn {
    /// The visual a transparent window is created on, and a colormap for it,
    /// **when something composites this screen** — `None` otherwise, and then
    /// [`TRANSPARENT`](crate::ShellCaps::TRANSPARENT) stays clear.
    ///
    /// A 32-bit visual alone is not enough: X draws a window's pixels as they
    /// are, alpha ignored, unless a compositor blends them, so on a bare server
    /// a "transparent" window is an opaque one in darkened colours. Two things
    /// composite: **Xwayland**, whose Wayland compositor blends each window by
    /// its alpha, and **a compositing manager**, which owns the
    /// `_NET_WM_CM_S<screen>` selection by the EWMH. Both are read once, here;
    /// a compositing manager started later is not seen, and one that quits
    /// leaves transparent windows drawn opaque.
    ///
    /// One colormap serves every transparent window, made once on the root
    /// and freed by the server when the connection closes.
    pub(super) fn setup_argb(
        &self,
        screen: *const ffi::Screen,
        screen_index: c_int,
    ) -> Option<Argb> {
        let visual = self.argb_visual(screen)?;
        if !self.has_extension("XWAYLAND") && !self.has_compositing_manager(screen_index) {
            crcbl_core::log::debug!("nothing composites this X screen; no transparent windows");
            return None;
        }
        let colormap = self.generate_id();
        // SAFETY: the connection is live, `colormap` is a fresh XID, the root
        // is this screen's and `visual` one of its visuals.
        unsafe {
            (self.lib.create_colormap)(
                self.raw(),
                ffi::value::COLORMAP_ALLOC_NONE,
                colormap,
                self.root,
                visual,
            );
        }
        Some(Argb { visual, colormap })
    }

    /// The screen's first 32-bit true-colour visual with alpha.
    fn argb_visual(&self, screen: *const ffi::Screen) -> Option<u32> {
        // SAFETY: `screen` is the setup reply's, which libxcb keeps for the
        // connection's lifetime, and each iterator walks memory inside it,
        // stopping at its `rem` count.
        unsafe {
            let mut depths = (self.lib.screen_allowed_depths_iterator)(screen);
            while depths.rem > 0 {
                let depth = *depths.data;
                let mut visuals = (self.lib.depth_visuals_iterator)(depths.data);
                while visuals.rem > 0 {
                    let visual = *visuals.data;
                    if is_argb(depth.depth, &visual) {
                        return Some(visual.visual_id);
                    }
                    (self.lib.visualtype_next)(&raw mut visuals);
                }
                (self.lib.depth_next)(&raw mut depths);
            }
        }
        None
    }

    /// Whether the server has the extension called `name`.
    fn has_extension(&self, name: &str) -> bool {
        let len = u16::try_from(name.len()).unwrap_or(u16::MAX);
        // SAFETY: the connection is live and `name` a counted string valid for
        // the call; a null error pointer discards the error, and a null reply
        // is handled below.
        let reply = unsafe {
            let cookie = (self.lib.query_extension)(self.raw(), len, name.as_ptr().cast());
            (self.lib.query_extension_reply)(self.raw(), cookie, core::ptr::null_mut())
        };
        if reply.is_null() {
            return false;
        }
        // SAFETY: `reply` is a live reply this call owns, freed exactly once.
        unsafe {
            let present = (*reply).present != 0;
            ffi::free_reply(reply);
            present
        }
    }

    /// Whether a compositing manager owns `_NET_WM_CM_S<screen_index>`.
    fn has_compositing_manager(&self, screen_index: c_int) -> bool {
        let name = format!("_NET_WM_CM_S{screen_index}");
        let len = u16::try_from(name.len()).unwrap_or(u16::MAX);
        // SAFETY: as `has_extension`; `only_if_exists = 1`, so an atom no one
        // has made answers `0`, and then no one owns it.
        let atom = unsafe {
            let cookie = (self.lib.intern_atom)(self.raw(), 1, len, name.as_ptr().cast());
            let reply = (self.lib.intern_atom_reply)(self.raw(), cookie, core::ptr::null_mut());
            if reply.is_null() {
                return false;
            }
            let atom = (*reply).atom;
            ffi::free_reply(reply);
            atom
        };
        if atom == ffi::value::NONE {
            return false;
        }
        // SAFETY: as above.
        unsafe {
            let cookie = (self.lib.get_selection_owner)(self.raw(), atom);
            let reply =
                (self.lib.get_selection_owner_reply)(self.raw(), cookie, core::ptr::null_mut());
            if reply.is_null() {
                return false;
            }
            let owner = (*reply).owner;
            ffi::free_reply(reply);
            owner != ffi::value::NONE
        }
    }

    /// Negotiates RandR, and selects the events that mean "the monitors
    /// changed".
    ///
    /// Returns the extension's first event number, which is what an incoming
    /// event's `response_type` has to be compared against — extension events
    /// are numbered from a base the server assigns per connection, so a
    /// hard-coded number reads an unrelated core event as a RandR one.
    ///
    /// `None` when libxcb-randr is missing, when the server has no RandR, or
    /// when it is older than 1.2 — which is the version that introduced CRTCs,
    /// and therefore the version below which there is no per-monitor geometry
    /// to enumerate at all. A pre-1.2 server had one screen and that was that,
    /// which is exactly what the fallback in [`monitors`](super::monitors)
    /// reports.
    pub(super) fn setup_randr(&self) -> Option<u8> {
        let randr = self.ext.randr?;
        // SAFETY: the connection is live and `randr.id` is the extension
        // descriptor libxcb caches; the reply it returns is owned by libxcb for
        // the connection's lifetime and must not be freed.
        let query =
            unsafe { (self.lib.get_extension_data)(self.raw(), ffi::extension_ptr(randr.id)) };
        if query.is_null() {
            return None;
        }
        // SAFETY: `query` is libxcb's cached reply, valid while the connection
        // is.
        let (present, first_event) = unsafe { ((*query).present, (*query).first_event) };
        if present == 0 {
            crcbl_core::log::debug!("the X server has no RANDR extension");
            return None;
        }

        // SAFETY: the connection is live; a null error pointer discards the
        // error, and a null reply is handled below.
        let reply = unsafe {
            let cookie = (randr.query_version)(self.raw(), 1, 3);
            (randr.query_version_reply)(self.raw(), cookie, core::ptr::null_mut())
        };
        if reply.is_null() {
            return None;
        }
        // SAFETY: `reply` is a live reply this call owns.
        let (major, minor) = unsafe { ((*reply).major_version, (*reply).minor_version) };
        // SAFETY: `reply` came from libxcb's `malloc` and is freed once.
        unsafe { ffi::free_reply(reply) };
        if major < 1 || (major == 1 && minor < 2) {
            crcbl_core::log::debug!(
                "RANDR {major}.{minor} predates CRTCs; monitors will not be enumerated"
            );
            return None;
        }

        // SAFETY: the connection and root window are live.
        unsafe {
            (randr.select_input)(
                self.raw(),
                self.root,
                ffi::value::RANDR_SCREEN_CHANGE_MASK
                    | ffi::value::RANDR_CRTC_CHANGE_MASK
                    | ffi::value::RANDR_OUTPUT_CHANGE_MASK,
            );
        }
        Some(first_event)
    }

    /// Checks that SHAPE can give a window an input shape, answering the
    /// library to give it with.
    ///
    /// `None` when libxcb-shape is missing, when the server has no SHAPE, or
    /// when it is older than 1.1, the version that added input shapes; then
    /// [`INPUT_REGION`](crate::ShellCaps::INPUT_REGION) stays clear.
    pub(super) fn setup_shape(&self) -> Option<&'static ffi::ShapeLib> {
        let shape = self.ext.shape?;
        // SAFETY: as `setup_randr` — libxcb owns the returned reply.
        let query =
            unsafe { (self.lib.get_extension_data)(self.raw(), ffi::extension_ptr(shape.id)) };
        if query.is_null() {
            return None;
        }
        // SAFETY: `query` is libxcb's cached reply.
        if unsafe { (*query).present } == 0 {
            crcbl_core::log::debug!("the X server has no SHAPE extension");
            return None;
        }
        // SAFETY: the connection is live; a null error pointer discards the
        // error, and a null reply is handled below.
        let reply = unsafe {
            let cookie = (shape.query_version)(self.raw());
            (shape.query_version_reply)(self.raw(), cookie, core::ptr::null_mut())
        };
        if reply.is_null() {
            return None;
        }
        // SAFETY: `reply` is a live reply this call owns.
        let (major, minor) = unsafe { ((*reply).major_version, (*reply).minor_version) };
        // SAFETY: freed exactly once.
        unsafe { ffi::free_reply(reply) };
        if (major, minor) < (1, 1) {
            crcbl_core::log::debug!("SHAPE {major}.{minor} has no input shapes");
            return None;
        }
        Some(shape)
    }

    /// The `dev_t` of the GPU the X server renders on, from DRI3 `Open`.
    ///
    /// The server hands back a descriptor for its own device node; its
    /// `st_rdev` is what a backend matches to an adapter's DRM node, as it does
    /// a Wayland compositor's dmabuf main device. `None` without libxcb-dri3,
    /// on a server with no DRI3 (Xvfb), or when the open is refused.
    pub(super) fn dri3_device(&self) -> Option<u64> {
        use std::os::fd::{FromRawFd, OwnedFd};
        use std::os::unix::fs::MetadataExt;

        let dri3 = self.ext.dri3?;
        // SAFETY: as `setup_randr` — libxcb owns the returned reply.
        let query =
            unsafe { (self.lib.get_extension_data)(self.raw(), ffi::extension_ptr(dri3.id)) };
        // SAFETY: `query` is libxcb's cached reply when it is not null.
        if query.is_null() || unsafe { (*query).present } == 0 {
            crcbl_core::log::debug!("the X server has no DRI3 extension");
            return None;
        }
        // SAFETY: the connection is live and `root` is its screen's root; a
        // null error pointer discards the error, and a null reply is handled.
        let reply = unsafe {
            let cookie = (dri3.open)(self.raw(), self.root, 0);
            (dri3.open_reply)(self.raw(), cookie, core::ptr::null_mut())
        };
        if reply.is_null() {
            return None;
        }
        // SAFETY: `reply` is a live reply this call owns, and its descriptor
        // array is inside it, `nfd` long.
        let fd = unsafe {
            if (*reply).nfd == 1 {
                Some(*(dri3.open_reply_fds)(self.raw(), reply))
            } else {
                None
            }
        };
        // SAFETY: freed exactly once; the descriptor was copied out above.
        unsafe { ffi::free_reply(reply) };
        // SAFETY: the reply passed this descriptor to us, and nothing else
        // holds it, so it is ours to own and close.
        let fd = unsafe { OwnedFd::from_raw_fd(fd?) };
        let device = std::fs::File::from(fd).metadata().ok()?.rdev();
        crcbl_core::log::debug!("crcbl-shell: the X server renders on DRM device {device:#x}");
        Some(device)
    }

    /// Negotiates XInput 2 and selects raw motion on the root window.
    ///
    /// Returns the extension's **major opcode**, not an event base — XI2
    /// delivers everything as `GeGeneric`, whose `extension` field is the
    /// opcode. That is the only way to tell an XI2 event from any other
    /// extension's generic event.
    ///
    /// # Why the root window, and why raw
    ///
    /// `XI_RawMotion` is only ever delivered to a selection on the **root**:
    /// raw events are pre-transform and pre-clipping, so they do not belong to
    /// any window and the server refuses to deliver them to one. That has a
    /// consequence worth stating, because it is a real difference from
    /// Wayland's `relative-pointer`, which is scoped to a `wl_pointer` on a
    /// focused surface: **this backend sees raw motion whether or not one of
    /// its windows is focused.** [`super::X11Shell`] therefore attributes raw
    /// motion to the focused window and drops it when none of ours is focused,
    /// rather than trusting the event to be about us.
    ///
    /// `None` when libxcb-xinput is missing or the server is XI1-only, and then
    /// [`RAW_POINTER_MOTION`](crate::ShellCaps::RAW_POINTER_MOTION) stays clear
    /// and a camera has to difference absolute positions — which is wrong at
    /// the screen edge, which is why the bit exists.
    pub(super) fn setup_xinput2(&self) -> Option<u8> {
        let xi = self.ext.xi?;
        // SAFETY: as `setup_randr` — libxcb owns the returned reply.
        let query = unsafe { (self.lib.get_extension_data)(self.raw(), ffi::extension_ptr(xi.id)) };
        if query.is_null() {
            return None;
        }
        // SAFETY: `query` is libxcb's cached reply.
        let (present, opcode) = unsafe { ((*query).present, (*query).major_opcode) };
        if present == 0 {
            crcbl_core::log::debug!("the X server has no XInputExtension");
            return None;
        }

        // SAFETY: the connection is live.
        let reply = unsafe {
            let cookie = (xi.query_version)(self.raw(), 2, 0);
            (xi.query_version_reply)(self.raw(), cookie, core::ptr::null_mut())
        };
        if reply.is_null() {
            return None;
        }
        // SAFETY: `reply` is a live reply this call owns.
        let major = unsafe { (*reply).major_version };
        // SAFETY: freed exactly once.
        unsafe { ffi::free_reply(reply) };
        if major < 2 {
            crcbl_core::log::debug!("the X server offers XInput {major} only; no raw motion");
            return None;
        }

        // `xcb_input_event_mask_t` is a two-field header immediately followed
        // by `mask_len` 32-bit words, laid out contiguously. Building it as a
        // `#[repr(C)]` pair is exactly that layout — a struct with the header
        // and one mask word, since one word covers every event number below 32.
        #[repr(C)]
        struct OneWordMask {
            header: ffi::XiEventMask,
            mask: u32,
        }
        let mask = OneWordMask {
            header: ffi::XiEventMask {
                deviceid: ffi::value::XI_ALL_MASTER_DEVICES,
                mask_len: 1,
            },
            mask: ffi::value::XI_RAW_MOTION_MASK,
        };
        // SAFETY: the connection and root are live, and `mask` is one
        // `xcb_input_event_mask_t` followed by its single declared mask word —
        // the layout `XISelectEvents` reads. It outlives the call, which
        // copies it into libxcb's request buffer.
        unsafe {
            (xi.select_events)(
                self.raw(),
                self.root,
                1,
                core::ptr::from_ref(&mask).cast::<ffi::XiEventMask>(),
            );
        }
        Some(opcode)
    }

    /// Asks the server to stop faking a `KeyRelease` in front of every
    /// auto-repeat, and reports whether it agreed.
    ///
    /// # Why this is not an optimisation
    ///
    /// The default X11 wire form of an auto-repeat is a `KeyRelease` followed
    /// **immediately** by a `KeyPress` of the same keycode at the same server
    /// millisecond, and neither half means what it says: the key never came up.
    /// The standard client-side answer is a one-event lookahead, which
    /// [`input`](super::input) implements — and which is only sound while both
    /// halves are in the same batch of events.
    ///
    /// **They are not always in the same batch.** A batch is whatever
    /// `xcb_poll_for_event` had buffered when `pump` asked, which is a
    /// socket-read boundary and not a protocol unit. On a loaded machine the
    /// pair splits, the lookahead sees a lone `KeyRelease`, and the backend
    /// emits a release for a key that is still down followed by a press that is
    /// not flagged as a repeat — the exact "jump button fires thirty times a
    /// second while held" failure the lookahead exists to prevent, appearing
    /// only under load. This was reproduced against `Xvfb`: two events, same
    /// keycode, same timestamp, one in each of two consecutive pumps.
    ///
    /// `XkbPerClientFlags(DetectableAutoRepeat)` removes the ambiguity at the
    /// source rather than guessing at it: the server stops synthesizing the
    /// release, a repeat arrives as a bare `KeyPress` of a key already held,
    /// and no lookahead — and therefore no batching assumption — is involved.
    /// It is per **client**, so nothing about any other application changes.
    ///
    /// `false` when libxcb-xkb is missing or the server has no XKB, and then
    /// the lookahead is what there is; see [`input`](super::input)'s module
    /// documentation for what that costs.
    pub(super) fn setup_detectable_auto_repeat(&self) -> bool {
        let Some(xkb) = self.ext.xkb else {
            return false;
        };
        // XKB refuses every other request from a client that has not announced
        // itself, so this round trip is mandatory rather than a version probe.
        // SAFETY: the connection is live; a null error pointer discards the
        // error and a null reply is handled below.
        let reply = unsafe {
            let cookie =
                (xkb.use_extension)(self.raw(), ffi::value::XKB_MAJOR, ffi::value::XKB_MINOR);
            (xkb.use_extension_reply)(self.raw(), cookie, core::ptr::null_mut())
        };
        if reply.is_null() {
            crcbl_core::log::debug!("the X server has no XKB extension");
            return false;
        }
        // SAFETY: `reply` is a live reply this call owns.
        let supported = unsafe { (*reply).supported };
        // SAFETY: freed exactly once.
        unsafe { ffi::free_reply(reply) };
        if supported == 0 {
            crcbl_core::log::debug!("the X server declined XKB 1.0");
            return false;
        }

        // SAFETY: the connection is live. The three trailing zeros are
        // `ctrlsToChange`, `autoCtrls` and `autoCtrlsValues`, none of which is
        // being touched — this changes one per-client flag and no keyboard
        // control.
        let reply = unsafe {
            let cookie = (xkb.per_client_flags)(
                self.raw(),
                ffi::value::XKB_USE_CORE_KBD,
                ffi::value::XKB_DETECTABLE_AUTO_REPEAT,
                ffi::value::XKB_DETECTABLE_AUTO_REPEAT,
                0,
                0,
                0,
            );
            (xkb.per_client_flags_reply)(self.raw(), cookie, core::ptr::null_mut())
        };
        if reply.is_null() {
            crcbl_core::log::debug!("XkbPerClientFlags failed; auto-repeat stays undetectable");
            return false;
        }
        // The reply is read back rather than assumed: a server may answer
        // without having set the bit, and a backend that believed the request
        // would then stop looking for repeat pairs that are still arriving.
        // SAFETY: `reply` is a live reply this call owns.
        let value = unsafe { (*reply).value };
        // SAFETY: freed exactly once.
        unsafe { ffi::free_reply(reply) };
        let enabled = value & ffi::value::XKB_DETECTABLE_AUTO_REPEAT != 0;
        if enabled {
            crcbl_core::log::debug!(
                "detectable auto-repeat is on; a repeat is a press of a held key"
            );
        } else {
            crcbl_core::log::debug!("the X server does not implement detectable auto-repeat");
        }
        enabled
    }

    /// Whether an EWMH-compliant window manager is running.
    ///
    /// The protocol's own two-step check, and both steps matter: the root
    /// carries `_NET_SUPPORTING_WM_CHECK` naming a window, and **that window
    /// carries the same property naming itself**. EWMH requires the second
    /// step precisely because the first survives a window manager that crashed
    /// — the root property is not cleaned up, so a one-step check reports a
    /// window manager that is not there, and every size hint is then
    /// advertised as honoured when nothing will honour it.
    ///
    /// A window manager started *after* this returns is deliberately not
    /// noticed; see [`X11Shell::latch_caps`](super::X11Shell::latch_caps).
    pub(super) fn detect_window_manager(&self) -> bool {
        let root_says = self.get_property_words(self.root, self.atoms.net_supporting_wm_check);
        let Some(&candidate) = root_says.first() else {
            return false;
        };
        if candidate == 0 {
            return false;
        }
        let it_says = self.get_property_words(candidate, self.atoms.net_supporting_wm_check);
        let confirmed = it_says.first() == Some(&candidate);
        if !confirmed {
            crcbl_core::log::debug!(
                "_NET_SUPPORTING_WM_CHECK on the root names window {candidate}, which does \
                 not confirm it — treating that as a window manager that died"
            );
        }
        confirmed
    }

    /// The desktop's scale factor, from `Xft.dpi`.
    ///
    /// # This is a string in a property, and that is not a shortcut
    ///
    /// X11 has no scale-factor protocol. `RESOURCE_MANAGER` on the root window
    /// is the X resource database — a newline-separated text file of
    /// `Name: value` lines, written by `xrdb`, read by every toolkit — and
    /// `Xft.dpi` in it is what GTK, Qt and SDL all actually use. So this parses
    /// text, and doing anything else would disagree with every other window on
    /// the desktop.
    ///
    /// **RandR's physical millimetres are deliberately not used.** They are
    /// available (see
    /// [`RandrOutputInfoReply::mm_width`](super::ffi::RandrOutputInfoReply))
    /// and computing a DPI from them is the classic mistake: a 15-inch 1080p
    /// laptop panel comes out at 141 DPI and would be scaled to 1.47×, which
    /// almost nobody wants, and many monitors report their millimetres wrong
    /// or not at all. Scale is a *preference*, and `Xft.dpi` is where the user
    /// expressed it.
    ///
    /// Clamped to a sane band: a malformed resource file must not produce a
    /// window a thousand times too big.
    pub(super) fn read_xft_scale(&self) -> f64 {
        let Some((_, _, bytes)) = self.get_property(self.root, ffi::value::ATOM_RESOURCE_MANAGER)
        else {
            return DEFAULT_SCALE;
        };
        // `RESOURCE_MANAGER` has type `STRING`, which in X11 is **Latin-1**,
        // not UTF-8 — so it is decoded byte-by-byte rather than validated.
        // Requiring the whole property to be valid UTF-8 meant one accented
        // character anywhere in a user's `.Xresources` — in a font name, a
        // colour comment, an unrelated application's resource — silently reset
        // the desktop scale to 1.0 and ignored a perfectly ASCII `Xft.dpi` two
        // lines further down.
        let text: String = bytes.iter().map(|byte| char::from(*byte)).collect();
        parse_xft_dpi(&text).map_or(DEFAULT_SCALE, |dpi| (dpi / BASE_DPI).clamp(0.5, 8.0))
    }
}

/// `Xft.dpi` out of an X resource database, or `None`.
///
/// A free function so the parser — the part that can be wrong about a real
/// user's `.Xresources` — is testable with no server. The format is
/// deliberately taken narrowly: `Xft.dpi` at the start of a line, a colon,
/// whitespace, a number. Resource files support wildcards, includes and
/// per-application prefixes, and honouring those would mean implementing
/// `xrdb`; what every toolkit actually looks for is this one line.
fn parse_xft_dpi(database: &str) -> Option<f64> {
    for line in database.lines() {
        let line = line.trim_start();
        let Some(rest) = line.strip_prefix("Xft.dpi") else {
            continue;
        };
        let Some(value) = rest.trim_start().strip_prefix(':') else {
            // `Xft.dpiFoo:` is a different resource, not this one.
            continue;
        };
        if let Ok(dpi) = value.trim().parse::<f64>()
            && dpi.is_finite()
            && dpi > 0.0
        {
            return Some(dpi);
        }
    }
    None
}

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

    /// The visual a transparent window needs: 32 bits, true colour, and bits
    /// its colour masks leave for alpha. Xwayland's and Xvfb's ARGB visual is
    /// the first; a 32-bit visual whose masks take every bit has no alpha.
    #[test]
    fn only_a_32_bit_true_colour_visual_with_spare_bits_has_alpha() {
        let visual = |class, red: u32, green: u32, blue: u32| ffi::VisualType {
            visual_id: 1,
            class,
            bits_per_rgb_value: 8,
            colormap_entries: 256,
            red_mask: red,
            green_mask: green,
            blue_mask: blue,
            pad0: [0; 4],
        };
        let argb = visual(
            ffi::value::TRUE_COLOR,
            0x00ff_0000,
            0x0000_ff00,
            0x0000_00ff,
        );
        assert!(is_argb(32, &argb));
        assert!(!is_argb(24, &argb), "a 24-bit depth has no room for alpha");
        let direct = visual(5, 0x00ff_0000, 0x0000_ff00, 0x0000_00ff);
        assert!(!is_argb(32, &direct), "direct colour is not true colour");
        let wide = visual(
            ffi::value::TRUE_COLOR,
            0xffc0_0000,
            0x003f_f800,
            0x0000_07ff,
        );
        assert!(!is_argb(32, &wide), "every bit is colour");
    }

    #[test]
    fn xft_dpi_is_read_the_way_a_real_xresources_file_writes_it() {
        // `xrdb` emits tab-separated lines; users write spaces. Both appear in
        // the wild and both have to work, because the alternative is a window
        // that is the wrong size on someone's desktop and right on ours.
        assert_eq!(parse_xft_dpi("Xft.dpi:\t192\n"), Some(192.0));
        assert_eq!(parse_xft_dpi("Xft.dpi: 120"), Some(120.0));
        assert_eq!(parse_xft_dpi("  Xft.dpi:96  "), Some(96.0));
        assert_eq!(
            parse_xft_dpi("*background:\t#000000\nXft.antialias:\t1\nXft.dpi:\t144\n"),
            Some(144.0),
            "one line among many"
        );
    }

    #[test]
    fn a_resource_that_merely_starts_with_the_name_is_not_the_one() {
        // `Xft.dpiScale` is not `Xft.dpi`, and a prefix match would read a
        // different setting's value as the scale.
        // A resource database is Latin-1, and a byte-by-byte decode of one is
        // what `read_xft_scale` hands this parser. A non-ASCII byte in an
        // unrelated resource must not hide the line below it.
        let latin1: String = b"Xft.dpiScale:\t2\n*faceName:\tCourier \xe9\nXft.dpi:\t144\n"
            .iter()
            .map(|byte| char::from(*byte))
            .collect();
        assert_eq!(parse_xft_dpi(&latin1), Some(144.0));

        assert_eq!(parse_xft_dpi("Xft.dpiScale:\t2\n"), None);
        assert_eq!(parse_xft_dpi("Xft.hinting:\t1\n"), None);
        assert_eq!(parse_xft_dpi(""), None);
        assert_eq!(parse_xft_dpi("Xft.dpi:\n"), None, "no value");
        assert_eq!(parse_xft_dpi("Xft.dpi:\tnonsense\n"), None);
        assert_eq!(parse_xft_dpi("Xft.dpi:\t0\n"), None, "zero is not a DPI");
        assert_eq!(parse_xft_dpi("Xft.dpi:\t-96\n"), None);
    }

    #[test]
    fn the_scale_is_the_dpi_over_ninety_six() {
        // The conversion every toolkit agrees on. 120 is the "125%" every
        // desktop settings panel offers, and it is *not* an integer scale —
        // which is what `ShellCaps::FRACTIONAL_SCALE` is asserting on X11.
        let scale = |dpi: f64| (dpi / BASE_DPI).clamp(0.5, 8.0);
        assert!((scale(96.0) - 1.0).abs() < f64::EPSILON);
        assert!((scale(120.0) - 1.25).abs() < f64::EPSILON);
        assert!((scale(144.0) - 1.5).abs() < f64::EPSILON);
        assert!((scale(192.0) - 2.0).abs() < f64::EPSILON);
        // A malformed database must not produce a window a thousand times too
        // big, or one that rounds to zero pixels.
        assert!((scale(1e9) - 8.0).abs() < f64::EPSILON);
        assert!((scale(1.0) - 0.5).abs() < f64::EPSILON);
    }
}