mdo-cli 0.6.2

A simple Rust CLI to convert Markdown to HTML5 (styled with simple.css), with optional file watching
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
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
use std::io;
use std::path::{Path, PathBuf};
use std::process::Command;
#[cfg(target_os = "windows")]
use std::process::Stdio;

use crate::handler;

const APP_DISPLAY_NAME: &str = "Open as HTML";
#[cfg(target_os = "linux")]
const DESKTOP_FILE_NAME: &str = "mdo.desktop";
#[cfg(target_os = "linux")]
const SETUP_DESKTOP_FILE_NAME: &str = "mdo-setup.desktop";
#[cfg(target_os = "windows")]
const WINDOWS_ICON_BYTES: &[u8] = include_bytes!("../assets/mdo.ico");
#[cfg(target_os = "linux")]
const SVG_ICON: &str = r##"<svg xmlns="http://www.w3.org/2000/svg" width="256" height="256" viewBox="0 0 256 256">
  <rect width="256" height="256" rx="48" fill="#f7f7f7"/>
  <text x="128" y="151"
        text-anchor="middle"
        dominant-baseline="middle"
        font-family="Segoe UI Symbol, Noto Sans Symbols 2, Noto Sans Symbols, DejaVu Sans, sans-serif"
        font-size="176"
        font-weight="700"
        fill="#1e66e2">â“‚</text>
</svg>
"##;

#[cfg(any(target_os = "linux", target_os = "windows"))]
use std::fs;

/// Register the file-manager integration for this user. On Linux this
/// writes the hidden `mdo.desktop` entry and its icon through a pure
/// planning step and a thin executor; on Windows it shells out to
/// `reg.exe` (see [`install_windows_plan`] for the registry shape).
/// Windows ignores `set_default`: choosing a default app lives in
/// Explorer's Open with dialog, not in the registration.
#[cfg(target_os = "linux")]
pub fn install(set_default: bool) -> io::Result<()> {
    let exe = std::env::current_exe()?;
    let data_home = xdg_data_home()?;

    let plan = linux_install_plan(&data_home, &exe, set_default);
    let report = apply_linux_install_plan(&plan)?;
    print_linux_install_report(&report);
    Ok(())
}

/// Data-first description of a Linux integration install: everything the
/// executor touches, decided without disk or environment access so the
/// planning step stays a pure function (unit-tested without spawn-capture),
/// mirroring the registry's [`install_windows_plan`].
#[cfg(target_os = "linux")]
#[derive(Clone, Debug, PartialEq, Eq)]
struct LinuxInstallPlan {
    /// The hidden `mdo.desktop` handler entry and where it goes.
    desktop_file: PathBuf,
    /// The entry's content, handler-invocation contract spelling included.
    desktop_entry: String,
    /// The hicolor icon file and where it goes.
    icon_file: PathBuf,
    /// Whether xdg-mime should try to register mdo as the default handler
    /// for the mimes in [`LinuxInstallPlan::default_mimes`].
    set_default: bool,
    /// The mimes to register, in order, exactly as the original inline flow
    /// did.
    default_mimes: &'static [&'static str],
    /// The data root the legacy nautilus script cleanup runs against.
    legacy_cleanup_root: Option<PathBuf>,
}

/// What the Linux install executor changed, for the caller to print. File
/// entries are paths; the default outcome is the one piece of xdg-mime's
/// best-effort behavior a human needs to see.
#[cfg(target_os = "linux")]
#[derive(Clone, Debug, PartialEq, Eq)]
struct LinuxInstallReport {
    desktop_file: PathBuf,
    icon_file: PathBuf,
    default: LinuxDefaultOutcome,
}

#[cfg(target_os = "linux")]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum LinuxDefaultOutcome {
    /// xdg-mime registered mdo for at least one of the mimes.
    Applied,
    /// Defaulting was requested but xdg-mime could not comply (tool
    /// missing or non-zero exit): the manual hint applies.
    NeedsManualHint,
    /// Defaulting was not requested: integration stays Open With-only.
    NotRequested,
}

#[cfg(target_os = "linux")]
fn linux_install_plan(data_home: &Path, current_exe: &Path, set_default: bool) -> LinuxInstallPlan {
    LinuxInstallPlan {
        desktop_file: data_home.join("applications").join(DESKTOP_FILE_NAME),
        desktop_entry: linux_desktop_entry(current_exe),
        icon_file: data_home
            .join("icons")
            .join("hicolor")
            .join("scalable")
            .join("apps")
            .join("mdo.svg"),
        set_default,
        default_mimes: &["text/markdown", "text/x-markdown"],
        legacy_cleanup_root: Some(data_home.to_path_buf()),
    }
}

/// Apply the plan in the original write order: directories, icon, entry
/// (mode 0644), best-effort desktop-database refresh, the optional default
/// registration, and the legacy cleanup. A scalable SVG under
/// hicolor/scalable/apps is resolved by name, so it needs no icon-cache
/// refresh; gtk-update-icon-cache on a user theme dir without an
/// index.theme just fails — skip it.
#[cfg(target_os = "linux")]
fn apply_linux_install_plan(plan: &LinuxInstallPlan) -> io::Result<LinuxInstallReport> {
    if let Some(applications) = plan.desktop_file.parent() {
        fs::create_dir_all(applications)?;
    }
    if let Some(icon_dir) = plan.icon_file.parent() {
        fs::create_dir_all(icon_dir)?;
    }
    fs::write(&plan.icon_file, SVG_ICON)?;
    fs::write(&plan.desktop_file, &plan.desktop_entry)?;

    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        fs::set_permissions(&plan.desktop_file, fs::Permissions::from_mode(0o644))?;
    }

    if let Some(applications) = plan.desktop_file.parent() {
        run_optional("update-desktop-database", &[applications.as_os_str()]);
    }

    let default = if plan.set_default {
        let mut ok = false;
        for mime in plan.default_mimes {
            ok |= run_optional_status(
                "xdg-mime",
                &[
                    std::ffi::OsStr::new("default"),
                    std::ffi::OsStr::new(DESKTOP_FILE_NAME),
                    std::ffi::OsStr::new(*mime),
                ],
            );
        }
        if ok {
            LinuxDefaultOutcome::Applied
        } else {
            LinuxDefaultOutcome::NeedsManualHint
        }
    } else {
        LinuxDefaultOutcome::NotRequested
    };

    if let Some(root) = &plan.legacy_cleanup_root {
        remove_legacy_nautilus_scripts(root)?;
    }

    Ok(LinuxInstallReport {
        desktop_file: plan.desktop_file.clone(),
        icon_file: plan.icon_file.clone(),
        default,
    })
}

