modde-games 0.1.0

Game plugin implementations for modde
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
//! Unified game detection across Steam and Heroic launchers.
//!
//! Scans all known launcher libraries and returns every detected game
//! installation, including launcher metadata. This allows the UI and CLI
//! to present a "pick your game" experience without manual path entry.

use std::path::{Path, PathBuf};
use std::process::{Command, ExitStatus, Stdio};

use anyhow::{Context, Result};
use serde_json::Value;
use tracing::{debug, info, warn};

use modde_core::paths;

/// A game installation detected by scanning launcher libraries.
#[derive(Debug, Clone)]
pub struct DetectedGame {
    /// The modde game_id (e.g. "skyrim-se", "cyberpunk2077").
    pub game_id: &'static str,
    /// Human-readable display name.
    pub display_name: &'static str,
    /// Absolute path to the game's install directory.
    pub install_path: PathBuf,
    /// Which launcher owns this installation.
    pub source: LauncherSource,
}

/// Which launcher/store a detected game belongs to.
#[derive(Debug, Clone)]
pub enum LauncherSource {
    Steam {
        app_id: String,
        library_path: PathBuf,
    },
    HeroicGog {
        app_id: String,
    },
    HeroicEpic {
        app_id: String,
    },
    HeroicSideload {
        app_id: String,
    },
}

impl LauncherSource {
    fn label_and_id(&self) -> (&str, &str) {
        match self {
            LauncherSource::Steam { app_id, .. } => ("Steam", app_id),
            LauncherSource::HeroicGog { app_id } => ("Heroic/GOG", app_id),
            LauncherSource::HeroicEpic { app_id } => ("Heroic/Epic", app_id),
            LauncherSource::HeroicSideload { app_id } => ("Heroic/Sideload", app_id),
        }
    }

    /// Launch the game via its detected launcher.
    ///
    /// Returns `Ok(Some(ExitStatus))` if we could wait for the game process to exit
    /// (Heroic), or `Ok(None)` for fire-and-forget launchers (Steam).
    pub fn launch(&self) -> Result<Option<ExitStatus>> {
        match self {
            LauncherSource::Steam { app_id, .. } => {
                let url = format!("steam://rungameid/{app_id}");
                info!(%url, "launching via Steam");
                open::that(&url)
                    .with_context(|| format!("failed to launch Steam via URI ({url})"))?;
                Ok(None)
            }
            LauncherSource::HeroicGog { app_id }
            | LauncherSource::HeroicEpic { app_id }
            | LauncherSource::HeroicSideload { app_id } => {
                let (bin, base_args) = heroic_command()
                    .context("Heroic Games Launcher not found (checked flatpak and PATH)")?;
                info!(%bin, %app_id, "launching via Heroic");
                let mut cmd = Command::new(&bin);
                for arg in &base_args {
                    cmd.arg(arg);
                }
                let status = cmd
                    .args(["--no-gui", "--launch", app_id])
                    .status()
                    .with_context(|| format!("failed to launch Heroic ({bin} --no-gui --launch {app_id})"))?;
                Ok(Some(status))
            }
        }
    }
}

impl std::fmt::Display for LauncherSource {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let (label, id) = self.label_and_id();
        write!(f, "{label} ({id})")
    }
}

/// Known game identifiers for matching against launcher databases.
///
/// Each entry maps a modde `game_id` to the IDs used by various launchers.
struct KnownGame {
    game_id: &'static str,
    display_name: &'static str,
    /// Steam app ID (None if not on Steam).
    steam_app_id: Option<&'static str>,
    /// Steam directory name under `steamapps/common/`.
    steam_dir: Option<&'static str>,
    /// GOG app ID for Heroic (None if not on GOG).
    gog_app_id: Option<&'static str>,
    /// Epic/Legendary app name (None if not on Epic).
    epic_app_id: Option<&'static str>,
}

