modde-games 0.2.1

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
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
//! Per-game tool/overlay management.
//!
//! Each tool (`MangoHud`, vkBasalt, `GameMode`, `ReShade`, `OptiScaler`, Proton) implements the
//! [`GameTool`] trait. Tools are registered via [`all_tools`] and resolved by ID
//! via [`resolve_tool`], following the same pattern as [`crate::resolve_game_plugin`].

pub mod gamemode;
pub mod mangohud;
pub mod optiscaler;
pub mod proton;
pub mod release;
pub mod reshade;
pub mod vkbasalt;

use std::future::Future;
use std::path::{Path, PathBuf};
use std::pin::Pin;

use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use smallvec::SmallVec;

use crate::detection::{DetectedGame, LauncherSource};

// ── Types ──────────────────────────────────────────────────────────────────

/// Category of gaming tool.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ToolCategory {
    /// Performance HUD overlay (`MangoHud`).
    Overlay,
    /// Post-processing / shader injection (vkBasalt, `ReShade`).
    PostProcess,
    /// System performance tuning (`GameMode`).
    Performance,
    /// Upscaling / frame generation (`OptiScaler`).
    Upscaler,
}

impl std::fmt::Display for ToolCategory {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Overlay => write!(f, "Overlay"),
            Self::PostProcess => write!(f, "Post-Processing"),
            Self::Performance => write!(f, "Performance"),
            Self::Upscaler => write!(f, "Upscaler"),
        }
    }
}

/// Whether a tool is available on the system.
#[derive(Debug, Clone)]
pub enum ToolAvailability {
    Available { version: Option<String> },
    NotInstalled { install_hint: String },
}

impl ToolAvailability {
    #[must_use]
    pub fn is_available(&self) -> bool {
        matches!(self, Self::Available { .. })
    }
}

/// A wrapper binary to chain before the game executable.
#[derive(Debug, Clone)]
pub struct WrapperEntry {
    pub exe: String,
    pub args: String,
}

/// Files applied by a tool to a game directory (for revert tracking).
#[derive(Debug, Clone, Default)]
pub struct AppliedFiles {
    /// Paths relative to the game directory.
    pub files: Vec<PathBuf>,
}

/// Non-mutating preview of what a tool apply would write.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ToolApplyPreview {
    /// Files the apply operation would manage, relative to the game directory.
    pub planned_files: Vec<PathBuf>,
    /// Planned files whose destination is missing or byte-different.
    pub changed_files: Vec<PathBuf>,
    /// Planned files whose destination already matches the expected bytes.
    pub unchanged_files: Vec<PathBuf>,
    /// Required inputs that are unavailable, such as a missing source DLL.
    pub missing_inputs: Vec<String>,
}

impl ToolApplyPreview {
    #[must_use]
    pub fn has_changes(&self) -> bool {
        !self.changed_files.is_empty()
    }

    pub fn record_file(&mut self, rel_path: PathBuf, changed: bool) {
        self.planned_files.push(rel_path.clone());
        if changed {
            self.changed_files.push(rel_path);
        } else {
            self.unchanged_files.push(rel_path);
        }
    }
}

