indicatrix-cut 0.6.2

Desktop faceting-design editor: library browsing, spectral 3D rendering, material retargeting, and a solid inspection view.
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
//! Load/save the settings TOML file.
//!
//! A settings file must never prevent the app from starting: every failure mode here
//! (missing file, unreadable file, corrupt/unparseable TOML) is caught and logged,
//! falling back to `SettingsFile::default()` rather than propagating an error.

use super::model::SettingsFile;
use std::{
    io,
    path::{Path, PathBuf},
};
use tracing::{info, warn};

// Named for THIS crate, not the public app this crate was copied from -- the two are
// separate binaries that can be installed side by side, and sharing one settings
// directory would mean whichever app last saved silently overwrites the other's file.
const APP_DIR_NAME: &str = "indicatrix-cut";
/// The public app's own app-dir name, kept for exactly one purpose:
/// [`migrate_legacy_settings_if_needed`]'s one-time copy, so a machine that already
/// has the public app configured doesn't have the editor start completely blank.
///
/// `"diagram-gui"` -- the old public viewer this editor (`indicatrix-cut`, née
/// `private/apps/diagram-editor`) superseded, before the 2026-09-07 suite-wide rename
/// to Indicatrix deleted it outright (see the rename map in project memory:
/// `apps/diagram-gui (old viewer) -> deleted; superseded by the editor`). This used
/// to be a no-op (both constants read `"indicatrix-cut"`), which made the migration
/// below silently copy a path onto itself and orphan any real `diagram-gui`
/// installation's settings on upgrade.
const LEGACY_APP_DIR_NAME: &str = "diagram-gui";
const SETTINGS_FILE_NAME: &str = "settings.toml";

/// Resolves `app_dir_name/settings.toml` inside the platform config directory (not
/// next to the executable, to avoid requiring write access to the install directory).
/// Shared by [`default_settings_path`] and [`legacy_settings_path`] so the two paths
/// can never disagree about where the platform config directory itself lives.
///
/// - Windows: `%APPDATA%\<app_dir_name>\settings.toml`
/// - macOS: `~/Library/Application Support/<app_dir_name>/settings.toml`
/// - Linux/other Unix: `$XDG_CONFIG_HOME/<app_dir_name>/settings.toml`, falling back to
///   `~/.config/<app_dir_name>/settings.toml`
///
/// If none of the expected environment variables are set (unusual, but not
/// impossible), falls back to a `<app_dir_name>/settings.toml` path relative to the
/// current working directory rather than failing outright.
fn settings_path_under(app_dir_name: &str) -> PathBuf {
    platform_config_dir()
        .unwrap_or_else(|| PathBuf::from("."))
        .join(app_dir_name)
        .join(SETTINGS_FILE_NAME)
}

/// This crate's own settings file path -- see [`settings_path_under`].
#[must_use]
pub fn default_settings_path() -> PathBuf {
    settings_path_under(APP_DIR_NAME)
}

/// Where the public app's settings file lives, in the SAME platform config directory
/// this crate's settings resolve under -- the one-time migration source. See
/// [`migrate_legacy_settings_if_needed`].
fn legacy_settings_path() -> PathBuf {
    settings_path_under(LEGACY_APP_DIR_NAME)
}

/// One-time carry-over of the public app's settings file into this crate's own,
/// now-separate one. Without this, the editor would start completely blank on a
/// machine that already had the old app configured -- losing remote workers, cert
/// directories, export paths, and presets.
///
/// Called once, right before [`load_or_default`], with `new_path` the editor's own
/// resolved settings path, threaded through rather than recomputed so tests can point
/// it at a temp directory.
///
/// - **Copies, never moves.** The legacy app is a separate, still-actively-used binary
///   reading the SAME file this copies FROM -- deleting or renaming it would break
///   that app. `std::fs::copy` duplicates bytes; it never touches the source.
/// - **Never overwrites an existing editor settings file.** Only fires into a
///   genuinely absent destination (checked first) -- a one-time bootstrap, not an
///   ongoing sync.
/// - **A failed copy must not stop the app starting.** Every failure mode is caught
///   and logged with `warn!`, falling through to whatever [`load_or_default`] does
///   with the still-absent destination.
pub fn migrate_legacy_settings_if_needed(new_path: &Path) {
    copy_legacy_settings_if_absent(&legacy_settings_path(), new_path);
}