/// Registry of all known games and their launcher identifiers.
const KNOWN_GAMES: &[KnownGame] = &[
    KnownGame {
        game_id: "skyrim-se",
        display_name: "The Elder Scrolls V: Skyrim Special Edition",
        steam_app_id: Some("489830"),
        steam_dir: Some("Skyrim Special Edition"),
        gog_app_id: None,
        epic_app_id: None,
    },
    // AE shares the same Steam dir as SE — detected as skyrim-se by default.
    // Users can override to skyrim-ae in settings.
    KnownGame {
        game_id: "fallout4",
        display_name: "Fallout 4",
        steam_app_id: Some("377160"),
        steam_dir: Some("Fallout 4"),
        gog_app_id: Some("1998527297"),
        epic_app_id: None,
    },
    KnownGame {
        game_id: "fallout76",
        display_name: "Fallout 76",
        steam_app_id: Some("1151340"),
        steam_dir: Some("Fallout76"),
        gog_app_id: None,
        epic_app_id: None,
    },
    KnownGame {
        game_id: "starfield",
        display_name: "Starfield",
        steam_app_id: Some("1716740"),
        steam_dir: Some("Starfield"),
        gog_app_id: None,
        epic_app_id: None,
    },
    KnownGame {
        game_id: "cyberpunk2077",
        display_name: "Cyberpunk 2077",
        steam_app_id: Some("1091500"),
        steam_dir: Some("Cyberpunk 2077"),
        gog_app_id: Some("1423049311"),
        epic_app_id: Some("Ginger"),
    },
    KnownGame {
        game_id: "stellar-blade",
        display_name: "Stellar Blade",
        steam_app_id: Some("3489700"),
        // Steam installs under `steamapps/common/Stellar Blade` — if your
        // install uses the trademark glyph ("Stellar Blade™"), update this.
        steam_dir: Some("Stellar Blade"),
        gog_app_id: None,
        epic_app_id: None,
    },
];

/// Detect the Heroic Games Launcher binary.
///
/// - Linux: checks flatpak first, then native binary on `$PATH`
/// - macOS: checks `/Applications/Heroic.app`, then `$PATH`
/// - Windows: checks standard install path, then `%PATH%`
///
/// Returns `(binary, base_args)` — e.g. `("flatpak", ["run", "com.heroicgameslauncher.hgl"])`
/// or `("heroic", [])`.
fn heroic_command() -> Option<(String, Vec<String>)> {
    #[cfg(target_os = "linux")]
    {
        // Check flatpak first (common on NixOS / immutable distros)
        if Command::new("flatpak")
            .args(["info", "com.heroicgameslauncher.hgl"])
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .status()
            .ok()
            .map(|s| s.success())
            .unwrap_or(false)
        {
            return Some((
                "flatpak".to_string(),
                vec!["run".to_string(), "com.heroicgameslauncher.hgl".to_string()],
            ));
        }

        // Check native binary on PATH
        if let Ok(path) = which::which("heroic") {
            return Some((path.to_string_lossy().to_string(), vec![]));
        }

        None
    }

    #[cfg(target_os = "macos")]
    {
        let app_path = "/Applications/Heroic.app/Contents/MacOS/Heroic";
        if std::path::Path::new(app_path).exists() {
            return Some((app_path.to_string(), vec![]));
        }
        if let Ok(path) = which::which("heroic") {
            return Some((path.to_string_lossy().to_string(), vec![]));
        }
        None
    }

    #[cfg(target_os = "windows")]
    {
        if let Some(exe) = modde_core::paths::heroic_exe_path() {
            return Some((exe.to_string_lossy().to_string(), vec![]));
        }
        if let Ok(path) = which::which("heroic") {
            return Some((path.to_string_lossy().to_string(), vec![]));
        }
        None
    }
}

/// Find a detected game by its modde game_id.
///
/// Convenience wrapper around [`scan_installed_games`] that returns the first
/// match. Used by both CLI and UI to resolve the launcher for a game.
pub fn find_detected_game(game_id: &str) -> Option<DetectedGame> {
    scan_installed_games()
        .into_iter()
        .find(|g| g.game_id == game_id)
}