/// Print the executor's report. This is the Linux install's whole CLI
/// surface; the exact lines mirror the pre-plan flow byte for byte.
#[cfg(target_os = "linux")]
fn print_linux_install_report(report: &LinuxInstallReport) {
    println!("Installed desktop entry: {}", report.desktop_file.display());
    println!("Installed icon: {}", report.icon_file.display());
    match report.default {
        LinuxDefaultOutcome::Applied => {
            println!("{APP_DISPLAY_NAME} is now the default Markdown handler.");
        }
        LinuxDefaultOutcome::NeedsManualHint => {
            println!(
                "Could not set {APP_DISPLAY_NAME} as the default automatically (is xdg-mime installed?)."
            );
            println!("To set it manually, run: xdg-mime default {DESKTOP_FILE_NAME} text/markdown");
            println!("(and the same for text/x-markdown)");
        }
        LinuxDefaultOutcome::NotRequested => {
            println!(
                "{APP_DISPLAY_NAME} is available from Open With without changing your default Markdown handler."
            );
        }
    }
}

/// Windows registration: resolve the handler beside the running exe, write
/// the icon, then apply the registry plan (planning and its tests are
/// pure; the executor is the only registry-touching step).
#[cfg(target_os = "windows")]
pub fn install(_set_default: bool) -> io::Result<()> {
    let current_exe = std::env::current_exe()?;
    let handler_selection = windows_handler_for(&current_exe);
    let command = windows_registry_command(&handler_selection.path, handler_selection.is_wrapper);
    let icon_file = install_windows_icon()?;
    let icon_ref = format!("\"{}\",0", icon_file.display());
    let current_exe_command = windows_registry_command(&current_exe, false);

    // Registry mutation is split into a pure planning step (`install_windows_plan`,
    // unit-tested below without touching the registry) and a thin executor
    // (`apply_registry_plan`) that shells out to `reg.exe`. This keeps the
    // "which keys/values would be written, in what order, with which
    // failure semantics" logic testable in CI without mutating the real
    // registry on the CI machine.
    let plan = install_windows_plan(
        handler_selection.is_wrapper,
        &command,
        &current_exe_command,
        &icon_ref,
    );
    apply_registry_plan(&plan)?;

    println!("Using handler: {}", handler_selection.path.display());
    println!("Using icon: {}", icon_file.display());
    if !handler_selection.is_wrapper {
        println!(
            "Note: mdo-open.exe was not found next to mdo.exe, so Explorer will launch mdo.exe directly."
        );
    }
    println!("{APP_DISPLAY_NAME} is registered for Markdown files.");
    println!("To make it the default, use Open with -> Choose another app -> {APP_DISPLAY_NAME} -> Always.");

    Ok(())
}

#[cfg(not(any(target_os = "linux", target_os = "windows")))]
pub fn install(_set_default: bool) -> io::Result<()> {
    Err(io::Error::new(
        io::ErrorKind::Unsupported,
        "built-in file-manager installation is currently supported on Windows and Linux",
    ))
}

#[cfg(target_os = "linux")]
pub fn uninstall() -> io::Result<()> {
    let data_home = xdg_data_home()?;
    let desktop_dir = data_home.join("applications");
    remove_linux_handler_files(&data_home)?;

    for mimeapps in mimeapps_paths(&data_home) {
        remove_desktop_from_mimeapps(&mimeapps)?;
    }

    run_optional("update-desktop-database", &[desktop_dir.as_os_str()]);

    println!("Done.");
    Ok(())
}

#[cfg(target_os = "windows")]
pub fn uninstall() -> io::Result<()> {
    // Uninstall was already best-effort (every op ignores failures), so this
    // reduces to applying the plan; `apply_registry_plan` returns `Ok(())`
    // whenever every op in the plan is best-effort, which is always true here.
    apply_registry_plan(&uninstall_windows_plan())?;
    let _ = remove_windows_icon();

    println!("Done.");
    println!(
        "If {APP_DISPLAY_NAME} was set as the default handler for .md, Windows will prompt you to pick a new default the next time you open a .md file."
    );
    Ok(())
}

#[cfg(not(any(target_os = "linux", target_os = "windows")))]
pub fn uninstall() -> io::Result<()> {
    Err(io::Error::new(
        io::ErrorKind::Unsupported,
        "built-in file-manager uninstallation is currently supported on Windows and Linux",
    ))
}

#[cfg(not(any(target_os = "linux", target_os = "windows")))]
pub fn integration_installed() -> bool {
    false
}

/// Report whether mdo's own handler registration is present for this user.
///
/// This is deliberately a cheap owned-state check (ADR 0004 defers the full
/// integration-state manager): it only asks "did mdo's install step leave its
/// own registration behind?" and never inspects handler health, partial or
/// stale remnants, system-wide registrations, or the effective default app.
/// A query failure reads as "not detected", so setup falls back to the
/// ordinary first-time flow — which is safe because install is idempotent.
#[cfg(target_os = "linux")]
pub fn integration_installed() -> bool {
    xdg_data_home()
        .map(|data_home| linux_integration_installed_at(&data_home))
        .unwrap_or(false)
}

#[cfg(target_os = "windows")]
pub fn integration_installed() -> bool {
    reg_key_exists(WINDOWS_OWNED_PROGID_COMMAND_KEY)
}

/// Install the application-menu entry for the native setup launcher.
///
/// This is deliberately separate from the install step above: the latter
/// owns the hidden Markdown file-handler entry and may be uninstalled without
/// making setup disappear from the application menu.
#[cfg(target_os = "linux")]
pub fn install_linux_setup_launcher_for_exe(setup_exe: &Path) -> io::Result<PathBuf> {
    let data_home = xdg_data_home()?;
    let desktop_file = write_linux_setup_launcher(setup_exe, &data_home)?;
    let desktop_dir = data_home.join("applications");

    run_optional("update-desktop-database", &[desktop_dir.as_os_str()]);
    Ok(desktop_file)
}