/// A config file generated by a tool.
#[derive(Debug, Clone)]
pub struct GeneratedConfig {
    /// Absolute path where the config should be written.
    pub path: PathBuf,
    /// File content.
    pub content: String,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ToolReleaseSummary {
    pub tag: String,
    pub name: Option<String>,
    pub published_at: Option<String>,
    pub assets: Vec<ToolReleaseAsset>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ToolReleaseAsset {
    pub name: String,
    pub download_url: String,
    pub size: u64,
}

pub type ToolReleaseListFuture<'a> =
    Pin<Box<dyn Future<Output = Result<Vec<ToolReleaseSummary>>> + Send + 'a>>;

pub type ToolReleaseInstallFuture<'a> =
    Pin<Box<dyn Future<Output = Result<ToolConfig>> + Send + 'a>>;

/// Game metadata available to per-game tools.
#[derive(Debug, Clone)]
pub struct ToolGameContext {
    pub game_id: String,
    pub display_name: String,
    pub install_path: Option<PathBuf>,
    pub launcher_source: Option<LauncherSource>,
    pub steam_app_id: Option<String>,
    pub executable_dir: Option<PathBuf>,
}

impl ToolGameContext {
    #[must_use]
    pub fn from_parts(
        game_id: &str,
        display_name: impl Into<String>,
        install_path: Option<PathBuf>,
        detected: Option<&DetectedGame>,
    ) -> Self {
        let plugin = crate::resolve_game_plugin(game_id);
        let executable_dir = install_path
            .as_deref()
            .and_then(|path| plugin.map(|plugin| plugin.executable_dir(path)));
        let launcher_source = detected.map(|game| game.source.clone());
        let steam_app_id = launcher_source.as_ref().and_then(|source| match source {
            LauncherSource::Steam { app_id, .. } => Some(app_id.clone()),
            LauncherSource::HeroicGog { .. }
            | LauncherSource::HeroicEpic { .. }
            | LauncherSource::HeroicSideload { .. } => None,
        });

        Self {
            game_id: game_id.to_string(),
            display_name: display_name.into(),
            install_path,
            launcher_source,
            steam_app_id,
            executable_dir,
        }
    }

    #[must_use]
    pub fn launcher_label(&self) -> String {
        self.launcher_source
            .as_ref()
            .map(ToString::to_string)
            .unwrap_or_else(|| "Not detected".to_string())
    }
}

/// Declarative field type for rendering per-tool settings in the UI.
#[derive(Debug, Clone, PartialEq)]
pub enum ToolSettingKind {
    Bool,
    TriStateBool,
    Text,
    Path,
    Select { options: Vec<ToolSelectOption> },
    Number { min: f64, max: f64, step: f64 },
    ReadOnly,
}

/// One selectable option for a tool setting.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ToolSelectOption {
    pub value: String,
    pub label: String,
}

impl ToolSelectOption {
    #[must_use]
    pub fn new(value: impl Into<String>, label: impl Into<String>) -> Self {
        Self {
            value: value.into(),
            label: label.into(),
        }
    }

    #[must_use]
    pub fn value_label(value: impl Into<String>) -> Self {
        let value = value.into();
        Self {
            label: value.clone(),
            value,
        }
    }
}

impl std::fmt::Display for ToolSelectOption {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.label)
    }
}

/// One user-facing setting exposed by a [`GameTool`].
#[derive(Debug, Clone, PartialEq)]
pub struct ToolSettingSpec {
    pub key: &'static str,
    pub label: &'static str,
    pub description: &'static str,
    pub section: &'static str,
    pub advanced: bool,
    pub kind: ToolSettingKind,
}

impl ToolSettingSpec {
    const DEFAULT_SECTION: &'static str = "General";

    #[must_use]
    pub fn bool(key: &'static str, label: &'static str, description: &'static str) -> Self {
        Self {
            key,
            label,
            description,
            section: Self::DEFAULT_SECTION,
            advanced: false,
            kind: ToolSettingKind::Bool,
        }
    }

    #[must_use]
    pub fn tri_state_bool(
        key: &'static str,
        label: &'static str,
        description: &'static str,
    ) -> Self {
        Self {
            key,
            label,
            description,
            section: Self::DEFAULT_SECTION,
            advanced: false,
            kind: ToolSettingKind::TriStateBool,
        }
    }

    #[must_use]
    pub fn text(key: &'static str, label: &'static str, description: &'static str) -> Self {
        Self {
            key,
            label,
            description,
            section: Self::DEFAULT_SECTION,
            advanced: false,
            kind: ToolSettingKind::Text,
        }
    }

    #[must_use]
    pub fn path(key: &'static str, label: &'static str, description: &'static str) -> Self {
        Self {
            key,
            label,
            description,
            section: Self::DEFAULT_SECTION,
            advanced: false,
            kind: ToolSettingKind::Path,
        }
    }

