vpxtool 0.30.0

Terminal based frontend and utilities for Visual Pinball
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
use std::path::{Path, PathBuf};

use crate::vpinball_config::VPinballConfig;
use dialoguer::Select;
use dialoguer::theme::ColorfulTheme;
use figment::{
    Figment,
    providers::{Format, Toml},
};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fs::{self, File};
use std::io::Write;
use std::{env, io};

const CONFIGURATION_FILE_NAME: &str = "vpxtool.cfg";

#[derive(Deserialize, Serialize, Debug, PartialEq, Clone, Eq)]
pub struct LaunchTemplate {
    pub name: String,
    pub executable: PathBuf,
    pub arguments: Option<Vec<String>>,
    pub env: Option<HashMap<String, String>>,
    pub vpinball_config: Option<PathBuf>,
}

#[derive(Deserialize, Serialize)]
pub struct Config {
    pub vpx_executable: PathBuf,
    pub vpx_config: Option<PathBuf>,
    pub tables_folder: Option<PathBuf>,
    pub tables_scan_max_depth: Option<usize>,
    pub diff: Option<String>,
    pub editor: Option<String>,
    pub launch_templates: Option<Vec<LaunchTemplate>>,
}

#[derive(PartialEq, Debug, Clone)]
pub struct ResolvedConfig {
    pub vpx_executable: PathBuf,
    pub launch_templates: Vec<LaunchTemplate>,
    pub vpx_config: PathBuf,
    pub tables_folder: PathBuf,
    pub tables_index_path: PathBuf,
    pub tables_scan_max_depth: Option<usize>,
    pub diff: Option<String>,
    pub editor: Option<String>,
}

impl ResolvedConfig {
    pub fn global_pinmame_folder(&self) -> PathBuf {
        if cfg!(target_os = "windows") {
            self.vpx_executable.parent().unwrap().join("VPinMAME")
        } else {
            dirs::home_dir().unwrap().join(".pinmame")
        }
    }

    /// This path can be absolute or relative.
    /// In case it is relative, it will need to be resolved relative to the table vpx file.
    pub fn configured_pinmame_folder(&self) -> Option<PathBuf> {
        // first we try to read the ini file
        if self.vpx_config.exists() {
            let vpinball_config = VPinballConfig::read(&self.vpx_config).unwrap();
            if let Some(value) = vpinball_config.get_pinmame_path() {
                if value.trim().is_empty() {
                    return None;
                }
                let path = PathBuf::from(value);
                return Some(path);
            }
        }
        None
    }
}

pub fn config_path() -> Option<PathBuf> {
    let home_directory_configuration_path = home_config_path();
    if home_directory_configuration_path.exists() {
        return Some(home_directory_configuration_path);
    }
    // migrate old config file if it exists
    let old_config_path = old_home_config_path();
    if old_config_path.exists() {
        println!(
            "Migrating config file from {old_config_path:?} to {home_directory_configuration_path:?}"
        );
        std::fs::create_dir_all(home_directory_configuration_path.parent().unwrap()).ok()?;
        std::fs::rename(&old_config_path, &home_directory_configuration_path).ok()?;
        return Some(home_directory_configuration_path);
    }
    let local_configuration_path = local_config_path();
    if local_configuration_path.exists() {
        return Some(local_configuration_path);
    }
    None
}

pub enum SetupConfigResult {
    Configured(PathBuf),
    Existing(PathBuf),
}

/// Setup the config file if it doesn't exist
///
/// This might require user input!
pub fn setup_config() -> io::Result<SetupConfigResult> {
    // TODO check if the config file already exists
    let existing_config_path = config_path();
    match existing_config_path {
        Some(path) => Ok(SetupConfigResult::Existing(path)),
        None => {
            // TODO avoid stdout interaction here
            println!("Warning: Failed find a config file.");
            let new_config = create_default_config()?;
            Ok(SetupConfigResult::Configured(new_config.0))
        }
    }
}

/// Load the config file if it exists, otherwise create a new one
///
/// This might require user input!
pub fn load_or_setup_config() -> io::Result<(PathBuf, ResolvedConfig)> {
    match load_config()? {
        Some(loaded) => Ok(loaded),
        None => {
            // TODO avoid stdout interaction here
            println!("Warning: Failed find a config file.");
            create_default_config()
        }
    }
}