#[cfg(target_os = "linux")]
fn write_linux_setup_launcher(setup_exe: &Path, data_home: &Path) -> io::Result<PathBuf> {
    let desktop_dir = data_home.join("applications");
    let desktop_file = desktop_dir.join(SETUP_DESKTOP_FILE_NAME);

    fs::create_dir_all(&desktop_dir)?;
    fs::write(&desktop_file, linux_setup_desktop_entry(setup_exe))?;

    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        fs::set_permissions(&desktop_file, fs::Permissions::from_mode(0o644))?;
    }

    Ok(desktop_file)
}

/// The owned-state check only looks for the mdo-owned handler desktop entry.
/// The visible `mdo-setup.desktop` launcher has its own lifecycle and does not
/// count as handler integration.
#[cfg(target_os = "linux")]
fn linux_integration_installed_at(data_home: &Path) -> bool {
    data_home
        .join("applications")
        .join(DESKTOP_FILE_NAME)
        .is_file()
}

#[cfg(target_os = "linux")]
fn remove_linux_handler_files(data_home: &Path) -> io::Result<()> {
    let desktop_file = data_home.join("applications").join(DESKTOP_FILE_NAME);
    let icon_file = data_home
        .join("icons")
        .join("hicolor")
        .join("scalable")
        .join("apps")
        .join("mdo.svg");

    remove_file_if_present(&desktop_file)?;
    remove_file_if_present(&icon_file)?;
    remove_legacy_nautilus_scripts(data_home)
}

/// The single registry key the owned-state check queries: the open command of
/// mdo's own `mdo.md` ProgID. Install writes it (see [`install_windows_plan`])
/// and uninstall deletes its parent ProgID key, so its presence tracks exactly
/// the registration mdo owns — nothing about defaults or other handlers.
#[cfg(target_os = "windows")]
const WINDOWS_OWNED_PROGID_COMMAND_KEY: &str = r"HKCU\Software\Classes\mdo.md\shell\open\command";

#[cfg(target_os = "windows")]
fn reg_key_exists(key: &str) -> bool {
    Command::new("reg")
        .args(["query", key, "/ve"])
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .status()
        .map(|status| status.success())
        .unwrap_or(false)
}

#[cfg(target_os = "linux")]
fn xdg_data_home() -> io::Result<PathBuf> {
    if let Some(value) = std::env::var_os("XDG_DATA_HOME") {
        return Ok(PathBuf::from(value));
    }

    let home = std::env::var_os("HOME").ok_or_else(|| {
        io::Error::new(
            io::ErrorKind::NotFound,
            "HOME is not set; cannot locate ~/.local/share",
        )
    })?;
    Ok(PathBuf::from(home).join(".local").join("share"))
}

#[cfg(target_os = "linux")]
fn linux_desktop_entry(exe: &Path) -> String {
    let quoted_exe = quote_desktop_exec_arg(&exe.to_string_lossy());
    // The Exec line is the handler invocation contract in desktop-entry
    // spelling: the binary, the contract flags, then the %f file placeholder.
    let open_flags = handler::OPEN_FLAGS.join(" ");
    format!(
        "[Desktop Entry]\n\
         Type=Application\n\
         Name={APP_DISPLAY_NAME}\n\
         GenericName=Markdown HTML Opener\n\
         Comment=Open Markdown as HTML in the default browser\n\
         Exec={quoted_exe} {open_flags} %f\n\
         Icon=mdo\n\
         Terminal=false\n\
         NoDisplay=true\n\
         MimeType=text/markdown;text/x-markdown;\n\
         Categories=Utility;TextTools;\n\
         StartupNotify=false\n"
    )
}

#[cfg(target_os = "linux")]
fn linux_setup_desktop_entry(setup_exe: &Path) -> String {
    let quoted_exe = quote_desktop_exec_arg(&setup_exe.to_string_lossy());
    format!(
        "[Desktop Entry]\n\
         Type=Application\n\
         Name=mdo Setup\n\
         GenericName=Markdown Opener Setup\n\
         Comment=Set up mdo and open the first-run tour\n\
         Exec={quoted_exe}\n\
         Icon=utilities-terminal\n\
         Terminal=false\n\
         NoDisplay=false\n\
         Categories=Utility;TextTools;\n\
         StartupNotify=false\n"
    )
}

#[cfg(target_os = "linux")]
fn quote_desktop_exec_arg(value: &str) -> String {
    let mut quoted = String::with_capacity(value.len() + 2);
    quoted.push('"');
    for ch in value.chars() {
        match ch {
            '\\' | '"' | '$' | '`' => {
                quoted.push('\\');
                quoted.push(ch);
            }
            _ => quoted.push(ch),
        }
    }
    quoted.push('"');
    quoted
}

#[cfg(target_os = "linux")]
fn run_optional(program: &str, args: &[&std::ffi::OsStr]) {
    let _ = run_optional_status(program, args);
}

#[cfg(target_os = "linux")]
fn run_optional_status(program: &str, args: &[&std::ffi::OsStr]) -> bool {
    Command::new(program)
        .args(args)
        .status()
        .map(|status| status.success())
        .unwrap_or(false)
}

#[cfg(target_os = "linux")]
fn remove_legacy_nautilus_scripts(data_home: &Path) -> io::Result<()> {
    let nautilus_dir = data_home.join("nautilus").join("scripts");
    for name in ["Open as HTML", "Preview with mdo", "Render with mdo"] {
        remove_file_if_present(&nautilus_dir.join(name))?;
    }
    Ok(())
}

#[cfg(target_os = "linux")]
fn remove_file_if_present(path: &Path) -> io::Result<()> {
    match fs::remove_file(path) {
        Ok(()) => {
            println!("Removed: {}", path.display());
            Ok(())
        }
        Err(e) if e.kind() == io::ErrorKind::NotFound => {
            println!("Skip   : {} (not present)", path.display());
            Ok(())
        }
        Err(e) => Err(e),
    }
}