    #[must_use]
    pub fn select(
        key: &'static str,
        label: &'static str,
        description: &'static str,
        options: &[&str],
    ) -> Self {
        Self {
            key,
            label,
            description,
            section: Self::DEFAULT_SECTION,
            advanced: false,
            kind: ToolSettingKind::Select {
                options: options
                    .iter()
                    .map(|option| ToolSelectOption::value_label(*option))
                    .collect(),
            },
        }
    }

    #[must_use]
    pub fn labeled_select(
        key: &'static str,
        label: &'static str,
        description: &'static str,
        options: &[(&str, &str)],
    ) -> Self {
        Self {
            key,
            label,
            description,
            section: Self::DEFAULT_SECTION,
            advanced: false,
            kind: ToolSettingKind::Select {
                options: options
                    .iter()
                    .map(|(value, label)| ToolSelectOption::new(*value, *label))
                    .collect(),
            },
        }
    }

    #[must_use]
    pub fn number(
        key: &'static str,
        label: &'static str,
        description: &'static str,
        min: f64,
        max: f64,
        step: f64,
    ) -> Self {
        Self {
            key,
            label,
            description,
            section: Self::DEFAULT_SECTION,
            advanced: false,
            kind: ToolSettingKind::Number { min, max, step },
        }
    }

    #[must_use]
    pub fn read_only(key: &'static str, label: &'static str, description: &'static str) -> Self {
        Self {
            key,
            label,
            description,
            section: Self::DEFAULT_SECTION,
            advanced: false,
            kind: ToolSettingKind::ReadOnly,
        }
    }

    #[must_use]
    pub fn section(mut self, section: &'static str) -> Self {
        self.section = section;
        self
    }

    #[must_use]
    pub fn advanced(mut self) -> Self {
        self.advanced = true;
        self
    }
}

/// Per-game tool configuration stored in the database.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolConfig {
    pub tool_id: String,
    pub enabled: bool,
    pub settings: serde_json::Value,
}

impl ToolConfig {
    pub fn new(tool_id: impl Into<String>) -> Self {
        Self {
            tool_id: tool_id.into(),
            enabled: false,
            settings: serde_json::Value::Object(serde_json::Map::new()),
        }
    }

    /// Get a string setting.
    #[must_use]
    pub fn get_str(&self, key: &str) -> Option<&str> {
        self.settings.get(key).and_then(|v| v.as_str())
    }

    /// Get a bool setting, defaulting to `false`.
    #[must_use]
    pub fn get_bool(&self, key: &str) -> bool {
        self.settings
            .get(key)
            .and_then(serde_json::Value::as_bool)
            .unwrap_or(false)
    }

    /// Get an integer setting.
    #[must_use]
    pub fn get_i64(&self, key: &str) -> Option<i64> {
        self.settings.get(key).and_then(serde_json::Value::as_i64)
    }

    /// Set a setting value.
    pub fn set(&mut self, key: impl Into<String>, value: serde_json::Value) {
        if let serde_json::Value::Object(ref mut map) = self.settings {
            map.insert(key.into(), value);
        }
    }
}

// ── Trait ───────────────────────────────────────────────────────────────────

/// A gaming tool/overlay that can be managed per-game.
pub trait GameTool: Send + Sync {
    /// Unique identifier (e.g. `"mangohud"`, `"gamemode"`).
    fn tool_id(&self) -> &'static str;

    /// Human-readable display name.
    fn display_name(&self) -> &'static str;

    /// Tool category.
    fn category(&self) -> ToolCategory;

