From 83a8e775d47f0a0bfb693a625badf0fdb7e25d49 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 06:34:14 -0800 Subject: [PATCH 1/4] Graphics: start on Mesa's software renderer when no adapter can show the window Part of #2654. On Linux and the BSDs, when no graphics adapter could show the window (no wgpu backend started, or the restarts left no adapter), the app ended. It now starts once more with LIBGL_ALWAYS_SOFTWARE=1 and VECTORCRAFT_GPU_SOFTWARE=1 and says in the status bar that it draws on the CPU. When that start also fails, or on Windows and macOS, or with WGPU_BACKEND, WGPU_ADAPTER_NAME or LIBGL_ALWAYS_SOFTWARE set, the error names the backends the driver needs. wgpu draws with Vulkan, OpenGL 3.3 or OpenGL ES 3.0. Intel's Ironlake graphics (8086:0046) has OpenGL 2.1 alone, so the window's surface failed with "Failed to create surface for any enabled backend: {}" before any adapter was listed, and gpu::finish restarted only without an adapter that had been picked. --- apps/vectorcraft/src/gpu.rs | 133 ++++++++++++++++++++++++++---- apps/vectorcraft/src/gpu/tests.rs | 49 +++++++++-- apps/vectorcraft/src/main.rs | 8 +- docs/development.md | 2 + 4 files changed, 169 insertions(+), 23 deletions(-) diff --git a/apps/vectorcraft/src/gpu.rs b/apps/vectorcraft/src/gpu.rs index 198e7dcc85..f71cc434ba 100644 --- a/apps/vectorcraft/src/gpu.rs +++ b/apps/vectorcraft/src/gpu.rs @@ -32,6 +32,12 @@ //! that adapter, as the next one in the order would be tried. Each restart leaves out one more //! adapter, so it ends when none is left. //! +//! When no adapter is picked at all, because none is left or no graphics backend started (wgpu +//! needs Vulkan, OpenGL 3.3 or OpenGL ES 3.0, and the driver of Intel's Ironlake graphics offers +//! none of them, so the window's surface failed "for any enabled backend" with no backend listed, +//! #2654), Linux and the BSDs start once more on Mesa's software renderer ([`Software`]); after +//! that, the error that ends the app says what the graphics driver needs. +//! //! An adapter can also hang instead of failing: on a hybrid laptop with High Performance chosen, //! the discrete GPU never put the window's first frame on the screen, with no error and no panic, //! and the app stayed in the background without a window (#964). [`watch_first_frame`] gives the @@ -853,7 +859,7 @@ pub fn watch_first_frame(startup: Arc) { // The new app records its own start. startup.ended(); skip.push(failed.to_string()); - match restart(&skip.join(",")) { + match restart(&skip.join(","), false) { Ok(()) => std::process::exit(0), Err(e) => { log::error!("starting again failed: {e}"); @@ -950,6 +956,94 @@ fn restart_without<'a>(graphics_failed: bool, frames: u64, picked: Option<&'a st picked.filter(|p| graphics_failed && frames < STARTUP_FRAMES && !skip.iter().any(|s| s == p)) } +/// Whether a start whose window no graphics adapter could show may start again on Mesa's software +/// renderer, which draws OpenGL on the CPU (llvmpipe). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Software { + /// Linux and the BSDs, where Mesa provides OpenGL, and this start isn't on it yet. + Possible, + /// This start already draws on it: the app started again with [`SOFTWARE_ENV`], or the user + /// set `LIBGL_ALWAYS_SOFTWARE`. + Tried, + /// Windows and macOS, or a start that `WGPU_BACKEND` or `WGPU_ADAPTER_NAME` chooses. + Unavailable, +} + +impl Software { + /// This start's [`Software`], from the platform and the environment. + pub fn from_env() -> Self { + if cfg!(any(windows, target_os = "macos")) || explicit_choice() { + Software::Unavailable + } else if software_start() || std::env::var_os("LIBGL_ALWAYS_SOFTWARE").is_some() { + Software::Tried + } else { + Software::Possible + } + } +} + +/// Set by the app when it starts again on Mesa's software renderer because no graphics adapter +/// could show the window (#2654). +pub const SOFTWARE_ENV: &str = "VECTORCRAFT_GPU_SOFTWARE"; + +/// Whether this start is the one the app made on Mesa's software renderer ([`SOFTWARE_ENV`]). +pub fn software_start() -> bool { + std::env::var_os(SOFTWARE_ENV).is_some() +} + +/// The graphics APIs the window can draw with on this platform, for the error that ends the app +/// when no adapter can show it and for the note of a start on Mesa's software renderer. +pub const NEEDS: &str = if cfg!(windows) { + "Direct3D 12, OpenGL 3.3 or OpenGL ES 3.0" +} else if cfg!(target_os = "macos") { + "Metal" +} else { + "Vulkan, OpenGL 3.3 or OpenGL ES 3.0" +}; + +/// What follows the window's run ([`next`]). +#[derive(Debug, PartialEq, Eq)] +enum Next { + /// The window closed normally. + Done, + /// Start again without the adapters in `skip`, on Mesa's software renderer when `software`. + Restart { skip: Vec, software: bool }, + /// End the app with this error. + Stop(String), +} + +/// What follows the window's run: `why` it failed (`None` when it closed normally), whether the +/// graphics failed, the `frames` the UI ran, the adapter `picked`, those left out (`skip`) and +/// whether the software renderer is still to try. A failure on an adapter while starting up starts +/// again without it. When no adapter was picked, because none can show the window or no graphics +/// backend started at all (an old GPU whose driver offers neither Vulkan nor OpenGL 3.3 or OpenGL +/// ES 3.0, such as Intel's Ironlake graphics, #2654), Linux and the BSDs start once more on Mesa's +/// software renderer, and after that the error says what the window needs. +fn next(why: Option, graphics_failed: bool, frames: u64, picked: Option<&str>, mut skip: Vec, software: Software) -> Next { + let Some(why) = why else { return Next::Done }; + if let Some(failed) = restart_without(graphics_failed, frames, picked, &skip) { + log::error!("the window failed on graphics adapter {failed} ({why}): starting again without it"); + skip.push(failed.to_string()); + return Next::Restart { skip, software: false }; + } + if !graphics_failed { + return Next::Stop(why); + } + if picked.is_some() || frames >= STARTUP_FRAMES { + return Next::Stop(format!("{why} ({HELP})")); + } + match software { + Software::Possible => { + log::error!("no graphics adapter could show the window ({why}): starting again on Mesa's software renderer, which draws on the CPU"); + Next::Restart { skip, software: true } + } + Software::Tried => Next::Stop(format!( + "{why}: no graphics adapter could show the window, not even Mesa's software renderer (the graphics driver needs {NEEDS}; {HELP})" + )), + Software::Unavailable => Next::Stop(format!("{why}: no graphics adapter could show the window (the graphics driver needs {NEEDS}; {HELP})")), + } +} + /// After the window's run: `Ok` when it closed normally or the app started again (see the module /// docs), otherwise why it failed. `outcome` is eframe's result, or the message of a panic that /// ended it. @@ -957,28 +1051,35 @@ pub fn finish(outcome: Result, startup: &Startup) -> Res // Whatever follows, this start didn't crash; a new app records its own start. startup.ended(); let (why, graphics_failed) = match outcome { - Ok(Ok(())) => return Ok(()), - Ok(Err(e @ eframe::Error::Wgpu(_))) => (e.to_string(), true), - Ok(Err(e)) => (e.to_string(), false), - Err(panic) => (panic, GRAPHICS_PANIC.load(Ordering::Relaxed)), + Ok(Ok(())) => (None, false), + Ok(Err(e @ eframe::Error::Wgpu(_))) => (Some(e.to_string()), true), + Ok(Err(e)) => (Some(e.to_string()), false), + Err(panic) => (Some(panic), GRAPHICS_PANIC.load(Ordering::Relaxed)), }; let frames = startup.ui.get().map_or(0, egui::Context::cumulative_frame_nr); - let mut skip = skipped(); - let Some(failed) = restart_without(graphics_failed, frames, startup.adapter.get().map(String::as_str), &skip) else { - return Err(if graphics_failed { format!("{why} ({HELP})") } else { why }); - }; - log::error!("the window failed on graphics adapter {failed} ({why}): starting again without it"); - skip.push(failed.to_string()); - restart(&skip.join(",")).map_err(|e| format!("{why}; starting again failed: {e}")) + let picked = startup.adapter.get().map(String::as_str); + match next(why.clone(), graphics_failed, frames, picked, skipped(), Software::from_env()) { + Next::Done => Ok(()), + Next::Stop(e) => Err(e), + Next::Restart { skip, software } => { + let why = why.unwrap_or_default(); + restart(&skip.join(","), software).map_err(|e| format!("{why}; starting again failed: {e}")) + } + } } -/// Start the app again with the same arguments, leaving out the adapters in `skip`. On Unix the -/// new app replaces this process (same process id, so an AppImage keeps its files mounted), and -/// this returns only on failure; on Windows it starts beside this one, which then exits. -fn restart(skip: &str) -> std::io::Result<()> { +/// Start the app again with the same arguments, leaving out the adapters in `skip`, and on Mesa's +/// software renderer when `software` (`LIBGL_ALWAYS_SOFTWARE`, with [`SOFTWARE_ENV`] so it is +/// tried once). On Unix the new app replaces this process (same process id, so an AppImage keeps +/// its files mounted), and this returns only on failure; on Windows it starts beside this one, +/// which then exits. +fn restart(skip: &str, software: bool) -> std::io::Result<()> { log::logger().flush(); let mut c = std::process::Command::new(std::env::current_exe()?); c.args(std::env::args_os().skip(1)).env(SKIP_ENV, skip); + if software { + c.env("LIBGL_ALWAYS_SOFTWARE", "1").env(SOFTWARE_ENV, "1"); + } #[cfg(unix)] { use std::os::unix::process::CommandExt as _; diff --git a/apps/vectorcraft/src/gpu/tests.rs b/apps/vectorcraft/src/gpu/tests.rs index 792518993d..4b660854f6 100644 --- a/apps/vectorcraft/src/gpu/tests.rs +++ b/apps/vectorcraft/src/gpu/tests.rs @@ -602,15 +602,52 @@ fn only_a_graphics_failure_while_starting_up_restarts_without_the_adapter() { fn a_normal_exit_or_another_failure_does_not_restart() { let startup = Startup::default(); assert_eq!(finish(Ok(Ok(())), &startup), Ok(())); - // No adapter was picked (none can show the window): the error is returned, nothing restarts. - let none = eframe::Error::Wgpu(eframe::egui_wgpu::WgpuError::CustomNativeAdapterSelectionError("no graphics adapter can show the window".into())); - assert_eq!( - finish(Ok(Err(none)), &startup), - Err(format!("WGPU error: Adapter selection failed: no graphics adapter can show the window ({HELP})")) - ); let _ = startup.adapter.set("Vulkan:1002:164e".into()); GRAPHICS_PANIC.store(false, Ordering::Relaxed); assert_eq!(finish(Err("a bug".into()), &startup), Err("a bug".into())); + // The same, decided without starting anything. + let amd = Some("Vulkan:1002:164e"); + for software in [Software::Possible, Software::Tried, Software::Unavailable] { + assert_eq!(next(None, false, 0, amd, vec![], software), Next::Done); + assert_eq!(next(Some("a bug".into()), false, 0, None, vec![], software), Next::Stop("a bug".into())); + // A failure after start-up, or on an adapter already left out, is not the start's. + assert_eq!(next(Some("lost".into()), true, STARTUP_FRAMES, amd, vec![], software), Next::Stop(format!("lost ({HELP})"))); + let skip = vec!["Vulkan:1002:164e".to_string()]; + assert_eq!(next(Some("lost".into()), true, 0, amd, skip, software), Next::Stop(format!("lost ({HELP})"))); + } + // An adapter that failed while starting up is left out, never with the software renderer. + assert_eq!( + next(Some("lost".into()), true, 0, amd, vec!["Gl:8086:0046".into()], Software::Possible), + Next::Restart { skip: vec!["Gl:8086:0046".into(), "Vulkan:1002:164e".into()], software: false } + ); +} + +/// #2654: on a ThinkPad T510 with Intel's Ironlake graphics, whose driver offers neither Vulkan +/// nor OpenGL 3.3 or OpenGL ES 3.0, wgpu started no backend, so the window's surface failed before +/// any adapter was listed and the app ended; started with `LIBGL_ALWAYS_SOFTWARE=1`, it ran on +/// llvmpipe. With no adapter picked, Linux starts once more on Mesa's software renderer, keeping +/// the adapters already left out, and the error after that says what the driver needs. +#[test] +fn a_start_no_adapter_can_show_tries_the_software_renderer_once() { + let surface = "WGPU error: Failed to create surface for any enabled backend: {}"; + let skip = vec!["Vulkan:8086:0046".to_string()]; + assert_eq!(next(Some(surface.into()), true, 0, None, skip.clone(), Software::Possible), Next::Restart { skip: skip.clone(), software: true }); + // No adapter left that can show the window, after restarts without each. + let none = "WGPU error: Adapter selection failed: no graphics adapter can show the window"; + assert_eq!(next(Some(none.into()), true, 0, None, skip.clone(), Software::Possible), Next::Restart { skip: skip.clone(), software: true }); + // Already on the software renderer: the app ends, saying what the window needs. + let Next::Stop(tried) = next(Some(surface.into()), true, 0, None, skip.clone(), Software::Tried) else { + panic!("a start already on the software renderer starts again") + }; + assert!(tried.starts_with(surface), "{tried}"); + assert!(tried.contains("not even Mesa's software renderer") && tried.contains(NEEDS) && tried.contains(HELP), "{tried}"); + // Windows, macOS or a backend the user chose: no software renderer to start on. + let Next::Stop(unavailable) = next(Some(surface.into()), true, 0, None, skip, Software::Unavailable) else { + panic!("a start without the software renderer starts again") + }; + assert!(unavailable.contains(NEEDS) && unavailable.contains(HELP) && !unavailable.contains("Mesa"), "{unavailable}"); + // A failure outside the graphics never starts again. + assert_eq!(next(Some("a bug".into()), false, 0, None, vec![], Software::Possible), Next::Stop("a bug".into())); } /// A log folder of its own for each test. diff --git a/apps/vectorcraft/src/main.rs b/apps/vectorcraft/src/main.rs index 6ab6778597..b34c3c23d9 100644 --- a/apps/vectorcraft/src/main.rs +++ b/apps/vectorcraft/src/main.rs @@ -920,7 +920,13 @@ fn main() -> std::process::ExitCode { let summary = adapter_summary(&rs.adapter.get_info()); log::info!("rendering with {summary} (power preference {power:?})"); created.created(&cc.egui_ctx); - if !gpu::skipped().is_empty() { + if gpu::software_start() { + // No graphics processor could show the window, so Mesa draws it on the CPU (#2654). + app.status(format!( + "No graphics processor could show the window, so VectorCraft started again on {summary}, which draws on the CPU and is slower. Showing it on the graphics processor needs a driver with {}", + gpu::NEEDS + )); + } else if !gpu::skipped().is_empty() { // A processor chosen in Settings can be the one that can't show the window. if chosen_gpu { app.status(format!( diff --git a/docs/development.md b/docs/development.md index 5a1b6efd95..3a1f06fd39 100644 --- a/docs/development.md +++ b/docs/development.md @@ -74,6 +74,7 @@ The canvas is rasterized on the CPU (`vectorcraft-render`, vello_cpu); the GPU ( - **Automatic on Linux and the BSDs** is the GPU that drives the panel or a monitor, then the system's order: Mesa's Vulkan device-select layer puts the GPU the desktop runs on first (the integrated one on hybrid laptops; `DRI_PRIME` and `MESA_VK_DEVICE_SELECT` steer it). A Wayland compositor may not accept frames from another GPU: on a desktop whose compositor ran on an NVIDIA GPU, rendering on the Ryzen's integrated GPU made KWin end the window's connection ("importing the supplied dmabufs failed") and 0.5.0 crashed at startup (#502). - 0.5.0 saved `powerSaving`, its default, for everyone; it reads as `automatic`. - **If the window fails on its adapter while starting up** (an error from wgpu, or a panic inside wgpu or egui-wgpu during the first frames), the app starts again without that adapter and tries the next one, telling which in the status bar; the run that failed keeps its log as `vectorcraft.1.log`. On Unix the new app replaces the process (an AppImage stays mounted); on Windows it starts beside it. Adapters are told apart by backend and PCI ids, or by name where the backend reports no ids (Metal lists every GPU of a dual-GPU Mac as `0000:0000`, #651). The adapters left out travel in `VECTORCRAFT_GPU_SKIP` (`backend:vendor:device`, such as `Vulkan:1002:164e`), one more on each restart, so the restarts end. When no adapter is left, the app logs why and exits with an error instead of panicking. +- **If no graphics adapter can show the window at all** on Linux or a BSD, the app starts once more on Mesa's software renderer (llvmpipe, through `LIBGL_ALWAYS_SOFTWARE=1`), which draws on the CPU and is slower, and says so in the status bar. That covers every adapter left out by the restarts above, and a GPU whose driver offers none of the backends wgpu draws with: Vulkan, OpenGL 3.3 or OpenGL ES 3.0. Intel's Ironlake graphics (PCI id `8086:0046`, in a ThinkPad T510) has OpenGL 2.1 alone, so wgpu started no backend and the window failed with `Failed to create surface for any enabled backend: {}` (#2654). The software start carries `VECTORCRAFT_GPU_SOFTWARE`, so it happens once; when it fails too, or when `WGPU_BACKEND`, `WGPU_ADAPTER_NAME` or `LIBGL_ALWAYS_SOFTWARE` is set, the app exits with an error that names the backends the driver needs. On a laptop with a second GPU, choosing that GPU in the firmware settings may give a driver with one of these backends. - **If the window's first frame never reaches the screen** within 20 seconds of the app being created (the files named at the start opened), the adapter counts as hanging and the app starts again without it in the same way (#964: High Performance on a hybrid laptop left the app running in the background with no window and nothing in the log). A window minimized at the start isn't counted. When the processor that hung was chosen in Preferences, the status bar points to Automatic. - **If the app crashes while the window starts**, as when Intel's Direct3D 12 driver (`igd12umd64.dll`) ended 0.9.0 before its window appeared on an Intel UHD Graphics 605 (#2243), no code in the process runs to start it again, so the next start leaves the adapter out. Each start writes `graphics-start.json` in the log folder before the graphics start and adds the adapter once one is picked; when the first frame reaches the screen or the app ends without crashing, the start is cleared from the file. A start that finds an earlier start still recorded there logs the adapter, leaves it out and shows a note in the status bar. When the crash came while the adapters were being listed (wgpu's Direct3D 12 backend creates a device on each GPU to list it), the next start lists OpenGL's adapters alone; on macOS, where wgpu has no OpenGL adapters, it lists them all. Later starts keep leaving them out until the app version or Preferences › Performance › Graphics Processor changes, a start shows its first frame on the adapter that crashed, or no adapter is left that can show the window. `WGPU_BACKEND` and `WGPU_ADAPTER_NAME` choose regardless of the file: a start with `WGPU_BACKEND=dx12` tries Direct3D 12 again, and when its first frame appears, the crash is cleared. A process ended from outside during the start (Task Manager, `kill`) counts as a crash. Runs without preferences (`VECTORCRAFT_NO_PREFS`) record nothing, and a start made while another copy of the app is starting neither reads nor writes the file. - **To recover from a Graphics Processor choice that doesn't work** without editing files: start once with `WGPU_POWER_PREF=low` (or `WGPU_ADAPTER_NAME=…`), which overrides the preference for that start while settings still save, and set Graphics Processor back to Automatic. `VECTORCRAFT_NO_PREFS=1` also starts without it, but saves nothing. @@ -109,6 +110,7 @@ When the interface thread stays in one part of a frame for 3 s (VectorCraft's ow | `WGPU_ADAPTER_NAME` | Graphics adapter by (part of) its name, any case (see [Desktop graphics processor](#desktop-graphics-processor)) | | `WGPU_BACKEND` | Graphics backends: `vulkan`, `dx12`, `metal`, `gl` | | `VECTORCRAFT_GPU_SKIP` | Set by the app when it starts again without a graphics adapter that failed (see [Desktop graphics processor](#desktop-graphics-processor)) | +| `VECTORCRAFT_GPU_SOFTWARE` | Set by the app, with `LIBGL_ALWAYS_SOFTWARE=1`, when it starts again on Mesa's software renderer because no graphics adapter could show the window (Linux and the BSDs; see [Desktop graphics processor](#desktop-graphics-processor)) | | `RUST_LOG` | Log levels for standard error and the log file (see [Logs](#logs)) | ## macOS: the menu bar From 5321337ce845efb5bef7834388b1d01bcb145742 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 06:42:57 -0800 Subject: [PATCH 2/4] Open: say when a file dialog is already open instead of waiting silently On some Wayland compositors the system file dialog can open as its own window out of sight. Pressing Open again on the Home screen then queued a second picker behind the first and showed nothing, so Open seemed to do nothing at all (#6160). - File > Open, Open With and Install Plug-in refuse a new picker while a file dialog is still open and say so in the status bar. - The Home screen's New, Open, template and Clear Recent buttons report a failed command in the status bar instead of dropping it. - An open picker that fails (the browser could not read the file) says why instead of being taken for a cancel. Part of #6160 --- crates/ui-egui/src/canvas/home.rs | 15 ++++++++++----- crates/ui-egui/src/io/open.rs | 9 ++++++++- crates/ui-egui/src/tests/home.rs | 20 ++++++++++++++++++++ crates/ui-egui/src/tests/picks.rs | 25 +++++++++++++++++++++++++ 4 files changed, 63 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/canvas/home.rs b/crates/ui-egui/src/canvas/home.rs index d95cdc02e1..5034e23f17 100644 --- a/crates/ui-egui/src/canvas/home.rs +++ b/crates/ui-egui/src/canvas/home.rs @@ -73,15 +73,20 @@ pub(super) fn home(app: &mut VectorcraftApp, ui: &mut Ui, rect: egui::Rect) { } } -/// What the start screen's user did. +/// What the start screen's user did. A command that fails says why in the status bar (#6160). fn run_action(app: &mut VectorcraftApp, action: StartAction) { + fn run(app: &mut VectorcraftApp, id: &str, params: serde_json::Value) { + if let Err(e) = app.run(id, params) { + app.status(e); + } + } match action { - StartAction::New => drop(app.run("file.newDialog", json!({}))), - StartAction::Open => drop(app.run("file.open", json!({}))), + StartAction::New => run(app, "file.newDialog", json!({})), + StartAction::Open => run(app, "file.open", json!({})), // A failure is reported to the user there. StartAction::OpenRecent(path) => drop(crate::io::open_reporting(app, &path.to_string_lossy())), - StartAction::UseTemplate(name) => drop(app.run("file.new", json!({ "preset": name }))), - StartAction::ClearRecent => drop(app.run("file.clearRecent", json!({}))), + StartAction::UseTemplate(name) => run(app, "file.new", json!({ "preset": name })), + StartAction::ClearRecent => run(app, "file.clearRecent", json!({})), StartAction::RemoveRecent(path) => app.ui.recent_files.retain(|recent| std::path::Path::new(recent) != path), StartAction::RevealRecent(path) => { // PLAN: `io::export` is a private module of `io`; `reveal_path` needs a re-export from io.rs (unowned). diff --git a/crates/ui-egui/src/io/open.rs b/crates/ui-egui/src/io/open.rs index 673f78af10..e5c59365b1 100644 --- a/crates/ui-egui/src/io/open.rs +++ b/crates/ui-egui/src/io/open.rs @@ -233,13 +233,19 @@ fn open_request<'a>(purpose: &str, folder: Option, filters: impl IntoIte /// Asks for a file to open with `request`; `then` gets its path. The web answers with the file's /// bytes, which open as File › Open opens them (the extension decides). A cancelled picker runs -/// nothing. While it is open the reply is `{pending: "fileDialog"}`. +/// nothing, and a picker that failed (the browser could not read the file) reports why. While it is +/// open the reply is `{pending: "fileDialog"}`. While another file dialog is still open, which can +/// be a window the system placed out of sight, the reply is an error saying so (#6160): a second +/// picker would only wait behind the first. fn ask_open( app: &mut VectorcraftApp, request: PickRequest, owner: Owner, then: impl FnOnce(&mut VectorcraftApp, String) -> Result + 'static, ) -> Result { + if app.file_dialog_open() { + return Err(file_asks::busy().into()); + } Ok(file_asks::ask(app, request, owner, move |app, picked| match picked { Picked::Contents(files) => { for (name, bytes) in &files { @@ -247,6 +253,7 @@ fn ask_open( } Ok(Value::Null) } + Picked::Failed(error) => Err(error), picked => match picked.first_path() { Some(path) => then(app, path.to_string_lossy().into_owned()), None => Err("cancelled".into()), diff --git a/crates/ui-egui/src/tests/home.rs b/crates/ui-egui/src/tests/home.rs index 5ccb6412a9..904de40932 100644 --- a/crates/ui-egui/src/tests/home.rs +++ b/crates/ui-egui/src/tests/home.rs @@ -125,6 +125,26 @@ fn home_screen(app: VectorcraftApp) -> Panel { home } +/// Home's Open while a file dialog is still open (a window the system may have placed out of sight) +/// says so in the status bar and asks for no second picker; once the first answers, Open asks again +/// (#6160). +#[test] +fn home_open_while_a_file_dialog_is_open_says_so() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + let picker = crate::tests::picks::scripted(&mut app); + let mut home = home_screen(app); + home.click("Open"); + assert_eq!(picker.requests().len(), 1); + assert!(home.app().ui.status.is_empty()); + home.click("Open"); + assert_eq!(picker.requests().len(), 1, "no second picker waits behind the first"); + assert_eq!(home.app().ui.status, crate::file_asks::busy()); + picker.cancel(); + crate::file_asks::poll(&mut home.app()); + home.click("Open"); + assert_eq!(picker.requests().len(), 2, "Open asks again once the first dialog answered"); +} + /// The Home screen lists the first recent files (#663); opening one that can't be opened says so. #[test] fn home_lists_recent_files_and_a_click_opens_one() { diff --git a/crates/ui-egui/src/tests/picks.rs b/crates/ui-egui/src/tests/picks.rs index 851d438904..1d521af1c0 100644 --- a/crates/ui-egui/src/tests/picks.rs +++ b/crates/ui-egui/src/tests/picks.rs @@ -49,6 +49,10 @@ impl Picker { pub(crate) fn cancel(&self) { self.files.answer(Picked::Cancelled); } + /// The newest open pick fails with `why`, as the browser's picker does when it cannot read the file. + pub(crate) fn fail(&self, why: &str) { + self.files.answer(Picked::Failed(why.into())); + } /// The bytes a save through the service (`Files::save`) wrote to `path`. pub(crate) fn file(&self, path: &str) -> Option> { self.files.file(std::path::Path::new(path)) @@ -197,6 +201,27 @@ fn app() -> VectorcraftApp { VectorcraftApp::new(Session::new(), Services::default()) } +/// File › Open and Install Plug-in ask for no second picker while a file dialog is still open, and +/// say so; an open picker that fails says why, and opens nothing (#6160). +#[test] +fn an_open_picker_is_refused_while_a_dialog_is_open_and_a_failed_one_says_why() { + for command in ["file.open", "ui.installPlugin"] { + let mut app = app(); + let picker = scripted(&mut app); + asks(&mut app, command); + for again in ["file.open", "ui.installPlugin"] { + assert_eq!(app.run(again, json!({})), Err(file_asks::busy().to_string()), "{again} after {command}"); + } + assert_eq!(picker.requests().len(), 1, "no second picker waits behind the first after {command}"); + picker.fail("the file could not be read"); + settle(&mut app); + assert_eq!(app.ui.status, "the file could not be read", "{command}"); + assert!(app.session.documents().is_empty(), "{command}"); + asks(&mut app, command); + assert_eq!(picker.requests().len(), 2, "{command} asks again once the first answered"); + } +} + /// The picks' answers, then the rest of a frame's pumps (Save Changes goes on once its save is written). fn settle(app: &mut VectorcraftApp) { let ctx = app.ui_ctx.clone().unwrap_or_default(); From 0b3cf56b81e34da4fcbe87566043f4bee16615bb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 06:59:34 -0800 Subject: [PATCH 3/4] Graphics: closing the window after a lost device no longer panics After the graphics device is lost, a frame the device could not present stays acquired by the window's surface. When the window closed, eframe released the surface, and wgpu's Vulkan backend panicked with "Trying to destroy a SwapchainAcquireSemaphore that is still in use by a SurfaceTexture" (gfx-rs/wgpu#9277), so the app stopped with an error. GraphicsLoss now remembers that a loss happened after the frame handled the report. When the window closes after a loss, the process ends in on_exit once the app has saved what it keeps on quitting, before the window's graphics are torn down, on every platform. This is the exit the macOS accessibility quit already takes (#661); a loss during start-up still goes to the adapter restart (#651). Fixes #6374 --- apps/vectorcraft/src/app.rs | 62 ++++++++++++++++++++++++++++------ crates/ui-egui/src/graphics.rs | 39 +++++++++++++++++++-- 2 files changed, 88 insertions(+), 13 deletions(-) diff --git a/apps/vectorcraft/src/app.rs b/apps/vectorcraft/src/app.rs index b91282e7da..791143bb42 100644 --- a/apps/vectorcraft/src/app.rs +++ b/apps/vectorcraft/src/app.rs @@ -1,4 +1,4 @@ -#[cfg(all(target_os = "macos", feature = "accessibility", feature = "wgpu"))] +#[cfg(feature = "wgpu")] use super::gpu; use super::nightly_session; use super::prefs::{flush, save_tick}; @@ -107,7 +107,7 @@ impl eframe::App for App { // Plug-ins still loading end before the launch marker does (the macOS exit below skips // dropping the app). self.app.session.cancel_plugin_loads(); - end_before_teardown(self.frames); + end_before_teardown(self.frames, self.graphics_loss.happened()); } } @@ -202,16 +202,58 @@ impl App { /// its own class, which AppKit's Touch Bar support was observing it under, and AppKit aborts the /// app as it quits on Macs with a Touch Bar. On a normal quit, only the launch marker is needed /// after the window, so it is ended here as `main` ends it after the window on other platforms. +/// On every platform, the process also ends here when the window's graphics device was lost +/// (`device_lost`, #6374). A frame the lost device could not present stays acquired, and releasing +/// the window's surface as eframe tears it down then panics in wgpu (gfx-rs/wgpu#9277). /// Not while the window is still starting up (`frames` below [`gpu::STARTUP_FRAMES`]): a graphics /// failure then starts the app again on another adapter (#651). -#[allow(unused_variables)] -fn end_before_teardown(frames: u64) { - #[cfg(all(target_os = "macos", feature = "accessibility", feature = "wgpu"))] - if frames >= gpu::STARTUP_FRAMES { - safe_mode::end_launch(); - log::info!("quitting"); - log::logger().flush(); - std::process::exit(0); +fn end_before_teardown(frames: u64, device_lost: bool) { + if !ends_before_teardown(frames, device_lost) { + return; + } + if device_lost { + log::info!("the graphics device was lost: quitting before the window's graphics are torn down"); + } + // `main` does these after the window, which this exit skips. + #[cfg(not(target_os = "macos"))] + single_instance::resign(); + safe_mode::end_launch(); + log::info!("quitting"); + log::logger().flush(); + std::process::exit(0); +} + +/// Whether [`end_before_teardown`] ends the process: after the window's start-up, on macOS with +/// accessibility, or once the graphics device was lost. +#[cfg(feature = "wgpu")] +fn ends_before_teardown(frames: u64, device_lost: bool) -> bool { + frames >= gpu::STARTUP_FRAMES && (device_lost || cfg!(all(target_os = "macos", feature = "accessibility"))) +} + +/// Without wgpu there is no device-lost report, and the window is torn down as usual. +#[cfg(not(feature = "wgpu"))] +fn ends_before_teardown(_frames: u64, _device_lost: bool) -> bool { + false +} + +#[cfg(all(test, feature = "wgpu"))] +mod tests { + use vectorcraft_ui_egui::graphics::GraphicsLoss; + + use super::*; + + /// A device lost while the app runs ends the process before eframe releases the window's + /// surface, on every platform; before the window has started, the start-up restart takes over. + #[test] + fn a_lost_graphics_device_ends_the_process_before_teardown() { + let always = cfg!(all(target_os = "macos", feature = "accessibility")); + let (loss, ctx) = (GraphicsLoss::default(), egui::Context::default()); + assert_eq!(ends_before_teardown(gpu::STARTUP_FRAMES, loss.happened()), always, "no loss: the usual teardown"); + let (l, c) = (loss.clone(), ctx.clone()); + std::thread::spawn(move || l.report(&c, "Unknown: Device is lost")).join().unwrap(); + assert!(loss.take().is_some(), "a frame handles the report"); + assert!(ends_before_teardown(gpu::STARTUP_FRAMES, loss.happened()), "after a loss the window is not torn down"); + assert!(!ends_before_teardown(gpu::STARTUP_FRAMES - 1, loss.happened()), "during start-up the adapter restart runs"); } } diff --git a/crates/ui-egui/src/graphics.rs b/crates/ui-egui/src/graphics.rs index 0ff54d12d3..27cf2c623c 100644 --- a/crates/ui-egui/src/graphics.rs +++ b/crates/ui-egui/src/graphics.rs @@ -10,6 +10,10 @@ //! - The web host then starts again with new graphics and a new egui context, handing it the same //! app. The app notices the new context and makes everything it uploaded to the old one again: //! its fonts and theme, the canvas, and every texture cache ([`TexCache`]). +//! - The desktop host can't give the window a new device. When the window closes after a loss +//! ([`GraphicsLoss::happened`]), the process ends once the app has saved what it keeps on +//! quitting, before the window's graphics are torn down: releasing a swapchain that still holds +//! a frame the lost device couldn't present panics in the graphics driver layer (#6374). use std::cell::{Cell, Ref, RefCell, RefMut}; use std::sync::atomic::{AtomicU64, Ordering}; @@ -20,7 +24,16 @@ use crate::VectorcraftApp; /// Raised by the host when the window's graphics device is lost (from any thread), read on the UI /// thread. Cheap to clone; the clones share the report. #[derive(Clone, Default)] -pub struct GraphicsLoss(Arc>>); +pub struct GraphicsLoss(Arc>); + +/// What a [`GraphicsLoss`] holds. +#[derive(Default)] +struct Loss { + /// The loss not handled yet, for [`GraphicsLoss::take`]. + why: Option, + /// A loss was reported at some point, handled or not. + happened: bool, +} impl GraphicsLoss { /// The graphics device was lost (`why`, for the log): the next frame of `ctx` handles it. A @@ -28,13 +41,23 @@ impl GraphicsLoss { pub fn report(&self, ctx: &egui::Context, why: impl Into) { let why = why.into(); log::error!("vectorcraft: the graphics device was lost: {why}"); - self.0.lock().unwrap_or_else(|e| e.into_inner()).get_or_insert(why); + { + let mut loss = self.0.lock().unwrap_or_else(|e| e.into_inner()); + loss.why.get_or_insert(why); + loss.happened = true; + } ctx.request_repaint(); } /// The loss reported since the last call, if any. pub fn take(&self) -> Option { - self.0.lock().unwrap_or_else(|e| e.into_inner()).take() + self.0.lock().unwrap_or_else(|e| e.into_inner()).why.take() + } + + /// Whether the device was lost at any point, a loss [`Self::take`] already handled included. + /// A window can't be given a new device, so once true this stays true. + pub fn happened(&self) -> bool { + self.0.lock().unwrap_or_else(|e| e.into_inner()).happened } } @@ -190,6 +213,16 @@ mod tests { assert_eq!(loss.take(), None, "handled once"); } + #[test] + fn a_handled_loss_is_still_known_when_the_window_closes() { + let (loss, ctx) = (GraphicsLoss::default(), crate::testing::ui_context()); + assert!(!loss.happened(), "nothing lost yet"); + let (l, c) = (loss.clone(), ctx.clone()); + std::thread::spawn(move || l.report(&c, "Unknown: Device is lost")).join().unwrap(); + assert!(loss.take().is_some(), "the next frame handles it"); + assert!(loss.happened(), "the device stays lost after the frame handled the report"); + } + #[test] fn a_tex_cache_empties_when_the_ui_moves_to_a_new_context() { thread_local! { From 452281a2694aa938fc5ffa83c736f9bc6c4be9f8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 09:33:37 -0800 Subject: [PATCH 4/4] Smooth Bridge: a selected group of circles is bridged Smooth Bridge refused a selected group with "select two or more circles to bridge", even when every object in the group was a circle, so grouping circles first and selecting the group did nothing. The command now takes the objects inside each selected group (at any depth; a clipping group stays one object), so a group of circles is bridged in place, inside the group. A group that holds anything other than a circle is still refused, as before. The dialog's Reach field counts a selected group's objects too, so it is available when a selected group holds three or more circles; a circle selected together with its group counts once. --- .../engine/src/cmd/addons/pathtools/bridge.rs | 24 ++++++-- .../src/cmd/addons/pathtools/bridge/tests.rs | 57 +++++++++++++++++++ crates/ui-egui/src/addons/pathtools/bridge.rs | 52 ++++++++++++++++- docs/mcp.md | 8 ++- 4 files changed, 132 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/cmd/addons/pathtools/bridge.rs b/crates/engine/src/cmd/addons/pathtools/bridge.rs index 4d4eb9cdf8..457114f820 100644 --- a/crates/engine/src/cmd/addons/pathtools/bridge.rs +++ b/crates/engine/src/cmd/addons/pathtools/bridge.rs @@ -3,7 +3,7 @@ //! the bridges connect, replacing the circles or added above them. use serde_json::{Value, json}; -use vectorcraft_doc::{NodeId, NodeKind}; +use vectorcraft_doc::{Document, Node, NodeId, NodeKind}; use vectorcraft_geom::PathData; use vectorcraft_pathops::addons::pathtools as pt; @@ -34,7 +34,7 @@ pub(super) fn specs() -> Vec { "Smooth Bridge", ["Object", "Plug-ins", "Path Precision Tools"], None, - "{radius?: % 1..1000 (100; the radius of each bridge's two arcs as a percentage of the smaller circle's radius: larger makes a wider, gentler bridge), gap?: pt 0..1000 (instead of radius: the arcs' radius is the smaller circle's radius plus this gap, so each arc stays this gap away from a circle of the smaller circle's size about the arc's center; for equal circles this gap apart that is where a third circle this gap from both sits, as in a triangular grid, so the channels around an empty place in such a grid are one width; giving both is an error), reach?: pt 0..10000 (10; with three or more circles: how far apart two circles' outlines may be for a bridge between them, overlapping ones included; two circles are bridged at any distance), keepOriginals?: bool (false: each outline replaces its circles, painted as the topmost of them; true: it goes directly above that circle and the circles stay), ids?: [id] (default: the selection)} join circles (paths whose outline is a circle, not hidden or locked) into metaball (aka meatball) shapes. Two circles become one closed outline: around each circle on its side away from the other, and along two concave arcs, one on each side, that touch both circles so the outline runs on smoothly into them. With three or more, every two circles within reach are bridged the same way, and the bridges that connect are united into one shape each (holes smaller than 1% of the smallest circle's area are filled); a pair within reach but too far apart for the radius gets no bridge, and so does one whose neck would be thinner than the precision its shape is united at, and a circle bridged to no other is left as it is. Overlapping and touching circles are joined too. One circle inside another (among three or more, any such pair within reach) is an error; so are two circles too far apart for the radius (the arcs would not reach both, or would cross), or three or more with no pair the arcs can join, which suggests a larger radius or gap when the largest one would bridge them; so are no two circles within reach, more than 2000 circles and more than 8000 bridges. One undo step; the outlines (and the circles left as they are) are selected → {ids, alone}, with {id} too for two circles", + "{radius?: % 1..1000 (100; the radius of each bridge's two arcs as a percentage of the smaller circle's radius: larger makes a wider, gentler bridge), gap?: pt 0..1000 (instead of radius: the arcs' radius is the smaller circle's radius plus this gap, so each arc stays this gap away from a circle of the smaller circle's size about the arc's center; for equal circles this gap apart that is where a third circle this gap from both sits, as in a triangular grid, so the channels around an empty place in such a grid are one width; giving both is an error), reach?: pt 0..10000 (10; with three or more circles: how far apart two circles' outlines may be for a bridge between them, overlapping ones included; two circles are bridged at any distance), keepOriginals?: bool (false: each outline replaces its circles, painted as the topmost of them; true: it goes directly above that circle and the circles stay), ids?: [id] (default: the selection; a group, other than a clipping group, gives the objects inside it)} join circles (paths whose outline is a circle, not hidden or locked) into metaball (aka meatball) shapes. Two circles become one closed outline: around each circle on its side away from the other, and along two concave arcs, one on each side, that touch both circles so the outline runs on smoothly into them. With three or more, every two circles within reach are bridged the same way, and the bridges that connect are united into one shape each (holes smaller than 1% of the smallest circle's area are filled); a pair within reach but too far apart for the radius gets no bridge, and so does one whose neck would be thinner than the precision its shape is united at, and a circle bridged to no other is left as it is. Overlapping and touching circles are joined too. One circle inside another (among three or more, any such pair within reach) is an error; so are two circles too far apart for the radius (the arcs would not reach both, or would cross), or three or more with no pair the arcs can join, which suggests a larger radius or gap when the largest one would bridge them; so are no two circles within reach, more than 2000 circles and more than 8000 bridges. One undo step; the outlines (and the circles left as they are) are selected → {ids, alone}, with {id} too for two circles", has_selection, bridge )] @@ -54,8 +54,8 @@ fn bridge(s: &mut Session, p: &Value) -> Result { None => pt::ArcRadius::Share(percent.unwrap_or(RADIUS) / 100.0), }; let keep = switch_or(p, "keepOriginals", false, C)?; - let mut roots = checked_ids_or_selection(s, p, C)?; - // An id given twice is one circle. + let mut roots = members(&s.doc()?.doc, &checked_ids_or_selection(s, p, C)?); + // An id given twice, or a circle given with its group, is one circle. roots.sort_unstable(); roots.dedup(); if roots.len() > pt::MAX_BRIDGED_CIRCLES { @@ -140,6 +140,22 @@ fn bridge(s: &mut Session, p: &Value) -> Result { Ok(out) } +/// The objects `ids` names, with each group among them (a clipping group excepted) as the objects +/// inside it, at any depth. +fn members(d: &Document, ids: &[NodeId]) -> Vec { + fn visit(n: &Node, out: &mut Vec) { + match &n.kind { + NodeKind::Group { children, clip: false } => children.iter().for_each(|c| visit(c, out)), + _ => out.push(n.id), + } + } + let mut out = vec![]; + for n in ids.iter().filter_map(|&id| d.node(id)) { + visit(n, &mut out); + } + out +} + /// The ids of `circles` at indices `at`, in paint order (the circles are listed in paint order). fn roots_of(circles: &[(NodeId, pt::Circle)], at: &[usize]) -> Vec { at.iter().filter_map(|&i| circles.get(i)).map(|(id, _)| *id).collect() diff --git a/crates/engine/src/cmd/addons/pathtools/bridge/tests.rs b/crates/engine/src/cmd/addons/pathtools/bridge/tests.rs index 745f216b68..8409ac2be6 100644 --- a/crates/engine/src/cmd/addons/pathtools/bridge/tests.rs +++ b/crates/engine/src/cmd/addons/pathtools/bridge/tests.rs @@ -354,3 +354,60 @@ fn locked_and_hidden_circles_are_not_bridged() { s.execute("object.hide", &json!({})).unwrap(); assert!(err(&mut s, json!({"ids": [a.0, b.0]})).contains("select two or more circles to bridge")); } + +fn group(s: &mut Session, ids: &[NodeId]) -> NodeId { + NodeId(s.execute("object.group", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})).unwrap()["id"].as_u64().unwrap()) +} + +fn children(s: &Session, id: NodeId) -> Vec { + s.doc().unwrap().doc.node(id).unwrap().children().unwrap().iter().map(|n| n.id).collect() +} + +#[test] +fn a_selected_group_of_circles_bridges_the_circles_inside_it() { + let mut s = session(); + let a = circle(&mut s, 100.0, 100.0, 20.0); + let b = circle(&mut s, 160.0, 100.0, 20.0); + let g = group(&mut s, &[a, b]); + select(&mut s, &[g]); + let steps = s.doc().unwrap().history.undo.len(); + let r = s.execute(BRIDGE, &json!({})).unwrap(); + assert_eq!(r["id"], json!(b.0), "two circles, joined in the upper one's place"); + assert_eq!(top_level(&s), [g]); + assert_eq!(children(&s, g), [b], "the outline stays in the group"); + assert!(area(&s, b) > 2.0 * std::f64::consts::PI * 400.0); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "one undo step"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(children(&s, g), [a, b]); + + // A group inside a group, given with one of its own circles, and a loose circle: three circles, so the reach + // applies. + let c = circle(&mut s, 300.0, 100.0, 20.0); + let outer = group(&mut s, &[g]); + let r = s.execute(BRIDGE, &json!({"ids": [outer.0, a.0, c.0], "reach": 30})).unwrap(); + assert_eq!(r["ids"], json!([b.0]), "the grouped circles are joined"); + assert_eq!(r["alone"], json!([c.0]), "the far circle is out of reach"); +} + +#[test] +fn a_selected_group_with_other_objects_or_a_clipping_group_is_refused() { + let mut s = session(); + let a = circle(&mut s, 100.0, 100.0, 20.0); + let b = circle(&mut s, 160.0, 100.0, 20.0); + let square = NodeId(s.execute("shape.rectangle", &json!({"x": 200, "y": 200, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap()); + let g = group(&mut s, &[a, b, square]); + let steps = s.doc().unwrap().history.undo.len(); + assert!(err(&mut s, json!({"ids": [g.0]})).contains("select two or more circles to bridge")); + assert_eq!(children(&s, g), [a, b, square]); + assert_eq!(s.doc().unwrap().history.undo.len(), steps, "nothing changed, no undo step"); + + let mut s = session(); + let a = circle(&mut s, 100.0, 100.0, 20.0); + let b = circle(&mut s, 160.0, 100.0, 20.0); + let mask = circle(&mut s, 130.0, 100.0, 80.0); + select(&mut s, &[a, b, mask]); + let clip = NodeId(s.execute("object.clippingMask.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + let before = top_level(&s); + assert!(err(&mut s, json!({"ids": [clip.0]})).contains("select two or more circles to bridge")); + assert_eq!(top_level(&s), before); +} diff --git a/crates/ui-egui/src/addons/pathtools/bridge.rs b/crates/ui-egui/src/addons/pathtools/bridge.rs index 76b3627f76..9cdf738b18 100644 --- a/crates/ui-egui/src/addons/pathtools/bridge.rs +++ b/crates/ui-egui/src/addons/pathtools/bridge.rs @@ -40,8 +40,8 @@ fn params(fields: &DialogFields) -> Value { /// Opens Smooth Bridge's dialog on the command's defaults. pub(crate) fn open(app: &mut VectorcraftApp) -> Result { // The reach applies to three or more circles; two are bridged at any distance. Counted once, before a preview - // replaces the selection with its result. - let many = app.session.doc().map(|doc| doc.selection.objects.len() > 2).unwrap_or(true); + // replaces the selection with its result, with a selected group counting the objects inside it. + let many = app.session.doc().map(|doc| members(&doc.doc, &doc.selection.objects) > 2).unwrap_or(true); let fields = DialogFields::from_pairs([ ("radius", FieldValue::Number(RADIUS)), ("constantGap", FieldValue::Bool(false)), @@ -72,6 +72,24 @@ pub(crate) fn open(app: &mut VectorcraftApp) -> Result { }) } +/// How many objects the command bridges for objects `ids`: each one, or for a group (a clipping group excepted) the +/// objects inside it, at any depth; an object given twice, or with its group, counts once. +fn members(doc: &vectorcraft_doc::Document, ids: &[vectorcraft_doc::NodeId]) -> usize { + fn visit(n: &vectorcraft_doc::Node, out: &mut std::collections::BTreeSet) { + match &n.kind { + vectorcraft_doc::NodeKind::Group { children, clip: false } => children.iter().for_each(|c| visit(c, out)), + _ => { + out.insert(n.id); + } + } + } + let mut out = std::collections::BTreeSet::new(); + for n in ids.iter().filter_map(|&id| doc.node(id)) { + visit(n, &mut out); + } + out.len() +} + #[cfg(test)] mod tests { use serde_json::{Value, json}; @@ -158,6 +176,36 @@ mod tests { assert_eq!(geometry(&panel.app()), original); } + #[test] + fn reach_counts_the_circles_inside_a_selected_group() { + use crate::tests::panel_harness::Panel; + + for (xs, many) in [(&[100.0, 124.0][..], false), (&[100.0, 124.0, 148.0][..], true)] { + let mut app = bridge_app(xs); + let ids: Vec = app.session.doc().unwrap().selection.objects.iter().map(|id| id.0).collect(); + let group = app.run("object.group", json!({ "ids": ids })).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [group]})).unwrap(); + let mut panel = Panel::new(app, crate::tests::picks::dialogs); + menus::invoke(&mut panel.app(), super::COMMAND, Value::Null); + panel.frame(); + assert_eq!(panel.enabled("Reach"), many, "{} circles in the group", xs.len()); + panel.click("OK"); + panel.frame(); + let inside = panel.app().session.doc().unwrap().doc.node(vectorcraft_doc::NodeId(group)).unwrap().children().unwrap().len(); + assert_eq!(inside, 1, "the circles in the group became one shape"); + } + // A group of two circles selected together with one of them: still two circles. + let mut app = bridge_app(&[100.0, 124.0]); + let ids: Vec = app.session.doc().unwrap().selection.objects.iter().map(|id| id.0).collect(); + let group = app.run("object.group", json!({ "ids": ids })).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [group, ids[0]]})).unwrap(); + assert_eq!(app.session.doc().unwrap().selection.objects.len(), 2); + let mut panel = Panel::new(app, crate::tests::picks::dialogs); + menus::invoke(&mut panel.app(), super::COMMAND, Value::Null); + panel.frame(); + assert!(!panel.enabled("Reach"), "a circle selected with its group counts once"); + } + #[test] fn constant_gap_shows_the_gap_and_bridges_many_circles_within_reach() { let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())); diff --git a/docs/mcp.md b/docs/mcp.md index a7fec3009e..7d8a3743ed 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -16843,8 +16843,9 @@ Commands: drawn, and the path's fills stay on it, below its dashes (a path without fills goes). A compound path's dashes are plain paths with its appearance. Paths without a dashed stroke stay as they are, and it is an error if none has one. The dashes are selected; more than 100,000 (or a pattern too fine to draw) is refused. → `{ids, dashes}`. -- `addon.pathtools.bridge {radius?, gap?, reach?, keepOriginals?, ids?}` joins circles (`ids`, default: the selection; - paths whose outline is a circle, not hidden or locked) into metaball (aka meatball) shapes, as one undo step (Object › +- `addon.pathtools.bridge {radius?, gap?, reach?, keepOriginals?, ids?}` joins circles (`ids`, default: the selection, + with a group other than a clipping group giving the objects inside it at any depth, which must all be circles; paths + whose outline is a circle, not hidden or locked) into metaball (aka meatball) shapes, as one undo step (Object › Plug-ins › Path Precision Tools › Smooth Bridge…). Two circles become one closed outline that goes around each circle on its side away from the other and along two concave arcs, one on each side of the line through the centers, each touching both circles from outside, so every anchor is smooth. `radius` is the arcs' radius as a percentage of the @@ -16870,7 +16871,8 @@ Commands: only when the largest would bridge a pair of them under these rules), when no two circles are within reach, and above 2,000 circles or 8,000 bridges. → `{ids, alone}`: the shapes and the circles left as they are, with `id` as well for two circles. Smooth Bridge… opens a dialog (`ui.menuDialog {command}`, kind `smoothBridge`) with Constant Gap (a Gap field in place of the Radius field in - percent), Reach (unavailable with two circles selected), Keep Originals and Preview. + percent), Reach (unavailable when the selection, a selected group's objects counted, holds two objects), Keep Originals + and Preview. - `addon.pathtools.tangentCircle {ids?, radius?, circle?}` draws the circles that touch two paths or compound paths and have `radius` (0.01 to 1,000,000 pt, needed with two), or that touch three (which set the radius themselves, so `radius` is then an error), as one undo step (Object › Plug-ins › Path Precision Tools › Tangent Circle…). `ids`