pinready 0.24.1

Cross-platform configurator and launcher supporting the adoption of Visual Pinball 10.8.1 — for testers and early adopters, not a replacement for a stable production setup
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
//! Launch-time display reconciliation across SDL video drivers.
//!
//! The wizard assigns roles to physical monitors and persists, per role, a
//! [`DisplayAnchor`](crate::display_id::DisplayAnchor) (layout position + EDID
//! fingerprint) — driver-independent. At launch we may run VPX under a
//! *different* SDL driver than the wizard used (the framerate escape hatch runs
//! VPX under XWayland while PinReady stays native Wayland), and the same
//! monitor is named differently there. This module re-resolves each role's
//! anchor to the target driver's SDL name and rewrites `*Display=` accordingly,
//! so VPX finds its screens whatever the driver.
//!
//! The switch is **atomic**: we only adopt the preferred driver if *every*
//! assigned role resolves under it; otherwise we leave the config untouched and
//! fall back to the session's own driver. No half-rewritten state ever reaches
//! VPX.

use crate::config::VpxConfig;
use crate::db::Database;
use crate::display_id::{self, DisplayAnchor, SdlDisplay};
use crate::screens::{DisplayInfo, DisplayRole};

/// `(role, ini section, `*Display*` key)` for the four assignable roles.
const ROLE_KEYS: &[(DisplayRole, &str, &str)] = &[
    (DisplayRole::Playfield, "Player", "PlayfieldDisplay"),
    (DisplayRole::Backglass, "Backglass", "BackglassDisplay"),
    (DisplayRole::Dmd, "ScoreView", "ScoreViewDisplay"),
    (DisplayRole::Topper, "Topper", "TopperDisplay"),
];

fn anchor_db_key(role: DisplayRole) -> String {
    format!("display_anchor_{role:?}")
}

fn serialize_anchor(a: &DisplayAnchor) -> String {
    format!(
        "{},{},{},{},{}",
        a.x,
        a.y,
        a.width,
        a.height,
        a.fingerprint.as_deref().unwrap_or("")
    )
}

fn parse_anchor(s: &str) -> Option<DisplayAnchor> {
    let mut it = s.splitn(5, ',');
    let x = it.next()?.parse().ok()?;
    let y = it.next()?.parse().ok()?;
    let width = it.next()?.parse().ok()?;
    let height = it.next()?.parse().ok()?;
    let fp = it.next().unwrap_or("");
    Some(DisplayAnchor {
        x,
        y,
        width,
        height,
        fingerprint: (!fp.is_empty()).then(|| fp.to_string()),
    })
}

fn load_anchor(db: &Database, role: DisplayRole) -> Option<DisplayAnchor> {
    db.get_config(&anchor_db_key(role))
        .as_deref()
        .and_then(parse_anchor)
}

/// Persist a [`DisplayAnchor`] per assigned role from the wizard's current
/// display enumeration (PinReady's own driver). The EDID fingerprint is filled
/// in by correlating against the kernel DRM monitors; roles whose monitor has
/// no usable EDID keep `fingerprint: None` and rely on position alone.
/// Where a corrected physical size is kept, keyed by display name.
fn size_db_key(name: &str) -> String {
    format!("display_size_mm:{name}")
}

/// Remember a physical size a human corrected, and only that.
///
/// The detected size is not stored: freezing it would pin today's detection
/// for everyone it already gets right, and would hide any later improvement
/// behind a number nobody chose. An override is written when the value in use
/// differs from what detection reported, and cleared when they agree again —
/// so correcting a size and then undoing the correction leaves nothing behind.
///
/// This exists because the size does reach VPX (`Player/ScreenWidth`) and never
/// came back: every launch re-enumerated and overwrote the correction, so an
/// owner whose 42-inch panel is reported as 72 had to fix it again every
/// single time.
pub fn persist_sizes(db: &Database, displays: &[DisplayInfo]) {
    for d in displays {
        let key = size_db_key(&d.name);
        let overridden = d.width_mm != d.detected_width_mm || d.height_mm != d.detected_height_mm;
        let value = if overridden && d.width_mm > 0 && d.height_mm > 0 {
            format!("{}x{}", d.width_mm, d.height_mm)
        } else {
            String::new()
        };
        if let Err(e) = db.set_config(&key, &value) {
            log::warn!("could not persist physical size for {}: {e}", d.name);
        }
    }
}