    /// Short user-facing description for the tool tab.
    fn description(&self) -> &'static str {
        "Game-specific tool integration."
    }

    /// Declarative settings rendered by the UI.
    fn settings_schema(&self) -> Vec<ToolSettingSpec> {
        Vec::new()
    }

    /// Declarative settings rendered by the UI with game context.
    fn settings_schema_for(
        &self,
        _context: Option<&ToolGameContext>,
        _config: &ToolConfig,
    ) -> Vec<ToolSettingSpec> {
        self.settings_schema()
    }

    /// Check if the tool is installed on the system.
    fn detect_available(&self) -> ToolAvailability;

    /// Environment variables to set when launching the game.
    fn env_vars(&self, config: &ToolConfig) -> SmallVec<[(String, String); 4]>;

    /// Environment variables to set when launching the game with game context.
    fn env_vars_for(
        &self,
        _context: Option<&ToolGameContext>,
        config: &ToolConfig,
    ) -> SmallVec<[(String, String); 4]> {
        self.env_vars(config)
    }

    /// Wrapper command to chain before the game (e.g. `gamemoderun`).
    fn wrapper_command(&self, _config: &ToolConfig) -> Option<WrapperEntry> {
        None
    }

    /// Wine DLL overrides needed (e.g. `"dxgi"`, `"version"`).
    fn wine_dll_overrides(&self, _config: &ToolConfig) -> SmallVec<[String; 4]> {
        SmallVec::new()
    }

    /// Wine DLL overrides needed with game context.
    fn wine_dll_overrides_for(
        &self,
        _context: Option<&ToolGameContext>,
        config: &ToolConfig,
    ) -> SmallVec<[String; 4]> {
        self.wine_dll_overrides(config)
    }

    /// Apply/install files into the game directory (DLLs, shaders, etc.).
    /// Returns a manifest of files written for revert tracking.
    fn apply(&self, _game_dir: &Path, _config: &ToolConfig) -> Result<AppliedFiles> {
        Ok(AppliedFiles::default())
    }

    /// Apply/install files with game context.
    fn apply_for(
        &self,
        game_dir: &Path,
        _context: Option<&ToolGameContext>,
        config: &ToolConfig,
    ) -> Result<AppliedFiles> {
        self.apply(game_dir, config)
    }

    /// Preview an apply without mutating the game directory.
    fn preview_apply_for(
        &self,
        _game_dir: &Path,
        _context: Option<&ToolGameContext>,
        _config: &ToolConfig,
    ) -> Result<ToolApplyPreview> {
        Ok(ToolApplyPreview::default())
    }

    /// Revert files previously applied by [`Self::apply`].
    fn revert(&self, game_dir: &Path, applied: &AppliedFiles) -> Result<()> {
        for rel in &applied.files {
            let path = game_dir.join(rel);
            if path.exists() {
                std::fs::remove_file(&path)
                    .with_context(|| format!("failed to remove {}", path.display()))?;
            }
        }
        Ok(())
    }

    /// Generate a per-game config file (e.g. MangoHud.conf).
    fn generate_config(&self, _config: &ToolConfig) -> Option<GeneratedConfig> {
        None
    }

    /// Generate a per-game config file with game context.
    fn generate_config_for(
        &self,
        _context: Option<&ToolGameContext>,
        config: &ToolConfig,
    ) -> Option<GeneratedConfig> {
        self.generate_config(config)
    }

    /// Default configuration for a fresh enable.
    fn default_config(&self) -> ToolConfig;

    /// Default configuration for a fresh enable with game context.
    fn default_config_for(&self, _context: Option<&ToolGameContext>) -> ToolConfig {
        self.default_config()
    }

    /// Whether this tool supports explicit per-game release selection.
    fn supports_releases(&self) -> bool {
        false
    }

    /// List upstream releases for release-backed tools.
    fn list_releases(&self) -> ToolReleaseListFuture<'_> {
        Box::pin(async {
            anyhow::bail!("{} does not support release selection", self.display_name())
        })
    }

    /// Return installable asset names for a release.
    fn installable_release_assets(&self, _release: &ToolReleaseSummary) -> Vec<String> {
        Vec::new()
    }

    /// Install a selected release asset and return the updated per-game config.
    fn install_release<'a>(
        &'a self,
        _game_id: &'a str,
        _config: ToolConfig,
        _tag: &'a str,
        _asset: &'a str,
    ) -> ToolReleaseInstallFuture<'a> {
        Box::pin(async {
            anyhow::bail!(
                "{} does not support release installation",
                self.display_name()
            )
        })
    }

    /// Install a selected release asset from a local path and return the updated per-game config.
    fn install_release_from_path<'a>(
        &'a self,
        _game_id: &'a str,
        _config: ToolConfig,
        _tag: &'a str,
        _asset: &'a str,
        _path: PathBuf,
    ) -> ToolReleaseInstallFuture<'a> {
        Box::pin(async {
            anyhow::bail!("{} does not support release pinning", self.display_name())
        })
    }
}