/// The actual copy logic behind [`migrate_legacy_settings_if_needed`], with `old_path`
/// passed in explicitly so this module's tests can exercise every branch with
/// temp-directory paths rather than touching a real `%APPDATA%`.
fn copy_legacy_settings_if_absent(old_path: &Path, new_path: &Path) {
    if new_path.exists() {
        // Already has its own settings -- never overwrite it.
        return;
    }
    if !old_path.exists() {
        // The common case: nothing to migrate. Not even worth a `warn!`.
        return;
    }
    if let Some(parent) = new_path.parent()
        && let Err(e) = std::fs::create_dir_all(parent)
    {
        warn!(
            "Could not create {} to migrate legacy indicatrix-cut settings into; \
             starting with defaults instead: {e}",
            parent.display()
        );
        return;
    }
    match std::fs::copy(old_path, new_path) {
        Ok(_) => info!(
            "Migrated settings from the legacy config at {} to {}.",
            old_path.display(),
            new_path.display()
        ),
        Err(e) => warn!(
            "Could not copy legacy settings from {} to {}; starting with defaults \
             instead: {e}",
            old_path.display(),
            new_path.display()
        ),
    }
}

#[cfg(target_os = "windows")]
fn platform_config_dir() -> Option<PathBuf> {
    std::env::var_os("APPDATA").map(PathBuf::from)
}

#[cfg(target_os = "macos")]
fn platform_config_dir() -> Option<PathBuf> {
    std::env::var_os("HOME").map(|home| {
        PathBuf::from(home)
            .join("Library")
            .join("Application Support")
    })
}

#[cfg(all(unix, not(target_os = "macos")))]
fn platform_config_dir() -> Option<PathBuf> {
    if let Some(xdg) = std::env::var_os("XDG_CONFIG_HOME") {
        return Some(PathBuf::from(xdg));
    }
    std::env::var_os("HOME").map(|home| PathBuf::from(home).join(".config"))
}

/// What happened while loading the settings file -- returned by [`load_with_outcome`]
/// alongside the (possibly-defaulted) [`SettingsFile`] so `gui::main_window` can toast
/// a corrupt-file recovery instead of the cutter's saved settings silently vanishing
/// with only a `tracing::warn!` nobody watching a release build's console ever sees.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SettingsLoadOutcome {
    /// Loaded normally, or the file was genuinely absent (first run) -- nothing to
    /// report.
    Ok,
    /// The file existed but its content was unreadable or failed to parse as valid
    /// `SettingsFile` TOML. Renamed aside to `renamed_to`
    /// (`settings.toml.corrupt-<unix-seconds>`, see [`rename_aside`]) before this load
    /// fell back to defaults, so the broken file is never silently overwritten by the
    /// very next save -- it stays on disk for the cutter (or a bug report) to inspect.
    Corrupt {
        /// Where the corrupt file was renamed to, for the toast to name.
        renamed_to: PathBuf,
    },
}

/// Renames `path` aside to `<path>.corrupt-<unix-seconds>` so the next save never
/// silently overwrites the one piece of evidence explaining what went wrong. Returns
/// the new path on success; logs and returns `None` on failure (e.g. no write
/// permission on the containing directory) rather than blocking startup on a rename
/// that isn't the load itself.
fn rename_aside(path: &Path) -> Option<PathBuf> {
    let unix_secs = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map_or(0, |d| d.as_secs());
    let mut renamed = path.as_os_str().to_owned();
    renamed.push(format!(".corrupt-{unix_secs}"));
    let renamed = PathBuf::from(renamed);
    match std::fs::rename(path, &renamed) {
        Ok(()) => Some(renamed),
        Err(e) => {
            warn!(
                "Could not rename the corrupt settings file at {} aside to {}: {e}. \
                 Continuing with defaults; the corrupt file is still at its original path.",
                path.display(),
                renamed.display()
            );
            None
        }
    }
}