/// Scan all known launchers for installed games.
///
/// Returns every detected game with its install path and launcher source.
/// A game may appear multiple times if installed via different launchers.
pub fn scan_installed_games() -> Vec<DetectedGame> {
    let mut detected = Vec::new();

    scan_steam_libraries(&mut detected);
    scan_heroic_stores(&mut detected);

    detected
}

/// Scan all Steam library folders for known games.
fn scan_steam_libraries(detected: &mut Vec<DetectedGame>) {
    let libraries = paths::steam_library_folders();

    for lib_path in &libraries {
        let common_dir = lib_path.join("steamapps/common");
        if !common_dir.is_dir() {
            continue;
        }

        for game in KNOWN_GAMES {
            let Some(steam_dir) = game.steam_dir else {
                continue;
            };

            let install_path = common_dir.join(steam_dir);
            if install_path.is_dir() {
                debug!(
                    game_id = game.game_id,
                    path = %install_path.display(),
                    "detected Steam game"
                );
                detected.push(DetectedGame {
                    game_id: game.game_id,
                    display_name: game.display_name,
                    install_path,
                    source: LauncherSource::Steam {
                        app_id: game.steam_app_id.unwrap_or("unknown").to_string(),
                        library_path: lib_path.clone(),
                    },
                });
            }
        }
    }
}

/// Scan Heroic's installed game databases (GOG, Epic/Legendary, Sideload).
fn scan_heroic_stores(detected: &mut Vec<DetectedGame>) {
    let Some(heroic_dir) = paths::heroic_config_dir() else {
        return;
    };

    // GOG store
    scan_heroic_store_file(
        &heroic_dir.join("gog_store/installed.json"),
        |app_id| {
            KNOWN_GAMES
                .iter()
                .find(|g| g.gog_app_id == Some(app_id))
                .map(|g| (g, HeroicStoreKind::Gog))
        },
        detected,
    );

    // Epic/Legendary store
    scan_heroic_store_file(
        &heroic_dir.join("legendary_store/installed.json"),
        |app_id| {
            KNOWN_GAMES
                .iter()
                .find(|g| g.epic_app_id == Some(app_id))
                .map(|g| (g, HeroicStoreKind::Epic))
        },
        detected,
    );

    // Sideloaded apps — match by directory name heuristic
    scan_heroic_sideload(&heroic_dir.join("sideload_apps/installed.json"), detected);
}

#[derive(Clone, Copy)]
enum HeroicStoreKind {
    Gog,
    Epic,
}

/// Parse a Heroic `installed.json` and match entries against known games.
fn scan_heroic_store_file(
    path: &Path,
    matcher: impl Fn(&str) -> Option<(&KnownGame, HeroicStoreKind)>,
    detected: &mut Vec<DetectedGame>,
) {
    let data = match std::fs::read_to_string(path) {
        Ok(d) => d,
        Err(e) => {
            debug!(error = %e, path = %path.display(), "failed to read Heroic store file");
            return;
        }
    };

    let parsed: Value = match serde_json::from_str(&data) {
        Ok(v) => v,
        Err(e) => {
            warn!(error = %e, path = %path.display(), "failed to parse Heroic store JSON");
            return;
        }
    };

    let Some(installed) = parsed.get("installed").and_then(|v| v.as_array()) else {
        debug!(path = %path.display(), "Heroic store file missing 'installed' array");
        return;
    };

    for entry in installed {
        let Some(app_name) = entry.get("appName").and_then(|v| v.as_str()) else {
            continue;
        };
        let Some(install_path) = entry.get("install_path").and_then(|v| v.as_str()) else {
            continue;
        };

        let install_path = PathBuf::from(install_path);
        if !install_path.is_dir() {
            continue;
        }

        if let Some((game, kind)) = matcher(app_name) {
            debug!(
                game_id = game.game_id,
                app_name,
                path = %install_path.display(),
                "detected Heroic game"
            );
            let source = match kind {
                HeroicStoreKind::Gog => LauncherSource::HeroicGog {
                    app_id: game.gog_app_id.unwrap_or(app_name).to_string(),
                },
                HeroicStoreKind::Epic => LauncherSource::HeroicEpic {
                    app_id: game.epic_app_id.unwrap_or(app_name).to_string(),
                },
            };
            detected.push(DetectedGame {
                game_id: game.game_id,
                display_name: game.display_name,
                install_path,
                source,
            });
        }
    }
}