// ── Registry ───────────────────────────────────────────────────────────────

/// All registered tools.
static ALL_TOOLS: [&dyn GameTool; 6] = [
    &mangohud::MANGOHUD,
    &vkbasalt::VKBASALT,
    &gamemode::GAMEMODE,
    &reshade::RESHADE,
    &optiscaler::OPTISCALER,
    &proton::PROTON,
];

#[must_use]
pub fn all_tools() -> &'static [&'static dyn GameTool] {
    &ALL_TOOLS
}

/// Resolve a tool by its ID string.
#[must_use]
pub fn resolve_tool(tool_id: &str) -> Option<&'static dyn GameTool> {
    all_tools().iter().find(|t| t.tool_id() == tool_id).copied()
}

// ── Helpers ────────────────────────────────────────────────────────────────

/// Directory where modde stores per-game tool configs.
#[must_use]
pub fn tool_config_dir(game_id: &str) -> PathBuf {
    modde_core::paths::modde_data_dir()
        .join("tools")
        .join(game_id)
}

/// Check if a binary is on `$PATH`.
///
/// Uses the `which` crate for cross-platform support (handles Windows
/// `%PATHEXT%` extensions like `.exe`, `.cmd`, `.bat` automatically).
pub(crate) fn which(binary: &str) -> Option<PathBuf> {
    which::which(binary).ok()
}

#[cfg(test)]
mod tests {
    use std::fs;
    use std::io::Write;
    use std::sync::OnceLock;

    #[test]
    fn plain_select_options_use_value_as_label() {
        let spec = super::ToolSettingSpec::select("mode", "Mode", "", &["0", "1"]);

        let super::ToolSettingKind::Select { options } = spec.kind else {
            panic!("expected select");
        };
        assert_eq!(options[0].value, "0");
        assert_eq!(options[0].label, "0");
        assert_eq!(options[1].to_string(), "1");
    }

    #[test]
    fn labeled_select_options_keep_distinct_value_and_label() {
        let spec = super::ToolSettingSpec::labeled_select(
            "mode",
            "Mode",
            "",
            &[("0", "0 - Conservative"), ("1", "1 - Aggressive")],
        );

        let super::ToolSettingKind::Select { options } = spec.kind else {
            panic!("expected select");
        };
        assert_eq!(options[0].value, "0");
        assert_eq!(options[0].label, "0 - Conservative");
        assert_eq!(options[1].to_string(), "1 - Aggressive");
    }

    #[test]
    fn setting_specs_are_not_advanced_by_default() {
        let plain = super::ToolSettingSpec::text("mode", "Mode", "");
        let advanced = plain.clone().advanced();

        assert!(!plain.advanced);
        assert!(advanced.advanced);
    }

    #[test]
    fn every_tool_has_ui_metadata_and_serializable_defaults() {
        for tool in super::all_tools() {
            assert!(!tool.description().trim().is_empty(), "{}", tool.tool_id());
            assert!(
                !tool.settings_schema().is_empty(),
                "{} should expose UI settings",
                tool.tool_id()
            );
            serde_json::to_string(&tool.default_config()).expect("default config serializes");
        }
    }

    #[test]
    fn proton_is_registered() {
        let tool = super::resolve_tool("proton").expect("proton tool should resolve");
        assert_eq!(tool.display_name(), "Proton");
    }