/// [`load_or_default`], plus what actually happened -- see [`SettingsLoadOutcome`].
/// Never panics and never propagates an error: this is deliberately infallible so a
/// broken settings file can never block startup.
#[must_use]
pub fn load_with_outcome(path: &Path) -> (SettingsFile, SettingsLoadOutcome) {
    let (mut file, outcome) = match std::fs::read_to_string(path) {
        Ok(contents) => match toml::from_str::<SettingsFile>(&contents) {
            Ok(file) => (file, SettingsLoadOutcome::Ok),
            Err(e) => {
                warn!(
                    "Settings file at {} is corrupt ({e}); falling back to defaults.",
                    path.display()
                );
                // Renamed BEFORE falling back to defaults: the very next save (which
                // happens on almost any interaction) would otherwise overwrite the
                // corrupt file with a fresh default one, losing the one piece of
                // evidence explaining what went wrong -- see this constructor's own
                // doc comment.
                let outcome = rename_aside(path).map_or(SettingsLoadOutcome::Ok, |renamed_to| {
                    SettingsLoadOutcome::Corrupt { renamed_to }
                });
                (SettingsFile::default(), outcome)
            }
        },
        Err(e) if e.kind() == io::ErrorKind::NotFound => {
            info!(
                "No settings file at {} yet; using defaults.",
                path.display()
            );
            (SettingsFile::default(), SettingsLoadOutcome::Ok)
        }
        Err(e) => {
            warn!(
                "Could not read settings file at {} ({e}); falling back to defaults.",
                path.display()
            );
            (SettingsFile::default(), SettingsLoadOutcome::Ok)
        }
    };
    file.ensure_built_in_presets();
    // Files from before the single-remote-endpoint rule carry a `remote_workers`
    // list; fold it into the single endpoint (logged inside). The next save writes only `remote`.
    file.settings.migrate_legacy_remote_workers();
    (file, outcome)
}

/// Loads settings from `path`, falling back to defaults (with built-in presets) on
/// any failure -- missing file, unreadable file, or corrupt/unparseable TOML. Never
/// panics and never propagates an error: this is deliberately infallible so a broken
/// settings file can never block startup.
///
/// A thin wrapper over [`load_with_outcome`] for callers that only want the settings
/// themselves. The application's only load, `gui::main_window`'s startup one, wants the
/// full [`SettingsLoadOutcome`] to toast a corrupt-file recovery, so this is a
/// convenience for tests.
///
/// Reading the file belongs to startup only: once the `SettingsPersister` is seeded
/// from it, the persister's in-memory snapshot is the source of truth, and a caller
/// that re-read the file mid-session would miss changes still inside the persister's
/// debounce window.
#[cfg(test)]
#[must_use]
pub fn load_or_default(path: &Path) -> SettingsFile {
    load_with_outcome(path).0
}