pub fn load_config() -> io::Result<Option<(PathBuf, ResolvedConfig)>> {
    match config_path() {
        Some(config_path) => {
            let config = read_config(&config_path)?;
            Ok(Some((config_path, config)))
        }
        None => Ok(None),
    }
}

fn read_config(config_path: &Path) -> io::Result<ResolvedConfig> {
    let figment = Figment::new().merge(Toml::file(config_path));
    let config: Config = figment.extract().map_err(|e| {
        io::Error::new(
            io::ErrorKind::InvalidData,
            format!("Failed to load config file: {e}"),
        )
    })?;
    // apply defaults
    // TODO we might want to suggest the value in the config file by having it empty with a comment
    let tables_folder = config
        .tables_folder
        .unwrap_or(default_tables_root(&config.vpx_executable));
    let vpx_config = config
        .vpx_config
        .unwrap_or_else(|| default_vpinball_ini_file(&config.vpx_executable));

    // generate launch templates if not set
    let launch_templates = config.launch_templates.unwrap_or_else(|| {
        // normal, force fullscreen, force windowed
        generate_default_launch_templates(&config.vpx_executable)
    });

    let resolved_config = ResolvedConfig {
        vpx_executable: config.vpx_executable,
        launch_templates,
        vpx_config,
        tables_folder: tables_folder.clone(),
        tables_index_path: tables_index_path(&tables_folder),
        tables_scan_max_depth: config.tables_scan_max_depth,
        diff: config.diff,
        editor: config.editor,
    };
    Ok(resolved_config)
}

fn generate_default_launch_templates(vpx_executable: &Path) -> Vec<LaunchTemplate> {
    // Only the basic Launch template is shipped by default. The previous
    // "Launch Fullscreen"/"Launch Windowed" templates relied on
    // -EnableTrueFullscreen/-DisableTrueFullscreen, which are deprecated and
    // not compiled into modern (BGFX) vpinball builds. Users who want forced
    // modes can define extra templates pointing at their own ini variants
    // via vpinball_config (passed to vpinball as -Ini <path>).
    let default_env = HashMap::from([
        ("SDL_VIDEODRIVER".to_string(), "".to_string()),
        ("SDL_RENDER_DRIVER".to_string(), "".to_string()),
    ]);

    vec![LaunchTemplate {
        name: "Launch".to_string(),
        executable: vpx_executable.to_owned(),
        arguments: None,
        env: Some(default_env),
        vpinball_config: None,
    }]
}

pub fn tables_index_path(tables_folder: &Path) -> PathBuf {
    tables_folder.join("vpxtool_index.json")
}

pub fn clear_config() -> io::Result<Option<PathBuf>> {
    let config_path = config_path();
    match config_path {
        Some(path) => {
            std::fs::remove_file(&path)?;
            Ok(Some(path))
        }
        None => Ok(None),
    }
}

fn local_config_path() -> PathBuf {
    Path::new(CONFIGURATION_FILE_NAME).to_path_buf()
}

fn old_home_config_path() -> PathBuf {
    dirs::config_dir().unwrap().join(CONFIGURATION_FILE_NAME)
}

fn home_config_path() -> PathBuf {
    dirs::config_dir()
        .unwrap()
        .join("vpxtool")
        .join(CONFIGURATION_FILE_NAME)
}

fn default_vpinball_ini_file(vpx_executable_path: &Path) -> PathBuf {
    // Batocera ships an opinionated layout that pre-dates the SDL pref-path
    // scheme; honour it when the marker exists.
    let batocera_path = PathBuf::from("/userdata/system/configs/vpinball/VPinballX.ini");
    if batocera_path.exists() {
        return batocera_path;
    }

    // Modern vpinball stores its ini at
    //   <SDL_GetPrefPath("VPinballX")>/<MAJOR>.<MINOR>/VPinballX.ini
    // SDL_GetPrefPath maps to dirs::data_dir() on all three platforms (Linux
    // ~/.local/share, macOS ~/Library/Application Support, Windows %AppData%).
    // We can't hardcode a version, so probe for the highest <MAJOR>.<MINOR>
    // subdirectory that has an ini and use it.
    if let Some(data_dir) = dirs::data_dir()
        && let Some(path) = newest_versioned_vpinball_ini(&data_dir.join("VPinballX"))
    {
        return path;
    }

    legacy_vpinball_ini(vpx_executable_path)
}