    #[test]
    fn proton_launch_integration_is_exposed() {
        let tool = super::resolve_tool("proton").expect("proton tool should resolve");
        let mut config = tool.default_config();
        config.enabled = true;
        config.set("extra_env", serde_json::json!("DXVK_ASYNC=1\nPROTON_LOG=1"));
        config.set("proton_enable_hdr", serde_json::json!(true));
        config.set("radv_perftest_rt", serde_json::json!(true));
        config.set("dll_override_mode", serde_json::json!("forced"));
        config.set("forced_dll_overrides", serde_json::json!("dxgi,winmm"));

        let env = tool.env_vars(&config);
        assert!(
            env.iter()
                .any(|(key, value)| key == "DXVK_ASYNC" && value == "1")
        );
        assert!(
            env.iter()
                .any(|(key, value)| key == "PROTON_LOG" && value == "1")
        );
        assert!(
            env.iter()
                .any(|(key, value)| key == "PROTON_ENABLE_HDR" && value == "1")
        );
        assert!(
            env.iter()
                .any(|(key, value)| key == "RADV_PERFTEST" && value == "rt,emulate_rt")
        );

        let overrides = tool.wine_dll_overrides(&config);
        assert!(overrides.iter().any(|value| value == "dxgi"));
        assert!(overrides.iter().any(|value| value == "winmm"));
    }

    #[test]
    fn mangohud_exposes_goverlay_config_keys() {
        let tool = super::resolve_tool("mangohud").expect("mangohud tool should resolve");
        let specs = tool.settings_schema();
        for key in [
            "custom_text_center",
            "background_alpha",
            "fps_limit_method",
            "gpu_junction_temp",
            "winesync",
            "media_player",
            "upload_logs",
            "display_server",
        ] {
            assert!(
                specs.iter().any(|spec| spec.key == key),
                "missing MangoHud key {key}"
            );
        }

        let mut config = tool.default_config();
        config.set("_game_id", serde_json::json!("skyrim-se"));
        config.set("custom_text_center", serde_json::json!("modde"));
        config.set("gpu_junction_temp", serde_json::json!(true));
        let generated = tool.generate_config(&config).expect("generated config");
        assert!(generated.content.contains("custom_text_center=modde"));
        assert!(generated.content.contains("gpu_junction_temp"));
    }

    #[test]
    fn optiscaler_release_provider_filters_installable_assets() {
        let tool = super::resolve_tool("optiscaler").expect("optiscaler tool should resolve");
        assert!(tool.supports_releases());
        let release = super::ToolReleaseSummary {
            tag: "v1".to_string(),
            name: None,
            published_at: None,
            assets: vec![
                super::ToolReleaseAsset {
                    name: "OptiScaler.7z".to_string(),
                    download_url: "https://example.test/OptiScaler.7z".to_string(),
                    size: 1,
                },
                super::ToolReleaseAsset {
                    name: "notes.txt".to_string(),
                    download_url: "https://example.test/notes.txt".to_string(),
                    size: 1,
                },
            ],
        };
        assert_eq!(
            tool.installable_release_assets(&release),
            vec!["OptiScaler.7z".to_string()]
        );
    }

    #[test]
    fn tool_context_derives_executable_dir_from_game_plugin() {
        let root = std::path::PathBuf::from("/tmp/modde-test-cyberpunk");
        let context =
            super::ToolGameContext::from_parts("cyberpunk2077", "Cyberpunk 2077", Some(root), None);
        assert!(
            context
                .executable_dir
                .expect("executable dir")
                .ends_with("bin/x64")
        );
    }

