Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .changes/deep-link-xdg-command-errors.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
"deep-link": patch
"deep-link-js": patch
---

Return an I/O error when an XDG registration, unregistration, or query command exits unsuccessfully on Linux. Match the queried desktop filename exactly, and remove the app's MIME association when unregistering so it is not selected again by fallback. Preserve other schemes, applications, defaults, and desktop command quoting.
2 changes: 1 addition & 1 deletion plugins/deep-link/guest-js/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ export async function register(protocol: string): Promise<null> {
* #### Platform-specific
*
* - **Windows:** Requires admin rights if the protocol is registered on the local machine (this can happen when registered from the NSIS installer when the install mode is set to both or per machine).
* - **Linux / FreeBSD:** Can only unregister the scheme if it was initially registered with {@link register}. May not work on older distros.
* - **Linux / FreeBSD:** Can only unregister the scheme if it was initially registered with {@link register}. Requires `update-desktop-database`. May not work on older distros.
* - **macOS / Android / iOS:** Unsupported.
*
* @returns A promise that resolves once the protocol has been unregistered.
Expand Down
14 changes: 14 additions & 0 deletions plugins/deep-link/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,20 @@ pub(crate) fn inspect_command_error<'a>(command: &'a str) -> impl Fn(&std::io::E
}
}

#[cfg(any(target_os = "linux", target_os = "freebsd"))]
pub(crate) fn check_command_status(
command: &str,
status: std::process::ExitStatus,
) -> std::io::Result<()> {
if status.success() {
Ok(())
} else {
Err(std::io::Error::other(format!(
"OS command `{command}` failed: {status}"
)))
}
}

impl Serialize for Error {
fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
where
Expand Down
101 changes: 89 additions & 12 deletions plugins/deep-link/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,7 @@ mod imp {
///
/// ## Platform-specific:
///
/// - **Linux / FreeBSD**: Can only unregister the scheme if it was initially registered with [`register`](`Self::register`). May not work on older distros.
/// - **Linux / FreeBSD**: Can only unregister the scheme if it was initially registered with [`register`](`Self::register`). Requires `update-desktop-database`. May not work on older distros.
/// - **macOS / Android / iOS**: Unsupported, will return [`Error::UnsupportedPlatform`](`crate::Error::UnsupportedPlatform`).
pub fn unregister<S: AsRef<str>>(&self, _protocol: S) -> crate::Result<()> {
Err(crate::Error::UnsupportedPlatform)
Expand Down Expand Up @@ -363,13 +363,17 @@ mod imp {
Command::new("update-desktop-database")
.arg(target)
.status()
.and_then(|status| {
crate::error::check_command_status("update-desktop-database", status)
})
.inspect_err(crate::error::inspect_command_error(
"update-desktop-database",
))?;

Command::new("xdg-mime")
.args(["default", &file_name, mime_type.as_str()])
.status()
.and_then(|status| crate::error::check_command_status("xdg-mime", status))
.inspect_err(crate::error::inspect_command_error("xdg-mime"))?;

Ok(())
Expand All @@ -387,7 +391,7 @@ mod imp {
///
/// - **Windows**: Requires admin rights if the protocol is registered on local machine
/// (this can happen when registered from the NSIS installer when the install mode is set to both or per machine)
/// - **Linux / FreeBSD**: Can only unregister the scheme if it was initially registered with [`register`](`Self::register`). May not work on older distros.
/// - **Linux / FreeBSD**: Can only unregister the scheme if it was initially registered with [`register`](`Self::register`). Requires `update-desktop-database`. May not work on older distros.
/// - **macOS / Android / iOS**: Unsupported, will return [`Error::UnsupportedPlatform`](`crate::Error::UnsupportedPlatform`).
pub fn unregister<S: AsRef<str>>(&self, _protocol: S) -> crate::Result<()> {
#[cfg(windows)]
Expand All @@ -405,27 +409,99 @@ mod imp {

#[cfg(any(target_os = "linux", target_os = "freebsd"))]
{
let mimeapps_path = self.app.path().config_dir()?.join("mimeapps.list");
let mut mimeapps = ini::Ini::load_from_file(&mimeapps_path)?;

let file_name = format!(
"{}-handler.desktop",
tauri::utils::platform::current_exe()?
.file_name()
.unwrap()
.to_string_lossy()
);
let scheme = format!("x-scheme-handler/{}", _protocol.as_ref());
let remove_entry = |section: &mut ini::Properties, key: &str, item: &str| {
let Some(value) = section.get(key) else {
return false;
};
let mut removed = false;
let remaining = value
.split(';')
.filter(|entry| {
if *entry == item {
removed = true;
false
} else {
!entry.is_empty()
}
})
.collect::<Vec<_>>()
.join(";");
if removed {
if remaining.is_empty() {
section.remove(key);
} else {
section.insert(key.to_string(), format!("{remaining};"));
}
}
removed
};
// Values are already desktop-file syntax. Preserve Exec quotes and escapes
// while removing only this app's scheme associations.
let load_ini = |path: &std::path::Path| {
ini::Ini::load_from_file_opt(
path,
ini::ParseOption {
enabled_quote: false,
enabled_escape: false,
},
)
};
let target = self.app.path().data_dir()?.join("applications");
let desktop_path = target.join(&file_name);
match load_ini(&desktop_path) {
Ok(mut desktop) => {
if let Some(section) = desktop.section_mut(Some("Desktop Entry")) {
if remove_entry(section, "MimeType", &scheme) {
desktop.write_to_file_policy(
&desktop_path,
ini::EscapePolicy::Nothing,
)?;
}
}
}
Err(ini::Error::Io(error)) if error.kind() == std::io::ErrorKind::NotFound => {}
Err(error) => return Err(error.into()),
}

if let Some(section) = mimeapps.section_mut(Some("Default Applications")) {
let scheme = format!("x-scheme-handler/{}", _protocol.as_ref());
// Clear stale cache entries even after a failed update or a removed desktop file.
if target.try_exists()? {
Command::new("update-desktop-database")
.arg(&target)
.status()
.and_then(|status| {
crate::error::check_command_status("update-desktop-database", status)
})
.inspect_err(crate::error::inspect_command_error(
"update-desktop-database",
))?;
}

if section.get(&scheme).unwrap_or_default() == file_name {
section.remove(scheme);
let mimeapps_path = self.app.path().config_dir()?.join("mimeapps.list");
match load_ini(&mimeapps_path) {
Ok(mut mimeapps) => {
let mut changed = false;
for group in ["Default Applications", "Added Associations"] {
if let Some(section) = mimeapps.section_mut(Some(group)) {
changed |= remove_entry(section, &scheme, &file_name);
}
}
if changed {
mimeapps
.write_to_file_policy(mimeapps_path, ini::EscapePolicy::Nothing)?;
}
}
Err(ini::Error::Io(error)) if error.kind() == std::io::ErrorKind::NotFound => {}
Err(error) => return Err(error.into()),
}

mimeapps.write_to_file(mimeapps_path)?;

Ok(())
}

Expand Down Expand Up @@ -477,7 +553,8 @@ mod imp {
.output()
.inspect_err(crate::error::inspect_command_error("xdg-mime"))?;

Ok(String::from_utf8_lossy(&output.stdout).contains(&file_name))
crate::error::check_command_status("xdg-mime", output.status)?;
Ok(String::from_utf8_lossy(&output.stdout).trim_end_matches('\n') == file_name)
}

#[cfg(not(any(windows, target_os = "linux", target_os = "freebsd")))]
Expand Down
Loading