#[cfg(target_os = "linux")]
fn mimeapps_paths(data_home: &Path) -> Vec<PathBuf> {
    let mut paths = Vec::new();
    if let Some(config_home) = std::env::var_os("XDG_CONFIG_HOME") {
        paths.push(PathBuf::from(config_home).join("mimeapps.list"));
    } else if let Some(home) = std::env::var_os("HOME") {
        paths.push(PathBuf::from(home).join(".config").join("mimeapps.list"));
    }
    paths.push(data_home.join("applications").join("mimeapps.list"));
    paths
}

#[cfg(target_os = "linux")]
fn remove_desktop_from_mimeapps(path: &Path) -> io::Result<()> {
    let contents = match fs::read_to_string(path) {
        Ok(contents) => contents,
        Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(()),
        Err(e) => return Err(e),
    };

    let updated = strip_mdo_from_mimeapps(&contents);
    if updated != contents {
        fs::write(path, updated)?;
        println!("Updated: {}", path.display());
    }

    Ok(())
}

#[cfg(target_os = "linux")]
fn strip_mdo_from_mimeapps(contents: &str) -> String {
    let mut section = "";
    let mut out = Vec::new();

    for line in contents.lines() {
        match line {
            "[Default Applications]" => {
                section = "default";
                out.push(line.to_string());
                continue;
            }
            "[Added Associations]" => {
                section = "added";
                out.push(line.to_string());
                continue;
            }
            _ if line.starts_with('[') => {
                section = "";
                out.push(line.to_string());
                continue;
            }
            _ => {}
        }

        if section == "default"
            && (line == "text/markdown=mdo.desktop" || line == "text/x-markdown=mdo.desktop")
        {
            continue;
        }

        if section == "added"
            && (line.starts_with("text/markdown=") || line.starts_with("text/x-markdown="))
        {
            if let Some((mime, apps)) = line.split_once('=') {
                let apps = apps
                    .split(';')
                    .filter(|app| !app.is_empty() && *app != DESKTOP_FILE_NAME)
                    .collect::<Vec<_>>();
                if apps.is_empty() {
                    continue;
                }
                out.push(format!("{mime}={};", apps.join(";")));
                continue;
            }
        }

        out.push(line.to_string());
    }

    let mut result = out.join("\n");
    if contents.ends_with('\n') {
        result.push('\n');
    }
    result
}

#[cfg(target_os = "windows")]
struct WindowsHandler {
    path: PathBuf,
    is_wrapper: bool,
}

#[cfg(target_os = "windows")]
fn windows_handler_for(current_exe: &Path) -> WindowsHandler {
    let sibling_wrapper = handler::sibling_binary(current_exe, "mdo-open.exe").ok();
    match sibling_wrapper {
        Some(path) => WindowsHandler {
            path,
            is_wrapper: true,
        },
        None => WindowsHandler {
            path: current_exe.to_path_buf(),
            is_wrapper: false,
        },
    }
}

#[cfg(target_os = "windows")]
fn windows_registry_command(handler_path: &Path, is_wrapper: bool) -> String {
    if is_wrapper {
        format!("\"{}\" \"%1\"", handler_path.display())
    } else {
        // The registry command is the handler invocation contract in
        // registry spelling: the binary, the contract flags, then the %1
        // file placeholder.
        format!(
            "\"{}\" {} \"%1\"",
            handler_path.display(),
            handler::OPEN_FLAGS.join(" ")
        )
    }
}

/// A single registry write/delete, described data-first so installation
/// logic can be composed and unit-tested without shelling out to `reg.exe`.
///
/// `best_effort` mirrors the original inline `let _ = reg_delete_key(...)`
/// pattern: some ops (e.g. clearing legacy verbs that may not exist) should
/// not abort the rest of the plan if they fail.
#[cfg(target_os = "windows")]
#[derive(Debug, Clone, PartialEq, Eq)]
struct RegistryOp {
    action: RegistryAction,
    best_effort: bool,
}

#[cfg(target_os = "windows")]
#[derive(Debug, Clone, PartialEq, Eq)]
enum RegistryAction {
    SetDefault {
        key: String,
        value: String,
    },
    SetValue {
        key: String,
        name: String,
        value: String,
    },
    DeleteKey {
        key: String,
    },
    DeleteValue {
        key: String,
        name: String,
    },
}

#[cfg(target_os = "windows")]
impl RegistryOp {
    fn required(action: RegistryAction) -> Self {
        Self {
            action,
            best_effort: false,
        }
    }

    fn best_effort(action: RegistryAction) -> Self {
        Self {
            action,
            best_effort: true,
        }
    }
}

/// Registry ops that register `exe_name` as an "Applications" handler for
/// Open With, mirroring the shape `register_windows_application` used to
/// write directly. Pure: takes already-computed strings and returns a plan.
#[cfg(target_os = "windows")]
fn application_registration_ops(exe_name: &str, command: &str, icon_ref: &str) -> Vec<RegistryOp> {
    let key = format!(r"HKCU\Software\Classes\Applications\{exe_name}");

    vec![
        RegistryOp::required(RegistryAction::SetValue {
            key: key.clone(),
            name: "FriendlyAppName".to_string(),
            value: APP_DISPLAY_NAME.to_string(),
        }),
        RegistryOp::required(RegistryAction::SetValue {
            key: key.clone(),
            name: "ApplicationName".to_string(),
            value: APP_DISPLAY_NAME.to_string(),
        }),
        RegistryOp::required(RegistryAction::SetDefault {
            key: format!(r"{key}\DefaultIcon"),
            value: icon_ref.to_string(),
        }),
        RegistryOp::required(RegistryAction::SetDefault {
            key: format!(r"{key}\shell\open\command"),
            value: command.to_string(),
        }),
        RegistryOp::required(RegistryAction::SetValue {
            key: format!(r"{key}\SupportedTypes"),
            name: ".md".to_string(),
            value: String::new(),
        }),
    ]
}