/// Writes `settings` to `path` as pretty-printed TOML, creating the parent directory
/// if needed. Writes to a temporary sibling file and renames it into place so a crash
/// or power loss mid-write can never leave a half-written, corrupt settings file
/// behind -- the rename is the only step that can make the new content visible, and
/// `std::fs::rename` replaces an existing destination atomically on both Windows
/// (`MoveFileExW` with `MOVEFILE_REPLACE_EXISTING`) and Unix.
pub fn save(path: &Path, settings: &SettingsFile) -> io::Result<()> {
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent)?;
    }
    let toml_str = toml::to_string_pretty(settings)
        .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;

    let tmp_path = path.with_extension("toml.tmp");
    std::fs::write(&tmp_path, toml_str)?;
    std::fs::rename(&tmp_path, path)?;
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::settings::model::{AppSettings, LightingPreset};
    use std::sync::atomic::{AtomicU32, Ordering};

    static COUNTER: AtomicU32 = AtomicU32::new(0);

    /// A fresh, unique scratch directory under the OS temp dir, cleaned up when the
    /// returned guard drops. Avoids adding a `tempfile` dependency for a handful of
    /// small round-trip tests.
    struct TempDir(PathBuf);
    impl TempDir {
        fn new(tag: &str) -> Self {
            let n = COUNTER.fetch_add(1, Ordering::Relaxed);
            let dir = std::env::temp_dir().join(format!(
                "indicatrix-cut-settings-test-{tag}-{}-{n}",
                std::process::id()
            ));
            std::fs::create_dir_all(&dir).unwrap();
            Self(dir)
        }
        fn path(&self) -> &Path {
            &self.0
        }
    }
    impl Drop for TempDir {
        fn drop(&mut self) {
            let _ = std::fs::remove_dir_all(&self.0);
        }
    }

    #[test]
    fn missing_file_falls_back_to_defaults_without_panicking() {
        let dir = TempDir::new("missing");
        let path = dir.path().join("does-not-exist.toml");
        let loaded = load_or_default(&path);
        assert_eq!(loaded, SettingsFile::default());
    }

    #[test]
    fn corrupt_file_falls_back_to_defaults_without_panicking() {
        let dir = TempDir::new("corrupt");
        let path = dir.path().join("settings.toml");
        std::fs::write(&path, "this is { not [ valid toml at all").unwrap();
        let loaded = load_or_default(&path);
        assert_eq!(loaded, SettingsFile::default());
    }

    #[test]
    fn unreadable_directory_in_place_of_file_falls_back_to_defaults() {
        // A directory in place of a file makes `read_to_string` fail with something
        // other than `NotFound`, exercising the third fallback arm.
        let dir = TempDir::new("isdir");
        let path = dir.path().join("settings.toml");
        std::fs::create_dir_all(&path).unwrap();
        let loaded = load_or_default(&path);
        assert_eq!(loaded, SettingsFile::default());
    }

    #[test]
    fn partially_corrupt_file_keeps_valid_fields_and_defaults_missing_ones() {
        let dir = TempDir::new("partial");
        let path = dir.path().join("settings.toml");
        // Valid TOML, missing most fields, with an extra unknown key -- must still
        // parse, defaulting everything not present.
        std::fs::write(
            &path,
            "[settings]\nexposure = 1.75\nsomething_unknown = true\n",
        )
        .unwrap();
        let loaded = load_or_default(&path);
        assert_eq!(loaded.settings.exposure, 1.75);
        assert_eq!(
            loaded.settings.target_samples,
            AppSettings::default().target_samples
        );
        // Built-ins still get filled in even with no [[presets]] at all.
        assert_eq!(
            loaded.presets.len(),
            super::super::model::built_in_presets().len()
        );
    }

    #[test]
    fn library_panel_collapsed_state_round_trips_through_save_and_load() {
        let dir = TempDir::new("library-panel-collapsed");
        let path = dir.path().join("settings.toml");

        let mut collapsed = SettingsFile::default();
        collapsed.settings.library_panel_collapsed = true;
        save(&path, &collapsed).unwrap();
        assert!(load_or_default(&path).settings.library_panel_collapsed);

        let mut expanded = SettingsFile::default();
        expanded.settings.library_panel_collapsed = false;
        save(&path, &expanded).unwrap();
        assert!(!load_or_default(&path).settings.library_panel_collapsed);
    }

    #[test]
    fn missing_library_panel_collapsed_key_defaults_to_expanded() {
        let dir = TempDir::new("library-panel-collapsed-missing-key");
        let path = dir.path().join("settings.toml");
        std::fs::write(&path, "[settings]\nexposure = 1.0\n").unwrap();
        assert!(!load_or_default(&path).settings.library_panel_collapsed);
    }

    #[test]
    fn editor_layout_settings_round_trip_through_save_and_load() {
        let dir = TempDir::new("editor-layout");
        let path = dir.path().join("settings.toml");

        let mut custom = SettingsFile::default();
        custom.settings.editor_dock_width = 620.0;
        custom.settings.editor_inspector_height = 310.0;
        custom.settings.editor_settings_collapsed = true;
        custom.settings.editor_inspector_collapsed = true;
        custom.settings.editor_remap_collapsed = true;
        custom.settings.editor_layout_touched = true;
        save(&path, &custom).unwrap();

        let loaded = load_or_default(&path);
        assert_eq!(loaded.settings.editor_dock_width, 620.0);
        assert_eq!(loaded.settings.editor_inspector_height, 310.0);
        assert!(loaded.settings.editor_settings_collapsed);
        assert!(loaded.settings.editor_inspector_collapsed);
        assert!(loaded.settings.editor_remap_collapsed);
        assert!(loaded.settings.editor_layout_touched);
    }

    #[test]
    fn missing_editor_layout_keys_default_to_the_old_fixed_layout() {
        let dir = TempDir::new("editor-layout-missing-key");
        let path = dir.path().join("settings.toml");
        std::fs::write(&path, "[settings]\nexposure = 1.0\n").unwrap();

        let loaded = load_or_default(&path);
        assert_eq!(
            loaded.settings.editor_dock_width,
            AppSettings::default().editor_dock_width
        );
        assert_eq!(
            loaded.settings.editor_inspector_height,
            AppSettings::default().editor_inspector_height
        );
        assert!(!loaded.settings.editor_settings_collapsed);
        assert!(!loaded.settings.editor_inspector_collapsed);
        assert!(!loaded.settings.editor_remap_collapsed);
        assert!(!loaded.settings.editor_layout_touched);
    }

    #[test]
    fn solid_view_mode_round_trips_through_save_and_load() {
        let dir = TempDir::new("solid-view-mode");
        let path = dir.path().join("settings.toml");

        let mut both = SettingsFile::default();
        both.settings.solid_view_mode = 2;
        save(&path, &both).unwrap();
        assert_eq!(load_or_default(&path).settings.solid_view_mode, 2);

        let mut solid = SettingsFile::default();
        solid.settings.solid_view_mode = 0;
        save(&path, &solid).unwrap();
        assert_eq!(load_or_default(&path).settings.solid_view_mode, 0);
    }

    #[test]
    fn missing_solid_view_mode_key_defaults_to_solid() {
        let dir = TempDir::new("solid-view-mode-missing-key");
        let path = dir.path().join("settings.toml");
        std::fs::write(&path, "[settings]\nexposure = 1.0\n").unwrap();
        assert_eq!(load_or_default(&path).settings.solid_view_mode, 0);
    }

    #[test]
    fn live_view_mode_round_trips_through_save_and_load() {
        let dir = TempDir::new("live-view-mode");
        let path = dir.path().join("settings.toml");

        let mut solid = SettingsFile::default();
        solid.settings.live_view_mode = 0;
        save(&path, &solid).unwrap();
        assert_eq!(load_or_default(&path).settings.live_view_mode, 0);

        let mut traced = SettingsFile::default();
        traced.settings.live_view_mode = 1;
        save(&path, &traced).unwrap();
        assert_eq!(load_or_default(&path).settings.live_view_mode, 1);
    }

    #[test]
    fn missing_live_view_mode_key_defaults_to_path_traced() {
        let dir = TempDir::new("live-view-mode-missing-key");
        let path = dir.path().join("settings.toml");
        std::fs::write(&path, "[settings]\nexposure = 1.0\n").unwrap();
        assert_eq!(load_or_default(&path).settings.live_view_mode, 1);
    }

    #[test]
    fn settings_with_a_lit_model_lighting_rig_round_trip() {
        let dir = TempDir::new("lit-model");
        let path = dir.path().join("settings.toml");

        let mut custom = SettingsFile::default();
        custom.settings.lighting_rig = "ISO hemisphere".to_string();
        save(&path, &custom).unwrap();

        let loaded = load_or_default(&path);
        assert_eq!(loaded.settings.lighting_rig, "ISO hemisphere");
    }

    #[test]
    fn save_then_load_round_trips_settings_and_presets() {
        let dir = TempDir::new("roundtrip");
        let path = dir.path().join("nested").join("settings.toml");

        let mut original = SettingsFile::default();
        original.settings.exposure = 1.65;
        original.settings.max_bounces = 20;
        original.settings.selected_material = "Ruby".to_string();
        original
            .upsert_user_preset(LightingPreset {
                name: "Golden Hour".to_string(),
                built_in: false,
                light_yaw_deg: 88.0,
                light_pitch_deg: 33.0,
                exposure: 1.15,
                lighting_rig: "D65 Daylight (5500K)".to_string(),
                camera_distance: 2.9,
                camera_yaw: None,
                camera_pitch: None,
                env_map_path: None,
                export_usable: false,
            })
            .unwrap();

        save(&path, &original).expect("save should succeed, creating parent dirs");
        assert!(path.exists());

        let loaded = load_or_default(&path);
        assert_eq!(loaded, original);
    }

    #[test]
    fn save_overwrites_existing_file_atomically() {
        let dir = TempDir::new("overwrite");
        let path = dir.path().join("settings.toml");

        let first = SettingsFile::default();
        save(&path, &first).unwrap();

        let mut second = SettingsFile::default();
        second.settings.exposure = 2.0;
        save(&path, &second).unwrap();

        let loaded = load_or_default(&path);
        assert_eq!(loaded.settings.exposure, 2.0);
        // No leftover temp file.
        assert!(!path.with_extension("toml.tmp").exists());
    }

    /// An old settings FILE holding two workers loads with the first as the single
    /// remote endpoint, and the next save no longer carries the retired list.
    #[test]
    fn an_old_file_with_two_workers_migrates_on_load_and_saves_without_the_list() {
        let dir = TempDir::new("two-workers");
        let path = dir.path().join("settings.toml");
        std::fs::write(
            &path,
            "[settings]\nexposure = 1.0\n\n\
             [[settings.remote_workers]]\nname = \"A\"\naddress = \"a.lan:7878\"\n\n\
             [[settings.remote_workers]]\nname = \"B\"\naddress = \"b.lan:7878\"\n",
        )
        .unwrap();
        let loaded = load_or_default(&path);
        let remote = loaded.settings.remote.as_ref().expect("first worker kept");
        assert_eq!(remote.connection.address, "a.lan:7878");
        assert_eq!(loaded.settings.legacy_remote_workers.len(), 0);

        save(&path, &loaded).unwrap();
        let text = std::fs::read_to_string(&path).unwrap();
        assert!(!text.contains("remote_workers"), "{text}");
        assert!(!text.contains("b.lan"), "{text}");
        assert_eq!(
            load_or_default(&path).settings.remote,
            loaded.settings.remote
        );
    }

    #[test]
    fn default_settings_path_is_non_empty_and_ends_with_settings_file_name() {
        let path = default_settings_path();
        assert!(path.to_string_lossy().ends_with("settings.toml"));
        assert!(path.components().any(|c| c.as_os_str() == APP_DIR_NAME));
    }

    /// [`migrate_legacy_settings_if_needed`] takes an explicit `new_path` precisely so
    /// these tests can point it at a temp directory rather than a real `%APPDATA%`.
    mod migration {
        use super::*;

        #[test]
        fn migrates_when_editor_settings_are_absent() {
            let dir = TempDir::new("migrate-absent");
            let old_path = dir.path().join("old-settings.toml");
            let new_path = dir.path().join("new-settings.toml");
            std::fs::write(&old_path, "[settings]\nexposure = 2.5\n").unwrap();

            copy_legacy_settings_if_absent(&old_path, &new_path);

            assert!(new_path.exists());
            assert_eq!(
                std::fs::read_to_string(&new_path).unwrap(),
                std::fs::read_to_string(&old_path).unwrap()
            );
            // Copy, never move: the legacy file must still be there afterward.
            assert!(old_path.exists());
        }

        #[test]
        fn does_not_fire_when_editor_settings_already_exist() {
            let dir = TempDir::new("migrate-existing");
            let old_path = dir.path().join("old-settings.toml");
            let new_path = dir.path().join("new-settings.toml");
            std::fs::write(&old_path, "[settings]\nexposure = 2.5\n").unwrap();
            std::fs::write(&new_path, "[settings]\nexposure = 9.9\n").unwrap();

            copy_legacy_settings_if_absent(&old_path, &new_path);

            // Untouched -- the editor's own file must never be clobbered by a legacy
            // one, even though the legacy file exists and differs.
            assert_eq!(
                std::fs::read_to_string(&new_path).unwrap(),
                "[settings]\nexposure = 9.9\n"
            );
        }

        #[test]
        fn survives_a_missing_legacy_file() {
            let dir = TempDir::new("migrate-no-legacy");
            let old_path = dir.path().join("does-not-exist.toml");
            let new_path = dir.path().join("new-settings.toml");

            copy_legacy_settings_if_absent(&old_path, &new_path);

            assert!(
                !new_path.exists(),
                "nothing to migrate from -> nothing written"
            );
        }

        #[test]
        fn survives_an_unreadable_legacy_file() {
            // A directory where a file is expected fails `fs::copy`, exercising the
            // "exists but unreadable" path distinctly from "absent".
            let dir = TempDir::new("migrate-unreadable-legacy");
            let old_path = dir.path().join("old-settings.toml");
            std::fs::create_dir_all(&old_path).unwrap();
            let new_path = dir.path().join("new-settings.toml");

            copy_legacy_settings_if_absent(&old_path, &new_path);

            assert!(
                !new_path.exists(),
                "a failed copy must not leave a partial/empty destination file"
            );
        }

        #[test]
        fn creates_the_destination_directory_when_missing() {
            let dir = TempDir::new("migrate-nested-dest");
            let old_path = dir.path().join("old-settings.toml");
            std::fs::write(&old_path, "[settings]\nexposure = 3.0\n").unwrap();
            let new_path = dir.path().join("nested").join("new-settings.toml");

            copy_legacy_settings_if_absent(&old_path, &new_path);

            assert!(new_path.exists());
        }
    }
}