From f5918495b35fb26e4f3cdc7d76d196c3c8a08aa9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 5 Dec 2026 14:12:47 -0800 Subject: [PATCH] Links: the desktop app opens links through the shared link opener The main window's UI runtime now gets a link opener (InstallSpec::open_links, craft-libs #5083), which takes every http, https and mailto link the app asks to open (Help menu, app bar Discord button, Home and About links, credits, the updater, an object's URL) and starts the system handler once per request. eframe's `links` feature, which opened them before, is removed. The runtime's opener drops every other scheme, including the file: URLs of View PDF after Saving and Show in Browser in Save for Web and SVG Options. The app now hands those to a new desktop service, Services::open_file_url, which opens them in the default web browser with the webbrowser crate, as eframe's `links` feature did. Without the service (the web build) they go to egui as before. On Linux and the BSDs the link opener runs xdg-open with the URL as its only argument. craft-libs' open_external runs `xdg-open -- `, and xdg-open (xdg-utils 1.1.3, Ubuntu 24.04) exits with "unexpected option '--'" without opening anything. A URL that starts with "-" is refused. macOS and Windows use open_external. --- Cargo.lock | 2 +- apps/vectorcraft/Cargo.toml | 8 +-- apps/vectorcraft/src/host_services.rs | 46 ++++++++++++++++ apps/vectorcraft/src/main.rs | 14 ++++- apps/vectorcraft/src/tests.rs | 21 ++++++++ crates/ui-egui/src/app.rs | 2 +- crates/ui-egui/src/app/links.rs | 76 +++++++++++++++++++++++++++ crates/ui-egui/src/services.rs | 5 ++ 8 files changed, 166 insertions(+), 8 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 10e4037173..f5de4044de 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2971,7 +2971,6 @@ dependencies = [ "raw-window-handle", "smithay-clipboard", "web-time", - "webbrowser", "windows-sys 0.61.2", "winit", ] @@ -8673,6 +8672,7 @@ dependencies = [ "wayland-backend", "wayland-client", "wayland-protocols", + "webbrowser", "windows", "winit", "winreg", diff --git a/apps/vectorcraft/Cargo.toml b/apps/vectorcraft/Cargo.toml index d4d2659b3e..74d7923011 100644 --- a/apps/vectorcraft/Cargo.toml +++ b/apps/vectorcraft/Cargo.toml @@ -23,10 +23,7 @@ vectorcraft-text = { workspace = true } # the update client. craft = { workspace = true, features = ["ui", "ui-app", "settings", "automation", "platform", "window", "dialogs", "print", "update"] } craft-nightly = { workspace = true } -# `links` makes egui's OpenUrl output (every link the app opens) start the system browser; without it egui-winit only -# logs the request. Remove it when the craft-libs pin includes storytold/craft-libs#5083, which opens links in the -# shared app setup. -eframe = { workspace = true, features = ["clipboard", "default_fonts", "links", "wayland", "x11"] } +eframe = { workspace = true, features = ["clipboard", "default_fonts", "wayland", "x11"] } egui = { workspace = true } egui_extras = { workspace = true } serde_json = { workspace = true } @@ -39,6 +36,9 @@ arboard = { workspace = true, features = ["image-data", "wayland-data-control"] image = { workspace = true } # The window's monitors, size and position (the same winit eframe runs on). winit = { version = "0.30", default-features = false } +# Opens the files View PDF after Saving and Show in Browser wrote in the default web browser +# (src/host_services.rs). MIT OR Apache-2.0. +webbrowser = "1.2" [target.'cfg(windows)'.dependencies] clipboard-win = { workspace = true } diff --git a/apps/vectorcraft/src/host_services.rs b/apps/vectorcraft/src/host_services.rs index 9e416d7711..aa4c978b62 100644 --- a/apps/vectorcraft/src/host_services.rs +++ b/apps/vectorcraft/src/host_services.rs @@ -108,6 +108,50 @@ fn reveal_command(path: &str) -> std::process::Command { c } +/// Opens the `file:` URL of a file the app wrote (View PDF after Saving, Show in Browser) in the +/// default web browser. +fn open_file_url(url: &str) -> Result<(), String> { + webbrowser::open(url).map_err(|e| format!("can't open {url}: {e}")) +} + +/// Opens a link with the system's handler, without waiting for it: +/// `craft::platform::open::open_external` on macOS and Windows, xdg-open elsewhere ([`link_command`]). +pub(crate) fn open_link(url: &str) -> Result<(), String> { + #[cfg(not(any(target_os = "macos", windows)))] + { + let mut c = link_command(url)?; + c.stdin(std::process::Stdio::null()).stdout(std::process::Stdio::null()).stderr(std::process::Stdio::null()); + c.spawn().map(|_| ()).map_err(|e| format!("can't open {url}: {e}")) + } + #[cfg(any(target_os = "macos", windows))] + { + craft::platform::open::open_external(url) + } +} + +/// xdg-open with `url` as its only argument. xdg-open stops with "unexpected option" at any +/// argument that starts with `-`, `--` included, which `craft::platform::open::open_external` puts +/// before the URL, so a URL that starts with `-` is refused here instead. Remove this once +/// craft-libs' `open_external` runs xdg-open without `--`. +#[cfg(not(any(target_os = "macos", windows)))] +fn link_command(url: &str) -> Result { + if url.starts_with('-') { + return Err(format!("can't open {url}: it starts with '-'")); + } + let mut c = std::process::Command::new("xdg-open"); + c.arg(url); + Ok(c) +} + +#[cfg(all(test, not(any(target_os = "macos", windows))))] +#[test] +fn xdg_open_gets_the_link_alone_and_never_an_option() { + let c = link_command("https://discord.gg/artcraft").unwrap(); + assert_eq!(c.get_program(), "xdg-open"); + assert_eq!(c.get_args().collect::>(), ["https://discord.gg/artcraft"], "xdg-open refuses a `--` before the URL"); + assert!(link_command("--help").is_err(), "xdg-open would read it as an option"); +} + /// Read a whole file. A device or pipe may never end: only a regular file is read. fn read_file(path: &str) -> Result, String> { if !std::fs::metadata(path).map_err(|e| e.to_string())?.is_file() { @@ -183,6 +227,8 @@ pub(crate) fn services(window: Parent) -> Services { reveal: Some(Box::new(reveal)), // Links panel: Edit Original; Package: Show Package. Relink to Folder and Package pick folders. open_file: Some(Box::new(open_file)), + // View PDF after Saving and Show in Browser open the file they wrote. + open_file_url: Some(Box::new(open_file_url)), // Edit Original of a raster image with Use System Defaults for Edit Original off (#5236). open_in_photocraft: Some(Box::new(open_in_photocraft)), check_application: Some(Box::new(|p| check_app(std::path::Path::new(p)))), diff --git a/apps/vectorcraft/src/main.rs b/apps/vectorcraft/src/main.rs index 63135d00e5..796a7d1dc3 100644 --- a/apps/vectorcraft/src/main.rs +++ b/apps/vectorcraft/src/main.rs @@ -439,6 +439,17 @@ fn desktop_shell_info(detected: Backend, forced_to_x11: bool) -> ShellInfo { ShellInfo::current().backend(backend) } +/// The UI runtime's install spec for the main window: the app's id, and every `http`, `https` or `mailto` link the +/// app asks to open (Help menu, About, credits, the updater, an object's URL) handed to `open_link`, which is +/// [`host_services::open_link`] in the app. +fn main_window_spec( + shell_info: ShellInfo, + windows: Arc, + open_link: impl Fn(&str) -> Result<(), String> + Send + Sync + 'static, +) -> InstallSpec { + InstallSpec::new(shell_info, windows).app_id(vectorcraft_ui_egui::os_window::app_id()).open_links(open_link) +} + /// The nightly channel this build is, as a string for the log. fn channel_name() -> &'static str { match build_flavor::COMPILED { @@ -885,8 +896,7 @@ fn main() -> std::process::ExitCode { if let Some(window) = &winit_window { restore_main_window(window, &placement, settings.lock().get().ui.legacy_window, wayland); } - let spec = InstallSpec::new(shell_info, Arc::new(SystemWindows)) - .app_id(vectorcraft_ui_egui::os_window::app_id()) + let spec = main_window_spec(shell_info, Arc::new(SystemWindows), host_services::open_link) .placement(Arc::new(Mutex::new(placement))) .frame(decision); let spec = match start_pen(&winit_window) { diff --git a/apps/vectorcraft/src/tests.rs b/apps/vectorcraft/src/tests.rs index c28fb19c13..f37e5e68b1 100644 --- a/apps/vectorcraft/src/tests.rs +++ b/apps/vectorcraft/src/tests.rs @@ -13,6 +13,27 @@ fn desktop_shell_reports_the_backend_selected_for_docking() { } } +/// The main window's install spec hands each link the app opens to the link opener once: Help › Discord reaches it, +/// and the window integration does not get the same request as well. +#[test] +fn help_links_open_through_the_main_windows_link_opener() { + let opened = Arc::new(Mutex::new(Vec::::new())); + let seen = Arc::clone(&opened); + let spec = main_window_spec(desktop_shell_info(Backend::X11, false), Arc::new(craft::window::system::NoWindows), move |url: &str| { + seen.lock().unwrap().push(url.to_owned()); + Ok(()) + }); + let mut frames = craft::ui::testing::Frames::uninstalled(); + craft::ui::install(&frames.ctx, spec).unwrap(); + let mut app = VectorcraftApp::new(Session::new(), Services::default()); + frames.idle(2, |ui| app.tick(ui.ctx())); + + app.open_link("help.discord"); + frames.idle(2, |ui| app.tick(ui.ctx())); + assert_eq!(*opened.lock().unwrap(), ["https://discord.gg/artcraft"], "the opener gets the link once"); + assert!(frames.opened().is_empty(), "the integration is not asked to open it too"); +} + /// The saved UI state of an old `ui.json`, as the legacy import reads it. fn legacy_ui(bytes: &[u8]) -> Option { vectorcraft_ui_egui::parse_legacy(bytes).ok().map(|(settings, _)| settings.ui) diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 162d1867ef..0e7f845ef2 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -712,7 +712,7 @@ impl VectorcraftApp { if ctx.current_pass_index() == 0 && let Some(u) = self.pending_url.take() { - ctx.open_url(egui::OpenUrl::new_tab(u)); + self.open_pending_url(ctx, u); } self.flush_clipboard_out(); self.drain_inbox(); diff --git a/crates/ui-egui/src/app/links.rs b/crates/ui-egui/src/app/links.rs index b7b7f5e6ec..aad6f18d42 100644 --- a/crates/ui-egui/src/app/links.rs +++ b/crates/ui-egui/src/app/links.rs @@ -15,6 +15,20 @@ impl VectorcraftApp { } } + /// Open the URL [`Self::open_url`] asked for: a `file:` URL with the host's + /// [`Services::open_file_url`](crate::Services::open_file_url) when it has one, any other URL + /// (and a `file:` URL without that service) as egui's `OpenUrl` in a new tab. + pub(crate) fn open_pending_url(&mut self, ctx: &egui::Context, url: String) { + let file = url.split_once(':').is_some_and(|(scheme, _)| scheme.eq_ignore_ascii_case("file")); + if file && let Some(open) = self.services.open_file_url.as_mut() { + if let Err(error) = open(&url) { + log::warn!("could not open {url:?}: {error}"); + } + return; + } + ctx.open_url(egui::OpenUrl::new_tab(url)); + } + /// Open `url`, which came from a document (an object's URL attribute), in the browser: /// [`browsable_url`]s only. pub(crate) fn open_document_url(&mut self, url: &str) -> Result<(), String> { @@ -122,3 +136,65 @@ impl VectorcraftApp { } } } + +#[cfg(test)] +mod tests { + use super::VectorcraftApp; + use std::cell::RefCell; + use std::rc::Rc; + + /// An app whose host opens `file:` URLs by recording them in the returned list. + fn app_opening_files() -> (VectorcraftApp, Rc>>) { + let opened = Rc::new(RefCell::new(Vec::new())); + let seen = Rc::clone(&opened); + let services = crate::Services { + open_file_url: Some(Box::new(move |url: &str| { + seen.borrow_mut().push(url.to_owned()); + Ok(()) + })), + ..Default::default() + }; + (VectorcraftApp::new(vectorcraft_engine::Session::new(), services), opened) + } + + /// The URLs the next frame of `app` asked egui to open. + fn opened_in_frame(app: &mut VectorcraftApp, ctx: &egui::Context) -> Vec { + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| app.tick(ui.ctx())); + out.textures_delta.clear(); + out.platform_output + .commands + .into_iter() + .filter_map(|c| match c { + egui::OutputCommand::OpenUrl(open) => Some(open.url), + _ => None, + }) + .collect() + } + + /// A file the app wrote opens through the host once, outside egui's links, which the UI + /// runtime's link opener would drop; a web link still goes to egui. + #[test] + fn a_written_file_opens_through_the_host_and_a_web_link_through_egui() { + let (mut app, files) = app_opening_files(); + let ctx = crate::testing::ui_context(); + + app.open_url("FILE:///tmp/out.pdf"); + assert!(opened_in_frame(&mut app, &ctx).is_empty(), "the file URL is not handed to egui"); + assert_eq!(*files.borrow(), ["FILE:///tmp/out.pdf"], "the host opens the file URL"); + assert!(opened_in_frame(&mut app, &ctx).is_empty()); + assert_eq!(files.borrow().len(), 1, "a frame without a request opens nothing again"); + + app.open_link("help.discord"); + assert_eq!(opened_in_frame(&mut app, &ctx), ["https://discord.gg/artcraft"]); + assert_eq!(files.borrow().len(), 1, "a web link does not reach the file opener"); + } + + /// Without the host's file opener (the web build), a `file:` URL goes to egui as before. + #[test] + fn without_a_file_opener_a_file_url_goes_to_egui() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = crate::testing::ui_context(); + app.open_url("file:///tmp/out.svg"); + assert_eq!(opened_in_frame(&mut app, &ctx), ["file:///tmp/out.svg"]); + } +} diff --git a/crates/ui-egui/src/services.rs b/crates/ui-egui/src/services.rs index 9791ad85ca..ee18d1326e 100644 --- a/crates/ui-egui/src/services.rs +++ b/crates/ui-egui/src/services.rs @@ -101,6 +101,11 @@ pub struct Services { /// Open a file (or a folder) in the system's default app for it (desktop: Edit Original, Show /// Package). Without it (the web) those answer with an error. pub open_file: Option, + /// Open a `file:` URL of a file the app wrote (View PDF after Saving, Save for Web's and SVG + /// Options' Show in Browser) in the web browser (desktop). The UI runtime's link + /// opener opens only `http`, `https` and `mailto` links. Without it the URL goes to egui like + /// any other link. + pub open_file_url: Option, /// Open a file in PhotoCraft where it is installed (desktop: Edit Original of a raster image /// with Preferences › File Handling › Use System Defaults for Edit Original off); `Ok(false)` /// when it isn't. Without it Edit Original uses `open_file`.