Skip to main content

mdo_cli/
file_manager.rs

1use std::io;
2use std::path::{Path, PathBuf};
3use std::process::Command;
4#[cfg(target_os = "windows")]
5use std::process::Stdio;
6
7use crate::handler;
8
9const APP_DISPLAY_NAME: &str = "Open as HTML";
10#[cfg(target_os = "linux")]
11const DESKTOP_FILE_NAME: &str = "mdo.desktop";
12#[cfg(target_os = "linux")]
13const SETUP_DESKTOP_FILE_NAME: &str = "mdo-setup.desktop";
14#[cfg(target_os = "windows")]
15const WINDOWS_ICON_BYTES: &[u8] = include_bytes!("../assets/mdo.ico");
16#[cfg(target_os = "linux")]
17const SVG_ICON: &str = r##"<svg xmlns="http://www.w3.org/2000/svg" width="256" height="256" viewBox="0 0 256 256">
18  <rect width="256" height="256" rx="48" fill="#f7f7f7"/>
19  <text x="128" y="151"
20        text-anchor="middle"
21        dominant-baseline="middle"
22        font-family="Segoe UI Symbol, Noto Sans Symbols 2, Noto Sans Symbols, DejaVu Sans, sans-serif"
23        font-size="176"
24        font-weight="700"
25        fill="#1e66e2">Ⓜ</text>
26</svg>
27"##;
28
29#[cfg(any(target_os = "linux", target_os = "windows"))]
30use std::fs;
31
32/// Register the file-manager integration for this user. On Linux this
33/// writes the hidden `mdo.desktop` entry and its icon through a pure
34/// planning step and a thin executor; on Windows it shells out to
35/// `reg.exe` (see [`install_windows_plan`] for the registry shape).
36/// Windows ignores `set_default`: choosing a default app lives in
37/// Explorer's Open with dialog, not in the registration.
38#[cfg(target_os = "linux")]
39pub fn install(set_default: bool) -> io::Result<()> {
40    let exe = std::env::current_exe()?;
41    let data_home = xdg_data_home()?;
42
43    let plan = linux_install_plan(&data_home, &exe, set_default);
44    let report = apply_linux_install_plan(&plan)?;
45    print_linux_install_report(&report);
46    Ok(())
47}
48
49/// Data-first description of a Linux integration install: everything the
50/// executor touches, decided without disk or environment access so the
51/// planning step stays a pure function (unit-tested without spawn-capture),
52/// mirroring the registry's [`install_windows_plan`].
53#[cfg(target_os = "linux")]
54#[derive(Clone, Debug, PartialEq, Eq)]
55struct LinuxInstallPlan {
56    /// The hidden `mdo.desktop` handler entry and where it goes.
57    desktop_file: PathBuf,
58    /// The entry's content, handler-invocation contract spelling included.
59    desktop_entry: String,
60    /// The hicolor icon file and where it goes.
61    icon_file: PathBuf,
62    /// Whether xdg-mime should try to register mdo as the default handler
63    /// for the mimes in [`LinuxInstallPlan::default_mimes`].
64    set_default: bool,
65    /// The mimes to register, in order, exactly as the original inline flow
66    /// did.
67    default_mimes: &'static [&'static str],
68    /// The data root the legacy nautilus script cleanup runs against.
69    legacy_cleanup_root: Option<PathBuf>,
70}
71
72/// What the Linux install executor changed, for the caller to print. File
73/// entries are paths; the default outcome is the one piece of xdg-mime's
74/// best-effort behavior a human needs to see.
75#[cfg(target_os = "linux")]
76#[derive(Clone, Debug, PartialEq, Eq)]
77struct LinuxInstallReport {
78    desktop_file: PathBuf,
79    icon_file: PathBuf,
80    default: LinuxDefaultOutcome,
81}
82
83#[cfg(target_os = "linux")]
84#[derive(Clone, Copy, Debug, PartialEq, Eq)]
85enum LinuxDefaultOutcome {
86    /// xdg-mime registered mdo for at least one of the mimes.
87    Applied,
88    /// Defaulting was requested but xdg-mime could not comply (tool
89    /// missing or non-zero exit): the manual hint applies.
90    NeedsManualHint,
91    /// Defaulting was not requested: integration stays Open With-only.
92    NotRequested,
93}
94
95#[cfg(target_os = "linux")]
96fn linux_install_plan(data_home: &Path, current_exe: &Path, set_default: bool) -> LinuxInstallPlan {
97    LinuxInstallPlan {
98        desktop_file: data_home.join("applications").join(DESKTOP_FILE_NAME),
99        desktop_entry: linux_desktop_entry(current_exe),
100        icon_file: data_home
101            .join("icons")
102            .join("hicolor")
103            .join("scalable")
104            .join("apps")
105            .join("mdo.svg"),
106        set_default,
107        default_mimes: &["text/markdown", "text/x-markdown"],
108        legacy_cleanup_root: Some(data_home.to_path_buf()),
109    }
110}
111
112/// Apply the plan in the original write order: directories, icon, entry
113/// (mode 0644), best-effort desktop-database refresh, the optional default
114/// registration, and the legacy cleanup. A scalable SVG under
115/// hicolor/scalable/apps is resolved by name, so it needs no icon-cache
116/// refresh; gtk-update-icon-cache on a user theme dir without an
117/// index.theme just fails — skip it.
118#[cfg(target_os = "linux")]
119fn apply_linux_install_plan(plan: &LinuxInstallPlan) -> io::Result<LinuxInstallReport> {
120    if let Some(applications) = plan.desktop_file.parent() {
121        fs::create_dir_all(applications)?;
122    }
123    if let Some(icon_dir) = plan.icon_file.parent() {
124        fs::create_dir_all(icon_dir)?;
125    }
126    fs::write(&plan.icon_file, SVG_ICON)?;
127    fs::write(&plan.desktop_file, &plan.desktop_entry)?;
128
129    #[cfg(unix)]
130    {
131        use std::os::unix::fs::PermissionsExt;
132        fs::set_permissions(&plan.desktop_file, fs::Permissions::from_mode(0o644))?;
133    }
134
135    if let Some(applications) = plan.desktop_file.parent() {
136        run_optional("update-desktop-database", &[applications.as_os_str()]);
137    }
138
139    let default = if plan.set_default {
140        let mut ok = false;
141        for mime in plan.default_mimes {
142            ok |= run_optional_status(
143                "xdg-mime",
144                &[
145                    std::ffi::OsStr::new("default"),
146                    std::ffi::OsStr::new(DESKTOP_FILE_NAME),
147                    std::ffi::OsStr::new(*mime),
148                ],
149            );
150        }
151        if ok {
152            LinuxDefaultOutcome::Applied
153        } else {
154            LinuxDefaultOutcome::NeedsManualHint
155        }
156    } else {
157        LinuxDefaultOutcome::NotRequested
158    };
159
160    if let Some(root) = &plan.legacy_cleanup_root {
161        remove_legacy_nautilus_scripts(root)?;
162    }
163
164    Ok(LinuxInstallReport {
165        desktop_file: plan.desktop_file.clone(),
166        icon_file: plan.icon_file.clone(),
167        default,
168    })
169}
170
171/// Print the executor's report. This is the Linux install's whole CLI
172/// surface; the exact lines mirror the pre-plan flow byte for byte.
173#[cfg(target_os = "linux")]
174fn print_linux_install_report(report: &LinuxInstallReport) {
175    println!("Installed desktop entry: {}", report.desktop_file.display());
176    println!("Installed icon: {}", report.icon_file.display());
177    match report.default {
178        LinuxDefaultOutcome::Applied => {
179            println!("{APP_DISPLAY_NAME} is now the default Markdown handler.");
180        }
181        LinuxDefaultOutcome::NeedsManualHint => {
182            println!(
183                "Could not set {APP_DISPLAY_NAME} as the default automatically (is xdg-mime installed?)."
184            );
185            println!("To set it manually, run: xdg-mime default {DESKTOP_FILE_NAME} text/markdown");
186            println!("(and the same for text/x-markdown)");
187        }
188        LinuxDefaultOutcome::NotRequested => {
189            println!(
190                "{APP_DISPLAY_NAME} is available from Open With without changing your default Markdown handler."
191            );
192        }
193    }
194}
195
196/// Windows registration: resolve the handler beside the running exe, write
197/// the icon, then apply the registry plan (planning and its tests are
198/// pure; the executor is the only registry-touching step).
199#[cfg(target_os = "windows")]
200pub fn install(_set_default: bool) -> io::Result<()> {
201    let current_exe = std::env::current_exe()?;
202    let handler_selection = windows_handler_for(&current_exe);
203    let command = windows_registry_command(&handler_selection.path, handler_selection.is_wrapper);
204    let icon_file = install_windows_icon()?;
205    let icon_ref = format!("\"{}\",0", icon_file.display());
206    let current_exe_command = windows_registry_command(&current_exe, false);
207
208    // Registry mutation is split into a pure planning step (`install_windows_plan`,
209    // unit-tested below without touching the registry) and a thin executor
210    // (`apply_registry_plan`) that shells out to `reg.exe`. This keeps the
211    // "which keys/values would be written, in what order, with which
212    // failure semantics" logic testable in CI without mutating the real
213    // registry on the CI machine.
214    let plan = install_windows_plan(
215        handler_selection.is_wrapper,
216        &command,
217        &current_exe_command,
218        &icon_ref,
219    );
220    apply_registry_plan(&plan)?;
221
222    println!("Using handler: {}", handler_selection.path.display());
223    println!("Using icon: {}", icon_file.display());
224    if !handler_selection.is_wrapper {
225        println!(
226            "Note: mdo-open.exe was not found next to mdo.exe, so Explorer will launch mdo.exe directly."
227        );
228    }
229    println!("{APP_DISPLAY_NAME} is registered for Markdown files.");
230    println!("To make it the default, use Open with -> Choose another app -> {APP_DISPLAY_NAME} -> Always.");
231
232    Ok(())
233}
234
235#[cfg(not(any(target_os = "linux", target_os = "windows")))]
236pub fn install(_set_default: bool) -> io::Result<()> {
237    Err(io::Error::new(
238        io::ErrorKind::Unsupported,
239        "built-in file-manager installation is currently supported on Windows and Linux",
240    ))
241}
242
243#[cfg(target_os = "linux")]
244pub fn uninstall() -> io::Result<()> {
245    let data_home = xdg_data_home()?;
246    let desktop_dir = data_home.join("applications");
247    remove_linux_handler_files(&data_home)?;
248
249    for mimeapps in mimeapps_paths(&data_home) {
250        remove_desktop_from_mimeapps(&mimeapps)?;
251    }
252
253    run_optional("update-desktop-database", &[desktop_dir.as_os_str()]);
254
255    println!("Done.");
256    Ok(())
257}
258
259#[cfg(target_os = "windows")]
260pub fn uninstall() -> io::Result<()> {
261    // Uninstall was already best-effort (every op ignores failures), so this
262    // reduces to applying the plan; `apply_registry_plan` returns `Ok(())`
263    // whenever every op in the plan is best-effort, which is always true here.
264    apply_registry_plan(&uninstall_windows_plan())?;
265    let _ = remove_windows_icon();
266
267    println!("Done.");
268    println!(
269        "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."
270    );
271    Ok(())
272}
273
274#[cfg(not(any(target_os = "linux", target_os = "windows")))]
275pub fn uninstall() -> io::Result<()> {
276    Err(io::Error::new(
277        io::ErrorKind::Unsupported,
278        "built-in file-manager uninstallation is currently supported on Windows and Linux",
279    ))
280}
281
282#[cfg(not(any(target_os = "linux", target_os = "windows")))]
283pub fn integration_installed() -> bool {
284    false
285}
286
287/// Report whether mdo's own handler registration is present for this user.
288///
289/// This is deliberately a cheap owned-state check (ADR 0004 defers the full
290/// integration-state manager): it only asks "did mdo's install step leave its
291/// own registration behind?" and never inspects handler health, partial or
292/// stale remnants, system-wide registrations, or the effective default app.
293/// A query failure reads as "not detected", so setup falls back to the
294/// ordinary first-time flow — which is safe because install is idempotent.
295#[cfg(target_os = "linux")]
296pub fn integration_installed() -> bool {
297    xdg_data_home()
298        .map(|data_home| linux_integration_installed_at(&data_home))
299        .unwrap_or(false)
300}
301
302#[cfg(target_os = "windows")]
303pub fn integration_installed() -> bool {
304    reg_key_exists(WINDOWS_OWNED_PROGID_COMMAND_KEY)
305}
306
307/// Install the application-menu entry for the native setup launcher.
308///
309/// This is deliberately separate from the install step above: the latter
310/// owns the hidden Markdown file-handler entry and may be uninstalled without
311/// making setup disappear from the application menu.
312#[cfg(target_os = "linux")]
313pub fn install_linux_setup_launcher_for_exe(setup_exe: &Path) -> io::Result<PathBuf> {
314    let data_home = xdg_data_home()?;
315    let desktop_file = write_linux_setup_launcher(setup_exe, &data_home)?;
316    let desktop_dir = data_home.join("applications");
317
318    run_optional("update-desktop-database", &[desktop_dir.as_os_str()]);
319    Ok(desktop_file)
320}
321
322#[cfg(target_os = "linux")]
323fn write_linux_setup_launcher(setup_exe: &Path, data_home: &Path) -> io::Result<PathBuf> {
324    let desktop_dir = data_home.join("applications");
325    let desktop_file = desktop_dir.join(SETUP_DESKTOP_FILE_NAME);
326
327    fs::create_dir_all(&desktop_dir)?;
328    fs::write(&desktop_file, linux_setup_desktop_entry(setup_exe))?;
329
330    #[cfg(unix)]
331    {
332        use std::os::unix::fs::PermissionsExt;
333        fs::set_permissions(&desktop_file, fs::Permissions::from_mode(0o644))?;
334    }
335
336    Ok(desktop_file)
337}
338
339/// The owned-state check only looks for the mdo-owned handler desktop entry.
340/// The visible `mdo-setup.desktop` launcher has its own lifecycle and does not
341/// count as handler integration.
342#[cfg(target_os = "linux")]
343fn linux_integration_installed_at(data_home: &Path) -> bool {
344    data_home
345        .join("applications")
346        .join(DESKTOP_FILE_NAME)
347        .is_file()
348}
349
350#[cfg(target_os = "linux")]
351fn remove_linux_handler_files(data_home: &Path) -> io::Result<()> {
352    let desktop_file = data_home.join("applications").join(DESKTOP_FILE_NAME);
353    let icon_file = data_home
354        .join("icons")
355        .join("hicolor")
356        .join("scalable")
357        .join("apps")
358        .join("mdo.svg");
359
360    remove_file_if_present(&desktop_file)?;
361    remove_file_if_present(&icon_file)?;
362    remove_legacy_nautilus_scripts(data_home)
363}
364
365/// The single registry key the owned-state check queries: the open command of
366/// mdo's own `mdo.md` ProgID. Install writes it (see [`install_windows_plan`])
367/// and uninstall deletes its parent ProgID key, so its presence tracks exactly
368/// the registration mdo owns — nothing about defaults or other handlers.
369#[cfg(target_os = "windows")]
370const WINDOWS_OWNED_PROGID_COMMAND_KEY: &str = r"HKCU\Software\Classes\mdo.md\shell\open\command";
371
372#[cfg(target_os = "windows")]
373fn reg_key_exists(key: &str) -> bool {
374    Command::new("reg")
375        .args(["query", key, "/ve"])
376        .stdout(Stdio::null())
377        .stderr(Stdio::null())
378        .status()
379        .map(|status| status.success())
380        .unwrap_or(false)
381}
382
383#[cfg(target_os = "linux")]
384fn xdg_data_home() -> io::Result<PathBuf> {
385    if let Some(value) = std::env::var_os("XDG_DATA_HOME") {
386        return Ok(PathBuf::from(value));
387    }
388
389    let home = std::env::var_os("HOME").ok_or_else(|| {
390        io::Error::new(
391            io::ErrorKind::NotFound,
392            "HOME is not set; cannot locate ~/.local/share",
393        )
394    })?;
395    Ok(PathBuf::from(home).join(".local").join("share"))
396}
397
398#[cfg(target_os = "linux")]
399fn linux_desktop_entry(exe: &Path) -> String {
400    let quoted_exe = quote_desktop_exec_arg(&exe.to_string_lossy());
401    // The Exec line is the handler invocation contract in desktop-entry
402    // spelling: the binary, the contract flags, then the %f file placeholder.
403    let open_flags = handler::OPEN_FLAGS.join(" ");
404    format!(
405        "[Desktop Entry]\n\
406         Type=Application\n\
407         Name={APP_DISPLAY_NAME}\n\
408         GenericName=Markdown HTML Opener\n\
409         Comment=Open Markdown as HTML in the default browser\n\
410         Exec={quoted_exe} {open_flags} %f\n\
411         Icon=mdo\n\
412         Terminal=false\n\
413         NoDisplay=true\n\
414         MimeType=text/markdown;text/x-markdown;\n\
415         Categories=Utility;TextTools;\n\
416         StartupNotify=false\n"
417    )
418}
419
420#[cfg(target_os = "linux")]
421fn linux_setup_desktop_entry(setup_exe: &Path) -> String {
422    let quoted_exe = quote_desktop_exec_arg(&setup_exe.to_string_lossy());
423    format!(
424        "[Desktop Entry]\n\
425         Type=Application\n\
426         Name=mdo Setup\n\
427         GenericName=Markdown Opener Setup\n\
428         Comment=Set up mdo and open the first-run tour\n\
429         Exec={quoted_exe}\n\
430         Icon=utilities-terminal\n\
431         Terminal=false\n\
432         NoDisplay=false\n\
433         Categories=Utility;TextTools;\n\
434         StartupNotify=false\n"
435    )
436}
437
438#[cfg(target_os = "linux")]
439fn quote_desktop_exec_arg(value: &str) -> String {
440    let mut quoted = String::with_capacity(value.len() + 2);
441    quoted.push('"');
442    for ch in value.chars() {
443        match ch {
444            '\\' | '"' | '$' | '`' => {
445                quoted.push('\\');
446                quoted.push(ch);
447            }
448            _ => quoted.push(ch),
449        }
450    }
451    quoted.push('"');
452    quoted
453}
454
455#[cfg(target_os = "linux")]
456fn run_optional(program: &str, args: &[&std::ffi::OsStr]) {
457    let _ = run_optional_status(program, args);
458}
459
460#[cfg(target_os = "linux")]
461fn run_optional_status(program: &str, args: &[&std::ffi::OsStr]) -> bool {
462    Command::new(program)
463        .args(args)
464        .status()
465        .map(|status| status.success())
466        .unwrap_or(false)
467}
468
469#[cfg(target_os = "linux")]
470fn remove_legacy_nautilus_scripts(data_home: &Path) -> io::Result<()> {
471    let nautilus_dir = data_home.join("nautilus").join("scripts");
472    for name in ["Open as HTML", "Preview with mdo", "Render with mdo"] {
473        remove_file_if_present(&nautilus_dir.join(name))?;
474    }
475    Ok(())
476}
477
478#[cfg(target_os = "linux")]
479fn remove_file_if_present(path: &Path) -> io::Result<()> {
480    match fs::remove_file(path) {
481        Ok(()) => {
482            println!("Removed: {}", path.display());
483            Ok(())
484        }
485        Err(e) if e.kind() == io::ErrorKind::NotFound => {
486            println!("Skip   : {} (not present)", path.display());
487            Ok(())
488        }
489        Err(e) => Err(e),
490    }
491}
492
493#[cfg(target_os = "linux")]
494fn mimeapps_paths(data_home: &Path) -> Vec<PathBuf> {
495    let mut paths = Vec::new();
496    if let Some(config_home) = std::env::var_os("XDG_CONFIG_HOME") {
497        paths.push(PathBuf::from(config_home).join("mimeapps.list"));
498    } else if let Some(home) = std::env::var_os("HOME") {
499        paths.push(PathBuf::from(home).join(".config").join("mimeapps.list"));
500    }
501    paths.push(data_home.join("applications").join("mimeapps.list"));
502    paths
503}
504
505#[cfg(target_os = "linux")]
506fn remove_desktop_from_mimeapps(path: &Path) -> io::Result<()> {
507    let contents = match fs::read_to_string(path) {
508        Ok(contents) => contents,
509        Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(()),
510        Err(e) => return Err(e),
511    };
512
513    let updated = strip_mdo_from_mimeapps(&contents);
514    if updated != contents {
515        fs::write(path, updated)?;
516        println!("Updated: {}", path.display());
517    }
518
519    Ok(())
520}
521
522#[cfg(target_os = "linux")]
523fn strip_mdo_from_mimeapps(contents: &str) -> String {
524    let mut section = "";
525    let mut out = Vec::new();
526
527    for line in contents.lines() {
528        match line {
529            "[Default Applications]" => {
530                section = "default";
531                out.push(line.to_string());
532                continue;
533            }
534            "[Added Associations]" => {
535                section = "added";
536                out.push(line.to_string());
537                continue;
538            }
539            _ if line.starts_with('[') => {
540                section = "";
541                out.push(line.to_string());
542                continue;
543            }
544            _ => {}
545        }
546
547        if section == "default"
548            && (line == "text/markdown=mdo.desktop" || line == "text/x-markdown=mdo.desktop")
549        {
550            continue;
551        }
552
553        if section == "added"
554            && (line.starts_with("text/markdown=") || line.starts_with("text/x-markdown="))
555        {
556            if let Some((mime, apps)) = line.split_once('=') {
557                let apps = apps
558                    .split(';')
559                    .filter(|app| !app.is_empty() && *app != DESKTOP_FILE_NAME)
560                    .collect::<Vec<_>>();
561                if apps.is_empty() {
562                    continue;
563                }
564                out.push(format!("{mime}={};", apps.join(";")));
565                continue;
566            }
567        }
568
569        out.push(line.to_string());
570    }
571
572    let mut result = out.join("\n");
573    if contents.ends_with('\n') {
574        result.push('\n');
575    }
576    result
577}
578
579#[cfg(target_os = "windows")]
580struct WindowsHandler {
581    path: PathBuf,
582    is_wrapper: bool,
583}
584
585#[cfg(target_os = "windows")]
586fn windows_handler_for(current_exe: &Path) -> WindowsHandler {
587    let sibling_wrapper = handler::sibling_binary(current_exe, "mdo-open.exe").ok();
588    match sibling_wrapper {
589        Some(path) => WindowsHandler {
590            path,
591            is_wrapper: true,
592        },
593        None => WindowsHandler {
594            path: current_exe.to_path_buf(),
595            is_wrapper: false,
596        },
597    }
598}
599
600#[cfg(target_os = "windows")]
601fn windows_registry_command(handler_path: &Path, is_wrapper: bool) -> String {
602    if is_wrapper {
603        format!("\"{}\" \"%1\"", handler_path.display())
604    } else {
605        // The registry command is the handler invocation contract in
606        // registry spelling: the binary, the contract flags, then the %1
607        // file placeholder.
608        format!(
609            "\"{}\" {} \"%1\"",
610            handler_path.display(),
611            handler::OPEN_FLAGS.join(" ")
612        )
613    }
614}
615
616/// A single registry write/delete, described data-first so installation
617/// logic can be composed and unit-tested without shelling out to `reg.exe`.
618///
619/// `best_effort` mirrors the original inline `let _ = reg_delete_key(...)`
620/// pattern: some ops (e.g. clearing legacy verbs that may not exist) should
621/// not abort the rest of the plan if they fail.
622#[cfg(target_os = "windows")]
623#[derive(Debug, Clone, PartialEq, Eq)]
624struct RegistryOp {
625    action: RegistryAction,
626    best_effort: bool,
627}
628
629#[cfg(target_os = "windows")]
630#[derive(Debug, Clone, PartialEq, Eq)]
631enum RegistryAction {
632    SetDefault {
633        key: String,
634        value: String,
635    },
636    SetValue {
637        key: String,
638        name: String,
639        value: String,
640    },
641    DeleteKey {
642        key: String,
643    },
644    DeleteValue {
645        key: String,
646        name: String,
647    },
648}
649
650#[cfg(target_os = "windows")]
651impl RegistryOp {
652    fn required(action: RegistryAction) -> Self {
653        Self {
654            action,
655            best_effort: false,
656        }
657    }
658
659    fn best_effort(action: RegistryAction) -> Self {
660        Self {
661            action,
662            best_effort: true,
663        }
664    }
665}
666
667/// Registry ops that register `exe_name` as an "Applications" handler for
668/// Open With, mirroring the shape `register_windows_application` used to
669/// write directly. Pure: takes already-computed strings and returns a plan.
670#[cfg(target_os = "windows")]
671fn application_registration_ops(exe_name: &str, command: &str, icon_ref: &str) -> Vec<RegistryOp> {
672    let key = format!(r"HKCU\Software\Classes\Applications\{exe_name}");
673
674    vec![
675        RegistryOp::required(RegistryAction::SetValue {
676            key: key.clone(),
677            name: "FriendlyAppName".to_string(),
678            value: APP_DISPLAY_NAME.to_string(),
679        }),
680        RegistryOp::required(RegistryAction::SetValue {
681            key: key.clone(),
682            name: "ApplicationName".to_string(),
683            value: APP_DISPLAY_NAME.to_string(),
684        }),
685        RegistryOp::required(RegistryAction::SetDefault {
686            key: format!(r"{key}\DefaultIcon"),
687            value: icon_ref.to_string(),
688        }),
689        RegistryOp::required(RegistryAction::SetDefault {
690            key: format!(r"{key}\shell\open\command"),
691            value: command.to_string(),
692        }),
693        RegistryOp::required(RegistryAction::SetValue {
694            key: format!(r"{key}\SupportedTypes"),
695            name: ".md".to_string(),
696            value: String::new(),
697        }),
698    ]
699}
700
701/// Pure planning step for the install executor below: given the already
702/// pure-computed handler command, current-exe command, and icon reference,
703/// produce the ordered list of registry writes install would perform.
704/// Unit-tested directly (see `windows_tests`) so the composition — which
705/// keys, which values, wrapper-vs-direct branching, best-effort cleanup of
706/// legacy verbs — is covered without mutating the real registry.
707#[cfg(target_os = "windows")]
708fn install_windows_plan(
709    is_wrapper: bool,
710    command: &str,
711    current_exe_command: &str,
712    icon_ref: &str,
713) -> Vec<RegistryOp> {
714    let mut ops = application_registration_ops("mdo.exe", current_exe_command, icon_ref);
715    if is_wrapper {
716        ops.extend(application_registration_ops(
717            "mdo-open.exe",
718            command,
719            icon_ref,
720        ));
721    }
722
723    ops.push(RegistryOp::required(RegistryAction::SetValue {
724        key: r"HKCU\Software\Classes\.md\OpenWithProgids".to_string(),
725        name: "mdo.md".to_string(),
726        value: String::new(),
727    }));
728
729    ops.push(RegistryOp::required(RegistryAction::SetDefault {
730        key: r"HKCU\Software\Classes\mdo.md".to_string(),
731        value: "Markdown document (Open as HTML)".to_string(),
732    }));
733    ops.push(RegistryOp::required(RegistryAction::SetDefault {
734        key: WINDOWS_OWNED_PROGID_COMMAND_KEY.to_string(),
735        value: command.to_string(),
736    }));
737    ops.push(RegistryOp::required(RegistryAction::SetDefault {
738        key: r"HKCU\Software\Classes\mdo.md\DefaultIcon".to_string(),
739        value: icon_ref.to_string(),
740    }));
741
742    for old_verb in [
743        r"HKCU\Software\Classes\SystemFileAssociations\.md\shell\Preview with mdo",
744        r"HKCU\Software\Classes\SystemFileAssociations\.md\shell\Render with mdo",
745    ] {
746        ops.push(RegistryOp::best_effort(RegistryAction::DeleteKey {
747            key: old_verb.to_string(),
748        }));
749    }
750
751    let verb = r"HKCU\Software\Classes\SystemFileAssociations\.md\shell\Open as HTML";
752    ops.push(RegistryOp::required(RegistryAction::SetDefault {
753        key: verb.to_string(),
754        value: APP_DISPLAY_NAME.to_string(),
755    }));
756    ops.push(RegistryOp::required(RegistryAction::SetDefault {
757        key: format!(r"{verb}\command"),
758        value: command.to_string(),
759    }));
760    ops.push(RegistryOp::required(RegistryAction::SetValue {
761        key: verb.to_string(),
762        name: "Icon".to_string(),
763        value: icon_ref.to_string(),
764    }));
765
766    ops
767}
768
769/// Pure planning step for [`uninstall`]: every op here is best-effort,
770/// matching the original `let _ = reg_delete_*(...)` calls — uninstall
771/// should remove everything it can rather than stop at the first missing
772/// key.
773#[cfg(target_os = "windows")]
774fn uninstall_windows_plan() -> Vec<RegistryOp> {
775    let mut ops = Vec::new();
776
777    for key in [
778        r"HKCU\Software\Classes\Applications\mdo.exe",
779        r"HKCU\Software\Classes\Applications\mdo-open.exe",
780        r"HKCU\Software\Classes\mdo.md",
781        r"HKCU\Software\Classes\SystemFileAssociations\.md\shell\Open as HTML",
782        r"HKCU\Software\Classes\SystemFileAssociations\.md\shell\Preview with mdo",
783        r"HKCU\Software\Classes\SystemFileAssociations\.md\shell\Render with mdo",
784        r"HKCU\Software\Classes\Applications\md2htmlx.exe",
785        r"HKCU\Software\Classes\md2htmlx.md",
786        r"HKCU\Software\Classes\SystemFileAssociations\.md\shell\Render with md2htmlx",
787    ] {
788        ops.push(RegistryOp::best_effort(RegistryAction::DeleteKey {
789            key: key.to_string(),
790        }));
791    }
792
793    ops.push(RegistryOp::best_effort(RegistryAction::DeleteValue {
794        key: r"HKCU\Software\Classes\.md\OpenWithProgids".to_string(),
795        name: "mdo.md".to_string(),
796    }));
797    ops.push(RegistryOp::best_effort(RegistryAction::DeleteValue {
798        key: r"HKCU\Software\Classes\.md\OpenWithProgids".to_string(),
799        name: "md2htmlx.md".to_string(),
800    }));
801
802    ops
803}
804
805/// The only impure step of the install/uninstall registry seam: apply an
806/// already-built plan by shelling out to `reg.exe` for each op, propagating
807/// the first failure among the `required` ops and swallowing failures on
808/// `best_effort` ops (mirroring the original `let _ = ...` cleanup calls).
809#[cfg(target_os = "windows")]
810fn apply_registry_plan(ops: &[RegistryOp]) -> io::Result<()> {
811    for op in ops {
812        let result = apply_registry_action(&op.action);
813        if !op.best_effort {
814            result?;
815        }
816    }
817    Ok(())
818}
819
820#[cfg(target_os = "windows")]
821fn apply_registry_action(action: &RegistryAction) -> io::Result<()> {
822    match action {
823        RegistryAction::SetDefault { key, value } => reg_add_default(key, value),
824        RegistryAction::SetValue { key, name, value } => reg_add_value(key, name, value),
825        RegistryAction::DeleteKey { key } => reg_delete_key(key),
826        RegistryAction::DeleteValue { key, name } => reg_delete_value(key, name),
827    }
828}
829
830#[cfg(target_os = "windows")]
831fn install_windows_icon() -> io::Result<PathBuf> {
832    let icon_file = windows_icon_file()?;
833    if let Some(parent) = icon_file.parent() {
834        fs::create_dir_all(parent)?;
835    }
836    fs::write(&icon_file, WINDOWS_ICON_BYTES)?;
837    Ok(icon_file)
838}
839
840#[cfg(target_os = "windows")]
841fn remove_windows_icon() -> io::Result<()> {
842    let icon_file = match windows_icon_file() {
843        Ok(path) => path,
844        Err(_) => return Ok(()),
845    };
846
847    match fs::remove_file(&icon_file) {
848        Ok(()) => {}
849        Err(e) if e.kind() == io::ErrorKind::NotFound => {}
850        Err(e) => return Err(e),
851    }
852
853    if let Some(parent) = icon_file.parent() {
854        match fs::remove_dir(parent) {
855            Ok(()) => {}
856            Err(e)
857                if matches!(
858                    e.kind(),
859                    io::ErrorKind::NotFound | io::ErrorKind::DirectoryNotEmpty
860                ) => {}
861            Err(e) => return Err(e),
862        }
863    }
864
865    Ok(())
866}
867
868#[cfg(target_os = "windows")]
869fn windows_icon_file() -> io::Result<PathBuf> {
870    let base = std::env::var_os("LOCALAPPDATA")
871        .or_else(|| std::env::var_os("APPDATA"))
872        .ok_or_else(|| {
873            io::Error::new(
874                io::ErrorKind::NotFound,
875                "LOCALAPPDATA and APPDATA are not set; cannot install icon",
876            )
877        })?;
878
879    Ok(PathBuf::from(base).join("mdo").join("mdo.ico"))
880}
881
882#[cfg(target_os = "windows")]
883fn reg_add_default(key: &str, value: &str) -> io::Result<()> {
884    reg_status(
885        Command::new("reg").args(["add", key, "/ve", "/d", value, "/f"]),
886        "reg add",
887    )
888}
889
890#[cfg(target_os = "windows")]
891fn reg_add_value(key: &str, name: &str, value: &str) -> io::Result<()> {
892    reg_status(
893        Command::new("reg").args(["add", key, "/v", name, "/t", "REG_SZ", "/d", value, "/f"]),
894        "reg add",
895    )
896}
897
898#[cfg(target_os = "windows")]
899fn reg_delete_key(key: &str) -> io::Result<()> {
900    reg_status(
901        Command::new("reg").args(["delete", key, "/f"]),
902        "reg delete",
903    )
904}
905
906#[cfg(target_os = "windows")]
907fn reg_delete_value(key: &str, name: &str) -> io::Result<()> {
908    reg_status(
909        Command::new("reg").args(["delete", key, "/v", name, "/f"]),
910        "reg delete",
911    )
912}
913
914#[cfg(target_os = "windows")]
915fn reg_status(command: &mut Command, action: &str) -> io::Result<()> {
916    let output = command
917        .stdout(Stdio::piped())
918        .stderr(Stdio::piped())
919        .output()?;
920    if output.status.success() {
921        Ok(())
922    } else {
923        let stderr = String::from_utf8_lossy(&output.stderr);
924        let stdout = String::from_utf8_lossy(&output.stdout);
925        let details = stderr.trim();
926        let details = if details.is_empty() {
927            stdout.trim()
928        } else {
929            details
930        };
931
932        let suffix = if details.is_empty() {
933            String::new()
934        } else {
935            format!(": {details}")
936        };
937
938        Err(io::Error::other(format!(
939            "{action} failed with status {}{suffix}",
940            output.status
941        )))
942    }
943}
944
945#[cfg(all(test, target_os = "linux"))]
946mod linux_tests {
947    use super::*;
948
949    #[test]
950    fn desktop_exec_arg_escapes_special_chars() {
951        assert_eq!(
952            quote_desktop_exec_arg(r#"/tmp/a\b"c$d`e/mdo"#),
953            r#""/tmp/a\\b\"c\$d\`e/mdo""#
954        );
955    }
956
957    #[test]
958    fn linux_install_plan_derives_standard_paths_and_entry_content() {
959        let data_home = Path::new("/home/u/.local/share");
960        let exe = Path::new("/opt/my tools/mdo");
961
962        let plan = linux_install_plan(data_home, exe, true);
963        assert_eq!(
964            plan.desktop_file,
965            data_home.join("applications").join(DESKTOP_FILE_NAME)
966        );
967        assert_eq!(
968            plan.icon_file,
969            data_home
970                .join("icons")
971                .join("hicolor")
972                .join("scalable")
973                .join("apps")
974                .join("mdo.svg")
975        );
976        // The entry content carries the handler invocation contract with the
977        // quoting rules applied (same emitted form the integration registers).
978        assert!(plan
979            .desktop_entry
980            .contains("Exec=\"/opt/my tools/mdo\" --open %f\n"));
981        assert!(plan.set_default);
982        assert_eq!(plan.default_mimes, &["text/markdown", "text/x-markdown"]);
983        assert_eq!(plan.legacy_cleanup_root, Some(data_home.to_path_buf()));
984
985        let plan_without_default = linux_install_plan(data_home, exe, false);
986        assert!(!plan_without_default.set_default);
987    }
988
989    #[test]
990    fn apply_linux_install_plan_writes_entry_and_icon_and_reports() {
991        let dir = std::env::temp_dir().join(format!(
992            "mdo-install-plan-test-{}-{:?}",
993            std::process::id(),
994            std::thread::current().id()
995        ));
996        let exe = dir.join("mdo");
997        fs::create_dir_all(&dir).unwrap();
998
999        let mut plan = linux_install_plan(&dir, &exe, false);
1000        // No legacy scripts exist in this fixture; the cleanup would be a
1001        // no-op either way (it only removes known files if present).
1002        plan.legacy_cleanup_root = None;
1003
1004        let report = apply_linux_install_plan(&plan).expect("apply should write the registration");
1005        assert_eq!(
1006            report.default,
1007            LinuxDefaultOutcome::NotRequested,
1008            "no default was requested"
1009        );
1010
1011        let entry = fs::read_to_string(&report.desktop_file).expect("entry written");
1012        assert!(entry.contains("[Desktop Entry]\n"));
1013        // The entry content carries the handler invocation contract with the
1014        // quoting rules applied (exe path comes from this fixture's anchor).
1015        assert!(
1016            entry.contains(&format!("Exec=\"{}\" --open %f\n", exe.display())),
1017            "entry should carry the contract Exec line: {entry}"
1018        );
1019        let icon = fs::read_to_string(&report.icon_file).expect("icon written");
1020        assert!(icon.contains("<svg"));
1021
1022        use std::os::unix::fs::PermissionsExt;
1023        let mode = fs::metadata(&report.desktop_file)
1024            .expect("entry metadata")
1025            .permissions()
1026            .mode();
1027        assert_eq!(mode & 0o777, 0o644, "the entry must stay mode 0644");
1028
1029        fs::remove_dir_all(dir).unwrap();
1030    }
1031
1032    #[test]
1033    fn apply_linux_install_plan_requested_default_without_mimes_needs_manual_hint() {
1034        // set_default=true with an empty mime list cannot spawn xdg-mime at
1035        // all, so the branch is deterministic: the executor must not assume
1036        // success just because defaulting was requested.
1037        let dir = std::env::temp_dir().join(format!(
1038            "mdo-install-plan-hint-test-{}-{:?}",
1039            std::process::id(),
1040            std::thread::current().id()
1041        ));
1042        let exe = dir.join("mdo");
1043        fs::create_dir_all(&dir).unwrap();
1044
1045        let mut plan = linux_install_plan(&dir, &exe, true);
1046        plan.default_mimes = &[];
1047        plan.legacy_cleanup_root = None;
1048
1049        let report = apply_linux_install_plan(&plan).expect("apply should complete");
1050        assert_eq!(report.default, LinuxDefaultOutcome::NeedsManualHint);
1051
1052        fs::remove_dir_all(dir).unwrap();
1053    }
1054
1055    #[test]
1056    fn setup_launcher_is_visible_and_not_a_file_handler() {
1057        let entry = linux_setup_desktop_entry(Path::new(r#"/opt/mdo tools/a\b"c$d`e/mdo-setup"#));
1058
1059        assert!(entry.contains("Name=mdo Setup\n"));
1060        assert!(entry.contains(r#"Exec="/opt/mdo tools/a\\b\"c\$d\`e/mdo-setup""#));
1061        assert!(entry.contains("Terminal=false\n"));
1062        assert!(entry.contains("NoDisplay=false\n"));
1063        assert!(!entry.contains("MimeType="));
1064        assert!(!entry.contains("%f"));
1065    }
1066
1067    #[test]
1068    fn setup_launcher_has_separate_handler_ownership() {
1069        assert_ne!(SETUP_DESKTOP_FILE_NAME, DESKTOP_FILE_NAME);
1070        let entry = linux_setup_desktop_entry(Path::new("/usr/bin/mdo-setup"));
1071        assert!(!entry.contains("Icon=mdo\n"));
1072    }
1073
1074    #[test]
1075    fn handler_uninstall_preserves_setup_launcher() {
1076        let data_home = std::env::temp_dir().join(format!(
1077            "mdo-setup-launcher-test-{}-{:?}",
1078            std::process::id(),
1079            std::thread::current().id()
1080        ));
1081        let applications = data_home.join("applications");
1082        fs::create_dir_all(&applications).unwrap();
1083        fs::write(applications.join(DESKTOP_FILE_NAME), "handler").unwrap();
1084
1085        let setup_file =
1086            write_linux_setup_launcher(Path::new("/opt/mdo/bin/mdo-setup"), &data_home).unwrap();
1087        // Registration is idempotent and rewrites stale content.
1088        fs::write(&setup_file, "stale").unwrap();
1089        write_linux_setup_launcher(Path::new("/opt/mdo/bin/mdo-setup"), &data_home).unwrap();
1090
1091        remove_linux_handler_files(&data_home).unwrap();
1092
1093        assert!(!applications.join(DESKTOP_FILE_NAME).exists());
1094        assert!(setup_file.exists());
1095        assert!(fs::read_to_string(&setup_file)
1096            .unwrap()
1097            .contains("Exec=\"/opt/mdo/bin/mdo-setup\"\n"));
1098        fs::remove_dir_all(data_home).unwrap();
1099    }
1100
1101    #[test]
1102    fn owned_state_check_tracks_only_the_handler_desktop_file() {
1103        let data_home = std::env::temp_dir().join(format!(
1104            "mdo-owned-state-test-{}-{:?}",
1105            std::process::id(),
1106            std::thread::current().id()
1107        ));
1108
1109        // Nothing installed yet: not detected.
1110        assert!(!linux_integration_installed_at(&data_home));
1111
1112        // The visible setup launcher alone is not handler integration.
1113        write_linux_setup_launcher(Path::new("/usr/bin/mdo-setup"), &data_home).unwrap();
1114        assert!(!linux_integration_installed_at(&data_home));
1115
1116        let applications = data_home.join("applications");
1117        fs::write(applications.join(DESKTOP_FILE_NAME), "handler").unwrap();
1118        assert!(linux_integration_installed_at(&data_home));
1119
1120        // Uninstall removes exactly what the check observes.
1121        remove_linux_handler_files(&data_home).unwrap();
1122        assert!(!linux_integration_installed_at(&data_home));
1123
1124        fs::remove_dir_all(data_home).unwrap();
1125    }
1126
1127    #[test]
1128    fn mimeapps_uninstall_removes_only_mdo_entries() {
1129        let input = "\
1130[Default Applications]\n\
1131text/markdown=mdo.desktop\n\
1132text/plain=code.desktop\n\
1133[Added Associations]\n\
1134text/markdown=code.desktop;mdo.desktop;other.desktop;\n\
1135text/x-markdown=mdo.desktop;\n\
1136image/png=viewer.desktop;\n";
1137
1138        let output = strip_mdo_from_mimeapps(input);
1139
1140        assert_eq!(
1141            output,
1142            "\
1143[Default Applications]\n\
1144text/plain=code.desktop\n\
1145[Added Associations]\n\
1146text/markdown=code.desktop;other.desktop;\n\
1147image/png=viewer.desktop;\n"
1148        );
1149    }
1150
1151    /// The desktop Exec line is one of the two emitted forms of the handler
1152    /// invocation contract (the other is the Windows registry command): the
1153    /// same binary and the same contract flags, derived from the contract
1154    /// rather than restated as a literal so the two cannot drift apart.
1155    #[test]
1156    fn desktop_entry_reflects_the_handler_invocation_contract() {
1157        let entry = linux_desktop_entry(Path::new("/opt/mdo/mdo"));
1158        let expected = format!(
1159            "Exec=\"/opt/mdo/mdo\" {} %f\n",
1160            handler::OPEN_FLAGS.join(" ")
1161        );
1162        assert!(
1163            entry.contains(&expected),
1164            "entry should carry the contract Exec line: {entry}"
1165        );
1166
1167        // The setup launcher entry is not open-mode: no contract flags.
1168        let setup_entry = linux_setup_desktop_entry(Path::new("/usr/bin/mdo-setup"));
1169        assert!(!setup_entry.contains(handler::OPEN_FLAGS[0]));
1170    }
1171}
1172
1173#[cfg(all(test, target_os = "windows"))]
1174mod windows_tests {
1175    use super::*;
1176
1177    /// The registry command is one of the two emitted forms of the handler
1178    /// invocation contract (the other is the Linux desktop Exec line): it
1179    /// must carry the same binary and the same contract flags, derived here
1180    /// rather than restated as a literal so the two cannot drift apart.
1181    #[test]
1182    fn registry_command_reflects_the_handler_invocation_contract() {
1183        let command = windows_registry_command(Path::new(r"C:\Tools\mdo.exe"), false);
1184        let expected = format!(
1185            r#""C:\Tools\mdo.exe" {} "%1""#,
1186            handler::OPEN_FLAGS.join(" ")
1187        );
1188        assert_eq!(command, expected);
1189
1190        // The forwarding wrapper carries NO flags: it owns the contract
1191        // itself and forwards the file as received.
1192        let wrapper = windows_registry_command(Path::new(r"C:\Tools\mdo-open.exe"), true);
1193        assert_eq!(wrapper, r#""C:\Tools\mdo-open.exe" "%1""#);
1194        assert!(!wrapper.contains(handler::OPEN_FLAGS[0]));
1195    }
1196
1197    #[test]
1198    fn registry_command_uses_open_flag_without_wrapper() {
1199        let command = windows_registry_command(Path::new(r"C:\Tools\mdo.exe"), false);
1200        assert_eq!(command, r#""C:\Tools\mdo.exe" --open "%1""#);
1201    }
1202
1203    #[test]
1204    fn registry_command_omits_open_flag_for_wrapper() {
1205        let command = windows_registry_command(Path::new(r"C:\Tools\mdo-open.exe"), true);
1206        assert_eq!(command, r#""C:\Tools\mdo-open.exe" "%1""#);
1207    }
1208
1209    // The exe path is only ever wrapped in quotes, never parsed or
1210    // re-escaped, so spaces and cmd.exe metacharacters (& ^ ( ) ...), which
1211    // are all legal in Windows filenames, must survive unmodified inside the
1212    // quoted segment. Quoting (rather than sanitizing) is what neutralizes
1213    // them for the shell that later reads the registry value.
1214    #[test]
1215    fn registry_command_preserves_spaces_in_exe_path() {
1216        let command =
1217            windows_registry_command(Path::new(r"C:\Program Files\mdo tools\mdo.exe"), false);
1218        assert_eq!(
1219            command,
1220            r#""C:\Program Files\mdo tools\mdo.exe" --open "%1""#
1221        );
1222    }
1223
1224    #[test]
1225    fn registry_command_preserves_cmd_metacharacters_in_exe_path() {
1226        let command =
1227            windows_registry_command(Path::new(r"C:\Program Files (x86)\mdo & co^\mdo.exe"), true);
1228        assert_eq!(
1229            command,
1230            r#""C:\Program Files (x86)\mdo & co^\mdo.exe" "%1""#
1231        );
1232    }
1233
1234    #[test]
1235    fn install_plan_registers_wrapper_and_direct_targets_when_wrapper_present() {
1236        let handler_command =
1237            windows_registry_command(Path::new(r"C:\Program Files\mdo & co\mdo-open.exe"), true);
1238        let current_exe_command =
1239            windows_registry_command(Path::new(r"C:\Program Files\mdo & co\mdo.exe"), false);
1240        let icon_ref = r#""C:\Users\me\AppData\Local\mdo\mdo.ico",0"#;
1241
1242        let plan = install_windows_plan(true, &handler_command, &current_exe_command, icon_ref);
1243
1244        // mdo.exe is always registered as an Applications handler using the
1245        // *direct* (--open) command, even when a wrapper exists, because
1246        // some surfaces (e.g. "Open With" listing before mdo-open exists)
1247        // may still reference mdo.exe directly.
1248        assert!(
1249            plan.contains(&RegistryOp::required(RegistryAction::SetDefault {
1250                key: r"HKCU\Software\Classes\Applications\mdo.exe\shell\open\command".to_string(),
1251                value: current_exe_command.clone(),
1252            }))
1253        );
1254
1255        // The wrapper is also registered as its own Applications handler,
1256        // using the wrapper (no --open) command.
1257        assert!(
1258            plan.contains(&RegistryOp::required(RegistryAction::SetDefault {
1259                key: r"HKCU\Software\Classes\Applications\mdo-open.exe\shell\open\command"
1260                    .to_string(),
1261                value: handler_command.clone(),
1262            }))
1263        );
1264
1265        // The .md ProgID's own open command must point at the *handler*
1266        // command (wrapper, if present) so double-click uses it.
1267        assert!(
1268            plan.contains(&RegistryOp::required(RegistryAction::SetDefault {
1269                key: r"HKCU\Software\Classes\mdo.md\shell\open\command".to_string(),
1270                value: handler_command.clone(),
1271            }))
1272        );
1273
1274        // Legacy verb cleanup must be best-effort so a first-time install
1275        // (where those keys never existed) does not fail the whole plan.
1276        assert!(
1277            plan.contains(&RegistryOp::best_effort(RegistryAction::DeleteKey {
1278                key: r"HKCU\Software\Classes\SystemFileAssociations\.md\shell\Preview with mdo"
1279                    .to_string(),
1280            }))
1281        );
1282        assert!(
1283            plan.contains(&RegistryOp::best_effort(RegistryAction::DeleteKey {
1284                key: r"HKCU\Software\Classes\SystemFileAssociations\.md\shell\Render with mdo"
1285                    .to_string(),
1286            }))
1287        );
1288
1289        // Every op besides the two legacy-verb deletes must be required
1290        // (install should fail loudly on a real registry error).
1291        let best_effort_count = plan.iter().filter(|op| op.best_effort).count();
1292        assert_eq!(best_effort_count, 2);
1293    }
1294
1295    #[test]
1296    fn install_plan_skips_wrapper_registration_without_wrapper() {
1297        let command = windows_registry_command(Path::new(r"C:\Tools\mdo.exe"), false);
1298        let icon_ref = r#""C:\Tools\mdo.ico",0"#;
1299
1300        let plan = install_windows_plan(false, &command, &command, icon_ref);
1301
1302        assert!(!plan.iter().any(|op| matches!(
1303            &op.action,
1304            RegistryAction::SetDefault { key, .. } | RegistryAction::SetValue { key, .. }
1305                if key.contains("mdo-open.exe")
1306        )));
1307    }
1308
1309    // The owned-state check must observe exactly the registration mdo owns:
1310    // install writes the queried key, and uninstall deletes an ancestor of it,
1311    // so "key present" can only mean "mdo's own install left it behind".
1312    #[test]
1313    fn owned_state_check_queries_a_key_install_writes_and_uninstall_removes() {
1314        let command = windows_registry_command(Path::new(r"C:\Tools\mdo.exe"), false);
1315        let plan = install_windows_plan(false, &command, &command, r#""C:\Tools\mdo.ico",0"#);
1316
1317        assert!(
1318            plan.contains(&RegistryOp::required(RegistryAction::SetDefault {
1319                key: WINDOWS_OWNED_PROGID_COMMAND_KEY.to_string(),
1320                value: command.clone(),
1321            }))
1322        );
1323
1324        assert!(uninstall_windows_plan().iter().any(|op| matches!(
1325            &op.action,
1326            RegistryAction::DeleteKey { key }
1327                if key.as_str() == WINDOWS_OWNED_PROGID_COMMAND_KEY
1328                    || WINDOWS_OWNED_PROGID_COMMAND_KEY.starts_with(&format!(r"{key}\"))
1329        )));
1330    }
1331
1332    #[test]
1333    fn uninstall_plan_is_entirely_best_effort() {
1334        let plan = uninstall_windows_plan();
1335
1336        assert!(!plan.is_empty());
1337        assert!(plan.iter().all(|op| op.best_effort));
1338
1339        // Legacy md2htmlx keys (an earlier project name) must still be
1340        // cleaned up so upgrading users do not keep a stale handler.
1341        assert!(
1342            plan.contains(&RegistryOp::best_effort(RegistryAction::DeleteKey {
1343                key: r"HKCU\Software\Classes\Applications\md2htmlx.exe".to_string(),
1344            }))
1345        );
1346        assert!(
1347            plan.contains(&RegistryOp::best_effort(RegistryAction::DeleteValue {
1348                key: r"HKCU\Software\Classes\.md\OpenWithProgids".to_string(),
1349                name: "md2htmlx.md".to_string(),
1350            }))
1351        );
1352    }
1353}