/// Scan Heroic sideloaded apps — match by directory name against known steam_dir names.
fn scan_heroic_sideload(path: &Path, detected: &mut Vec<DetectedGame>) {
    let data = match std::fs::read_to_string(path) {
        Ok(d) => d,
        Err(e) => {
            debug!(error = %e, path = %path.display(), "failed to read Heroic sideload file");
            return;
        }
    };

    let parsed: Value = match serde_json::from_str(&data) {
        Ok(v) => v,
        Err(e) => {
            warn!(error = %e, path = %path.display(), "failed to parse Heroic sideload JSON");
            return;
        }
    };

    let Some(installed) = parsed.get("installed").and_then(|v| v.as_array()) else {
        debug!(path = %path.display(), "Heroic sideload file missing 'installed' array");
        return;
    };

    for entry in installed {
        let Some(app_name) = entry.get("appName").and_then(|v| v.as_str()) else {
            continue;
        };
        let Some(install_path_str) = entry.get("install_path").and_then(|v| v.as_str()) else {
            continue;
        };

        let install_path = PathBuf::from(install_path_str);
        if !install_path.is_dir() {
            continue;
        }

        // Try to match by directory name
        let dir_name = install_path
            .file_name()
            .and_then(|n| n.to_str())
            .unwrap_or("");

        for game in KNOWN_GAMES {
            let matches = game
                .steam_dir
                .map(|sd| sd.eq_ignore_ascii_case(dir_name))
                .unwrap_or(false);

            if matches {
                debug!(
                    game_id = game.game_id,
                    app_name,
                    path = %install_path.display(),
                    "detected Heroic sideloaded game"
                );
                detected.push(DetectedGame {
                    game_id: game.game_id,
                    display_name: game.display_name,
                    install_path,
                    source: LauncherSource::HeroicSideload {
                        app_id: app_name.to_string(),
                    },
                });
                break;
            }
        }
    }
}

/// Find the install path for a specific game by scanning all launchers.
///
/// This is used by `GamePlugin::detect_install()` implementations to check
/// all available sources instead of just hardcoded paths.
pub fn find_game_install(game_id: &str) -> Option<PathBuf> {
    // Check settings override first
    let settings = modde_core::settings::AppSettings::load();
    if let Some(path) = settings.game_path(game_id) {
        if path.is_dir() {
            return Some(path.clone());
        }
    }

    // Scan all launchers
    scan_installed_games()
        .into_iter()
        .find(|g| g.game_id == game_id)
        .map(|g| g.install_path)
}

#[cfg(test)]
mod tests {
    use super::*;
    // ── Heroic store file parsing ─────────────────────────────────────

    fn write_heroic_installed(dir: &std::path::Path, entries: &[(&str, &str)]) {
        let items: Vec<serde_json::Value> = entries
            .iter()
            .map(|(app_name, install_path)| {
                serde_json::json!({
                    "appName": app_name,
                    "install_path": install_path,
                })
            })
            .collect();
        let json = serde_json::json!({ "installed": items });
        std::fs::write(dir, serde_json::to_string(&json).unwrap()).unwrap();
    }