/// Put corrected sizes back on freshly enumerated displays.
///
/// Call right after [`crate::screens::enumerate_displays`]. A display with no
/// stored correction is left exactly as detection found it.
pub fn apply_saved_sizes(db: &Database, displays: &mut [DisplayInfo]) {
    for d in displays.iter_mut() {
        let Some(raw) = db.get_config(&size_db_key(&d.name)) else {
            continue;
        };
        let Some((w, h)) = parse_size_mm(&raw) else {
            continue;
        };
        log::info!(
            "display {}: using corrected size {w}x{h} mm (detection said {}x{})",
            d.name,
            d.detected_width_mm,
            d.detected_height_mm
        );
        d.width_mm = w;
        d.height_mm = h;
        d.size_inches = diagonal_inches(w, h);
    }
}

/// Put the roles the wizard saved back on freshly enumerated displays.
///
/// [`crate::screens::enumerate_displays`] only guesses roles from pixel count,
/// which cannot tell two 1920x1080 screens apart: the launcher covers and a
/// reopened wizard then put the backglass on the screen chosen as DMD. Each
/// assigned role is found by its `*Display=` name, else by its stored anchor.
/// All or nothing, like [`reconcile_all`]: if one assigned role is missing the
/// guessed roles are kept and the startup check sends the user to the wizard.
pub fn apply_saved_roles(config: &VpxConfig, db: &Database, displays: &mut [DisplayInfo]) {
    let mut found = Vec::new();
    for (role, section, key) in assigned_roles(config) {
        let name = config.get(section, key).unwrap_or_default();
        let idx = displays
            .iter()
            .position(|d| crate::vpx_display::matches(&name, &d.name, d.x, d.y))
            .or_else(|| anchored_display_index(db, role, displays));
        let Some(idx) = idx else {
            log::info!("saved {role:?} display {name:?} not found, keeping guessed roles");
            return;
        };
        found.push((role, idx));
    }
    restore_roles(displays, &found);
}

fn restore_roles(displays: &mut [DisplayInfo], found: &[(DisplayRole, usize)]) {
    if found.is_empty() {
        return;
    }
    for d in displays.iter_mut() {
        d.role = DisplayRole::Unused;
    }
    for &(role, idx) in found {
        displays[idx].role = role;
        log::info!("display {}: saved role {role:?}", displays[idx].name);
    }
}

/// `"932x540"` -> `(932, 540)`. Anything else is ignored rather than guessed
/// at: a malformed row should fall back to detection, not to zero.
fn parse_size_mm(raw: &str) -> Option<(i32, i32)> {
    let (w, h) = raw.trim().split_once('x')?;
    let (w, h) = (w.trim().parse().ok()?, h.trim().parse().ok()?);
    (w > 0 && h > 0).then_some((w, h))
}

/// Diagonal in inches from a size in millimetres.
fn diagonal_inches(w: i32, h: i32) -> Option<u32> {
    (w > 0 && h > 0).then(|| {
        let diag = ((f64::from(w)).powi(2) + (f64::from(h)).powi(2)).sqrt();
        (diag / 25.4).round() as u32
    })
}

pub fn persist_anchors(db: &Database, displays: &[DisplayInfo]) {
    let sdl: Vec<SdlDisplay> = displays.iter().map(to_sdl).collect();
    let correlation = display_id::correlate(&sdl, &display_id::read_drm_monitors());

    for &(role, _, _) in ROLE_KEYS {
        let Some(d) = displays.iter().find(|d| d.role == role) else {
            let _ = db.set_config(&anchor_db_key(role), "");
            continue;
        };
        let fingerprint = correlation
            .iter()
            .find(|(name, _)| *name == d.name)
            .map(|(_, id)| id.fingerprint.clone());
        let anchor = DisplayAnchor {
            x: d.x,
            y: d.y,
            width: d.width,
            height: d.height,
            fingerprint,
        };
        if let Err(e) = db.set_config(&anchor_db_key(role), &serialize_anchor(&anchor)) {
            log::warn!("could not persist display anchor for {role:?}: {e}");
        }
    }
}

fn to_sdl(d: &DisplayInfo) -> SdlDisplay {
    SdlDisplay {
        name: d.name.clone(),
        x: d.x,
        y: d.y,
        width: d.width,
        height: d.height,
        width_mm: d.width_mm,
        height_mm: d.height_mm,
    }
}

/// Index into `displays` of the monitor a role is anchored to, matched by the
/// stored anchor's layout position + size (driver-independent). `None` if the
/// role has no anchor or no current display sits at that geometry.
///
/// Used at window-creation time (before the name reconciliation runs), where
/// the ini's `*Display=` may still hold a name from another driver that won't
/// match the current SDL enumeration — the anchor resolves regardless.
pub fn anchored_display_index(
    db: &Database,
    role: DisplayRole,
    displays: &[DisplayInfo],
) -> Option<usize> {
    let a = load_anchor(db, role)?;
    displays
        .iter()
        .position(|d| d.x == a.x && d.y == a.y && d.width == a.width && d.height == a.height)
}