    #[test]
    fn optiscaler_restore_commands_use_supplied_executable_dir() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let game_dir = tmp.path().join("game");
        let staging = tmp.path().join("staging");
        let mod_bin = staging.join("mods/test/bin/x64");
        fs::create_dir_all(&mod_bin).expect("mod bin");
        fs::write(mod_bin.join("winmm.dll"), b"dll").expect("dll");
        let exe_dir = game_dir.join("Binaries/Win64");
        let commands = super::optiscaler::fgmod_restore_commands_for_executable_dir(
            &game_dir, &staging, &exe_dir,
        );
        assert_eq!(commands.len(), 1);
        assert!(commands[0].1.ends_with("Binaries/Win64/winmm.dll"));
    }

    #[test]
    fn protonup_rs_install_args_are_non_interactive() {
        let args = super::proton::protonup_rs_install_args("GE-Proton10-34", "steam");
        assert_eq!(
            args,
            vec![
                "--tool",
                "GEProton",
                "--version",
                "GE-Proton10-34",
                "--for",
                "steam"
            ]
        );
    }

    #[test]
    fn ge_proton_release_filter_accepts_real_tags() {
        assert!(super::proton::is_ge_proton_version("GE-Proton10-34"));
        assert!(super::proton::is_ge_proton_version("Proton-GE-Proton8-32"));
        assert!(!super::proton::is_ge_proton_version(""));
        assert!(!super::proton::is_ge_proton_version("notes"));
        assert!(!super::proton::is_ge_proton_version("Proton-Experimental"));
    }

    #[test]
    fn proton_version_options_preserve_catalog_order_and_dedup() {
        let options = super::proton::merge_proton_version_options(
            vec![
                "GE-Proton10-34".to_string(),
                "GE-Proton10-33".to_string(),
                "GE-Proton10-34".to_string(),
            ],
            vec!["GE-Proton10-32".to_string(), "GE-Proton10-33".to_string()],
        );
        assert_eq!(
            options,
            vec![
                "latest".to_string(),
                "GE-Proton10-34".to_string(),
                "GE-Proton10-33".to_string(),
                "GE-Proton10-32".to_string(),
            ]
        );
    }

    fn ensure_test_data_dir() -> std::path::PathBuf {
        static DATA_DIR: OnceLock<std::path::PathBuf> = OnceLock::new();
        DATA_DIR
            .get_or_init(|| {
                let default_dir = modde_core::paths::data_dir().join("modde");
                if modde_core::paths::modde_data_dir() != default_dir {
                    return modde_core::paths::modde_data_dir();
                }

                let tempdir = tempfile::TempDir::new().expect("create tempdir");
                let data_dir = tempdir.path().join("data");
                std::fs::create_dir_all(&data_dir).expect("create data dir");
                // set_data_dir is idempotent (first caller wins); return whatever
                // actually became the override — ours, or a parallel test's.
                modde_core::paths::set_data_dir(data_dir);
                std::mem::forget(tempdir);
                modde_core::paths::modde_data_dir()
            })
            .clone()
    }

    #[tokio::test]
    async fn optiscaler_install_release_from_path_extracts_local_archive() {
        let _ = ensure_test_data_dir();
        let tempdir = tempfile::TempDir::new().expect("create tempdir");
        let archive_path = tempdir.path().join("OptiScaler.zip");
        let file = std::fs::File::create(&archive_path).expect("create archive");
        let mut zip = zip::ZipWriter::new(file);
        zip.start_file("OptiScaler.dll", zip::write::FileOptions::<()>::default())
            .expect("start file");
        zip.write_all(b"dll-bytes").expect("write dll");
        zip.finish().expect("finish archive");

        let tool = super::resolve_tool("optiscaler").expect("optiscaler tool should resolve");
        let config = tool.default_config();
        let updated = tool
            .install_release_from_path(
                "stellar-blade",
                config,
                "v1.0",
                "OptiScaler.zip",
                archive_path,
            )
            .await
            .expect("install from path");

        assert_eq!(updated.get_str("release_tag"), Some("official:v1.0"));
        assert_eq!(updated.get_str("release_asset"), Some("OptiScaler.zip"));
        assert!(
            super::optiscaler::cached_release_dir("official:v1.0")
                .join("OptiScaler.dll")
                .exists()
        );
    }
}