fn newest_versioned_vpinball_ini(base: &Path) -> Option<PathBuf> {
    let mut versions: Vec<((u32, u32), PathBuf)> = fs::read_dir(base)
        .ok()?
        .flatten()
        .filter(|e| e.file_type().is_ok_and(|t| t.is_dir()))
        .filter_map(|e| {
            let name = e.file_name();
            let parsed = parse_major_minor(name.to_str()?)?;
            Some((parsed, e.path()))
        })
        .collect();
    // Highest version first; (10, 10) > (10, 9) by tuple ordering.
    versions.sort_by_key(|(version, _)| std::cmp::Reverse(*version));

    versions.into_iter().find_map(|(_, dir)| {
        let ini = dir.join("VPinballX.ini");
        ini.exists().then_some(ini)
    })
}

fn parse_major_minor(s: &str) -> Option<(u32, u32)> {
    let mut parts = s.splitn(2, '.');
    let major = parts.next()?.parse().ok()?;
    let minor = parts.next()?.parse().ok()?;
    Some((major, minor))
}

/// If the saved `vpx_config` is the legacy auto-generated default and the
/// resolver would now pick something different (typically because the user
/// upgraded vpinball and it migrated to the SDL pref path), return the
/// modern path so callers can prompt the user to update their config.
///
/// Returns None if the saved path is custom (not the legacy default), or if
/// the resolver agrees with the saved path.
pub fn stale_vpx_config_suggestion(saved: &Path, vpx_executable: &Path) -> Option<PathBuf> {
    if saved != legacy_vpinball_ini(vpx_executable) {
        return None;
    }
    let resolved = default_vpinball_ini_file(vpx_executable);
    (resolved != saved).then_some(resolved)
}

/// Rewrite the saved vpxtool config with `vpx_config` set to the given path.
/// All other fields are preserved from the on-disk file, along with comments,
/// blank lines, and field ordering (uses `toml_edit` for in-place edits).
pub fn rewrite_vpx_config(config_file: &Path, vpx_config: &Path) -> io::Result<()> {
    let toml_str = std::fs::read_to_string(config_file)?;
    let mut doc: toml_edit::DocumentMut = toml_str.parse().map_err(io::Error::other)?;
    doc["vpx_config"] = toml_edit::value(vpx_config.to_string_lossy().into_owned());
    std::fs::write(config_file, doc.to_string())
}

fn legacy_vpinball_ini(vpx_executable_path: &Path) -> PathBuf {
    if cfg!(target_os = "windows") {
        vpx_executable_path.parent().unwrap().join("VPinballX.ini")
    } else {
        dirs::home_dir()
            .unwrap()
            .join(".vpinball")
            .join("VPinballX.ini")
    }
}

/// Create a default config file
///
/// This requires user input!
fn create_default_config() -> io::Result<(PathBuf, ResolvedConfig)> {
    let local_configuration_path = local_config_path();
    let home_directory_configuration_path = home_config_path();
    let choices: Vec<(&str, String)> = vec![
        (
            "Home",
            home_directory_configuration_path
                .to_string_lossy()
                .to_string(),
        ),
        (
            "Local",
            local_configuration_path.to_string_lossy().to_string(),
        ),
    ];

    let selection_opt = Select::with_theme(&ColorfulTheme::default())
        .with_prompt("Choose a configuration location:")
        .default(0)
        .items(
            choices
                .iter()
                .map(|(choice, description)| format!("{choice} \x1b[90m{description}\x1b[0m"))
                .collect::<Vec<_>>(),
        )
        .interact_opt()?;

    let config_file = if let Some(index) = selection_opt {
        let (_selected_choice, path) = (&choices[index].0, &choices[index].1);
        PathBuf::from(path)
    } else {
        unreachable!("Failed to select a configuration file path.");
    };

    let mut vpx_executable = default_vpinball_executable();

    if !vpx_executable.exists() {
        println!("Warning: Failed to detect the vpinball executable.");
        print!("vpinball executable path: ");
        io::stdout().flush().expect("Failed to flush stdout");

        let mut new_executable_path = String::new();
        io::stdin()
            .read_line(&mut new_executable_path)
            .expect("Failed to read line");

        vpx_executable = PathBuf::from(new_executable_path.trim().to_string());

        if !vpx_executable.exists() {
            println!("Error: input file path wasn't found.");
            println!("Executable path is not set. ");
            std::process::exit(1);
        }
    }

    write_default_config(&config_file, &vpx_executable)?;

    let resolved_config = read_config(&config_file)?;
    Ok((config_file, resolved_config))
}

