diff --git a/Cargo.lock b/Cargo.lock index 170ad40f3d..5aff7bd0a3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -9049,6 +9049,7 @@ dependencies = [ "vectorcraft-effects", "vectorcraft-geom 0.25.1", "vectorcraft-pathops 0.25.1", + "vectorcraft-render", "vectorcraft-testkit", "vectorcraft-text", ] diff --git a/apps/vectorcraft/src/app.rs b/apps/vectorcraft/src/app.rs index 791143bb42..2715e08125 100644 --- a/apps/vectorcraft/src/app.rs +++ b/apps/vectorcraft/src/app.rs @@ -44,7 +44,7 @@ impl eframe::App for App { if let Some(window_frame) = self.window_frame.as_mut() { window_frame(); } - // The characters Alt + keypad codes typed (#5108). + // The keypad digits of Alt + keypad codes leave the frame (#5108). #[cfg(windows)] super::windows_alt_codes::raw_input_hook(raw); // Symbol-font characters a keyboard tool typed (NHM Writer legacy Tamil). 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..b603ed7960 100644 --- a/apps/vectorcraft/src/main.rs +++ b/apps/vectorcraft/src/main.rs @@ -396,15 +396,36 @@ fn read_command_line( /// Whether the window opens through XWayland, for Linux Display Server `pref` (`main`). #[cfg(target_os = "linux")] fn opens_through_xwayland(pref: Option<&str>) -> bool { - if !xwayland::wanted(pref, |name| std::env::var_os(name), xwayland::pen_attached) { + use xwayland::Choice; + let choice = xwayland::choose(pref, |name| std::env::var_os(name), xwayland::pen_attached); + // On native Wayland winit 0.30 receives no pen input, so the log says why the window stays there. + match &choice { + Choice::NotWayland | Choice::Chosen | Choice::Pen(_) => {} + Choice::NoXDisplay { x11: true } => { + log::warn!("Linux Display Server is X11, but there is no X display (DISPLAY is unset): opening the window on Wayland") + } + Choice::NoXDisplay { x11: false } => log::info!( + "opening the window on Wayland, where a pen does not reach it: there is no X display (DISPLAY is unset) to open it through XWayland" + ), + Choice::NativeWayland => log::info!("VECTORCRAFT_NATIVE_WAYLAND is set: opening the window on Wayland, where a pen does not reach it"), + Choice::NoPen => log::info!("no pen in /proc/bus/input/devices: opening the window on Wayland"), + Choice::NoDeviceList(e) => log::warn!("can't look for a pen ({e}): opening the window on Wayland, where a pen does not reach it"), + } + if !choice.xwayland() { return false; } if !xwayland::x11_libraries_found() { - log::warn!("Linux Display Server is X11, but the X11 libraries aren't all installed: opening the window on Wayland"); + if let Choice::Pen(name) = &choice { + log::warn!( + "pen found ({name}), but the X11 libraries aren't all installed: opening the window on Wayland, where the pen does not reach it" + ); + } else { + log::warn!("Linux Display Server is X11, but the X11 libraries aren't all installed: opening the window on Wayland"); + } return false; } - if pref != Some("x11") { - log::info!("pen found: opening the window through XWayland, where the pen works (VECTORCRAFT_NATIVE_WAYLAND=1 keeps Wayland)"); + if let Choice::Pen(name) = &choice { + log::info!("pen found ({name}): opening the window through XWayland, where the pen works (VECTORCRAFT_NATIVE_WAYLAND=1 keeps Wayland)"); } else { log::info!("opening the window through XWayland (Preferences › Performance › Linux Display Server)"); } @@ -722,14 +743,14 @@ fn main() -> std::process::ExitCode { // With Windows Ink, winit reports a pen as a touch and drops its barrel button and which end // is down; the message hook notes each pointer contact and whether it starts with the barrel // button held, and writes the pen's end into the pen feed (`windows_stylus`). It also notes the - // characters Alt + keypad codes type (`windows_alt_codes`). + // keypad digits of Alt + keypad codes (`windows_alt_codes`). #[cfg(windows)] let options = { use winit::platform::windows::EventLoopBuilderExtWindows as _; let mut options = options; options.event_loop_builder = Some(Box::new(|builder| { builder.with_msg_hook(|msg| { - // Alt + keypad codes (#5108), which winit drops; neither hook consumes a message. + // Alt + keypad codes (#5108); neither hook consumes a message. windows_alt_codes::msg_hook(msg); windows_stylus::msg_hook(msg) }); @@ -920,7 +941,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/apps/vectorcraft/src/tablet.rs b/apps/vectorcraft/src/tablet.rs index 4dd8f7d9ec..2c6a8b68c1 100644 --- a/apps/vectorcraft/src/tablet.rs +++ b/apps/vectorcraft/src/tablet.rs @@ -41,7 +41,7 @@ //! the rotation's range is 0°, and an axis a pen lacks reads nothing. #![cfg_attr(not(target_os = "linux"), allow(dead_code))] -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use craft::behavior::PointerSample; use craft::ui::runtime::pen::PenSource; @@ -189,6 +189,8 @@ enum Update { struct Pens { devices: HashMap, last: HashMap; 5]>, + /// The pens an event has come from, for the log. + heard: HashSet, } impl Pens { @@ -197,10 +199,37 @@ impl Pens { /// same id starts without them. fn set_devices(&mut self, devices: impl IntoIterator) { let devices: HashMap = devices.into_iter().take(MAX_DEVICES).map(|d| (d.id, d)).collect(); - self.last.retain(|id, _| devices.get(id).is_some_and(|d| self.devices.get(id) == Some(d))); + let unchanged = |id: &u16| devices.get(id).is_some_and(|d| self.devices.get(id) == Some(d)); + self.last.retain(|id, _| unchanged(id)); + self.heard.retain(|id| unchanged(id)); self.devices = devices; } + /// The names of the pens listed, by device id, for the log. + fn pen_names(&self) -> Vec<&str> { + let mut pens: Vec<&Device> = self.devices.values().filter(|d| d.is_pen()).collect(); + pens.sort_by_key(|d| d.id); + pens.into_iter().map(|d| d.name.as_str()).collect() + } + + /// The pens listed, as the log line says it: under XWayland on a Wayland session this tells + /// whether XWayland lists the pen at all (#5622). + fn summary(&self) -> String { + let names = self.pen_names(); + if names.is_empty() { + "the X server lists no pen (a pointer device with an \"Abs Pressure\" valuator): a pen draws at full pressure".to_string() + } else { + format!("pens listed: {}", names.join(", ")) + } + } + + /// The name of pen `id` when this is the first event from it since it was listed, for the log: + /// it tells whether the pen's events reach the app at all. + fn first_event(&mut self, id: u16) -> Option<&str> { + let device = self.devices.get(&id).filter(|d| d.is_pen())?; + self.heard.insert(id).then_some(device.name.as_str()) + } + /// A raw motion or button event of device `id`, with the valuators that changed. fn handle(&mut self, id: u16, valuators: impl IntoIterator) -> Update { let Some(device) = self.devices.get(&id) else { return Update::Keep }; @@ -231,6 +260,9 @@ impl Pens { /// A raw event as the X server sends it: its valuator mask and the values of the valuators /// set in it. A pen's sample or another pointer's `None` goes into `pen`. fn raw_event(&mut self, pen: &PenSource, id: u16, mask: &[u32], values: &[f64]) { + if let Some(name) = self.first_event(id) { + log::info!("tablet: events arrive from the pen {name:?}"); + } if let Update::Set(sample) = self.handle(id, valuators(mask, values)) { pen.set(sample); } @@ -304,6 +336,7 @@ mod x11 { .map_err(|e| format!("XISelectEvents failed: {e}"))?; let mut pens = Pens::default(); pens.set_devices(query_devices(&conn)); + log::info!("tablet: {}", pens.summary()); std::thread::Builder::new() .name("vectorcraft-tablet-x11".into()) .spawn(move || run(&conn, &mut pens, &pen)) @@ -321,7 +354,14 @@ mod x11 { let values: Vec = e.axisvalues.iter().map(|v| fp3232(v.integral, v.frac)).collect(); pens.raw_event(pen, e.deviceid, &e.valuator_mask, &values); } - Event::XinputHierarchy(_) | Event::XinputDeviceChanged(_) => pens.set_devices(query_devices(conn)), + Event::XinputHierarchy(_) | Event::XinputDeviceChanged(_) => { + let before = pens.summary(); + pens.set_devices(query_devices(conn)); + let after = pens.summary(); + if after != before { + log::info!("tablet: {after}"); + } + } _ => {} } } @@ -623,6 +663,31 @@ mod tests { assert!(s.pressure < 0.001, "{}", s.pressure); } + /// #5622: the log names the pens the X server lists (XWayland's included) and the first event + /// from each, once, again after the pen is listed anew, and never for a mouse. + #[test] + fn the_log_names_the_pens_listed_and_the_first_event_from_each() { + let stylus = Device::new(11, "xwayland-tablet stylus:16", Some("xwayland-tablet stylus"), pen_valuators()); + let eraser = Device::new(12, "xwayland-tablet eraser:16", Some("xwayland-tablet eraser"), pen_valuators()); + let mut pens = Pens::default(); + assert!(pens.summary().contains("lists no pen"), "{}", pens.summary()); + pens.set_devices([eraser.clone(), mouse(4), stylus.clone()]); + assert_eq!(pens.summary(), "pens listed: xwayland-tablet stylus:16, xwayland-tablet eraser:16"); + assert_eq!(pens.first_event(11), Some("xwayland-tablet stylus:16")); + assert_eq!(pens.first_event(11), None, "once"); + assert_eq!(pens.first_event(4), None, "a mouse"); + assert_eq!(pens.first_event(99), None, "a device not listed"); + // Listed again unchanged: still heard. Another device under the same id: heard anew. + pens.set_devices([eraser.clone(), mouse(4), stylus]); + assert_eq!(pens.first_event(11), None); + pens.set_devices([eraser, mouse(4), pen(11)]); + assert_eq!(pens.first_event(11), Some("Wacom Intuos Pro M Pen stylus")); + // The events go into the feed as before. + let source = PenSource::default(); + pens.raw_event(&source, 12, &[0b100], &[65535.0]); + assert_eq!(source.current().map(|s| (s.eraser, s.pressure)), Some((true, 1.0))); + } + #[test] fn fixed_point_values() { assert_eq!(fp3232(3, 1 << 31), 3.5); diff --git a/apps/vectorcraft/src/windows_alt_codes.rs b/apps/vectorcraft/src/windows_alt_codes.rs index 0abf65ddc9..c358a65653 100644 --- a/apps/vectorcraft/src/windows_alt_codes.rs +++ b/apps/vectorcraft/src/windows_alt_codes.rs @@ -4,14 +4,12 @@ //! Windows does the work: when Alt comes up after keypad digits, `TranslateMessage` posts a //! `WM_CHAR` holding the character the code stands for (in the system's ANSI code page for a code //! with a leading 0, else its OEM code page), the convention every Windows text field follows -//! (). winit -//! 0.30 reads a `WM_CHAR` only as part of the key press before it, so it drops this one, which -//! follows a key release, and egui never sees the text. winit's message hook ([`msg_hook`]) sees -//! the message before winit handles it: [`AltCodes`] notes keypad digits typed with Alt held, takes -//! the character that follows Alt's release, and [`raw_input_hook`] hands it to the frame as typed -//! text, so the Type tool (or a panel's text field) types it like any other character, in the -//! same undo step as the typing round it. The keypad digits themselves are taken out of the frame, -//! so they don't run a shortcut bound to Alt and a digit. +//! (). winit reports +//! that character as a key press of its own with the character as its text (storytold/winit W36), +//! so egui types it like any other character. Each keypad digit typed with Alt held also arrives +//! as Alt and a digit, which would run a shortcut bound to Alt and that digit: winit's message +//! hook ([`msg_hook`]) sees each message before winit handles it, [`AltCodes`] notes the keypad +//! digits typed with Alt held, and [`raw_input_hook`] takes them out of the frame. //! //! With NumLock off the keypad keys arrive as Insert, End, Down, Page Down, Left, Clear, Right, //! Home, Up and Page Up, and Windows still composes the code from them. They are told from the @@ -29,11 +27,11 @@ use std::cell::RefCell; use egui::{Event, Key}; +#[cfg(windows)] const WM_KEYDOWN: u32 = 0x0100; -const WM_KEYUP: u32 = 0x0101; -const WM_CHAR: u32 = 0x0102; const WM_SYSKEYDOWN: u32 = 0x0104; const WM_SYSKEYUP: u32 = 0x0105; +#[cfg(windows)] const WM_SYSCHAR: u32 = 0x0106; /// `VK_NUMPAD0` to `VK_NUMPAD9` (`winuser.h`): keypad digits with NumLock on. const VK_NUMPAD0: usize = 0x60; @@ -49,25 +47,15 @@ const DIGIT_KEYS: [Key; 10] = [Key::Num0, Key::Num1, Key::Num2, Key::Num3, Key:: /// Bit 24 of a key message's `lParam`: an extended key, such as the navigation keys beside the /// keypad (the keypad's own keys clear it). const EXTENDED_KEY: isize = 1 << 24; -/// `VK_MENU`, `VK_LMENU` and `VK_RMENU`: Alt. -const ALT_KEYS: [usize; 3] = [0x12, 0xA4, 0xA5]; thread_local! { /// The UI thread's sequence: [`msg_hook`] and [`raw_input_hook`] both run on it. static CODES: RefCell = RefCell::new(AltCodes::default()); } -/// Where an Alt + keypad code stands, from the keyboard messages of the thread's queue. +/// The keypad digits typed with Alt held, from the keyboard messages of the thread's queue. #[derive(Default)] struct AltCodes { - /// Keypad digits typed while Alt has been held. - digits: usize, - /// Alt came up after keypad digits: the next character message is the code's character. - armed: bool, - /// A high surrogate waiting for its low half. - high: Option, - /// Characters the codes typed, for the next frame. - typed: String, /// The digits of the keypad presses and releases with Alt held since the last frame, which /// egui reports as Alt and a digit (or, with NumLock off, Alt and a navigation key): taken /// out of the frame. @@ -88,80 +76,45 @@ fn keypad_digit(wparam: usize, lparam: isize) -> Option { impl AltCodes { /// Note a keyboard message `message` with `wparam` (the virtual-key code, or a UTF-16 unit) - /// and `lparam` (its flags). + /// and `lparam` (its flags). Windows sends a key pressed or released with Alt held as a system + /// key. fn message(&mut self, message: u32, wparam: usize, lparam: isize) { - let keypad = match message { - WM_SYSKEYDOWN | WM_SYSKEYUP => keypad_digit(wparam, lparam), - _ => None, - }; - if let Some(d) = keypad { - // Windows sends a key pressed with Alt held as a system key. - if message == WM_SYSKEYDOWN { - self.digits += 1; - self.armed = false; - } + if matches!(message, WM_SYSKEYDOWN | WM_SYSKEYUP) + && let Some(d) = keypad_digit(wparam, lparam) + { self.keypad_events.push(d); - return; - } - match message { - WM_KEYDOWN | WM_SYSKEYDOWN if ALT_KEYS.contains(&wparam) => {} - // Any other key ends the sequence and keeps its own meaning. - WM_KEYDOWN | WM_SYSKEYDOWN => self.reset(), - WM_KEYUP | WM_SYSKEYUP if ALT_KEYS.contains(&wparam) => { - self.armed = self.digits > 0; - self.digits = 0; - } - WM_CHAR | WM_SYSCHAR if self.armed => { - let unit = (wparam & 0xffff) as u16; - if (0xd800..0xdc00).contains(&unit) { - self.high = Some(unit); - return; - } - let units: Vec = self.high.take().into_iter().chain([unit]).collect(); - self.typed.extend(char::decode_utf16(units).filter_map(Result::ok).filter(|c| !c.is_control())); - self.armed = false; - } - _ => {} } } - fn reset(&mut self) { - self.digits = 0; - self.armed = false; - self.high = None; - } - - /// Hand the frame `events` the characters typed since the last frame, as typed text, and take - /// out the keypad digits typed with Alt held. + /// Take out of the frame `events` the keypad digits typed with Alt held since the last frame. + /// The character a code types comes from winit, as typed text. fn drain(&mut self, events: &mut Vec) { let mut keypad = std::mem::take(&mut self.keypad_events); - if !keypad.is_empty() { - events.retain(|e| { - let Event::Key { key, modifiers, .. } = e else { - return true; - }; - if !modifiers.alt { - return true; - } - // The first keypad key still to take out that egui reports as `key`. - let stands_for = |d: &usize| DIGIT_KEYS.get(*d) == Some(key) || NUMLOCK_OFF_EGUI_KEYS.get(*d) == Some(key); - match keypad.iter().position(stands_for) { - Some(i) => { - keypad.remove(i); - false - } - None => true, - } - }); - } - if !self.typed.is_empty() { - events.push(Event::Text(std::mem::take(&mut self.typed))); + if keypad.is_empty() { + return; } + events.retain(|e| { + let Event::Key { key, modifiers, .. } = e else { + return true; + }; + if !modifiers.alt { + return true; + } + // The first keypad key still to take out that egui reports as `key`. + let stands_for = |d: &usize| DIGIT_KEYS.get(*d) == Some(key) || NUMLOCK_OFF_EGUI_KEYS.get(*d) == Some(key); + match keypad.iter().position(stands_for) { + Some(i) => { + keypad.remove(i); + false + } + None => true, + } + }); } } -/// winit's message hook for the keyboard: notes Alt + keypad codes and the characters they type, -/// and hands each message to `windows_symbol_chars`. It never consumes the message. +/// winit's message hook for the keyboard: notes the keypad digits typed with Alt held, and hands +/// each message to `windows_symbol_chars`. It never consumes the message. #[cfg(windows)] #[allow(unsafe_code)] pub fn msg_hook(msg: *const std::ffi::c_void) { @@ -182,7 +135,7 @@ pub fn msg_hook(msg: *const std::ffi::c_void) { } } -/// Before egui reads the main window's frame: the characters Alt + keypad codes typed, as text. +/// Before egui reads the main window's frame: the keypad digits typed with Alt held are taken out. pub fn raw_input_hook(raw: &mut egui::RawInput) { CODES.with(|c| { if let Ok(mut c) = c.try_borrow_mut() { @@ -196,6 +149,9 @@ mod tests { use super::*; const ALT: usize = 0x12; + const WM_KEYDOWN: u32 = 0x0100; + const WM_KEYUP: u32 = 0x0101; + const WM_CHAR: u32 = 0x0102; /// Alt held, keypad digits `code`, Alt released, and the character Windows then posts. fn alt_code(c: &mut AltCodes, code: &str, posted: u16) { @@ -215,59 +171,53 @@ mod tests { } #[test] - fn an_alt_code_types_its_character_when_alt_comes_up() { + fn an_alt_codes_keypad_digits_leave_the_frame_and_its_character_is_typed_once() { let mut c = AltCodes::default(); alt_code(&mut c, "0176", 0xB0); alt_code(&mut c, "0151", 0x2014); - let mut events = vec![key(Key::Num0, true, true), key(Key::Num0, true, false), key(Key::Num1, false, true)]; + // winit reports each code's character as typed text. + let mut events = vec![ + key(Key::Num0, true, true), + key(Key::Num0, true, false), + key(Key::Num1, false, true), + Event::Text("°".into()), + Event::Text("—".into()), + ]; c.drain(&mut events); // The keypad digits typed with Alt are gone (eight presses and eight releases, two here); - // the digit typed without Alt stays, and the characters follow. - assert_eq!(events, vec![key(Key::Num1, false, true), Event::Text("°—".into())]); + // the digit typed without Alt stays, and each character stays once. + assert_eq!(events, vec![key(Key::Num1, false, true), Event::Text("°".into()), Event::Text("—".into())]); let mut events = vec![key(Key::Num0, true, true)]; c.drain(&mut events); assert_eq!(events.len(), 1, "counts don't carry over to a later frame"); } #[test] - fn a_character_without_a_code_before_it_is_left_to_winit() { + fn characters_are_left_to_winit() { let mut c = AltCodes::default(); - // A plain key press's character (winit types it), and Alt pressed and released alone. + // A plain key press's character, Alt pressed and released alone, and a code's character. c.message(WM_KEYDOWN, 0x41, 0); c.message(WM_CHAR, usize::from(b'a'), 0); c.message(WM_SYSKEYDOWN, ALT, 0); c.message(WM_KEYUP, ALT, 0); c.message(WM_CHAR, usize::from(b'b'), 0); + alt_code(&mut c, "0176", 0xB0); let mut events = vec![]; c.drain(&mut events); assert!(events.is_empty(), "{events:?}"); } #[test] - fn another_key_while_alt_is_held_cancels_the_code() { + fn alt_with_another_key_keeps_its_shortcut() { let mut c = AltCodes::default(); c.message(WM_SYSKEYDOWN, ALT, 0); c.message(WM_SYSKEYDOWN, VK_NUMPAD0 + 1, 0); // Alt+F: a shortcut, not a code. c.message(WM_SYSKEYDOWN, 0x46, 0); c.message(WM_KEYUP, ALT, 0); - c.message(WM_CHAR, 0x41, 0); - let mut events = vec![]; + let mut events = vec![key(Key::Num1, true, true), key(Key::F, true, true)]; c.drain(&mut events); - assert!(!events.iter().any(|e| matches!(e, Event::Text(_))), "{events:?}"); - } - - #[test] - fn a_code_above_the_basic_plane_arrives_as_two_halves() { - let mut c = AltCodes::default(); - c.message(WM_SYSKEYDOWN, ALT, 0); - c.message(WM_SYSKEYDOWN, VK_NUMPAD0 + 1, 0); - c.message(WM_KEYUP, ALT, 0); - c.message(WM_CHAR, 0xD83D, 0); - c.message(WM_CHAR, 0xDE00, 0); - let mut events = vec![]; - c.drain(&mut events); - assert_eq!(events, vec![Event::Text("😀".into())]); + assert_eq!(events, vec![key(Key::F, true, true)]); } /// Alt held, keypad digits `code` with NumLock off (keypad Insert, End, …, flags without the @@ -284,7 +234,7 @@ mod tests { } #[test] - fn with_numlock_off_the_keypad_keys_type_the_code_and_leave_the_caret_alone() { + fn with_numlock_off_the_keypad_keys_leave_the_caret_alone() { let mut c = AltCodes::default(); alt_code_numlock_off(&mut c, "0176", 0xB0); // What egui reports for keypad 0, 1, 7 and 6 with NumLock off and Alt held, a press and a @@ -296,7 +246,7 @@ mod tests { } events.push(key(Key::Home, false, true)); c.drain(&mut events); - assert_eq!(events, vec![key(Key::Home, false, true), Event::Text("°".into())]); + assert_eq!(events, vec![key(Key::Home, false, true)]); } #[test] @@ -309,11 +259,11 @@ mod tests { let mut events = vec![key(Key::Num5, true, true), key(Key::ArrowDown, true, true), key(Key::PageDown, true, true), key(Key::ArrowLeft, true, true)]; c.drain(&mut events); - assert_eq!(events, vec![Event::Text("—ê".into())]); + assert!(events.is_empty(), "{events:?}"); } #[test] - fn the_separate_navigation_keys_still_move_the_caret_and_cancel_the_code() { + fn the_separate_navigation_keys_still_move_the_caret() { let mut c = AltCodes::default(); c.message(WM_SYSKEYDOWN, ALT, 0); c.message(WM_SYSKEYDOWN, NUMLOCK_OFF_KEYS[1], 0); @@ -322,7 +272,6 @@ mod tests { c.message(WM_SYSKEYDOWN, NUMLOCK_OFF_KEYS[7], EXTENDED_KEY); c.message(WM_SYSKEYUP, NUMLOCK_OFF_KEYS[7], EXTENDED_KEY); c.message(WM_KEYUP, ALT, 0); - c.message(WM_CHAR, 0x41, 0); let mut events = vec![key(Key::End, true, true), key(Key::End, true, false), key(Key::Home, true, true), key(Key::Home, true, false)]; c.drain(&mut events); assert_eq!(events, vec![key(Key::Home, true, true), key(Key::Home, true, false)]); diff --git a/apps/vectorcraft/src/xwayland.rs b/apps/vectorcraft/src/xwayland.rs index 38b210c05e..1471f44199 100644 --- a/apps/vectorcraft/src/xwayland.rs +++ b/apps/vectorcraft/src/xwayland.rs @@ -22,18 +22,61 @@ use std::path::{Path, PathBuf}; const X11_LIBS: &[&str] = &["libX11.so.6", "libX11-xcb.so.1", "libxcb.so.1", "libXcursor.so.1", "libXi.so.6", "libxkbcommon.so.0", "libxkbcommon-x11.so.0"]; -/// Whether the saved `linuxDisplayServer` and the environment ask for XWayland: `x11` chosen, or -/// any other choice (`automatic`, `x11WithPen`, none saved) with `pen` finding a pen and -/// `VECTORCRAFT_NATIVE_WAYLAND` unset (or `0`); a Wayland session (winit picks Wayland whenever -/// `WAYLAND_DISPLAY` or `WAYLAND_SOCKET` is set); and an X display to open. `pen` runs only after -/// the other checks. -pub fn wanted(pref: Option<&str>, var: impl Fn(&str) -> Option, pen: impl FnOnce() -> bool) -> bool { +/// What the pen check found: the name of the first pen, `None` when there is none, or why the +/// device list could not be read. +pub type PenProbe = Result, String>; + +/// Where the window opens, and why, as [`choose`] decides it. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Choice { + /// Not a Wayland session: the window opens where winit opens it. + NotWayland, + /// XWayland, because Linux Display Server is X11 (XWayland). + Chosen, + /// XWayland, because the pen of this name is attached. + Pen(String), + /// Wayland: the session has no X display (`DISPLAY` is unset, as in the Flatpak on a Wayland + /// session), so XWayland can't be used. `x11` is whether X11 (XWayland) was chosen. + NoXDisplay { x11: bool }, + /// Wayland: `VECTORCRAFT_NATIVE_WAYLAND` keeps the window there. + NativeWayland, + /// Wayland: no pen is attached. + NoPen, + /// Wayland: the input devices could not be listed, for this reason. + NoDeviceList(String), +} + +impl Choice { + /// Whether the window opens through XWayland. + pub fn xwayland(&self) -> bool { + matches!(self, Self::Chosen | Self::Pen(_)) + } +} + +/// Where the saved `linuxDisplayServer` and the environment open the window: XWayland for `x11` +/// chosen, or for any other choice (`automatic`, `x11WithPen`, none saved) with `pen` finding a pen +/// and `VECTORCRAFT_NATIVE_WAYLAND` unset (or `0`), on a Wayland session (winit picks Wayland +/// whenever `WAYLAND_DISPLAY` or `WAYLAND_SOCKET` is set) with an X display to open. `pen` runs +/// only after the other checks. +pub fn choose(pref: Option<&str>, var: impl Fn(&str) -> Option, pen: impl FnOnce() -> PenProbe) -> Choice { let set = |name: &str| var(name).is_some_and(|v| !v.is_empty()); - let session = (set("WAYLAND_DISPLAY") || set("WAYLAND_SOCKET")) && set("DISPLAY"); - let native_wayland = var("VECTORCRAFT_NATIVE_WAYLAND").is_some_and(|v| !v.is_empty() && v != "0"); - match pref { - Some("x11") => session, - _ => session && !native_wayland && pen(), + if !set("WAYLAND_DISPLAY") && !set("WAYLAND_SOCKET") { + return Choice::NotWayland; + } + let x11 = pref == Some("x11"); + if !set("DISPLAY") { + return Choice::NoXDisplay { x11 }; + } + if x11 { + return Choice::Chosen; + } + if var("VECTORCRAFT_NATIVE_WAYLAND").is_some_and(|v| !v.is_empty() && v != "0") { + return Choice::NativeWayland; + } + match pen() { + Ok(Some(name)) => Choice::Pen(name), + Ok(None) => Choice::NoPen, + Err(e) => Choice::NoDeviceList(e), } } @@ -44,20 +87,28 @@ const BTN_TOOL_PEN: u32 = 0x140; const ABS_X: u32 = 0x00; const ABS_Y: u32 = 0x01; -/// Is a pen attached? Reads `/proc/bus/input/devices`; a file that can't be read has no pen. -pub fn pen_attached() -> bool { - std::fs::read_to_string("/proc/bus/input/devices").is_ok_and(|devices| has_pen(&devices)) +/// The pen attached, from `/proc/bus/input/devices`, or why that file could not be read. +pub fn pen_attached() -> PenProbe { + std::fs::read_to_string("/proc/bus/input/devices").map(|devices| find_pen(&devices)).map_err(|e| format!("/proc/bus/input/devices: {e}")) } -/// Is a pen among the input devices `/proc/bus/input/devices` lists? A pen is a device whose +/// Is a pen among the input devices `/proc/bus/input/devices` lists? +#[cfg(test)] +fn has_pen(devices: &str) -> bool { + find_pen(devices).is_some() +} + +/// The name of the first pen among the input devices `/proc/bus/input/devices` lists (its +/// `N: Name=` line without the quotes, empty when it has none). A pen is a device whose /// `B: KEY=` bitmap has `BTN_TOOL_PEN` and whose `B: ABS=` bitmap has `ABS_X` and `ABS_Y`, as /// libinput asks of a tablet tool. A virtual keyboard made with uinput can claim every key code, /// `BTN_TOOL_PEN` included, but has no absolute axes. -fn has_pen(devices: &str) -> bool { - devices.split("\n\n").any(|device| { - let bitmap = |name: &str| device.lines().find_map(|l| l.strip_prefix(name)); - bitmap("B: KEY=").is_some_and(|keys| bit_set(keys, BTN_TOOL_PEN)) - && bitmap("B: ABS=").is_some_and(|axes| bit_set(axes, ABS_X) && bit_set(axes, ABS_Y)) +fn find_pen(devices: &str) -> Option { + devices.split("\n\n").find_map(|device| { + let field = |name: &str| device.lines().find_map(|l| l.strip_prefix(name)); + let pen = field("B: KEY=").is_some_and(|keys| bit_set(keys, BTN_TOOL_PEN)) + && field("B: ABS=").is_some_and(|axes| bit_set(axes, ABS_X) && bit_set(axes, ABS_Y)); + pen.then(|| field("N: Name=").map_or_else(String::new, |n| n.trim().trim_matches('"').to_string())) }) } @@ -147,6 +198,11 @@ mod tests { panic!("the pen check ran") } + /// [`choose`] as a yes or no, with a pen check that finds a pen or none. + fn wanted(pref: Option<&str>, var: impl Fn(&str) -> Option, pen: impl FnOnce() -> bool) -> bool { + choose(pref, var, || Ok(pen().then(|| "Pen".to_string()))).xwayland() + } + #[test] fn xwayland_only_when_chosen_on_wayland_with_an_x_display() { let wayland = env(&[("WAYLAND_DISPLAY", "wayland-0"), ("DISPLAY", ":0")]); @@ -183,6 +239,40 @@ mod tests { assert!(wanted(Some("x11"), &native, no_probe)); } + /// #5622: the choice names why the window stays on Wayland, where the pen does not reach it, + /// so that the log tells a missing X display (the Flatpak on a Wayland session) from a pen + /// that is not listed or a device list that can't be read. + #[test] + fn the_choice_says_why_the_window_stays_on_wayland() { + let wayland = env(&[("WAYLAND_DISPLAY", "wayland-0"), ("DISPLAY", ":0")]); + let no_x = env(&[("WAYLAND_DISPLAY", "wayland-0")]); + let native = env(&[("WAYLAND_DISPLAY", "wayland-0"), ("DISPLAY", ":0"), ("VECTORCRAFT_NATIVE_WAYLAND", "1")]); + let pen = || Ok(Some("ELAN9008:00 04F3:2C82 Stylus".to_string())); + let never = || -> PenProbe { panic!("the pen check ran") }; + assert_eq!(choose(None, env(&[("DISPLAY", ":0")]), never), Choice::NotWayland); + assert_eq!(choose(None, &no_x, never), Choice::NoXDisplay { x11: false }); + assert_eq!(choose(Some("x11"), &no_x, never), Choice::NoXDisplay { x11: true }); + assert_eq!(choose(Some("x11"), &wayland, never), Choice::Chosen); + assert_eq!(choose(Some("automatic"), &native, never), Choice::NativeWayland); + assert_eq!(choose(Some("automatic"), &wayland, pen), Choice::Pen("ELAN9008:00 04F3:2C82 Stylus".to_string())); + assert_eq!(choose(Some("x11WithPen"), &wayland, || Ok(None)), Choice::NoPen); + let unreadable = choose(None, &wayland, || Err("/proc/bus/input/devices: Permission denied".to_string())); + assert_eq!(unreadable, Choice::NoDeviceList("/proc/bus/input/devices: Permission denied".to_string())); + for stays in [Choice::NotWayland, Choice::NoXDisplay { x11: true }, Choice::NativeWayland, Choice::NoPen, unreadable] { + assert!(!stays.xwayland(), "{stays:?}"); + } + assert!(Choice::Chosen.xwayland() && Choice::Pen(String::new()).xwayland()); + } + + /// The pen check names the pen it found, for the log. + #[test] + fn the_pen_check_names_the_pen() { + assert_eq!(find_pen(WITH_PEN).as_deref(), Some("Wacom Intuos Pro M Pen")); + let without = WITH_PEN.split("\n\n").take(2).collect::>().join("\n\n"); + assert_eq!(find_pen(&without), None); + assert_eq!(find_pen("B: KEY=1c03 0 0 0 0 0\nB: ABS=3\n").as_deref(), Some(""), "a pen without a name line"); + } + /// `/proc/bus/input/devices` of a laptop with a Wacom Intuos Pro attached (64-bit longs: the /// pen's `KEY=1c03 0 0 0 0 0` has bit 0x140, `BTN_TOOL_PEN`), from PhotoCraft's tests. const WITH_PEN: &str = "I: Bus=0011 Vendor=0001 Product=0001 Version=ab83\n\ diff --git a/crates/engine/src/cmd/addons/pathtools/bridge.rs b/crates/engine/src/cmd/addons/pathtools/bridge.rs index ea4f940ab9..2f56079b18 100644 --- a/crates/engine/src/cmd/addons/pathtools/bridge.rs +++ b/crates/engine/src/cmd/addons/pathtools/bridge.rs @@ -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; 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. An object that is not a circle is an error that says why (an ellipse whose width and height differ, a compound path, a hidden or locked object, or another object). 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, and a group or compound path the other circles leave empty goes; 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. An object that is not a circle is an error that says why (an ellipse whose width and height differ, a compound path, a hidden or locked object, or another object). 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 )] @@ -130,7 +130,8 @@ fn bridge(s: &mut Session, p: &Value) -> Result { } beside.finish(d)?; } else { - // Each shape's topmost circle becomes its outline (a plain path now) and the others go. + // Each shape's topmost circle becomes its outline (a plain path now) and the others go, + // with each group they leave empty. let mut gone = vec![]; for (members, outline) in shapes { let Some((&top, rest)) = members.split_last() else { continue }; @@ -141,7 +142,9 @@ fn bridge(s: &mut Session, p: &Value) -> Result { made.push(top); gone.extend_from_slice(rest); } + let parents: Vec = gone.iter().filter_map(|id| d.parent_of(*id)).collect(); remove_each(d, &gone)?; + remove_emptied(d, parents)?; } sel.set(made.iter().chain(&alone).copied()); Ok(made) @@ -189,6 +192,24 @@ fn not_a_circle(d: &Document, id: NodeId, editable: bool) -> &'static str { } } +/// Remove each of `parents` that is left with nothing in it, and then each group above it left with +/// nothing in it in turn. Layers stay. +fn remove_emptied(d: &mut Document, parents: Vec) -> Result<()> { + for parent in parents { + let mut at = Some(parent); + while let Some(id) = at { + match d.node(id) { + Some(n) if !n.is_layer() && n.children().is_some_and(|c| c.is_empty()) => { + at = d.parent_of(id); + d.remove(id)?; + } + _ => break, + } + } + } + Ok(()) +} + /// 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 f9b9ea23ef..1f47454749 100644 --- a/crates/engine/src/cmd/addons/pathtools/bridge/tests.rs +++ b/crates/engine/src/cmd/addons/pathtools/bridge/tests.rs @@ -373,6 +373,118 @@ fn an_id_given_twice_is_one_circle() { assert_eq!(top_level(&s), [b]); } +/// The objects directly inside `id`. +fn inside(s: &Session, id: NodeId) -> Vec { + s.doc().unwrap().doc.node(id).unwrap().children().unwrap().iter().map(|n| n.id).collect() +} + +fn make(s: &mut Session, command: &str, ids: &[NodeId]) -> NodeId { + select(s, ids); + NodeId(s.execute(command, &json!({})).unwrap()["id"].as_u64().unwrap()) +} + +#[test] +fn a_group_the_bridged_circles_leave_empty_goes_in_the_same_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 ga = make(&mut s, "object.group", &[a]); + let gb = make(&mut s, "object.group", &[b]); + let steps = s.doc().unwrap().history.undo.len(); + let r = s.execute(BRIDGE, &json!({"ids": [a.0, b.0]})).unwrap(); + assert_eq!(r["id"], json!(b.0)); + assert_eq!(top_level(&s), [gb], "the lower circle's group, left empty, goes"); + assert_eq!(inside(&s, gb), [b], "the outline stays in the upper circle's group"); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "one undo step"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(top_level(&s), [ga, gb]); + assert_eq!((inside(&s, ga), inside(&s, gb)), (vec![a], vec![b])); + + // Kept circles leave their groups as they are. + s.execute(BRIDGE, &json!({"ids": [a.0, b.0], "keepOriginals": true})).unwrap(); + assert_eq!(top_level(&s), [ga, gb]); + assert_eq!(inside(&s, ga), [a]); +} + +#[test] +fn groups_above_an_emptied_group_go_in_turn_and_a_group_with_other_objects_stays() { + let mut s = session(); + // a in a group that is all of another group; c in a group with a square; b on the layer. + let a = circle(&mut s, 100.0, 100.0, 20.0); + let b = circle(&mut s, 150.0, 100.0, 20.0); + let c = circle(&mut s, 200.0, 100.0, 20.0); + let square = NodeId(s.execute("shape.rectangle", &json!({"x": 300, "y": 200, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap()); + let inner = make(&mut s, "object.group", &[a]); + let outer = make(&mut s, "object.group", &[inner]); + let gc = make(&mut s, "object.group", &[square, c]); + let layer = s.doc().unwrap().doc.layers[0].id; + let r = s.execute(BRIDGE, &json!({"ids": [a.0, b.0, c.0]})).unwrap(); + assert_eq!(ids(&r["ids"]), [c], "one shape, in the topmost circle's place"); + assert_eq!(top_level(&s), [gc], "both groups around a go, b goes from the layer"); + assert_eq!(inside(&s, gc), [c, square], "the group with the square stays"); + let d = &s.doc().unwrap().doc; + assert!(d.node(inner).is_none() && d.node(outer).is_none()); + assert!(d.node(layer).is_some(), "the layer stays"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(inside(&s, outer), [inner]); + assert_eq!(inside(&s, inner), [a]); +} + +#[test] +fn a_compound_path_the_bridged_circles_leave_empty_goes() { + 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 compound = make(&mut s, "object.compoundPath.make", &[a]); + assert_eq!(inside(&s, compound), [a]); + s.execute(BRIDGE, &json!({"ids": [a.0, b.0]})).unwrap(); + assert_eq!(top_level(&s), [b]); + assert!(s.doc().unwrap().doc.node(compound).is_none()); +} + +#[test] +fn a_selected_group_of_grouped_circles_keeps_only_the_outlines_group() { + 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 ga = make(&mut s, "object.group", &[a]); + let gb = make(&mut s, "object.group", &[b]); + let outer = make(&mut s, "object.group", &[ga, gb]); + select(&mut s, &[outer]); + s.execute(BRIDGE, &json!({})).unwrap(); + assert_eq!(top_level(&s), [outer]); + assert_eq!(inside(&s, outer), [gb], "the lower circle's group goes, the outline's stays"); + assert_eq!(inside(&s, gb), [b]); +} + +#[test] +fn layers_and_sublayers_the_bridged_circles_leave_empty_stay() { + let mut s = session(); + let a = circle(&mut s, 100.0, 100.0, 20.0); + let upper = NodeId(s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().unwrap()); + let sub = NodeId(s.execute("layer.newSublayer", &json!({"parent": upper.0})).unwrap()["id"].as_u64().unwrap()); + s.execute("layer.setCurrent", &json!({"id": sub.0})).unwrap(); + let b = circle(&mut s, 160.0, 100.0, 20.0); + let c = circle(&mut s, 220.0, 100.0, 20.0); + // a below in the first layer, b and c in the sublayer: c's shape takes a's and b's places. + s.execute(BRIDGE, &json!({"ids": [a.0, b.0, c.0], "reach": 30})).unwrap(); + let d = &s.doc().unwrap().doc; + assert!(d.layers.iter().any(|l| l.id != upper && l.children().is_some_and(|c| c.is_empty())), "the emptied layer stays"); + assert_eq!(inside(&s, sub), [c]); + // The sublayer left with nothing in it stays too. + let mut s = session(); + let a = circle(&mut s, 100.0, 100.0, 20.0); + let upper = NodeId(s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().unwrap()); + let sub = NodeId(s.execute("layer.newSublayer", &json!({"parent": upper.0})).unwrap()["id"].as_u64().unwrap()); + s.execute("layer.setCurrent", &json!({"id": sub.0})).unwrap(); + let b = circle(&mut s, 160.0, 100.0, 20.0); + s.execute("layer.setCurrent", &json!({"id": upper.0})).unwrap(); + let c = circle(&mut s, 220.0, 100.0, 20.0); + s.execute(BRIDGE, &json!({"ids": [a.0, b.0, c.0], "reach": 30})).unwrap(); + assert_eq!(inside(&s, sub), Vec::::new(), "the emptied sublayer stays"); + assert_eq!(inside(&s, upper), [sub, c]); +} + #[test] fn small_circles_at_the_default_reach_bridge_the_pairs_the_arcs_can_join() { let mut s = session(); diff --git a/crates/svg/Cargo.toml b/crates/svg/Cargo.toml index 310b9c8e6f..08fcbbd3de 100644 --- a/crates/svg/Cargo.toml +++ b/crates/svg/Cargo.toml @@ -21,6 +21,8 @@ vectorcraft-effects = { workspace = true } vectorcraft-brush = { workspace = true } vectorcraft-text = { workspace = true } vectorcraft-pathops = { workspace = true } +# Installed memory (cgroup limits included), which sizes the element limit. +vectorcraft-render = { workspace = true } kurbo = { workspace = true } # Image elements still go through usvg's image href resolution (src/import/files.rs, src/import/budget.rs). usvg = { workspace = true } diff --git a/crates/svg/src/import.rs b/crates/svg/src/import.rs index 5e7afdd55a..20261eef95 100644 --- a/crates/svg/src/import.rs +++ b/crates/svg/src/import.rs @@ -28,6 +28,11 @@ pub(crate) use fx::BLEND; /// expansion bombs (#3564). pub const MAX_NODES: usize = if cfg!(target_arch = "wasm32") { 500_000 } else { 2_000_000 }; +/// Most elements an SVG may expand to on this machine, its memory considered (#10165). +pub fn max_elements() -> usize { + budget::max_elements() as usize +} + mod convert; mod importer; mod layers; @@ -112,7 +117,7 @@ pub(crate) fn svg_filters(svg: &str, room: usize, taken: impl Fn(&str) -> bool) } let xml = parse(svg)?; // Before the style cascade of `depth::height`, as `import` measures it. - budget::check(&xml, budget::Cost::LIMITS, depth::MAX_ELEMENT_DEPTH)?; + budget::check(&xml, budget::Cost::limits(), depth::MAX_ELEMENT_DEPTH)?; if depth::height(&xml, depth::MAX_ELEMENT_DEPTH).is_none() { return Err(too_deep()); } @@ -142,7 +147,7 @@ pub(crate) fn import_finding( let xml = parse(svg)?; // Before the style cascade of `depth::height` and the prepass, which keeps the declarations of // each element it reads; measured again below on the text usvg reads when that differs. - let spent = budget::check(&xml, budget::Cost::LIMITS, depth::MAX_ELEMENT_DEPTH)?; + let spent = budget::check(&xml, budget::Cost::limits(), depth::MAX_ELEMENT_DEPTH)?; let Some(height) = depth::height(&xml, depth::MAX_ELEMENT_DEPTH) else { return Err(too_deep()); }; @@ -165,8 +170,8 @@ pub(crate) fn import_finding( // Before usvg copies what ``s show and the style values of each copy: the text usvg reads. let spent = match &src { Cow::Borrowed(_) if !rewritten => spent, - Cow::Borrowed(_) => budget::check(&xml, budget::Cost::LIMITS, usize::MAX)?, - Cow::Owned(prepared) => budget::check(&parse(prepared)?, budget::Cost::LIMITS, usize::MAX)?, + Cow::Borrowed(_) => budget::check(&xml, budget::Cost::limits(), usize::MAX)?, + Cow::Owned(prepared) => budget::check(&parse(prepared)?, budget::Cost::limits(), usize::MAX)?, }; let files = found.files; files.spent_by_svg(spent); diff --git a/crates/svg/src/import/budget.rs b/crates/svg/src/import/budget.rs index 2520a8932a..b7b45f03da 100644 --- a/crates/svg/src/import/budget.rs +++ b/crates/svg/src/import/budget.rs @@ -6,8 +6,9 @@ //! sheets and the `style` attribute give the element, so a long style on an element that ``s //! copy, again and again in a chain, or that a style sheet rule gives to many elements, takes more //! memory than the file holds many times over. usvg stops past 1,000,000 elements, but only after -//! it has made them and copied their styles. An SVG past [`MAX_SVG_ELEMENTS`] elements or -//! [`MAX_COPIED_STYLES`] bytes of copied styles is refused here instead. +//! it has made them and copied their styles. An SVG past [`max_elements`] elements (fewer than +//! [`MAX_SVG_ELEMENTS`] when the machine's memory has room for fewer) or [`MAX_COPIED_STYLES`] +//! bytes of copied styles is refused here instead. //! //! The copies are counted, never made: each element's count is worked out once and added up, so a //! `` of an element costs one addition, however many elements its copy holds. References @@ -43,6 +44,32 @@ use crate::{MAX_ELEMENT_DEPTH, SvgError}; /// which usvg stops (its count includes a root of its own). pub(crate) const MAX_SVG_ELEMENTS: usize = if MAX_NODES < 999_999 { MAX_NODES } else { 999_999 }; +/// Memory an element takes, about, from reading the SVG to drawing what is made of it (bytes): a +/// 400,000-path SVG converted to PNG peaked at about 4.4 KB a path (#10165), with room to spare. +const ELEMENT_BYTES: u64 = 8 << 10; + +/// Most elements usvg may make of an SVG on this machine: [`MAX_SVG_ELEMENTS`], fewer when the +/// installed memory (or the process's cgroup limit) has room for fewer, so a large SVG is refused +/// with an error instead of running out of memory. +pub(crate) fn max_elements() -> u64 { + static LIMIT: std::sync::OnceLock = std::sync::OnceLock::new(); + *LIMIT.get_or_init(|| elements_for(vectorcraft_render::installed_memory())) +} + +/// [`max_elements`] with `memory` bytes installed (`None` or 0: not known). +fn elements_for(memory: Option) -> u64 { + memory.filter(|&m| m > 0).map_or(MAX_SVG_ELEMENTS as u64, |m| (m / ELEMENT_BYTES).min(MAX_SVG_ELEMENTS as u64)) +} + +/// The error for an SVG past [`max_elements`]: naming the memory when that is what limits it. +fn too_many_elements() -> SvgError { + let most = max_elements(); + match vectorcraft_render::installed_memory() { + Some(memory) if most < MAX_SVG_ELEMENTS as u64 => SvgError::TooLargeForMemory(most as usize, memory >> 20), + _ => SvgError::TooLarge(MAX_SVG_ELEMENTS), + } +} + /// Most bytes of style values usvg may copy into the elements of an SVG and the SVG images it /// shows, all together: VectorCraft's own limit. pub(crate) const MAX_COPIED_STYLES: u64 = 64 << 20; @@ -209,7 +236,9 @@ pub(crate) struct Cost { impl Cost { /// The most an SVG and the SVG images it shows may cost together. - pub(crate) const LIMITS: Cost = Cost { elements: MAX_SVG_ELEMENTS as u64, bytes: MAX_COPIED_STYLES, tests: MAX_SELECTOR_TESTS }; + pub(crate) fn limits() -> Cost { + Cost { elements: max_elements(), bytes: MAX_COPIED_STYLES, tests: MAX_SELECTOR_TESTS } + } pub(crate) fn add(self, other: Cost) -> Cost { Cost { @@ -408,7 +437,7 @@ pub(super) fn check(xml: &roxmltree::Document, left: Cost, depth: usize) -> Resu pub(super) fn check_spending(xml: &roxmltree::Document, left: Cost, depth: usize) -> (Result, u64) { let (result, tests) = measure_spending(xml, left, depth); let result = result.map_err(|past| match past { - Past::Elements => SvgError::TooLarge(MAX_SVG_ELEMENTS), + Past::Elements => too_many_elements(), Past::Bytes => SvgError::StylesTooLarge((MAX_COPIED_STYLES >> 20) as usize), Past::Tests => SvgError::StylesTooComplex, Past::Depth => SvgError::TooDeep(MAX_ELEMENT_DEPTH), @@ -562,6 +591,19 @@ mod tests { assert_eq!(MAX_SVG_ELEMENTS, if cfg!(target_arch = "wasm32") { 500_000 } else { 999_999 }); } + #[test] + fn less_memory_reads_fewer_elements_up_to_the_element_limit() { + let most = MAX_SVG_ELEMENTS as u64; + assert_eq!(elements_for(None), most, "unknown memory"); + assert_eq!(elements_for(Some(0)), most, "unknown memory"); + assert_eq!(elements_for(Some(1 << 40)), most, "plenty of memory"); + // A 1 GiB container can't hold the 400,000 paths that took 1.77 GB (#10165). + let small = elements_for(Some(1 << 30)); + assert!(small < 400_000, "{small}"); + assert!(elements_for(Some(512 << 20)) < small); + assert!(max_elements() <= most); + } + #[test] fn style_sheet_rules_count_where_they_match() { let groups = "".repeat(4); @@ -614,7 +656,7 @@ mod tests { let xml = roxmltree::Document::parse(&deep).unwrap(); assert_eq!(measure(&xml, NO_LIMITS, MAX_ELEMENT_DEPTH).err(), Some(Past::Depth)); assert!(super::super::depth::height(&xml, MAX_ELEMENT_DEPTH).is_none()); - assert!(matches!(check(&xml, Cost::LIMITS, MAX_ELEMENT_DEPTH), Err(SvgError::TooDeep(_)))); + assert!(matches!(check(&xml, Cost::limits(), MAX_ELEMENT_DEPTH), Err(SvgError::TooDeep(_)))); for text in [chain(5, ""), svg("")] { let xml = roxmltree::Document::parse(&text).unwrap(); let height = super::super::depth::height(&xml, usize::MAX).unwrap_or(0); @@ -674,7 +716,7 @@ mod tests { fn a_selector_that_never_matches_stops_at_the_test_limit() { let never = nested(60, &format!(".missing{} {{fill:red}}", " g".repeat(20))); let xml = roxmltree::Document::parse(&never).unwrap(); - assert_eq!(measure(&xml, Cost::LIMITS, usize::MAX).err(), Some(Past::Tests)); + assert_eq!(measure(&xml, Cost::limits(), usize::MAX).err(), Some(Past::Tests)); let before = super::super::css::selector_tests(); let err = super::super::import(&never, &crate::ImportOptions::default(), MAX_NODES).err(); assert!(matches!(err, Some(SvgError::StylesTooComplex)), "{err:?}"); diff --git a/crates/svg/src/import/files.rs b/crates/svg/src/import/files.rs index 631bed3d0c..525e900c87 100644 --- a/crates/svg/src/import/files.rs +++ b/crates/svg/src/import/files.rs @@ -478,7 +478,7 @@ impl Files { // reads it ([`Files::svg_tree`]), which then refuses one past the limits, within what the // linked SVG files measured before it left: past it, its links aren't read, and the // selector tests it made still count. - let (result, tests) = budget::check_spending(&xml, budget::Cost::LIMITS.less(reading.measured), left); + let (result, tests) = budget::check_spending(&xml, budget::Cost::limits().less(reading.measured), left); match result { Ok(cost) => reading.measured = reading.measured.add(cost), Err(e) => { @@ -593,13 +593,13 @@ impl Files { } /// What usvg makes of the SVG holding the images ([`budget::check`]): its images make at most - /// what is left of [`budget::Cost::LIMITS`]. + /// what is left of [`budget::Cost::limits()`]. pub(in crate::import) fn spent_by_svg(&self, spent: budget::Cost) { self.set_spent(spent); } fn spent(&self) -> budget::Cost { - self.spent.lock().map(|s| *s).unwrap_or(budget::Cost::LIMITS) + self.spent.lock().map(|s| *s).unwrap_or(budget::Cost::limits()) } fn set_spent(&self, spent: budget::Cost) { @@ -807,7 +807,7 @@ impl Files { // with theirs while usvg reads it, and only when it decodes. Too deep, it is left out; // past the other limits, the whole SVG is refused. let spent = self.spent(); - let cost = match budget::check(&xml, budget::Cost::LIMITS.less(spent), left) { + let cost = match budget::check(&xml, budget::Cost::limits().less(spent), left) { Ok(cost) => cost, Err(SvgError::TooDeep(_)) => return leave_out(&self.too_deep, true), Err(e) => { diff --git a/crates/svg/src/lib.rs b/crates/svg/src/lib.rs index ad3e91588f..0bcd5999b7 100644 --- a/crates/svg/src/lib.rs +++ b/crates/svg/src/lib.rs @@ -363,6 +363,10 @@ pub enum SvgError { /// nested-image expansion bombs, #3564). #[error("the SVG expands to more than {0} objects")] TooLarge(usize), + /// The SVG expands to more objects (the first number) than this machine's memory, or the + /// process's memory limit (the second number, in MB), has room to read (#10165). + #[error("the SVG expands to more than {0} objects, more than the {1} MB of memory available has room for")] + TooLargeForMemory(usize, u64), /// The SVG expands to more nested SVG images than the reader takes (a guard against /// nested-image expansion bombs, #3564). #[error("the SVG expands to more than {0} nested SVG images")] @@ -536,7 +540,7 @@ pub fn svg_filters(svg: &str, room: usize, taken: impl Fn(&str) -> bool) -> Resu pub use glyph::glyph_art; pub use import::{ MAX_DATA_URL_BYTES, MAX_ELEMENT_DEPTH, MAX_FOREIGN, MAX_FOREIGN_VALUE, MAX_NESTED_SVG_IMAGES, MAX_NESTED_SVG_READS, MAX_NESTED_SVG_TEXT, - MAX_NODES, + MAX_NODES, max_elements, }; /// Import an SVG document reading the files it links to as `opts` says, also returning warnings. diff --git a/crates/svg/tests/it/import_details.rs b/crates/svg/tests/it/import_details.rs index 25c5152de9..a4046e3fe7 100644 --- a/crates/svg/tests/it/import_details.rs +++ b/crates/svg/tests/it/import_details.rs @@ -892,11 +892,22 @@ fn styles_that_expand_past_the_limit_are_refused() { assert_eq!(art(&d).len(), 5000); } +/// `err` refuses an SVG past the element limit: the most usvg reads, or fewer on a machine whose +/// memory has room for fewer (#10165). +fn past_the_element_limit(err: &SvgError) -> bool { + let most = vectorcraft_svg::MAX_NODES.min(999_999); + match *err { + SvgError::TooLarge(n) => n == most, + SvgError::TooLargeForMemory(n, _) => n < most && n == vectorcraft_svg::max_elements(), + _ => false, + } +} + /// A chain of ``s that makes more elements than usvg reads is refused before usvg makes them. #[test] fn a_use_chain_past_the_elements_usvg_reads_is_refused() { let err = import_with(&use_chain(20, ""), &ImportOptions::default()).unwrap_err(); - assert!(matches!(err, SvgError::TooLarge(n) if n == vectorcraft_svg::MAX_NODES.min(999_999)), "{err:?}"); + assert!(past_the_element_limit(&err), "{err:?}"); } /// An SVG image whose styles expand past the limit refuses the SVG showing it, and the SVG images @@ -927,9 +938,13 @@ fn svg_images_share_the_element_limit() { assert_ne!(chain, unshown); let image = image_of("image/svg+xml", &unshown); let rect = r#""#; - assert!(import_with(&svg(&format!("{rect}{image}")), &ImportOptions::default()).is_ok()); + // One image fits, unless this machine's memory has room for fewer elements than it makes. + match import_with(&svg(&format!("{rect}{image}")), &ImportOptions::default()) { + Ok(_) => {} + Err(err) => assert!(vectorcraft_svg::max_elements() < 700_000 && past_the_element_limit(&err), "{err:?}"), + } let err = import_with(&svg(&format!("{rect}{}", image.repeat(2))), &ImportOptions::default()).unwrap_err(); - assert!(matches!(err, SvgError::TooLarge(n) if n == vectorcraft_svg::MAX_NODES.min(999_999)), "{err:?}"); + assert!(past_the_element_limit(&err), "{err:?}"); } /// A `:not()` rule, which only the import's own style cascade reads, counts toward the style limit diff --git a/crates/ui-egui/src/menus/model.rs b/crates/ui-egui/src/menus/model.rs index 21c5a61701..73a4296dd9 100644 --- a/crates/ui-egui/src/menus/model.rs +++ b/crates/ui-egui/src/menus/model.rs @@ -40,9 +40,15 @@ pub(crate) struct Menus { /// The pass number of the last frame with a pointer button or a key press ([`pressed_pass`]), `None` before the /// first: the `input` of [`state_key`]. pressed: Option, + /// The address of the window's keymap that the panel rows took their shortcuts from ([`keymap_addr`]), `None` + /// before the window has one. + keymap: Option, /// How many times [`refresh`] built the model. #[cfg(test)] pub(crate) rebuilds: u64, + /// How many times [`refresh`] set the keymap's shortcuts again without building the model ([`refresh_shortcuts`]). + #[cfg(test)] + pub(crate) shortcut_refreshes: u64, /// The menus as built, before a layout. pub(crate) bar: MenuBar, /// `bar` laid out for the shell's target: what the in-window bar shows. @@ -92,14 +98,22 @@ pub(crate) fn translate_label(english: &'static str) -> String { /// preview, or a typing session), the hash takes the revision the interaction began from in place of the current one, /// which each of its previews changes, and changes as it ends. The hash stays the same as a tool's drag begins. An /// interaction that a dialog, a panel or the font menu begins changes the hash as it begins, since commands that check -/// for an open interaction change state then and the menus stay open while it previews. +/// for an open interaction change state then and the menus stay open while it previews. The window's keymap, which the +/// shown shortcuts are read from, is in the hash too. pub(crate) fn state_key(app: &VectorcraftApp, input: Option) -> u64 { + let mut h = DefaultHasher::new(); + (rows_key(app, input), keymap_addr(app)).hash(&mut h); + h.finish() +} + +/// [`state_key`] without the window's keymap: what the model's rows are built from. A new keymap alone changes only +/// the shortcuts of the rows that read it, which [`refresh`] sets again without a rebuild ([`refresh_shortcuts`]). +fn rows_key(app: &VectorcraftApp, input: Option) -> u64 { let mut h = DefaultHasher::new(); input.hash(&mut h); app.run_count.hash(&mut h); - // The window's keymap, which the panel rows read their shortcuts from (`Build::decorate`): the framework builds it - // after the first frame's menus, and builds a new one when the bindings or the catalog change. - app.ui_ctx.as_ref().and_then(craft::ui::runtime::commands::keymap).map(|k| std::sync::Arc::as_ptr(&k).addr()).hash(&mut h); + // The user's shortcuts, which the catalog's rows are made from. + std::sync::Arc::as_ptr(&app.shortcut_overrides).addr().hash(&mut h); let s = &app.session; (s.journal.len(), s.active_index(), s.clipboard.is_empty(), s.tool_composing()).hash(&mut h); if let Some(d) = s.active() { @@ -129,12 +143,19 @@ pub(crate) fn state_key(app: &VectorcraftApp, input: Option) -> u64 { } /// Brings the menus up to date once per frame, before the frame's input: the model is built again -/// when the rows' state ([`state_key`]) or the shell's target changed. +/// when the rows' state ([`rows_key`]) or the shell's target changed. When only the window's keymap +/// changed (the framework builds the first one after the first frame's menus), the rows that read +/// their shortcuts from it get them again ([`refresh_shortcuts`]). pub(crate) fn refresh(app: &mut VectorcraftApp, ctx: &egui::Context) { let target = Target::of_shell(&WindowHost::of(ctx).shell()); let press = last_press(app, ctx); - let key = state_key(app, press); + let key = rows_key(app, press); + let keymap = keymap_addr(app); if app.menus.key == Some(key) && app.menus.target == Some(target) { + if app.menus.keymap != keymap { + refresh_shortcuts(app, target); + app.menus.keymap = keymap; + } return; } rebuild(app, target); @@ -144,6 +165,54 @@ pub(crate) fn refresh(app: &mut VectorcraftApp, ctx: &egui::Context) { } app.menus.key = Some(key); app.menus.target = Some(target); + app.menus.keymap = keymap; +} + +/// The address of the window's keymap, which the panel rows read their shortcuts from ([`reads_keymap`]): the framework +/// builds it after the first frame's menus, and builds a new one when the bindings or the catalog change. +fn keymap_addr(app: &VectorcraftApp) -> Option { + app.ui_ctx.as_ref().and_then(craft::ui::runtime::commands::keymap).map(|k| std::sync::Arc::as_ptr(&k).addr()) +} + +/// Whether the row running `id` with `params` shows a shortcut read from the window's keymap ([`Build::decorate`]). +fn reads_keymap(id: &str, params: &Value) -> bool { + matches!(id, "window.panel" | "edit.preferences") && !params.is_null() +} + +/// Sets the shortcuts of the rows that read the window's keymap ([`reads_keymap`]) again and lays the bar out again. +/// The rows' states and the catalog stay as the last rebuild made them. +fn refresh_shortcuts(app: &mut VectorcraftApp, target: Target) { + fn walk(app: &VectorcraftApp, nodes: &mut [Node]) { + for node in nodes { + match node { + Node::Item(item) if reads_keymap(&item.command.id, &item.command.params) => { + let shortcut = super::labels::item_shortcut(app, &item.command.id, &item.command.params); + item.shortcut = shortcut; + } + Node::Submenu { children, .. } => walk(app, children), + _ => {} + } + } + } + let mut bar = std::mem::take(&mut app.menus.bar); + for menu in &mut bar.menus { + walk(app, &mut menu.children); + } + app.menus.bar = bar; + lay_out(app, target); + #[cfg(test)] + { + app.menus.shortcut_refreshes += 1; + } +} + +/// Lays `app.menus.bar` out for `target` into `app.menus.laid`, which is edited only when the laid-out bar differs. +fn lay_out(app: &mut VectorcraftApp, target: Target) { + let options = LayoutOptions::new(APP_NAME).label(&translate_label); + let laid = layout(&app.menus.bar, target, &options).bar; + if *app.menus.laid != laid { + app.menus.laid.edit(|l| *l = laid); + } } /// The pass number of the last frame with a pointer button pressed or released or a key pressed, the frame `ctx` read @@ -297,14 +366,9 @@ fn rebuild(app: &mut VectorcraftApp, target: Target) { row_states(app, &rows, &mut states, &mut checks); crate::panels::panel_menu_states(app, &mut states); - let bar = MenuBar::new(menus); - let options = LayoutOptions::new(APP_NAME).label(&translate_label); - let laid = layout(&bar, target, &options).bar; app.menus.rows = Some(rows); - app.menus.bar = bar; - if *app.menus.laid != laid { - app.menus.laid.edit(|l| *l = laid); - } + app.menus.bar = MenuBar::new(menus); + lay_out(app, target); app.menus.states.edit(|s| *s = states); } @@ -620,7 +684,7 @@ impl Build<'_> { // A panel row shows the chord of the panel's shortcut (`panel:`), which binds `window.panel {panel}`; // a Window row runs it with `toggle: true`, so the framework finds no chord for the row's own command. // Settings' first page shows Preferences' shortcut, which binds `edit.preferences` with no page. - "window.panel" | "edit.preferences" if !params.is_null() => { + _ if reads_keymap(id, params) => { let mut item = item; item.shortcut = super::labels::item_shortcut(self.app, id, params); item @@ -681,6 +745,76 @@ mod tests { assert!(app.menus.states.get(&CommandRef::new("object.group")).is_some_and(CommandState::is_enabled)); } + /// A new window keymap with nothing else changed (the framework builds the first one after the first frame's + /// menus) sets the panel rows' shortcuts from it, in the bar and in the laid-out bar, without building the menus + /// again. The menus are also built again when a process-wide catalog changes, so the fonts and plug-ins are held + /// steady against tests running alongside, and the steps run again on a new app, at most 20 times, until the + /// other catalogs held still through them. + #[test] + fn a_new_keymap_alone_sets_the_shortcuts_without_a_rebuild() { + fn clear(nodes: &mut [Node]) { + for node in nodes { + match node { + Node::Item(item) if reads_keymap(&item.command.id, &item.command.params) => item.shortcut = None, + Node::Submenu { children, .. } => clear(children), + _ => {} + } + } + } + fn panel_chords(bar: &MenuBar) -> usize { + bar.items() + .into_iter() + .filter(|it| it.command.id == "window.panel" && it.command.params["toggle"] == true && it.shortcut.is_some()) + .count() + } + let fonts = vectorcraft_text::FontDb::global(); + let _steady = (vectorcraft_text::test_fonts::steady_fonts(fonts), vectorcraft_plugins::steady::steady_plugins()); + let catalogs = || { + ( + crate::menus::plugin_revision(), + fonts.generation(), + fonts.installed_fonts_ready(), + crate::scripts_menu::revision(), + crate::dialogs::proof_setup::saved_revision(), + ) + }; + let run = || { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let ctx = crate::testing::ui_context(); + for _ in 0..2 { + crate::testing::app_frame(&mut app, &ctx, egui::RawInput::default()); + } + let shown = panel_chords(&app.menus.bar); + // The menus as a refresh before the window's keymap leaves them. + app.menus.keymap = None; + for menu in &mut app.menus.bar.menus { + clear(&mut menu.children); + } + app.menus.laid.edit(|laid| laid.menus.iter_mut().for_each(|menu| clear(&mut menu.children))); + let (rebuilds, refreshes) = (app.menus.rebuilds, app.menus.shortcut_refreshes); + refresh(&mut app, &ctx); + let first = (app.menus.rebuilds - rebuilds, app.menus.shortcut_refreshes - refreshes); + let chords = (panel_chords(&app.menus.bar), panel_chords(&app.menus.laid)); + refresh(&mut app, &ctx); + let second = (app.menus.rebuilds - rebuilds, app.menus.shortcut_refreshes - refreshes); + (shown, first, chords, second) + }; + let (shown, first, chords, second) = (0..20) + .find_map(|_| { + let before = catalogs(); + let out = run(); + (catalogs() == before).then_some(out) + }) + .unwrap_or_else(|| panic!("tests running alongside kept changing the font and plug-in catalogs")); + assert!(shown > 0, "the panel rows show their shortcuts' chords"); + assert_eq!(first.0, 0, "a new keymap alone does not build the menus again"); + assert_eq!(first.1, 1, "the new keymap sets the shortcuts"); + assert_eq!(chords.0, shown, "the panel rows show their chords again"); + assert_eq!(chords.1, shown, "the laid-out bar shows them too"); + assert_eq!(second, (0, 1), "the same keymap sets nothing again"); + } + /// A rebuild runs the check of a command that many rows share once: Effect's dialogs, Window's panels, the /// interface languages and Envelope Distort's Release, which decides whether Make or Reset is shown. #[test] diff --git a/crates/ui-egui/src/panels/properties/document_sections.rs b/crates/ui-egui/src/panels/properties/document_sections.rs index cff44b4f44..d702cbf899 100644 --- a/crates/ui-egui/src/panels/properties/document_sections.rs +++ b/crates/ui-egui/src/panels/properties/document_sections.rs @@ -24,35 +24,27 @@ use crate::panels::transform; /// Appearance fill and stroke, the view's rulers, grids, guides and snapping, the keyboard /// increment and Scale Strokes & Effects, and Quick Actions. /// -/// The body of every section but Appearance shows in a `MemoView` keyed on what it reads, so a -/// frame that changes none of it replays the body. What a body picks comes back through an `Outbox` -/// and runs after its section. +/// Every section but Appearance shows in a `MemoView` keyed on what it reads, header and body together, +/// so a frame that changes none of it replays the whole section. What a section picks comes back +/// through an `Outbox` and runs after it. pub(super) fn document_sections(app: &mut VectorcraftApp, ui: &mut Ui) { let lang = crate::i18n::current(); let units = app.session.general_unit(); let unit = Unit::ALL.iter().position(|u| *u == units).unwrap_or(usize::MAX); let artboards = app.session.active().map_or(0, |d| d.doc.artboards.len()); let mut picked_units = Vec::new(); - super::section(tl!("Document")).show(ui, |ui, _| { - let document = DocumentProps { unit, units, artboards, lang, picked: Outbox::new(&mut picked_units) }; - let _ = MemoView::new("properties-document", document, document_body).show(ui); - }); + let document = DocumentProps { unit, units, artboards, lang, picked: Outbox::new(&mut picked_units) }; + memoized("properties-document", document, document_section, ui); if let Some(u) = picked_units.pop() { app.run("document.setUnits", json!({ "units": u.label() })).ok(); } super::section(tl!("Appearance")).show(ui, |ui, _| super::appearance_section::fill_stroke_rows(app, ui)); - super::section(tl!("Rulers & Grids")).show(ui, |ui, _| { - let _ = MemoView::new("properties-rulers", Language { lang }, rulers_body).show(ui); - }); - super::section(tl!("Guides")).show(ui, |ui, _| { - let _ = MemoView::new("properties-guides", Language { lang }, guides_body).show(ui); - }); + memoized("properties-rulers", Language { lang }, rulers_section, ui); + memoized("properties-guides", Language { lang }, guides_section, ui); let mut snaps = Vec::new(); let (point, grid) = (app.ui.view.snap_to_point, app.ui.view.snap_to_grid); - super::section(tl!("Snap Options")).show(ui, |ui, _| { - let snap = SnapProps { point, grid, lang, picked: Outbox::new(&mut snaps) }; - let _ = MemoView::new("properties-snap", snap, snap_body).show(ui); - }); + let snap = SnapProps { point, grid, lang, picked: Outbox::new(&mut snaps) }; + memoized("properties-snap", snap, snap_section, ui); for command in snaps { app.run(command, json!({})).ok(); } @@ -62,11 +54,9 @@ pub(super) fn document_sections(app: &mut VectorcraftApp, ui: &mut Ui) { let unit = Unit::ALL.iter().position(|u| *u == general).unwrap_or(usize::MAX); let (increment, scale) = (app.session.prefs.keyboard_increment, app.session.prefs.scale_strokes); let (bare_points, lengths) = (app.session.prefs.numbers_without_units_are_points, crate::canvas::rulers::general_lengths(app)); - super::section(tl!("Preferences")).show(ui, |ui, _| { - let picked = Outbox::new(&mut prefs); - let preferences = PreferencesProps { increment, unit, bare_points, lengths, scale, lang, picked }; - let _ = MemoView::new("properties-preferences", preferences, preferences_body).show(ui); - }); + let picked = Outbox::new(&mut prefs); + let preferences = PreferencesProps { increment, unit, bare_points, lengths, scale, lang, picked }; + memoized("properties-preferences", preferences, preferences_section, ui); for pick in prefs { match pick { PreferencePick::Increment(event) => { @@ -79,9 +69,50 @@ pub(super) fn document_sections(app: &mut VectorcraftApp, ui: &mut Ui) { PreferencePick::ScaleStrokes(on) => transform::set_pref(app, "scaleStrokes", on), } } - super::section(tl!("Quick Actions")).show(ui, |ui, _| { - let _ = MemoView::new("properties-quick-actions", Language { lang }, quick_actions_body).show(ui); - }); + memoized("properties-quick-actions", Language { lang }, quick_actions_section, ui); +} + +/// Shows `section` in a `MemoView` with `id`, keyed on `props`. A section scrolled out of view still runs or replays, so +/// its controls keep their focus stops and accessibility nodes. Tests can show it directly instead, to compare where +/// the memoized sections land with where direct ones do. +fn memoized(id: &'static str, props: P, section: fn(&mut P, &mut Ui), ui: &mut Ui) { + #[cfg(test)] + if tests::shown_directly() { + let mut props = props; + section(&mut props, ui); + return; + } + let _ = MemoView::new(id, props, section).shown_out_of_view().show(ui); +} + +/// The Document section: its header and [`document_body`]. +fn document_section(p: &mut DocumentProps<'_>, ui: &mut Ui) { + super::section(tl!("Document")).show(ui, |ui, _| document_body(p, ui)); +} + +/// The Rulers & Grids section: its header and [`rulers_body`]. +fn rulers_section(p: &mut Language, ui: &mut Ui) { + super::section(tl!("Rulers & Grids")).show(ui, |ui, _| rulers_body(p, ui)); +} + +/// The Guides section: its header and [`guides_body`]. +fn guides_section(p: &mut Language, ui: &mut Ui) { + super::section(tl!("Guides")).show(ui, |ui, _| guides_body(p, ui)); +} + +/// The Snap Options section: its header and [`snap_body`]. +fn snap_section(p: &mut SnapProps<'_>, ui: &mut Ui) { + super::section(tl!("Snap Options")).show(ui, |ui, _| snap_body(p, ui)); +} + +/// The Preferences section: its header and [`preferences_body`]. +fn preferences_section(p: &mut PreferencesProps<'_>, ui: &mut Ui) { + super::section(tl!("Preferences")).show(ui, |ui, _| preferences_body(p, ui)); +} + +/// The Quick Actions section: its header and [`quick_actions_body`]. +fn quick_actions_section(p: &mut Language, ui: &mut Ui) { + super::section(tl!("Quick Actions")).show(ui, |ui, _| quick_actions_body(p, ui)); } /// What a section that reads only command states reads besides them: the interface language of its labels. @@ -248,6 +279,63 @@ mod tests { SECTION_RUNS.with(std::cell::Cell::get) } + thread_local! { + /// This thread shows the memoized sections directly, outside their `MemoView`s. + static DIRECT: std::cell::Cell = const { std::cell::Cell::new(false) }; + } + + pub(super) fn shown_directly() -> bool { + DIRECT.with(std::cell::Cell::get) + } + + /// The runs of text the whole Properties panel paints with nothing selected, after idle frames that replay the + /// memoized sections, with the sections shown in their `MemoView`s or, with `direct`, directly. + fn panel_texts(direct: bool) -> Vec<(String, egui::Rect)> { + DIRECT.with(|d| d.set(direct)); + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + let mut panel = Panel::new(app, super::super::show); + panel.frame(); + let before = runs(); + panel.frame(); + panel.frame(); + if !direct { + assert_eq!(runs(), before, "the last frames replay the memoized sections"); + } + let texts = panel.texts(); + DIRECT.with(|d| d.set(false)); + texts + } + + /// Whole sections shown in `MemoView`s, header and body, land where the same sections shown directly do under the + /// app's `SectionRhythm::Spaced` and `QuietHeader::Heads`: the Document section under the panel's heading draws no + /// rule above it, and each later section keeps the stack's gap. + #[test] + fn memoized_sections_land_where_direct_ones_do() { + let direct = panel_texts(true); + for heading in ["Document", "Rulers & Grids", "Guides", "Snap Options", "Preferences", "Quick Actions", "Snap to Point"] { + assert!(direct.iter().any(|(text, _)| text == heading), "the panel shows {heading:?}: {direct:?}"); + } + let memoized = panel_texts(false); + assert_eq!(memoized, direct, "memoized sections land where direct ones do"); + } + + /// In a panel too short for every section, the sections below the fold still register their controls, so Tab + /// and a screen reader reach them before the panel scrolls. + #[test] + fn sections_below_the_fold_keep_their_controls() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + let mut panel = Panel::new(app, super::super::show); + panel.room(egui::vec2(300.0, 200.0)); + panel.frame(); + panel.frame(); + for name in ["Keyboard Increment", "Scale Strokes & Effects", "Snap to Grid"] { + assert!(panel.shows(name), "the panel registers {name:?} below the fold"); + assert!(panel.rect(name).top() > 200.0, "{name:?} is below the fold of a 200 pt panel"); + } + } + #[test] fn canceling_the_units_popup_leaves_the_document_unchanged() { let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); diff --git a/docs/development.md b/docs/development.md index 5a1b6efd95..e3890df321 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 @@ -134,7 +136,7 @@ The window runs natively on Wayland (eframe's `wayland` feature) and on X11. On - **Clipboard owners that never answer (#510):** reading the clipboard waits on the app that owns it: arboard gives up on an X11 owner after 4 s for each format it tries, and a Wayland read waits for the owner to send its data. So on Linux the check that enables the Paste menu items runs on a background thread with a second clipboard handle (`crates/ui-egui/src/clipboard_probe.rs`, installed as `Services::clipboard_probe`), only while nothing is copied in the app and a document is open, and the window keeps drawing. Every arboard read on Linux and the BSDs, including the UI thread's (a paste, and a Copy or Cut checking what the clipboard held), runs on a worker thread with a handle of its own and waits 2 s at most: an owner that never sends its data costs one read that wait, and later reads fail at once until it answers. A paste's bitmap read waits up to 10 s on the paste's background thread, so the UI thread does not wait for it. When one of a paste's reads gets no answer in its 2 s, or a paste follows a read that has not been answered yet, such as the paste's own check whether the clipboard still holds what VectorCraft copied, the paste waits on that thread for that read's answer, up to 10 s after the read was sent, and pastes what it holds. When the answer is what VectorCraft copied, holds nothing to paste, or does not come, the paste takes the internal clipboard. On X11, quitting within 25 s of a read that got no answer waits for that read to end, so the app's own handle is the last one and hands what it copied to the clipboard manager when one runs. That includes a read of the Paste menu check's handle: quitting waits up to 27 s for the background thread to drop it before the app drops its own, and quits after that wait even when the handle has not been dropped. The app takes its windows off screen before these waits (`apps/vectorcraft/src/quit_windows.rs`). An X11 main window, an XWayland one included, is hidden. winit cannot hide a native Wayland window, so on Linux the app attaches no buffer to the main window's surface, which unmaps it while the window and its connection stay open for the Wayland clipboard. On Linux the X11 windows of floating panels and documents are unmapped through a second X11 connection. On native Wayland, floating panels and documents are normally drawn inside the main window; on the BSDs a native Wayland main window stays on screen until the waits end. Windows and macOS keep the check on the UI thread: Windows only asks which formats the clipboard holds, macOS asks the pasteboard server. - **Copied files:** files copied in a file manager (`text/uri-list`; `CF_HDROP` on Windows, file URLs on macOS) paste as the first one that is art (SVG, PDF, EPS, EMF/WMF or a bitmap; a `.ai` or `.ait` file from the editing data it holds, else as the PDF or PostScript it holds), before the clipboard's other formats (which include the files' paths as text). - **Dropping files on the window does not work under Wayland:** winit 0.30, which eframe 0.37 runs on, has no Wayland drag and drop ([winit#1881](https://github.com/rust-windowing/winit/issues/1881), added in winit 0.31; [egui#1563](https://github.com/emilk/egui/issues/1563)), so no `dropped_files` arrive. Until eframe moves to winit 0.31: copy the files in the file manager and paste them, use File › Place or Open, or open the window through XWayland, where drops work: set **Preferences › Performance › Linux Display Server** to **X11 (XWayland)** and restart (#1151), or start the app with `WAYLAND_DISPLAY= vectorcraft`. The preference (`linuxDisplayServer`, read at startup in `apps/vectorcraft/src/main.rs`, shown on Linux only) has winit open the window on X11 (`EventLoopBuilderExtX11::with_x11`) when the session is Wayland, `DISPLAY` is set and the X11 libraries winit loads are installed (`apps/vectorcraft/src/xwayland.rs` reads `ldconfig -p` and the usual library directories); otherwise the window opens on Wayland and the log says why. Unlike clearing `WAYLAND_DISPLAY`, it leaves the clipboard on the compositor's own. -- **Pens and pen displays under Wayland (#491, #2028):** winit 0.30 doesn't bind the Wayland tablet protocol (`zwp_tablet_v2`; tablet input arrives in winit 0.31, [winit#4318](https://github.com/rust-windowing/winit/pull/4318), [egui#7731](https://github.com/emilk/egui/pull/7731)). Since Plasma 6.3, KWin no longer turns tablet input into pointer input for such apps ([kwin!6336](https://invent.kde.org/plasma/kwin/-/merge_requests/6336), commit [25c65abd](https://invent.kde.org/plasma/kwin/-/commit/25c65abddd95eb87fb892a8594faccbf509ff62f)), and GNOME's Mutter does not turn it into pointer input either (that commit's message): on KWin the pen moves the compositor's cursor over the window, but the app gets no motion or presses and shows none of its own cursors. Until eframe moves to winit 0.31, the app runs under XWayland, which supports the tablet protocol and hands the pen to X11 apps as a pointer: Preferences › Performance › Linux Display Server's Automatic (the default) and X11 (XWayland) When a Pen Is Attached (`x11WithPen`) open the window through XWayland when `/proc/bus/input/devices` lists a pen as the app starts, a device with the `BTN_TOOL_PEN` key and the `ABS_X` and `ABS_Y` axes, and log `pen found: opening the window through XWayland`, as PhotoCraft does (#4967; `VECTORCRAFT_NATIVE_WAYLAND=1` keeps the window on Wayland). For a pen attached after the app started, either run the app under XWayland (Preferences › Performance › Linux Display Server › X11 (XWayland); `WAYLAND_DISPLAY= vectorcraft`, or `env -u WAYLAND_DISPLAY vectorcraft`; for a desktop launcher, put `env WAYLAND_DISPLAY=` before the command in its `Exec=` line), or turn KWin's deprecated emulation back on for the whole session by setting `KWIN_WAYLAND_EMULATE_TABLET=1` in KWin's environment (for example in a file under `~/.config/environment.d/` or in `/etc/environment`) and logging in again. The pen then works as a mouse. Under XWayland the app also reads the pen's pressure (next item); with KWin's emulation on native Wayland the pen has no pressure. Other compositors that don't emulate a pointer for tablets behave the same way. +- **Pens and pen displays under Wayland (#491, #2028):** winit 0.30 doesn't bind the Wayland tablet protocol (`zwp_tablet_v2`; tablet input arrives in winit 0.31, [winit#4318](https://github.com/rust-windowing/winit/pull/4318), [egui#7731](https://github.com/emilk/egui/pull/7731)). Since Plasma 6.3, KWin no longer turns tablet input into pointer input for such apps ([kwin!6336](https://invent.kde.org/plasma/kwin/-/merge_requests/6336), commit [25c65abd](https://invent.kde.org/plasma/kwin/-/commit/25c65abddd95eb87fb892a8594faccbf509ff62f)), and GNOME's Mutter does not turn it into pointer input either (that commit's message): on KWin the pen moves the compositor's cursor over the window, but the app gets no motion or presses and shows none of its own cursors. Until eframe moves to winit 0.31, the app runs under XWayland, which supports the tablet protocol and hands the pen to X11 apps as a pointer: Preferences › Performance › Linux Display Server's Automatic (the default) and X11 (XWayland) When a Pen Is Attached (`x11WithPen`) open the window through XWayland when `/proc/bus/input/devices` lists a pen as the app starts, a device with the `BTN_TOOL_PEN` key and the `ABS_X` and `ABS_Y` axes, and log `pen found (): opening the window through XWayland`, as PhotoCraft does (#4967; `VECTORCRAFT_NATIVE_WAYLAND=1` keeps the window on Wayland). When the window stays on Wayland on such a session, the log says why (#5622): `no pen in /proc/bus/input/devices`, `can't look for a pen` with the reason, `VECTORCRAFT_NATIVE_WAYLAND is set`, `there is no X display (DISPLAY is unset)`, or that the X11 libraries aren't all installed. The Flatpak gets no X display on a Wayland session (`--socket=fallback-x11`); `flatpak override --user --nosocket=fallback-x11 --socket=x11 ai.storyteller.vectorcraft` gives it one and keeps its Wayland socket. `--socket=x11` alone is not enough: while `fallback-x11` is set, Flatpak gives the app no X display whenever Wayland is available. `GDK_BACKEND=x11` does not move the window to XWayland: winit does not read it. Under X11 the log lists the pens the X server lists (`tablet: pens listed: …`, for example `xwayland-tablet stylus:16` under XWayland, or `the X server lists no pen`) and the first event from each pen (`tablet: events arrive from the pen …`). For a pen attached after the app started, either run the app under XWayland (Preferences › Performance › Linux Display Server › X11 (XWayland); `WAYLAND_DISPLAY= vectorcraft`, or `env -u WAYLAND_DISPLAY vectorcraft`; for a desktop launcher, put `env WAYLAND_DISPLAY=` before the command in its `Exec=` line), or turn KWin's deprecated emulation back on for the whole session by setting `KWIN_WAYLAND_EMULATE_TABLET=1` in KWin's environment (for example in a file under `~/.config/environment.d/` or in `/etc/environment`) and logging in again. The pen then works as a mouse. Under XWayland the app also reads the pen's pressure (next item); with KWin's emulation on native Wayland the pen has no pressure. Other compositors that don't emulate a pointer for tablets behave the same way. - **Pen pressure under X11 and XWayland (#764):** winit 0.30 hands a pen to an X11 window as a mouse, without its pressure. When the window is on X11, XWayland included, the desktop app opens a second X connection (x11rb's `RustConnection`) and reads XInput2 raw events for every device (`apps/vectorcraft/src/tablet.rs`, from PhotoCraft's `crates/tablet`). A device with an `Abs Pressure` valuator is a pen, unless its XInput type is `TOUCHPAD` or `TOUCHSCREEN`. While a pen is the pointer that moved last, its pressure, scaled from the valuator's range to 0..1, reaches the tools that use pressure: the Paintbrush's pressure-sensitive brushes and the Liquify tools' Use Pressure Pen. The reader also reads `Abs Tilt X` and `Abs Tilt Y` (from a pen that has both) in degrees, scaled to ±60° when the valuator's range does not fit in ±90, and `Abs Rotary Z` (an Art Pen's barrel rotation) as a turn with the middle of the range at 0°; the Paintbrush records them for brushes with Tilt, Bearing and Rotation variation. A pen device whose name or XInput type contains `eraser` (in any case) is the pen's eraser end: while the pointer is over the window, the canvas selects the Eraser tool when the eraser end moves, and it selects the tool used before when the tip moves again (`crates/ui-egui/src/stylus.rs`). The X server needs XInput 2.1 or later; otherwise the log has a `tablet pressure:` warning with the reason, and the pen draws at full pressure. - **Pen tilt and rotation on macOS (#764):** with each tablet event's pressure (#852), `apps/vectorcraft/src/mac_tablet.rs` reads its `tilt`, −1..1 on each axis, scaled to ±60° with each axis keeping AppKit's sign (x positive to the right, y positive towards the bottom and the user), and its `rotation`, negated to run clockwise. Until a pen reports a tilt or a rotation other than 0 after it comes near the tablet, that value reads as none, since a pen without one reports 0. The Paintbrush records them as it does under X11. diff --git a/docs/hardware-parity.md b/docs/hardware-parity.md index 2f77e494bb..cc7c4c656c 100644 --- a/docs/hardware-parity.md +++ b/docs/hardware-parity.md @@ -25,7 +25,7 @@ It reads the pen's tilt and barrel rotation on Windows with Windows Ink (#372), | Pen tilt, bearing, barrel rotation (6D Art Pen) | yes, drives brushes | read from AppKit's tablet events (tilt, and the barrel rotation of a pen that reports one); Calligraphic and Scatter brushes vary with them (#764; not yet tried on a Mac) | with Windows Ink, read from the pen's `POINTER_PEN_INFO` (tilt and barrel rotation where its pen mask says the pen reports them); Calligraphic and Scatter brushes vary with them (#372; not yet tried with a pen) | under X11 and XWayland, read from XInput2 raw events; Calligraphic and Scatter brushes vary with them (#764); **no** on native Wayland | no | partial: native Wayland and the web read none (an Art brush's Width, a Pattern brush's Scale and Bristle brushes follow them, #8490); 3–6 h (#372) | | Pen eraser end | yes | the eraser end (AppKit's tablet proximity events) selects the Eraser tool and the tip brings back the tool used before, as on Linux (#852; not yet tried on a Mac) | with Windows Ink, an inverted pen or its eraser button (`PEN_FLAG_INVERTED`, `PEN_FLAG_ERASER` in the pen's pointer messages) selects the Eraser tool and the tip brings back the tool used before, as on Linux (not yet tried with a pen) | under X11 and XWayland, the eraser end selects the Eraser tool and the tip brings back the tool used before (#764); **no** on native Wayland | a press of the eraser end (Pointer Events eraser button, `button` 5) selects the Eraser tool, and that press erases; a press of the tip brings back the tool used before; Pointer Events report no end while the pen hovers | partial | | Touch gestures (pinch zoom, two-finger pan, rotate view, Touch workspace) | yes (Windows touch, Surface) | trackpad pinch, scroll and rotate | pinch, pan (a second finger cancels the first finger's tool press, #4198); two-finger tap undo, three-finger redo (#585); in the Touch workspace a two-finger tap switches between the Selection tool and the last drawing tool | same where winit reports touch | eframe until the first pen contact, then Pointer Events (pen and fingers told apart); long press opens the context menu | partial: touch-screen rotation missing (the Touch workspace ships, #3139), 3–5 h | -| Trackpad (smooth scroll, pinch) | yes | yes | precision touchpads | yes | yes | done | +| Trackpad (smooth scroll, pinch) | yes | yes | precision touchpads | smooth scroll; pinch and rotate on native Wayland where the compositor offers pointer gestures (#5981), not under X11 or XWayland | yes | done | | HiDPI / Retina, per-monitor scale | yes | yes | yes | yes | yes | done; a window dragged between monitors of different scale can still grow on Windows (#1459, open); the custom title bar's window on Windows stays truly borderless so the pointer lines up with what is drawn (#1791, #1758; awaiting the reporter's confirmation) ; macOS cursors use aligned 1×/2× native image representations (#2292), covered by headless construction tests; mixed-display transitions and physical cursor sizing remain unverified, no additional hardware validated | | Multiple monitors: panels and document windows on another screen | yes | yes: floating panels (#4135) and floating document windows (#5278) are OS windows, and a floating panel reopens on the monitor where it was left (#6038) | yes | under X11; on Wayland they are windows inside the main window | — | partial: Wayland remains, 6–10 h (with multiple windows, gap G7) | | Display colour profile (proof and display through the monitor's ICC) | yes | yes: the window is tagged sRGB and macOS converts it | yes: the display's default ICC profile, Windows' own conversion with Advanced Color on | X11: colord or `_ICC_PROFILE`; Wayland: sRGB | — | done on macOS, Windows and X11; Wayland and floating document windows remain | diff --git a/docs/mcp.md b/docs/mcp.md index 033bdf6bc5..4bd94717cc 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -16875,7 +16875,9 @@ Commands: larger radius or gap only when the largest (1,000% or 1,000 pt) would bridge the circles. The outline replaces the two circles, painted as the upper one (a plain path), unless `keepOriginals` is true: then it goes directly above the upper circle, painted as it, and the circles stay. The outline is selected. Two circles are bridged however far apart - their outlines are; `reach` does not apply to them. + their outlines are; `reach` does not apply to them. When outlines replace circles (with any number of circles), a group + or compound path that the circles leave with nothing in it is removed, and so is each group above it left empty in + turn; layers stay. With three or more circles, every two whose outlines are at most `reach` apart (0 to 10,000 pt, 10 by default; overlapping ones included) are bridged the same way, and the bridges that connect are united into one shape each, which can have holes where bridges enclose space; holes smaller than 1% of the smallest circle's area are filled. A diff --git a/docs/type-parity.md b/docs/type-parity.md index 60b4a7117d..9d3d069cc8 100644 --- a/docs/type-parity.md +++ b/docs/type-parity.md @@ -57,7 +57,7 @@ against Illustrator's public documentation; **estimated** unless noted. | Hidden characters (Show Hidden Characters) | done | `type.hiddenCharacters`: marks spaces, tabs, nonbreaking and narrow nonbreaking spaces, the spaces of a set width, discretionary hyphens, forced line breaks, paragraph ends and the story's end, in horizontal, vertical and right-to-left type and on a path, and none on type in a hidden group or layer; the mark shapes are VectorCraft's own. Evidence: `canvas::tests::hidden_characters_*` | | Spell check (Check Spelling, Auto Spell Check, custom dictionary) | done | the engine (#4936): `text.spelling.check` lists the unknown words of the document's type, each run in its Language, at the bytes `text.editRange` changes, and `text.spelling.suggest` gives suggestions, both from craft-proof, each paragraph on its own (English from the first dictionary it finds: a Hunspell dictionary in the user's dictionaries folder, the SCOWL dictionary built in from craft-i18n, a system Hunspell dictionary, and last the public-domain Moby word list built into it; other languages from the dictionaries craft-proof finds for them). The custom dictionary commands are done: `text.spelling.addWord`, `removeWord` and `changeWord` (Add, and Edit Custom Dictionary's Add, Delete and Change), and `text.spelling.dictionary` lists the words, saved to `Custom Dictionary.txt` beside the preferences; Ignore All: `text.spelling.ignoreAll` skips a word in the active document while it is open. Auto Spell Check is done: Edit › Spelling › Auto Spell Check (`edit.autoSpellCheck`, off at first, saved with the view settings) draws a red wavy line under the unknown words of the visible type, leaves out type with effects, and follows edits, the custom dictionary and Ignore All. A right-click on an underlined word lists the words its dictionary suggests (each replaces it in one undo step, `text.editRange`), or No Suggestions, then Ignore All and Add to Dictionary, and a right-click on type has Spelling › Auto Spell Check, checked while it is on. Edit › Edit Custom Dictionary… lists the custom dictionary's words, with an Entry field and Add, Delete and Change, applied on Done (Cancel leaves the dictionary as it was). The modal Check Spelling dialog is done: Edit › Spelling › Check Spelling… (`Cmd+I`, `ui.checkSpelling`) opens a modal dialog displaying the unrecognized word in sentence context ("Not in Dictionary"), a list of suggestions with double-click or selection to replace ("Change to" field), and action buttons: Ignore, Ignore All, Change (one-step Undo/Redo via `text.editRange`), Change All (batched across occurrences in a single undo step), Add to Dictionary (`text.spelling.addWord`), Done and Cancel, with keyboard navigation (Tab between controls, Enter to Change or Done, Escape to close). Evidence: `crates/engine/src/tests/spelling.rs`, `crates/ui-egui/src/canvas/tests.rs` (`auto_spell_check_*`), `crates/ui-egui/src/tests/contextmenu.rs` (the right-click), `crates/ui-egui/src/dialogs/custom_dictionary.rs` (the dialog), `crates/ui-egui/src/dialogs/check_spelling.rs` (the Check Spelling dialog). | | Smart Punctuation, Change Case, Find & Replace | done | Type › Smart Punctuation… opens a dialog with the ff, fi, ffi and ff, fl, ffl ligatures, Smart Quotes, Smart Spaces, En, Em Dashes, Ellipses and Expert Fractions, Replace In and Report Results, which lists the count of each replacement; ligatures and fractions are written only where the font has a glyph for them. Evidence: `tests::menucmds::smart_punctuation_ligatures_spaces_and_fractions_are_counted`, `smart_punctuation_skips_ligatures_and_fractions_the_font_lacks`, `smart_spaces_keeps_one_space_after_a_period`, `dialogs::smart_punctuation::tests::menu_item_opens_the_dialog_and_ok_reports_the_counts` | -| Alt + numeric-keypad codes while typing (Windows: `Alt+0176` → °) | partial | #5108: on Windows the character Windows posts when Alt comes up after keypad digits is typed at the caret like any other, in the typing's undo step, and the keypad digits typed with Alt run no shortcut. With NumLock off the keypad keys (Insert, End, arrows, Clear, Home, Page Up/Down without the extended-key flag) count as digits too and don't move the caret (`windows_alt_codes` unit tests; neither NumLock on nor off has been tried on a Windows machine yet). `type.insert {code}` (Windows Alt+0 code, Windows-1252 for 128–159) and `{unicode}` (hex code point) insert a character by its code (`menucmds::insert_a_character_by_its_code`). macOS and Linux have no such system convention and egui reports a keypad digit as the top-row digit, so there it does nothing; a floating panel window doesn't receive the character | +| Alt + numeric-keypad codes while typing (Windows: `Alt+0176` → °) | partial | #5108: on Windows the character Windows posts when Alt comes up after keypad digits is typed at the caret like any other, in the typing's undo step (winit reports it as typed text), and the keypad digits typed with Alt run no shortcut. With NumLock off the keypad keys (Insert, End, arrows, Clear, Home, Page Up/Down without the extended-key flag) count as digits too and don't move the caret (`windows_alt_codes` unit tests; neither NumLock on nor off has been tried on a Windows machine yet). `type.insert {code}` (Windows Alt+0 code, Windows-1252 for 128–159) and `{unicode}` (hex code point) insert a character by its code (`menucmds::insert_a_character_by_its_code`). macOS and Linux have no such system convention and egui reports a keypad digit as the top-row digit, so there it does nothing; in a floating panel window the keypad digits typed with Alt are not taken out of the frame | | Caret: the arrows and Delete step over whole clusters (Thai consonant with its marks, combining accents, emoji); Backspace removes one character | done | in text with right-to-left characters the arrows move in visual order and stop on both sides of a character drawn with no width, such as a zero width non-joiner | | Touch Type tool | done | moves, scales and rotates one character through its kerning, baseline shift, scales and rotation (`text.touchType`); a character with a preceding logical character on the same line can move along the line in either reading direction; the first logical character moves only up and down. Positive `dx` follows reading order. These direction rules are VectorCraft's choices. | | Retype (identify fonts in outlines/images) | partial | Phase 1 (#4934): Type › Retype (`type.retype`) turns outlined glyphs back into type when each shape is exactly a glyph of a loaded font, a font the document uses or a family named in `fonts` (the same up to uniform scale, rotation and translation): one object per line unless lines stack into one object as described below, in that font and size, at the same baseline and turn, with the first glyph's fill and stroke, in one undo step; shapes that match no font stay as they are and are reported. Near matches: with `tolerance` (0 to 0.05), shapes of up to 8 contours whose leftover distance from a glyph, relative to the shape's outline spread (the root mean square distance of its sampled outline points from their center), is at most the tolerance (simplified outlines, curves split in two, contours in another order or direction) match too, and each line reports a `score`; a compound path holding several glyphs is split into them and becomes type only when all of them match, a part still matching exactly when some of its contours run the other way round (an o's counter alone in an even-odd compound). A line of three or more exactly matched glyphs keeps the spacing most of its gaps share as tracking (gaps one space wide stay word spaces when type draws them). A line of two glyphs that untracked type does not draw in place takes the tracking of the nearest tracked line in the same font, size and turn, and keeps it only when type at that tracking draws both glyphs in place; a line of one or two glyphs that joins tracked lines in one object takes their tracking. Other lines are set untracked, each glyph at its own position, and lines stacked at one leading and lined up at their starts, ends or centers become one area type object with that leading and alignment (VectorCraft's own rules, checked against the layout). Window › Retype shows the Retype panel, which lists the fonts whose glyphs exactly match at least one selected outlined shape, comparing up to 96 loaded fonts with those of the document's live type first, ranked by how many shapes each matches, with samples, and sets a listed font on selected live type (`retype.find`, `type.retypeFonts`). Both also compare the installed fonts not loaded yet, reading their files within VectorCraft's own limits (256 MiB per file, 2 GiB and 500,000 glyphs per search) and loading only the fonts that match; `type.retype` matches them with its tolerance and splits compound paths for them as it does for loaded fonts; in the app the search runs in the background with Cancel (`retype.cancelSearch`). Missing (phase 2): glyphs fused into one contour, near matches and compound paths of several glyphs in the panel's list, opening the panel from the Type menu and the context menu, filtering the list by font source and favorites, text in images. Public behaviour: [identify fonts](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/identify-fonts-using-retype.html), [apply to live text](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/apply-retype-suggested-fonts-to-live-text.html) | diff --git a/xtask/src/layers.rs b/xtask/src/layers.rs index f2fb1f1ce0..869074b03f 100644 --- a/xtask/src/layers.rs +++ b/xtask/src/layers.rs @@ -80,6 +80,8 @@ pub const INTRA_LAYER_ORDER: &[&[&str]] = &[ &["pathops", "trace"], &["text", "effects"], &["render", "eps"], + // SVG import sizes its element limit from the installed memory the renderer reads (#10165). + &["render", "svg"], &["metafile", "eps"], // Non-native art in Illustrator editing data is a PDF, drawn by the PDF importer. &["pdf", "eps"],