/// Enumerate the displays SDL reports under `driver`, by re-invoking ourselves
/// as `--enumerate-displays <driver>`. A subprocess keeps SDL's video driver
/// isolated from our own winit/Wayland stack; it inherits our session env
/// (`DISPLAY`/`WAYLAND_DISPLAY`/`XAUTHORITY`) so both drivers can connect.
pub fn enumerate_via_subprocess(driver: &str) -> Vec<SdlDisplay> {
    let Ok(exe) = std::env::current_exe() else {
        return Vec::new();
    };
    let out = match std::process::Command::new(exe)
        .arg("--enumerate-displays")
        .arg(driver)
        .output()
    {
        Ok(o) if o.status.success() => o.stdout,
        Ok(o) => {
            log::warn!(
                "--enumerate-displays {driver} exited {}: {}",
                o.status,
                String::from_utf8_lossy(&o.stderr).trim()
            );
            return Vec::new();
        }
        Err(e) => {
            log::warn!("could not spawn --enumerate-displays {driver}: {e}");
            return Vec::new();
        }
    };

    String::from_utf8_lossy(&out)
        .lines()
        .filter_map(|line| {
            // name \t x \t y \t w \t h \t refresh \t wmm \t hmm
            let f: Vec<&str> = line.split('\t').collect();
            if f.len() < 8 {
                return None;
            }
            Some(SdlDisplay {
                name: f[0].to_string(),
                x: f[1].parse().ok()?,
                y: f[2].parse().ok()?,
                width: f[3].parse().ok()?,
                height: f[4].parse().ok()?,
                width_mm: f[6].parse().ok()?,
                height_mm: f[7].parse().ok()?,
            })
        })
        .collect()
}

/// Roles that currently carry a non-empty `*Display=` in the config — i.e. the
/// screens VPX will actually try to open.
fn assigned_roles(config: &VpxConfig) -> Vec<(DisplayRole, &'static str, &'static str)> {
    ROLE_KEYS
        .iter()
        .copied()
        .filter(|&(_, section, key)| config.get(section, key).is_some_and(|v| !v.is_empty()))
        .collect()
}

/// Try to reconcile every assigned role's `*Display=` to `driver`'s SDL names.
///
/// Returns `true` and commits the rewrites only if **all** assigned roles
/// resolved; otherwise returns `false` and leaves `config` untouched (atomic).
fn reconcile_all(config: &mut VpxConfig, db: &Database, driver: &str) -> bool {
    let roles = assigned_roles(config);
    if roles.is_empty() {
        return false;
    }
    let sdl = enumerate_via_subprocess(driver);
    if sdl.is_empty() {
        return false; // could not enumerate — never wipe names
    }
    let correlation = display_id::correlate(&sdl, &display_id::read_drm_monitors());
    // VPX from rev 5515 wants the display id, name and position under its driver
    let ids = crate::vpx_display::uses_ids(config, db);

    // Resolve everything first; only apply if all succeed.
    let mut resolved = Vec::new();
    for (role, section, key) in roles {
        let Some(anchor) = load_anchor(db, role) else {
            return false; // no anchor for an assigned role → can't safely switch
        };
        let Some(name) = display_id::resolve_anchor(&anchor, &sdl, &correlation) else {
            return false; // monitor gone under this driver → bail
        };
        // The anchor's own geometry first (two same-named screens), else the
        // first display of that name
        let pos = sdl
            .iter()
            .find(|d| d.name == name && d.x == anchor.x && d.y == anchor.y)
            .or_else(|| sdl.iter().find(|d| d.name == name))
            .map(|d| (d.x, d.y));
        let Some((x, y)) = pos else {
            return false;
        };
        resolved.push((section, key, crate::vpx_display::value(&name, x, y, ids)));
    }
    for (section, key, name) in resolved {
        config.set(section, key, &name);
    }
    true
}