fn write_default_config(config_file: &Path, vpx_executable: &Path) -> io::Result<()> {
    let launch_templates = generate_default_launch_templates(vpx_executable);

    let vpx_config = default_vpinball_ini_file(vpx_executable);
    let tables_folder = default_tables_root(vpx_executable);
    let config = Config {
        vpx_executable: vpx_executable.to_owned(),
        launch_templates: Some(launch_templates),
        vpx_config: Some(vpx_config.clone()),
        tables_folder: Some(tables_folder.clone()),
        tables_scan_max_depth: None,
        diff: None,
        editor: None,
    };
    write_config(config_file, &config)?;
    Ok(())
}

fn write_config(config_file: &Path, config: &Config) -> io::Result<()> {
    let toml = toml::to_string(&config).unwrap();
    // make sure the parent directory exists
    if let Some(parent) = config_file.parent() {
        std::fs::create_dir_all(parent)?;
    }
    let mut file = File::create(config_file)?;
    file.write_all(toml.as_bytes())
}

pub fn default_tables_root(vpx_executable: &Path) -> PathBuf {
    // when on macos we assume that the tables are in ~/.vpinball/tables
    if cfg!(target_os = "macos") {
        dirs::home_dir().unwrap().join(".vpinball").join("tables")
    } else {
        vpx_executable.parent().unwrap().join("tables")
    }
}