/// Pure planning step for the install executor below: given the already
/// pure-computed handler command, current-exe command, and icon reference,
/// produce the ordered list of registry writes install would perform.
/// Unit-tested directly (see `windows_tests`) so the composition — which
/// keys, which values, wrapper-vs-direct branching, best-effort cleanup of
/// legacy verbs — is covered without mutating the real registry.
#[cfg(target_os = "windows")]
fn install_windows_plan(
    is_wrapper: bool,
    command: &str,
    current_exe_command: &str,
    icon_ref: &str,
) -> Vec<RegistryOp> {
    let mut ops = application_registration_ops("mdo.exe", current_exe_command, icon_ref);
    if is_wrapper {
        ops.extend(application_registration_ops(
            "mdo-open.exe",
            command,
            icon_ref,
        ));
    }

    ops.push(RegistryOp::required(RegistryAction::SetValue {
        key: r"HKCU\Software\Classes\.md\OpenWithProgids".to_string(),
        name: "mdo.md".to_string(),
        value: String::new(),
    }));

    ops.push(RegistryOp::required(RegistryAction::SetDefault {
        key: r"HKCU\Software\Classes\mdo.md".to_string(),
        value: "Markdown document (Open as HTML)".to_string(),
    }));
    ops.push(RegistryOp::required(RegistryAction::SetDefault {
        key: WINDOWS_OWNED_PROGID_COMMAND_KEY.to_string(),
        value: command.to_string(),
    }));
    ops.push(RegistryOp::required(RegistryAction::SetDefault {
        key: r"HKCU\Software\Classes\mdo.md\DefaultIcon".to_string(),
        value: icon_ref.to_string(),
    }));

    for old_verb in [
        r"HKCU\Software\Classes\SystemFileAssociations\.md\shell\Preview with mdo",
        r"HKCU\Software\Classes\SystemFileAssociations\.md\shell\Render with mdo",
    ] {
        ops.push(RegistryOp::best_effort(RegistryAction::DeleteKey {
            key: old_verb.to_string(),
        }));
    }

    let verb = r"HKCU\Software\Classes\SystemFileAssociations\.md\shell\Open as HTML";
    ops.push(RegistryOp::required(RegistryAction::SetDefault {
        key: verb.to_string(),
        value: APP_DISPLAY_NAME.to_string(),
    }));
    ops.push(RegistryOp::required(RegistryAction::SetDefault {
        key: format!(r"{verb}\command"),
        value: command.to_string(),
    }));
    ops.push(RegistryOp::required(RegistryAction::SetValue {
        key: verb.to_string(),
        name: "Icon".to_string(),
        value: icon_ref.to_string(),
    }));

    ops
}

/// Pure planning step for [`uninstall`]: every op here is best-effort,
/// matching the original `let _ = reg_delete_*(...)` calls — uninstall
/// should remove everything it can rather than stop at the first missing
/// key.
#[cfg(target_os = "windows")]
fn uninstall_windows_plan() -> Vec<RegistryOp> {
    let mut ops = Vec::new();

    for key in [
        r"HKCU\Software\Classes\Applications\mdo.exe",
        r"HKCU\Software\Classes\Applications\mdo-open.exe",
        r"HKCU\Software\Classes\mdo.md",
        r"HKCU\Software\Classes\SystemFileAssociations\.md\shell\Open as HTML",
        r"HKCU\Software\Classes\SystemFileAssociations\.md\shell\Preview with mdo",
        r"HKCU\Software\Classes\SystemFileAssociations\.md\shell\Render with mdo",
        r"HKCU\Software\Classes\Applications\md2htmlx.exe",
        r"HKCU\Software\Classes\md2htmlx.md",
        r"HKCU\Software\Classes\SystemFileAssociations\.md\shell\Render with md2htmlx",
    ] {
        ops.push(RegistryOp::best_effort(RegistryAction::DeleteKey {
            key: key.to_string(),
        }));
    }

    ops.push(RegistryOp::best_effort(RegistryAction::DeleteValue {
        key: r"HKCU\Software\Classes\.md\OpenWithProgids".to_string(),
        name: "mdo.md".to_string(),
    }));
    ops.push(RegistryOp::best_effort(RegistryAction::DeleteValue {
        key: r"HKCU\Software\Classes\.md\OpenWithProgids".to_string(),
        name: "md2htmlx.md".to_string(),
    }));

    ops
}

/// The only impure step of the install/uninstall registry seam: apply an
/// already-built plan by shelling out to `reg.exe` for each op, propagating
/// the first failure among the `required` ops and swallowing failures on
/// `best_effort` ops (mirroring the original `let _ = ...` cleanup calls).
#[cfg(target_os = "windows")]
fn apply_registry_plan(ops: &[RegistryOp]) -> io::Result<()> {
    for op in ops {
        let result = apply_registry_action(&op.action);
        if !op.best_effort {
            result?;
        }
    }
    Ok(())
}

#[cfg(target_os = "windows")]
fn apply_registry_action(action: &RegistryAction) -> io::Result<()> {
    match action {
        RegistryAction::SetDefault { key, value } => reg_add_default(key, value),
        RegistryAction::SetValue { key, name, value } => reg_add_value(key, name, value),
        RegistryAction::DeleteKey { key } => reg_delete_key(key),
        RegistryAction::DeleteValue { key, name } => reg_delete_value(key, name),
    }
}

#[cfg(target_os = "windows")]
fn install_windows_icon() -> io::Result<PathBuf> {
    let icon_file = windows_icon_file()?;
    if let Some(parent) = icon_file.parent() {
        fs::create_dir_all(parent)?;
    }
    fs::write(&icon_file, WINDOWS_ICON_BYTES)?;
    Ok(icon_file)
}

#[cfg(target_os = "windows")]
fn remove_windows_icon() -> io::Result<()> {
    let icon_file = match windows_icon_file() {
        Ok(path) => path,
        Err(_) => return Ok(()),
    };

    match fs::remove_file(&icon_file) {
        Ok(()) => {}
        Err(e) if e.kind() == io::ErrorKind::NotFound => {}
        Err(e) => return Err(e),
    }

    if let Some(parent) = icon_file.parent() {
        match fs::remove_dir(parent) {
            Ok(()) => {}
            Err(e)
                if matches!(
                    e.kind(),
                    io::ErrorKind::NotFound | io::ErrorKind::DirectoryNotEmpty
                ) => {}
            Err(e) => return Err(e),
        }
    }

    Ok(())
}