/// Which assigned roles' monitors are **not** currently present, checked in an
/// anchor-aware way: a role resolves if its [`DisplayAnchor`] resolves against
/// the currently-connected displays (by layout position or EDID fingerprint) —
/// regardless of what name the ini currently holds.
///
/// This supersedes the old raw-name check at startup: after a launch under a
/// different driver the ini may hold e.g. x11 names while PinReady runs
/// Wayland, and the anchor still resolves, so we no longer re-open the wizard
/// spuriously on an X11↔Wayland transition. Roles without a stored anchor fall
/// back to the legacy name match. Returns the `*Display=` values that failed.
pub fn unresolvable_assigned_displays(
    config: &VpxConfig,
    db: &Database,
    connected: &[DisplayInfo],
) -> Vec<String> {
    let sdl: Vec<SdlDisplay> = connected.iter().map(to_sdl).collect();
    let correlation = display_id::correlate(&sdl, &display_id::read_drm_monitors());

    let mut unresolved = Vec::new();
    for &(role, section, key) in ROLE_KEYS {
        let Some(name) = config.get(section, key).filter(|v| !v.is_empty()) else {
            continue; // role not assigned
        };
        let ok = match load_anchor(db, role) {
            Some(anchor) => display_id::resolve_anchor(&anchor, &sdl, &correlation).is_some(),
            // legacy fallback
            None => connected
                .iter()
                .any(|d| crate::vpx_display::matches(&name, &d.name, d.x, d.y)),
        };
        if !ok {
            unresolved.push(name);
        }
    }
    unresolved
}

/// The `{prefix}FullScreen` value a secondary VPX window (backglass / DMD /
/// topper) should use for the given session.
///
/// Under a **real X11 (Xorg)** session, gnome-shell does not map a
/// borderless-fullscreen window placed on a non-primary output — the window is
/// created (VPX logs it on the right display) but stays invisible, showing the
/// desktop. Windowed mode (`0`) maps correctly and VPX still positions it on
/// the target monitor via `*Display=`. Under Wayland/XWayland, borderless
/// fullscreen (`1`) works, so keep it.
///
/// The playfield (primary output) maps fine at borderless fullscreen
/// everywhere and is left untouched — this only governs the secondary windows.
fn secondary_fullscreen(session: Option<&str>) -> i32 {
    if session == Some("x11") { 0 } else { 1 }
}

/// Reconcile the `{prefix}FullScreen` mode of the assigned secondary displays
/// to the current session (see [`secondary_fullscreen`]). Only touches
/// FullScreen; positions/sizes/refresh are untouched.
fn reconcile_fullscreen(config: &mut VpxConfig, session: Option<&str>) {
    let fs = secondary_fullscreen(session);
    for (disp_section, disp_key, fs_key) in [
        ("Backglass", "BackglassDisplay", "BackglassFullScreen"),
        ("ScoreView", "ScoreViewDisplay", "ScoreViewFullScreen"),
        ("Topper", "TopperDisplay", "TopperFullScreen"),
    ] {
        let assigned = config
            .get(disp_section, disp_key)
            .is_some_and(|v| !v.is_empty());
        if assigned {
            config.set_i32(disp_section, fs_key, fs);
        }
    }
}

/// Pick the SDL video driver to launch VPX under, reconciling `*Display=` names
/// and the secondary-window fullscreen mode to the current environment.
///
/// Prefers the framerate-optimal driver ([`preferred_vpx_driver`]): native
/// Wayland when the compositor supports `wp_fifo_v1`, else XWayland. That
/// switch is taken only when every assigned screen re-resolves under it
/// (config rewritten in place); otherwise we fall back to the session's own
/// driver with the names left as the wizard wrote them.
///
/// [`preferred_vpx_driver`]: crate::wayland_caps::preferred_vpx_driver
pub fn choose_driver_and_reconcile(config: &mut VpxConfig, db: &Database) -> Option<&'static str> {
    let session = crate::session::detect();
    // Secondary-window fullscreen mode depends on the session (real X11 vs
    // Wayland/XWayland), independent of the name reconciliation below.
    reconcile_fullscreen(config, session);
    if let Some(preferred) = crate::wayland_caps::preferred_vpx_driver(session) {
        if reconcile_all(config, db, preferred) {
            log::info!("VPX display driver: {preferred} (screens reconciled)");
            return Some(preferred);
        }
        log::info!(
            "VPX display driver: falling back to session driver {:?} \
             (preferred {preferred} could not reconcile all screens)",
            session
        );
    }
    session
}

#[cfg(test)]
mod tests {

    /// A size that matches detection is not an override, and storing it would
    /// pin today's detection for someone it already gets right.
    #[test]
    fn only_a_corrected_size_is_remembered() {
        assert_eq!(super::parse_size_mm("932x540"), Some((932, 540)));
        assert_eq!(super::parse_size_mm(" 932 x 540 "), Some((932, 540)));
        // An empty row is how "no override" is written; it must not parse to
        // a zero size that would then be shown as the real one.
        assert_eq!(super::parse_size_mm(""), None);
        assert_eq!(super::parse_size_mm("0x0"), None);
        assert_eq!(super::parse_size_mm("932"), None);
        assert_eq!(super::parse_size_mm("nonsense"), None);
    }