fn default_vpinball_executable() -> PathBuf {
    if cfg!(target_os = "windows") {
        // baller installer default
        let dir = PathBuf::from("c:\\vPinball\\VisualPinball");
        let exe = dir.join("VPinballX64.exe");

        // Check current directory
        let local = env::current_dir().unwrap();
        if local.join("VPinballX64.exe").exists() {
            local.join("VPinballX64.exe")
        } else if local.join("VPinballX.exe").exists() {
            local.join("VPinballX.exe")
        } else if exe.exists() {
            exe
        } else {
            dir.join("VPinballX.exe")
        }
    } else if cfg!(target_os = "macos") {
        let dmg_install =
            PathBuf::from("/Applications/VPinballX_GL.app/Contents/MacOS/VPinballX_GL");
        if dmg_install.exists() {
            dmg_install
        } else {
            let mut local = env::current_dir().unwrap();
            local = local.join("VPinballX_GL");
            local
        }
    } else {
        let mut local = env::current_dir().unwrap();
        local = local.join("VPinballX_GL");

        if local.exists() {
            local
        } else {
            let home = dirs::home_dir().unwrap();
            home.join("vpinball").join("vpinball").join("VPinballX_GL")
        }
    }
}

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

    #[cfg(target_os = "linux")]
    #[test]
    fn test_write_default_config_linux() -> io::Result<()> {
        use std::io::Read;
        let temp_dir = testdir!();
        let config_file = temp_dir.join(CONFIGURATION_FILE_NAME);
        write_default_config(&config_file, &PathBuf::from("/home/me/vpinball"))?;
        // print the config file
        let mut file = File::open(&config_file)?;
        let mut contents = String::new();
        file.read_to_string(&mut contents)?;
        println!("Config file contents: {contents}");
        let config = read_config(&config_file)?;
        assert_eq!(
            config,
            ResolvedConfig {
                vpx_executable: PathBuf::from("/home/me/vpinball"),
                launch_templates: vec!(LaunchTemplate {
                    name: "Launch".to_string(),
                    executable: PathBuf::from("/home/me/vpinball"),
                    arguments: None,
                    env: Some(HashMap::from([
                        ("SDL_VIDEODRIVER".to_string(), "".to_string()),
                        ("SDL_RENDER_DRIVER".to_string(), "".to_string()),
                    ])),
                    vpinball_config: None,
                },),

                vpx_config: default_vpinball_ini_file(&PathBuf::from("/home/me/vpinball")),
                tables_folder: PathBuf::from("/home/me/tables"),
                tables_index_path: PathBuf::from("/home/me/tables/vpxtool_index.json"),
                tables_scan_max_depth: None,
                diff: None,
                editor: None,
            }
        );
        Ok(())
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn test_read_launch_template_with_vpinball_config() -> io::Result<()> {
        let temp_dir = testdir!();
        let config_file = temp_dir.join(CONFIGURATION_FILE_NAME);
        let mut file = File::create(&config_file)?;
        file.write_all(
            b"vpx_executable = \"/tmp/test/vpinball\"\n\
              \n\
              [[launch_templates]]\n\
              name = \"Launch BGFX\"\n\
              executable = \"/tmp/test/VPinballX_BGFX\"\n\
              vpinball_config = \"/tmp/test/VPinballX_BGFX.ini\"\n\
              \n\
              [[launch_templates]]\n\
              name = \"Launch GL\"\n\
              executable = \"/tmp/test/VPinballX_GL\"\n",
        )?;

        let config = read_config(&config_file)?;

        assert_eq!(
            config.launch_templates,
            vec![
                LaunchTemplate {
                    name: "Launch BGFX".to_string(),
                    executable: PathBuf::from("/tmp/test/VPinballX_BGFX"),
                    arguments: None,
                    env: None,
                    vpinball_config: Some(PathBuf::from("/tmp/test/VPinballX_BGFX.ini")),
                },
                LaunchTemplate {
                    name: "Launch GL".to_string(),
                    executable: PathBuf::from("/tmp/test/VPinballX_GL"),
                    arguments: None,
                    env: None,
                    vpinball_config: None,
                },
            ]
        );
        Ok(())
    }

    #[test]
    fn test_read_config_with_tables_scan_max_depth() -> io::Result<()> {
        let temp_dir = testdir!();
        let config_file = temp_dir.join(CONFIGURATION_FILE_NAME);
        let mut file = File::create(&config_file)?;
        file.write_all(
            b"vpx_executable = \"/tmp/test/vpinball\"\n\
              tables_scan_max_depth = 2\n",
        )?;

        let config = read_config(&config_file)?;
        assert_eq!(config.tables_scan_max_depth, Some(2));
        Ok(())
    }

    // test that we can read an incomplete config file with missing tables_folder
    #[cfg(target_os = "linux")]
    #[test]
    fn test_read_incomplete_config_linux() -> io::Result<()> {
        let temp_dir = testdir!();
        let config_file = temp_dir.join(CONFIGURATION_FILE_NAME);
        let mut file = File::create(&config_file)?;
        file.write_all(b"vpx_executable = \"/tmp/test/vpinball\"")?;

        let config = read_config(&config_file)?;

        assert_eq!(
            config,
            ResolvedConfig {
                vpx_executable: PathBuf::from("/tmp/test/vpinball"),
                launch_templates: vec!(LaunchTemplate {
                    name: "Launch".to_string(),
                    executable: PathBuf::from("/tmp/test/vpinball"),
                    arguments: None,
                    env: Some(HashMap::from([
                        ("SDL_VIDEODRIVER".to_string(), "".to_string()),
                        ("SDL_RENDER_DRIVER".to_string(), "".to_string()),
                    ])),
                    vpinball_config: None,
                },),
                vpx_config: default_vpinball_ini_file(&PathBuf::from("/tmp/test/vpinball")),
                tables_folder: PathBuf::from("/tmp/test/tables"),
                tables_index_path: PathBuf::from("/tmp/test/tables/vpxtool_index.json"),
                tables_scan_max_depth: None,
                diff: None,
                editor: None,
            }
        );
        Ok(())
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn test_read_incomplete_config_macos() -> io::Result<()> {
        let temp_dir = testdir!();
        let config_file = temp_dir.join(CONFIGURATION_FILE_NAME);
        let mut file = File::create(&config_file)?;
        file.write_all(b"vpx_executable = \"/tmp/test/vpinball\"")?;

        let config = read_config(&config_file)?;

        let expected_tables_dir = dirs::home_dir().unwrap().join(".vpinball").join("tables");
        assert_eq!(
            config,
            ResolvedConfig {
                vpx_executable: PathBuf::from("/tmp/test/vpinball"),
                launch_templates: vec!(LaunchTemplate {
                    name: "Launch".to_string(),
                    executable: PathBuf::from("/tmp/test/vpinball"),
                    arguments: None,
                    env: Some(HashMap::from([
                        ("SDL_VIDEODRIVER".to_string(), "".to_string()),
                        ("SDL_RENDER_DRIVER".to_string(), "".to_string()),
                    ])),
                    vpinball_config: None,
                }),
                vpx_config: default_vpinball_ini_file(&PathBuf::from("/tmp/test/vpinball")),
                tables_folder: expected_tables_dir.clone(),
                tables_index_path: expected_tables_dir.join("vpxtool_index.json"),
                tables_scan_max_depth: None,
                diff: None,
                editor: None,
            }
        );
        Ok(())
    }

    #[cfg(target_os = "windows")]
    #[test]
    fn test_read_incomplete_config_windows() -> io::Result<()> {
        let temp_dir = testdir!();
        let config_file = temp_dir.join(CONFIGURATION_FILE_NAME);
        let mut file = File::create(&config_file)?;
        file.write_all(b"vpx_executable = \"C:\\\\test\\\\vpinball\"")?;

        let config = read_config(&config_file)?;

        assert_eq!(
            config,
            ResolvedConfig {
                vpx_executable: PathBuf::from("C:\\test\\vpinball"),
                vpx_config: default_vpinball_ini_file(&PathBuf::from("C:\\test\\vpinball")),
                tables_folder: PathBuf::from("C:\\test\\tables"),
                tables_index_path: PathBuf::from("C:\\test\\tables\\vpxtool_index.json"),
                tables_scan_max_depth: None,
                diff: None,
                editor: None,
                launch_templates: vec!(LaunchTemplate {
                    name: "Launch".to_string(),
                    executable: PathBuf::from("C:\\test\\vpinball"),
                    arguments: None,
                    env: Some(HashMap::from([
                        ("SDL_VIDEODRIVER".to_string(), "".to_string()),
                        ("SDL_RENDER_DRIVER".to_string(), "".to_string()),
                    ])),
                    vpinball_config: None,
                })
            }
        );
        Ok(())
    }

    #[test]
    fn test_parse_major_minor() {
        assert_eq!(parse_major_minor("10.8"), Some((10, 8)));
        assert_eq!(parse_major_minor("10.10"), Some((10, 10)));
        assert_eq!(parse_major_minor("11.0"), Some((11, 0)));
        assert_eq!(parse_major_minor("10"), None);
        assert_eq!(parse_major_minor("10.8.0"), None);
        assert_eq!(parse_major_minor(""), None);
        assert_eq!(parse_major_minor("foo"), None);
    }

    #[test]
    fn test_newest_versioned_vpinball_ini_picks_highest() -> io::Result<()> {
        // Layout under <base>:
        //   10.8/VPinballX.ini      <- ini present
        //   10.10/VPinballX.ini     <- ini present, highest version
        //   11.0/                   <- newer dir but no ini, must be skipped
        //   not-a-version/          <- ignored
        let base = testdir!().join("VPinballX");
        for (version, has_ini) in [("10.8", true), ("10.10", true), ("11.0", false)] {
            let dir = base.join(version);
            fs::create_dir_all(&dir)?;
            if has_ini {
                File::create(dir.join("VPinballX.ini"))?;
            }
        }
        fs::create_dir_all(base.join("not-a-version"))?;

        // 11.0 has no ini, so 10.10 wins (numeric, not lexicographic).
        let picked = newest_versioned_vpinball_ini(&base).expect("expected an ini path");
        assert_eq!(picked, base.join("10.10").join("VPinballX.ini"));
        Ok(())
    }

    #[test]
    fn test_newest_versioned_vpinball_ini_returns_none_when_empty() {
        let base = testdir!().join("does-not-exist");
        assert_eq!(newest_versioned_vpinball_ini(&base), None);
    }

    #[test]
    fn test_rewrite_vpx_config_preserves_comments_and_layout() -> io::Result<()> {
        // A user-edited config file: comments, blank lines, and a non-default
        // field ordering. After rewrite_vpx_config swaps the vpx_config value,
        // everything else must come through byte-faithfully.
        let temp_dir = testdir!();
        let config_file = temp_dir.join(CONFIGURATION_FILE_NAME);
        let original = "\
# vpxtool config for the tournament rig

vpx_executable = \"/home/me/vpinball\"

# old default - vpxtool will offer to fix this
vpx_config = \"/home/me/.vpinball/VPinballX.ini\"

# don't recurse beyond two levels
tables_scan_max_depth = 2
";
        std::fs::write(&config_file, original)?;

        let new_path = PathBuf::from("/home/me/.local/share/VPinballX/10.8/VPinballX.ini");
        rewrite_vpx_config(&config_file, &new_path)?;

        let after = std::fs::read_to_string(&config_file)?;
        let expected = original.replace(
            "/home/me/.vpinball/VPinballX.ini",
            "/home/me/.local/share/VPinballX/10.8/VPinballX.ini",
        );
        assert_eq!(after, expected);
        Ok(())
    }
}