    #[test]
    fn scan_heroic_gog_detects_known_game() {
        let tmp = tempfile::tempdir().unwrap();
        let install_dir = tmp.path().join("cyberpunk");
        std::fs::create_dir_all(&install_dir).unwrap();

        let store_file = tmp.path().join("installed.json");
        write_heroic_installed(&store_file, &[("1423049311", &install_dir.to_string_lossy())]);

        let mut detected = Vec::new();
        scan_heroic_store_file(
            &store_file,
            |app_id| {
                KNOWN_GAMES
                    .iter()
                    .find(|g| g.gog_app_id == Some(app_id))
                    .map(|g| (g, HeroicStoreKind::Gog))
            },
            &mut detected,
        );

        assert_eq!(detected.len(), 1);
        assert_eq!(detected[0].game_id, "cyberpunk2077");
        assert_eq!(detected[0].install_path, install_dir);
        assert!(matches!(detected[0].source, LauncherSource::HeroicGog { .. }));
    }

    #[test]
    fn scan_heroic_gog_unknown_game_ignored() {
        let tmp = tempfile::tempdir().unwrap();
        let install_dir = tmp.path().join("some_game");
        std::fs::create_dir_all(&install_dir).unwrap();

        let store_file = tmp.path().join("installed.json");
        write_heroic_installed(&store_file, &[("9999999999", &install_dir.to_string_lossy())]);

        let mut detected = Vec::new();
        scan_heroic_store_file(
            &store_file,
            |app_id| {
                KNOWN_GAMES
                    .iter()
                    .find(|g| g.gog_app_id == Some(app_id))
                    .map(|g| (g, HeroicStoreKind::Gog))
            },
            &mut detected,
        );

        assert_eq!(detected.len(), 0, "unknown game should not be added");
    }

    #[test]
    fn scan_heroic_nonexistent_install_path_skipped() {
        let tmp = tempfile::tempdir().unwrap();
        let store_file = tmp.path().join("installed.json");
        // Path does not exist on disk
        write_heroic_installed(&store_file, &[("1423049311", "/nonexistent/cyberpunk")]);

        let mut detected = Vec::new();
        scan_heroic_store_file(
            &store_file,
            |app_id| {
                KNOWN_GAMES
                    .iter()
                    .find(|g| g.gog_app_id == Some(app_id))
                    .map(|g| (g, HeroicStoreKind::Gog))
            },
            &mut detected,
        );

        assert_eq!(detected.len(), 0, "nonexistent install path should be skipped");
    }

    #[test]
    fn scan_heroic_missing_file_is_no_op() {
        let mut detected = Vec::new();
        // Should not panic
        scan_heroic_store_file(
            std::path::Path::new("/nonexistent/installed.json"),
            |_| None,
            &mut detected,
        );
        assert_eq!(detected.len(), 0);
    }

    #[test]
    fn scan_heroic_malformed_json_is_no_op() {
        let tmp = tempfile::tempdir().unwrap();
        let store_file = tmp.path().join("installed.json");
        std::fs::write(&store_file, "this is not json").unwrap();

        let mut detected = Vec::new();
        scan_heroic_store_file(
            &store_file,
            |_| None,
            &mut detected,
        );
        assert_eq!(detected.len(), 0);
    }

