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