#[cfg(target_os = "windows")]
fn windows_icon_file() -> io::Result<PathBuf> {
    let base = std::env::var_os("LOCALAPPDATA")
        .or_else(|| std::env::var_os("APPDATA"))
        .ok_or_else(|| {
            io::Error::new(
                io::ErrorKind::NotFound,
                "LOCALAPPDATA and APPDATA are not set; cannot install icon",
            )
        })?;

    Ok(PathBuf::from(base).join("mdo").join("mdo.ico"))
}

#[cfg(target_os = "windows")]
fn reg_add_default(key: &str, value: &str) -> io::Result<()> {
    reg_status(
        Command::new("reg").args(["add", key, "/ve", "/d", value, "/f"]),
        "reg add",
    )
}

#[cfg(target_os = "windows")]
fn reg_add_value(key: &str, name: &str, value: &str) -> io::Result<()> {
    reg_status(
        Command::new("reg").args(["add", key, "/v", name, "/t", "REG_SZ", "/d", value, "/f"]),
        "reg add",
    )
}

#[cfg(target_os = "windows")]
fn reg_delete_key(key: &str) -> io::Result<()> {
    reg_status(
        Command::new("reg").args(["delete", key, "/f"]),
        "reg delete",
    )
}

#[cfg(target_os = "windows")]
fn reg_delete_value(key: &str, name: &str) -> io::Result<()> {
    reg_status(
        Command::new("reg").args(["delete", key, "/v", name, "/f"]),
        "reg delete",
    )
}

#[cfg(target_os = "windows")]
fn reg_status(command: &mut Command, action: &str) -> io::Result<()> {
    let output = command
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .output()?;
    if output.status.success() {
        Ok(())
    } else {
        let stderr = String::from_utf8_lossy(&output.stderr);
        let stdout = String::from_utf8_lossy(&output.stdout);
        let details = stderr.trim();
        let details = if details.is_empty() {
            stdout.trim()
        } else {
            details
        };

        let suffix = if details.is_empty() {
            String::new()
        } else {
            format!(": {details}")
        };

        Err(io::Error::other(format!(
            "{action} failed with status {}{suffix}",
            output.status
        )))
    }
}

#[cfg(all(test, target_os = "linux"))]
mod linux_tests {
    use super::*;

