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#[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#[cfg(target_os = "linux")]
54#[derive(Clone, Debug, PartialEq, Eq)]
55struct LinuxInstallPlan {
56 desktop_file: PathBuf,
58 desktop_entry: String,
60 icon_file: PathBuf,
62 set_default: bool,
65 default_mimes: &'static [&'static str],
68 legacy_cleanup_root: Option<PathBuf>,
70}
71
72#[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 Applied,
88 NeedsManualHint,
91 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#[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#[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#[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(¤t_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(¤t_exe, false);
207
208 let plan = install_windows_plan(
215 handler_selection.is_wrapper,
216 &command,
217 ¤t_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 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#[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#[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#[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#[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 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 format!(
609 "\"{}\" {} \"%1\"",
610 handler_path.display(),
611 handler::OPEN_FLAGS.join(" ")
612 )
613 }
614}
615
616#[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#[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#[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#[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#[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 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 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 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 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 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 assert!(!linux_integration_installed_at(&data_home));
1111
1112 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 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 #[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 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 #[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 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 #[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, ¤t_exe_command, icon_ref);
1243
1244 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 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 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 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 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 #[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 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}