    #[test]
    fn scan_heroic_empty_installed_array() {
        let tmp = tempfile::tempdir().unwrap();
        let store_file = tmp.path().join("installed.json");
        std::fs::write(&store_file, r#"{"installed":[]}"#).unwrap();

        let mut detected = Vec::new();
        scan_heroic_store_file(
            &store_file,
            |_| None,
            &mut detected,
        );
        assert_eq!(detected.len(), 0);
    }

    #[test]
    fn scan_heroic_sideload_matches_by_dirname() {
        let tmp = tempfile::tempdir().unwrap();
        // Create a dir named like the Cyberpunk Steam dir
        let install_dir = tmp.path().join("Cyberpunk 2077");
        std::fs::create_dir_all(&install_dir).unwrap();

        let store_file = tmp.path().join("installed.json");
        write_heroic_installed(&store_file, &[("some_sideload_id", &install_dir.to_string_lossy())]);

        let mut detected = Vec::new();
        scan_heroic_sideload(&store_file, &mut detected);

        assert_eq!(detected.len(), 1);
        assert_eq!(detected[0].game_id, "cyberpunk2077");
        assert!(matches!(detected[0].source, LauncherSource::HeroicSideload { .. }));
    }

    #[test]
    fn scan_heroic_sideload_unknown_dirname_ignored() {
        let tmp = tempfile::tempdir().unwrap();
        let install_dir = tmp.path().join("Some Unknown Game 2077");
        std::fs::create_dir_all(&install_dir).unwrap();

        let store_file = tmp.path().join("installed.json");
        write_heroic_installed(&store_file, &[("some_id", &install_dir.to_string_lossy())]);

        let mut detected = Vec::new();
        scan_heroic_sideload(&store_file, &mut detected);

        assert_eq!(detected.len(), 0);
    }

    // ── Steam library scanning ────────────────────────────────────────

    #[test]
    fn scan_steam_libraries_detects_game_in_common() {
        let tmp = tempfile::tempdir().unwrap();
        // Create a fake Steam library with "Cyberpunk 2077" in steamapps/common/
        let common = tmp.path().join("steamapps/common/Cyberpunk 2077");
        std::fs::create_dir_all(&common).unwrap();

        // Temporarily override HOME to point to our temp dir so steam_library_folders works
        // Instead, we directly test scan_steam_libraries by injecting a mock path.
        // We can do this by patching the paths module — but since we can't do that easily,
        // we test via the internal helper by constructing the detection directly.
        let detected_game = KNOWN_GAMES.iter().find(|g| g.game_id == "cyberpunk2077").unwrap();
        let install_path = common.clone();
        assert_eq!(install_path.file_name().unwrap(), "Cyberpunk 2077");
        assert!(install_path.is_dir());
        // If we had a real Steam library here, scan_steam_libraries would find this.
        // This is a structural test asserting KNOWN_GAMES has the right steam_dir.
        assert_eq!(detected_game.steam_dir, Some("Cyberpunk 2077"));
    }

    // ── LauncherSource display ────────────────────────────────────────

    #[test]
    fn launcher_source_display_steam() {
        let src = LauncherSource::Steam {
            app_id: "1091500".to_string(),
            library_path: PathBuf::from("/games"),
        };
        assert_eq!(src.to_string(), "Steam (1091500)");
    }

    #[test]
    fn launcher_source_display_heroic_gog() {
        let src = LauncherSource::HeroicGog { app_id: "1423049311".to_string() };
        assert_eq!(src.to_string(), "Heroic/GOG (1423049311)");
    }

    #[test]
    fn launcher_source_display_heroic_epic() {
        let src = LauncherSource::HeroicEpic { app_id: "Ginger".to_string() };
        assert_eq!(src.to_string(), "Heroic/Epic (Ginger)");
    }

    #[test]
    fn launcher_source_display_sideload() {
        let src = LauncherSource::HeroicSideload { app_id: "custom_app".to_string() };
        assert_eq!(src.to_string(), "Heroic/Sideload (custom_app)");
    }

    // ── KNOWN_GAMES integrity ─────────────────────────────────────────

    #[test]
    fn known_games_ids_are_unique() {
        let ids: Vec<_> = KNOWN_GAMES.iter().map(|g| g.game_id).collect();
        let deduped: std::collections::HashSet<_> = ids.iter().collect();
        assert_eq!(ids.len(), deduped.len(), "KNOWN_GAMES has duplicate game_ids");
    }

    #[test]
    fn known_games_includes_supported_games() {
        use crate::SUPPORTED_GAME_IDS;
        for &game_id in SUPPORTED_GAME_IDS.iter()
            .filter(|g| **g != "skyrim-ae")  // AE intentionally shares SE's steam dir
        {
            if ["skyrim-se", "fallout4", "cyberpunk2077"].contains(&game_id) {
                assert!(
                    KNOWN_GAMES.iter().any(|g| g.game_id == game_id),
                    "KNOWN_GAMES missing {game_id}"
                );
            }
        }
    }
}