    /// The inches beside the name are derived, so a corrected size has to
    /// correct them too — otherwise the panel stays labelled 72 inches while
    /// carrying the millimetres of a 42.
    #[test]
    fn correcting_the_millimetres_corrects_the_inches() {
        // What the Windows API reported for a 42-inch panel.
        assert_eq!(super::diagonal_inches(1600, 900), Some(72));
        // What it actually measures.
        assert_eq!(super::diagonal_inches(932, 540), Some(42));
        assert_eq!(super::diagonal_inches(0, 0), None);
    }
    use super::*;

    fn display(name: &str, x: i32, w: i32, h: i32) -> DisplayInfo {
        DisplayInfo {
            name: name.to_string(),
            x,
            y: 0,
            width: w,
            height: h,
            refresh_rate: 60.0,
            best_mode: None,
            is_primary: false,
            total_pixels: w as u64 * h as u64,
            size_inches: None,
            width_mm: 0,
            height_mm: 0,
            detected_width_mm: 0,
            detected_height_mm: 0,
            role: DisplayRole::Unused,
            monitor_index: 0,
            content_scale: 1.0,
            native_handle: None,
        }
    }

    /// Two 1920x1080 secondaries: the pixel-count guess gives the backglass to
    /// the first one listed, the saved roles must win over it.
    #[test]
    fn saved_roles_beat_the_pixel_count_guess() {
        let mut d = vec![
            display("LG TV SSCR2", 0, 3840, 2160),
            display("Monitor", 5760, 1920, 1080),
            display("DELL S2721QS", 3840, 1920, 1080),
        ];
        d[0].role = DisplayRole::Playfield;
        d[1].role = DisplayRole::Backglass;
        d[2].role = DisplayRole::Dmd;
        restore_roles(
            &mut d,
            &[
                (DisplayRole::Playfield, 0),
                (DisplayRole::Backglass, 2),
                (DisplayRole::Dmd, 1),
            ],
        );
        assert_eq!(d[0].role, DisplayRole::Playfield);
        assert_eq!(d[1].role, DisplayRole::Dmd);
        assert_eq!(d[2].role, DisplayRole::Backglass);
    }

    /// A screen the wizard left unused must not keep a guessed role.
    #[test]
    fn unsaved_screens_become_unused() {
        let mut d = vec![display("A", 0, 3840, 2160), display("B", 3840, 1920, 1080)];
        d[1].role = DisplayRole::Backglass;
        restore_roles(&mut d, &[(DisplayRole::Playfield, 0)]);
        assert_eq!(d[0].role, DisplayRole::Playfield);
        assert_eq!(d[1].role, DisplayRole::Unused);
    }

    #[test]
    fn anchor_roundtrip_with_fingerprint() {
        let a = DisplayAnchor {
            x: 0,
            y: 0,
            width: 3840,
            height: 2160,
            fingerprint: Some("deadbeef".into()),
        };
        let parsed = parse_anchor(&serialize_anchor(&a)).unwrap();
        assert_eq!(parsed.x, 0);
        assert_eq!(parsed.width, 3840);
        assert_eq!(parsed.fingerprint.as_deref(), Some("deadbeef"));
    }

    #[test]
    fn anchor_roundtrip_without_fingerprint() {
        let a = DisplayAnchor {
            x: 3840,
            y: 0,
            width: 1920,
            height: 1080,
            fingerprint: None,
        };
        let parsed = parse_anchor(&serialize_anchor(&a)).unwrap();
        assert_eq!(parsed.x, 3840);
        assert_eq!(parsed.fingerprint, None);
    }

    #[test]
    fn parse_anchor_rejects_short() {
        assert!(parse_anchor("0,0,3840").is_none());
    }

    #[test]
    fn secondary_windows_are_windowed_only_under_real_x11() {
        // Real Xorg session → windowed (gnome-shell X11 won't map borderless FS
        // on secondary outputs). Wayland session (incl. VPX-on-XWayland) and the
        // non-Linux None case → borderless fullscreen.
        assert_eq!(secondary_fullscreen(Some("x11")), 0);
        assert_eq!(secondary_fullscreen(Some("wayland")), 1);
        assert_eq!(secondary_fullscreen(None), 1);
    }
}