    #[test]
    fn desktop_exec_arg_escapes_special_chars() {
        assert_eq!(
            quote_desktop_exec_arg(r#"/tmp/a\b"c$d`e/mdo"#),
            r#""/tmp/a\\b\"c\$d\`e/mdo""#
        );
    }

    #[test]
    fn linux_install_plan_derives_standard_paths_and_entry_content() {
        let data_home = Path::new("/home/u/.local/share");
        let exe = Path::new("/opt/my tools/mdo");

        let plan = linux_install_plan(data_home, exe, true);
        assert_eq!(
            plan.desktop_file,
            data_home.join("applications").join(DESKTOP_FILE_NAME)
        );
        assert_eq!(
            plan.icon_file,
            data_home
                .join("icons")
                .join("hicolor")
                .join("scalable")
                .join("apps")
                .join("mdo.svg")
        );
        // The entry content carries the handler invocation contract with the
        // quoting rules applied (same emitted form the integration registers).
        assert!(plan
            .desktop_entry
            .contains("Exec=\"/opt/my tools/mdo\" --open %f\n"));
        assert!(plan.set_default);
        assert_eq!(plan.default_mimes, &["text/markdown", "text/x-markdown"]);
        assert_eq!(plan.legacy_cleanup_root, Some(data_home.to_path_buf()));

        let plan_without_default = linux_install_plan(data_home, exe, false);
        assert!(!plan_without_default.set_default);
    }

    #[test]
    fn apply_linux_install_plan_writes_entry_and_icon_and_reports() {
        let dir = std::env::temp_dir().join(format!(
            "mdo-install-plan-test-{}-{:?}",
            std::process::id(),
            std::thread::current().id()
        ));
        let exe = dir.join("mdo");
        fs::create_dir_all(&dir).unwrap();

        let mut plan = linux_install_plan(&dir, &exe, false);
        // No legacy scripts exist in this fixture; the cleanup would be a
        // no-op either way (it only removes known files if present).
        plan.legacy_cleanup_root = None;

        let report = apply_linux_install_plan(&plan).expect("apply should write the registration");
        assert_eq!(
            report.default,
            LinuxDefaultOutcome::NotRequested,
            "no default was requested"
        );

        let entry = fs::read_to_string(&report.desktop_file).expect("entry written");
        assert!(entry.contains("[Desktop Entry]\n"));
        // The entry content carries the handler invocation contract with the
        // quoting rules applied (exe path comes from this fixture's anchor).
        assert!(
            entry.contains(&format!("Exec=\"{}\" --open %f\n", exe.display())),
            "entry should carry the contract Exec line: {entry}"
        );
        let icon = fs::read_to_string(&report.icon_file).expect("icon written");
        assert!(icon.contains("<svg"));

        use std::os::unix::fs::PermissionsExt;
        let mode = fs::metadata(&report.desktop_file)
            .expect("entry metadata")
            .permissions()
            .mode();
        assert_eq!(mode & 0o777, 0o644, "the entry must stay mode 0644");

        fs::remove_dir_all(dir).unwrap();
    }

    #[test]
    fn apply_linux_install_plan_requested_default_without_mimes_needs_manual_hint() {
        // set_default=true with an empty mime list cannot spawn xdg-mime at
        // all, so the branch is deterministic: the executor must not assume
        // success just because defaulting was requested.
        let dir = std::env::temp_dir().join(format!(
            "mdo-install-plan-hint-test-{}-{:?}",
            std::process::id(),
            std::thread::current().id()
        ));
        let exe = dir.join("mdo");
        fs::create_dir_all(&dir).unwrap();

        let mut plan = linux_install_plan(&dir, &exe, true);
        plan.default_mimes = &[];
        plan.legacy_cleanup_root = None;

        let report = apply_linux_install_plan(&plan).expect("apply should complete");
        assert_eq!(report.default, LinuxDefaultOutcome::NeedsManualHint);

        fs::remove_dir_all(dir).unwrap();
    }

    #[test]
    fn setup_launcher_is_visible_and_not_a_file_handler() {
        let entry = linux_setup_desktop_entry(Path::new(r#"/opt/mdo tools/a\b"c$d`e/mdo-setup"#));

        assert!(entry.contains("Name=mdo Setup\n"));
        assert!(entry.contains(r#"Exec="/opt/mdo tools/a\\b\"c\$d\`e/mdo-setup""#));
        assert!(entry.contains("Terminal=false\n"));
        assert!(entry.contains("NoDisplay=false\n"));
        assert!(!entry.contains("MimeType="));
        assert!(!entry.contains("%f"));
    }

    #[test]
    fn setup_launcher_has_separate_handler_ownership() {
        assert_ne!(SETUP_DESKTOP_FILE_NAME, DESKTOP_FILE_NAME);
        let entry = linux_setup_desktop_entry(Path::new("/usr/bin/mdo-setup"));
        assert!(!entry.contains("Icon=mdo\n"));
    }

    #[test]
    fn handler_uninstall_preserves_setup_launcher() {
        let data_home = std::env::temp_dir().join(format!(
            "mdo-setup-launcher-test-{}-{:?}",
            std::process::id(),
            std::thread::current().id()
        ));
        let applications = data_home.join("applications");
        fs::create_dir_all(&applications).unwrap();
        fs::write(applications.join(DESKTOP_FILE_NAME), "handler").unwrap();

        let setup_file =
            write_linux_setup_launcher(Path::new("/opt/mdo/bin/mdo-setup"), &data_home).unwrap();
        // Registration is idempotent and rewrites stale content.
        fs::write(&setup_file, "stale").unwrap();
        write_linux_setup_launcher(Path::new("/opt/mdo/bin/mdo-setup"), &data_home).unwrap();

        remove_linux_handler_files(&data_home).unwrap();

        assert!(!applications.join(DESKTOP_FILE_NAME).exists());
        assert!(setup_file.exists());
        assert!(fs::read_to_string(&setup_file)
            .unwrap()
            .contains("Exec=\"/opt/mdo/bin/mdo-setup\"\n"));
        fs::remove_dir_all(data_home).unwrap();
    }

    #[test]
    fn owned_state_check_tracks_only_the_handler_desktop_file() {
        let data_home = std::env::temp_dir().join(format!(
            "mdo-owned-state-test-{}-{:?}",
            std::process::id(),
            std::thread::current().id()
        ));

        // Nothing installed yet: not detected.
        assert!(!linux_integration_installed_at(&data_home));

        // The visible setup launcher alone is not handler integration.
        write_linux_setup_launcher(Path::new("/usr/bin/mdo-setup"), &data_home).unwrap();
        assert!(!linux_integration_installed_at(&data_home));

        let applications = data_home.join("applications");
        fs::write(applications.join(DESKTOP_FILE_NAME), "handler").unwrap();
        assert!(linux_integration_installed_at(&data_home));

        // Uninstall removes exactly what the check observes.
        remove_linux_handler_files(&data_home).unwrap();
        assert!(!linux_integration_installed_at(&data_home));

        fs::remove_dir_all(data_home).unwrap();
    }

    #[test]
    fn mimeapps_uninstall_removes_only_mdo_entries() {
        let input = "\
[Default Applications]\n\
text/markdown=mdo.desktop\n\
text/plain=code.desktop\n\
[Added Associations]\n\
text/markdown=code.desktop;mdo.desktop;other.desktop;\n\
text/x-markdown=mdo.desktop;\n\
image/png=viewer.desktop;\n";

        let output = strip_mdo_from_mimeapps(input);

        assert_eq!(
            output,
            "\
[Default Applications]\n\
text/plain=code.desktop\n\
[Added Associations]\n\
text/markdown=code.desktop;other.desktop;\n\
image/png=viewer.desktop;\n"
        );
    }

    /// The desktop Exec line is one of the two emitted forms of the handler
    /// invocation contract (the other is the Windows registry command): the
    /// same binary and the same contract flags, derived from the contract
    /// rather than restated as a literal so the two cannot drift apart.
    #[test]
    fn desktop_entry_reflects_the_handler_invocation_contract() {
        let entry = linux_desktop_entry(Path::new("/opt/mdo/mdo"));
        let expected = format!(
            "Exec=\"/opt/mdo/mdo\" {} %f\n",
            handler::OPEN_FLAGS.join(" ")
        );
        assert!(
            entry.contains(&expected),
            "entry should carry the contract Exec line: {entry}"
        );

        // The setup launcher entry is not open-mode: no contract flags.
        let setup_entry = linux_setup_desktop_entry(Path::new("/usr/bin/mdo-setup"));
        assert!(!setup_entry.contains(handler::OPEN_FLAGS[0]));
    }
}

#[cfg(all(test, target_os = "windows"))]
mod windows_tests {
    use super::*;

    /// The registry command is one of the two emitted forms of the handler
    /// invocation contract (the other is the Linux desktop Exec line): it
    /// must carry the same binary and the same contract flags, derived here
    /// rather than restated as a literal so the two cannot drift apart.
    #[test]
    fn registry_command_reflects_the_handler_invocation_contract() {
        let command = windows_registry_command(Path::new(r"C:\Tools\mdo.exe"), false);
        let expected = format!(
            r#""C:\Tools\mdo.exe" {} "%1""#,
            handler::OPEN_FLAGS.join(" ")
        );
        assert_eq!(command, expected);

        // The forwarding wrapper carries NO flags: it owns the contract
        // itself and forwards the file as received.
        let wrapper = windows_registry_command(Path::new(r"C:\Tools\mdo-open.exe"), true);
        assert_eq!(wrapper, r#""C:\Tools\mdo-open.exe" "%1""#);
        assert!(!wrapper.contains(handler::OPEN_FLAGS[0]));
    }

    #[test]
    fn registry_command_uses_open_flag_without_wrapper() {
        let command = windows_registry_command(Path::new(r"C:\Tools\mdo.exe"), false);
        assert_eq!(command, r#""C:\Tools\mdo.exe" --open "%1""#);
    }

    #[test]
    fn registry_command_omits_open_flag_for_wrapper() {
        let command = windows_registry_command(Path::new(r"C:\Tools\mdo-open.exe"), true);
        assert_eq!(command, r#""C:\Tools\mdo-open.exe" "%1""#);
    }

    // The exe path is only ever wrapped in quotes, never parsed or
    // re-escaped, so spaces and cmd.exe metacharacters (& ^ ( ) ...), which
    // are all legal in Windows filenames, must survive unmodified inside the
    // quoted segment. Quoting (rather than sanitizing) is what neutralizes
    // them for the shell that later reads the registry value.
    #[test]
    fn registry_command_preserves_spaces_in_exe_path() {
        let command =
            windows_registry_command(Path::new(r"C:\Program Files\mdo tools\mdo.exe"), false);
        assert_eq!(
            command,
            r#""C:\Program Files\mdo tools\mdo.exe" --open "%1""#
        );
    }

    #[test]
    fn registry_command_preserves_cmd_metacharacters_in_exe_path() {
        let command =
            windows_registry_command(Path::new(r"C:\Program Files (x86)\mdo & co^\mdo.exe"), true);
        assert_eq!(
            command,
            r#""C:\Program Files (x86)\mdo & co^\mdo.exe" "%1""#
        );
    }

    #[test]
    fn install_plan_registers_wrapper_and_direct_targets_when_wrapper_present() {
        let handler_command =
            windows_registry_command(Path::new(r"C:\Program Files\mdo & co\mdo-open.exe"), true);
        let current_exe_command =
            windows_registry_command(Path::new(r"C:\Program Files\mdo & co\mdo.exe"), false);
        let icon_ref = r#""C:\Users\me\AppData\Local\mdo\mdo.ico",0"#;

        let plan = install_windows_plan(true, &handler_command, &current_exe_command, icon_ref);

        // mdo.exe is always registered as an Applications handler using the
        // *direct* (--open) command, even when a wrapper exists, because
        // some surfaces (e.g. "Open With" listing before mdo-open exists)
        // may still reference mdo.exe directly.
        assert!(
            plan.contains(&RegistryOp::required(RegistryAction::SetDefault {
                key: r"HKCU\Software\Classes\Applications\mdo.exe\shell\open\command".to_string(),
                value: current_exe_command.clone(),
            }))
        );

        // The wrapper is also registered as its own Applications handler,
        // using the wrapper (no --open) command.
        assert!(
            plan.contains(&RegistryOp::required(RegistryAction::SetDefault {
                key: r"HKCU\Software\Classes\Applications\mdo-open.exe\shell\open\command"
                    .to_string(),
                value: handler_command.clone(),
            }))
        );

        // The .md ProgID's own open command must point at the *handler*
        // command (wrapper, if present) so double-click uses it.
        assert!(
            plan.contains(&RegistryOp::required(RegistryAction::SetDefault {
                key: r"HKCU\Software\Classes\mdo.md\shell\open\command".to_string(),
                value: handler_command.clone(),
            }))
        );

        // Legacy verb cleanup must be best-effort so a first-time install
        // (where those keys never existed) does not fail the whole plan.
        assert!(
            plan.contains(&RegistryOp::best_effort(RegistryAction::DeleteKey {
                key: r"HKCU\Software\Classes\SystemFileAssociations\.md\shell\Preview with mdo"
                    .to_string(),
            }))
        );
        assert!(
            plan.contains(&RegistryOp::best_effort(RegistryAction::DeleteKey {
                key: r"HKCU\Software\Classes\SystemFileAssociations\.md\shell\Render with mdo"
                    .to_string(),
            }))
        );

        // Every op besides the two legacy-verb deletes must be required
        // (install should fail loudly on a real registry error).
        let best_effort_count = plan.iter().filter(|op| op.best_effort).count();
        assert_eq!(best_effort_count, 2);
    }

    #[test]
    fn install_plan_skips_wrapper_registration_without_wrapper() {
        let command = windows_registry_command(Path::new(r"C:\Tools\mdo.exe"), false);
        let icon_ref = r#""C:\Tools\mdo.ico",0"#;

        let plan = install_windows_plan(false, &command, &command, icon_ref);

        assert!(!plan.iter().any(|op| matches!(
            &op.action,
            RegistryAction::SetDefault { key, .. } | RegistryAction::SetValue { key, .. }
                if key.contains("mdo-open.exe")
        )));
    }

    // The owned-state check must observe exactly the registration mdo owns:
    // install writes the queried key, and uninstall deletes an ancestor of it,
    // so "key present" can only mean "mdo's own install left it behind".
    #[test]
    fn owned_state_check_queries_a_key_install_writes_and_uninstall_removes() {
        let command = windows_registry_command(Path::new(r"C:\Tools\mdo.exe"), false);
        let plan = install_windows_plan(false, &command, &command, r#""C:\Tools\mdo.ico",0"#);

        assert!(
            plan.contains(&RegistryOp::required(RegistryAction::SetDefault {
                key: WINDOWS_OWNED_PROGID_COMMAND_KEY.to_string(),
                value: command.clone(),
            }))
        );

        assert!(uninstall_windows_plan().iter().any(|op| matches!(
            &op.action,
            RegistryAction::DeleteKey { key }
                if key.as_str() == WINDOWS_OWNED_PROGID_COMMAND_KEY
                    || WINDOWS_OWNED_PROGID_COMMAND_KEY.starts_with(&format!(r"{key}\"))
        )));
    }

    #[test]
    fn uninstall_plan_is_entirely_best_effort() {
        let plan = uninstall_windows_plan();

        assert!(!plan.is_empty());
        assert!(plan.iter().all(|op| op.best_effort));

        // Legacy md2htmlx keys (an earlier project name) must still be
        // cleaned up so upgrading users do not keep a stale handler.
        assert!(
            plan.contains(&RegistryOp::best_effort(RegistryAction::DeleteKey {
                key: r"HKCU\Software\Classes\Applications\md2htmlx.exe".to_string(),
            }))
        );
        assert!(
            plan.contains(&RegistryOp::best_effort(RegistryAction::DeleteValue {
                key: r"HKCU\Software\Classes\.md\OpenWithProgids".to_string(),
                name: "md2htmlx.md".to_string(),
            }))
        );
    }
}