diff --git a/ASSETS.md b/ASSETS.md index 76a3d41962..5e3dc3281c 100644 --- a/ASSETS.md +++ b/ASSETS.md @@ -141,6 +141,8 @@ Generated-in-code art is original and has no file to list. This covers the defau | `assets/icons/dc-arrow-down.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-arrow-extend.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-arrow-fill.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | The Selection and Direct Selection arrows' fill, painted black or white under their outline | +| `assets/icons/dc-arrow-left.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/icons/dc-arrow-right.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-arrow-tip.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-arrow-up.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-artboard.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | @@ -213,6 +215,8 @@ Generated-in-code art is original and has no file to list. This covers the defau | `assets/icons/dc-graphic-styles.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-grid-view.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-group-select.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/icons/dc-guide-horizontal.svg` | VectorCraft contributors | Original work, drawn for VectorCraft (a ruler down the left with a line across) | MIT OR Apache-2.0 | | +| `assets/icons/dc-guide-vertical.svg` | VectorCraft contributors | Original work, drawn for VectorCraft (a ruler along the top with a line down) | MIT OR Apache-2.0 | | | `assets/icons/dc-help.svg` | VectorCraft contributors | Original work, drawn for VectorCraft (a question mark in a circle) | MIT OR Apache-2.0 | | | `assets/icons/dc-join-bevel.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-join-miter.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | diff --git a/ROADMAP.md b/ROADMAP.md index 4d415cc0ba..abd6a3548b 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -147,6 +147,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap - 2026-11-15: Circle through three points: three Shift-clicks with the Ellipse tool, or `shape.circleThroughPoints` with three points or three selected anchor points, draw the circle whose edge passes through them, with the current paint, in one undo step; after two points the tool previews the circle through the pointer, and two points that are the same or three on one line are refused with a message. Scores and estimates unchanged. - 2026-11-17: Circle tool (after the Ellipse tool in its group): two clicks or a drag draw the circle on that diameter, and a click followed by a drag from a second point to a third draws the circle through the three; Shift keeps the diameter at 45° steps, Alt rounds a two-point circle's diameter to the rulers' ticks at the current zoom, points snap to Smart Guides, and the tool shows the circle, its center, its radii and its diameter until the release, or "Circle too large" for points on one line or a circle past the canvas. `shape.circleThroughPoints` also takes two points or two selected anchor points as the ends of a diameter. One undo step per circle. A VectorCraft addition: headline numbers unchanged. - 2026-11-17: Circle Tool Options (double-click the Circle tool): Show Center, Show Radii and Show Diameter switch what the tool shows while a circle is drawn, Color sets the color of the center cross and radius lines, Anchors at Standard Positions off puts the circle's anchors at the points it was drawn through (`shape.circleThroughPoints {anchors: "points"}`), and Third Point by Dragging off draws a three-point circle with three clicks and a two-point circle with a double-click on the second point. A VectorCraft addition: headline numbers unchanged. +- 2026-11-17: Circle tool, From Center (a Control bar checkbox, `tool.setOption` `fromCenter`): the first point is the circle's center and the outline passes through the pointer, which snaps to Smart Guides and anchor points, so a circle centered on one corner of a rectangle can pass through the opposite corner; `shape.circleThroughPoints {center, points: [[x, y]]}` draws it. One undo step per circle. A VectorCraft addition: headline numbers unchanged. - 2026-11-19: Quick Pen tool, in the Pen tool's group (Alt+P, Option+P on macOS): clicks or drags add straight lines, continuous arcs or sharp-corner arcs; Alt tapped on its own switches the action, C flips the last arc, `[` and `]` size it, a click on the first point closes the path and a click on an open end continues it (`path.quickPen`, part of #2660). Headline numbers unchanged. - 2026-11-19: Quick Pen length handles: a handle beyond the start and the end of the path being drawn, or of the selected path, makes the line or arc there longer or shorter when dragged; a line keeps its direction and an arc its circle (`path.quickPenLength`, part of #2660). Headline numbers unchanged. - 2026-11-19: Quick Pen toolbar on the canvas while the tool is active: Straight Line, Continuous Arc and Sharp Corner Arc, Flip Arc, and More Options with Hide Toolbar, Pin Toolbar Position and Reset Toolbar Position; it follows the drawing beside the path's last point and its handle drags it (`tool.quickPen.flipArc`, `window.quickPenToolbar`, Window › Quick Pen Toolbar; part of #2660). Headline numbers unchanged. diff --git a/apps/vectorcraft/Cargo.toml b/apps/vectorcraft/Cargo.toml index 61a4ba381a..bc9945e513 100644 --- a/apps/vectorcraft/Cargo.toml +++ b/apps/vectorcraft/Cargo.toml @@ -61,8 +61,9 @@ pollster = "1" # which src/host_services.rs uses to read the path PhotoCraft registers under App Paths. # Win32_Devices_Display has `QueryDisplayConfig`, Win32_UI_ColorSystem the display's ICC profile and # Win32_System_LibraryLoader `GetProcAddress`, which src/display_profile.rs uses to read the -# display's color profile for the canvas. -windows = { version = "0.62", features = ["Win32_Devices_Display", "Win32_Foundation", "Win32_Graphics_DirectWrite", "Win32_Graphics_Gdi", "Win32_System_LibraryLoader", "Win32_System_Registry", "Win32_System_Threading", "Win32_UI_ColorSystem", "Win32_UI_Input_KeyboardAndMouse", "Win32_UI_Input_Pointer", "Win32_UI_WindowsAndMessaging"] } +# display's color profile for the canvas. Win32_UI_HiDpi has `GetDpiForMonitor`, which +# src/windows_display_size.rs uses to read a monitor's raw density for Display Print Size. +windows = { version = "0.62", features = ["Win32_Devices_Display", "Win32_Foundation", "Win32_Graphics_DirectWrite", "Win32_Graphics_Gdi", "Win32_System_LibraryLoader", "Win32_System_Registry", "Win32_System_Threading", "Win32_UI_ColorSystem", "Win32_UI_HiDpi", "Win32_UI_Input_KeyboardAndMouse", "Win32_UI_Input_Pointer", "Win32_UI_WindowsAndMessaging"] } # The renderer's worker count follows those cores (src/windows_cores.rs). vectorcraft-render = { workspace = true } @@ -83,7 +84,8 @@ objc2-core-text = { version = "0.3", default-features = false, features = ["std" # The windows' Metal layers and the sRGB color space they are tagged with (src/mac_color_space.rs). # Zlib OR Apache-2.0 OR MIT, already in the build through wgpu with these features. objc2-quartz-core = { version = "0.3", default-features = false, features = ["std", "objc2-core-foundation", "objc2-core-graphics", "CALayer", "CAMetalLayer"] } -objc2-core-graphics = { version = "0.3", default-features = false, features = ["std", "CGColorSpace"] } +# CGDisplayScreenSize gives a display's physical size for Display Print Size (src/screen_density.rs). +objc2-core-graphics = { version = "0.3", default-features = false, features = ["std", "CGColorSpace", "CGDirectDisplay", "CGDisplayConfiguration"] } # Waits for the answer of a file dialog shown as a sheet (src/main.rs, #867). MIT OR Apache-2.0, # already in the build through eframe. pollster = "1" diff --git a/apps/vectorcraft/src/app.rs b/apps/vectorcraft/src/app.rs index c8b4f370ad..83d488a243 100644 --- a/apps/vectorcraft/src/app.rs +++ b/apps/vectorcraft/src/app.rs @@ -184,6 +184,11 @@ impl App { let now = ctx.input(|i| i.time); if let Some(w) = &self.winit_window { self.display_profile.tick(w, now, self.app.session.prefs.monitor_profile_display, &self.app.display_profile, ctx); + if let Some(read) = self.screen_density.tick(w, self.app.session.prefs.display_print_size, ctx) { + self.app.services.screens = read.screens; + self.app.set_screen_reading(read.main); + ctx.request_repaint(); + } } self.app.tick(ctx); if self.app.ui.status == "quit" { diff --git a/apps/vectorcraft/src/main.rs b/apps/vectorcraft/src/main.rs index 9bfb5ea3d2..7c23fe71ba 100644 --- a/apps/vectorcraft/src/main.rs +++ b/apps/vectorcraft/src/main.rs @@ -60,6 +60,7 @@ mod process_identity; mod profile_root; #[cfg(not(any(target_os = "macos", windows)))] mod quit_windows; +mod screen_density; #[cfg(not(target_os = "macos"))] mod single_instance; #[cfg(windows)] @@ -69,6 +70,8 @@ mod window_frame; mod windows_alt_codes; #[cfg(windows)] mod windows_cores; +#[cfg(windows)] +mod windows_display_size; mod windows_stylus; mod windows_symbol_chars; mod xwayland; @@ -206,6 +209,9 @@ struct App { held_files: Vec, /// Reads the profile of the display that shows the main window, for the canvas. display_profile: display_profile::Reader, + /// Measures the density of the display that shows the main window, for Display Print Size at + /// 100% Zoom. + screen_density: screen_density::Tracker, /// When this frame's input hook started, for the hang report's frame times (`hang_watch`). frame_start: Option, /// The shortest time between the starts of two frames, while the window presents without vsync @@ -989,6 +995,7 @@ fn main() -> std::process::ExitCode { winit_window, held_files, display_profile: Default::default(), + screen_density: Default::default(), frame_start: None, min_frame, last_frame_began: None, diff --git a/apps/vectorcraft/src/screen_density.rs b/apps/vectorcraft/src/screen_density.rs new file mode 100644 index 0000000000..4a8c91ec76 --- /dev/null +++ b/apps/vectorcraft/src/screen_density.rs @@ -0,0 +1,817 @@ +//! The densities of the connected displays, in points (at each display's scale factor) per inch, +//! for Preferences › General › Display Print Size at 100% Zoom (`Services::screen_ppi` for the +//! display that shows most of the main window, `Services::screens` for every display): a +//! display's size in points divided by the physical size the system reports for it. +//! +//! - macOS: `CGDisplayScreenSize`. +//! - Windows: `GetDpiForMonitor`'s raw density (`windows_display_size`). +//! - X11 on Linux, XWayland included: the RandR output's width and height in millimeters. +//! - Wayland on Linux: the physical width and height of the compositor's `wl_output` for the display. +//! - Other systems: no size, so an inch takes 96 points. +//! +//! A display that reports no size, or a size no display has, gives `None`, and an inch then takes +//! 96 points. While the preference is on, the displays are listed once a second while the app +//! draws. When the list changes, a background thread reads every display's size, and a later +//! frame takes the result. A reading that fails is tried again after [`RETRY_AFTER`] seconds, and +//! the displays are read again [`READ_AGAIN_AFTER`] seconds after the last reading; the app draws a +//! frame for each of these when nothing else makes it draw. + +use std::sync::mpsc::{Receiver, TryRecvError}; + +use vectorcraft_ui_egui::{ScreenDensity, ScreenPpi}; +use winit::dpi::{PhysicalPosition, PhysicalSize}; +use winit::monitor::MonitorHandle; + +/// Seconds between two listings of the displays. +const LOOK_EVERY: f64 = 1.0; + +/// Seconds after a failed reading before the same displays are read again. +const RETRY_AFTER: f64 = 10.0; + +/// Seconds after a reading before the same displays are read again: a display can be replaced by +/// one the listing cannot tell apart (the same connector, resolution and scale). +const READ_AGAIN_AFTER: f64 = 60.0; + +/// Millimeters in an inch. +const MM_PER_INCH: f64 = 25.4; + +/// How far the horizontal and vertical densities of one display may differ, as a fraction of the +/// larger: square pixels on a display that reports its true size give two densities this close. +const AXES_AGREE: f64 = 0.1; + +/// A connected display as winit lists it: what a reading needs, and what tells two lists apart. +#[derive(Clone, Debug, PartialEq)] +pub(crate) struct Display { + name: Option, + position: PhysicalPosition, + size: PhysicalSize, + /// The display's scale factor, as its bits. + scale: u64, + /// The system's id of the display ([`native_id`]). + id: i64, +} + +impl Display { + fn of(m: &MonitorHandle) -> Self { + Self { name: m.name(), position: m.position(), size: m.size(), scale: m.scale_factor().to_bits(), id: native_id(m) } + } +} + +/// One display's physical size in millimeters: `None` when the system reports none, an error when +/// asking for it failed. +type Size = Result, String>; + +/// The physical sizes of displays, one for each display read, or why none could be read. +type Reading = Result, String>; + +/// What the host hands the app: the density of the main window's display, unread while that +/// display is unknown or has not answered yet, and every display's that answered. +#[derive(Clone, Debug, PartialEq)] +pub(crate) struct Densities { + pub(crate) main: ScreenPpi, + pub(crate) screens: Vec, +} + +/// What a display answered: its physical size (`Some(None)` for none), or `None` while it has not +/// answered. +type Answer = Option>; + +/// What a listing gives: the displays, the one that shows most of the main window, and the main +/// window's scale factor. +type Listing = (Vec, Option, f64); + +/// Keeps the densities current from the main window's frames. +#[derive(Default)] +pub(crate) struct Tracker { + /// When the displays were last listed. + looked: Option, + /// The display that showed most of the main window at the last listing, and the window's scale + /// factor then. + current: Option<(Display, f64)>, + /// The displays of the last reading that finished, each with what it answered. + read: Option>, + /// The displays of the last reading that failed, and when it failed. + failed: Option<(Vec, f64)>, + /// The reading in progress: the displays it reads, and where its result arrives. + running: Option<(Vec, Receiver)>, + /// The reading in progress started before the preference was last turned off: its result is + /// dropped when it arrives, and no other reading starts until then. + obsolete: bool, + /// What [`Self::tick`] returned last. + reported: Option, + /// The displays of the last listing. + listed: Option>, + /// When the last reading that finished ended. + read_at: f64, + /// When the first tick ran: the tracker's clock, which runs while the window draws nothing. + origin: Option, +} + +impl Tracker { + /// Lists the displays when a listing is due and Display Print Size is `enabled`, starts a + /// reading on a background thread when they changed, and returns the densities when they + /// differ from what it returned before. The thread asks `ctx` for a frame when its reading is + /// ready. + pub(crate) fn tick(&mut self, window: &winit::window::Window, enabled: bool, ctx: &egui::Context) -> Option { + let now = self.origin.get_or_insert_with(std::time::Instant::now).elapsed().as_secs_f64(); + let list = || { + // winit stops on a display that went away while it is being asked about (Windows); that + // listing is dropped, and the next one is made a second later. + let listing = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + let current = window.current_monitor().map(|m| Display::of(&m)); + (window.available_monitors().map(|m| Display::of(&m)).collect::>(), current, window.scale_factor()) + })); + listing.map_err(|_| log::debug!("a display went away while the displays were listed")).ok() + }; + let wayland = is_wayland(window); + let start = |displays: Vec| { + let (tx, rx) = std::sync::mpsc::channel(); + let ctx = ctx.clone(); + let spawned = std::thread::Builder::new().name("display size".into()).spawn(move || { + // The app may have quit, and dropped the receiver, before the reading ends. + let _ = tx.send(read_all(&displays, wayland)); + ctx.request_repaint(); + }); + spawned.map(|_| rx).map_err(|e| format!("couldn't start reading the displays' sizes: {e}")) + }; + let densities = self.update(now, enabled, list, start); + // A failed reading is tried again at a listing RETRY_AFTER seconds later, also in an app + // that is not drawing. A reading in progress asks for a frame when it ends. + if enabled + && self.running.is_none() + && let Some((_, at)) = &self.failed + { + let due = (at + RETRY_AFTER).max(self.looked.map_or(0.0, |l| l + LOOK_EVERY)); + ctx.request_repaint_after(std::time::Duration::from_secs_f64((due - now).clamp(0.0, RETRY_AFTER))); + } else if enabled && self.running.is_none() && self.read.is_some() { + // An app that is not drawing still lists and reads the displays READ_AGAIN_AFTER seconds + // after the last reading. + let due = (self.read_at + READ_AGAIN_AFTER).max(self.looked.map_or(0.0, |l| l + LOOK_EVERY)); + ctx.request_repaint_after(std::time::Duration::from_secs_f64((due - now).clamp(0.0, READ_AGAIN_AFTER))); + } + densities + } + + /// [`Self::tick`] with the listing (`list`) and the start of a reading (`start`) passed in. + fn update( + &mut self, + now: f64, + enabled: bool, + list: impl FnOnce() -> Option, + start: impl FnOnce(Vec) -> Result, String>, + ) -> Option { + let was_running = self.running.is_some(); + if let Some((displays, rx)) = self.running.take() { + match rx.try_recv() { + Err(TryRecvError::Empty) => self.running = Some((displays, rx)), + _ if self.obsolete => self.obsolete = false, + Ok(Ok(sizes)) => { + // A display whose size could not be read keeps what an earlier reading gave it, + // or stays unanswered, until the reading is tried again. + let mut failed = false; + let read: Vec<_> = displays + .iter() + .zip(sizes.into_iter().chain(std::iter::repeat(Ok(None)))) + .map(|(d, s)| { + let mm = s.map(Some).unwrap_or_else(|e| { + log::debug!("couldn't read a display's physical size: {e}"); + failed = true; + self.earlier(d) + }); + (d.clone(), mm) + }) + .collect(); + self.failed = failed.then_some((displays, now)); + self.read = Some(read); + self.read_at = now; + } + Ok(Err(e)) => { + log::debug!("couldn't read the displays' physical sizes: {e}"); + self.fail(displays, now); + } + Err(TryRecvError::Disconnected) => { + log::debug!("the reading of the displays' physical sizes stopped without a result"); + self.fail(displays, now); + } + } + } + // When a reading ends, the displays are listed again at once: they may have changed while + // it ran, and the frame its end asked for may be the last one for a while. + if was_running && self.running.is_none() { + self.looked = None; + } + if !enabled { + // Turned on again, the displays are read and the densities reported anew: a display + // may have been replaced meanwhile by one that lists the same. + self.reported = None; + self.read = None; + self.failed = None; + self.looked = None; + self.obsolete = self.running.is_some(); + return None; + } + // The densities change only at a listing, and one follows the end of every reading. + let listing = !self.looked.is_some_and(|at| (at..at + LOOK_EVERY).contains(&now)); + if !listing && self.reported.is_some() { + return None; + } + if listing { + self.looked = Some(now); + } + if let Some((displays, current, scale)) = listing.then(list).flatten() { + // winit can give the window's display as it was before a change of resolution: the + // display is found in the listing by its id and name. + let current = current.map(|c| displays.iter().find(|d| d.id == c.id && d.name == c.name).cloned().unwrap_or(c)); + self.current = current.map(|c| (c, scale)); + self.listed = Some(displays.clone()); + // These displays are read once, and again RETRY_AFTER seconds after a reading of them + // failed in whole or in part. + let known = self.read.as_ref().is_some_and(|r| r.iter().map(|(d, _)| d).eq(displays.iter())); + let due = match &self.failed { + Some((d, at)) if *d == displays => !(*at..*at + RETRY_AFTER).contains(&now), + _ => !known || now - self.read_at >= READ_AGAIN_AFTER, + }; + if self.running.is_none() && due { + match start(displays.clone()) { + Ok(rx) => self.running = Some((displays, rx)), + Err(e) => { + log::warn!("{e}"); + self.fail(displays, now); + } + } + } + } + let read = self.read.as_ref()?; + // The main window counts in its own scale factor, which on Wayland can be a fraction where + // the display gives a whole number. A window on no display (a Wayland window before it is + // shown, or after its display went), or on one that is being read or has not answered, has + // its density unread. + let main = match &self.current { + Some((c, scale)) => match read.iter().find(|(d, _)| d == c) { + Some((d, Some(mm))) => ScreenPpi::Read(mm.and_then(|mm| points_per_inch(d.size, *scale, mm))), + _ => ScreenPpi::Unread, + }, + None => ScreenPpi::Unread, + }; + // The displays where the last listing has them, each with what the reading of it gave; a + // display the readings have not reached yet is unread. + let listed = self.listed.as_deref().unwrap_or_default(); + let screens = listed + .iter() + .map(|d| { + let [w, h] = [d.size.width, d.size.height].map(|v| i32::try_from(v).unwrap_or(i32::MAX)); + let scale = f64::from_bits(d.scale); + let mm = read.iter().find(|(e, _)| e == d).and_then(|(_, mm)| *mm); + let ppi = mm.map_or(ScreenPpi::Unread, |mm| ScreenPpi::Read(mm.and_then(|mm| points_per_inch(d.size, scale, mm)))); + ScreenDensity { rect: [d.position.x, d.position.y, w, h], scale, ppi } + }) + .collect(); + let densities = Densities { main, screens }; + if self.reported.as_ref() == Some(&densities) { + return None; + } + match main { + ScreenPpi::Read(Some(p)) => log::info!("the window's display has {p:.1} points to an inch"), + ScreenPpi::Read(None) => log::info!("the window's display reports no physical size; an inch is 96 points"), + ScreenPpi::Unread => log::info!("the window's display has not been read; an inch is 96 points"), + } + self.reported = Some(densities.clone()); + Some(densities) + } +} + +impl Tracker { + /// What the last reading gave display `d`, when it answered. + fn earlier(&self, d: &Display) -> Answer { + self.read.as_ref()?.iter().find(|(e, _)| e == d)?.1 + } + + /// Records that reading `displays` failed at `now`; they are read again after [`RETRY_AFTER`] + /// seconds. After an earlier reading, they become the displays known, each with what that + /// reading gave it, if anything. Before any reading, nothing is reported yet. + fn fail(&mut self, displays: Vec, now: f64) { + if self.read.is_some() { + let read = displays.iter().map(|d| (d.clone(), self.earlier(d))).collect(); + self.read = Some(read); + } + self.failed = Some((displays, now)); + } +} + +/// The density, in points per inch, of a display `size` physical pixels wide and high, drawn at +/// `scale` pixels to a point, that the system says is `mm` millimeters wide and high. `None` for a +/// size that is no display's: zero or less, an aspect ratio given in place of the size (16 × 9, +/// 160 × 90 and the like), axes whose densities disagree in either orientation, or a pixel density +/// outside [`vectorcraft_ui_egui::state::SCREEN_PPI_RANGE`]. The range applies to the pixels, before +/// the scale divides them into points. A display turned a quarter turn may report the size of its +/// panel upright, so the axes are also tried swapped. +pub(crate) fn points_per_inch(size: PhysicalSize, scale: f64, mm: [f64; 2]) -> Option { + if !(scale.is_finite() && scale > 0.0) || mm.iter().any(|v| !(v.is_finite() && *v > 0.0)) || aspect_as_size(mm) { + return None; + } + let pixels = [f64::from(size.width), f64::from(size.height)]; + let density = |[w, h]: [f64; 2]| [pixels[0] / (w / MM_PER_INCH), pixels[1] / (h / MM_PER_INCH)]; + let agree = |[x, y]: [f64; 2]| (x - y).abs() <= AXES_AGREE * x.max(y); + let [x, y] = [density(mm), density([mm[1], mm[0]])].into_iter().find(|d| agree(*d))?; + let ppi = (x + y) / 2.0; + vectorcraft_ui_egui::state::SCREEN_PPI_RANGE.contains(&ppi).then_some(ppi / scale) +} + +/// Whether `mm` is an aspect ratio that a display's EDID gave in place of its size: 16:9, 16:10 +/// or 4:3, in centimeters or tenths of them. +fn aspect_as_size(mm: [f64; 2]) -> bool { + const RATIOS: [[f64; 2]; 3] = [[16.0, 9.0], [16.0, 10.0], [4.0, 3.0]]; + let sorted = if mm[0] >= mm[1] { mm } else { [mm[1], mm[0]] }; + RATIOS.iter().any(|r| [1.0, 10.0].iter().any(|k| sorted == [r[0] * k, r[1] * k])) +} + +/// Whether `window` is a Wayland window, whose displays the compositor describes. +#[cfg(target_os = "linux")] +fn is_wayland(window: &winit::window::Window) -> bool { + use winit::raw_window_handle::{HasWindowHandle as _, RawWindowHandle}; + window.window_handle().ok().is_some_and(|h| matches!(h.as_raw(), RawWindowHandle::Wayland(_))) +} + +#[cfg(not(target_os = "linux"))] +fn is_wayland(_: &winit::window::Window) -> bool { + false +} + +/// The system's id of `monitor`: the display id on macOS, the monitor handle on Windows, the RandR +/// CRTC on X11. +#[cfg(target_os = "macos")] +fn native_id(monitor: &MonitorHandle) -> i64 { + use winit::platform::macos::MonitorHandleExtMacOS as _; + i64::from(monitor.native_id()) +} + +#[cfg(windows)] +fn native_id(monitor: &MonitorHandle) -> i64 { + use winit::platform::windows::MonitorHandleExtWindows as _; + monitor.hmonitor() as i64 +} + +#[cfg(target_os = "linux")] +fn native_id(monitor: &MonitorHandle) -> i64 { + use winit::platform::x11::MonitorHandleExtX11 as _; + i64::from(monitor.native_id()) +} + +#[cfg(not(any(target_os = "macos", windows, target_os = "linux")))] +fn native_id(_: &MonitorHandle) -> i64 { + 0 +} + +/// The physical width and height, in millimeters, the system reports for each of `displays`. +#[cfg(target_os = "macos")] +fn read_all(displays: &[Display], _: bool) -> Reading { + Ok(displays + .iter() + .map(|d| { + Ok(u32::try_from(d.id).ok().map(|id| { + let size = objc2_core_graphics::CGDisplayScreenSize(id); + [size.width, size.height] + })) + }) + .collect()) +} + +#[cfg(windows)] +fn read_all(displays: &[Display], _: bool) -> Reading { + Ok(displays + .iter() + .map(|d| { + let dpi = crate::windows_display_size::raw_dpi(d.id as isize)?; + Ok(dpi.map(|[x, y]| [f64::from(d.size.width) / x * MM_PER_INCH, f64::from(d.size.height) / y * MM_PER_INCH])) + }) + .collect()) +} + +#[cfg(target_os = "linux")] +fn read_all(displays: &[Display], wayland: bool) -> Reading { + if wayland { wayland::read_all(displays) } else { x11::read_all(displays) } +} + +#[cfg(not(any(target_os = "macos", windows, target_os = "linux")))] +fn read_all(displays: &[Display], _: bool) -> Reading { + Ok(displays.iter().map(|_| Ok(None)).collect()) +} + +#[cfg(target_os = "linux")] +mod x11 { + use x11rb::CURRENT_TIME; + use x11rb::protocol::randr; + + use super::{Display, Reading, Size}; + + /// The millimeters RandR reports for the first output of each display's CRTC. + pub(super) fn read_all(displays: &[Display]) -> Reading { + let (conn, _) = x11rb::connect(None).map_err(|e| format!("couldn't connect to the X11 display: {e}"))?; + let ask = |e: x11rb::errors::ConnectionError| format!("couldn't ask the X11 display: {e}"); + // RandR answers only a client that gave the version it speaks; 1.2 has CRTCs and outputs. + randr::query_version(&conn, 1, 2).map_err(ask)?.reply().map_err(|e| format!("the X11 display has no RandR 1.2: {e}"))?; + let size = |d: &Display| -> Size { + let Ok(crtc) = u32::try_from(d.id) else { return Ok(None) }; + let info = randr::get_crtc_info(&conn, crtc, CURRENT_TIME) + .map_err(ask)? + .reply() + .map_err(|e| format!("the X11 display has no such CRTC: {e}"))?; + let Some(output) = info.outputs.first() else { return Ok(None) }; + let info = randr::get_output_info(&conn, *output, CURRENT_TIME) + .map_err(ask)? + .reply() + .map_err(|e| format!("the X11 display has no such output: {e}"))?; + Ok(Some([f64::from(info.mm_width), f64::from(info.mm_height)])) + }; + Ok(displays.iter().map(size).collect()) + } +} + +#[cfg(target_os = "linux")] +mod wayland { + use wayland_client::globals::{GlobalListContents, registry_queue_init}; + use wayland_client::protocol::wl_output::{self, WlOutput}; + use wayland_client::protocol::wl_registry::{self, WlRegistry}; + use wayland_client::{Connection, Dispatch, QueueHandle}; + + use super::{Display, Reading}; + + /// The physical size the compositor gives for the output of each display's name, asked on a + /// connection of its own; with no name, or a compositor that names no outputs, the only + /// output's. + pub(super) fn read_all(displays: &[Display]) -> Reading { + let conn = Connection::connect_to_env().map_err(|e| format!("no Wayland compositor: {e}"))?; + let (globals, mut queue) = registry_queue_init::(&conn).map_err(|e| e.to_string())?; + let qh = queue.handle(); + let mut state = Outputs::default(); + for global in globals.contents().clone_list().into_iter().filter(|g| g.interface == "wl_output") { + // Version 4 names the output; older ones give its size only. + let output: WlOutput = globals.registry().bind(global.name, global.version.min(4), &qh, state.outputs.len()); + state.outputs.push((output, Output::default())); + } + // The compositor sends each output's geometry, name and `done` in reply to the bind. + queue.roundtrip(&mut state).map_err(|e| e.to_string())?; + let found: Vec<&Output> = state.outputs.iter().map(|(_, o)| o).collect(); + let named = found.iter().any(|o| o.name.is_some()); + Ok(displays + .iter() + .map(|d| { + let pick = match d.name.as_deref() { + Some(name) if named => found.iter().find(|o| o.name.as_deref() == Some(name)), + _ if found.len() == 1 => found.first(), + _ => None, + }; + Ok(pick.and_then(|o| o.mm)) + }) + .collect()) + } + + /// One output's name and physical size. + #[derive(Default)] + struct Output { + name: Option, + mm: Option<[f64; 2]>, + } + + /// The outputs bound, each with what its events gave. + #[derive(Default)] + struct Outputs { + outputs: Vec<(WlOutput, Output)>, + } + + impl Dispatch for Outputs { + fn event(_: &mut Self, _: &WlRegistry, _: wl_registry::Event, _: &GlobalListContents, _: &Connection, _: &QueueHandle) {} + } + + impl Dispatch for Outputs { + fn event(state: &mut Self, _: &WlOutput, event: wl_output::Event, index: &usize, _: &Connection, _: &QueueHandle) { + let Some((_, output)) = state.outputs.get_mut(*index) else { return }; + match event { + wl_output::Event::Geometry { physical_width, physical_height, .. } => { + output.mm = Some([f64::from(physical_width), f64::from(physical_height)]); + } + wl_output::Event::Name { name } => output.name = Some(name), + _ => {} + } + } + } +} + +#[cfg(test)] +mod tests { + use std::cell::Cell; + use std::sync::mpsc::{Sender, channel}; + + use super::*; + + /// A 14-inch laptop panel at twice its points: 3024 × 1964 pixels, 302 × 196 mm, draws 127 + /// points to an inch, more than the 96 a fixed inch assumes. + #[test] + fn a_laptop_panel_has_more_points_to_an_inch_than_the_reference() { + let ppi = points_per_inch(PhysicalSize::new(3024, 1964), 2.0, [302.0, 196.0]); + assert!(ppi.is_some_and(|p| p > 96.0 && (p - 1512.0 / (302.0 / MM_PER_INCH)).abs() < 1.0), "{ppi:?}"); + } + + /// The same display in a scaled mode (more points on the same glass) draws more points to an + /// inch, and at a higher scale factor fewer: the density counts the window's points. + #[test] + fn the_density_counts_points_at_the_windows_scale() { + let at = |w, h, scale| points_per_inch(PhysicalSize::new(w, h), scale, [527.0, 296.0]).unwrap_or(0.0); + assert!(at(1920, 1080, 1.0) > 0.0); + assert!(at(2560, 1440, 1.0) > at(1920, 1080, 1.0), "more pixels on the same glass"); + assert!(at(3840, 2160, 2.0) < at(3840, 2160, 1.5), "a larger scale factor makes each point larger"); + } + + /// A display turned a quarter turn whose system reports its panel's size upright still + /// measures; axes that disagree either way do not. + #[test] + fn a_turned_display_measures_and_disagreeing_axes_do_not() { + let upright = points_per_inch(PhysicalSize::new(1920, 1080), 1.0, [527.0, 296.0]); + let turned = points_per_inch(PhysicalSize::new(1080, 1920), 1.0, [527.0, 296.0]); + assert!(upright.is_some() && turned.is_some()); + assert!((upright.unwrap_or(0.0) - turned.unwrap_or(1.0)).abs() < 1e-9); + assert_eq!(points_per_inch(PhysicalSize::new(1920, 1080), 1.0, [527.0, 527.0]), None); + } + + /// Sizes no display has give no density: none, an aspect ratio in place of the size, and + /// densities past the range a display can have. + #[test] + fn reports_that_are_no_displays_size_give_no_density() { + let at = |mm| points_per_inch(PhysicalSize::new(1920, 1080), 1.0, mm); + for mm in [[0.0, 0.0], [-1.0, 300.0], [f64::NAN, 300.0], [160.0, 90.0], [16.0, 9.0], [160.0, 100.0], [40.0, 30.0], [9.0, 16.0]] { + assert_eq!(at(mm), None, "{mm:?}"); + } + assert_eq!(points_per_inch(PhysicalSize::new(1920, 1080), 0.0, [527.0, 296.0]), None, "no scale"); + assert_eq!(points_per_inch(PhysicalSize::new(100, 56), 1.0, [5270.0, 2960.0]), None, "under the range"); + assert_eq!(points_per_inch(PhysicalSize::new(7680, 4320), 1.0, [53.0, 30.0]), None, "over it"); + } + + /// The range applies to the display's pixels: a 1920 × 1080 display of 527 × 296 mm drawn at + /// scale 4 has about 23 points to an inch, which is a real density. + #[test] + fn a_large_scale_factor_does_not_put_a_display_out_of_range() { + let ppi = points_per_inch(PhysicalSize::new(1920, 1080), 4.0, [527.0, 296.0]); + let pixels = points_per_inch(PhysicalSize::new(1920, 1080), 1.0, [527.0, 296.0]).unwrap_or(0.0); + assert!(ppi.is_some_and(|p| p < 30.0 && (p - pixels / 4.0).abs() < 1e-9), "{ppi:?}"); + let print = vectorcraft_ui_egui::state::print_ppi(true, ppi); + assert_eq!(print, ppi, "Actual Size counts from it, not from 96"); + } + + /// A 1920 × 1080 display at scale 1 and position `x`, named `name`. + fn display(name: &str, x: i32) -> Display { + Display { + name: Some(name.into()), + position: PhysicalPosition::new(x, 0), + size: PhysicalSize::new(1920, 1080), + scale: 1.0f64.to_bits(), + id: 0, + } + } + + /// The sizes of a 24-inch display (about 92 points to an inch) and a 27-inch one (about 82). + const SIZES: [[f64; 2]; 2] = [[531.0, 299.0], [598.0, 336.0]]; + + /// A reading that gives every display one of [`SIZES`], in turn. + fn sizes(n: usize) -> Reading { + Ok((0..n).map(|i| Ok(Some(SIZES[i % SIZES.len()]))).collect()) + } + + /// Drives a tracker: counts its listings and readings, and hands out the sender of the reading + /// it started last. + struct Rig { + tracker: Tracker, + displays: Vec, + current: usize, + /// The window's display as winit last gave it, when that lags behind the listing. + lagging: Option, + window_scale: f64, + lists: Cell, + reads: Cell, + sender: Option>, + fail_to_start: bool, + } + + impl Rig { + fn new() -> Self { + Self { + tracker: Tracker::default(), + displays: vec![display("left", 0), display("right", 1920)], + current: 0, + lagging: None, + window_scale: 1.0, + lists: Cell::new(0), + reads: Cell::new(0), + sender: None, + fail_to_start: false, + } + } + + fn tick(&mut self, now: f64, enabled: bool) -> Option { + let current = self.lagging.clone().or_else(|| self.displays.get(self.current).cloned()); + let (displays, scale) = (self.displays.clone(), self.window_scale); + let (lists, reads, fail) = (&self.lists, &self.reads, self.fail_to_start); + let mut sender = None; + let out = self.tracker.update( + now, + enabled, + || { + lists.set(lists.get() + 1); + Some((displays, current, scale)) + }, + |_| { + reads.set(reads.get() + 1); + if fail { + return Err("no thread".into()); + } + let (tx, rx) = channel(); + sender = Some(tx); + Ok(rx) + }, + ); + if sender.is_some() { + self.sender = sender; + } + out + } + + fn finish(&mut self, reading: Reading) { + if let Some(tx) = self.sender.take() { + tx.send(reading).unwrap(); + } + } + } + + /// The first listing starts a reading, and the densities arrive once the reading ends, without + /// a frame waiting for it. The main window's density is its display's, and every display gets + /// its own. + #[test] + fn the_densities_arrive_when_the_reading_ends() { + let mut rig = Rig::new(); + assert_eq!(rig.tick(0.0, true), None, "the reading runs in the background"); + assert_eq!(rig.reads.get(), 1); + assert_eq!(rig.tick(2.0, true), None, "still running: no second reading"); + assert_eq!(rig.reads.get(), 1); + rig.finish(sizes(2)); + let got = rig.tick(2.1, true).unwrap_or_else(|| panic!("the densities")); + let ppi = got.screens.iter().map(|s| s.ppi.ppi().unwrap_or(0.0)).collect::>(); + assert!(ppi[0] > ppi[1] && ppi[1] > 0.0, "the smaller display is denser: {ppi:?}"); + assert_eq!(got.main, ScreenPpi::Read(Some(ppi[0])), "the main window is on the left display"); + assert_eq!(got.screens[1].rect, [1920, 0, 1920, 1080]); + assert_eq!(rig.tick(5.0, true), None, "nothing changed"); + assert_eq!(rig.reads.get(), 1, "the same displays are not read again"); + assert_eq!(rig.tick(5.2, false), None, "off, nothing is reported"); + assert_eq!(rig.tick(5.4, true), None, "turned on again, the displays are read again at once"); + assert_eq!(rig.reads.get(), 2); + rig.finish(sizes(2)); + assert_eq!(rig.tick(5.5, true), Some(got), "and the densities reported anew"); + } + + /// The displays are listed at most once a second, and not at all with the preference off. + #[test] + fn the_displays_are_listed_once_a_second_while_the_preference_is_on() { + let mut rig = Rig::new(); + rig.tick(0.0, true); + rig.tick(0.5, true); + assert_eq!(rig.lists.get(), 1); + rig.tick(1.0, true); + assert_eq!(rig.lists.get(), 2); + rig.tick(5.0, false); + assert_eq!(rig.lists.get(), 2, "off, nothing is asked of the system"); + } + + /// The main window moving to the other display reports that display's density without a new + /// reading; a display joining the list is read again, and while a display that changed is + /// read, the densities reported before stay. + #[test] + fn a_change_of_display_is_reported() { + let mut rig = Rig::new(); + rig.tick(0.0, true); + rig.finish(sizes(2)); + let left = rig.tick(0.1, true).and_then(|d| d.main.ppi()); + rig.current = 1; + let right = rig.tick(1.5, true).and_then(|d| d.main.ppi()); + assert!(left.is_some() && right.is_some() && left != right, "{left:?} then {right:?}"); + assert_eq!(rig.reads.get(), 1); + // A window drawn at 1.5 pixels a point (a fractional scale the display does not list) + // has fewer points to an inch than the display's own scale of 1 gives. + rig.window_scale = 1.5; + let scaled = rig.tick(2.6, true).and_then(|d| d.main.ppi()); + assert!(scaled.zip(right).is_some_and(|(s, r)| (s * 1.5 - r).abs() < 1e-9), "{scaled:?} at 1.5, {right:?} at 1"); + rig.window_scale = 1.0; + rig.displays.push(display("third", 3840)); + rig.tick(4.0, true); + assert_eq!(rig.reads.get(), 2, "a new display is read"); + rig.finish(sizes(3)); + rig.tick(4.5, true); + // The window's display changes resolution: until it is read again its density is unread. + rig.displays[1].size = PhysicalSize::new(2560, 1440); + assert_eq!(rig.tick(6.0, true).map(|d| d.main), Some(ScreenPpi::Unread), "the display is being read"); + assert_eq!(rig.reads.get(), 3); + rig.finish(sizes(3)); + let sharper = rig.tick(6.1, true).and_then(|d| d.main.ppi()); + assert!(sharper.zip(right).is_some_and(|(s, r)| s > r), "more pixels on the same glass: {sharper:?}, {right:?}"); + // winit still gives the window's display at its old resolution: it is found by its name. + let mut old = rig.displays[1].clone(); + old.size = PhysicalSize::new(1920, 1080); + rig.lagging = Some(old); + rig.window_scale = 1.25; + let lagging = rig.tick(7.2, true).and_then(|d| d.main.ppi()); + assert!(lagging.zip(sharper).is_some_and(|(l, s)| (l * 1.25 - s).abs() < 1e-9), "{lagging:?} from {sharper:?}"); + rig.lagging = None; + // It changes again and this time the reading fails: its density is unread. + rig.displays[1].size = PhysicalSize::new(3840, 2160); + let reading = rig.tick(8.5, true).unwrap_or_else(|| panic!("a report")); + assert_eq!(reading.main, ScreenPpi::Unread, "the display is being read: {reading:?}"); + assert!(reading.screens.iter().any(|s| s.rect[2] == 3840 && s.ppi == ScreenPpi::Unread), "listed where it is now, unread: {reading:?}"); + rig.finish(Err("the display server went away".into())); + assert_eq!(rig.tick(8.6, true), None, "the failed reading leaves it unread"); + } + + /// A display that changes while a reading runs is read as soon as that reading ends. + #[test] + fn a_change_during_a_reading_is_read_when_it_ends() { + let mut rig = Rig::new(); + rig.tick(0.0, true); + rig.displays[1].size = PhysicalSize::new(2560, 1440); + rig.tick(1.0, true); + assert_eq!(rig.reads.get(), 1, "one reading at a time"); + rig.finish(sizes(2)); + rig.tick(1.2, true); + assert_eq!(rig.reads.get(), 2, "the changed display is read at once"); + } + + /// A display whose size could not be read does not hold back the others, and the displays are + /// read again after a while. + #[test] + fn one_display_that_fails_leaves_the_others() { + let mut rig = Rig::new(); + rig.tick(0.0, true); + rig.finish(Ok(vec![Ok(Some(SIZES[0])), Err("no answer".into())])); + let got = rig.tick(0.1, true).unwrap_or_else(|| panic!("the densities")); + assert!(got.main.ppi().is_some() && got.screens[1].ppi == ScreenPpi::Unread, "the display that did not answer is unread: {got:?}"); + rig.tick(5.0, true); + assert_eq!(rig.reads.get(), 1, "not again at once"); + rig.tick(0.1 + RETRY_AFTER, true); + assert_eq!(rig.reads.get(), 2, "tried again"); + rig.finish(sizes(2)); + let full = rig.tick(11.0, true).unwrap_or_else(|| panic!("the densities")); + assert!(full.screens.iter().all(|s| s.ppi.ppi().is_some()), "{full:?}"); + rig.tick(30.0, true); + assert_eq!(rig.reads.get(), 2, "and left alone once every display was read"); + // A display joins, and the window's display, unchanged, fails to answer: it keeps its size. + rig.displays.push(display("third", 3840)); + rig.tick(32.0, true); + rig.finish(Ok(vec![Err("no answer".into()), Ok(Some(SIZES[1])), Ok(Some(SIZES[0]))])); + let kept = rig.tick(32.1, true).unwrap_or_else(|| panic!("the densities")); + assert!(kept.main.ppi().is_some() && kept.main == full.main, "{kept:?}"); + // A window on no display has its density unread. + rig.current = 9; + assert_eq!(rig.tick(34.0, true).map(|d| d.main), Some(ScreenPpi::Unread)); + // The window's display fails to answer the first reading: its density is unread, not a + // display without a size. + let mut rig = Rig::new(); + rig.tick(0.0, true); + rig.finish(Ok(vec![Err("no answer".into()), Ok(Some(SIZES[1]))])); + let first = rig.tick(0.1, true).unwrap_or_else(|| panic!("the densities")); + assert_eq!((first.main, first.screens[0].ppi), (ScreenPpi::Unread, ScreenPpi::Unread), "{first:?}"); + } + + /// A reading that fails, or a thread that cannot start, is tried again after a while; the + /// same displays are not read on every listing until then. + #[test] + fn a_failed_reading_is_tried_again() { + let mut rig = Rig::new(); + rig.tick(0.0, true); + rig.finish(Err("the display server went away".into())); + assert_eq!(rig.tick(1.0, true), None); + assert_eq!(rig.reads.get(), 1, "not again at once"); + rig.tick(5.0, true); + assert_eq!(rig.reads.get(), 1); + rig.tick(1.0 + RETRY_AFTER, true); + assert_eq!(rig.reads.get(), 2, "tried again"); + rig.finish(sizes(2)); + assert!(rig.tick(12.0, true).is_some_and(|d| d.main.ppi().is_some()), "and read"); + let mut rig = Rig::new(); + rig.fail_to_start = true; + rig.tick(0.0, true); + rig.tick(1.0 + RETRY_AFTER, true); + assert_eq!(rig.reads.get(), 2, "a thread that did not start is tried again too"); + } + + /// Displays that list the same are read again a while after the last reading, so a display + /// replaced by one on the same connector at the same resolution and scale gets its own size. + #[test] + fn displays_that_list_the_same_are_read_again_after_a_while() { + let mut rig = Rig::new(); + rig.tick(0.0, true); + rig.finish(sizes(2)); + let first = rig.tick(0.1, true).unwrap_or_else(|| panic!("the densities")); + rig.tick(0.1 + READ_AGAIN_AFTER - 1.0, true); + assert_eq!(rig.reads.get(), 1, "not before the time is up"); + rig.tick(0.1 + READ_AGAIN_AFTER, true); + assert_eq!(rig.reads.get(), 2, "read again"); + rig.finish(Ok(vec![Ok(Some(SIZES[1])), Ok(Some(SIZES[0]))])); + let replaced = rig.tick(0.2 + READ_AGAIN_AFTER, true).unwrap_or_else(|| panic!("the densities")); + assert!(replaced.main.ppi().is_some() && replaced.main != first.main, "the new panel's density: {first:?} then {replaced:?}"); + } +} diff --git a/apps/vectorcraft/src/windows_display_size.rs b/apps/vectorcraft/src/windows_display_size.rs new file mode 100644 index 0000000000..fc7041ebd6 --- /dev/null +++ b/apps/vectorcraft/src/windows_display_size.rs @@ -0,0 +1,20 @@ +//! Windows: a monitor's raw density, the pixels per inch of the screen itself as Windows reads it +//! from the monitor, for Display Print Size at 100% Zoom (`crate::screen_density`). +//! +//! `GetDpiForMonitor` is a C API with no safe binding, hence the scoped `unsafe_code` allowance. +#![allow(unsafe_code)] + +use windows::Win32::Graphics::Gdi::HMONITOR; +use windows::Win32::UI::HiDpi::{GetDpiForMonitor, MDT_RAW_DPI}; + +/// The horizontal and vertical pixels per inch of the monitor winit's handle `monitor` names: +/// `None` when Windows reports no density for it, an error when the call fails. +pub(crate) fn raw_dpi(monitor: isize) -> Result, String> { + let (mut x, mut y) = (0u32, 0u32); + // SAFETY: `monitor` is a handle winit got from Windows for a connected monitor; a handle that + // has gone stale makes the call fail, which returns an error. Both pointers point at live + // `u32`s for the length of the call. + unsafe { GetDpiForMonitor(HMONITOR(monitor as *mut core::ffi::c_void), MDT_RAW_DPI, &mut x, &mut y) } + .map_err(|e| format!("couldn't read a monitor's density: {e}"))?; + Ok((x > 0 && y > 0).then(|| [f64::from(x), f64::from(y)])) +} diff --git a/assets/icons/dc-arrow-left.svg b/assets/icons/dc-arrow-left.svg new file mode 100644 index 0000000000..4d2ad158b6 --- /dev/null +++ b/assets/icons/dc-arrow-left.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/dc-arrow-right.svg b/assets/icons/dc-arrow-right.svg new file mode 100644 index 0000000000..f53cc9e5ef --- /dev/null +++ b/assets/icons/dc-arrow-right.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/dc-guide-horizontal.svg b/assets/icons/dc-guide-horizontal.svg new file mode 100644 index 0000000000..941eba1f1d --- /dev/null +++ b/assets/icons/dc-guide-horizontal.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/dc-guide-vertical.svg b/assets/icons/dc-guide-vertical.svg new file mode 100644 index 0000000000..3383fd4c22 --- /dev/null +++ b/assets/icons/dc-guide-vertical.svg @@ -0,0 +1 @@ + diff --git a/crates/color/src/lib.rs b/crates/color/src/lib.rs index c3d74615ae..1fdcab123d 100644 --- a/crates/color/src/lib.rs +++ b/crates/color/src/lib.rs @@ -14,6 +14,7 @@ pub mod oklab; pub mod palette_io; pub mod recolor; pub mod swatch; +pub mod wcag; pub use blend::BlendMode; pub use freeform::{Freeform, FreeformMode, FreeformPoint}; diff --git a/crates/color/src/wcag.rs b/crates/color/src/wcag.rs new file mode 100644 index 0000000000..ef42eec957 --- /dev/null +++ b/crates/color/src/wcag.rs @@ -0,0 +1,146 @@ +//! Contrast between two colors as WCAG 2 measures it (): +//! the relative luminance of display sRGB with the 0.04045 threshold, the ratio +//! (L1 + 0.05) / (L2 + 0.05) from 1 to 21, and the minimum ratios of success criteria 1.4.3 +//! (Contrast (Minimum), AA), 1.4.6 (Contrast (Enhanced), AAA) and 1.4.11 (Non-text Contrast, AA). + +/// What the content in front is, which sets the ratio it needs. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum Category { + /// Text below the large-scale size: AA 4.5:1, AAA 7:1. + #[default] + NormalText, + /// Large-scale text (at least 18 pt, or 14 pt bold): AA 3:1, AAA 4.5:1. + LargeText, + /// User interface components and graphical objects: AA 3:1, no AAA level. + Graphics, +} + +impl Category { + pub const ALL: [Category; 3] = [Category::NormalText, Category::LargeText, Category::Graphics]; + + /// The id commands and settings use. + pub fn id(self) -> &'static str { + match self { + Category::NormalText => "normalText", + Category::LargeText => "largeText", + Category::Graphics => "graphics", + } + } + + pub fn parse(s: &str) -> Option { + Self::ALL.into_iter().find(|c| c.id() == s) + } + + /// The English name shown in menus. + pub fn label(self) -> &'static str { + match self { + Category::NormalText => "Normal Text", + Category::LargeText => "Large Text", + Category::Graphics => "Graphics", + } + } + + /// The minimum ratio for AA, and for AAA where the category has that level. + pub fn minimums(self) -> (f64, Option) { + match self { + Category::NormalText => (4.5, Some(7.0)), + Category::LargeText => (3.0, Some(4.5)), + Category::Graphics => (3.0, None), + } + } + + /// Whether `ratio` meets AA, and AAA where the category has that level. The unrounded ratio + /// is compared, so 4.499:1 fails 4.5:1. + pub fn passes(self, ratio: f64) -> (bool, Option) { + let (aa, aaa) = self.minimums(); + (ratio >= aa, aaa.map(|m| ratio >= m)) + } +} + +/// The relative luminance of display sRGB `srgb` (each channel 0 to 1), from 0 for black to 1 +/// for white. +pub fn relative_luminance(srgb: [f32; 3]) -> f64 { + let lin = |v: f32| { + let v = f64::from(v.clamp(0.0, 1.0)); + if v <= 0.04045 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) } + }; + 0.2126 * lin(srgb[0]) + 0.7152 * lin(srgb[1]) + 0.0722 * lin(srgb[2]) +} + +/// The contrast ratio of display sRGB colors `a` and `b`, from 1 to 21, whichever is lighter. +pub fn contrast_ratio(a: [f32; 3], b: [f32; 3]) -> f64 { + let (la, lb) = (relative_luminance(a), relative_luminance(b)); + (la.max(lb) + 0.05) / (la.min(lb) + 0.05) +} + +/// Display sRGB `fg` drawn at `opacity` (0 to 1) over the opaque `bg`, mixed per channel as the +/// canvas mixes a translucent color. +pub fn over(fg: [f32; 3], opacity: f32, bg: [f32; 3]) -> [f32; 3] { + let a = if opacity.is_finite() { opacity.clamp(0.0, 1.0) } else { 1.0 }; + std::array::from_fn(|i| fg[i] * a + bg[i] * (1.0 - a)) +} + +/// `ratio` as text with two decimals, cut off rather than rounded, so a ratio just under a +/// minimum never reads as the minimum: 4.4963 is "4.49:1". +pub fn ratio_text(ratio: f64) -> String { + let r = if ratio.is_finite() { ratio.clamp(1.0, 21.0) } else { 1.0 }; + format!("{:.2}:1", (r * 100.0).floor() / 100.0) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn hex(s: &str) -> [f32; 3] { + let v = |i: usize| u8::from_str_radix(&s[i..i + 2], 16).map_or(0.0, |b| f32::from(b) / 255.0); + [v(0), v(2), v(4)] + } + + #[test] + fn black_on_white_is_21_and_a_color_on_itself_is_1() { + assert!((contrast_ratio(hex("000000"), hex("ffffff")) - 21.0).abs() < 1e-9); + assert!((contrast_ratio(hex("ffffff"), hex("000000")) - 21.0).abs() < 1e-9); + assert!((contrast_ratio(hex("355f78"), hex("355f78")) - 1.0).abs() < 1e-12); + } + + #[test] + fn ratios_near_a_minimum_are_compared_unrounded_and_cut_off_in_text() { + let r = contrast_ratio(hex("fdc96e"), hex("355f78")); + assert!((r - 4.4963).abs() < 1e-3, "{r}"); + assert_eq!(ratio_text(r), "4.49:1"); + assert_eq!(Category::NormalText.passes(r), (false, Some(false))); + assert_eq!(Category::LargeText.passes(r), (true, Some(false))); + let gray = contrast_ratio(hex("767676"), hex("ffffff")); + assert!((gray - 4.542).abs() < 1e-3, "{gray}"); + assert_eq!(ratio_text(gray), "4.54:1"); + assert!(Category::NormalText.passes(gray).0); + let lighter = contrast_ratio(hex("777777"), hex("ffffff")); + assert!((lighter - 4.478).abs() < 1e-3, "{lighter}"); + assert_eq!(ratio_text(lighter), "4.47:1"); + assert!(!Category::NormalText.passes(lighter).0); + assert_eq!(ratio_text(21.0), "21.00:1"); + assert_eq!(ratio_text(f64::NAN), "1.00:1"); + } + + #[test] + fn graphics_have_no_aaa_level() { + assert_eq!(Category::Graphics.passes(3.0), (true, None)); + assert_eq!(Category::Graphics.passes(2.99), (false, None)); + assert_eq!(Category::LargeText.passes(4.5), (true, Some(true))); + } + + #[test] + fn category_ids_parse_back() { + for c in Category::ALL { + assert_eq!(Category::parse(c.id()), Some(c)); + } + assert_eq!(Category::parse("NormalText"), None); + } + + #[test] + fn half_opaque_black_over_white_is_mid_gray() { + assert_eq!(over([0.0; 3], 0.5, [1.0; 3]), [0.5; 3]); + assert_eq!(over([0.2; 3], f32::NAN, [1.0; 3]), [0.2; 3]); + assert_eq!(over([0.2; 3], 2.0, [1.0; 3]), [0.2; 3]); + } +} diff --git a/crates/doc/src/document_guides.rs b/crates/doc/src/document_guides.rs index ba203610d6..909fedd04d 100644 --- a/crates/doc/src/document_guides.rs +++ b/crates/doc/src/document_guides.rs @@ -5,6 +5,15 @@ use super::node::{held_guides, map_held, strip_held}; use super::{Affine, Arc, Document, Node, NodeId, NodeKind, PatternDef, Point, Rect, Selection, SymbolBoxes, Vec2, artboard_holds}; use std::collections::{BTreeMap, HashSet}; +/// What a transform makes of a ruler guide ([`Document::transformed_guide`]). +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum GuideTransform { + /// It stays a ruler guide: vertical at x `pos`, or horizontal at y `pos`. + Ruler { vertical: bool, pos: f64 }, + /// It becomes a guide path along the line between the two points. + Path(Point, Point), +} + impl Document { /// Union of the geometric bounds of `ids` (their visual bounds when `visual`), with symbol /// instances measured by their art ([`Node::geometric_bounds_with`]). @@ -369,6 +378,62 @@ impl Document { Some(if g.vertical { (r.y0, r.y1) } else { (r.x0, r.x1) }) } + /// The line ruler guide `g` stands for as a path: across its artboard for an artboard guide, + /// and across the bounds of all the artboards for a canvas guide. None when there is no + /// artboard to measure a canvas guide by. + pub fn guide_line(&self, g: &Guide) -> Option<(Point, Point)> { + let artboards = || self.artboards.iter().map(|a| a.rect).reduce(|a, b| a.union(b)); + let (a, b) = self.guide_span(g).or_else(|| artboards().map(|r| if g.vertical { (r.y0, r.y1) } else { (r.x0, r.x1) }))?; + Some(if g.vertical { (Point::new(g.pos, a), Point::new(g.pos, b)) } else { (Point::new(a, g.pos), Point::new(b, g.pos)) }) + } + + /// What `xf` makes of ruler guide `g` ([`Self::transform_ruler_guides`]), or None when the + /// document has no line for it ([`Self::guide_line`]). + pub fn transformed_guide(&self, g: &Guide, xf: Affine) -> Option { + let (a, b) = self.guide_line(g)?; + let (a, b) = (xf * a, xf * b); + let tol = 1e-9 * a.distance(b).max(1.0); + Some(if (a.x - b.x).abs() <= tol { + GuideTransform::Ruler { vertical: true, pos: (a.x + b.x) / 2.0 } + } else if (a.y - b.y).abs() <= tol { + GuideTransform::Ruler { vertical: false, pos: (a.y + b.y) / 2.0 } + } else { + GuideTransform::Path(a, b) + }) + } + + /// Apply `xf` to the ruler guides selected in `sel`, each as the line [`Self::guide_line`] + /// gives it. A line that stays vertical or horizontal stays a ruler guide, at its new place. A + /// line at any other angle becomes a guide path with that line, on the guide's layer, named + /// as the guide was; `sel` then holds the path as a selected object instead of the guide. + /// Guides that cannot be edited ([`Self::guide_editable`]) stay as they are. + pub fn transform_ruler_guides(&mut self, sel: &mut Selection, xf: Affine) { + for id in sel.guides.clone() { + let Some(g) = self.ruler_guide(id).filter(|g| self.guide_editable(g)) else { continue }; + let (a, b) = match self.transformed_guide(&g, xf) { + Some(GuideTransform::Ruler { vertical, pos }) => { + self.edit_ruler_guide(id, |g| (g.vertical, g.pos) = (vertical, pos)); + continue; + } + Some(GuideTransform::Path(a, b)) => (a, b), + None => continue, + }; + let Some(layer) = self.parent_of(id) else { continue }; + let path = self.alloc_id(); + let look = crate::Appearance::basic(vectorcraft_color::Paint::None, vectorcraft_color::Paint::None, 0.0); + let mut n = Node::path(path, vectorcraft_geom::shapes::line(a, b), look); + if let NodeKind::Path { guide, .. } = &mut n.kind { + *guide = true; + } + n.name = g.name.clone(); + if self.insert(Some(layer), usize::MAX, n).is_err() { + continue; + } + self.retain_guides(sel, |g| g.id != Some(id)); + sel.objects.push(path); + } + } + /// The ruler guide node `g` names, if this document has it. fn guide_node(&self, g: &Guide) -> Option { g.id.filter(|id| self.node(*id).is_some_and(Node::is_ruler_guide)) diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 2ee96ec2f1..5c52b167a1 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -168,6 +168,7 @@ pub use artboard::{ARTBOARD_GAP, Artboard, ArtboardSide, LockedArtboards, Retire pub use canvas_range::BeyondCanvas; #[cfg(test)] use document_ext::free_id; +pub use document_guides::GuideTransform; pub use graphic_style::{DEFAULT_GRAPHIC_STYLE, GraphicStyle}; pub use guides::{GridPrefs, Guide, RulerMode}; #[cfg(test)] diff --git a/crates/effects/src/group.rs b/crates/effects/src/group.rs index 55e3ad6fe3..74a24c2442 100644 --- a/crates/effects/src/group.rs +++ b/crates/effects/src/group.rs @@ -66,7 +66,7 @@ pub const PATHFINDER_EFFECT_PRECISION: std::ops::RangeInclusive = 0.001..=1 /// The documentation of [`PATHFINDER_OPTION_KEYS`], as a literal for `concat!`. macro_rules! options_doc { () => { - "precision?: pt 0.001..10 (effect.apply: Pathfinder Options › Precision; 0.01 when missing; results are refit to within it and pieces thinner than it are dropped), removeRedundantPoints?: bool (effect.apply: Pathfinder Options › Remove Redundant Points; false when missing; results lose the anchors that don't change their shape to within precision), removeUnpainted?: bool (effect.apply: Pathfinder Options › Divide and Outline Will Remove Unpainted Artwork; false when missing; Divide and Outline leave out the pieces of members with no visible fill, a compound shape's area going by the shape's own fill, except that Divide keeps every piece when the group or compound shape has a visible fill of its own; the other operations ignore it)" + "precision?: pt 0.001..10 (effect.apply: Pathfinder Options › Precision; 0.01 when missing, and a stored value that is not a number evaluates as 0.01; results are refit to within it and pieces thinner than it are dropped; Outline treats crossings closer together than precision / 10000 as one point, or than the tolerance for the art's size when that is larger), removeRedundantPoints?: bool (effect.apply: Pathfinder Options › Remove Redundant Points; false when missing; results lose the anchors that don't change their shape to within precision), removeUnpainted?: bool (effect.apply: Pathfinder Options › Divide and Outline Will Remove Unpainted Artwork; false when missing; Divide and Outline leave out the pieces of members with no visible fill, a compound shape's area going by the shape's own fill, except that Divide keeps every piece when the group or compound shape has a visible fill of its own; the other operations ignore it)" }; } @@ -102,14 +102,21 @@ impl Default for PathfinderEffectOptions { } } +/// The `precision` stored in a Pathfinder effect's parameters `p`, out of range or not, when it is a +/// JSON number. A value of another type (`true`, `"1 pt"`) is not a precision. +pub(crate) fn stored_precision(p: &Value) -> Option { + p.get("precision").and_then(Value::as_f64).filter(|v| v.is_finite()) +} + impl PathfinderEffectOptions { - /// The options in `p`: a missing or non-numeric value takes its default and a precision out of - /// range its nearest bound, so a live effect always evaluates. + /// The options in `p`: a missing value, or one of the wrong type (a precision that is not a + /// number), takes its default, and a precision out of range its nearest bound, so a live effect + /// always evaluates. pub fn from_params(p: &Value) -> Self { let d = PathfinderEffectOptions::default(); let (lo, hi) = (*PATHFINDER_EFFECT_PRECISION.start(), *PATHFINDER_EFFECT_PRECISION.end()); PathfinderEffectOptions { - precision: crate::util::num(p, "precision", d.precision).clamp(lo, hi), + precision: stored_precision(p).unwrap_or(d.precision).clamp(lo, hi), remove_redundant_points: crate::util::flag(p, "removeRedundantPoints", d.remove_redundant_points), remove_unpainted: crate::util::flag(p, "removeUnpainted", d.remove_unpainted), } diff --git a/crates/effects/src/params.rs b/crates/effects/src/params.rs index ab588838a6..fed9df7811 100644 --- a/crates/effects/src/params.rs +++ b/crates/effects/src/params.rs @@ -131,9 +131,12 @@ pub fn scale_effect(e: &mut Effect, s: f64) { let mut keys: Vec<&str> = info.lengths.keys(relative).collect(); keys.extend(merged.as_object().into_iter().flat_map(|m| m.keys()).map(String::as_str).filter(|k| crate::raster_px_range(&e.id, k).is_some())); for k in keys { - let missing = - if k == "precision" && crate::takes_pathfinder_options(&e.id) { crate::PathfinderEffectOptions::default().precision } else { f64::NAN }; - let v = util::num(&merged, k, missing); + // A Pathfinder effect's precision that is not a number scales the precision it evaluates with. + let v = if k == "precision" && crate::takes_pathfinder_options(&e.id) { + crate::group::stored_precision(&merged).unwrap_or(crate::PathfinderEffectOptions::default().precision) + } else { + util::num(&merged, k, f64::NAN) + }; if v.is_finite() { if !e.params.is_object() { e.params = Value::Object(Map::new()); diff --git a/crates/effects/src/tests.rs b/crates/effects/src/tests.rs index 3b0acaa821..f916ee0d87 100644 --- a/crates/effects/src/tests.rs +++ b/crates/effects/src/tests.rs @@ -2186,3 +2186,23 @@ fn a_pathfinder_effects_precision_is_a_distance_that_scales_with_the_object() { assert_eq!(e.params["precision"].as_f64(), Some(8.0), "{id}"); } } + +#[test] +fn a_pathfinder_effects_stored_precision_that_is_not_a_number_is_the_default() { + let d = PathfinderEffectOptions::default().precision; + for v in [json!(true), json!(false), json!("1abc"), json!("5 pt"), json!(null), json!([2.0])] { + assert_eq!(PathfinderEffectOptions::from_params(&json!({ "precision": v })).precision, d, "{v}"); + } + // A number out of range takes its nearest bound. + assert_eq!(PathfinderEffectOptions::from_params(&json!({"precision": 50.0})).precision, *PATHFINDER_EFFECT_PRECISION.end()); + assert_eq!(PathfinderEffectOptions::from_params(&json!({"precision": 0})).precision, *PATHFINDER_EFFECT_PRECISION.start()); + // Scale Strokes & Effects scales the precision such an effect evaluates with. + for (id, _, _) in PATHFINDER_EFFECTS { + for v in [json!(true), json!("1abc")] { + let mut e = crate::new_effect(id, &json!({ "precision": v })).unwrap(); + crate::scale_effect(&mut e, 3.0); + let scaled = e.params["precision"].as_f64().unwrap_or(f64::NAN); + assert!((scaled - d * 3.0).abs() < 1e-12, "{id} {v}: {scaled}"); + } + } +} diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index cf21c25e46..7e6028b045 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -105,8 +105,9 @@ proptest = { workspace = true } vectorcraft-text = { workspace = true, features = ["test-fonts"] } # How many times an open reads a PDF. vectorcraft-pdf = { workspace = true, features = ["read-count"] } -# How many times the symbol list is read to find symbols by name. -vectorcraft-doc = { workspace = true, features = ["symbol-read-count"] } +# How many times the symbol list is read to find symbols by name, and how many objects are +# measured against locked artboards. +vectorcraft-doc = { workspace = true, features = ["symbol-read-count", "locked-artboard-count"] } wat = { workspace = true } # Zstandard streams for the Illustrator editing data fuzz tests. ruzstd = { workspace = true } diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 56f955106b..74a10d337f 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -855,7 +855,7 @@ pub(crate) use object::bounds_rewrite; pub(crate) use object::{keep_aligned_in, refresh_pixel_aligned}; /// The rules `object.scale`, `object.reflect` and `object.shear` check their params with. pub use object::{reflect_axis, scale_factors, shear_tangent}; -pub(crate) use paint::{LIVE_PAINT_BUCKET, asks_defaults_only}; +pub(crate) use paint::{asks_defaults_only, painting_tool_of}; pub use plugin_call::{Location, ParamsPlace, key_location, location_in, location_keys}; pub use select::SIMILAR; pub(crate) use vectorcraft_doc::range::parse_range; diff --git a/crates/engine/src/cmd/addons/pathtools/shape.rs b/crates/engine/src/cmd/addons/pathtools/shape.rs index fc88442997..6c16893aba 100644 --- a/crates/engine/src/cmd/addons/pathtools/shape.rs +++ b/crates/engine/src/cmd/addons/pathtools/shape.rs @@ -4,13 +4,15 @@ //! (`vectorcraft_tools::addons::parametric_shape`), which SVG export leaves out. use serde_json::{Value, json}; -use vectorcraft_doc::{Node, NodeKind}; +use vectorcraft_doc::{Document, Node, NodeKind}; use vectorcraft_geom::{FillRule, PathData, Point}; use vectorcraft_pathops::addons::pathtools::shapes::{ParametricShape, ShapeKind, recognise}; +use vectorcraft_render::effects; use vectorcraft_tools::addons::parametric_shape::{CREATE, EDIT, KEY, apply, read, stored, to_json}; +use super::super::super::menucmds::whole_or; use super::super::super::{CommandSpec, bad, checked_id, checked_ids_or_selection, cmd, has_doc, has_selection}; -use crate::{EngineError, Result, Session}; +use crate::{EngineError, MAX_COORD, Result, Session}; /// The undo step's name and the command's label. const CONVERT: &str = "Convert to Parametric Shape"; @@ -31,7 +33,7 @@ pub fn specs() -> Vec { "Edit Parametric Shape", [], None, - "{id, kind?, center?, width?, height?, rotation?: degrees clockwise (0: upright), count?, a?, b?, radius?} change a parametric shape's numbers (as addon.pathtools.shape.create takes them; a new kind takes its own defaults for the values not given), as one undo step; with none, or the same ones, nothing changes → {id, shape (its numbers now)}", + "{id, kind?, center?, width?, height?, rotation?: degrees clockwise (0: upright), count?, a?, b?, radius?, reference?: 0..8 (a point on the 9-point grid of the bounding box as object.setBounds measures it, rotated with rotated objects)} change a parametric shape's numbers (as addon.pathtools.shape.create takes them; a new kind takes its own defaults for the values not given), as one undo step; with `reference` and no `center`, that point of the bounding box keeps its place (as the Transform panel's W and H do; snapping to the pixel grid and an attachment to a path apply afterwards), otherwise the center stays; with none, or the same ones, nothing changes → {id, shape (its numbers now; null when snapping to the pixel grid left a plain path)}", has_doc, set ), @@ -95,15 +97,55 @@ fn set(s: &mut Session, p: &Value) -> Result { return Err(bad(C, "the path is locked or hidden")); } let old = d.node(id).and_then(read).ok_or_else(|| bad(C, "the object is not an editable parametric shape"))?; + let reference = match p.get("reference").filter(|v| !v.is_null()) { + Some(_) => match whole_or(p, "reference", 4, C)? { + i @ 0..=8 => Some(i as usize), + _ => return Err(bad(C, "`reference` must be from 0 to 8")), + }, + None => None, + }; let shape = apply(old, p).map_err(|e| bad(C, e))?; if shape != old { + // Without a center, the reference point of the bounding box (as the Transform panel and + // `object.setBounds` measure it; the geometric box where the preview leaves none) keeps + // its place: the new outline moves onto it. The box after the edit is measured the same way + // as the box before it. + let how = s.bounds_measure(); + let geometric = effects::preview::Measure { preview: false, ..how }; + let boxed = |d: &Document, m: effects::preview::Measure| effects::preview::oriented_bounds_with(d, &[id], m).map(|b| (m, b)); + let keep = match reference.filter(|_| p.get("center").is_none_or(Value::is_null)) { + Some(i) => { + let d = &s.doc()?.doc; + let (m, b) = boxed(d, how).or_else(|| boxed(d, geometric)).ok_or_else(|| EngineError::Other("no bounds".into()))?; + Some((i, m, b.reference_point(i))) + } + None => None, + }; let path = outline(&shape, C)?; s.edit(EDIT, |d, sel| { shape_node(d.node_mut(id).ok_or(EngineError::NoNode(id))?, &shape, path); + if let Some((i, m, was)) = keep + && let Some(now) = boxed(d, m).map(|(_, b)| b.reference_point(i)) + && now != was + { + let mut moved = shape; + moved.center += was - now; + let path = outline(&moved, C)?; + shape_node(d.node_mut(id).ok_or(EngineError::NoNode(id))?, &moved, path); + } + // A shape named by `id` and not selected is not checked after the edit: one the edit + // takes past the coordinate limit is an error here, and nothing changes. + if !crate::sanity::objects_in_range(d, &[id]) { + return Err(bad(C, format!("coordinate out of range (limit ±{MAX_COORD} pt)"))); + } sel.anchors.remove(&id); sel.segments.remove(&id); Ok(()) })?; + // The numbers the edit committed (an object attached to a path is put back on it); none + // when snapping to the pixel grid left a plain path. + let committed = s.doc()?.doc.node(id).and_then(read); + return Ok(json!({ "id": id.0, "shape": committed.map_or(Value::Null, |c| to_json(&c)) })); } Ok(json!({ "id": id.0, "shape": to_json(&shape) })) } diff --git a/crates/engine/src/cmd/addons/pathtools/tests.rs b/crates/engine/src/cmd/addons/pathtools/tests.rs index 8cd83bacfd..c474cfae85 100644 --- a/crates/engine/src/cmd/addons/pathtools/tests.rs +++ b/crates/engine/src/cmd/addons/pathtools/tests.rs @@ -476,6 +476,92 @@ fn set_changes_the_numbers_in_one_step_and_nothing_without_a_change() { assert_eq!(path(&s, id).anchor_count(), 16); } +#[test] +fn set_keeps_the_reference_point_of_the_bounding_box_in_place() { + let mut s = session(); + let corner = |s: &Session, id: NodeId, i: usize| s.transform_box(&[id]).unwrap().reference_point(i); + // (kind, its own rotation, a turn with object.rotate, which turns its bounding box too) + for (kind, rotation, turn) in [ + ("rectangle", 0.0, 0.0), + ("rectangle", 30.0, 0.0), + ("rectangle", 180.0, 0.0), + ("rectangle", 0.0, 30.0), + ("star", 0.0, 0.0), + ("heart", 0.0, 0.0), + ] { + let r = s.execute("addon.pathtools.shape.create", &json!({"kind": kind, "center": [200, 150], "rotation": rotation})).unwrap(); + let id = id_of(&r); + if turn != 0.0 { + s.execute("object.rotate", &json!({"angle": turn, "origin": [200, 150]})).unwrap(); + assert!(s.transform_box(&[id]).unwrap().angle != 0.0, "the box turns with the object"); + } + // Each of the 9 points of the box the Transform panel shows stays where it was while the + // width and then the height change, as `object.setBounds` keeps it. + for refi in 0..9 { + for key in ["width", "height"] { + let (before, was) = (shape_of(&s, id).unwrap(), corner(&s, id, refi)); + let grown = if key == "width" { before.width } else { before.height } + 10.0; + s.execute("addon.pathtools.shape.set", &json!({"id": id.0, key: grown, "reference": refi})).unwrap(); + let moved = corner(&s, id, refi).distance(was); + assert!(moved < 1e-6, "{kind} at {rotation}°, reference {refi}, {key}: the point moved {moved} pt"); + let after = shape_of(&s, id).unwrap(); + assert!((if key == "width" { after.width } else { after.height } - grown).abs() < 1e-9, "{kind}, {key}: the new size"); + } + } + // Without a reference point, and with an explicit center, the old rules hold. + s.execute("addon.pathtools.shape.set", &json!({"id": id.0, "width": 80})).unwrap(); + let c = shape_of(&s, id).unwrap().center; + s.execute("addon.pathtools.shape.set", &json!({"id": id.0, "width": 120})).unwrap(); + assert!(shape_of(&s, id).unwrap().center.distance(c) < 1e-9, "the center stays by default"); + s.execute("addon.pathtools.shape.set", &json!({"id": id.0, "width": 60, "center": [10, 20], "reference": 0})).unwrap(); + assert!(shape_of(&s, id).unwrap().center.distance(Point::new(10.0, 20.0)) < 1e-9, "a center given wins"); + } + let id = star(&mut s); + refuses( + &mut s, + "addon.pathtools.shape.set", + &[ + json!({"id": id.0, "width": 50, "reference": -1}), + json!({"id": id.0, "width": 50, "reference": 1.5}), + json!({"id": id.0, "width": 50, "reference": 9}), + json!({"id": id.0, "width": 50, "reference": 9.0}), + ], + ); + // A whole number written with a decimal point picks the same point. + s.execute("addon.pathtools.shape.set", &json!({"id": id.0, "width": 50, "reference": 8.0})).unwrap(); + let written_whole = shape_of(&s, id).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("addon.pathtools.shape.set", &json!({"id": id.0, "width": 50, "reference": 8})).unwrap(); + assert!(shape_of(&s, id).unwrap().center.distance(written_whole.center) < 1e-9, "`8.0` and `8` pick the same point"); + s.execute("edit.undo", &json!({})).unwrap(); + // With Use Preview Bounds the point is on the box as drawn: a star's stroked tips reach past + // its anchors by more as the star is stretched, so the drawn box and the anchors' box move apart. + s.prefs.use_preview_bounds = true; + let stroked = id_of(&s.execute("addon.pathtools.shape.create", &json!({"kind": "star", "center": [300, 300], "count": 5})).unwrap()); + s.execute("paint.setStroke", &json!({"ids": [stroked.0], "color": "#000000"})).unwrap(); + s.execute("stroke.set", &json!({"ids": [stroked.0], "weight": 12})).unwrap(); + let geometric = |s: &Session, i: usize| s.doc().unwrap().doc.oriented_bounds(&[stroked], false).unwrap().reference_point(i); + for refi in [0, 2, 6, 8] { + let (was, anchors_were) = (corner(&s, stroked, refi), geometric(&s, refi)); + let wide = shape_of(&s, stroked).unwrap().width * 2.5; + s.execute("addon.pathtools.shape.set", &json!({"id": stroked.0, "width": wide, "reference": refi})).unwrap(); + let moved = corner(&s, stroked, refi).distance(was); + assert!(moved < 1e-6, "stroked star, reference {refi}: the drawn box's point moved {moved} pt"); + assert!(geometric(&s, refi).distance(anchors_were) > 1e-3, "reference {refi}: the anchors' box is not the one kept"); + s.execute("edit.undo", &json!({})).unwrap(); + } + s.prefs.use_preview_bounds = false; + // A shape set by id, not selected, that the edit would take past the coordinate limit. + let edge = id_of(&s.execute("addon.pathtools.shape.create", &json!({"kind": "rectangle", "center": [3_999_900, 100]})).unwrap()); + select(&mut s, &[]); + refuses( + &mut s, + "addon.pathtools.shape.set", + &[json!({"id": edge.0, "width": 180, "reference": 0}), json!({"id": edge.0, "center": [3_999_990, 100]})], + ); + s.execute("addon.pathtools.shape.set", &json!({"id": edge.0, "width": 180, "reference": 2})).unwrap(); +} + #[test] fn bad_shape_params_are_refused() { let mut s = session(); diff --git a/crates/engine/src/cmd/colorcmds.rs b/crates/engine/src/cmd/colorcmds.rs index 5f4b7b05f4..063c25f4b2 100644 --- a/crates/engine/src/cmd/colorcmds.rs +++ b/crates/engine/src/cmd/colorcmds.rs @@ -14,7 +14,8 @@ use std::sync::Arc; use serde_json::{Value, json}; use vectorcraft_color::cms::Model; use vectorcraft_color::harmony::{self, Guide, GuideOptions, Harmony}; -use vectorcraft_color::{Color, Paint, keep_model}; +use vectorcraft_color::wcag::{self, Category}; +use vectorcraft_color::{BlendMode, Color, Paint, keep_model}; use vectorcraft_doc::live::lerp_color; use vectorcraft_doc::pattern::PatternDef; pub(crate) use vectorcraft_doc::recolor::map_paint; @@ -135,6 +136,15 @@ pub fn specs() -> Vec { always, harmony ), + cmd!( + query "color.contrast", + "Contrast", + [], + None, + "{color?: a color (#rrggbbaa and #rgba are refused; default the active Fill or Stroke proxy's color, or its selected gradient stop or freeform point, or a gradient mesh's first picked point; a picked object's solid color mixed towards the fill that stains its dynamic symbol instance), against?: a color or \"below\" (default: the color VectorCraft draws at the center of the selection's bounds with the selected objects hidden, as the canvas shows it without template layers and guides; a picked object of a dynamic symbol instance hides only itself and is measured at its own center; needs a selection), opacity?: 0..100 (default the opacity the proxy's color is drawn with: the object's opacity times that of its groups and layer (for a picked symbol object, also of its instance and the groups of the symbol's art around it), its fill's or stroke's row (not for type's character paint) and a stop's or point's own, a translucent group or layer drawing the art inside it, the art behind the object included, over what is outside it; 100 for a given `color`)} the WCAG 2 contrast ratio (https://www.w3.org/TR/WCAG22/#dfn-contrast-ratio) of the color, drawn at that opacity over the background with the blend modes the proxy's color is drawn with (its row's, the object's and those of its groups and layer, innermost first, each blending the result with the art below it inside the object, groups and layer around it, the object's rows below its row included (with `against` or `opacity` given, with the background); inside an object, group or layer that isolates its blending, the modes blend only with the art it holds; Normal for a given `color`), against the background, in display sRGB: normal text needs 4.5:1 for AA and 7:1 for AAA, large text 3:1 and 4.5:1, and graphics 3:1 for AA; the unrounded ratio is compared → {ratio, against: \"#rrggbb\" (the background in working RGB, as `against` takes it; the sampled one rounded to 8 bits, so giving it back answers the same ratio unless `opacity` is omitted and a group or layer around the object is translucent, has a blend mode or isolates its blending, or the measured row is translucent or blends over rows below it, since a given background stands for the art below each such level), normalText: {aa, aaa}, largeText: {aa, aaa}, graphics: {aa}}", + always, + contrast + ), ] } @@ -701,8 +711,15 @@ impl Indexing { v.as_f64().filter(|x| (0.0..=100.0).contains(x)).ok_or_else(|| bad(C, "`ditherAmount` must be a number from 0 to 100"))?.round() as u8 } }; - let options = - |r: Reduction| PaletteOptions { colors: colors.unwrap_or(256), reduction: r, dither, dither_amount, transparency: true, matte: None }; + let options = |r: Reduction| PaletteOptions { + colors: colors.unwrap_or(256), + reduction: r, + dither, + dither_amount, + transparency: true, + matte: None, + ..PaletteOptions::default() + }; let refuse_colors = |name: &str| match colors { Some(_) => Err(bad(C, format!("`colors` does not apply to the {name} reduction"))), None => Ok(()), @@ -984,3 +1001,625 @@ fn harmony(s: &mut Session, p: &Value) -> Result { let hex = |cs: &[Color]| cs.iter().map(Color::to_hex).collect::>(); Ok(json!({ "rule": rule.id(), "colors": hex(&g.colors), "grid": g.grid.iter().map(|r| hex(r)).collect::>() })) } + +/// The side, in points, of the square [`color_below`] renders. +const BELOW_SIDE: f64 = 1.0; +/// The pixels per point [`color_below`] renders at. +const BELOW_SCALE: f64 = 4.0; + +fn contrast(s: &mut Session, p: &Value) -> Result { + const C: &str = "color.contrast"; + check_numbers(p, &["opacity"], C)?; + let opacity = match p.get("opacity").and_then(Value::as_f64) { + Some(o) if (0.0..=100.0).contains(&o) => Some(o as f32 / 100.0), + Some(_) => { + let key = "opacity"; + return Err(bad(C, format!("`{key}` must be from 0 to 100"))); + } + None => None, + }; + let below = p.get("against").is_none_or(|v| v.is_null() || v.as_str() == Some("below")); + let (color, drawn) = match p.get("color") { + None | Some(Value::Null) => proxy_color(s, opacity.is_some(), below).map_err(|e| bad(C, e))?, + Some(v) => (color_value(v).ok_or_else(|| bad(C, "invalid `color`"))?, Drawn::default()), + }; + let rich_black = s.prefs.black_on_screen == "rich"; + let cms = vectorcraft_color::cms::active(); + let shown = |c: &Color| match *c { + Color::Cmyk { c, m, y, k } if rich_black && c <= 0.0 && m <= 0.0 && y <= 0.0 && k >= 1.0 => [0.0; 3], + _ => cms.display_rgb(c), + }; + let to_8bit = |c: [f32; 3]| c.map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8); + // The background in display sRGB, and as the working RGB `#rrggbb` a given `against` reads as. + let (against, written) = match p.get("against").filter(|_| !below) { + None => { + // The sample in working RGB, rounded to 8 bits: the background the answer writes is the + // one the ratio uses, and giving it back answers the same ratio. + let working = to_8bit(cms.srgb_to_rgb(color_below(s, rich_black, None, &[], None).map_err(|e| bad(C, e))?.0)); + (cms.rgb_to_srgb(working.map(|v| f32::from(v) / 255.0)), working) + } + Some(v) => { + let key = "against"; + let shown = shown(&color_value(v).ok_or_else(|| bad(C, format!("`{key}` must be a color or {}", "\"below\"")))?); + (shown, to_8bit(cms.srgb_to_rgb(shown))) + } + }; + // Innermost first: the row (inside the object), the object, then its groups and layer. A given + // opacity takes the place of the object's and of its groups' and layer's. + let row = drawn.row.map(|(blend, o)| Step { + blend, + opacity: if opacity.is_some() { 1.0 } else { o }, + isolate: false, + hide: Some(Part::Rows), + within: Part::Rows, + }); + let object = Step { blend: drawn.blend, opacity: opacity.unwrap_or(drawn.opacity), isolate: drawn.isolate, hide: None, within: Part::Object }; + let groups = drawn.around.iter().map(|l| Step { + blend: l.blend, + opacity: if opacity.is_some() { 1.0 } else { l.opacity }, + isolate: l.isolate, + hide: Some(l.part.clone()), + within: l.part.clone(), + }); + let steps = row.into_iter().chain([object]).chain(groups).collect::>(); + // With the background sampled and no opacity given, each level blends with and draws over the + // art below it inside the levels around it, as the canvas composites groups; otherwise the + // background stands for that art. Inside an object, group or layer that isolates its blending, + // the art below is only what that level holds (nothing, for a given background). + let sampled = below && opacity.is_none(); + // A level with a blend mode that does not isolate draws what is inside it over the art below it, + // then takes that art back out by the alpha of what it holds drawn alone, and blends the rest: + // `alone` is the alpha of what the next level out holds drawn alone. Each level's opacity + // applies to what it holds, and the art beside it in the level around it adds to the alpha once. + let blends = |a: &Step| a.blend != BlendMode::Normal && !a.isolate; + let mut x = (shown(&color), 1.0f32); + let mut alone = 1.0f32; + for (k, step) in steps.iter().enumerate() { + if step.blend == BlendMode::Normal && step.opacity >= 1.0 && x.1 >= 1.0 && alone >= 1.0 { + continue; + } + let above = &steps[k + 1..]; + let scope = above.iter().find(|a| a.isolate); + let full = above.iter().filter(|a| a.blend != BlendMode::Normal || a.opacity < 1.0).map(|a| &a.within).collect::>(); + let read = |scope: Option<&Part>| color_below(s, rich_black, step.hide.as_ref(), &full, scope).map_err(|e| bad(C, e)); + let backdrop = match scope { + Some(_) if !sampled => ([0.0; 3], 0.0), + None if !sampled => (against, 1.0), + // The background itself, as the answer writes it. + None if step.hide.is_none() && full.is_empty() => (against, 1.0), + _ => read(scope.map(|a| &a.within))?, + }; + // The alpha of the art below the level inside the level around it, while a blending level + // lies further out (none for a given background). + let inner = match above.first() { + Some(around) if sampled && above.iter().take_while(|a| !a.isolate).any(blends) => read(Some(&around.within))?.1, + _ => 0.0, + }; + let source = if !blends(step) { + x + } else if alone <= 0.0 { + (x.0, 0.0) + } else { + (std::array::from_fn(|i| ((x.0[i] * x.1 - (1.0 - alone) * backdrop.0[i] * backdrop.1) / alone).clamp(0.0, 1.0)), alone) + }; + // A level that isolates its blending carries out the alpha of what it holds composited on + // its own. + let drawn = if step.isolate { x.1 } else { alone } * step.opacity.clamp(0.0, 1.0); + x = composite(step.blend, source, step.opacity, backdrop); + alone = drawn + inner * (1.0 - drawn); + } + let front = if x.1 >= 1.0 { x.0 } else { wcag::over(x.0, x.1, against) }; + let ratio = wcag::contrast_ratio(front, against); + let levels = |c: Category| { + let (aa, aaa) = c.passes(ratio); + match aaa { + Some(aaa) => json!({ "aa": aa, "aaa": aaa }), + None => json!({ "aa": aa }), + } + }; + let [r, g, b] = written; + Ok(json!({ + "ratio": ratio, + "against": format!("#{r:02x}{g:02x}{b:02x}"), + "normalText": levels(Category::NormalText), + "largeText": levels(Category::LargeText), + "graphics": levels(Category::Graphics), + })) +} + +/// An object around the proxy's object: one in the document, or a group of the picked object's +/// dynamic symbol instance's art, by its path in the art (the art's root for an empty path). For +/// [`color_below`], also the objects the proxy's color comes from, or their rows from the one the +/// proxy shows up. +#[derive(Clone, PartialEq)] +enum Part { + Doc(NodeId), + Art(Vec), + Object, + Rows, +} + +/// An object around the proxy's object that draws it: its opacity, blend mode, whether it isolates +/// the blending inside it, and which object it is. +#[derive(Clone, PartialEq)] +struct Level { + opacity: f32, + blend: BlendMode, + isolate: bool, + part: Part, + /// Whether it has an opacity mask that is not disabled. + masked: bool, +} + +/// Whether object `n` has an opacity mask that is not disabled. +fn masked(n: &Node) -> bool { + n.extras().mask.as_ref().is_some_and(|m| !m.disabled) +} + +/// How the proxy's color is drawn: the object's opacity, its fill or stroke row's blend mode and +/// opacity (none for type's character paint or a colorize color), each times that of a stop or +/// point when it holds the paint, the object's blend mode and whether it isolates its blending, and +/// the groups and layer around the object, innermost first. +#[derive(Clone, PartialEq)] +struct Drawn { + opacity: f32, + row: Option<(BlendMode, f32)>, + blend: BlendMode, + isolate: bool, + around: Vec, + /// The object's shown fill and stroke rows with paint below the row, which the row draws over. + lower: Vec, +} + +impl Default for Drawn { + fn default() -> Self { + Self { opacity: 1.0, row: None, blend: BlendMode::Normal, isolate: false, around: vec![], lower: vec![] } + } +} + +/// One level [`contrast`] draws the color through: the row, the object, or a [`Level`]. `hide` is +/// what [`color_below`] hides to read the art below it (`None`: the selection), and `within` the +/// object whose art is read inside it. +struct Step { + blend: BlendMode, + opacity: f32, + isolate: bool, + hide: Option, + within: Part, +} + +/// `x` (a display sRGB color and its alpha) drawn at `opacity` with blend mode `mode` over `backdrop` +/// (likewise), as the PDF compositing formulas give it: the mode applies where the backdrop is +/// drawn, and over nothing the color stays as it is. +fn composite(mode: BlendMode, x: ([f32; 3], f32), opacity: f32, backdrop: ([f32; 3], f32)) -> ([f32; 3], f32) { + let (b, ab) = backdrop; + let a = x.1 * if opacity.is_finite() { opacity.clamp(0.0, 1.0) } else { 1.0 }; + let mixed = vectorcraft_color::blend::blend_rgb(mode, b, x.0); + let out = a + ab * (1.0 - a); + if out <= 0.0 { + return (b, 0.0); + } + (std::array::from_fn(|i| (a * ((1.0 - ab) * x.0[i] + ab * mixed[i]) + ab * (1.0 - a) * b[i]) / out), out) +} + +/// Whether `a` and `b` draw a color alike: the same blend modes and isolation, and unless +/// `given_opacity` (which takes the place of their opacities) the same opacities. With `below`, the +/// levels that change what they draw must be the same objects too, since the art below each one is +/// read with that object hidden, and the object's opacity must be the same apart from its row's, +/// since the row draws over the object's rows below it and the object over the art behind it, and a +/// row that blends or is translucent must lie over the same shown rows. +fn draws_alike(a: &Drawn, b: &Drawn, given_opacity: bool, below: bool) -> bool { + let counts = |l: &&Level| l.blend != BlendMode::Normal || l.isolate || (!given_opacity && l.opacity < 1.0); + let level = |x: &Level, y: &Level| { + x.blend == y.blend + && x.isolate == y.isolate + && (given_opacity || (x.opacity - y.opacity).abs() < 1e-6) + && (!below || given_opacity || x.part == y.part) + }; + let (la, lb) = (a.around.iter().filter(counts).collect::>(), b.around.iter().filter(counts).collect::>()); + // A row in Normal mode draws as type's character paint does, and an object's isolation only + // changes a row's blending. + let row = |d: &Drawn| d.row.map(|r| r.0).filter(|m| *m != BlendMode::Normal); + let total = |d: &Drawn| d.opacity * d.row.map_or(1.0, |r| r.1); + // A row that blends or lets art through draws over the rows below it, read at one point. + let over_rows = |d: &Drawn| d.row.is_some_and(|(m, o)| m != BlendMode::Normal || o < 1.0); + row(a) == row(b) + && (given_opacity || !below || !(over_rows(a) || over_rows(b)) || a.lower == b.lower) + && a.blend == b.blend + && (row(a).is_none() || a.isolate == b.isolate) + && (given_opacity || (total(a) - total(b)).abs() < 1e-6) + && (given_opacity || (row(a).is_none() && !below) || (a.opacity - b.opacity).abs() < 1e-6) + && la.len() == lb.len() + && la.iter().zip(&lb).all(|(x, y)| level(x, y)) +} + +/// The active proxy's color (its selected gradient stop or freeform point, else the first, or a +/// gradient mesh's first picked point, each at its own opacity) and how +/// it is drawn ([`Drawn`]). With `given_opacity`, the opacities of the selected objects are not +/// compared, since the given opacity takes their place; with `below` (the background is sampled), +/// objects in different translucent or blending groups or layers differ, since the art below each +/// such level is read with it hidden. +fn proxy_color(s: &Session, given_opacity: bool, below: bool) -> std::result::Result<(Color, Drawn), String> { + let stroke = !s.fill_active; + let (fill_mixed, stroke_mixed) = s.proxy_mixed(); + if if stroke { stroke_mixed } else { fill_mixed } { + return Err("the selected objects' colors differ: give `color`".into()); + } + let (fill, stroke_paint) = s.proxy_paints(); + // The Fill proxy shows a gradient mesh's picked points, each drawn at its own opacity. + let points = if stroke { vec![] } else { s.fill_mesh_points() }; + let source = || { + s.proxy_source(stroke) + .map(|(n, item)| { + let d = drawn_settings(s, &n, item, stroke)?; + Ok::<_, String>(match picked_opacities(&n, &points).first() { + Some(o) => at(&d, *o), + None => d, + }) + }) + .transpose() + }; + let drawing; + // Selected objects that share a color but draw it differently have no one answer. + if let Some(st) = s.active().filter(|st| st.selection.symbol_part.is_none()) { + let item = s.appearance_item(); + // Every painted object inside a selected group counts, as the proxy's color comes from all, + // except hidden ones and those inside a hidden group, which draw nothing. The first shown + // one gives the opacity and blend modes the answer uses. + let shown = |id: NodeId| st.doc.ancestry(id).unwrap_or_default().iter().all(|a| st.doc.node(*a).is_some_and(|x| x.visible)); + let mut drawn = vec![]; + for n in st.selection.subjects().iter().filter_map(|id| st.doc.node(*id)) { + for (n, item) in shown_sources(n, item, stroke).into_iter().filter(|(c, _)| shown(c.id)) { + let d = drawn_settings(s, n, item, stroke)?; + let picked = picked_opacities(n, &points); + if picked.is_empty() { + drawn.push(d); + } else { + drawn.extend(picked.into_iter().map(|o| at(&d, o))); + } + } + } + drawing = match drawn.first() { + Some(first) => first.clone(), + None => source()?.unwrap_or_default(), + }; + if !drawn.iter().all(|d| draws_alike(d, &drawing, given_opacity, below)) { + // With `opacity` given, the opacities are not compared and the background stands for the + // art below. + if !given_opacity && drawn.iter().all(|d| draws_alike(d, &drawing, true, below)) { + return Err("the selected objects' colors differ: give `opacity` or `color`".into()); + } + return Err("the selected objects' colors differ: give `color`".into()); + } + } else { + drawing = source()?.unwrap_or_default(); + } + let no_color = || "the active fill or stroke has no color: give `color`".to_string(); + match if stroke { stroke_paint } else { fill } { + Paint::Solid { color, .. } => Ok((stained(s, color), drawing)), + Paint::Gradient(g) if g.gradient.kind == vectorcraft_color::GradientKind::Freeform => { + let f = g.freeform_on(vectorcraft_geom::Rect::new(0.0, 0.0, 1.0, 1.0)); + let i = s.selected_freeform_point().filter(|i| *i < f.points.len()).unwrap_or(0); + f.points.get(i).map(|pt| (pt.color, at(&drawing, pt.opacity))).ok_or_else(no_color) + } + Paint::Gradient(g) => { + let i = s.selected_stop().unwrap_or(0).min(g.gradient.stops.len().saturating_sub(1)); + g.gradient.stops.get(i).map(|st| (st.color, at(&drawing, st.opacity))).ok_or_else(no_color) + } + Paint::None | Paint::Pattern { .. } => Err(no_color()), + } +} + +/// `drawing` with a stop's or point's `opacity`, which applies where its paint is drawn: in its +/// row, else in the object. +fn at(drawing: &Drawn, opacity: f32) -> Drawn { + match drawing.row { + Some((m, o)) => Drawn { row: Some((m, o * opacity)), ..drawing.clone() }, + None => Drawn { opacity: drawing.opacity * opacity, ..drawing.clone() }, + } +} + +/// The opacities of the picked points of gradient mesh `n` ([`Session::fill_mesh_points`]), whose +/// colors the Fill proxy shows for it: empty for another object or with no points picked. +fn picked_opacities(n: &Node, points: &[(NodeId, Vec)]) -> Vec { + match (&n.kind, points.iter().find(|(id, _)| *id == n.id)) { + (NodeKind::Mesh(m), Some((_, v))) => v.iter().filter_map(|i| m.points.get(*i)).map(|q| q.opacity).collect(), + _ => vec![], + } +} + +/// The objects whose fill or stroke the proxy shows for selected object `n`, with the appearance +/// item each shows: `n` itself when it holds such an item, else every painted object inside it +/// ([`Session::proxy_source`] shows the first). +fn shown_sources(n: &Node, item: Option, stroke: bool) -> Vec<(&Node, Option)> { + if n.appearance.item_of_kind(item, !stroke).is_some() { + return vec![(n, item)]; + } + let mut nodes = vec![]; + super::paint::painted(n, true, stroke, &mut nodes); + nodes.into_iter().map(|c| (c, None)).collect() +} + +/// How object `n` draws its fill or stroke (`item`, else the proxy's row), as [`Drawn`] gives it. An +/// error for a hidden row. +fn drawn_settings(s: &Session, n: &Node, item: Option, stroke: bool) -> std::result::Result { + let item = n.appearance.item_of_kind(item, !stroke); + // Without a targeted row, type shows its characters' paint and a colorized image its + // colorize color, which no fill or stroke row's opacity applies to. + let own_paint = item.is_none() && (matches!(n.kind, NodeKind::Text(_)) || (!stroke && n.extras().colorize.is_some())); + let own = match (own_paint, stroke) { + (true, _) => None, + (false, true) => n.appearance.stroke_at(item).map(|l| (l.opacity, l.blend, l.visible)), + (false, false) => n.appearance.fill_at(item).map(|l| (l.opacity, l.blend, l.visible)), + }; + if own.is_some_and(|o| !o.2) { + return Err("the active fill or stroke is hidden: give `color`".to_string()); + } + // The groups and layer the object is in draw it too (`enclosing` lists the outermost first). + let mut around = enclosing(s, n.id); + around.reverse(); + // An opacity mask sets how much of the color shows at each point, which no one opacity gives. + if masked(n) || around.iter().any(|l| l.masked) { + return Err("the active fill or stroke is drawn through an opacity mask: give `color`".to_string()); + } + // The rows below the row that draw, as `hide_rows` leaves them shown. + let rows = &n.appearance.items; + let at_row = item.or_else(|| rows.iter().rposition(|r| r.is_fill() != stroke)); + let lower = match (own, at_row) { + (Some(_), Some(i)) => rows.iter().take(i).filter(|r| r.visible() && !r.paint().is_none()).cloned().collect(), + _ => vec![], + }; + Ok(Drawn { opacity: n.opacity, row: own.map(|o| (o.1, o.0)), blend: n.blend, isolate: n.isolate, around, lower }) +} + +/// `color` as the canvas draws the picked object of a dynamic symbol instance that a fill stains +/// (`symbol_overrides::instance_art` mixes the art's solid paints towards the instance's fill); +/// `color` itself otherwise. +fn stained(s: &Session, color: Color) -> Color { + let stain = s.active().and_then(|st| { + let sp = st.selection.symbol_part.as_ref()?; + st.selected_symbol_part()?; + vectorcraft_doc::symbol_overrides::stain(st.doc.node(sp.instance)?) + }); + match stain { + Some((c, amount)) => color.lerp(&c, amount.clamp(0.0, 1.0)), + None => color, + } +} + +/// The objects that draw the proxy's object `id` ([`Level`]), outermost first: its groups and +/// layer, and for a picked object of a dynamic symbol instance, the instance, its groups and layer, +/// and the groups of the symbol's art around the object. +fn enclosing(s: &Session, id: NodeId) -> Vec { + let Some(st) = s.active() else { return vec![] }; + let doc = &st.doc; + let level = |n: &Node, part: Part| Level { opacity: n.opacity, blend: n.blend, isolate: n.isolate, part, masked: masked(n) }; + // `ancestry` lists the object itself last. + let in_doc = |id: NodeId, own: bool| { + let ids = doc.ancestry(id).unwrap_or_default(); + let nodes = ids.into_iter().filter(|a| own || *a != id).filter_map(|a| doc.node(a)); + nodes.map(|a| level(a, Part::Doc(a.id))).collect::>() + }; + let Some(sp) = st.selection.symbol_part.as_ref() else { return in_doc(id, false) }; + let art = doc.node(sp.instance).and_then(|inst| { + let NodeKind::SymbolInstance { symbol, .. } = &inst.kind else { return None }; + let sym = doc.symbols.iter().find(|s| s.name == *symbol)?; + Some(vectorcraft_doc::symbol_overrides::dynamic_art(&sym.art, inst)) + }); + // Without the picked object, the proxy shows the selected object itself (`proxy_source`). + let Some(art) = art.filter(|a| vectorcraft_doc::symbol_overrides::part(a, &sp.path).is_some()) else { return in_doc(id, false) }; + let mut out = in_doc(sp.instance, true); + if let Some((_, groups)) = sp.path.split_last() { + // The art's root and each group on the way to the object, not the object itself. + let mut n = &art; + out.push(level(n, Part::Art(vec![]))); + for (k, &i) in groups.iter().enumerate() { + let Some(c) = n.children().and_then(|c| c.get(usize::try_from(i).ok()?)) else { break }; + n = c; + out.push(level(n, Part::Art(groups[..=k].to_vec()))); + } + } + out +} + +/// The display sRGB VectorCraft draws at the center of the selection's bounds with the selected +/// objects hidden: the average of a small square rendered as the canvas renders it (artboards, the +/// on-screen Appearance of Black, no proof, no template layers or guides), over white where nothing +/// is drawn, with its alpha. With `hide`, that object (a group or layer around the selection) is +/// hidden in place of the selection, or for [`Part::Rows`], the proxy's row and the rows above it; +/// the objects of `full` draw at full opacity in Normal mode; and with `scope` (a group or layer +/// around the selection, or the proxy's objects), only the art inside it is drawn, over nothing, +/// without artboards. +fn color_below( + s: &Session, + rich_black: bool, + hide: Option<&Part>, + full: &[&Part], + scope: Option<&Part>, +) -> std::result::Result<([f32; 3], f32), String> { + super::has_selection(s)?; + let st = s.active().ok_or("no document open")?; + let ids = st.selection.objects.clone(); + // A picked object of a dynamic symbol instance hides only itself: the rest of the instance + // stays in the sample, measured at the object's center. + let picked = st.selection.symbol_part.as_ref().and_then(|sp| { + let inst = st.doc.node(sp.instance)?; + let center = kurbo::Shape::bounding_box(&vectorcraft_doc::hit::symbol_part_outline(&st.doc, inst, &sp.path)?).center(); + vectorcraft_doc::symbol_overrides::part(inst_art(&st.doc, sp.instance)?, &sp.path)?; + Some((sp, center)) + }); + let center = match picked { + Some((_, center)) => center, + None => st.doc.bounds_of(&ids, false).ok_or("nothing selected")?.center(), + }; + // The objects the proxy's color comes from, with the row each shows (`proxy_color`); for a picked + // object, the object itself at `sp.path`, with its topmost row of the kind. + let (stroke, item) = (!s.fill_active, s.appearance_item()); + let shown = |id: NodeId| st.doc.ancestry(id).unwrap_or_default().iter().all(|a| st.doc.node(*a).is_some_and(|x| x.visible)); + let painted = match picked { + Some(_) => vec![], + None => { + let nodes = st.selection.subjects().iter().filter_map(|id| st.doc.node(*id)); + nodes.flat_map(|n| shown_sources(n, item, stroke)).filter(|(c, _)| shown(c.id)).map(|(c, item)| (c.id, item)).collect::>() + } + }; + let own = |p: Option<&Part>| matches!(p, Some(Part::Art(_) | Part::Object | Part::Rows)); + let art_edits = picked.is_some() && (hide.is_none() || own(hide) || full.iter().any(|p| own(Some(p))) || own(scope)); + let mut copy = (art_edits || !full.is_empty() || hide == Some(&Part::Rows)).then(|| Document::clone(&st.doc)); + let mut hidden = HashSet::new(); + // The art of the picked object's instance in `copy`, as a copy of its symbol that only this + // instance draws, so other instances of the symbol keep it. + let symbol = match (picked, copy.as_mut()) { + (Some((sp, _)), Some(doc)) if art_edits => Some(own_symbol(doc, sp.instance).ok_or("the picked object is not found")?), + _ => None, + }; + let lost = || "the picked object is not found".to_string(); + match (hide, picked) { + (None, Some((sp, _))) => art_mut(copy.as_mut(), symbol, &sp.path).ok_or_else(lost)?.visible = false, + (None, None) => hidden.extend(ids), + (Some(Part::Doc(id)), _) => hidden.extend([*id]), + // The art's root is all the instance draws. + (Some(Part::Art(path)), Some((sp, _))) if path.is_empty() => hidden.extend([sp.instance]), + (Some(Part::Art(path)), _) => art_mut(copy.as_mut(), symbol, path).ok_or_else(lost)?.visible = false, + (Some(Part::Rows), Some((sp, _))) => hide_rows(art_mut(copy.as_mut(), symbol, &sp.path).ok_or_else(lost)?, None, stroke), + (Some(Part::Rows), None) => { + for (id, item) in &painted { + if let Some(n) = copy.as_mut().and_then(|d| d.node_mut(*id)) { + hide_rows(n, *item, stroke); + } + } + } + (Some(Part::Object), _) => return Err(lost()), + } + // The levels around the one read draw what is inside them as it is. An instance's override of + // an object of its art's opacity or blend mode is dropped with it. + let plain = |n: &mut Node| { + n.opacity = 1.0; + n.blend = BlendMode::Normal; + }; + let plain_art = |copy: &mut Option, path: &[u32]| -> std::result::Result<(), String> { + plain(art_mut(copy.as_mut(), symbol, path).ok_or_else(lost)?); + let sp = picked.ok_or_else(lost)?.0; + if let Some(e) = copy.as_mut().and_then(|d| d.node_mut(sp.instance)).and_then(Node::extras_if_any) { + for o in e.symbol_overrides.iter_mut().filter(|o| o.path == path) { + (o.opacity, o.blend) = (None, None); + } + } + Ok(()) + }; + for p in full { + let ids = match (p, picked) { + (Part::Doc(id), _) => vec![*id], + (Part::Art(path), _) => { + plain_art(&mut copy, path)?; + continue; + } + (Part::Object, Some((sp, _))) => { + plain_art(&mut copy, &sp.path)?; + continue; + } + (Part::Object, None) => painted.iter().map(|p| p.0).collect(), + (Part::Rows, _) => continue, + }; + for id in ids { + if let Some(n) = copy.as_mut().and_then(|d| d.node_mut(id)) { + plain(n); + } + } + } + // Inside a level, only the art that level holds is drawn, over nothing. + if let Some(scope) = scope { + let (keep, path) = match (scope, picked) { + (Part::Doc(id), _) => (vec![*id], &[][..]), + (Part::Art(path), Some((sp, _))) => (vec![sp.instance], &path[..]), + (Part::Object, Some((sp, _))) => (vec![sp.instance], &sp.path[..]), + (Part::Object, None) => (painted.iter().map(|p| p.0).collect(), &[][..]), + _ => return Err(lost()), + }; + // Everything that is neither on the way to a kept object nor inside one is hidden. + let on_way = keep.iter().flat_map(|k| st.doc.ancestry(*k).unwrap_or_default()).collect::>(); + let parents = std::iter::once(None).chain(on_way.iter().filter(|a| !keep.contains(a)).map(|a| Some(*a))); + for parent in parents { + hidden.extend(st.doc.children(parent).into_iter().flatten().map(|n| n.id).filter(|n| !on_way.contains(n))); + } + for (k, &keep) in path.iter().enumerate() { + let group = art_mut(copy.as_mut(), symbol, &path[..k]).and_then(Node::children_mut).ok_or_else(lost)?; + for (i, c) in group.iter_mut().enumerate() { + if u32::try_from(i).ok() != Some(keep) { + Arc::make_mut(c).visible = false; + } + } + } + } + let h = BELOW_SIDE / 2.0; + let region = vectorcraft_geom::Rect::new(center.x - h, center.y - h, center.x + h, center.y + h); + // Template layers and guides are aids to drawing, not artwork: left out as exports leave them. + let opts = vectorcraft_render::RenderOptions { + background: scope.is_none().then_some([255, 255, 255, 255]), + artboards: scope.is_none(), + hidden, + rich_black, + skip_templates: true, + ..Default::default() + }; + let img = vectorcraft_render::Renderer::new().render_region_with(copy.as_ref().unwrap_or(&st.doc), region, BELOW_SCALE, &opts); + let px = img.pixels.as_chunks::<4>().0; + if px.is_empty() { + return Ok(if scope.is_none() { ([1.0; 3], 1.0) } else { ([0.0; 3], 0.0) }); + } + // The pixels are premultiplied: the average color is their sum over their alpha's. + let mut sum = [0.0f64; 4]; + for p in px { + for (s, v) in sum.iter_mut().zip(p) { + *s += f64::from(*v); + } + } + let alpha = sum[3] / (px.len() as f64 * 255.0); + if alpha <= 0.0 { + return Ok(([0.0; 3], 0.0)); + } + let rgb = [0, 1, 2].map(|i| (sum[i] / (px.len() as f64 * 255.0) / alpha).clamp(0.0, 1.0) as f32); + Ok((rgb, alpha as f32)) +} + +/// Hides fill or stroke row `item` of `n` (else its topmost row of the kind) and every row above it. +fn hide_rows(n: &mut Node, item: Option, stroke: bool) { + let a = &mut n.appearance; + let Some(i) = a.item_of_kind(item, !stroke).or_else(|| a.items.iter().rposition(|r| r.is_fill() != stroke)) else { return }; + for r in a.items.iter_mut().skip(i) { + match r { + vectorcraft_doc::AppearanceItem::Fill(f) => f.visible = false, + vectorcraft_doc::AppearanceItem::Stroke(s) => s.visible = false, + } + } +} + +/// The art the symbol instance `inst` of `doc` draws, as its symbol holds it. +fn inst_art(doc: &Document, inst: NodeId) -> Option<&Arc> { + let NodeKind::SymbolInstance { symbol, .. } = &doc.node(inst)?.kind else { return None }; + doc.symbols.iter().find(|s| s.name == *symbol).map(|s| &s.art) +} + +/// The object at `path` in the art of `doc`'s symbol at index `symbol` (the art's root for an empty +/// path). +fn art_mut<'a>(doc: Option<&'a mut Document>, symbol: Option, path: &[u32]) -> Option<&'a mut Node> { + let mut n = Arc::make_mut(&mut doc?.symbols.get_mut(symbol?)?.art); + for &i in path { + n = Arc::make_mut(n.children_mut()?.get_mut(usize::try_from(i).ok()?)?); + } + Some(n) +} + +/// Makes the symbol instance `inst` of `doc` draw a copy of its symbol, so that a change to the copy +/// leaves other instances as they are. Returns the copy's index in the document's symbols. +fn own_symbol(doc: &mut Document, inst: NodeId) -> Option { + let NodeKind::SymbolInstance { symbol, .. } = &doc.node(inst)?.kind else { return None }; + let mut sym = doc.symbols.iter().find(|s| s.name == *symbol)?.clone(); + sym.name = unique_name(&sym.name, |name| doc.symbols.iter().any(|s| s.name == name)); + let name = sym.name.clone(); + doc.symbols.push(sym); + if let NodeKind::SymbolInstance { symbol, .. } = &mut doc.node_mut(inst)?.kind { + *symbol = name; + } + Some(doc.symbols.len() - 1) +} diff --git a/crates/engine/src/cmd/create.rs b/crates/engine/src/cmd/create.rs index e248f2bbc3..9e28b5805c 100644 --- a/crates/engine/src/cmd/create.rs +++ b/crates/engine/src/cmd/create.rs @@ -73,7 +73,7 @@ pub fn specs() -> Vec { "Circle Through Points", [], None, - "{points?: [[x, y], [x, y]] or [[x, y], [x, y], [x, y]] (two: the ends of a diameter; left out: the two or three selected anchor points, where a path selected whole counts all its anchors and selected segments' ends do not count), anchors?: \"standard\"|\"points\" (default standard: four anchors at 0°, 90°, 180° and 270°; points: an anchor at each point and more between them so that no curve turns more than a quarter)} → {id, cx, cy, radius}: a circle with the current paint whose edge passes through the points, not pixel-aligned even while Align New Objects to Pixel Grid is on; two points that are the same, three on one line, or a circle reaching past the canvas are an error, and nothing is drawn", + "{points?: [[x, y], [x, y]] or [[x, y], [x, y], [x, y]] (two: the ends of a diameter; left out: the two or three selected anchor points, where a path selected whole counts all its anchors and selected segments' ends do not count), center?: [x, y] (the circle's center; `points` then holds the one point its edge passes through, [[x, y]]), anchors?: \"standard\"|\"points\" (default standard: four anchors at 0°, 90°, 180° and 270°; points: an anchor at each point and more between them so that no curve turns more than a quarter)} → {id, cx, cy, radius}: a circle with the current paint whose edge passes through the points, not pixel-aligned even while Align New Objects to Pixel Grid is on; two points that are the same, a point on `center`, three on one line, a circle reaching past the canvas, or one too small for its edges to differ at its coordinates are an error, and nothing is drawn", has_doc, circle_through_points ), @@ -449,9 +449,33 @@ fn ellipse(s: &mut Session, p: &Value) -> Result { /// Ellipse tool drag is. fn circle_through_points(s: &mut Session, p: &Value) -> Result { const C: &str = "shape.circleThroughPoints"; - let points = match p.get("points").filter(|v| !v.is_null()) { - Some(v) => two_or_three_points(v).ok_or_else(|| bad(C, "`points` must be two or three [x, y] pairs of numbers"))?, - None => selected_anchor_points(s)?.ok_or_else(|| bad(C, "direct-select two or three anchor points, or give `points`"))?, + const SAME: &str = "no circle passes through these points: two are the same or all three lie on one line"; + let (center, radius, points) = match p.get("center") { + // From a center: the circle at `center` whose edge passes through the one point. A null + // `center` is refused, as a null `points` with a center is. + Some(c) => { + let one = p.get("points").and_then(Value::as_array).and_then(|v| match v.as_slice() { + [q] => pair(q), + _ => None, + }); + let (c, q) = pair(c).zip(one).ok_or_else(|| bad(C, "`center` must be an [x, y] pair of numbers, with one [x, y] pair in `points`"))?; + let r = c.distance(q); + if r == 0.0 { + return Err(bad(C, "the point in `points` is on `center`")); + } + if !r.is_finite() { + return Err(bad(C, "result would exceed the canvas (coordinates out of range)")); + } + (c, r, vec![q]) + } + None => { + let points = match p.get("points").filter(|v| !v.is_null()) { + Some(v) => two_or_three_points(v).ok_or_else(|| bad(C, "`points` must be two or three [x, y] pairs of numbers"))?, + None => selected_anchor_points(s)?.ok_or_else(|| bad(C, "direct-select two or three anchor points, or give `points`"))?, + }; + let (c, r) = shapes::circle_through_points(&points).ok_or_else(|| bad(C, SAME))?; + (c, r, points) + } }; let key = "anchors"; let at_points = match p.get(key).map(Value::as_str) { @@ -459,13 +483,15 @@ fn circle_through_points(s: &mut Session, p: &Value) -> Result { Some(Some("points")) => true, Some(_) => return Err(bad(C, format!("`{key}` must be one of {}", "standard, points"))), }; - let (center, radius) = shapes::circle_through_points(&points) - .ok_or_else(|| bad(C, "no circle passes through these points: two are the same or all three lie on one line"))?; + let r = Rect::new(center.x - radius, center.y - radius, center.x + radius, center.y + radius); + // A radius below the step between doubles at the center leaves opposite edges on one number. + if !(r.width() > 0.0 && r.height() > 0.0) { + return Err(bad(C, "the circle is too small to draw at these coordinates")); + } // Not pixel-aligned: the circle stays through the points. let mut out = if at_points { add_art_unaligned(s, "Ellipse", path_kind(shapes::circle_with_anchors_at(center, radius, &points), None))? } else { - let r = Rect::new(center.x - radius, center.y - radius, center.x + radius, center.y + radius); let live = LiveShape::Ellipse { w: r.width(), h: r.height(), pie: (0.0, 360.0), xf: Affine::translate(r.origin().to_vec2()) }; add_art_unaligned(s, "Ellipse", path_kind(live.to_path(), Some(live)))? }; @@ -475,13 +501,17 @@ fn circle_through_points(s: &mut Session, p: &Value) -> Result { Ok(out) } +/// The point an `[x, y]` pair of finite numbers gives. +fn pair(v: &Value) -> Option { + match v.as_array().map(Vec::as_slice) { + Some([x, y]) => x.as_f64().zip(y.as_f64()).filter(|(x, y)| x.is_finite() && y.is_finite()).map(|(x, y)| Point::new(x, y)), + _ => None, + } +} + /// The two or three points `[[x, y], [x, y]]` or `[[x, y], [x, y], [x, y]]` holds, each pair two /// finite numbers. fn two_or_three_points(v: &Value) -> Option> { - let pair = |v: &Value| match v.as_array().map(Vec::as_slice) { - Some([x, y]) => x.as_f64().zip(y.as_f64()).filter(|(x, y)| x.is_finite() && y.is_finite()).map(|(x, y)| Point::new(x, y)), - _ => None, - }; match v.as_array() { Some(pairs) if matches!(pairs.len(), 2 | 3) => pairs.iter().map(pair).collect(), _ => None, diff --git a/crates/engine/src/cmd/docmenu.rs b/crates/engine/src/cmd/docmenu.rs index 717c9cdc14..1cf7af0334 100644 --- a/crates/engine/src/cmd/docmenu.rs +++ b/crates/engine/src/cmd/docmenu.rs @@ -14,8 +14,8 @@ use super::panelcmds::artboard_at; use super::pathops::Beside; use super::select::{first_selectable, is_selectable, selectable_ids, walk_selectable}; use super::{ - CommandSpec, EngineError, Point, Result, Session, bad, checked_ids_param, cmd, f64_req, has_doc, has_selection, id_param, number_or, ok, - str_param, switch_or, text_param, + CommandSpec, EngineError, Result, Session, bad, checked_ids_param, cmd, f64_req, has_doc, has_selection, id_param, number_or, ok, str_param, + switch_or, text_param, }; pub fn specs() -> Vec { @@ -730,13 +730,10 @@ fn release_guides(s: &mut Session, p: &Value) -> Result { }; // Find each ruler guide's line and its parent: the guide's layer, else where new art goes. let st = s.doc()?; - let artboards = st.doc.artboards.iter().map(|a| a.rect).reduce(|a, b| a.union(b)); let mut lines = Vec::with_capacity(rulers.len()); for &i in &rulers { let Some(g) = st.doc.ruler_guide(i) else { continue }; - let span = st.doc.guide_span(&g).or_else(|| artboards.map(|r| if g.vertical { (r.y0, r.y1) } else { (r.x0, r.x1) })); - let Some((a, b)) = span else { continue }; - let (a, b) = if g.vertical { (Point::new(g.pos, a), Point::new(g.pos, b)) } else { (Point::new(a, g.pos), Point::new(b, g.pos)) }; + let Some((a, b)) = st.doc.guide_line(&g) else { continue }; let parent = match g.layer.filter(|l| st.doc.node(*l).is_some_and(Node::is_layer)) { Some(l) => Some(l), None => st.target_parent()?, diff --git a/crates/engine/src/cmd/draw2/commands.rs b/crates/engine/src/cmd/draw2/commands.rs index 9a2ee80033..08404a3092 100644 --- a/crates/engine/src/cmd/draw2/commands.rs +++ b/crates/engine/src/cmd/draw2/commands.rs @@ -12,7 +12,7 @@ pub fn specs() -> Vec { "Pencil", [], None, - "{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation,wheel]…] (pen pressure 0..1: the stroke keeps it, for Calligraphic and Scatter brushes with Pressure variation; a point without one presses fully. Pen tilt in degrees, each −90..90, x positive leaning right and y leaning down the page, and barrel rotation in degrees clockwise, 0..360: the stroke keeps how far the pen leaned, which way and how far its barrel turned, for brushes with Tilt, Bearing and Rotation variation. An airbrush pen's finger wheel 0..1: the stroke keeps it for brushes with Stylus Wheel variation, a point without one half way; null for what a point lacks. A pressure, tilt, rotation or wheel outside its range, or a point array of more than seven numbers, is an error), fidelity?: pt (1.5; from 0.000015625 (0.01 / 640) to 100 / 0.0313 (about 3194.89), the Pencil's and the Paintbrush's 0.01 to 100 px Fidelity at the highest and the lowest zoom; a value outside that range is an error. The tools send their Fidelity in pixels divided by the zoom, kept within the range), fit?: bool (true; false: the points are joined by straight segments, as the Pencil previews a stroke with Live curve fitting off), closed?, style?: \"pencil\" (default) | \"brush\", fill?: bool, keepSelected?: bool (true: the drawn or continued path is selected; false: a new path leaves nothing selected, and a continued or redrawn one is deselected while the rest of the selection stays), leaveSelection?: bool (false; true with keepSelected false: a new path leaves the selection as it is, as the Pencil previews a stroke that redraws a path), extend?: {id, end?: \"end\" (default) | \"start\"}, connect?: {id, end: \"start\"|\"end\"} (only with extend), redraw?: {id, within?: pt (12)}} fit a freehand stroke → {id}. extend continues the path from that end, and closes it when `closed` is true (left out, when the stroke ends within four Fidelities of the path's other end, 6 to 400 pt); with connect, the stroke ends on that end of another path's last open subpath and joins it on, in one path with the extended path's appearance (the other path is removed when nothing of it is left); redraw (Edit Selected Paths) replaces the section of the path between where the stroke starts and ends, each within `within` of one subpath (the way round a closed one that leaves the bigger shape; on an open one the way the stroke runs along it at each end decides: it replaces the part it runs along where it starts and joins the part it runs into where it lands, so it replaces the part between, keeps it and closes the path along the stroke, or, when its ends disagree, ends where it is lifted; an end that leaves or meets the path squarely follows the other end, and when both do it closes only if it goes round both pieces beyond), the stroke's ends bent smoothly onto the path; a stroke that starts on it and returns to the same point adds a loop there, and one lifted farther than `within` from it takes the path with it: a closed subpath opens where the stroke starts, an open one is cut there and drops the part the stroke heads along, and the path ends where the stroke does. Any other style, extend end or connect end, connect without extend, and a connect that names no other path with an open end are errors, a stroke of one point included, and nothing changes", + "{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation,wheel]…] (pen pressure 0..1: the stroke keeps it, for Calligraphic and Scatter brushes with Pressure variation; a point without one presses fully. Pen tilt in degrees, each −90..90, x positive leaning right and y leaning down the page, and barrel rotation in degrees clockwise, 0..360: the stroke keeps how far the pen leaned, which way and how far its barrel turned, for brushes with Tilt, Bearing and Rotation variation. An airbrush pen's finger wheel 0..1: the stroke keeps it for brushes with Stylus Wheel variation, a point without one half way; null for what a point lacks. A pressure, tilt, rotation or wheel outside its range, or a point array of more than seven numbers, is an error), fidelity?: pt (1.5; from 0.000015625 (0.01 / 640) to 100 / 0.0313 (about 3194.89), the Pencil's and the Paintbrush's 0.01 to 100 px Fidelity at the highest and the lowest zoom; a value outside that range is an error. The tools send their Fidelity in pixels divided by the zoom, kept within the range), fit?: bool (true; false: the points are joined by straight segments, as the Pencil previews a stroke with Live curve fitting off), closed?, style?: \"pencil\" (default) | \"brush\", fill?: bool, keepSelected?: bool (true: the drawn or continued path is selected; false: a new path leaves nothing selected, and a continued or redrawn one is deselected while the rest of the selection stays), preview?: bool (false; true: the stroke is drawn as a new path on top, as with Draw Normal, and the selection stays as it is, as the Pencil previews a stroke that redraws a path), extend?: {id, end?: \"end\" (default) | \"start\"}, connect?: {id, end: \"start\"|\"end\"} (only with extend), redraw?: {id, within?: pt (12)}} fit a freehand stroke → {id}. extend continues the path from that end, and closes it when `closed` is true (left out, when the stroke ends within four Fidelities of the path's other end, 6 to 400 pt); with connect, the stroke ends on that end of another path's last open subpath and joins it on, in one path with the extended path's appearance (the other path is removed when nothing of it is left); redraw (Edit Selected Paths) replaces the section of the path between where the stroke starts and ends, each within `within` of one subpath (the way round a closed one that leaves the bigger shape; on an open one the way the stroke runs along it at each end decides: it replaces the part it runs along where it starts and joins the part it runs into where it lands, so it replaces the part between, keeps it and closes the path along the stroke, or, when its ends disagree, ends where it is lifted; an end that leaves or meets the path squarely follows the other end, and when both do it closes only if it goes round both pieces beyond), the stroke's ends bent smoothly onto the path; a stroke that starts on it and returns to the same point adds a loop there, and one lifted farther than `within` from it takes the path with it: a closed subpath opens where the stroke starts, an open one is cut there and drops the part the stroke heads along, and the path ends where the stroke does. Any other style, extend end or connect end, connect without extend, and a connect that names no other path with an open end are errors, a stroke of one point included, and nothing changes", has_doc, freehand ), @@ -129,7 +129,7 @@ pub fn specs() -> Vec { "Smooth", [], None, - "{points: [[x,y]…] (pen values after x and y are checked as path.freehand checks them and do not change the smoothing), radius?: pt (12; from 0.001 to 1000), fidelity?: pt (2.5; from 0.000078125 to about 3195, the Smooth tool's 0.05 to 100 px at the highest and the lowest zoom: the tool sends its Fidelity in screen pixels divided by the zoom, kept within the range)} smooth selected paths near the drag, keeping a corner where the path turns by more than 57.5° at the anchor and over radius and twice radius on either side, and leaving a subpath as it is when the result would not be smoother (docs/mcp.md) → {ids, before, after}. A radius or fidelity outside its range is refused with an error, and nothing changes", + "{points: [[x,y]…] (pen values after x and y are checked as path.freehand checks them and do not change the smoothing), radius?: pt (12; from 0.001 to 1000), fidelity?: pt (2.5; from 0.000078125 to about 3195, the Smooth tool's 0.05 to 100 px at the highest and the lowest zoom: the tool sends its Fidelity in screen pixels divided by the zoom, kept within the range), smoothness?: % (50; 0 to 100: how far along the path each point is averaged before the refit, in proportion: none at 0, twice as far as at 50 at 100)} smooth selected paths near the drag, keeping a corner where the path turns by more than 57.5° at the anchor and over radius and twice radius on either side, and leaving a subpath as it is when the result would not be smoother (docs/mcp.md) → {ids, before, after}. A radius, fidelity or smoothness outside its range is refused with an error, and nothing changes", has_selection, smooth_region ), @@ -147,7 +147,7 @@ pub fn specs() -> Vec { "Blob Brush", [], None, - "{points: [[x,y]…] or [[x,y,pressure]…] (pen pressure 0..1; pen values are checked as path.freehand checks them), size?: pt (10; from 0.1 to 1000), sizeMode?: \"fixed\" (default) | \"pressure\" (Blob Brush Tool Options' Size set to Pressure: the brush is size − sizeVariation wide at the lightest pen pressure and size + sizeVariation at the heaviest, at least 0.1 pt; a stroke without pressure keeps the size), sizeVariation?: pt (0; from 0 to 1000, checked with Fixed too), angle?: ° (0, −180–180: the tip's long axis counter-clockwise from horizontal, kept on the page along the stroke), roundness?: % (100, 0–100: the tip's short axis in percent of its long one, 100 round; 0 is drawn as 0.1), fidelity?: pt (0.01–100; the brush follows the stroke fitted at this tolerance as path.freehand fits a Pencil stroke, and a higher value gives a smoother shape; without it the brush follows every point), merge?: true, mergeOnlySelection?: bool (false: merge with any touching same-color blob; true: only with selected ones), keepSelected?: bool (false: the drawn or merged path is not selected, and the rest of the selection stays; true: it is selected)} filled brush shape, merged with the topmost touching same-color blob and the touching ones next to it in stacking order in its group or layer → {id}. An angle, roundness or fidelity outside its range is rejected with an error, and nothing changes", + "{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation,wheel]…] (pen pressure 0..1, finger wheel 0..1; pen values are checked as path.freehand checks them), size?: pt (10; from 0.1 to 1000), sizeMode?: \"fixed\" (default) | \"pressure\" | \"stylusWheel\" (Blob Brush Tool Options' Size set to Pressure: the brush is size − sizeVariation wide at the lightest pen pressure and size + sizeVariation at the heaviest; set to Stylus Wheel: size − sizeVariation wide at one end of an airbrush pen's finger wheel travel, size at the middle and size + sizeVariation at the other end; at least 0.1 pt; a stroke without that reading, and a point without a wheel on Stylus Wheel, keeps the size), sizeVariation?: pt (0; from 0 to 1000, checked with Fixed too), angle?: ° (0, −180–180: the tip's long axis counter-clockwise from horizontal, kept on the page along the stroke), roundness?: % (100, 0–100: the tip's short axis in percent of its long one, 100 round; 0 is drawn as 0.1), fidelity?: pt (0.01–100; the brush follows the stroke fitted at this tolerance as path.freehand fits a Pencil stroke, and a higher value gives a smoother shape; without it the brush follows every point), merge?: true, mergeOnlySelection?: bool (false: merge with any touching same-color blob; true: only with selected ones), keepSelected?: bool (false: the drawn or merged path is not selected, and the rest of the selection stays; true: it is selected)} filled brush shape, merged with the topmost touching same-color blob and the touching ones next to it in stacking order in its group or layer → {id}. An unknown sizeMode, or an angle, roundness or fidelity outside its range, is rejected with an error, and nothing changes", has_doc, blob ), diff --git a/crates/engine/src/cmd/draw2/common.rs b/crates/engine/src/cmd/draw2/common.rs index 36280196b7..f69ac40822 100644 --- a/crates/engine/src/cmd/draw2/common.rs +++ b/crates/engine/src/cmd/draw2/common.rs @@ -236,22 +236,27 @@ impl PenRecord { } } -/// Blob Brush and Eraser Tool Options' Size set to Pressure (`sizeMode: "pressure"`, with -/// `sizeVariation` in points, 0..1000): the stroke's pen pressure along it and the variation, `None` -/// for Fixed (the default), no variation or a stroke without pressure (a mouse), which keeps the -/// size. A `sizeVariation` outside its range is an error with Fixed too. -pub(super) fn size_pressure(p: &Value, samples: &[Sample], cmd: &str) -> Result> { +/// Blob Brush and Eraser Tool Options' Size set to Pressure (`sizeMode: "pressure"`) or, for the +/// Blob Brush, Stylus Wheel (`sizeMode: "stylusWheel"`), with `sizeVariation` in points, 0..1000: +/// the stroke's pen pressure or airbrush finger wheel along it (0..1, the size less the variation +/// at 0 and plus it at 1) and the variation. `None` for Fixed (the default), no variation or a +/// stroke without that reading (a mouse, a pen without a wheel), which keeps the size. A +/// `sizeVariation` outside its range is an error with Fixed too. +pub(super) fn size_profile(p: &Value, samples: &[Sample], cmd: &str) -> Result> { + const MODES: &str = "\"fixed\", \"pressure\" or \"stylusWheel\""; let variation = ranged(p, "sizeVariation", 0.0, SIZE_VARIATIONS, cmd)?; - match p.get("sizeMode").filter(|v| !v.is_null()).map(|v| v.as_str().ok_or(v)) { - None | Some(Ok("fixed")) => Ok(None), - Some(Ok("pressure")) => Ok(stroke_pressure(samples).filter(|_| variation > 0.0).map(|prof| (prof, variation))), - Some(Ok(other)) => Err(bad(cmd, format!("sizeMode is \"fixed\" or \"pressure\", not `{other}`"))), - Some(Err(other)) => Err(bad(cmd, format!("sizeMode is \"fixed\" or \"pressure\", not {other}"))), - } + let read = match p.get("sizeMode").filter(|v| !v.is_null()).map(|v| v.as_str().ok_or(v)) { + None | Some(Ok("fixed")) => return Ok(None), + Some(Ok("pressure")) => stroke_pressure(samples), + Some(Ok("stylusWheel")) => stroke_wheel(samples), + Some(Ok(other)) => return Err(bad(cmd, format!("sizeMode is {MODES}, not `{other}`"))), + Some(Err(other)) => return Err(bad(cmd, format!("sizeMode is {MODES}, not {other}"))), + }; + Ok(read.filter(|_| variation > 0.0).map(|prof| (prof, variation))) } -/// The area a stroke along `spine` covers with Size set to Pressure: as wide at each point as -/// [`vectorcraft_tools::draw2::pressure_size`] gives for the pressure `prof` records there, with +/// The area a stroke along `spine` covers with Size set to Pressure or Stylus Wheel: as wide at +/// each point as [`vectorcraft_tools::draw2::pressure_size`] gives for the reading `prof` records there, with /// round ends and joins, its overlaps united into one outline. pub(super) fn pressure_region(spine: &PathData, size: f64, variation: f64, prof: &PressureProfile) -> Result { let widest = size + variation; diff --git a/crates/engine/src/cmd/draw2/cut.rs b/crates/engine/src/cmd/draw2/cut.rs index cc543f3e05..445a71b171 100644 --- a/crates/engine/src/cmd/draw2/cut.rs +++ b/crates/engine/src/cmd/draw2/cut.rs @@ -1,7 +1,7 @@ use super::common::{ PenRecord, SIZE_VARIATIONS, SIZES, Sample, center_strokes, dist_to_polyline, fill_targets, has_fill, has_painted_ancestor_stroke, has_painted_stroke, ids_json, path_mut, path_of, points_param, poly_bounds, pressure_region, ranged, replace_with_pieces, samples_param, - set_geometry, sibling_with, size_pressure, target_paths, usize_opt, + set_geometry, sibling_with, size_profile, target_paths, usize_opt, }; use super::{ Anchor, AnchorKind, Beside, BezPath, BoolOp, Cap, Document, EngineError, FillRule, Join, NodeId, NodeKind, Paint, ParamCurve, PathData, Point, @@ -314,7 +314,7 @@ pub(super) fn erase_region(s: &mut Session, p: &Value) -> Result { if varies_beyond_size_pressure(&vary) { return erase_varied(s, &samples, [angle, roundness, size], vary); } - let pressure = if vary[2].0 == Variation::Pressure { size_pressure(p, &samples, C)? } else { None }; + let pressure = if vary[2].0 == Variation::Pressure { size_profile(p, &samples, C)? } else { None }; let pts: Vec = samples.into_iter().map(|s| s.pt).collect(); let r = size / 2.0; // The tip's short axis (its narrowest with Pressure): an open path is sampled at least every half of it. diff --git a/crates/engine/src/cmd/draw2/freehand.rs b/crates/engine/src/cmd/draw2/freehand.rs index 5f281e2e34..da269286cd 100644 --- a/crates/engine/src/cmd/draw2/freehand.rs +++ b/crates/engine/src/cmd/draw2/freehand.rs @@ -1,5 +1,5 @@ use super::common::{ - PenRecord, SIZES, Sample, brush_region, path_kind, path_mut, path_of, poly_bounds, pressure_region, ranged, samples_param, size_pressure, + PenRecord, SIZES, Sample, brush_region, path_kind, path_mut, path_of, poly_bounds, pressure_region, ranged, samples_param, size_profile, stroke_paint, subpath_len, target_paths, within_input_bound, }; use super::{ @@ -130,8 +130,9 @@ fn fit_from(a: Point, pts: &[Point], tol: Option, reach: f64) -> Vec, b: Option, reach: f64) { +/// lands on its target and the other end's bend doesn't move it off. Where a bend stops between two +/// points far apart, a point is added there, so the stroke beyond `reach` stays as drawn. +fn bend_ends(stroke: &mut Vec, a: Option, b: Option, reach: f64) { let (Some(&first), Some(&last)) = (stroke.first(), stroke.last()) else { return }; // How far along the stroke each point lies, measured before anything moves. let mut along = Vec::with_capacity(stroke.len()); @@ -153,6 +154,39 @@ fn bend_ends(stroke: &mut [Point], a: Option, b: Option, reach: f6 } return; } + // A point where each bend stops, when that falls between two points (strokes sent by a script + // can have few, far apart): without it, the straight piece to the next point would tilt beyond + // `reach`. + let (mut c0, mut c1) = (a.map(|_| reach), b.map(|_| total - reach)); + if let (Some(x), Some(y)) = (c0, c1) + && x > y + { + (c0, c1) = (Some(y), Some(x)); + } + // Both bends stop at the same place (a stroke twice `reach` long): one point there. + if let (Some(x), Some(y)) = (c0, c1) + && (y - x).abs() < 1e-9 + { + c1 = None; + } + let mut points = Vec::with_capacity(stroke.len() + 2); + let mut dists = Vec::with_capacity(stroke.len() + 2); + let mut before: Option<(Point, f64)> = None; + for (&p, &d) in stroke.iter().zip(&along) { + if let Some((q, e)) = before { + for c in [c0, c1].into_iter().flatten() { + if e + 1e-9 < c && c < d - 1e-9 { + points.push(q.lerp(p, (c - e) / (d - e))); + dists.push(c); + } + } + } + points.push(p); + dists.push(d); + before = Some((p, d)); + } + *stroke = points; + let along = dists; let weight = |d: f64| (1.0 - d / reach).max(0.0); let (shift_a, shift_b) = (a.map(|a| a - first), b.map(|b| b - last)); for (p, &d) in stroke.iter_mut().zip(&along) { @@ -528,7 +562,7 @@ pub(crate) fn freehand_brushed(s: &mut Session, p: &Value, brush_name: Option<&s let keep_selected = switch_or(p, "keepSelected", true, C)?; // The Pencil's preview of a stroke that redraws a path draws it as a new path but leaves the // selection as it is: the path being redrawn stays selected until the release redraws it. - let leave_selection = switch_or(p, "leaveSelection", false, C)?; + let preview = switch_or(p, "preview", false, C)?; let filled = switch_or(p, "fill", false, C)?; let extend = p.get("extend").filter(|v| !v.is_null()); if extend.is_none() && p.get("connect").is_some_and(|v| !v.is_null()) { @@ -779,8 +813,13 @@ pub(crate) fn freehand_brushed(s: &mut Session, p: &Value, brush_name: Option<&s st.brush = Some(name.to_string()); } } - let out = insert_look(s, label, path_kind(PathData::single(sp)), look, None, keep_selected)?; - if !keep_selected && !leave_selection { + // A preview goes on top as Draw Normal places it: Draw Inside would put it in the selected + // path's clip group, clipped, and Draw Behind behind the path. + let mode = if preview { std::mem::replace(&mut s.draw_mode, crate::DrawMode::Normal) } else { s.draw_mode }; + let out = insert_look(s, label, path_kind(PathData::single(sp)), look, None, keep_selected && !preview); + s.draw_mode = mode; + let out = out?; + if !keep_selected && !preview { // A new stroke with Keep selected off leaves nothing selected: Illustrator starts the stroke // by dropping the earlier selection, it does not keep it (#5752). s.select(|_, sel| sel.clear())?; @@ -843,8 +882,8 @@ pub(super) fn blob(s: &mut Session, p: &Value) -> Result { } let tip = vectorcraft_tools::draw2::blob_tip(angle, roundness); let squash = tip.inverse(); - // Width profiles use distance along the spine, so measure pressure on the same squashed - // points that the outline reads for a non-round tip. + // Width profiles use distance along the spine, so measure the pressure or wheel on the same + // squashed points that the outline reads for a non-round tip. let mapped_samples: Vec = if roundness < 100.0 { samples .iter() @@ -857,7 +896,7 @@ pub(super) fn blob(s: &mut Session, p: &Value) -> Result { } else { samples.clone() }; - let pressure = size_pressure(p, &mapped_samples, C)?; + let pressure = size_profile(p, &mapped_samples, C)?; let pts: Vec = samples.into_iter().map(|s| s.pt).collect(); let mapped_pts: Vec = mapped_samples.into_iter().map(|s| s.pt).collect(); // The widest the brush gets: the area merges look in. @@ -875,12 +914,15 @@ pub(super) fn blob(s: &mut Session, p: &Value) -> Result { Some(tol) => Some(pressure_region(&spine(Some(tol)), size, *variation, prof)?).filter(|r| !r.is_empty()), None => None, }; + let dab = || brush_region(&mapped_pts[..1], vectorcraft_tools::draw2::pressure_size(size, *variation, prof.at(0.0))); match fitted { Some(r) => r, - None => pressure_region(&spine(None), size, *variation, prof)?, + // Samples that all lie at one point give a spine with no length: one dab from the + // first reading, as a click paints. + None => Some(pressure_region(&spine(None), size, *variation, prof)?).filter(|r| !r.is_empty()).unwrap_or_else(dab), } } - // A click: one dab as wide as the pen pressed. + // A click: one dab as wide as the pen pressed or the wheel was set. (Some((prof, variation)), false) => brush_region(&mapped_pts, vectorcraft_tools::draw2::pressure_size(size, *variation, prof.at(0.0))), (None, _) => { let fitted = fidelity @@ -975,4 +1017,23 @@ mod bend_tests { assert_eq!(pts[2], Point::new(48.0, 0.0), "{pts:?}"); assert_eq!(pts[1], Point::new(44.0, 0.0), "halfway, half of each end's shift: {pts:?}"); } + + /// With points far apart (a stroke sent by a script), the bend still stops `reach` along the + /// stroke: a point is added there, and the stroke beyond it stays as drawn. + #[test] + fn bend_ends_stops_at_the_reach_between_points_far_apart() { + let mut pts = vec![Point::new(0.0, 0.0), Point::new(100.0, 0.0), Point::new(200.0, 0.0)]; + bend_ends(&mut pts, Some(Point::new(0.0, 10.0)), Some(Point::new(200.0, 0.0)), 40.0); + assert_eq!(pts.first(), Some(&Point::new(0.0, 10.0)), "{pts:?}"); + assert!(pts.contains(&Point::new(40.0, 0.0)), "a point where the bend stops: {pts:?}"); + assert!(pts.iter().filter(|p| p.x >= 40.0).all(|p| p.y == 0.0), "beyond the reach, as drawn: {pts:?}"); + } + + /// Where both bends stop at the same place, one point is added there, not two. + #[test] + fn bend_ends_adds_one_point_where_both_bends_stop() { + let mut pts = vec![Point::new(0.0, 0.0), Point::new(100.0, 0.0)]; + bend_ends(&mut pts, Some(Point::new(0.0, 10.0)), Some(Point::new(100.0, 10.0)), 50.0); + assert_eq!(pts, [Point::new(0.0, 10.0), Point::new(50.0, 0.0), Point::new(100.0, 10.0)]); + } } diff --git a/crates/engine/src/cmd/draw2/smooth.rs b/crates/engine/src/cmd/draw2/smooth.rs index b787bc5d0e..820572287f 100644 --- a/crates/engine/src/cmd/draw2/smooth.rs +++ b/crates/engine/src/cmd/draw2/smooth.rs @@ -12,10 +12,16 @@ use super::{ // ---------- Smooth ---------- /// The spread (points) of the Gaussian the Smooth tool smooths a path along its length with before -/// refitting it, as a share of the tool's reach: a third, so each point is averaged with the stretch -/// of path within the reach on either side of it. VectorCraft's own value. +/// refitting it at the default Smoothness ([`SMOOTH_SMOOTHNESS`]), as a share of the tool's reach: a +/// third, so each point is averaged with the stretch of path within the reach on either side of it. +/// The spread grows in proportion to the Smoothness, from none at 0% to twice this at 100%. +/// VectorCraft's own value. const SMOOTH_SPREAD: f64 = 1.0 / 3.0; +/// The Smoothness (percent) `path.smoothRegion` smooths with when the drag leaves it out. VectorCraft's +/// own value. +const SMOOTH_SMOOTHNESS: f64 = 50.0; + /// The degrees by which a path must turn at an anchor, and over the tool's reach and twice its reach /// on either side of it, for the Smooth tool to keep the anchor as a corner ([`smooth_corners`]): a /// turn of more than 57.5°, an angle inside the corner of less than 122.5°. VectorCraft's own value, @@ -929,7 +935,11 @@ pub(super) fn smooth_region(s: &mut Session, p: &Value) -> Result { if !(lo..=hi).contains(&tol) { return Err(bad(C, format!("`fidelity` must be from {lo} to {hi} pt"))); } - let sigma = radius * SMOOTH_SPREAD; + let smoothness = number_or(p, "smoothness", SMOOTH_SMOOTHNESS, C)?; + if !(0.0..=100.0).contains(&smoothness) { + return Err(bad(C, "`smoothness` must be from 0 to 100")); + } + let sigma = radius * SMOOTH_SPREAD * smoothness / SMOOTH_SMOOTHNESS; let st = s.doc()?; let mut plan = vec![]; let (mut before, mut after) = (0, 0); diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 80277d64b8..33455ea9d9 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -24,7 +24,7 @@ pub fn specs() -> Vec { "New…", ["File"], None, - "{preset?: a name from file.newPresets (start from it; the other params change it), name?|title?: document name (default Untitled-N), width?: pt=612|\"210 mm\", height?: pt=792 (each more than 0 and at most 3,999,856 pt, as artboard.new takes them), units?: \"Pixels\"|\"Points\"|\"Picas\"|\"Inches\"|\"Millimeters\"|\"Centimeters\"|\"Feet\"|\"Yards\"|\"Meters\"|\"Feet & Inches\" (default: prefs unitsGeneral, as print presets; screen presets: Pixels), orientation?: \"portrait\"|\"landscape\" (swaps width and height to match), artboards?: n (1–1000), artboardLayout?: {layout?: \"gridByRow\"|\"gridByColumn\"|\"row\"|\"column\", columns?: n (default: all in one row), spacing?: pt=20, rightToLeft?: bool}, bleed?: pt|[top, bottom, left, right]|{top?, …} (0–72 pt), backgroundContents?: \"transparent\"|\"white\" (a white artboard background, not an object), colorMode?: \"rgb\"|\"cmyk\" (a CMYK document starts with CMYK swatches and stores the colours applied to it as CMYK), rasterEffectsPpi?: 72|150|300 (1–2400), previewMode?: \"default\"|\"pixel\"|\"overprint\" (overprint turns Overprint Preview on, pixel Pixel Preview in the app; default leaves both), alignNewObjectsToPixelGrid?: bool (Advanced Options › Align New Objects to Pixel Grid: paths drawn in the document are pixel-aligned; default on for the Mobile and Web presets, else off; document.setup changes it later), profile?: a category of file.newPresets|null (the New Document profile the document starts from, see file.newProfiles; default: a built-in preset's category, kept by the saved and Recent presets made from it; null or no preset: the defaults), created?: Unix seconds|null (File Info's created date; default now, recorded in the journal so a replay matches), size?: a preset's size label (a preset file.newPresets lists can be passed back; ignored)} → {index, previewMode, profile?: the profile applied, warnings?: [text] (a color profile the profile's file carries that can't be used), profileError?: {profile, reason} (its file could not be read, was larger than 64 MiB or is not a native document, or the request may not read the profiles folder, a reason that leaves out the folder's path: the document has the defaults)}; the size is remembered in file.newPresets' Recent", + "{preset?: a name from file.newPresets (start from it; the other params change it), name?|title?: document name (default Untitled-N), width?: pt=612|\"210 mm\", height?: pt=792 (each more than 0 and at most 3,999,856 pt, as artboard.new takes them), units?: \"Pixels\"|\"Points\"|\"Picas\"|\"Inches\"|\"Millimeters\"|\"Centimeters\"|\"Feet\"|\"Yards\"|\"Meters\"|\"Feet & Inches\" (default: prefs unitsGeneral, as print presets; screen presets: Pixels), orientation?: \"portrait\"|\"landscape\" (swaps width and height to match), artboards?: n (1–1000), artboardLayout?: {layout?: \"gridByRow\"|\"gridByColumn\"|\"row\"|\"column\", columns?: n (default: all in one row), rows?: n (gridByColumn only, an error with another layout: that many rows, in place of columns; a preset keeps them until columns without rows or another layout is given), spacing?: pt=20, rightToLeft?: bool}, bleed?: pt|[top, bottom, left, right]|{top?, …} (0–72 pt), backgroundContents?: \"transparent\"|\"white\" (a white artboard background, not an object), colorMode?: \"rgb\"|\"cmyk\" (a CMYK document starts with CMYK swatches and stores the colours applied to it as CMYK), rasterEffectsPpi?: 72|150|300 (1–2400), previewMode?: \"default\"|\"pixel\"|\"overprint\" (overprint turns Overprint Preview on, pixel Pixel Preview in the app; default leaves both), alignNewObjectsToPixelGrid?: bool (Advanced Options › Align New Objects to Pixel Grid: paths drawn in the document are pixel-aligned; default on for the Mobile and Web presets, else off; document.setup changes it later), profile?: a category of file.newPresets|null (the New Document profile the document starts from, see file.newProfiles; default: a built-in preset's category, kept by the saved and Recent presets made from it; null or no preset: the defaults), created?: Unix seconds|null (File Info's created date; default now, recorded in the journal so a replay matches), size?: a preset's size label (a preset file.newPresets lists can be passed back; ignored)} → {index, previewMode, profile?: the profile applied, warnings?: [text] (a color profile the profile's file carries that can't be used), profileError?: {profile, reason} (its file is a link or a folder, could not be read, was larger than 64 MiB or is not a native document, or the request may not read the profiles folder, a reason that leaves out the folder's path: the document has the defaults)}; the size is remembered in file.newPresets' Recent", always, super::newdoc::file_new ), @@ -225,7 +225,7 @@ pub fn specs() -> Vec { "Clear", ["Edit"], Some("Delete"), - "{ids?, guides?: bool (with ids: also delete the selected ruler guides), keepJoined?: bool (without ids: the direct-selected anchors of a path with no selected segment are removed as path.removeAnchors removes them, without opening the path, and the next anchor along is selected (the one before at an open path's end); default: prefs deleteKeepsPathsJoined)} delete the objects `ids`, else the selection (fully selected objects and direct-selected anchors together, else ruler guides; a compound-path member selected on its own is deleted alone, and a compound left with no members goes too); without ids, refused while an object of a symbol instance's art is selected", + "{ids?, guides?: bool (with ids: also delete the selected ruler guides), keepJoined?: bool (without ids: the direct-selected anchors of a path with no selected segment are removed as path.removeAnchors removes them, without opening the path, and the next anchor along is selected (the one before at an open path's end); default: prefs deleteKeepsPathsJoined), keepEmpty?: bool (keep a compound path left with no members)} delete the objects `ids`, else the selection (fully selected objects and direct-selected anchors together, else ruler guides; a compound-path member selected on its own is deleted alone, and a compound left with no members goes too unless keepEmpty); without ids, refused while an object of a symbol instance's art is selected", has_selection_or_guides, clear ), @@ -1224,6 +1224,7 @@ fn cut_direct_selection(s: &mut Session, roots: &[NodeId]) -> Result { fn clear(s: &mut Session, p: &Value) -> Result { let guides = switch_or(p, "guides", false, "edit.clear")?; + let keep_empty = switch_or(p, "keepEmpty", false, "edit.clear")?; switch_or(p, "keepJoined", false, "edit.clear")?; let explicit = if p.get("ids").is_some() { Some(checked_ids_param(s, p, "ids", "edit.clear")?) } else { None }; // An object of a symbol instance's art can't be removed from the instance alone. @@ -1257,8 +1258,11 @@ fn clear(s: &mut Session, p: &Value) -> Result { return ok(); } s.edit("Clear", |d, sel| { - let parents: Vec<_> = - ids.iter().filter_map(|id| d.parent_of(*id).filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. })))).collect(); + let parents: Vec<_> = if keep_empty { + Vec::new() + } else { + ids.iter().filter_map(|id| d.parent_of(*id).filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. })))).collect() + }; d.remove_many(&ids)?; for p in parents { if d.node(p).is_some_and(|n| n.children().is_some_and(|c| c.is_empty())) { diff --git a/crates/engine/src/cmd/fileio.rs b/crates/engine/src/cmd/fileio.rs index 7aca68fd02..2c1ee412a6 100644 --- a/crates/engine/src/cmd/fileio.rs +++ b/crates/engine/src/cmd/fileio.rs @@ -37,7 +37,7 @@ mod encode; pub mod eps; mod export; pub(crate) mod imagemap; -mod importer; +pub(crate) mod importer; pub mod jxlread; mod legacy_ai; mod load; @@ -167,8 +167,8 @@ use formats::{ARTBOARD, ARTBOARDS, RANGE, USE_ARTBOARDS, import_name, writable}; pub use formats::{ DOC_EXTS, DOCX_EXTS, FORMATS, Format, FormatOption, OPEN_EXTS, PLACE_EXTS, RTF_EXTS, TEXT_EXTS, UNASSOCIATED_EXTS, builtin_open_filters, export_extensions, extension, file_stem, format, format_for_name, has_own_title, importer_formats, library_open_filters, open_extensions, - open_filters, opens_as_other, opens_with_importer, place_filters, plugin_formats, read_extensions, readable_format, readable_format_for_name, - titled_for_export, writable_format, + open_filters, opens_as_other, opens_with_importer, place_dialog_filters, place_filters, places_with_importer, plugin_formats, read_extensions, + readable_format, readable_format_for_name, titled_for_export, writable_format, }; #[cfg(test)] diff --git a/crates/engine/src/cmd/fileio/commands.rs b/crates/engine/src/cmd/fileio/commands.rs index a41831b200..0c03b1ea11 100644 --- a/crates/engine/src/cmd/fileio/commands.rs +++ b/crates/engine/src/cmd/fileio/commands.rs @@ -126,7 +126,7 @@ pub fn specs() -> Vec { "File Formats", [], None, - "{} → {formats: [{id, label, extensions, mime, read, write, raster, options: {name: {type, default, description}}, plugin?: the id of the exporter plug-in (write only) or importer plug-in (read only) that adds the format (its id is plugin.; see plugin.list)}], readable: [id…], writable: [id…], openExtensions: [ext…] (the importers' extensions that no built-in format reads included), unsupported: [{id, label, extensions, hint}] (formats asked for that can be neither opened nor written, such as DWG and PageMaker, with what to use instead)}", + "{} → {formats: [{id, label, extensions, mime, read, write, raster, options: {name: {type, default, description}}, plugin?: the id of the exporter plug-in (write only) or importer plug-in (read only) that adds the format (its id is plugin.; see plugin.list), place?: true (an importer's format whose files file.place also reads, see file.place's importer)}], readable: [id…], writable: [id…], openExtensions: [ext…] (the importers' extensions that no built-in format reads included), unsupported: [{id, label, extensions, hint}] (formats asked for that can be neither opened nor written, such as DWG and PageMaker, with what to use instead)}", always, formats ), diff --git a/crates/engine/src/cmd/fileio/encode.rs b/crates/engine/src/cmd/fileio/encode.rs index 1ecb41290e..23b7a1c13f 100644 --- a/crates/engine/src/cmd/fileio/encode.rs +++ b/crates/engine/src/cmd/fileio/encode.rs @@ -348,6 +348,7 @@ impl RasterOptions { Some(v) => background(v).map_err(|e| bad(C, format!("matte: {e}")))?, None => Some([255; 3]), }, + ..PaletteOptions::default() }, tiff: TiffOptions { color_model, diff --git a/crates/engine/src/cmd/fileio/formats.rs b/crates/engine/src/cmd/fileio/formats.rs index 0db990ad4c..0272bab874 100644 --- a/crates/engine/src/cmd/fileio/formats.rs +++ b/crates/engine/src/cmd/fileio/formats.rs @@ -737,11 +737,26 @@ fn format_filters() -> impl Iterator bool { let ext = extension(name); - !ext.is_empty() && !PLACE_EXTS.contains(&ext.as_str()) && !vectorcraft_plugins::import::for_extension(&ext).is_empty() + !ext.is_empty() + && !PLACE_EXTS.contains(&ext.as_str()) + && !vectorcraft_plugins::import::for_extension(&ext).is_empty() + && !places_with_importer(name) +} + +/// Whether File › Place places a file named `name` with an importer plug-in when no built-in format +/// reads its content: no built-in format reads its extension, and an installed importer whose manifest +/// sets `place` lists it. +pub fn places_with_importer(name: &str) -> bool { + let ext = extension(name); + !ext.is_empty() + && readable_format(&ext).is_none() + && !PLACE_EXTS.contains(&ext.as_str()) + && !vectorcraft_plugins::import::placing(&ext).is_empty() } /// Whether File › Open opens a file of extension `ext` (lower case) as something other than a @@ -871,6 +886,53 @@ pub fn place_filters() -> impl Iterator ImporterPart { + use vectorcraft_plugins::{import, registry}; + static MADE: std::sync::Mutex> = std::sync::Mutex::new(None); + let mut made = MADE.lock().unwrap_or_else(|e| e.into_inner()); + let revision = registry::revision(); + if let Some((r, part)) = made.as_ref() + && *r == revision + { + return part.clone(); + } + let mut exts: Vec<&'static str> = PLACE_EXTS.to_vec(); + let mut filters = Vec::new(); + for p in import::installed().into_iter().filter(|p| p.manifest().place) { + let m = p.manifest(); + let own: Vec<&'static str> = + m.extensions.iter().filter(|e| readable_format(e).is_none() && !PLACE_EXTS.contains(&e.as_str())).map(|e| registry::intern(e)).collect(); + if own.is_empty() { + continue; + } + for &e in &own { + if !exts.contains(&e) { + exts.push(e); + } + } + let own: &'static [&'static str] = Box::leak(own.into_boxed_slice()); + filters.push((registry::intern(&m.name), own)); + } + let exts: &'static [&'static str] = if exts.len() == PLACE_EXTS.len() { PLACE_EXTS } else { Box::leak(exts.into_boxed_slice()) }; + let part = (exts, filters); + *made = Some((revision, part.clone())); + part +} + +/// File › Place's own dialog filters: [`place_filters`], with the extensions of the installed +/// importer plug-ins that place their files in "All placeable files" and one filter per such +/// importer after the others, under its name ([`places_with_importer`]). Pickers that relink an +/// image use [`place_filters`]. +pub fn place_dialog_filters() -> impl Iterator { + let (all, importers) = importer_place_part(); + std::iter::once(("All placeable files", all)).chain(place_filters().skip(1)).chain(importers) +} + /// A format by id or extension (any case, leading dot allowed; `jpeg` finds `jpg`): a built-in /// one, else one a plug-in adds ([`plugin_formats`]), an exporter's before an importer's for an /// extension both list. A built-in format keeps its extension, so an exporter or importer that @@ -1021,6 +1083,9 @@ pub(super) fn formats(_: &mut Session, _: &Value) -> Result { let mut v = f.to_json(); if let Some(id) = vectorcraft_plugins::export::plugin_id(f.id) { v["plugin"] = json!(id); + if vectorcraft_plugins::import::by_format(f.id).is_some_and(|p| p.manifest().place) { + v["place"] = json!(true); + } } v }; diff --git a/crates/engine/src/cmd/fileio/importer.rs b/crates/engine/src/cmd/fileio/importer.rs index 3ba6c6fa19..d89cfa22b7 100644 --- a/crates/engine/src/cmd/fileio/importer.rs +++ b/crates/engine/src/cmd/fileio/importer.rs @@ -1,58 +1,118 @@ -//! `document.open` of the files importer plug-ins read ([`vectorcraft_plugins::import`]). +//! `document.open` and `file.place` of the files importer plug-ins read +//! ([`vectorcraft_plugins::import`]). //! //! A file opens with an importer when `importer` names one (its format id, `plugin.`), which //! must list the file's extension, or when no built-in format reads the file, by its content or by //! its extension, and an importer lists its extension (the one whose id sorts first, when several //! do). A built-in format that can't read a damaged file reports its own error: the file is not -//! handed to an importer instead. Place reads only the built-in formats. +//! handed to an importer instead. File › Place uses an importer by the same rules, among the +//! importers whose manifests set `place` ([`named_for_place`], [`for_place`]). //! //! The importer is given the file's bytes, at most [`import::MAX_INPUT_BYTES`] of them: a file //! named by `path` that only an importer can read is read no further than that. Its objects become -//! a new document whose artboard is their bounds, and nothing opens when the importer fails, -//! declines, is cancelled or returns objects that don't pass the checks a filter's output does. +//! a new document whose artboard is their bounds (or, to place, the art of one group), and nothing +//! opens or is placed when the importer fails, declines, is cancelled or returns objects that don't +//! pass the checks a filter's output does. use std::sync::Arc; use serde_json::Value; -use vectorcraft_doc::{Document, MAX_COORD}; +use vectorcraft_doc::{Document, MAX_COORD, NodeId}; use vectorcraft_geom::Rect; -use vectorcraft_plugins::{Plugin, export, import, objects}; +use vectorcraft_plugins::import::Mode; +use vectorcraft_plugins::{Manifest, Plugin, export, import, objects}; use super::super::{Result, bad, str_param}; -use super::load::{Loaded, detect, file_name}; -use super::{err, extension, file_stem, format}; +use super::load::{Loaded, Source, detect, file_name}; +use super::{Format, err, extension, file_stem, format}; use crate::EngineError; const C: &str = "document.open"; -/// The importer `document.open`'s params `p` name (`importer`), if any; a value that isn't a -/// string is an error. -fn named(p: &Value) -> Result> { +/// The importer command `cmd`'s params `p` name (`importer`), if any; a value that isn't a string +/// is an error. +fn named<'a>(p: &'a Value, cmd: &str) -> Result> { match p.get("importer").filter(|v| !v.is_null()) { None => Ok(None), - Some(v) => v.as_str().map(Some).ok_or_else(|| bad(C, "`importer` must be a plug-in format id (see document.formats)")), + Some(v) => v.as_str().map(Some).ok_or_else(|| bad(cmd, "`importer` must be a plug-in format id (see document.formats)")), } } +/// Checks that importer `m` lists the extension of the file `name`: else command `cmd`'s error, +/// which names the extensions it lists. +fn check_extension(cmd: &str, m: &Manifest, name: &str) -> Result<()> { + if m.extensions.contains(&extension(name)) { + return Ok(()); + } + let shown = vectorcraft_plugins::permissions::display_text(&m.name, vectorcraft_plugins::permissions::MAX_SHOWN_NAME); + let exts: Vec = m.extensions.iter().map(|e| format!(".{e}")).collect(); + Err(bad(cmd, format!("“{shown}” opens {} files, not `{}`", exts.join(", "), file_name(name)))) +} + /// The importer that opens the file `name` holding `bytes` with `document.open`'s params `p`: the /// one `importer` names, which must list the file's extension; else, when no built-in format reads /// the file, the first installed importer that lists its extension; else `None`. pub(super) fn pick(name: &str, bytes: &[u8], p: &Value) -> Result>> { - let ext = extension(name); - if let Some(id) = named(p)? { + if let Some(id) = named(p, C)? { let plugin = import::named(id).map_err(|e| bad(C, e.to_string()))?; - let m = plugin.manifest(); - if !m.extensions.contains(&ext) { - let shown = vectorcraft_plugins::permissions::display_text(&m.name, vectorcraft_plugins::permissions::MAX_SHOWN_NAME); - let exts: Vec = m.extensions.iter().map(|e| format!(".{e}")).collect(); - return Err(bad(C, format!("“{shown}” opens {} files, not `{}`", exts.join(", "), file_name(name)))); - } + check_extension(C, plugin.manifest(), name)?; return Ok(Some(plugin)); } if detect(name, bytes).is_some() { return Ok(None); } - Ok(import::for_extension(&ext).into_iter().next()) + Ok(import::for_extension(&extension(name)).into_iter().next()) +} + +/// The importer `file.place`'s params `p` name (`importer`) for the file `name`, which must set +/// `place` in its manifest and list the file's extension (errors of command `cmd`); `None` when `p` +/// names none. +pub(crate) fn named_for_place(name: &str, p: &Value, cmd: &str) -> Result>> { + let Some(id) = named(p, cmd)? else { return Ok(None) }; + let plugin = import::named(id).map_err(|e| bad(cmd, e.to_string()))?; + let m = plugin.manifest(); + if !m.place { + return Err(match import::not_placing(m) { + vectorcraft_plugins::Error::Params(why) => bad(cmd, why), + e => bad(cmd, e.to_string()), + }); + } + check_extension(cmd, m, name)?; + Ok(Some(plugin)) +} + +/// The importer File › Place uses for the file `name` when no built-in format reads it: the first +/// installed importer, by plug-in id, whose manifest sets `place` and that lists its extension. +pub(crate) fn for_place(name: &str) -> Option> { + import::placing(&extension(name)).into_iter().next() +} + +/// Whether an importer may read a file of extension `ext` for `mode` when none is named: no +/// built-in format reads the extension (for Place, as text, RTF or Word either) and an importer +/// that reads for `mode` lists it. +fn importer_reads(ext: &str, mode: Mode) -> bool { + super::readable_format(ext).is_none() + && match mode { + Mode::Import => !import::for_extension(ext).is_empty(), + Mode::Place => !super::PLACE_EXTS.contains(&ext) && !import::placing(ext).is_empty(), + } +} + +/// The error of the file `name`, past [`import::MAX_INPUT_BYTES`], which an importer would read +/// for `mode`. +fn too_large(name: &str, mode: Mode) -> EngineError { + match mode { + Mode::Import => err(format!("can't open `{}`: {}", file_name(name), import::too_large())), + Mode::Place => failed(Mode::Place, name, import::too_large()), + } +} + +/// The error of the file `name`, which importer `e` couldn't read for `mode`. +fn failed(mode: Mode, name: &str, e: impl std::fmt::Display) -> EngineError { + match mode { + Mode::Import => err(format!("can't open `{}`: {e}", file_name(name))), + Mode::Place => err(format!("can't place `{}`: {e}", file_name(name))), + } } /// How much of a file [`detect`] is given: more than its content checks read. @@ -61,14 +121,17 @@ const SNIFF_BYTES: usize = 64 << 10; /// Refuses `document.open`'s `dataBase64` in `p` before it is decoded when it holds a file past /// [`import::MAX_INPUT_BYTES`] that only an importer reads, by the rule of `read_path`. pub(super) fn check_data(p: &Value) -> Result<()> { + check_data_for(p, Mode::Import, C) +} + +/// [`check_data`] for `mode` and command `cmd`: `file.place`'s params with [`Mode::Place`]. +fn check_data_for(p: &Value, mode: Mode, cmd: &str) -> Result<()> { let Some(b64) = str_param(p, "dataBase64") else { return Ok(()); }; let name = str_param(p, "name").unwrap_or("Untitled"); - let ext = extension(name); - let explicit = named(p)?.is_some(); - let built_in = !explicit && (super::readable_format(&ext).is_some() || import::for_extension(&ext).is_empty()); - if built_in || vectorcraft_format::base64_decoded_len(b64) <= import::MAX_INPUT_BYTES as u64 { + let explicit = named(p, cmd)?.is_some(); + if (!explicit && !importer_reads(&extension(name), mode)) || vectorcraft_format::base64_decoded_len(b64) <= import::MAX_INPUT_BYTES as u64 { return Ok(()); } if !explicit { @@ -78,79 +141,121 @@ pub(super) fn check_data(p: &Value) -> Result<()> { return Ok(()); } } - Err(err(format!("can't open `{}`: {}", file_name(name), import::too_large()))) + Err(too_large(name, mode)) } /// The file at `path` for `document.open`'s params `p`. A file that only an importer reads (one /// `importer` names, or an extension no built-in format reads that an importer lists) is read up /// to [`import::MAX_INPUT_BYTES`]: past that, it is an error, unless the start of the file shows a /// built-in format and no importer was named, which is read whole as any other file is. A file past -/// the limit that isn't read whole is reported from its size, without reading it. -#[cfg(not(target_arch = "wasm32"))] +/// the limit that isn't read whole is reported from its size: with `importer` named, before any of +/// it is read, and otherwise after the start of it is read to look for a built-in format. pub(super) fn read_path(path: &str, p: &Value) -> Result> { - let ext = extension(path); - let explicit = named(p)?.is_some(); - if !explicit && (super::readable_format(&ext).is_some() || import::for_extension(&ext).is_empty()) { + read_path_for(path, p, Mode::Import, C) +} + +/// [`read_path`] for `mode` and command `cmd`: `file.place`'s params with [`Mode::Place`]. +#[cfg(not(target_arch = "wasm32"))] +fn read_path_for(path: &str, p: &Value, mode: Mode, cmd: &str) -> Result> { + let explicit = named(p, cmd)?.is_some(); + if explicit { + return read_for_importer(path, mode); + } + if !importer_reads(&extension(path), mode) { return super::read_file(path); } let head = super::read_file_head(path, SNIFF_BYTES)?; if head.len() < SNIFF_BYTES { return Ok(head); } - if !explicit && detect(path, &head).is_some() { + if detect(path, &head).is_some() { return super::read_file(path); } - let too_large = || err(format!("can't open `{}`: {}", file_name(path), import::too_large())); - let size = std::fs::metadata(path).map_err(|e| EngineError::Other(format!("{path}: {e}")))?.len(); - if size > import::MAX_INPUT_BYTES as u64 { - return Err(too_large()); + read_for_importer(path, mode) +} + +/// The file at `path` for an importer: refused from its size, before any of it is read, when it is +/// past [`import::MAX_INPUT_BYTES`]. +#[cfg(not(target_arch = "wasm32"))] +fn read_for_importer(path: &str, mode: Mode) -> Result> { + super::may_read(path)?; + let meta = std::fs::metadata(path).map_err(|e| EngineError::Other(format!("{path}: {e}")))?; + if meta.is_file() && meta.len() > import::MAX_INPUT_BYTES as u64 { + return Err(too_large(path, mode)); } - // The file can grow after the size is read. + // The file can grow after the size is read; anything but a regular file is refused here. let file = super::read_file_head(path, import::MAX_INPUT_BYTES + 1)?; if file.len() > import::MAX_INPUT_BYTES { - return Err(too_large()); + return Err(too_large(path, mode)); } Ok(file) } #[cfg(target_arch = "wasm32")] -pub(super) fn read_path(path: &str, _: &Value) -> Result> { +fn read_path_for(path: &str, _: &Value, _: Mode, _: &str) -> Result> { super::read_file(path) } +/// The file `file.place`'s params `p` name, as [`super::source`] reads it for command `cmd`, except +/// that a file an importer would place (one `importer` names, or an extension no built-in format +/// reads that an importer which places its files lists) is read, or decoded, only when it is at +/// most [`import::MAX_INPUT_BYTES`] long. +pub(crate) fn place_source<'a>(p: &'a Value, cmd: &str) -> Result> { + match str_param(p, "path") { + Some(path) => Ok(Source { name: path, bytes: read_path_for(path, p, Mode::Place, cmd)?, path: Some(path) }), + None => { + check_data_for(p, Mode::Place, cmd)?; + super::source(p, cmd) + } + } +} + +/// The file `name` holding `bytes` read by importer `plugin` for `mode` with command `cmd`'s params +/// `p` (`params`: the importer's own parameters) → the importer's format, a new document holding its +/// objects on its first layer, their ids, and its warnings. +fn read( + name: &str, + bytes: &[u8], + plugin: &Plugin, + p: &Value, + cmd: &str, + mode: Mode, +) -> Result<(&'static Format, Document, Vec, Vec)> { + let m = plugin.manifest(); + let format = format(&export::format_id(&m.id)).filter(|f| f.read).ok_or_else(|| err(vectorcraft_plugins::Error::NotFound(m.id.clone())))?; + let (ext, stem) = (extension(name), file_stem(name)); + let source = import::Source { extension: &ext, name: &stem }; + let params = p.get("params").cloned().unwrap_or(Value::Null); + let imported = import::run_as(plugin, bytes, ¶ms, source, mode).map_err(|e| match e { + vectorcraft_plugins::Error::Cancelled => EngineError::Cancelled, + vectorcraft_plugins::Error::Params(why) => bad(cmd, why), + e => failed(mode, name, e), + })?; + let mut doc = Document::new(1.0, 1.0); + let layer = doc.layers.first().map(|l| l.id); + let admit = |fx: &[vectorcraft_doc::Effect], n: &vectorcraft_doc::Node| crate::cmd::plugin::admit_effects_for(cmd, fx, n); + let ids = objects::apply_output(&mut doc, &[], imported.objects, layer, &admit).map_err(|e| failed(mode, name, e))?; + Ok((format, doc, ids, imported.warnings)) +} + +/// The file `name` holding `bytes` read by importer `plugin` to place it, with `file.place`'s params +/// `p` (errors of command `cmd`) → the importer's format, the document holding its objects on its +/// first layer, and its warnings. Importer `plugin`'s manifest must set `place`. +pub(crate) fn read_for_place(name: &str, bytes: &[u8], plugin: &Plugin, p: &Value, cmd: &str) -> Result<(&'static Format, Document, Vec)> { + let (format, doc, _, warnings) = read(name, bytes, plugin, p, cmd, Mode::Place)?; + Ok((format, doc, warnings)) +} + /// The file `name` holding `bytes` read by importer `plugin` with `document.open`'s params `p` /// (`params`: the importer's own parameters) into a new document, its artboard the bounds of what /// the importer returned. pub(super) fn load(name: &str, bytes: &[u8], plugin: &Plugin, p: &Value) -> Result { - let m = plugin.manifest(); - let format = format(&export::format_id(&m.id)).filter(|f| f.read).ok_or_else(|| err(vectorcraft_plugins::Error::NotFound(m.id.clone())))?; - let (ext, stem) = (extension(name), file_stem(name)); - let source = import::Source { extension: &ext, name: &stem }; - let params = p.get("params").cloned().unwrap_or(Value::Null); - let imported = import::run(plugin, bytes, ¶ms, source).map_err(|e| match e { - vectorcraft_plugins::Error::Cancelled => EngineError::Cancelled, - vectorcraft_plugins::Error::Params(why) => bad(C, why), - e => err(format!("can't open `{}`: {e}", file_name(name))), - })?; - let mut doc = Document::new(1.0, 1.0); - let layer = doc.layers.first().map(|l| l.id); - let admit = |fx: &[vectorcraft_doc::Effect], n: &vectorcraft_doc::Node| crate::cmd::plugin::admit_effects_for(C, fx, n); - let ids = - objects::apply_output(&mut doc, &[], imported.objects, layer, &admit).map_err(|e| err(format!("can't open `{}`: {e}", file_name(name))))?; + let (format, mut doc, ids, warnings) = read(name, bytes, plugin, p, C, Mode::Import)?; if let (Some(bounds), Some(board)) = (doc.bounds_of(&ids, true), doc.artboards.first_mut()) { board.rect = artboard_rect(bounds); } doc.title = file_name(name); - Ok(Loaded { - doc, - format, - warnings: imported.warnings, - restored: false, - converted: false, - preview_only: false, - editing_data: false, - native_pdf_compatible: None, - }) + Ok(Loaded { doc, format, warnings, restored: false, converted: false, preview_only: false, editing_data: false, native_pdf_compatible: None }) } /// The artboard of art with bounds `r`: `r` within ±[`MAX_COORD`], at least 1 pt wide and high diff --git a/crates/engine/src/cmd/freeform.rs b/crates/engine/src/cmd/freeform.rs index 548e5fade2..e31c21dd00 100644 --- a/crates/engine/src/cmd/freeform.rs +++ b/crates/engine/src/cmd/freeform.rs @@ -19,7 +19,7 @@ pub fn specs() -> Vec { "Add Freeform Point", [], None, - "{at: [x,y] (document coordinates), color? (default: the gradient's colour there; #rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), opacity?: 0..1 (or 0..100), spread?: 0..1 (or 0..100 %; the radius of pure colour around the point, a fraction of half the object's larger side; default 0), line?: true (join it to the selected point: extends the line ending there, else starts one), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind; without one, a Live Paint group's faces take a fill edit and its edges take a stroke edit), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} add a point to the freeform gradient (an unplaced one keeps its automatic points first) and select it. On a path directly in a graph series, the graph also stores the edited gradient when it is on the topmost visible fill or stroke, as for the other paint.freeform edits (docs/mcp.md); on a graph label's row, or on a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows for every label or line of its kind (a line's gradient without its points); the points on a label's characters are not stored; an error while the proxies show the Live Paint Bucket's colors and no ids, id or item are given → {index}", + "{at: [x,y] (document coordinates), color? (default: the gradient's colour there; #rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), opacity?: 0..1 (or 0..100), spread?: 0..1 (or 0..100 %; the radius of pure colour around the point, a fraction of half the object's larger side; default 0), line?: true (join it to the selected point: extends the line ending there, else starts one), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind; without one, a Live Paint group's faces take a fill edit and its edges take a stroke edit), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} add a point to the freeform gradient (an unplaced one keeps its automatic points first) and select it. On a path directly in a graph series, the graph also stores the edited gradient when it is on the topmost visible fill or stroke, as for the other paint.freeform edits (docs/mcp.md); on a graph label's row, or on a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows for every label or line of its kind (a line's gradient without its points); the points on a label's characters are not stored; an error while the proxy shows the colors the active tool paints with (the Live Paint Bucket's, the Shape Builder's fill) and no ids, id or item are given → {index}", has_doc, add_point ), @@ -28,7 +28,7 @@ pub fn specs() -> Vec { "Edit Freeform Point", [], None, - "{index? (default: the selected point), at?: [x,y] (document coordinates), color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), opacity?: 0..1 (or 0..100), spread?: 0..1 (or 0..100 %), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind; without one, a Live Paint group's faces take a fill edit and its edges take a stroke edit), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} move or recolour a point of the freeform gradient; an error while the proxies show the Live Paint Bucket's colors and no ids, id or item are given → {index}", + "{index? (default: the selected point), at?: [x,y] (document coordinates), color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), opacity?: 0..1 (or 0..100), spread?: 0..1 (or 0..100 %), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind; without one, a Live Paint group's faces take a fill edit and its edges take a stroke edit), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} move or recolour a point of the freeform gradient; an error while the proxy shows the colors the active tool paints with (the Live Paint Bucket's, the Shape Builder's fill) and no ids, id or item are given → {index}", has_doc, set_point ), @@ -37,7 +37,7 @@ pub fn specs() -> Vec { "Delete Freeform Point", [], None, - "{index? (default: the selected point), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind; without one, a Live Paint group's faces take a fill edit and its edges take a stroke edit), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} remove a point (never the last one); lines through it close up around it and lines left with one point go; an error while the proxies show the Live Paint Bucket's colors and no ids, id or item are given → {index}", + "{index? (default: the selected point), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind; without one, a Live Paint group's faces take a fill edit and its edges take a stroke edit), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} remove a point (never the last one); lines through it close up around it and lines left with one point go; an error while the proxy shows the colors the active tool paints with (the Live Paint Bucket's, the Shape Builder's fill) and no ids, id or item are given → {index}", has_doc, delete_point ), @@ -46,7 +46,7 @@ pub fn specs() -> Vec { "Add Freeform Line", [], None, - "{points: [index, …] (at least two), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind; without one, a Live Paint group's faces take a fill edit and its edges take a stroke edit), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} join points with a smooth line through them, in order; an error while the proxies show the Live Paint Bucket's colors and no ids, id or item are given → {line}", + "{points: [index, …] (at least two), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind; without one, a Live Paint group's faces take a fill edit and its edges take a stroke edit), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} join points with a smooth line through them, in order; an error while the proxy shows the colors the active tool paints with (the Live Paint Bucket's, the Shape Builder's fill) and no ids, id or item are given → {line}", has_doc, add_line ), @@ -55,7 +55,7 @@ pub fn specs() -> Vec { "Split Freeform Line", [], None, - "{line: line index, segment: the segment from the line's point `segment` to the next, t?: 0..1 along it (default 0.5), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind; without one, a Live Paint group's faces take a fill edit and its edges take a stroke edit), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} add a point on a line there (colour, opacity and spread between the segment's ends) and select it; an error while the proxies show the Live Paint Bucket's colors and no ids, id or item are given → {index}", + "{line: line index, segment: the segment from the line's point `segment` to the next, t?: 0..1 along it (default 0.5), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind; without one, a Live Paint group's faces take a fill edit and its edges take a stroke edit), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} add a point on a line there (colour, opacity and spread between the segment's ends) and select it; an error while the proxy shows the colors the active tool paints with (the Live Paint Bucket's, the Shape Builder's fill) and no ids, id or item are given → {index}", has_doc, split_line ), @@ -64,7 +64,7 @@ pub fn specs() -> Vec { "Select Freeform Point", [], None, - "{index: point index | null to clear} select a point of the freeform gradient behind the active proxy (the first selected object's; an index is an error while the proxies show the Live Paint Bucket's colors): the point the Gradient tool, the Gradient and Color panels and Delete act on → {index}", + "{index: point index | null to clear} select a point of the freeform gradient behind the active proxy (the first selected object's; an index is an error while the proxy shows the colors the active tool paints with: the Live Paint Bucket's, the Shape Builder's fill): the point the Gradient tool, the Gradient and Color panels and Delete act on → {index}", has_doc, select_point ), @@ -73,7 +73,7 @@ pub fn specs() -> Vec { "Freeform Gradient", [], None, - "{stroke?: bool (default: the active proxy)} the freeform gradient behind the proxy of the first selected object (an error while the proxies show the Live Paint Bucket's colors) → {mode: points|lines, points: [{at: [x,y] (document coordinates), color, opacity, spread}], lines: [[index, …]], selected: index|null}", + "{stroke?: bool (default: the active proxy)} the freeform gradient behind the proxy of the first selected object (an error while the proxy shows the colors the active tool paints with: the Live Paint Bucket's, the Shape Builder's fill) → {mode: points|lines, points: [{at: [x,y] (document coordinates), color, opacity, spread}], lines: [[index, …]], selected: index|null}", has_doc, get ), @@ -81,13 +81,21 @@ pub fn specs() -> Vec { } const NOT_FREEFORM: &str = "the paint is not a freeform gradient (apply one with paint.editGradient {kind: \"freeform\"})"; -const BUCKET_NOT_FREEFORM: &str = "the Live Paint Bucket's colors have no freeform points (give ids, id or item to edit an object's)"; -const BUCKET_NO_POINTS: &str = "the Live Paint Bucket's colors have no freeform points"; + +/// " have no freeform points" for the tool whose colors the fill (or stroke, `stroke`) +/// proxy shows ([`Session::painting_tool`]): the Live Paint Bucket's colors, the Shape Builder's +/// fill. None when the proxy shows the selection's paint. +fn tool_no_points(s: &Session, stroke: bool) -> Option<&'static str> { + s.painting_tool(stroke).map(|id| match id { + "shapeBuilder" => "the Shape Builder's fill has no freeform points", + _ => "the Live Paint Bucket's colors have no freeform points", + }) +} /// The error of `paint.freeform.get` and `paint.freeform.selectPoint` when the active proxy shows no freeform gradient: -/// while the Live Paint Bucket paints, the proxies show its colors, which have none. -fn no_proxy_freeform(s: &Session) -> &'static str { - if s.bucket_paints() { BUCKET_NO_POINTS } else { NOT_FREEFORM } +/// while the active tool paints with the chosen colors of that kind, the proxy shows them, which have none. +fn no_proxy_freeform(s: &Session, stroke: bool) -> &'static str { + tool_no_points(s, stroke).unwrap_or(NOT_FREEFORM) } impl Session { @@ -187,13 +195,16 @@ pub(crate) fn parse_mode(m: &str) -> std::result::Result { /// as one undo step; returns what it returned for the first. An unplaced gradient gets the /// automatic points it shows first, and the stops follow the points' colours. fn edit(s: &mut Session, p: &Value, cmd: &str, mut f: impl FnMut(&mut Freeform, Space) -> std::result::Result) -> Result { - // While the Live Paint Bucket paints, the proxies show its colors, which have no freeform points - // (paint.freeform.get finds none): an edit that names no target is refused. A bad `aligned` or - // `target` is refused first, as it is without the bucket. - if super::paint::for_bucket(s, p) { + // While the active tool paints with the chosen colors (the Live Paint Bucket's, the Shape + // Builder's fill), the proxy shows them, and they have no freeform points (paint.freeform.get + // finds none): an edit that names no target is refused. A bad `aligned`, `target` or `stroke` + // is refused first, as it is otherwise. + let kind = super::paint::tool_gradient_kind(s, p, cmd)?; + if super::paint::for_tool(s, p, kind) { super::appearance::aligned(p, cmd)?; super::appearance::targets_contents(p)?; - return Err(bad(cmd, BUCKET_NOT_FREEFORM)); + let none = tool_no_points(s, kind).unwrap_or(NOT_FREEFORM); + return Err(bad(cmd, format!("{none} (give ids, id or item to edit an object's)"))); } let item = item_target(s, p, cmd)?; let stroke = edits_stroke(s, p, item, !s.fill_active, cmd)?; @@ -347,7 +358,7 @@ fn select_point(s: &mut Session, p: &Value) -> Result { Some(Value::Null) => None, Some(v) => { let i = v.as_u64().map(index).ok_or_else(|| bad(C, "`index` must be a whole number or null"))?; - let (f, _) = s.proxy_freeform(!s.fill_active).ok_or_else(|| bad(C, no_proxy_freeform(s)))?; + let (f, _) = s.proxy_freeform(!s.fill_active).ok_or_else(|| bad(C, no_proxy_freeform(s, !s.fill_active)))?; check_index(&f, i).map_err(|e| bad(C, e))?; Some(i) } @@ -359,7 +370,7 @@ fn select_point(s: &mut Session, p: &Value) -> Result { fn get(s: &mut Session, p: &Value) -> Result { const C: &str = "paint.freeform.get"; let stroke = switch_or(p, "stroke", !s.fill_active, C)?; - let (f, _) = s.proxy_freeform(stroke).ok_or_else(|| bad(C, no_proxy_freeform(s)))?; + let (f, _) = s.proxy_freeform(stroke).ok_or_else(|| bad(C, no_proxy_freeform(s, stroke)))?; let selected = if stroke != s.fill_active { s.selected_freeform_point().filter(|i| *i < f.points.len()) } else { None }; let mut v = vectorcraft_tools::params::freeform_json(&f); v["selected"] = json!(selected); diff --git a/crates/engine/src/cmd/gradient.rs b/crates/engine/src/cmd/gradient.rs index 2b14fdba2d..1178906459 100644 --- a/crates/engine/src/cmd/gradient.rs +++ b/crates/engine/src/cmd/gradient.rs @@ -24,7 +24,7 @@ pub fn specs() -> Vec { "Gradient", ["Window", "Gradient"], None, - "{stroke?: bool (default: the targeted item's kind, else the active proxy), kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical, sweeps the stops once around the center, clockwise from the vector, with a seam where the last stop meets the first; diamond runs the stops from the center out to a square with a corner at the end of the vector; freeform places points on each object, coloured along the stops), mode?: points|lines (freeform: how the Gradient tool adds points), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (how the colours between the stops mix: in display RGB, perceptually (OKLab) so the steps look even, or around the hue wheel: hue, saturation and brightness each change evenly from one stop to the next, the hue angle falling with hue-clockwise (red, magenta, blue, cyan, green, yellow) and rising with hue-counterclockwise; two stops whose hues are less than half a color level apart keep that hue; a stop whose RGB numbers are less than half a color level apart is gray and takes the hue of the stop it mixes with, and black that stop's saturation too; these two methods are VectorCraft's own, and SVG and PDF exports draw their gradients as RGB images, CMYK and spot color stops included; SVG exports draw a Perceptual gradient as an image, and PDF exports do too unless it is linear, radial, conic or diamond, has spot color stops, every other stop is paper white or written in CMYK or gray (an export that converts colors to a CMYK destination profile writes RGB and Lab stops in CMYK, and so does a CMYK document unless the export converts colors to an RGB destination profile), it is not a dithered fill and its curve does not have too many stops: then PDF writes tints of one spot ink as a Separation shading in that ink, and spot inks mixed with other spot, CMYK or gray inks as a DeviceN shading; freeform gradients mix their own way), spread?: pad|repeat|reflect (linear, radial, conic and diamond: what the gradient paints past the ends of its stops: pad carries the end colors on; repeat and reflect run the stops `repeats` times along the vector (around the circle, for a conic) and on past both ends, reflect mirroring every other run; an error on a freeform gradient), repeats?: 1..100 (a whole number: how many times repeat and reflect run the stops along the vector; VectorCraft's own limit; pad keeps it unused), stops?: [{offset 0..1, color? (needed without swatch; #rrggbbaa and #rgba are refused), opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: colour swatch name (a global or spot colour or tint swatch links the stop, so swatch edits recolour it and a spot stop prints on its plate; a process colour just gives its colour), tint?: 0..100 (% of the linked swatch; default 100, or a tint swatch's own)}] (at least 2; a freeform gradient's points are recoloured along them), keepModel?: bool (as paint.setFill; a stop color the gradient already has keeps its model), angle?: deg counter-clockwise (0: the gradient runs left to right; radial, conic and diamond: the vector turns about the center), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep and is an error for the other kinds; an error when no object is edited, as with nothing selected, the Live Paint Bucket's gradient, or a fill edit of a Live Paint group without faces: the default gradient fits each new object and keeps no aspect), reverse?: bool (the same ramp the other way round: the stops in reverse order, and a hue method turned the other way unless `method` is given too), dither?: bool (fills only: a linear, radial, conic or diamond gradient fill is drawn with fine noise that hides banding, and as pixels in SVG and PDF exports), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.setFill; without stroke, the kind of the row edited), ids?|id?, defaultsOnly?: bool (as paint.setFill), strokeMode?: within|along|across (strokes only: the gradient lies on the page and shows through the stroke, runs from the start of each subpath to its end, or runs from the stroke's left edge to its right all along it; with nothing selected, for the next object drawn; type characters' own strokes always paint within), target?: \"object\"|\"contents\"} edit the gradient in place (keeps its placement); solid/none paints become the default gradient. Without `item`, a Live Paint group's faces take a fill edit and its edges take a stroke edit. On a path directly in a graph series, the graph also stores the gradient when it is on the topmost visible fill or stroke (docs/mcp.md); on a graph label's row, or on a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows for every label or line of its kind (a line's gradient without its placement), and on its characters their gradient without its placement, fitted to each label. While the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), or `defaultsOnly: true` is given, only the default changes (the paint the bucket paints with)", + "{stroke?: bool (default: the targeted item's kind, else the active proxy), kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical, sweeps the stops once around the center, clockwise from the vector, with a seam where the last stop meets the first; diamond runs the stops from the center out to a square with a corner at the end of the vector; freeform places points on each object, coloured along the stops), mode?: points|lines (freeform: how the Gradient tool adds points), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (how the colours between the stops mix: in display RGB, perceptually (OKLab) so the steps look even, or around the hue wheel: hue, saturation and brightness each change evenly from one stop to the next, the hue angle falling with hue-clockwise (red, magenta, blue, cyan, green, yellow) and rising with hue-counterclockwise; two stops whose hues are less than half a color level apart keep that hue; a stop whose RGB numbers are less than half a color level apart is gray and takes the hue of the stop it mixes with, and black that stop's saturation too; these two methods are VectorCraft's own, and SVG and PDF exports draw their gradients as RGB images, CMYK and spot color stops included; SVG exports draw a Perceptual gradient as an image, and PDF exports do too unless it is linear, radial, conic or diamond, has spot color stops, every other stop is paper white or written in CMYK or gray (an export that converts colors to a CMYK destination profile writes RGB and Lab stops in CMYK, and so does a CMYK document unless the export converts colors to an RGB destination profile), it is not a dithered fill and its curve does not have too many stops: then PDF writes tints of one spot ink as a Separation shading in that ink, and spot inks mixed with other spot, CMYK or gray inks as a DeviceN shading; freeform gradients mix their own way), spread?: pad|repeat|reflect (linear, radial, conic and diamond: what the gradient paints past the ends of its stops: pad carries the end colors on; repeat and reflect run the stops `repeats` times along the vector (around the circle, for a conic) and on past both ends, reflect mirroring every other run; an error on a freeform gradient), repeats?: 1..100 (a whole number: how many times repeat and reflect run the stops along the vector; VectorCraft's own limit; pad keeps it unused), stops?: [{offset 0..1, color? (needed without swatch; #rrggbbaa and #rgba are refused), opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: colour swatch name (a global or spot colour or tint swatch links the stop, so swatch edits recolour it and a spot stop prints on its plate; a process colour just gives its colour), tint?: 0..100 (% of the linked swatch; default 100, or a tint swatch's own)}] (at least 2; a freeform gradient's points are recoloured along them), keepModel?: bool (as paint.setFill; a stop color the gradient already has keeps its model), angle?: deg counter-clockwise (0: the gradient runs left to right; radial, conic and diamond: the vector turns about the center), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep and is an error for the other kinds; an error when no object is edited, as with nothing selected, the Live Paint Bucket's gradient, the Shape Builder's fill, or a fill edit of a Live Paint group without faces: the default gradient fits each new object and keeps no aspect), reverse?: bool (the same ramp the other way round: the stops in reverse order, and a hue method turned the other way unless `method` is given too), dither?: bool (fills only: a linear, radial, conic or diamond gradient fill is drawn with fine noise that hides banding, and as pixels in SVG and PDF exports), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.setFill; without stroke, the kind of the row edited), ids?|id?, defaultsOnly?: bool (as paint.setFill), strokeMode?: within|along|across (strokes only: the gradient lies on the page and shows through the stroke, runs from the start of each subpath to its end, or runs from the stroke's left edge to its right all along it; with nothing selected, for the next object drawn; type characters' own strokes always paint within), target?: \"object\"|\"contents\"} edit the gradient in place (keeps its placement); solid/none paints become the default gradient. Without `item`, a Live Paint group's faces take a fill edit and its edges take a stroke edit. On a path directly in a graph series, the graph also stores the gradient when it is on the topmost visible fill or stroke (docs/mcp.md); on a graph label's row, or on a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows for every label or line of its kind (a line's gradient without its placement), and on its characters their gradient without its placement, fitted to each label. While the Live Paint Bucket, or for a fill the Shape Builder, is the active tool and no ids, id or item are given (a null ids or id counts as none), or `defaultsOnly: true` is given, only the default changes (the paint the tool paints with)", has_doc, edit_gradient ), @@ -42,7 +42,7 @@ pub fn specs() -> Vec { "Select Gradient Stop", [], None, - "{index: stop index (0 = the start) | null to clear} select a stop of the gradient behind the active proxy (the first selected object's, else the default paint; the default paint's while the Live Paint Bucket is the active tool): the stop the Gradient tool's annotator, the Gradient and Color panels and Delete/arrow keys act on; refused while an object of a symbol instance's art is selected, except while the Live Paint Bucket is the active tool → {index}", + "{index: stop index (0 = the start) | null to clear} select a stop of the gradient behind the active proxy (the first selected object's, else the default paint; the default paint's while the Live Paint Bucket, or with the Fill proxy in front the Shape Builder, is the active tool): the stop the Gradient tool's annotator, the Gradient and Color panels and Delete/arrow keys act on; refused while an object of a symbol instance's art is selected, except while the proxy in front shows the default paint that way → {index}", always, select_stop ), @@ -61,9 +61,9 @@ pub(crate) fn active_gradient(s: &Session) -> Option { fn select_stop(s: &mut Session, p: &Value) -> Result { const C: &str = "gradient.selectStop"; // No document is needed for the default paint's gradient, so this does not use `refuse_symbol_part`. - // While the Live Paint Bucket is active the proxies show the default paint, whose stops can be - // selected with a part picked. - if !s.bucket_paints() && s.active().is_some_and(|st| st.selection.symbol_part.is_some()) { + // While the Live Paint Bucket is active the proxies show the default paint (the Shape Builder's + // Fill proxy does too), whose stops can be selected with a part picked. + if !s.tool_paints(!s.fill_active) && s.active().is_some_and(|st| st.selection.symbol_part.is_some()) { return Err(super::brushsym::part_only()); } let index = match p.get("index") { @@ -84,10 +84,10 @@ fn select_stop(s: &mut Session, p: &Value) -> Result { /// Whose gradient a selected stop belongs to: the active document, its first selected object /// (None: the default paint), whether a part of a symbol instance's art is picked, the proxy in -/// front, the Appearance panel's active item and whether the Live Paint Bucket is the active tool -/// (its proxies show the default paint). Selecting other art, picking a part of the instance, -/// toggling the proxy, picking another item or choosing the bucket or leaving it leaves no stop -/// selected. +/// front, the Appearance panel's active item and the tool the proxy in front shows the default +/// paint for (the Live Paint Bucket, or the Shape Builder's Fill proxy). Selecting other art, +/// picking a part of the instance, toggling the proxy, picking another item or choosing such a +/// tool or leaving it leaves no stop selected. #[derive(Clone, Copy, Debug, PartialEq)] pub(crate) struct StopOwner { doc: Option, @@ -98,7 +98,8 @@ pub(crate) struct StopOwner { part: bool, fill: bool, item: Option, - bucket: bool, + /// The tool whose color the proxy in front stood for ([`Session::painting_tool`]). + painter: Option<&'static str>, } impl StopOwner { @@ -111,19 +112,24 @@ impl StopOwner { part: st.is_some_and(|d| d.selection.symbol_part.is_some()), fill: s.fill_active, item: s.appearance_item(), - bucket: s.bucket_paints(), + painter: s.painting_tool(!s.fill_active), } } + + /// The tool whose gradient the stop is on; None for the selection's paint. + pub(crate) fn painter(&self) -> Option<&'static str> { + self.painter + } } impl Session { /// Does `paint.editGradient` without `ids` edit objects on the fill (or the stroke, `stroke`)? It does not - /// while the Live Paint Bucket is active or when nothing it can paint is selected (a Live Paint group stands - /// only for its faces in a fill edit and its edges in a stroke edit): it then edits no object and takes no - /// `aspect`. + /// while the active tool paints with the chosen fill (or stroke: [`Session::tool_paints`]) or when nothing it + /// can paint is selected (a Live Paint group stands only for its faces in a fill edit and its edges in a stroke + /// edit): it then edits no object and takes no `aspect`. pub fn gradient_edit_has_objects(&self, stroke: bool) -> bool { let p = json!({ "stroke": stroke }); - !super::paint::for_bucket(self, &p) + !super::paint::for_tool(self, &p, stroke) && item_target(self, &p, "paint.editGradient") .is_ok_and(|item| item.of_kind(self, !stroke).targets_for(self, &p, !stroke).is_ok_and(|ids| !ids.is_empty())) } @@ -526,9 +532,10 @@ fn apply_gradient_edit_in_model( if let Some(b) = bounds { gp.seed_freeform(b, if switched { inside } else { &|_| true }); } + // Without points (the default gradient's, placed on no object yet) the stops are the colors. if recolor && !switched - && let Some(f) = &mut gp.freeform + && let Some(f) = gp.freeform.as_mut().filter(|f| !f.points.is_empty()) { f.recolor(&gp.gradient); gp.gradient.stops = f.stops(); @@ -546,9 +553,10 @@ fn apply_gradient_edit_in_model( fn edit_gradient(s: &mut Session, p: &Value) -> Result { const C: &str = "paint.editGradient"; - // While the Live Paint Bucket is active, the gradient it paints with changes; the selection keeps its own. - let bucket = super::paint::bucket_color_params(s, p, C)?; - let p = bucket.as_ref().unwrap_or(p); + // While the active tool paints with the chosen fill or stroke, the gradient it paints with changes; the + // selection keeps its own. + let for_tool = super::paint::tool_gradient_params(s, p, C)?; + let p = for_tool.as_ref().unwrap_or(p); let item = item_target(s, p, C)?; let stroke = edits_stroke(s, p, item, !s.fill_active, C)?; check_switches(p, &["reverse", "dither"], C)?; @@ -649,7 +657,7 @@ fn edit_gradient(s: &mut Session, p: &Value) -> Result { })?; if let Some(m) = mode && !selected - && (bucket.is_some() || p.get("ids").is_none()) + && (for_tool.is_some() || p.get("ids").is_none()) && let Some(st) = s.new_art_stroke_mut() { st.gradient_mode = m; diff --git a/crates/engine/src/cmd/gradpresets.rs b/crates/engine/src/cmd/gradpresets.rs index 89deda43ad..9b429beaa2 100644 --- a/crates/engine/src/cmd/gradpresets.rs +++ b/crates/engine/src/cmd/gradpresets.rs @@ -33,7 +33,7 @@ pub fn specs() -> Vec { "Apply Gradient Preset", [], None, - "{name: a preset's name (gradient.presets.list), stroke?, item?, ids?|id?, defaultsOnly?, target? (as paint.editGradient)} give the gradient behind the active proxy (or the targeted fill or stroke) the preset's type, stops, method, spread and repeats (a freeform preset's: the first three), and a fill its dither, keeping its placement; a solid or no paint becomes the gradient. One undo step, as paint.editGradient (while the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), or `defaultsOnly: true` is given, only the default changes, by the active proxy) → {name, ids: the objects painted (none: only the default changed)}", + "{name: a preset's name (gradient.presets.list), stroke?, item?, ids?|id?, defaultsOnly?, target? (as paint.editGradient)} give the gradient behind the active proxy (or the targeted fill or stroke) the preset's type, stops, method, spread and repeats (a freeform preset's: the first three), and a fill its dither, keeping its placement; a solid or no paint becomes the gradient. One undo step, as paint.editGradient (while the Live Paint Bucket, or for a fill the Shape Builder, is the active tool and no ids, id or item are given (a null ids or id counts as none), or `defaultsOnly: true` is given, only the default changes, by the active proxy) → {name, ids: the objects painted (none: only the default changed)}", has_doc, apply ), @@ -207,10 +207,10 @@ fn apply(s: &mut Session, p: &Value) -> Result { const C: &str = "gradient.presets.apply"; let name = name_param(p, C)?; let preset = s.gradient_preset(name).ok_or_else(|| bad(C, format!("no gradient preset `{name}` (see gradient.presets.list)")))?; - // While the Live Paint Bucket is active, the gradient it paints with changes, chosen by the - // active proxy rather than the selection's Appearance row (as paint.editGradient chooses). - let bucket = super::paint::bucket_color_params(s, p, C)?; - let p = bucket.as_ref().unwrap_or(p); + // While the active tool paints with the chosen fill or stroke, the gradient it paints with + // changes (as paint.editGradient chooses). + let for_tool = super::paint::tool_gradient_params(s, p, C)?; + let p = for_tool.as_ref().unwrap_or(p); let stroke = edits_stroke(s, p, item_target(s, p, C)?, !s.fill_active, C)?; let g = &preset.gradient; let mut edit = p.clone(); diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 1782e60f9c..5c7c75c610 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -66,7 +66,7 @@ pub fn specs() -> Vec { "Set Current Layer", [], None, - "{id} click a row: it alone is highlighted, and the layer it is (or the layer it is in) becomes the current layer, where new art goes. Not an undo step → {id, layer}", + "{id, keepRows?: bool} click a row: it alone is highlighted, and the layer it is (or the layer it is in) becomes the current layer, where new art goes. `keepRows` true leaves the highlighted rows as they are. Not an undo step → {id, layer}", has_doc, set_current ), @@ -102,10 +102,19 @@ pub fn specs() -> Vec { "Select Art", [], None, - "{id, add?: bool} the Layers panel's selection column: select the visible, unlocked art of a layer (its sublayers' too), or the object itself; `add` (Shift-click) adds it to the selection, or removes it when it is all selected already → {selected: [..]}", + "{id, add?: bool} or {range: [id…], add?: bool} the Layers panel's selection column: select the visible, unlocked art of a layer (its sublayers' too), or the object itself; `add` (Shift-click with no square clicked before, or Ctrl/Cmd-click) adds it to the selection, or removes it when it is all selected already. `range` (Shift-click, the rows from the last square clicked to this one): the art of every listed row that is visible, unlocked and inside the isolated art is selected, or added to the selection with `add` (Shift+Ctrl/Cmd-click); a range with no such row is an error. Not an undo step; the highlighted rows stay → {selected: [..]} (with `range`: {range, selected})", has_doc, select_art ), + cmd!( + "layer.selectHighlighted", + "Select Art of Highlighted Rows", + [], + None, + "{add?: bool} select the art of the Layers panel's highlighted rows, as clicking each row's selection square does: a layer's or sublayer's visible, unlocked art (its sublayers' too), or the group or object itself; hidden and locked rows and rows outside the isolated art are left out. `add` adds the art to the selection. No highlighted row, or none that is visible and unlocked, is an error. Not an undo step; the highlighted rows stay → {rows, selected: [..]}", + has_doc, + select_highlighted + ), cmd!( "layer.move", "Move Rows", @@ -633,10 +642,13 @@ fn duplicate_rows(s: &mut Session, p: &Value) -> Result { fn set_current(s: &mut Session, p: &Value) -> Result { const C: &str = "layer.setCurrent"; let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing id"))?; + let keep_rows = switch_or(p, "keepRows", false, C)?; let st = s.doc_mut()?; let layer = st.doc.layer_containing(id).ok_or(EngineError::NoNode(id))?; st.active_layer = Some(layer); - st.layer_rows = vec![id]; + if !keep_rows { + st.layer_rows = vec![id]; + } st.revision += 1; Ok(json!({ "id": id.0, "layer": layer.0 })) } @@ -753,6 +765,11 @@ fn in_isolation(doc: &Document, isolation: Option, id: NodeId) -> bool { /// The selection column: select a row's art. fn select_art(s: &mut Session, p: &Value) -> Result { const C: &str = "layer.selectAll"; + if let Some(ids) = ids_param(p, "range", C)? { + let add = switch_or(p, "add", false, C)?; + let (range, selected) = select_rows_art(s, ids, add, C, "no row in the range is visible, unlocked and inside the isolated art")?; + return Ok(json!({ "range": range, "selected": selected })); + } let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing id"))?; let add = switch_or(p, "add", false, C)?; let st = s.doc()?; @@ -789,6 +806,51 @@ fn select_art(s: &mut Session, p: &Value) -> Result { Ok(json!({ "selected": st.selection.objects.iter().map(|i| i.0).collect::>() })) } +/// Select Art of Highlighted Rows: the art of the highlighted rows, as their selection squares +/// select it. +fn select_highlighted(s: &mut Session, p: &Value) -> Result { + const C: &str = "layer.selectHighlighted"; + let add = switch_or(p, "add", false, C)?; + let rows = s.doc()?.highlighted_rows(); + if rows.is_empty() { + return Err(bad(C, "no row is highlighted")); + } + let (rows, selected) = select_rows_art(s, rows, add, C, "no highlighted row is visible, unlocked and inside the isolated art")?; + Ok(json!({ "rows": rows, "selected": selected })) +} + +/// Selects the art of the Layers panel rows `ids` (at most [`MAX_ROWS`]), or adds it to the +/// selection with `add`: each row that is visible, unlocked and inside the isolated art (or is the +/// isolated layer) gives what its selection square selects, a layer's visible, unlocked art (its +/// sublayers' too) or the group or object itself, as [`Selection::target_range`] gathers it for a +/// range of target circles. Nothing is targeted and the highlighted rows stay. Without such a row it +/// is the error `none`. Returns the rows used and the selected objects. +/// +/// [`Selection::target_range`]: vectorcraft_doc::Selection::target_range +fn select_rows_art(s: &mut Session, mut ids: Vec, add: bool, c: &str, none: &str) -> Result<(Vec, Vec)> { + ids.truncate(MAX_ROWS); + let rows = { + let st = s.doc()?; + // Measures the locked artboards once for every row, not once per row. + let editable = st.doc.editable(); + ids.retain(|id| { + st.doc.node(*id).is_some_and(|n| { + let isolated_layer = st.isolation == Some(*id) && n.is_layer(); + !n.is_ruler_guide() && editable(*id) && (isolated_layer || in_isolation(&st.doc, st.isolation, *id)) + }) + }); + st.layer_rows.clone() + }; + if ids.is_empty() { + return Err(bad(c, none)); + } + s.select(|d, sel| sel.target_range(d, &ids, add))?; + let st = s.doc_mut()?; + // The selection column leaves the highlighted rows as they are. + st.layer_rows = rows; + Ok((ids.iter().map(|i| i.0).collect(), st.selection.objects.iter().map(|i| i.0).collect())) +} + #[derive(Clone, Copy, PartialEq, Eq)] enum Place { Above, diff --git a/crates/engine/src/cmd/library.rs b/crates/engine/src/cmd/library.rs index 80c4cbefb9..4f92220324 100644 --- a/crates/engine/src/cmd/library.rs +++ b/crates/engine/src/cmd/library.rs @@ -1247,7 +1247,7 @@ fn use_item(s: &mut Session, p: &Value) -> Result { } Kind::FillColor | Kind::StrokeColor => { let stroke = to_stroke(p, kind)?; - let only = super::paint::defaults_only(s, p, C)?; + let only = super::paint::defaults_only(s, p, C, stroke)?; let color = data.get("color").cloned().ok_or_else(|| bad(C, "no colour"))?; let set = if stroke { "paint.setStroke" } else { "paint.setFill" }; match str_param(&data, "spot").map(str::trim).filter(|n| !n.is_empty()) { @@ -1260,7 +1260,7 @@ fn use_item(s: &mut Session, p: &Value) -> Result { } Kind::FillGradient | Kind::StrokeGradient => { let stroke = to_stroke(p, kind)?; - let only = super::paint::defaults_only(s, p, C)?; + let only = super::paint::defaults_only(s, p, C, stroke)?; let damaged = || bad(C, "the library item is damaged"); let mut g: GradientPaint = data.get("gradient").cloned().and_then(|v| serde_json::from_value(v).ok()).ok_or_else(damaged)?; if !clean_gradient(&mut g) { @@ -1275,7 +1275,7 @@ fn use_item(s: &mut Session, p: &Value) -> Result { } Kind::FillPattern | Kind::StrokePattern => { let stroke = to_stroke(p, kind)?; - let only = super::paint::defaults_only(s, p, C)?; + let only = super::paint::defaults_only(s, p, C, stroke)?; let pattern = use_pattern(s, &data, stroke, only)?; Ok(json!({ "kind": if stroke { "strokePattern" } else { "fillPattern" }, "pattern": pattern })) } diff --git a/crates/engine/src/cmd/newart.rs b/crates/engine/src/cmd/newart.rs index b95134aa59..ffea03187d 100644 --- a/crates/engine/src/cmd/newart.rs +++ b/crates/engine/src/cmd/newart.rs @@ -224,9 +224,11 @@ impl Session { /// the first selected object (so the last selection's once nothing is selected). Not while the /// Live Paint Bucket is the active tool: the fill and stroke are the colors it paints with. Nor /// after a command that changed only them (`defaultsOnly`), unless a later step of a batch - /// changed what new art would take ([`Session::new_art_source`]). + /// changed what new art would take ([`Session::new_art_source`]). While the Shape Builder is + /// active, the fill it paints with stays ([`Session::tool_paints`]). pub(crate) fn inherit_new_art(&mut self) { - if self.prefs.new_art_basic || self.bucket_paints() { + let (fill, stroke) = (self.tool_paints(false), self.tool_paints(true)); + if self.prefs.new_art_basic || (fill && stroke) { return; } let Some(source) = self.new_art_source() else { return }; @@ -234,7 +236,20 @@ impl Session { return; } let NewArtSource { appearance, opacity, blend, style, .. } = source; + let kept_fill = fill.then(|| self.paint.fill.clone()); + let kept_stroke = stroke.then(|| (self.paint.stroke.clone(), self.paint.stroke_width)); self.take_new_art(appearance, opacity, blend, style, true); + let p = &mut self.paint; + // New art whose kept paint differs from the selection's is not linked to its graphic style. + if kept_fill.as_ref().is_some_and(|f| *f != p.fill) || kept_stroke.as_ref().is_some_and(|(s, w)| *s != p.stroke || *w != p.stroke_width) { + p.style = None; + } + if let Some(f) = kept_fill { + p.fill = f; + } + if let Some((s, w)) = kept_stroke { + (p.stroke, p.stroke_width) = (s, w); + } } /// What [`Session::inherit_new_art`] gives new art: the appearance of the active document's @@ -275,13 +290,14 @@ impl Session { let (fill, stroke) = self.proxy_paints(); let weight_mixed = read.as_ref().map_or_else(|| self.active().is_some_and(|st| st.stroke_mixed().weight), |p| p.weight_mixed); let weight = self.shown_stroke().filter(|st| st.paint != Paint::None && !weight_mixed).map(|st| st.width); - if !fill_mixed { + // A proxy that shows the color the active tool paints with (the Shape Builder's fill) keeps it. + if !fill_mixed && !self.tool_paints(false) { self.paint.fill = unplaced(&fill); } - if !stroke_mixed { + if !stroke_mixed && !self.tool_paints(true) { self.paint.stroke = unplaced(&stroke); } - if let Some(width) = weight { + if let Some(width) = weight.filter(|_| !self.tool_paints(true)) { self.paint.stroke_width = width; } } diff --git a/crates/engine/src/cmd/newdoc.rs b/crates/engine/src/cmd/newdoc.rs index 4785816809..8272f7d8cb 100644 --- a/crates/engine/src/cmd/newdoc.rs +++ b/crates/engine/src/cmd/newdoc.rs @@ -27,7 +27,7 @@ pub fn specs() -> Vec { "New Document Presets", [], None, - "{category?: \"Recent\"|\"Saved\"|\"Mobile\"|\"Web\"|\"Print\"|\"Film & Video\"|\"Art & Illustration\"|\"Branding\"|\"Social\"} the New Document presets by category (Recent: the last sizes used; Saved: the user's presets) → {categories: [{name, presets: [{name, size: \"1920 × 1080 px\", width: pt, height: pt, units, orientation, artboards, artboardLayout: {layout, columns, spacing, rightToLeft}, bleed, backgroundContents, colorMode, rasterEffectsPpi, previewMode, alignNewObjectsToPixelGrid (on in the Mobile and Web presets)}]}]}; file.new {preset: name} starts from one", + "{category?: \"Recent\"|\"Saved\"|\"Mobile\"|\"Web\"|\"Print\"|\"Film & Video\"|\"Art & Illustration\"|\"Branding\"|\"Social\"} the New Document presets by category (Recent: the last sizes used; Saved: the user's presets) → {categories: [{name, presets: [{name, size: \"1920 × 1080 px\", width: pt, height: pt, units, orientation, artboards, artboardLayout: {layout, columns, rows? (a grid by column made with rows), spacing, rightToLeft}, bleed, backgroundContents, colorMode, rasterEffectsPpi, previewMode, alignNewObjectsToPixelGrid (on in the Mobile and Web presets)}]}]}; file.new {preset: name} starts from one", always, list ), @@ -146,6 +146,11 @@ fn de_ppi<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result bool { + *n == 0 +} + /// Everything New Document sets: a preset (built-in, saved or recent) or `file.new`'s params. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(default, rename_all = "camelCase")] @@ -166,6 +171,9 @@ pub struct DocSettings { pub layout: ArtboardLayout, /// Columns of a grid layout. pub columns: u32, + /// Rows of a grid by column, in place of `columns` when more than 0. + #[serde(skip_serializing_if = "is_zero")] + pub rows: u32, /// Space between artboards, points: 0 to `MAX_SPACING` (a saved or Recent preset's value /// outside that range is read as the nearer end). #[serde(deserialize_with = "de_spacing")] @@ -203,6 +211,7 @@ impl Default for DocSettings { artboards: 1, layout: ArtboardLayout::GridByRow, columns: 0, + rows: 0, spacing: 20.0, right_to_left: false, bleed: [0.0; 4], @@ -222,9 +231,17 @@ pub const MAX_ARTBOARDS: u32 = 1000; pub const RASTER_PPI: [(f64, &str); 3] = [(72.0, "Screen (72 ppi)"), (150.0, "Medium (150 ppi)"), (300.0, "High (300 ppi)")]; impl DocSettings { + /// The rows a grid by column with `rows` uses, at most one for each artboard. + fn grid_rows(&self) -> Option { + (self.layout == ArtboardLayout::GridByColumn && self.rows > 0).then(|| (self.rows as usize).min(self.artboards.max(1) as usize)) + } + /// The columns a grid actually uses (0 or more than the artboards: one row). pub fn grid_columns(&self) -> usize { let n = self.artboards.max(1) as usize; + if let Some(rows) = self.grid_rows() { + return n.div_ceil(rows); + } match self.layout { ArtboardLayout::Row => n, ArtboardLayout::Column => 1, @@ -246,6 +263,12 @@ impl DocSettings { /// As `file.newPresets` lists it (and `file.new` takes it back). pub fn to_json(&self) -> Value { + let mut layout = + json!({"layout": self.layout.id(), "columns": self.grid_columns(), "spacing": self.spacing, "rightToLeft": self.right_to_left}); + // The rows as set, also when there are fewer artboards than rows. + if let Some(o) = layout.as_object_mut().filter(|_| self.grid_rows().is_some()) { + o.insert("rows".into(), json!(self.rows)); + } json!({ "name": self.name, "size": self.size_label(), @@ -254,7 +277,7 @@ impl DocSettings { "units": self.units.label(), "orientation": self.orientation(), "artboards": self.artboards, - "artboardLayout": {"layout": self.layout.id(), "columns": self.grid_columns(), "spacing": self.spacing, "rightToLeft": self.right_to_left}, + "artboardLayout": layout, "bleed": self.bleed, "backgroundContents": self.background.id(), "colorMode": color_mode_id(self.color_mode), @@ -337,25 +360,23 @@ impl DocSettings { Ok(self) } - /// `artboardLayout: {layout?, columns?, spacing?, rightToLeft?}` or just a layout id. + /// `artboardLayout: {layout?, columns?, rows?, spacing?, rightToLeft?}` or just a layout id. fn layout_params(&mut self, l: &Value, cmd: &str) -> Result<()> { let bad_layout = || bad(cmd, "artboardLayout.layout must be gridByRow, gridByColumn, row or column"); if let Some(id) = l.as_str() { self.layout = ArtboardLayout::parse(id).ok_or_else(bad_layout)?; + if self.layout != ArtboardLayout::GridByColumn { + self.rows = 0; + } return Ok(()); } let o = l.as_object().ok_or_else(|| bad(cmd, "artboardLayout must be {layout?, columns?, spacing?, rightToLeft?}"))?; + let count = |v: &Value| v.as_f64().filter(|c| c.is_finite() && *c >= 1.0).map(|c| c.round().min(MAX_ARTBOARDS as f64) as u32); for (k, v) in o { match k.as_str() { "layout" => self.layout = v.as_str().and_then(ArtboardLayout::parse).ok_or_else(bad_layout)?, - "columns" => { - self.columns = v - .as_f64() - .filter(|c| c.is_finite() && *c >= 1.0) - .ok_or_else(|| bad(cmd, "artboardLayout.columns must be 1 or more"))? - .round() - .min(MAX_ARTBOARDS as f64) as u32 - } + "columns" => self.columns = count(v).ok_or_else(|| bad(cmd, "artboardLayout.columns must be 1 or more"))?, + "rows" => self.rows = count(v).ok_or_else(|| bad(cmd, "artboardLayout.rows must be 1 or more"))?, "spacing" => { self.spacing = v .as_f64() @@ -366,18 +387,30 @@ impl DocSettings { _ => return Err(bad(cmd, format!("unknown artboardLayout key `{k}` (layout, columns, spacing, rightToLeft)"))), } } + if o.contains_key("rows") && self.layout != ArtboardLayout::GridByColumn { + return Err(bad(cmd, "artboardLayout.rows needs the gridByColumn layout")); + } + // Columns without rows, or another layout, replace a preset's rows. + if (o.contains_key("columns") && !o.contains_key("rows")) || self.layout != ArtboardLayout::GridByColumn { + self.rows = 0; + } + if self.grid_rows().is_some() { + self.columns = u32::try_from(self.grid_columns()).unwrap_or(u32::MAX); + } Ok(()) } - /// The artboard rectangles, the first at the origin's side. + /// The artboard rectangles, the first at the origin's side. A grid by column with `rows` has + /// that many rows (at most one for each artboard). pub fn boards(&self) -> Vec { let n = self.artboards.max(1) as usize; let sizes = vec![(self.width, self.height); n]; let by_column = self.layout == ArtboardLayout::GridByColumn; - grid_origins(&sizes, Point::ZERO, self.grid_columns(), self.spacing, by_column, self.right_to_left) - .into_iter() - .map(|o| Rect::from_origin_size(o, (self.width, self.height))) - .collect() + let origins = match self.grid_rows() { + Some(rows) => grid_origins_rc(&sizes, Point::ZERO, (rows, n.div_ceil(rows)), self.spacing, true, self.right_to_left), + None => grid_origins(&sizes, Point::ZERO, self.grid_columns(), self.spacing, by_column, self.right_to_left), + }; + origins.into_iter().map(|o| Rect::from_origin_size(o, (self.width, self.height))).collect() } /// The new document (title and swatches set by `file.new`). @@ -528,7 +561,7 @@ pub(crate) fn side_error(cmd: &str, units: Unit) -> crate::EngineError { bad(cmd, format!("width and height must be more than 0 and at most {limit}")) } /// Largest artboard spacing, points. -const MAX_SPACING: f64 = 1.0e5; +pub(crate) const MAX_SPACING: f64 = 1.0e5; pub fn color_mode_id(m: ColorMode) -> &'static str { match m { @@ -968,20 +1001,29 @@ impl Session { /// Profile `name`'s document, its file's path and a warning for each color profile the file /// carries that can't be used: `None` when it has no file (the shipped profile, the defaults), - /// the reason when the request being served may not read it, or its file can't be read, is - /// larger than [`MAX_PROFILE_BYTES`] or isn't a native document VectorCraft reads. + /// the reason when the request being served may not read it, or its file is a link or a folder, + /// can't be read, is larger than [`MAX_PROFILE_BYTES`] or isn't a native document VectorCraft + /// reads. fn read_profile(&self, name: &str) -> std::result::Result, String> { let Some(path) = self.profile_path(name) else { return Ok(None) }; let file = path.to_string_lossy().to_string(); // Checked before the file is looked for, so a request that may not read the folder learns // nothing of its files, nor where the folder is. + // A script's gate does not apply to reads of the app's own folder; the automation roots in + // force still do. let denied = |_| PROFILE_DENIED.to_string(); - crate::file_access::check_read(&file).map_err(denied)?; - if std::fs::symlink_metadata(&path).is_err_and(|e| e.kind() == std::io::ErrorKind::NotFound) { - return Ok(None); - } - crate::file_access::check_read(&file).map_err(denied)?; - let bytes = crate::store::read_capped(&path, MAX_PROFILE_BYTES)?; + let read = crate::file_access::app_folder_read(|| { + crate::file_access::check_read(&file).map_err(denied)?; + match std::fs::symlink_metadata(&path) { + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None), + // A link is refused: the script's gate does not check where it leads. + Ok(m) if !m.file_type().is_file() => return Err("not a plain file".to_string()), + _ => {} + } + crate::file_access::check_read(&file).map_err(denied)?; + crate::store::read_capped(&path, MAX_PROFILE_BYTES).map(Some) + })?; + let Some(bytes) = read else { return Ok(None) }; // The color profiles the file carries are installed where missing, as opening it installs // them, so the new document's assigned profiles draw and are saved with it. let (mut doc, _, mut warnings) = super::fileio::decode_native_file(&bytes).map_err(|e| e.to_string())?; diff --git a/crates/engine/src/cmd/object/commands.rs b/crates/engine/src/cmd/object/commands.rs index 8ce478ad97..182dc0601f 100644 --- a/crates/engine/src/cmd/object/commands.rs +++ b/crates/engine/src/cmd/object/commands.rs @@ -34,8 +34,8 @@ pub fn specs() -> Vec { "Rotate…", ["Object", "Transform"], None, - "{ids?: [id…] (selected first; default: the selection), angle: deg (counter-clockwise), absolute?: bool (angle is the bounding box's new angle, not an amount), origin?: [x,y] (default: the bounding box centre), copy?, objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size)} → {ids}. With anchors selected with Direct Selection (and no copy), only those anchors and their handles transform, about the centre of their own box.", - has_selection, + "{ids?: [id…] (selected first; default: the selection), angle: deg (counter-clockwise), absolute?: bool (angle is the bounding box's new angle, not an amount), origin?: [x,y] (default: the bounding box centre), copy?, objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size)} → {ids}. With anchors selected with Direct Selection (and no copy), only those anchors and their handles transform, about the centre of their own box. Selected ruler guides that can be edited rotate too (without ids), each as the line view.guides.release makes of it, and the default origin is the center of the objects' box and those lines together: a guide that ends up vertical or horizontal stays a ruler guide, and one at any other angle becomes a selected guide path along its line. absolute with only ruler guides selected is an error.", + has_selection_or_guides, rotate ), cmd!( @@ -71,7 +71,7 @@ pub fn specs() -> Vec { ["Object", "Transform"], Some("Cmd+D"), "{copy?, strokes?, corners?, patterns?, typeAreas?, interpolate?: bool (as object.transform's; default: the value the transform it repeats used, else object.transform's default)} the last transform's matrix on the selection (after a perspective move or scale: that plane-space transform, without these params)", - has_selection, + has_selection_or_guides, transform_again ), cmd!( diff --git a/crates/engine/src/cmd/object/transform.rs b/crates/engine/src/cmd/object/transform.rs index 1ccd74d57f..68c681b0a5 100644 --- a/crates/engine/src/cmd/object/transform.rs +++ b/crates/engine/src/cmd/object/transform.rs @@ -16,7 +16,27 @@ fn origin_of(s: &Session, p: &Value, ids: &[NodeId]) -> Result { { return Ok(b.center()); } - s.transform_box(ids).map(|b| b.center()).ok_or_else(|| EngineError::Other("selection has no bounds".into())) + // Selected ruler guides transform with the selection (not with objects named by `ids`, nor + // with Transform Objects off), so the center is that of the objects' box and the guides' + // lines together. + let guides = if p.get("ids").is_none_or(Value::is_null) && transforms_objects(p) { editable_guides(s)? } else { vec![] }; + let boxed = s.transform_box(ids); + if guides.is_empty() { + return boxed.map(|b| b.center()).ok_or_else(|| EngineError::Other("selection has no bounds".into())); + } + let objects = boxed.map(|b| { + let c = b.corners(); + c.iter().fold(Rect::from_points(c[0], c[0]), |r, p| r.union_pt(*p)) + }); + let lines = guides.into_iter().filter_map(|g| st.doc.guide_line(&g)).map(|(a, b)| Rect::from_points(a, b)); + let b = lines.fold(objects, |acc, r| Some(acc.map_or(r, |acc| acc.union(r)))); + b.map(|b| b.center()).ok_or_else(|| EngineError::Other("selection has no bounds".into())) +} + +/// The selected ruler guides that a transform changes: those that can be edited. +fn editable_guides(s: &Session) -> Result> { + let st = s.doc()?; + Ok(st.selection.guides.iter().filter_map(|id| st.doc.ruler_guide(*id)).filter(|g| st.doc.guide_editable(g)).collect()) } /// What a transform command scales besides geometry: Scale Strokes & Effects and Scale Corners from @@ -125,8 +145,18 @@ fn apply_transform_moving_guides( let c = xf.as_coeffs(); let is_translation = (c[0] - 1.0).abs() < 1e-9 && c[1].abs() < 1e-9 && c[2].abs() < 1e-9 && (c[3] - 1.0).abs() < 1e-9; let delta = guides.unwrap_or(Vec2::new(c[4], c[5])); - let with_guides = objects && p.get("ids").is_none_or(Value::is_null) && is_translation; - let has_guides = with_guides && !s.doc()?.selection.guides.is_empty(); + // The selected ruler guides transform with the selection: a move moves them, and any other + // transform maps the line each one stands for ([`Document::transform_ruler_guides`]). + let with_guides = objects && p.get("ids").is_none_or(Value::is_null); + // A transform that leaves every guide where it is (a scale of a guide along its own line) + // changes no guide; with a copy, the guides are copied all the same. + let has_guides = with_guides && { + let d = &s.doc()?.doc; + let same = |g: &vectorcraft_doc::Guide| { + d.transformed_guide(g, xf) == Some(vectorcraft_doc::GuideTransform::Ruler { vertical: g.vertical, pos: g.pos }) + }; + editable_guides(s)?.iter().any(|g| is_translation || copy || !same(g)) + }; // A transform of ids that name no object, or an identity transform without a copy, moves // nothing: the document and its undo history stay as they are, and Transform Again repeats it. // With a copy, the reply lists the copies, and there are none. @@ -196,10 +226,12 @@ fn apply_transform_moving_guides( crate::cmd::patterncmds::move_tile_with_art(d, &targets, before); } } - if with_guides && (delta.x != 0.0 || delta.y != 0.0) { + if with_guides && is_translation && (delta.x != 0.0 || delta.y != 0.0) { for i in sel.guides.clone() { d.edit_ruler_guide(i, |g| *g = g.moved(delta)); } + } else if with_guides && !is_translation { + d.transform_ruler_guides(sel, xf); } Ok(targets) })? @@ -388,6 +420,10 @@ pub(super) fn rotate(s: &mut Session, p: &Value) -> Result { check_switches(p, &TRANSFORM_SWITCHES, "object.rotate")?; check_switches(p, &["absolute"], "object.rotate")?; let ids = selected_roots_to_transform(s)?; + // A bounding box angle is that of objects; ruler guides selected alone have none. + if bool_or(p, "absolute", false) && ids.is_empty() { + return Err(bad("object.rotate", "absolute needs objects selected: ruler guides have no bounding box angle")); + } let o = origin_of(s, p, &ids)?; let mut angle = f64_or(p, "angle", 0.0); if bool_or(p, "absolute", false) { diff --git a/crates/engine/src/cmd/paint.rs b/crates/engine/src/cmd/paint.rs index b09bc04d4b..25ca3a60ca 100644 --- a/crates/engine/src/cmd/paint.rs +++ b/crates/engine/src/cmd/paint.rs @@ -20,6 +20,21 @@ use crate::{DocState, EngineError}; /// object in particular is the color it paints with ([`apply_paint`]). pub(crate) const LIVE_PAINT_BUCKET: &str = "livePaintBucket"; +/// The Shape Builder's tool id. While it is active, a fill chosen for no object in particular is +/// the current fill only, which merges fill with when Pick Color From is Color Swatches; a stroke +/// chosen then still paints the selection. +const SHAPE_BUILDER: &str = "shapeBuilder"; + +/// Tool `id`'s id when it paints with the fill (or the stroke, `stroke`) chosen while it is +/// active: the Live Paint Bucket with both, the Shape Builder with the fill. +pub(crate) fn painting_tool_of(id: &str, stroke: bool) -> Option<&'static str> { + match id { + LIVE_PAINT_BUCKET => Some(LIVE_PAINT_BUCKET), + SHAPE_BUILDER if !stroke => Some(SHAPE_BUILDER), + _ => None, + } +} + pub fn specs() -> Vec { vec![ cmd!( @@ -27,7 +42,7 @@ pub fn specs() -> Vec { "Fill", [], None, - "{color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}|{l,a,b} (CIE Lab; #rrggbbaa and #rgba are refused), none?: true, swatch?: name (a global or spot colour stays linked, so swatch edits recolour it; a tint swatch links to its base at its tint; a gradient swatch is recorded as the gradient's swatch and fits each object, keeping its aspect; the built-in \"[Registration]\" prints on every plate), tint?: 0..100 (% of a global or spot `swatch`; default 100, or a tint swatch's own), gradient?: {kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical: the stops sweep once around the center `start`, clockwise from the vector; diamond: the stops run from the center `start` out to a square with a corner at `end`), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (as paint.editGradient; default classic), spread?: pad|repeat|reflect (as paint.editGradient; default pad), repeats?: 1..100 (as paint.editGradient; default 1), stops?: [{offset 0..1, color, opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: global or spot colour (or tint) swatch the stop links to (its colour comes from the swatch), tint?: 0..100}] (at least 2; default white→black), angle?: deg counter-clockwise (0: the gradient runs left to right), start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep, counterclockwise, and is an error for the other kinds; without start/end the gradient is placed on each object's bounds), focal?: [x,y] (radial, with start/end: the focal point, where the first stop sits; an error with a conic or diamond), dither?: bool (linear, radial, conic and diamond fills: drawn with fine noise that hides banding, and as pixels in SVG and PDF exports; strokes ignore it), swatch?: linked gradient swatch name}, item?: appearance item index|null (omitted: the Appearance panel's active item if it is a fill, else the top fill), aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md), opacity?: 0..100 (a percentage, as transparency.set's; the opacity of that fill item on each target, in the undo step of the paint, or alone without color, none, swatch or gradient, when it changes neither the defaults nor the recent colors (with New Art Has Basic Appearance off, the next shape copies the first selected object's appearance after any command, its opacity included); with no paint or a solid color, the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso take it themselves, and with another paint the fill item takes it; with no paint, a target without that fill item is left as it is (a paint given with the opacity creates the item, which then takes it, except for the color a grayscale or 1-bit image is drawn in, which creates none), and an opacity that no target takes is an error that also leaves the paint undone; type characters have no opacity of their own, so an opacity that only characters would take is an error, and so are one with nothing selected and no ids and one for an object selected in a symbol instance), ids?|id?, defaultsOnly?: bool, focus?: true (false keeps the active proxy), keepModel?: false (in a CMYK document, RGB colours and gradient stops are stored as CMYK unless true; Gray stays Gray), target?: \"object\"|\"contents\", span?: \"object\" (default: each target fits a gradient to its own bounds)|\"selection\" (a linear, radial, conic or diamond `gradient` without start/end is placed once on the union of the targets' bounds, so it runs across them)} sets the selection's fill and the default (new art fits a gradient to itself); a solid color recolors only the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso (unless an `item` index is given or the Appearance panel's active item is a fill); while the Type tool has characters selected (and no ids, id or item are given), the paint goes to those characters only; without `item`, a Live Paint group among the targets (or inside one) takes the fill on its faces only; without `item`, a grayscale or 1-bit image takes a solid color as the color it is drawn in (white pixels transparent; `none` takes it off; an image with an alpha channel takes only a spot color, black or white; a colorized image whose link is missing takes a solid color as its new colorize color, and refuses a process color while its color is a spot color, black or white); with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's fill changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint of the topmost visible fill when the command wrote that row or changed it, and its opacity when `opacity` changed it (exceptions: docs/mcp.md); on a graph label, the graph stores the paint for every label of its kind, as a character fill when the characters took it and with the label's rows when a row did; on a graph's axis line, tick mark or radar ring, its rows for every line of its kind. While the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), or `defaultsOnly: true` is given, only the default changes (the color the bucket paints with) and the selection keeps its paint; `defaultsOnly` with ids, id or item is refused, and the journal records a change the bucket made this way with `defaultsOnly: true`, so a replay with another tool active changes the default too → {objects: how many objects took the paint (the objects inside a group, unless an appearance item of the group's own is targeted; 0 when only the default changed)}", + "{color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}|{l,a,b} (CIE Lab; #rrggbbaa and #rgba are refused), none?: true, swatch?: name (a global or spot colour stays linked, so swatch edits recolour it; a tint swatch links to its base at its tint; a gradient swatch is recorded as the gradient's swatch and fits each object, keeping its aspect; the built-in \"[Registration]\" prints on every plate), tint?: 0..100 (% of a global or spot `swatch`; default 100, or a tint swatch's own), gradient?: {kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical: the stops sweep once around the center `start`, clockwise from the vector; diamond: the stops run from the center `start` out to a square with a corner at `end`), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (as paint.editGradient; default classic), spread?: pad|repeat|reflect (as paint.editGradient; default pad), repeats?: 1..100 (as paint.editGradient; default 1), stops?: [{offset 0..1, color, opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: global or spot colour (or tint) swatch the stop links to (its colour comes from the swatch), tint?: 0..100}] (at least 2; default white→black), angle?: deg counter-clockwise (0: the gradient runs left to right), start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep, counterclockwise, and is an error for the other kinds; without start/end the gradient is placed on each object's bounds), focal?: [x,y] (radial, with start/end: the focal point, where the first stop sits; an error with a conic or diamond), dither?: bool (linear, radial, conic and diamond fills: drawn with fine noise that hides banding, and as pixels in SVG and PDF exports; strokes ignore it), swatch?: linked gradient swatch name}, item?: appearance item index|null (omitted: the Appearance panel's active item if it is a fill, else the top fill), aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md), opacity?: 0..100 (a percentage, as transparency.set's; the opacity of that fill item on each target, in the undo step of the paint, or alone without color, none, swatch or gradient, when it changes neither the defaults nor the recent colors (with New Art Has Basic Appearance off, the next shape copies the first selected object's appearance after any command, its opacity included); with no paint or a solid color, the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso take it themselves, and with another paint the fill item takes it; with no paint, a target without that fill item is left as it is (a paint given with the opacity creates the item, which then takes it, except for the color a grayscale or 1-bit image is drawn in, which creates none), and an opacity that no target takes is an error that also leaves the paint undone; type characters have no opacity of their own, so an opacity that only characters would take is an error, and so are one with nothing selected and no ids and one for an object selected in a symbol instance), ids?|id?, defaultsOnly?: bool, focus?: true (false keeps the active proxy), keepModel?: false (in a CMYK document, RGB colours and gradient stops are stored as CMYK unless true; Gray stays Gray), target?: \"object\"|\"contents\", span?: \"object\" (default: each target fits a gradient to its own bounds)|\"selection\" (a linear, radial, conic or diamond `gradient` without start/end is placed once on the union of the targets' bounds, so it runs across them)} sets the selection's fill and the default (new art fits a gradient to itself); a solid color recolors only the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso (unless an `item` index is given or the Appearance panel's active item is a fill); while the Type tool has characters selected (and no ids, id or item are given), the paint goes to those characters only; without `item`, a Live Paint group among the targets (or inside one) takes the fill on its faces only; without `item`, a grayscale or 1-bit image takes a solid color as the color it is drawn in (white pixels transparent; `none` takes it off; an image with an alpha channel takes only a spot color, black or white; a colorized image whose link is missing takes a solid color as its new colorize color, and refuses a process color while its color is a spot color, black or white); with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's fill changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint of the topmost visible fill when the command wrote that row or changed it, and its opacity when `opacity` changed it (exceptions: docs/mcp.md); on a graph label, the graph stores the paint for every label of its kind, as a character fill when the characters took it and with the label's rows when a row did; on a graph's axis line, tick mark or radar ring, its rows for every line of its kind. While the Live Paint Bucket or the Shape Builder is the active tool and no ids, id or item are given (a null ids or id counts as none), or `defaultsOnly: true` is given, only the default changes (the color the bucket paints with, and the fill the Shape Builder's merges take with Pick Color From Color Swatches) and the selection keeps its paint; `defaultsOnly` with ids, id or item is refused, and the journal records a change either tool made this way with `defaultsOnly: true`, so a replay with another tool active changes the default too → {objects: how many objects took the paint (the objects inside a group, unless an appearance item of the group's own is targeted; 0 when only the default changed)}", has_doc, |s, p| set_paint(s, p, true) ), @@ -36,7 +51,7 @@ pub fn specs() -> Vec { "Stroke", [], None, - "{…as paint.setFill, item?: the stroke item to set, aligned?: bool (as paint.setFill), opacity?: 0..100 (the opacity of that stroke item, as paint.setFill's for the fill item)} same as paint.setFill, for the stroke; without `item`, a Live Paint group among the targets (or inside one) takes the stroke on its edges only; with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's stroke changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint and weight of the topmost visible stroke when the command wrote that row or changed it, and its opacity when `opacity` changed it (exceptions: docs/mcp.md); on a graph label, as paint.setFill", + "{…as paint.setFill, item?: the stroke item to set, aligned?: bool (as paint.setFill), opacity?: 0..100 (the opacity of that stroke item, as paint.setFill's for the fill item)} same as paint.setFill, for the stroke (while the Shape Builder is the active tool, the selection still takes the stroke); without `item`, a Live Paint group among the targets (or inside one) takes the stroke on its edges only; with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's stroke changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint and weight of the topmost visible stroke when the command wrote that row or changed it, and its opacity when `opacity` changed it (exceptions: docs/mcp.md); on a graph label, as paint.setFill", has_doc, |s, p| { set_paint(s, p, false) } ), @@ -45,7 +60,7 @@ pub fn specs() -> Vec { "Swap Fill and Stroke", [], Some("Shift+X"), - "{ids?|id?, defaultsOnly?: bool} swap the fill and stroke of the selection (type too) and of the defaults. A Live Paint group's faces take the stroke its edges share and its edges take the fill its faces share, a gradient fitted to each face or edge; a group whose faces' fills or edges' strokes differ (a freeform gradient counts as differing), or that has no face or no edge, keeps its paint. On a path directly in a graph series, the graph also stores the swapped paints and the stroke weight, and on a graph label the swapped paints of its characters for every label of its kind, and on a graph's axis line, tick mark or radar ring what the swap changes on its rows for every line of its kind (exceptions: docs/mcp.md). While the Live Paint Bucket is the active tool and no ids or id are given (a null one counts as none), or `defaultsOnly: true` is given, only the defaults change", + "{ids?|id?, defaultsOnly?: bool} swap the fill and stroke of the selection (type too) and of the defaults. A Live Paint group's faces take the stroke its edges share and its edges take the fill its faces share, a gradient fitted to each face or edge; a group whose faces' fills or edges' strokes differ (a freeform gradient counts as differing), or that has no face or no edge, keeps its paint. On a path directly in a graph series, the graph also stores the swapped paints and the stroke weight, and on a graph label the swapped paints of its characters for every label of its kind, and on a graph's axis line, tick mark or radar ring what the swap changes on its rows for every line of its kind (exceptions: docs/mcp.md). While the Live Paint Bucket or the Shape Builder is the active tool and no ids or id are given (a null one counts as none), or `defaultsOnly: true` is given, only the defaults change (with the Shape Builder, the default fill takes the stroke the Stroke proxy shows, the selection's)", has_doc, swap ), @@ -54,7 +69,7 @@ pub fn specs() -> Vec { "Default Fill and Stroke", [], Some("D"), - "{ids?|id?, defaultsOnly?: bool} white fill and 1 pt black stroke for the selection and the defaults (in a document whose Default Graphic Style differs from the shipped one, as a New Document profile can redefine it: that style's fills, strokes and effects, without its opacity or a link to it); type gets black fill and no stroke. A Live Paint group's faces get no fill and its edges get a 0.5 pt black stroke, in place of their whole appearance and also when the Default Graphic Style is redefined, and with only Live Paint groups selected (or in ids) the defaults become no fill and a 0.5 pt black stroke (with New Art Has Basic Appearance off, new art then takes the selection's appearance, as after any command). On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke, and on a graph label the black fill and no stroke of its characters for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (exceptions: docs/mcp.md). While the Live Paint Bucket is the active tool and no ids or id are given (a null one counts as none), or `defaultsOnly: true` is given, only the defaults change", + "{ids?|id?, defaultsOnly?: bool} white fill and 1 pt black stroke for the selection and the defaults (in a document whose Default Graphic Style differs from the shipped one, as a New Document profile can redefine it: that style's fills, strokes and effects, without its opacity or a link to it); type gets black fill and no stroke. A Live Paint group's faces get no fill and its edges get a 0.5 pt black stroke, in place of their whole appearance and also when the Default Graphic Style is redefined, and with only Live Paint groups selected (or in ids) the defaults become no fill and a 0.5 pt black stroke (with New Art Has Basic Appearance off, new art then takes the selection's appearance, as after any command). On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke, and on a graph label the black fill and no stroke of its characters for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (exceptions: docs/mcp.md). While the Live Paint Bucket or the Shape Builder is the active tool and no ids or id are given (a null one counts as none), or `defaultsOnly: true` is given, only the defaults change", has_doc, default_paint ), @@ -75,7 +90,7 @@ pub fn specs() -> Vec { "None", [], Some("/"), - "{defaultsOnly?: bool} set the active proxy (fill or stroke) to None, as paint.setFill or paint.setStroke with none does (while the Live Paint Bucket is the active tool, or with `defaultsOnly: true`, only the default changes) → {objects}", + "{defaultsOnly?: bool} set the active proxy (fill or stroke) to None, as paint.setFill or paint.setStroke with none does (while the Live Paint Bucket, or for a fill the Shape Builder, is the active tool, or with `defaultsOnly: true`, only the default changes) → {objects}", has_doc, |s, p| { let f = s.fill_active; @@ -103,7 +118,7 @@ pub fn proxy_specs() -> Vec { "Invert", [], None, - "{stroke?: bool (default: the active proxy), ids?|id?, defaultsOnly?: bool, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} invert the active proxy's colours of the selection (or ids; groups recolour their contents and, except with target \"contents\", their own fills and strokes; a compound path's member stands for its compound path; a Live Paint group recolors its faces' fills or its edges' strokes) keeping each colour's model, as edit.colors.invert does; the Appearance panel's active fill/stroke item (appearance.setActiveItem) is inverted instead when it is of that kind and no ids are given; with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's solid color changes for this instance only, and a gradient or pattern, or type whose characters differ in color, is refused; with nothing selected, or while the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), or `defaultsOnly: true` is given, invert the default. On a path directly in a graph series, the graph also stores the new color of the topmost visible fill or stroke, and on a graph label the new color of its characters and rows for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (docs/mcp.md); no undo step when no color changes → {changed}", + "{stroke?: bool (default: the active proxy), ids?|id?, defaultsOnly?: bool, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} invert the active proxy's colours of the selection (or ids; groups recolour their contents and, except with target \"contents\", their own fills and strokes; a compound path's member stands for its compound path; a Live Paint group recolors its faces' fills or its edges' strokes) keeping each colour's model, as edit.colors.invert does; the Appearance panel's active fill/stroke item (appearance.setActiveItem) is inverted instead when it is of that kind and no ids are given; with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's solid color changes for this instance only, and a gradient or pattern, or type whose characters differ in color, is refused; with nothing selected, or while the Live Paint Bucket, or for a fill the Shape Builder, is the active tool and no ids, id or item are given (a null ids or id counts as none), or `defaultsOnly: true` is given, invert the default. On a path directly in a graph series, the graph also stores the new color of the topmost visible fill or stroke, and on a graph label the new color of its characters and rows for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (docs/mcp.md); no undo step when no color changes → {changed}", has_doc, |s, p| proxy_recolor(s, p, "paint.invert", "Invert", &super::colorcmds::invert) ), @@ -112,7 +127,7 @@ pub fn proxy_specs() -> Vec { "Complement", [], None, - "{stroke?: bool (default: the active proxy), ids?|id?, defaultsOnly?: bool, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} replace the active proxy's colours by their complements ((highest + lowest) − each component, over RGB or CMY; grey unchanged) keeping each colour's model; a Live Paint group recolors its faces' fills or its edges' strokes as with paint.invert; honours the Appearance panel's active item and a selected object of a dynamic symbol instance as paint.invert does; with nothing selected, or while the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), or `defaultsOnly: true` is given, the default; no undo step when no color changes → {changed}", + "{stroke?: bool (default: the active proxy), ids?|id?, defaultsOnly?: bool, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} replace the active proxy's colours by their complements ((highest + lowest) − each component, over RGB or CMY; grey unchanged) keeping each colour's model; a Live Paint group recolors its faces' fills or its edges' strokes as with paint.invert; honours the Appearance panel's active item and a selected object of a dynamic symbol instance as paint.invert does; with nothing selected, or while the Live Paint Bucket, or for a fill the Shape Builder, is the active tool and no ids, id or item are given (a null ids or id counts as none), or `defaultsOnly: true` is given, the default; no undo step when no color changes → {changed}", has_doc, |s, p| proxy_recolor(s, p, "paint.complement", "Complement", &|c: Color| c.complement_keep_model()) ), @@ -121,7 +136,7 @@ pub fn proxy_specs() -> Vec { "Apply Last Color", [], Some(","), - "{stroke?: bool (default: the active proxy), ids?|id?, defaultsOnly?: bool, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} apply the last solid colour used (paint.recent lastColor) to the active proxy of the selection and the default (while the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), or `defaultsOnly: true` is given, to the default only) → {objects} (as paint.setFill)", + "{stroke?: bool (default: the active proxy), ids?|id?, defaultsOnly?: bool, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} apply the last solid colour used (paint.recent lastColor) to the active proxy of the selection and the default (while the Live Paint Bucket, or for a fill the Shape Builder, is the active tool and no ids, id or item are given (a null ids or id counts as none), or `defaultsOnly: true` is given, to the default only) → {objects} (as paint.setFill)", has_doc, |s, p| { let paint = Paint::solid(s.last_solid); @@ -133,7 +148,7 @@ pub fn proxy_specs() -> Vec { "Apply Last Gradient", [], Some("."), - "{stroke?: bool (default: the active proxy), ids?|id?, defaultsOnly?: bool, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} apply the last gradient used (paint.recent lastGradient), fitted to each object, to the active proxy of the selection and the default (while the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), or `defaultsOnly: true` is given, to the default only) → {objects} (as paint.setFill)", + "{stroke?: bool (default: the active proxy), ids?|id?, defaultsOnly?: bool, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} apply the last gradient used (paint.recent lastGradient), fitted to each object, to the active proxy of the selection and the default (while the Live Paint Bucket, or for a fill the Shape Builder, is the active tool and no ids, id or item are given (a null ids or id counts as none), or `defaultsOnly: true` is given, to the default only) → {objects} (as paint.setFill)", has_doc, |s, p| { let paint = super::gradient::unplaced(&Paint::Gradient(Box::new(s.last_gradient.clone()))); @@ -161,7 +176,7 @@ pub fn proxy_specs() -> Vec { "Fill and Stroke", [], None, - "{} → {fill, stroke: the paints the Fill/Stroke proxies show (the Appearance panel's active item for the proxy of its kind, else the first selected object's, a group's first painted object's, a Live Paint group's first face's fill and first edge's stroke, type: its first run's; else the defaults for new art; when that object is a gradient mesh with points picked by the Mesh tool, Direct Selection or the Lasso and no fill item is active, the fill is its first picked point's color), fillActive, fillMixed, strokeMixed: the selected objects' (or a selected group's contents') fills (strokes) differ, a Live Paint group counting with its faces' fills and its edges' strokes, shown as a \"?\" proxy (a gradient mesh with points picked counts with their colors), fillOpacity, strokeOpacity: 0..100, the opacity of the fill item that paint.setFill {opacity} sets (the stroke item that paint.setStroke {opacity} sets), from the first selected object (or painted object in a selected group; a selected path of a compound path stands for its compound, and a Live Paint group for its faces' fills and its edges' strokes) that has one (a gradient mesh's first picked point's), or null with nothing selected (the defaults for new art), for an object selected in a symbol instance, while the Live Paint Bucket is the active tool, while the Type tool has characters selected, and when only type characters or objects without that item are selected}", + "{} → {fill, stroke: the paints the Fill/Stroke proxies show (the Appearance panel's active item for the proxy of its kind, else the first selected object's, a group's first painted object's, a Live Paint group's first face's fill and first edge's stroke, type: its first run's; else the defaults for new art; when that object is a gradient mesh with points picked by the Mesh tool, Direct Selection or the Lasso and no fill item is active, the fill is its first picked point's color), fillActive, fillMixed, strokeMixed: the selected objects' (or a selected group's contents') fills (strokes) differ, a Live Paint group counting with its faces' fills and its edges' strokes, shown as a \"?\" proxy (a gradient mesh with points picked counts with their colors), fillOpacity, strokeOpacity: 0..100, the opacity of the fill item that paint.setFill {opacity} sets (the stroke item that paint.setStroke {opacity} sets), from the first selected object (or painted object in a selected group; a selected path of a compound path stands for its compound, and a Live Paint group for its faces' fills and its edges' strokes) that has one (a gradient mesh's first picked point's), or null with nothing selected (the defaults for new art), for an object selected in a symbol instance, while the Live Paint Bucket is the active tool (for fillOpacity, also the Shape Builder), while the Type tool has characters selected, and when only type characters or objects without that item are selected}", always, proxies ), @@ -204,11 +219,11 @@ impl Session { /// The object whose fill (or stroke) the proxy shows, with the Appearance panel's active item /// when it stands for it (see [`Session::proxy_paints`]); None: the defaults for new art. With /// an object of a dynamic symbol instance selected ([`DocState::selected_symbol_part`]), that - /// object as the instance draws it. None while the Live Paint Bucket is the active tool (or - /// another tool works for it, [`Session::bucket_paints`]): the proxies show the colors it - /// paints with. + /// object as the instance draws it. None while the active tool paints with the chosen fill (or + /// stroke), or another tool works for it ([`Session::tool_paints`]): the proxy shows the color + /// it paints with. pub(crate) fn proxy_source(&self, stroke: bool) -> Option<(Cow<'_, Node>, Option)> { - if self.bucket_paints() { + if self.tool_paints(stroke) { return None; } let st = self.active()?; @@ -243,16 +258,16 @@ impl Session { /// `paint.setStroke {opacity}` sets): the item's, or for a gradient mesh with points picked the /// first picked point's. The rows the command would edit are read in order (a group without an /// active Appearance row stands for its contents), and the first that exists answers. `None` - /// with nothing selected, for an object selected in a symbol instance, while the Live Paint - /// Bucket is the active tool (or another tool works for it, [`Session::bucket_paints`]), while + /// with nothing selected, for an object selected in a symbol instance, while the active tool + /// paints with the chosen fill (or stroke), or another tool works for it ([`Session::tool_paints`]), while /// the Type tool has characters selected, and when only type /// characters, objects without that item or the art of graph designs in a graph series are /// selected. pub fn proxy_opacity(&self, stroke: bool) -> Option { let st = self.active()?; - // The Live Paint Bucket takes a fill or stroke chosen as the color it paints with, and the - // selection keeps its own (for_bucket). - if st.selection.symbol_part.is_some() || self.bucket_paints() { + // Such a tool takes a fill or stroke chosen as the color it paints with, and the selection + // keeps its own (for_tool). + if st.selection.symbol_part.is_some() || self.tool_paints(stroke) { return None; } // The command would give the opacity to the characters, which have none of their own. @@ -516,25 +531,40 @@ impl DocState { } } -/// Is `t` the Live Paint Bucket, or a tool armed to switch back to it after its pick? -fn works_for_bucket(t: &dyn vectorcraft_tools::Tool) -> bool { - t.id() == LIVE_PAINT_BUCKET || t.returns_to() == Some(LIVE_PAINT_BUCKET) +/// The id of tool `t`, or of the tool its armed pick switches back to, when that tool paints with +/// the chosen fill or stroke ([`painting_tool_of`]). +fn painter_of(t: &dyn vectorcraft_tools::Tool) -> Option<&'static str> { + let of = |id: &str| painting_tool_of(id, false).or_else(|| painting_tool_of(id, true)); + of(t.id()).or_else(|| t.returns_to().and_then(of)) } impl Session { - /// Did the Live Paint Bucket, or the Eyedropper armed for it, lend the active tool (a Cmd+click)? - pub(crate) fn lent_by_bucket(&self) -> bool { - self.lender.as_deref().is_some_and(works_for_bucket) + /// The tool that lent the active tool (a Cmd+click) when it paints with the chosen colors, or + /// the Eyedropper armed for such a tool did ([`painter_of`]). + pub(crate) fn lent_by_painter(&self) -> Option<&'static str> { + self.lender.as_deref().and_then(painter_of) } - /// Do the fill and stroke proxies, and the paint commands that name no objects, stand for the - /// colors the Live Paint Bucket paints with? They do while the bucket is the active tool, while - /// a Cmd+click with the bucket uses the Selection tool, and while the Eyedropper samples into a - /// stop of the bucket's gradient for the Gradient panel's eyedropper, up to and including the - /// sample its click takes before it switches back to the bucket. - pub fn bucket_paints(&self) -> bool { - // A Cmd+click lends the Selection tool to the bucket, or to the Eyedropper armed for it. - self.back_to_bucket || works_for_bucket(self.tool.as_ref()) || self.lent_by_bucket() + /// Do the fill proxy (the stroke proxy, with `stroke`), and the fill (stroke) commands that + /// name no objects, stand for the color the active tool paints with ([`painting_tool_of`]: the + /// Live Paint Bucket's fill and stroke, the Shape Builder's fill)? They do while such a tool is + /// active, while a Cmd+click with it uses the Selection tool, and while the Eyedropper samples + /// into a stop of its gradient for the Gradient panel's eyedropper, up to and including the + /// sample its click takes before it switches back to that tool. + pub fn tool_paints(&self, stroke: bool) -> bool { + self.painting_tool(stroke).is_some() + } + + /// The id of the tool whose fill (or stroke, `stroke`) the proxy stands for + /// ([`Session::tool_paints`]); None when it stands for the selection's. + pub(crate) fn painting_tool(&self, stroke: bool) -> Option<&'static str> { + let of = + |t: &dyn vectorcraft_tools::Tool| painting_tool_of(t.id(), stroke).or_else(|| t.returns_to().and_then(|id| painting_tool_of(id, stroke))); + // A Cmd+click lends the Selection tool to such a tool, or to the Eyedropper armed for it. + self.back_to_painter + .and_then(|id| painting_tool_of(id, stroke)) + .or_else(|| of(self.tool.as_ref())) + .or_else(|| self.lender.as_deref().and_then(of)) } /// The tool the active tool's armed one-shot pick switches back to after its click @@ -545,12 +575,14 @@ impl Session { /// [`DocState::proxy_mixed`] of the active document for the Appearance panel's active item. /// A gradient mesh with points picked ([`Session::fill_mesh_points`]) counts with their colors. - /// Neither is mixed while the Live Paint Bucket is the active tool ([`Session::proxy_source`]). + /// A proxy that stands for the color the active tool paints with ([`Session::tool_paints`]) is + /// not mixed ([`Session::proxy_source`]). pub fn proxy_mixed(&self) -> (bool, bool) { - if self.bucket_paints() { + if self.tool_paints(false) && self.tool_paints(true) { return (false, false); } - self.active().map_or((false, false), |st| st.proxy_mixed_with(self.appearance_item(), &self.fill_mesh_points())) + let (fill, stroke) = self.active().map_or((false, false), |st| st.proxy_mixed_with(self.appearance_item(), &self.fill_mesh_points())); + (fill && !self.tool_paints(false), stroke && !self.tool_paints(true)) } } @@ -735,8 +767,8 @@ pub(crate) fn apply_paint(s: &mut Session, p: &Value, paint: Paint, fill: bool) /// characters, to an object selected in a symbol instance, or to no target at all is an error. fn apply_paint_opacity(s: &mut Session, p: &Value, paint: Option, opacity: Option, fill: bool) -> Result { let cmd = if fill { "paint.setFill" } else { "paint.setStroke" }; - let bucket = bucket_color_params(s, p, cmd)?; - let p = bucket.as_ref().unwrap_or(p); + let for_tool = tool_color_params(s, p, cmd, !fill)?; + let p = for_tool.as_ref().unwrap_or(p); let focus = switch_or(p, "focus", true, cmd)?; // An opacity alone places no gradient, so `span` may only be "object" with it. let span = spans_targets(p, paint.as_ref().unwrap_or(&Paint::None)).map_err(|e| bad(cmd, e))?; @@ -1033,12 +1065,13 @@ fn names_no_target(p: &Value) -> bool { ["ids", "id"].iter().all(|k| p.get(k).is_none_or(Value::is_null)) && p.get("item").is_none() } -/// Is the Live Paint Bucket the active tool ([`Session::bucket_paints`]), or does `p` give +/// Does the active tool paint with the chosen fill (or stroke, `stroke`: [`Session::tool_paints`], +/// the Live Paint Bucket's fill and stroke, the Shape Builder's fill), or does `p` give /// `defaultsOnly: true`, while `p` names no `ids`, `id` or `item`? A fill, stroke or stroke weight -/// chosen then is what the bucket paints with, so it goes to the defaults and the selection keeps -/// its paint. -pub(crate) fn for_bucket(s: &Session, p: &Value) -> bool { - names_no_target(p) && (s.bucket_paints() || asks_defaults_only(p)) +/// of that kind chosen then is what the tool paints with, so it goes to the defaults and the +/// selection keeps its paint. +pub(crate) fn for_tool(s: &Session, p: &Value, stroke: bool) -> bool { + names_no_target(p) && (s.tool_paints(stroke) || asks_defaults_only(p)) } /// Does `p` give `defaultsOnly: true`? @@ -1046,17 +1079,18 @@ pub(crate) fn asks_defaults_only(p: &Value) -> bool { p.get("defaultsOnly") == Some(&Value::Bool(true)) } -/// `p` with `ids: []` (and without `defaultsOnly`) when [`for_bucket`]: the paint goes to the -/// defaults only. None otherwise. A bad `target` or `aligned` is refused first, as it is without -/// the bucket, and so is a `defaultsOnly` that is not a bool or comes with `ids`, `id` or `item`. -/// When the bucket routed the command, the journal entry notes `defaultsOnly: true`, so replaying -/// it with another tool active changes the defaults only as well. -pub(crate) fn bucket_color_params(s: &mut Session, p: &Value, cmd: &str) -> Result> { +/// `p` with `ids: []` (and without `defaultsOnly`) when [`for_tool`] for the fill (or stroke, +/// `stroke`): the paint goes to the defaults only. None otherwise. A bad `target` or `aligned` is +/// refused first, as it is when the selection takes the paint, and so is a `defaultsOnly` that is +/// not a bool or comes with `ids`, `id` or `item`. When the active tool routed the command, the +/// journal entry notes `defaultsOnly: true`, so replaying it with another tool active changes the +/// defaults only as well. +pub(crate) fn tool_color_params(s: &mut Session, p: &Value, cmd: &str, stroke: bool) -> Result> { let only = switch_or(p, "defaultsOnly", false, cmd)?; if only && !names_no_target(p) { return Err(bad(cmd, "`defaultsOnly` cannot be combined with `ids`, `id` or `item`")); } - if !for_bucket(s, p) { + if !for_tool(s, p, stroke) { return Ok(None); } super::appearance::aligned(p, cmd)?; @@ -1071,28 +1105,62 @@ pub(crate) fn bucket_color_params(s: &mut Session, p: &Value, cmd: &str) -> Resu Ok(Some(Value::Object(v))) } -/// Whether the paint commands that `cmd` runs with params of its own change only the defaults: -/// `p` gives `defaultsOnly: true`, or the Live Paint Bucket paints ([`Session::bucket_paints`]), -/// which the journal entry of `cmd` notes for a replay. -pub(crate) fn defaults_only(s: &mut Session, p: &Value, cmd: &str) -> Result { +/// The kind of gradient `p` of a gradient command (`cmd`) edits when the active tool can paint +/// with it: the kind `stroke` names, else the proxy in front's when the tool paints with it, else +/// the kind `p` edits on the selection (the Appearance panel's active row's). +pub(crate) fn tool_gradient_kind(s: &Session, p: &Value, cmd: &str) -> Result { + check_switches(p, &["stroke"], cmd)?; + // A tool that paints with both kinds (the Live Paint Bucket), or with neither, needs no kind. + Ok(if s.tool_paints(false) == s.tool_paints(true) || p.get("stroke").is_some_and(Value::is_boolean) { + p.get("stroke").and_then(Value::as_bool).unwrap_or(!s.fill_active) + } else if s.tool_paints(!s.fill_active) { + !s.fill_active + } else { + // A null `ids` or `id` names no target, as `for_tool` reads it. + let mut q = p.clone(); + if let Some(o) = q.as_object_mut() { + o.retain(|k, v| !(matches!(k.as_str(), "ids" | "id") && v.is_null())); + } + super::appearance::edits_stroke(s, &q, item_target(s, &q, cmd)?, !s.fill_active, cmd)? + }) +} + +/// [`tool_color_params`] for `paint.editGradient` or `gradient.presets.apply` (`cmd`), for the kind +/// [`tool_gradient_kind`] gives. The params name that kind as their `stroke` when `p` gives none, +/// since the selection's Appearance row no longer picks it. +pub(crate) fn tool_gradient_params(s: &mut Session, p: &Value, cmd: &str) -> Result> { + let stroke = tool_gradient_kind(s, p, cmd)?; + Ok(tool_color_params(s, p, cmd, stroke)?.map(|mut v| { + if p.get("stroke").is_none_or(Value::is_null) { + v["stroke"] = json!(stroke); + } + v + })) +} + +/// Whether the paint commands that `cmd` runs with params of its own for the fill (or the stroke, +/// `stroke`) change only the defaults: `p` gives `defaultsOnly: true`, or the active tool paints +/// with that kind ([`Session::tool_paints`]), which the journal entry of `cmd` notes for a replay. +pub(crate) fn defaults_only(s: &mut Session, p: &Value, cmd: &str, stroke: bool) -> Result { if switch_or(p, "defaultsOnly", false, cmd)? { s.note_defaults_only(); return Ok(true); } - let bucket = s.bucket_paints(); - if bucket { + let tool = s.tool_paints(stroke); + if tool { s.note_journal("defaultsOnly", json!(true)); s.note_defaults_only(); } - Ok(bucket) + Ok(tool) } impl Session { /// Note that the running command changed only the paint defaults, with the appearance new art /// takes from the selection now ([`Session::inherit_new_art`]). No appearance is captured - /// while inheritance does not run (New Art Has Basic Appearance on, or the bucket painting). + /// while inheritance does not run (New Art Has Basic Appearance on, or the active tool painting + /// with both the fill and the stroke). fn note_defaults_only(&mut self) { - let inherits = !self.prefs.new_art_basic && !self.bucket_paints(); + let inherits = !self.prefs.new_art_basic && !(self.tool_paints(false) && self.tool_paints(true)); self.defaults_only_ran = Some(if inherits { self.new_art_source() } else { None }); } } @@ -1534,8 +1602,17 @@ fn shared_paint(d: &Document, parts: &[NodeId], fill: bool) -> Option { } fn swap(s: &mut Session, p: &Value) -> Result { - let bucket = bucket_color_params(s, p, "paint.swap")?; - let p = bucket.as_ref().unwrap_or(p); + // The swap changes a fill, so it goes to the defaults only while the active tool paints with the chosen fill. + let for_tool = tool_color_params(s, p, "paint.swap", false)?; + let p = for_tool.as_ref().unwrap_or(p); + // A tool that paints with the fill only (the Shape Builder): the Stroke proxy shows the + // selection's stroke, which the current fill takes unless the proxy shows mixed strokes. With + // nothing selected it shows the stroke for new art, which the swap moves as it is. + // A swap with `defaultsOnly` and no such tool swaps the defaults alone. + let fill_only = s.tool_paints(false) && !s.tool_paints(true); + let shown_stroke = (for_tool.is_some() && fill_only && !s.proxy_mixed().1) + .then(|| s.proxy_source(true).map(|(n, item)| super::gradient::unplaced(&proxy_paint(&n, true, item)))) + .flatten(); let targets = paint_targets(s, p)?; let given = !targets.is_empty(); // A whole Live Paint group: its faces take the stroke its edges share and its edges the fill its faces share. @@ -1599,6 +1676,9 @@ fn swap(s: &mut Session, p: &Value) -> Result { s.paint.stroke_width = 1.0; } std::mem::swap(&mut s.paint.fill, &mut s.paint.stroke); + if let Some(stroke) = shown_stroke { + s.paint.fill = stroke; + } ok() } @@ -1606,8 +1686,9 @@ fn swap(s: &mut Session, p: &Value) -> Result { const LIVE_PAINT_DEFAULT_WEIGHT: f64 = 0.5; fn default_paint(s: &mut Session, p: &Value) -> Result { - let bucket = bucket_color_params(s, p, "paint.default")?; - let p = bucket.as_ref().unwrap_or(p); + // As with paint.swap, the new fill decides whether only the defaults change. + let for_tool = tool_color_params(s, p, "paint.default", false)?; + let p = for_tool.as_ref().unwrap_or(p); let targets = paint_targets(s, p)?; let given = !targets.is_empty(); // A whole Live Paint group: its faces lose their fill and its edges take a black 0.5 pt stroke. @@ -1687,9 +1768,9 @@ fn default_paint(s: &mut Session, p: &Value) -> Result { /// default when there are none) and remember the first target's new paint. The Appearance panel's /// active item of the proxy's kind is recoloured in each selected object's own stack instead. fn proxy_recolor(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dyn Fn(Color) -> Color) -> Result { - let bucket = bucket_color_params(s, p, cmd)?; - let p = bucket.as_ref().unwrap_or(p); let stroke = stroke_param(s, p, cmd)?; + let for_tool = tool_color_params(s, p, cmd, stroke)?; + let p = for_tool.as_ref().unwrap_or(p); // An object of a dynamic symbol instance's art selected with Direct Selection: the solid color // it shows is recolored for this instance only. A gradient or pattern is refused, and so is type // whose characters differ in that paint, since one change holds one paint. diff --git a/crates/engine/src/cmd/path.rs b/crates/engine/src/cmd/path.rs index b7df3dc467..2859ecf1c0 100644 --- a/crates/engine/src/cmd/path.rs +++ b/crates/engine/src/cmd/path.rs @@ -122,7 +122,7 @@ pub fn specs() -> Vec { "Delete Anchor Points", [], None, - "{} delete the direct-selected anchors and their segments, opening closed paths there, and delete objects selected whole alongside them; what remains of a path stays selected, so a second Delete removes it (the Delete key, unless the deleteKeepsPathsJoined preference is on)", + "{keepEmpty?: bool (keep a compound path left with no members)} delete the direct-selected anchors and their segments, opening closed paths there, and delete objects selected whole alongside them; what remains of a path stays selected, so a second Delete removes it (the Delete key, unless the deleteKeepsPathsJoined preference is on)", has_anchors, delete_anchors ), @@ -328,10 +328,21 @@ pub(crate) fn interpolates_handles(s: &mut Session, p: &Value, cmd: &str) -> Res Ok(on) } -/// [`transform_selected`] on the active document's selection, as one undo step `label`. +/// [`transform_selected`] on the active document's selection, as one undo step `label`. A +/// transform other than a move also transforms the selected ruler guides +/// ([`Document::transform_ruler_guides`]). pub(crate) fn transform_anchors(s: &mut Session, label: &str, xf: vectorcraft_geom::Affine, sc: Scaling, interpolate: bool) -> Result<()> { let sel = s.doc()?.selection.clone(); - s.edit(label, |doc, _| transform_selected(doc, &sel, xf, sc, interpolate)) + // As [`transform_selected`] tells a move apart, which moves the guides itself. + let c = xf.as_coeffs(); + let is_translation = (c[0] - 1.0).abs() < 1e-9 && c[1].abs() < 1e-9 && c[2].abs() < 1e-9 && (c[3] - 1.0).abs() < 1e-9; + s.edit(label, |doc, live| { + transform_selected(doc, &sel, xf, sc, interpolate)?; + if !is_translation { + doc.transform_ruler_guides(live, xf); + } + Ok(()) + }) } /// Apply `xf` to the direct-selected anchors, their handles with them, and (with `sc`) to the @@ -1720,6 +1731,7 @@ pub(crate) fn delete_anchors(s: &mut Session, p: &Value) -> Result { pub(crate) fn delete_anchors_joined(s: &mut Session, p: &Value, keep_joined: bool) -> Result { // `guides: true` (Cut, #3226): the selected ruler guides go in the same undo step. let with_guides = switch_or(p, "guides", false, "path.deleteAnchors")?; + let keep_empty = switch_or(p, "keepEmpty", false, "path.deleteAnchors")?; let st = s.doc()?; let sel = st.selection.anchors.clone(); let segments = st.selection.segments.clone(); @@ -1737,12 +1749,16 @@ pub(crate) fn delete_anchors_joined(s: &mut Session, p: &Value, keep_joined: boo .copied() .filter(|id| !d.ancestry(*id).unwrap_or_default().iter().rev().skip(1).any(|ancestor| targets.contains(ancestor))) .collect(); - // The compound paths that hold a deleted object; one left with no members goes too. - let compounds: BTreeSet = whole_ids - .iter() - .chain(sel.keys()) - .filter_map(|id| d.parent_of(*id).filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. })))) - .collect(); + // The compound paths that hold a deleted object; one left with no members goes too, unless `keepEmpty`. + let compounds: BTreeSet = if keep_empty { + BTreeSet::new() + } else { + whole_ids + .iter() + .chain(sel.keys()) + .filter_map(|id| d.parent_of(*id).filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. })))) + .collect() + }; if !whole_ids.is_empty() { d.remove_many(&whole_ids)?; } diff --git a/crates/engine/src/cmd/pathops.rs b/crates/engine/src/cmd/pathops.rs index 1793f17d5c..b28cf537dc 100644 --- a/crates/engine/src/cmd/pathops.rs +++ b/crates/engine/src/cmd/pathops.rs @@ -126,7 +126,7 @@ pub fn specs() -> Vec { "Pathfinder Options…", ["Window", "Pathfinder"], None, - "{precision?: pt 0.001..10 (0.01; how closely the Pathfinder operations follow the paths: results are refit to within it and pieces thinner than it are dropped), removeRedundantPoints?: bool (false; the results lose the anchors that don't change their shape), removeUnpainted?: bool (false; Divide and Outline leave out the pieces of objects with no fill)} Pathfinder Options, kept in the preferences and used by every later Shape Mode and Pathfinder operation (not Trap); {} reads them → the options", + "{precision?: pt 0.001..10 (0.01; how closely the Pathfinder operations follow the paths: results are refit to within it and pieces thinner than it are dropped; Outline treats crossings closer together than precision / 10000 as one point, or than the tolerance for the art's size when that is larger), removeRedundantPoints?: bool (false; the results lose the anchors that don't change their shape), removeUnpainted?: bool (false; Divide and Outline leave out the pieces of objects with no fill)} Pathfinder Options, kept in the preferences and used by every later Shape Mode and Pathfinder operation (not Trap); {} reads them → the options", always, pathfinder_options ), @@ -610,8 +610,8 @@ impl Default for PathfinderOptions { } } -/// The range of Pathfinder Options › Precision (pt). -pub const PATHFINDER_PRECISION_RANGE: std::ops::RangeInclusive = 0.001..=10.0; +/// The range of Pathfinder Options › Precision (pt), which a Pathfinder effect's `precision` shares. +pub const PATHFINDER_PRECISION_RANGE: std::ops::RangeInclusive = vectorcraft_render::effects::PATHFINDER_EFFECT_PRECISION; impl PathfinderOptions { /// These options with those `p` names (`precision` in pt or a string with a unit), or why `p` diff --git a/crates/engine/src/cmd/place.rs b/crates/engine/src/cmd/place.rs index a1a42a9acd..e787899cd2 100644 --- a/crates/engine/src/cmd/place.rs +++ b/crates/engine/src/cmd/place.rs @@ -32,6 +32,9 @@ //! - A VectorCraft document placed from a file with Link (the default) becomes a placed document: //! one locked object showing the artboard `page`, linked to the file and read again when it //! changes ([`document`]); without Link, an editable copy of its art. +//! - A file an importer plug-in whose manifest sets `place` reads (the one `importer` names, else +//! the first by id that lists the extension of a file no built-in format reads) becomes one group +//! of the objects it returned, embedded ([`fileio::importer`]). //! //! The art lands centred on `at`, fitted into `rect`, or (Replace) where the replaced object was, //! with its transform; Template puts it on a new template layer. The images, symbols, patterns and @@ -82,7 +85,7 @@ pub fn specs() -> Vec { "Place…", ["File"], Some("Cmd+Shift+P"), - "{path | name | dataBase64 (a file's path, or its name with its bytes), link?: true (a raster image keeps its file's path; a VectorCraft document at path becomes one locked placed document showing artboard `page`, linked to the file and read again when it changes (links.update; saving it in this app updates it at once), drawn as vectors in every output; so does a PDF/.ai page at path, showing its `crop` box, unless password or textAs: \"outlines\" is given, and an EPS file, a PostScript file or a PostScript .ai at path, showing the art false gives; false: an editable copy of its art, as from dataBase64; other files are embedded), text?: {characterSet?: \"unicode\" (UTF-8, or UTF-16 with a byte-order mark, or without one by dataset.import's rule: an even length, at least half of its two-byte units holding a NUL byte, the byte order that reads a line break, valid UTF-16 with no NUL character; other bytes as the platform's 8-bit set) | \"ansi\" (the platform's 8-bit set) | \"shiftJis\" | \"gb2312\" (read as GBK) | \"chineseBig5\" | \"cyrillic\" (windows-1251, x-mac-cyrillic on mac) | \"gb18030\" | \"greek\" (windows-1253) | \"turkish\" (windows-1254) | \"baltic\" (windows-1257) | \"centralEuropean\" (windows-1250) (the WHATWG Encoding Standard's decoders: a byte-order mark is read as ordinary bytes, a malformed sequence as U+FFFD), platform?: \"windows\" (ANSI is Windows-1252) | \"mac\" (ANSI is Mac Roman), removeLineReturns?: false (each block of lines becomes one paragraph; blank lines end paragraphs), removeParagraphReturns?: false (drop blank lines), replaceSpaces?: n (runs of n ≥ 2 spaces become a tab)} (a .txt file, placed as area type filling rect, the replaced object's bounds, or else the artboard less a 36 pt margin), template?: false (onto a new locked template layer below the current layer), replace?: false (swap the one selected object, keeping its stacking place and transform; no at/rect; refused while an object of a symbol instance's art is selected), at?: [x, y] centre (default: the first artboard's centre), rect?: [x, y, width, height] fit inside; aspect kept (wins over at), page?: 1 (PDF/.ai page, or a native document's artboard), crop?: \"crop\" (clipped to that page or artboard, default; an SVG, only when given: framed and clipped by its viewBox, else by its art's bounds) | \"bounding\" (the bounds of the art that shows, with its strokes and effects, as an export measures them: hidden objects and guides left out) | \"art\" | \"trim\" | \"bleed\" | \"media\" (a PDF page's boxes), password? (an encrypted PDF), layers?: false (a PSD or PSB file: true embeds its layers as one group named after the file, read as document.open reads them: an image for each layer and a group for each layer group, with the layer's name, visibility, opacity, blend mode and opacity mask, at the place its merged image would take and clipped to the canvas when layers, hidden ones included, reach past it; never linked: link is then false unless given, and link: true is refused; a file without layers is embedded as its merged image, and so are one whose layers are all left out and one whose layers can't be read, with a warning), hiddenLayers?: false (with layers: true, the hidden layers come in hidden instead of being left out; refused without it), importSlices?: bool (a PSD or PSB file: its slices become user slices, moved and scaled with the placed art, in the same undo step; default true when the file is embedded, false when it is linked, and true with link is refused; slices the file generated automatically are left out), dxf?: {…the DXF options of document.open} (a .dxf drawing: fit fills the artboard under at, else the first; fitted or uncentred art lands with its drawing's artboard on that artboard, else it is centred on at), showImportOptions?: true (in the app, a text file without text, a DXF drawing without dxf, a PSD or PSB file embedded without layers (with two layers or more, or with slices) and a PDF with several pages or a password and no page ask for those options first, and an encrypted PDF given page and no password asks for its password; false places them with the options last confirmed, a PDF on page 1 (or page), and asks only an encrypted PDF's password)} → {ids, name, format, linked, width, height, warnings, image?: the id of the image of a DCS file or PSD/PSB file placed in a clip group, which the Links commands take, slices?: [the ids of the user slices a PSD file brought in]}. A PSD or PSB file that names a clipping path places in a clip group of that path (even-odd), as does its merged image in document.open. Raster images come in at 100% of their physical size (the file's ppi, else 72); SVG, DXF, HP-GL (.plt, .hpgl, .hgl, .hpg), PDF/.ai, EMF/WMF and PICT (.pct, .pic, .pict; clipped to the picture's frame), EPS (clipped to its bounding box; as document.open reads it), a .ai saved without PDF compatibility (from its editing data, as document.open reads it: the art of the layers that show on artboard `page`, clipped to that artboard unless crop is \"bounding\") and native documents as one group, with the images, symbols, patterns, swatches and brushes they use. A DCS file (an EPS file with one program per printing plate, DCS 1.0 or 2.0) is placed only from its path with link (else an error, as are document.open and links.embed): one linked image of its plates mixed into CMYK, clipped by the clipping path its composite is drawn through, its spot plates added as spot swatches in the process equivalents the file gives (a swatch of the same name is kept, with a warning); print separations and Separations Preview show each plate on its own ink, and plate files of their own are read from its folder. One undo step; selects what it placed (unless on a template layer); never touches the clipboard. A PNG, JPEG, GIF or WebP image whose pixels can't be read (a file cut short) is an error, and nothing is placed", + "{path | name | dataBase64 (a file's path, or its name with its bytes), link?: true (a raster image keeps its file's path; a VectorCraft document at path becomes one locked placed document showing artboard `page`, linked to the file and read again when it changes (links.update; saving it in this app updates it at once), drawn as vectors in every output; so does a PDF/.ai page at path, showing its `crop` box, unless password or textAs: \"outlines\" is given, and an EPS file, a PostScript file or a PostScript .ai at path, showing the art false gives; false: an editable copy of its art, as from dataBase64; other files are embedded), text?: {characterSet?: \"unicode\" (UTF-8, or UTF-16 with a byte-order mark, or without one by dataset.import's rule: an even length, at least half of its two-byte units holding a NUL byte, the byte order that reads a line break, valid UTF-16 with no NUL character; other bytes as the platform's 8-bit set) | \"ansi\" (the platform's 8-bit set) | \"shiftJis\" | \"gb2312\" (read as GBK) | \"chineseBig5\" | \"cyrillic\" (windows-1251, x-mac-cyrillic on mac) | \"gb18030\" | \"greek\" (windows-1253) | \"turkish\" (windows-1254) | \"baltic\" (windows-1257) | \"centralEuropean\" (windows-1250) (the WHATWG Encoding Standard's decoders: a byte-order mark is read as ordinary bytes, a malformed sequence as U+FFFD), platform?: \"windows\" (ANSI is Windows-1252) | \"mac\" (ANSI is Mac Roman), removeLineReturns?: false (each block of lines becomes one paragraph; blank lines end paragraphs), removeParagraphReturns?: false (drop blank lines), replaceSpaces?: n (runs of n ≥ 2 spaces become a tab)} (a .txt file, placed as area type filling rect, the replaced object's bounds, or else the artboard less a 36 pt margin), template?: false (onto a new locked template layer below the current layer), replace?: false (swap the one selected object, keeping its stacking place and transform; no at/rect; refused while an object of a symbol instance's art is selected), at?: [x, y] centre (default: the first artboard's centre), rect?: [x, y, width, height] fit inside; aspect kept (wins over at), page?: 1 (PDF/.ai page, or a native document's artboard), crop?: \"crop\" (clipped to that page or artboard, default; an SVG, only when given: framed and clipped by its viewBox, else by its art's bounds) | \"bounding\" (the bounds of the art that shows, with its strokes and effects, as an export measures them: hidden objects and guides left out) | \"art\" | \"trim\" | \"bleed\" | \"media\" (a PDF page's boxes), password? (an encrypted PDF), layers?: false (a PSD or PSB file: true embeds its layers as one group named after the file, read as document.open reads them: an image for each layer and a group for each layer group, with the layer's name, visibility, opacity, blend mode and opacity mask, at the place its merged image would take and clipped to the canvas when layers, hidden ones included, reach past it; never linked: link is then false unless given, and link: true is refused; a file without layers is embedded as its merged image, and so are one whose layers are all left out and one whose layers can't be read, with a warning), hiddenLayers?: false (with layers: true, the hidden layers come in hidden instead of being left out; refused without it), importSlices?: bool (a PSD or PSB file: its slices become user slices, moved and scaled with the placed art, in the same undo step; default true when the file is embedded, false when it is linked, and true with link is refused; slices the file generated automatically are left out), dxf?: {…the DXF options of document.open} (a .dxf drawing: fit fills the artboard under at, else the first; fitted or uncentred art lands with its drawing's artboard on that artboard, else it is centred on at), showImportOptions?: true (in the app, a text file without text, a DXF drawing without dxf, a PSD or PSB file embedded without layers (with two layers or more, or with slices) and a PDF with several pages or a password and no page ask for those options first, and an encrypted PDF given page and no password asks for its password; false places them with the options last confirmed, a PDF on page 1 (or page), and asks only an encrypted PDF's password), importer?: \"plugin.\" (an importer plug-in whose manifest sets place, see document.formats: it reads the file, which must have an extension it lists, also one a built-in format reads; without importer, a file no built-in format reads, by its content or its extension, is read by the first such importer by id that lists its extension; it is given the file, at most 128 MiB, with _context.mode \"place\", and its objects, guides left out, are placed as one group named after the file, in the order it returned them, embedded whatever link says), params?: {…} (the importer's own parameters, see plugin.info)} → {ids, name, format, linked, width, height, warnings, image?: the id of the image of a DCS file or PSD/PSB file placed in a clip group, which the Links commands take, slices?: [the ids of the user slices a PSD file brought in]}. A PSD or PSB file that names a clipping path places in a clip group of that path (even-odd), as does its merged image in document.open. Raster images come in at 100% of their physical size (the file's ppi, else 72); SVG, DXF, HP-GL (.plt, .hpgl, .hgl, .hpg), PDF/.ai, EMF/WMF and PICT (.pct, .pic, .pict; clipped to the picture's frame), EPS (clipped to its bounding box; as document.open reads it), a .ai saved without PDF compatibility (from its editing data, as document.open reads it: the art of the layers that show on artboard `page`, clipped to that artboard unless crop is \"bounding\") and native documents as one group, with the images, symbols, patterns, swatches and brushes they use. A DCS file (an EPS file with one program per printing plate, DCS 1.0 or 2.0) is placed only from its path with link (else an error, as are document.open and links.embed): one linked image of its plates mixed into CMYK, clipped by the clipping path its composite is drawn through, its spot plates added as spot swatches in the process equivalents the file gives (a swatch of the same name is kept, with a warning); print separations and Separations Preview show each plate on its own ink, and plate files of their own are read from its folder. One undo step; selects what it placed (unless on a template layer); never touches the clipboard. A PNG, JPEG, GIF or WebP image whose pixels can't be read (a file cut short) is an error, and nothing is placed", has_doc, place ), @@ -190,10 +193,14 @@ fn load_sliced(p: &Value, cmd: &str, board: Option, link_pdf: bool) -> Res /// The file `p` names, read into placeable art; a DXF drawing's Fit to Artboard fills `board` /// (unless the params name their own box). A PDF/.ai page or an EPS file read from a path is placed /// linked with Link when `link_pdf` (false for the queries, which read it embedded). A PSD or PSB -/// file's slices go to `slices`. +/// file's slices go to `slices`. A file an importer plug-in places (the one `importer` names, or one +/// no built-in format reads) is read by it ([`plugin_art`]). fn load_into(p: &Value, cmd: &str, board: Option, link_pdf: bool, slices_out: &mut Slices) -> Result { - let src = fileio::source(p, cmd)?; + let src = fileio::importer::place_source(p, cmd)?; let name = fileio::file_name(src.name); + if let Some(plugin) = fileio::importer::named_for_place(src.name, p, cmd)? { + return plugin_art(name, src.name, &src.bytes, &plugin, p, cmd); + } // An Affinity file is recognised by its signature, whatever its name says. if fileio::TEXT_EXTS.contains(&fileio::extension(src.name).as_str()) && !vectorcraft_affinity::is_affinity(&src.bytes) { let text = text::import(&src.bytes, text::TextOptions::parse(p, cmd)?, cmd)?; @@ -228,8 +235,12 @@ fn load_into(p: &Value, cmd: &str, board: Option, link_pdf: bool, slices_o } return Ok(Loaded { name, format: &doc::FORMAT, art: Art::Text(story), natural: TEXT_FRAME, warnings, link: None, board: None }); } - let format = fileio::detect(src.name, &src.bytes) - .ok_or_else(|| bad(cmd, format!("can't place `{name}`: not a format VectorCraft reads (see document.formats)")))?; + let Some(format) = fileio::detect(src.name, &src.bytes) else { + return match fileio::importer::for_place(src.name) { + Some(plugin) => plugin_art(name, src.name, &src.bytes, &plugin, p, cmd), + None => Err(bad(cmd, format!("can't place `{name}`: not a format VectorCraft reads (see document.formats)"))), + }; + }; let page = match p.get("page") { None => 1, Some(v) => v.as_u64().filter(|n| (1..=100_000).contains(n)).ok_or_else(|| bad(cmd, "page must be a whole number from 1"))? as usize, @@ -385,6 +396,20 @@ fn load_into(p: &Value, cmd: &str, board: Option, link_pdf: bool, slices_o Ok(Loaded { name, format, art: Art::Vector { src: Box::new(doc), nodes, clip }, natural, warnings, link: None, board }) } +/// The file `src` (named `name`) holding `bytes`, read by importer plug-in `plugin` with `p`'s +/// `params`, as art to place: its objects in paint order, guides left out, in a group whose natural +/// box is the bounds of what they draw. It is embedded: an importer reads the file once, so there is +/// nothing to link to. +fn plugin_art(name: String, src: &str, bytes: &[u8], plugin: &vectorcraft_plugins::Plugin, p: &Value, cmd: &str) -> Result { + let (format, mut doc, warnings) = fileio::importer::read_for_place(src, bytes, plugin, p, cmd)?; + let layers = std::mem::take(&mut doc.layers); + let nodes = art_of(layer_art(&layers)); + let natural = shown_bounds(&doc.symbol_boxes(), &nodes) + .filter(|r| r.width() > 0.0 || r.height() > 0.0) + .ok_or_else(|| bad(cmd, format!("`{name}` has no art to place")))?; + Ok(Loaded { name, format, art: Art::Vector { src: Box::new(doc), nodes, clip: None }, natural, warnings, link: None, board: None }) +} + /// A PSD or PSB file's layers, read as `document.open` reads them into `doc`, as art to place: an /// image for each layer and a group for each layer group, bottom first, with the layer's name, /// visibility, opacity, blend mode and opacity mask. The art's natural box is the file's canvas, @@ -992,7 +1017,7 @@ fn read_queue(doc: u64, p: Value, queued: Vec) -> Result { let thumbnail = p.get("thumbnail").and_then(Value::as_f64); let (mut entries, mut files, mut skipped) = (vec![], vec![], vec![]); for mut q in queued { - for k in ["link", "template", "page", "crop", "text", "dxf", "layers", "hiddenLayers", "importSlices"] { + for k in ["link", "template", "page", "crop", "text", "dxf", "layers", "hiddenLayers", "importSlices", "importer", "params"] { if let Some(v) = p.get(k) { q[k] = v.clone(); } diff --git a/crates/engine/src/cmd/plugin.rs b/crates/engine/src/cmd/plugin.rs index 30515fcb45..6f8ce2256f 100644 --- a/crates/engine/src/cmd/plugin.rs +++ b/crates/engine/src/cmd/plugin.rs @@ -101,6 +101,9 @@ pub fn describe(p: &Plugin) -> Value { Kind::Exporter | Kind::Importer => { v["format"] = json!(export::format_id(&m.id)); v["extensions"] = json!(m.extensions); + if m.place { + v["place"] = json!(true); + } } Kind::Filter => {} } @@ -147,7 +150,7 @@ pub fn describe(p: &Plugin) -> Value { /// The plug-in's own parameters from command params: `params` if given, else the top-level keys /// minus the ones the command itself uses. -fn plugin_params(p: &Value) -> Value { +pub fn plugin_params(p: &Value) -> Value { if let Some(v) = p.get("params") { return v.clone(); } @@ -382,6 +385,7 @@ impl FilterRun { // A command's undo step is named after the command. let label = self.label(); let (inputs, parent) = (self.inputs, self.parent); + let notice = out.notice; // The output is applied to a copy of the document, as `colorcmds::edit_if_changed` applies // its pass: only a copy whose objects or kept data differ becomes the document, as one undo // step. Otherwise the document, its undo and redo steps and its saved state stay as they @@ -423,6 +427,11 @@ impl FilterRun { if let Some(cmd) = &self.command { out["command"] = json!(cmd.id); } + // Only an output that was applied reports its notice, with the name of the plug-in that ran. + if let Some(notice) = notice { + out["notice"] = json!(notice); + out["pluginName"] = json!(m.name); + } Ok(out) } } @@ -442,8 +451,9 @@ fn not_granted(name: &str, permission: Permission) -> EngineError { /// parameters and `_context` (what it keeps with the document included), and applies its output as /// one undo step ([`objects::apply_output`]; effect records as [`admit_effects`] admits them), with /// what it keeps with the document from now on: the output handed in for this very run when there -/// is one ([`FilterRun::hand_in`]), else the plug-in's, run now. → `{plugin, ids}`: what it made or -/// changed, which is then selected. +/// is one ([`FilterRun::hand_in`]), else the plug-in's, run now. → `{plugin, ids, notice?, +/// pluginName?}`: what it made or changed, which is then selected, and the output's `notice` once it +/// was applied, with the plug-in's name. fn run(s: &mut Session, p: &Value) -> Result { // An output handed in is for this run only (the app hands it in just before), whatever it does. let handed = s.plugin_output.take(); @@ -816,7 +826,7 @@ fn spec_of(p: &Plugin, c: &Command) -> &'static CommandSpec { fields.push_str(own); } let params = format!( - "{{{fields}}} run “{label}”, a command of plug-in {}, on the selected paths and compound paths as plugin.run runs a filter, with _context.command {:?}: one undo step, none when the run changes nothing → {{plugin, command, ids}}", + "{{{fields}}} run “{label}”, a command of plug-in {}, on the selected paths and compound paths as plugin.run runs a filter, with _context.command {:?}: one undo step, none when the run changes nothing → {{plugin, command, ids, notice?, pluginName?}} (pluginName, the plug-in's name, comes with notice)", m.id, c.id ); let mut made = MADE.lock().unwrap_or_else(|e| e.into_inner()); @@ -852,9 +862,9 @@ fn unrouted(_: &mut Session, _: &Value) -> Result { /// Runs plug-in command `id` (`plugin..`): a filter run of the plug-in on /// `ids` (else the selection) with the command's own parameters, checked before it runs, and /// `_context.command`, under the plug-in's permissions and budget, applied as one undo step named -/// after the command → `{plugin, command, ids}`. A run that fails (a trap, an exhausted budget, an -/// output it may not make) leaves the document as it was, and the error names the plug-in and the -/// command. +/// after the command → `{plugin, command, ids, notice?, pluginName?}`. A run that fails (a trap, an exhausted +/// budget, an output it may not make) leaves the document as it was, and the error names the +/// plug-in and the command. pub(crate) fn run_command(s: &mut Session, id: &str, p: &Value) -> Result { // An output handed in is for `plugin.run` alone. s.plugin_output = None; @@ -1533,9 +1543,11 @@ fn start_folder(s: &Session, folder: &str, record: Option) -> FolderPending let allow = move |f: &std::path::Path| { scope.clone().run(|| match f.to_str() { Some(f) => crate::file_access::check_read(f), - // A lossy name would check another file than the one loaded. - None if crate::file_access::current().is_none() => Ok(()), - None => Err(format!("automation path rejected: {} isn't valid text", f.display())), + // A lossy name would check another file than the one loaded, so such a file loads only + // where no read is checked: without roots and outside a script's command. + None if crate::file_access::current().is_some() => Err(format!("automation path rejected: {} isn't valid text", f.display())), + None if crate::file_access::in_script_command() => Err(format!("Script file access denied: {} isn't valid text", f.display())), + None => Ok(()), }) }; // The modules start loading once the loads queued before them are done. @@ -1848,7 +1860,7 @@ pub fn specs() -> Vec { "List Plug-ins", [], None, - "{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\"|\"importer\", author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.), format? and extensions? (an exporter's or importer's format id, plugin., for document.export or document.open's importer, and its file extensions), budget?: \"heavy\" (a filter that may compute for longer, see plugin.install's allowHeavy), inputs?: [\"type\"|\"image\"|\"symbolInstance\"] (the objects besides paths a filter reads, see plugin.run), context?: [\"settings\"|\"artboards\"|\"layers\"|\"swatches\"] (the parts of the active document a filter's runs and its or a live effect's commands are given in _context.document, with or without a selection, see docs/plugins.md), size, source, permissions: [name] (what it may do: the ones its manifest lists, else the ones its kind implies; progress: it may report its progress, see Cancel and write log lines; settings: it may keep settings of its own; cache: it may keep a cache of its own; commands: a filter may run the commands its commandAllowlist names, see docs/plugins.md), commandAllowlist?: [command id] (the commands a filter with the commands permission may run while it runs, with vc_call), hash (the module's SHA-256), api (the plug-in API level it was built for, 1, 2 or 3), paintOutput?: true (a live effect whose pieces have paints of their own, see docs/plugins.md), cacheBytes (the bytes its cache holds; see plugin.clearCache), commands?: [{id, command (its command id, plugin.., which runs it), label, params (doc), paramsSchema, menu?: {path: [menu label], after?: item label (escaped), placed?: false (it stays in its plug-in's submenu: its label reads like a built-in item or submenu of that menu or another plug-in command placed there)} (the menu its manifest places it in, see docs/plugins.md)}] (the menu commands a filter or live effect adds)}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}], leftOut} | null (under automation read roots, a folder outside them is null, and a failed file and a plug-in's source outside them are named by their file name), safeMode: bool (no plug-in loads or runs, see plugin.safeMode), disabled: [{id, file, name, label}] (turned off for the next launch, see plugin.setEnabled)}", + "{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\"|\"importer\", author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.), format? and extensions? (an exporter's or importer's format id, plugin., for document.export or document.open's importer, and its file extensions), place?: true (an importer whose files file.place also reads, see file.place's importer), budget?: \"heavy\" (a filter that may compute for longer, see plugin.install's allowHeavy), inputs?: [\"type\"|\"image\"|\"symbolInstance\"] (the objects besides paths a filter reads, see plugin.run), context?: [\"settings\"|\"artboards\"|\"layers\"|\"swatches\"] (the parts of the active document a filter's runs and its or a live effect's commands are given in _context.document, with or without a selection, see docs/plugins.md), size, source, permissions: [name] (what it may do: the ones its manifest lists, else the ones its kind implies; progress: it may report its progress, see Cancel and write log lines; settings: it may keep settings of its own; cache: it may keep a cache of its own; commands: a filter may run the commands its commandAllowlist names, see docs/plugins.md), commandAllowlist?: [command id] (the commands a filter with the commands permission may run while it runs, with vc_call), hash (the module's SHA-256), api (the plug-in API level it was built for, 1, 2 or 3), paintOutput?: true (a live effect whose pieces have paints of their own, see docs/plugins.md), cacheBytes (the bytes its cache holds; see plugin.clearCache), commands?: [{id, command (its command id, plugin.., which runs it), label, params (doc), paramsSchema, menu?: {path: [menu label], after?: item label (escaped), placed?: false (it stays in its plug-in's submenu: its label reads like a built-in item or submenu of that menu or another plug-in command placed there)} (the menu its manifest places it in, see docs/plugins.md)}] (the menu commands a filter or live effect adds)}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}], leftOut} | null (under automation read roots, a folder outside them is null, and a failed file and a plug-in's source outside them are named by their file name), safeMode: bool (no plug-in loads or runs, see plugin.safeMode), disabled: [{id, file, name, label}] (turned off for the next launch, see plugin.setEnabled)}", always, list ), @@ -1866,7 +1878,7 @@ pub fn specs() -> Vec { "Run Plug-in", [], None, - "{id, params?: {…} (the plug-in's parameters; or give them as top-level keys; missing ones take their defaults, see plugin.info), ids?: [object id] (left out or null: the selection), …the plug-in's parameters as top-level keys} run an object filter on the selected paths and compound paths (inside selected groups and layers too; hidden, locked, guide and clipping paths, compound paths that clip a clip group and paths inside a group that clips one are left out): it may change, delete or add objects, as one undo step (an output that changes no object and no kept data records none and leaves the document unmodified); the result is selected, except the objects it locked or made guides. A filter whose manifest lists inputs (type, image, symbolInstance; it lists doc.read in permissions, so plugin.install needs grant) is also given the selected objects of those kinds to read, in paint order from the bottom, with at most 16 MiB of pixels and 16 MiB of type runs per run (an object that doesn't fit what the objects before it left comes with pixelsOmitted or truncated; an image that reaches the decoder counts toward the pixels even when decoding fails); every object counts toward the input's half of the plug-in's memory cap, ids, bounds, transforms and names included, and an object whose fields besides its pixels and runs don't fit fails the run with a memory-budget error naming it and its size (a path or compound path fails it with the memory-budget error for a selection too large to hand over), and more than 100,000 of these objects fail it with an object-budget error: its output returns each as {id} or exactly as given, or the run is refused and nothing changes. With nothing selected it gets no objects (generators add theirs to the current layer). A filter with a commandAllowlist runs the commands it names while it runs (vc_call, see docs/plugins.md): its calls and its output are one undo step, and a run that fails or makes a call that fails changes nothing → {plugin, ids}", + "{id, params?: {…} (the plug-in's parameters; or give them as top-level keys; missing ones take their defaults, see plugin.info), ids?: [object id] (left out or null: the selection), …the plug-in's parameters as top-level keys} run an object filter on the selected paths and compound paths (inside selected groups and layers too; hidden, locked, guide and clipping paths, compound paths that clip a clip group and paths inside a group that clips one are left out): it may change, delete or add objects, as one undo step (an output that changes no object and no kept data records none and leaves the document unmodified); the result is selected, except the objects it locked or made guides. A filter whose manifest lists inputs (type, image, symbolInstance; it lists doc.read in permissions, so plugin.install needs grant) is also given the selected objects of those kinds to read, in paint order from the bottom, with at most 16 MiB of pixels and 16 MiB of type runs per run (an object that doesn't fit what the objects before it left comes with pixelsOmitted or truncated; an image that reaches the decoder counts toward the pixels even when decoding fails); every object counts toward the input's half of the plug-in's memory cap, ids, bounds, transforms and names included, and an object whose fields besides its pixels and runs don't fit fails the run with a memory-budget error naming it and its size (a path or compound path fails it with the memory-budget error for a selection too large to hand over), and more than 100,000 of these objects fail it with an object-budget error: its output returns each as {id} or exactly as given, or the run is refused and nothing changes. With nothing selected it gets no objects (generators add theirs to the current layer). A filter with a commandAllowlist runs the commands it names while it runs (vc_call, see docs/plugins.md): its calls and its output are one undo step, and a run that fails or makes a call that fails changes nothing → {plugin, ids, notice?, pluginName?} (notice: the text the output reports in its notice key once applied, escaped and cut at 200 characters; pluginName: the plug-in's name, with it)", has_doc, run ), diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index ec7d3ac989..9a715abf11 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -243,6 +243,7 @@ pub(super) const ALLOWED: &[&str] = &[ "layer.releaseToLayersBuild", "layer.reverse", "layer.selectAll", + "layer.selectHighlighted", "layer.setCurrent", "layer.setProps", "layer.showAll", @@ -741,6 +742,7 @@ pub(super) const DENIED: &[&str] = &[ "addon.cleanup.splitText", "addon.pathtools.movePointsTogether", "addon.pen.nextSegment", + "color.contrast", "effect.refreshDeferred", "graphicStyle.setOptions", "object.blend.createSpine", diff --git a/crates/engine/src/cmd/stroke.rs b/crates/engine/src/cmd/stroke.rs index 78e56e8f33..420b3ed1eb 100644 --- a/crates/engine/src/cmd/stroke.rs +++ b/crates/engine/src/cmd/stroke.rs @@ -241,7 +241,7 @@ fn stroke_set(s: &mut Session, p: &Value) -> Result { let change = StrokeChange::parse(p, C)?; // The stroke the Live Paint Bucket paints with changes; the selection keeps its own, and its // active Appearance row is not a target. - let bucket_p = super::paint::bucket_color_params(s, p, C)?; + let bucket_p = super::paint::tool_color_params(s, p, C, true)?; let bucket = bucket_p.is_some(); let p = bucket_p.as_ref().unwrap_or(p); let item = item_target(s, p, C)?.of_kind(s, false); @@ -397,7 +397,7 @@ fn stroke_step(s: &mut Session, p: &Value, up: bool) -> Result { let unit = s.stroke_unit(); // The weight the Live Paint Bucket paints with changes; the selection keeps its own, and its // active Appearance row is not a target. - let bucket_p = super::paint::bucket_color_params(s, p, c)?; + let bucket_p = super::paint::tool_color_params(s, p, c, true)?; let bucket = bucket_p.is_some(); let p = bucket_p.as_ref().unwrap_or(p); let item = item_target(s, p, c)?.of_kind(s, false); @@ -450,7 +450,7 @@ impl Session { /// selection's stroke. pub fn shown_stroke(&self) -> Option { let st = self.active()?; - if self.bucket_paints() { + if self.tool_paints(true) { return Some(self.new_art_stroke()); } if let Some(part) = st.selected_symbol_part() { @@ -622,7 +622,7 @@ fn stroke_advanced(s: &mut Session, p: &Value) -> Result { if brush.is_some() && super::switch_or(p, "defaultsOnly", false, C)? { return Err(bad(C, "`defaultsOnly` cannot be combined with `brush`")); } - let bucket_p = if brush.is_none() { super::paint::bucket_color_params(s, p, C)? } else { None }; + let bucket_p = if brush.is_none() { super::paint::tool_color_params(s, p, C, true)? } else { None }; let bucket = bucket_p.is_some(); let p = bucket_p.as_ref().unwrap_or(p); let item = item_target(s, p, C)?.of_kind(s, false); diff --git a/crates/engine/src/cmd/swatchlib.rs b/crates/engine/src/cmd/swatchlib.rs index c4db83826e..1d4a57bde3 100644 --- a/crates/engine/src/cmd/swatchlib.rs +++ b/crates/engine/src/cmd/swatchlib.rs @@ -1585,7 +1585,7 @@ fn add(s: &mut Session, p: &Value) -> Result { let mut out = json!({"library": shown_library_id(s, &info.id), "added": added_names, "existing": names(&existing)}); if let (Some(cmd), Some((_, first))) = (apply, picked.first()) { let name = added.iter().chain(&existing).find(|(l, _)| *l == first.name).map_or(first.name.clone(), |(_, n)| n.clone()); - let only = super::paint::defaults_only(s, p, C)?; + let only = super::paint::defaults_only(s, p, C, cmd == "paint.setStroke")?; s.execute(cmd, &super::paint::with_defaults_only(json!({"swatch": name, "focus": focus}), only))?; // Adding and applying undo together. squash(s, undo_before, "Add to Swatches"); diff --git a/crates/engine/src/cmd/webexport.rs b/crates/engine/src/cmd/webexport.rs index 5f2d2cbffd..f578bcd61d 100644 --- a/crates/engine/src/cmd/webexport.rs +++ b/crates/engine/src/cmd/webexport.rs @@ -32,7 +32,7 @@ pub fn specs() -> Vec { "Save for Web", [], None, - "{path?, preset?: a webExport.presets name (its settings, then these keys), format?: gif (default)|jpg|png8|png24, reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray (gif/png8, as the next five), colors?: 128 (2–256), dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, webSnap?: 0 (0–100 %: colours that close to a web-safe one become it), lossy?: 0 (0–100, gif), colorTable?: {locked?: [\"#rrggbb\"…] (kept when reducing), transparent?: [\"#rrggbb\"…] (become transparent), webShift?: [\"#rrggbb\"…] (become web-safe), sort?: none|hue|luminance|popularity, deleted?: [\"#rrggbb\"…] (taken out of the table: their pixels take the nearest color left, and at least one color stays), customPalette?: [\"#rrggbb\"…] (a fixed palette used instead of the reduction's, at most `colors` entries, its transparent colors taking one slot together (the transparent pixels' slot when there are any), its shifted and then its locked colors kept first; a new reduction without colorTable clears it and deleted), shifted?: {\"#source\": \"#rrggbb\"…} (each source color is written as the color given, wherever it is in the image; kept when reducing as a locked color is, before the locked ones, while one palette slot is left for the reduction; at most 256; a source the table does not hold shifts nothing; a color shifted to itself is removed; a shifted color is not web-shifted, and a transparent one stays transparent; GIF lossy moves no pixel into or out of a shifted color)} (colours as the preview's colors[].source; #rrggbbaa and #rgba are refused here and in matte), transparency?: true (gif/png8/png24), matte?: white (default)|black|none|\"#rrggbb\" (what edges blend into; jpg and opaque png24: the background), interlaced?: false (gif/png8/png24), quality?: 60 (jpg: 0–100), progressive?: false (jpg), optimized?: true (jpg), embedProfile?: false (jpg: sRGB profile), width?: px | height?: px | percent?: 100 (the image size, proportional; width wins over height, height over percent), antiAlias?: none|art (default)|type, clipToArtboard?: true (the artboard; false: the art and the slices), artboard?: 0 (0-based), convertToSrgb?: true (PNG files say they are sRGB), metadata?: none|copyright (default)|contact|all (File Info written as PNG text, a GIF or JPEG comment), slices?: all (default)|selected|none (one image per slice: images/.), output?: images (default)|html (an HTML page placing the image or slices, .html)} → {path, files: [path…], bytes (total), width, height, warnings: [] or [a note that an image couldn't be decoded and is missing from the image]}; no path → {files: [{name, dataBase64}], bytes, width, height, warnings} (names such as page.html, images/page_01.gif). A single image without HTML is written at path itself", + "{path?, preset?: a webExport.presets name (its settings, then these keys), format?: gif (default)|jpg|png8|png24, reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray (gif/png8, as the next five), colors?: 128 (2–256), dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, webSnap?: 0 (0–100 %: colours that close to a web-safe one become it), lossy?: 0 (0–100, gif), colorTable?: {locked?: [\"#rrggbb\"…] (kept when reducing), transparent?: [\"#rrggbb\"…] (become transparent), webShift?: [\"#rrggbb\"…] (become web-safe), sort?: none|hue|luminance|popularity, deleted?: [\"#rrggbb\"…] (taken out of the table: their pixels take the nearest color left, and at least one color stays), customPalette?: [\"#rrggbb\"…] (a fixed palette used instead of the reduction's, at most `colors` entries, its transparent colors taking one slot together (the transparent pixels' slot when there are any), its shifted and then its locked colors kept first; a new reduction without colorTable clears it and deleted), shifted?: {\"#source\": \"#rrggbb\"…} (each source color is written as the color given, wherever it is in the image; kept when reducing as a locked color is, before the locked ones, while one palette slot is left for the reduction; at most 256; a source the table does not hold shifts nothing; a color shifted to itself is removed; a shifted color is not web-shifted, and a transparent one stays transparent; GIF lossy moves no pixel into or out of a shifted color)} (colours as the preview's colors[].source; #rrggbbaa and #rgba are refused here and in matte), transparency?: true (gif/png8/png24), transparencyDither?: none (default: pixels under half opacity become transparent)|diffusion|pattern|noise (gif/png8 with transparency: partly transparent pixels become transparent or keep their color in a dither, about as many keeping it as their opacity says with pattern, noise or diffusion at amount 100; fully transparent and opaque pixels do not change), transparencyDitherAmount?: 100 (0–100: the diffusion dither's strength, a lower amount closer to none, 0 as none), matte?: white (default)|black|none|\"#rrggbb\" (what edges blend into; jpg and opaque png24: the background), interlaced?: false (gif/png8/png24), quality?: 60 (jpg: 0–100), progressive?: false (jpg), optimized?: true (jpg), embedProfile?: false (jpg: sRGB profile), width?: px | height?: px | percent?: 100 (the image size, proportional; width wins over height, height over percent), antiAlias?: none|art (default)|type, clipToArtboard?: true (the artboard; false: the art and the slices), artboard?: 0 (0-based), convertToSrgb?: true (PNG files say they are sRGB), metadata?: none|copyright (default)|contact|all (File Info written as PNG text, a GIF or JPEG comment), slices?: all (default)|selected|none (one image per slice: images/.), output?: images (default)|html (an HTML page placing the image or slices, .html)} → {path, files: [path…], bytes (total), width, height, warnings: [] or [a note that an image couldn't be decoded and is missing from the image]}; no path → {files: [{name, dataBase64}], bytes, width, height, warnings} (names such as page.html, images/page_01.gif). A single image without HTML is written at path itself", has_doc, export ), @@ -403,6 +403,12 @@ pub struct WebSettings { pub dither_amount: u8, /// Keep transparent pixels transparent (GIF, PNG-8, PNG-24). pub transparency: bool, + /// GIF and PNG-8 with `transparency`: how partly transparent pixels are split between the + /// transparent entry and their color (`none`: under half opacity is transparent). + #[serde(serialize_with = "ser_key", deserialize_with = "de_key")] + pub transparency_dither: Dither, + /// 0–100: the strength of the `diffusion` transparency dither. + pub transparency_dither_amount: u8, /// What partly transparent edges blend into (JPEG and opaque PNG-24: the background): `white`, /// `black`, `none` or `#rrggbb`. pub matte: String, @@ -449,6 +455,8 @@ impl Default for WebSettings { dither: Dither::Diffusion, dither_amount: 100, transparency: true, + transparency_dither: Dither::None, + transparency_dither_amount: 100, matte: "white".into(), interlaced: false, web_snap: 0, @@ -497,6 +505,10 @@ impl WebSettings { fn checked(mut self) -> std::result::Result { self.colors = self.colors.clamp(2, 256); self.dither_amount = self.dither_amount.min(100); + if self.transparency_dither_amount > 100 { + let key = "transparencyDitherAmount"; + return Err(format!("`{key}` must be from 0 to 100")); + } self.web_snap = self.web_snap.min(100); self.lossy = self.lossy.min(100); self.quality = self.quality.min(100); @@ -804,6 +816,8 @@ fn palette_image(rgba: &[u8], w: u32, h: u32, s: &WebSettings, matte: Option<[u8 dither_amount: s.dither_amount, transparency: s.transparency, matte, + transparency_dither: s.transparency_dither, + transparency_dither_amount: s.transparency_dither_amount, }; let (mut ix, dropped) = reduced(rgba, w, h, s, &o, &kept)?; // Map to transparent works on the colours the reduction made. @@ -910,7 +924,7 @@ fn reduced( return Ok((quantize::quantize_to(rgba, w, h, o, &left), vec![])); } // A fixed palette holds at most `colors` entries, the transparent one included. - let has_clear = s.transparency && rgba.as_chunks::<4>().0.iter().any(|p| p[3] < 128); + let has_clear = quantize::clear_mask(rgba, w, o).contains(&true); let removed = custom.iter().any(|c| deleted.contains(c)); let mut left: Vec<[u8; 3]> = vec![]; for c in custom { @@ -977,12 +991,13 @@ fn clear_dropped(ix: &mut Indexed, rgba: &[u8], o: &PaletteOptions, kept: &[[u8; return vec![]; } let all: Vec<[u8; 3]> = kept.iter().chain(&dropped).copied().collect(); + let width = ix.width; let Indexed { palette, transparent, indices, .. } = ix; // The entry such pixels take, looked up at the first of them. let mut entry: Option> = None; let mut taken = vec![false; dropped.len()]; let mut pixel = 0; - quantize::nearest_entries(rgba, o, &all, |n| { + quantize::nearest_entries(rgba, width, o, &all, |n| { if let Some(d) = n.and_then(|n| n.checked_sub(kept.len())) { let e = *entry.get_or_insert_with(|| { transparent.or_else(|| palette.iter().position(|c| to_clear.contains(c)).and_then(|i| u8::try_from(i).ok())).or_else(|| { diff --git a/crates/engine/src/cmd/xform.rs b/crates/engine/src/cmd/xform.rs index fcb176a793..f12df3f229 100644 --- a/crates/engine/src/cmd/xform.rs +++ b/crates/engine/src/cmd/xform.rs @@ -30,7 +30,7 @@ pub fn specs() -> Vec { "Sample Color", [], None, - "{color (#rrggbbaa and #rgba are refused), stroke?: bool (default: whichever proxy is active), ids?, defaultsOnly?: bool, stop?: index, clearStroke?: bool} sample a color into the active fill/stroke (and the selection; `ids: []` changes only the paint default, and so does a sample without ids while the Live Paint Bucket is the active tool or with `defaultsOnly: true` (refused with ids), `stop` included); `clearStroke: true` requires `stroke: false`, `ids: []` and no `stop`, and clears the default stroke after sampling an image into the fill; with `stop`, recolor that stop of the gradient behind the proxy instead (paint.editGradient); with `stop` and objects in `ids`, whatever tool is active, the stops come from the topmost fill (or stroke) of the first object that paint.editGradient edits for those ids (a compound path for its member); in a CMYK document an RGB color is stored as CMYK through the color settings, as paint.setFill stores it", + "{color (#rrggbbaa and #rgba are refused), stroke?: bool (default: whichever proxy is active), ids?, defaultsOnly?: bool, stop?: index, clearStroke?: bool} sample a color into the active fill/stroke (and the selection; `ids: []` changes only the paint default, and so does a sample without ids while the Live Paint Bucket, or for a fill the Shape Builder, is the active tool or with `defaultsOnly: true` (refused with ids), `stop` included); `clearStroke: true` requires `stroke: false`, `ids: []` and no `stop`, and clears the default stroke after sampling an image into the fill; with `stop`, recolor that stop of the gradient behind the proxy instead (paint.editGradient); with `stop` and objects in `ids`, whatever tool is active, the stops come from the topmost fill (or stroke) of the first object that paint.editGradient edits for those ids (a compound path for its member); in a CMYK document an RGB color is stored as CMYK through the color settings, as paint.setFill stores it", has_doc, sample_color ), diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs index 8f67677684..c5896ff817 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -207,9 +207,16 @@ pub fn unconfined(f: impl FnOnce() -> T) -> T { with_gate_reads_exempt(true, || with_scope(Some(Scope::Unconfined), f)) } +/// Run `f`, a read of a file in one of the app's own folders, with reads exempt from the gate of +/// the script command this thread runs. Unlike [`unconfined`], the roots in force still apply. +pub(crate) fn app_folder_read(f: impl FnOnce() -> T) -> T { + with_gate_reads_exempt(true, f) +} + thread_local! { /// Are reads on this thread exempt from the gate of the script command it runs? Only inside an - /// [`unconfined`] entered after the gate was put in force ([`with_script_gate`]). + /// [`unconfined`] or an [`app_folder_read`] entered after the gate was put in force + /// ([`with_script_gate`]). static GATE_READS_EXEMPT: std::cell::Cell = const { std::cell::Cell::new(false) }; } diff --git a/crates/engine/src/interaction.rs b/crates/engine/src/interaction.rs index f7f9197f1d..6dd833263b 100644 --- a/crates/engine/src/interaction.rs +++ b/crates/engine/src/interaction.rs @@ -22,6 +22,10 @@ pub struct Interaction { /// Conversion of new-art paints waits until a color-mode preview is accepted. pub(crate) deferred_color_mode: Option, pub(crate) color_mode_paints: Option<(vectorcraft_tools::PaintDefaults, vectorcraft_tools::PaintDefaults)>, + /// A preview ran while the active tool painted with the chosen fill or stroke + /// ([`crate::Session::tool_paints`]): the next preview and a cancel put back the new-art paints + /// from before the interaction, whichever tool is active then. + pub(crate) tool_paints: bool, /// Per-document state restored on cancel (current layer, highlighted Layers panel rows, /// isolation). pub active_layer: Option, diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 5560c26fcc..f0d60d9a71 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -74,11 +74,16 @@ pub struct Session { /// While Cmd lends `tool` (a selection tool) for a drag: the tool it was lent to, which comes /// back as it was at the release ([`Session::pointer`]). pub(crate) lender: Option>, - /// Set while tool actions that end by switching back to the Live Paint Bucket are applied (the - /// Eyedropper's sample into a stop of the bucket's gradient), and while a tool the bucket lent - /// is deactivated as it goes back: their paint commands change the colors the bucket paints - /// with ([`Session::bucket_paints`]). - pub(crate) back_to_bucket: bool, + /// While tool actions that end by switching back to a tool that paints with the chosen colors + /// are applied (the Eyedropper's sample into a stop of the Live Paint Bucket's gradient), and + /// while a tool such a tool lent is deactivated as it goes back, that tool's id: their paint + /// commands change the colors it paints with ([`Session::tool_paints`]). + pub(crate) back_to_painter: Option<&'static str>, + /// Whose gradient the stop was on when the Eyedropper was last armed to sample into one + /// (`tool.setOption {stop}`), when it was the gradient a tool paints with + /// ([`Session::painting_tool`]); None for a stop of the selection's paint. A pick armed for + /// such a stop samples only into a stop selected on that gradient, and otherwise ends. + pub(crate) stop_pick: Option, /// Pointer and key input that came while the tool computed an edit on another thread, each with /// its number and view, made in order once the edit is applied. held_input: std::collections::VecDeque<(u64, tooling::HeldInput, ViewInfo)>, diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index 1e0edb076e..87d6c6df80 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -93,6 +93,8 @@ pub struct Prefs { /// Artboard Options › Update While Dragging: the area outside the artboards stays darker while /// the Artboard tool moves or resizes an artboard; off, it draws as usual until the drag ends. pub artboard_update_while_dragging: bool, + /// General › Display Print Size at 100% Zoom (on by default): 100% shows an inch of the + /// document in an inch of the display. A preferences file without the key reads as on. pub display_print_size: bool, pub double_click_to_isolate: bool, pub transform_pattern_tiles: bool, @@ -503,7 +505,7 @@ impl Default for Prefs { type_glyph_bounds: false, fade_region_outside_artboard: true, artboard_update_while_dragging: true, - display_print_size: false, + display_print_size: true, double_click_to_isolate: true, transform_pattern_tiles: false, scale_corners: false, diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs new file mode 100644 index 0000000000..39c740cb2e --- /dev/null +++ b/crates/engine/src/script/dom.rs @@ -0,0 +1,2258 @@ +//! The script object model: the global `app`, the open documents, their selection and the art in +//! them, as the help pages , +//! , +//! , +//! and +//! describe them. +//! +//! The objects are host classes ([`vectorcraft_js::HostClass`]): each holds the run's number, the +//! document's [`crate::DocState::uid`] and, for art, the object's id, and every read looks the +//! document and the object up again. An object that was deleted, a document that was closed and an +//! object from an earlier run of a named engine throw an error on every member. Every change runs +//! a command, as `vc.run` does, so it joins the run's transaction and its one undo step for each +//! changed document; a change that changes nothing runs no command. A change to a document that is +//! not the active one makes it active for the command and makes the other one active again after. +//! +//! Collections are counted from 0, and `pageItems` lists art topmost first, as +//! reads the frontmost path as +//! `pathItems[0]`. A collection read with a name, `pageItems["name"]`, gives the object `getByName` +//! gives, and a script may name the application's members without `app.`, as +//! describes; here +//! that holds for `activeDocument`, `documents` and `selection`. +//! +//! VectorCraft's own rules: +//! - A document's selection lists the selected objects topmost first, as `pageItems` does, whatever +//! order they were selected or made in. The objectReferences page above says instead that the +//! first object is the one last added to the page; VectorCraft does not follow that sentence. +//! - A collection read with a name that nothing has throws `Not found`, and `"name" in pageItems` is +//! false then. Assigning to such a name throws the same error. +//! - Assigning `activeDocument` or `selection` without `app.` assigns `app.activeDocument` or the +//! active document's selection. A top-level `var selection = ...` does the same and does +//! not make a variable of the script. Assigning `documents` keeps its value. +//! - Collections list documents in tab order. The objectReferences page says `documents[0]` is +//! always the active document; VectorCraft does not follow that yet. +//! - `pageItems` lists every object, with the objects inside groups and compound paths after the +//! group or compound path, and leaves out layers and ruler guides. An index out of range gives +//! `undefined`; `index` and `getByName` throw `Not found` when nothing matches. +//! - Script coordinates are points with Y up from the bottom of the first artboard +//! (`DOCUMENTCOORDINATESYSTEM`, the default) or points with Y down from the top-left corner of +//! the active artboard (`ARTBOARDCOORDINATESYSTEM`), as `app.coordinateSystem` says for the run. +//! - Enumerated values are strings such as `"ZOrderMethod.BRINGTOFRONT"`. +//! - `app.activeDocument` with no document open throws `No active document`. +//! - Assigning `Document.selection` takes one object, a list of them, `null` or `[]`; every object +//! must be one of that document's that can be selected, or nothing changes. +//! - Members the help pages list that are not here yet throw an error that says so. +//! - Assigning `hidden`, `locked`, `opacity`, `position`, `left`, `top`, `width` or `height` to an +//! object in a hidden or locked layer, and `zOrder()` on one, throw `Cannot edit` and change +//! nothing, even for the value the object has. The exception is `opacity` given the value the +//! object has when that changes nothing; on a graph's mark or label whose series or kind keeps +//! another opacity it would still change the graph, so it is refused too. Its `name` and `note` +//! still change. An object that is hidden or locked itself, or is in a hidden or locked group, +//! takes them. +//! - `name` and `note` take a number or a Boolean as the text `String(value)` gives. +//! - A compound path whose last path `move` or `remove()` takes out stays, empty. +//! - An object with nothing in it, such as an empty group or a compound path whose paths moved out, +//! reads its bounds, `position`, `width` and `height` as zeros, and assigning them does nothing. + +use std::cell::{Cell, RefCell}; +use std::collections::{HashMap, HashSet}; +use std::rc::Rc; +use std::sync::Arc; + +use serde_json::{Value, json}; +use vectorcraft_geom::{Point, Rect}; +use vectorcraft_js::{Data, HostClass, HostError, HostFunction, HostItem, HostMember, Realm, RunError, host_ref, host_ref_parts}; + +use super::{HISTORY_LOST, Host, Link, Savepoint, command, command_value, current, data_size}; +use crate::{DocState, Document, NodeId, NodeKind, Session}; + +/// The error for a member read or called with no document open. +pub const NO_ACTIVE_DOCUMENT: &str = "No active document"; +/// The error for an object that was deleted, or that came from an earlier run. +pub const STALE_ITEM: &str = "Stale page item"; +/// The error for a document that was closed, or that came from an earlier run. +pub const STALE_DOCUMENT: &str = "Stale document"; +/// The error of `index` and `getByName` when nothing matches. +pub const NOT_FOUND: &str = "Not found"; +/// The most objects one read of a selection gives, and the most a selection assignment takes. +pub const MAX_LISTED: usize = 10_000; +/// The longest name an object or a path query may have, in bytes. +pub const MAX_TEXT_BYTES: usize = 4096; +/// The most artboards `Documents.add` makes. +pub const MAX_ARTBOARDS: f64 = 100.0; +/// The largest width or height `Documents.add` takes, in points, as `file.new` takes them. +pub const MAX_SIZE: f64 = 3_999_856.0; + +/// The page item classes, with the typename of each kind of object ([`typename`]). +const ITEM_CLASSES: &[&str] = &[ + "PathItem", + "CompoundPathItem", + "GroupItem", + "GraphItem", + "TextFrame", + "PlacedItem", + "RasterItem", + "SymbolItem", + "MeshItem", + "BlendItem", + "EnvelopeItem", + "RepeatItem", + "PlacedDocumentItem", + "IntertwineItem", +]; + +/// `app.coordinateSystem`. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(super) enum Coords { + #[default] + Document, + Artboard, +} + +const DOCUMENT_COORDS: &str = "CoordinateSystem.DOCUMENTCOORDINATESYSTEM"; +const ARTBOARD_COORDS: &str = "CoordinateSystem.ARTBOARDCOORDINATESYSTEM"; + +/// What the object model keeps for one run: its coordinate system, the lists of page items and the +/// answers of which objects are on a locked artboard for the last [`ITEM_LISTS`] documents read, +/// each kept while its document is unchanged, whether a call's own savepoint ([`atomically`]) is +/// open, and the settings of each `DocumentPreset` the run made. +#[derive(Default)] +pub(super) struct State { + coords: Cell, + items: RefCell>, + locked: RefCell>, + saving: Cell, + presets: RefCell>>, +} + +impl State { + /// Whether a call's own savepoint is open: its commands take none of their own. + pub(super) fn saving(&self) -> bool { + self.saving.get() + } +} + +/// Runs `f`, whose commands are kept together or put back together: when `f` fails, every +/// document, the selection and the undo histories are as they were before it, with no undo step +/// and no change to the document's saved state. +fn atomically(h: &Host, f: impl FnOnce(&Host) -> std::result::Result) -> std::result::Result { + if h.dom.saving.get() { + return f(h); + } + let save = Savepoint::take(&mut h.session.borrow_mut(), "edit.duplicate"); + h.dom.saving.set(true); + let r = f(h); + h.dom.saving.set(false); + let mut s = h.session.borrow_mut(); + if r.is_ok() { + save.keep(&mut s); + } else if !save.restore(&mut s) { + return Err(HostError::Abort(HISTORY_LOST.to_string())); + } + r +} + +/// A document's uid, the document as it was, and the ids of its page items then. +type ItemList = (u64, Arc, Rc>); + +/// A document's uid, the document and its new art ([`Document::new_art`]) as they were, and for +/// each object of a layer or sublayer asked about then, whether it was on a locked artboard. +type LockedList = (u64, Arc, Arc>, HashMap); + +/// How many documents' lists [`State`] keeps at once, of each kind. +const ITEM_LISTS: usize = 4; + +/// The kept list of the document `uid` as `doc` is, if there is one. +fn kept_items(lists: &[ItemList], uid: u64, doc: &Arc) -> Option>> { + lists.iter().find(|(u, d, _)| *u == uid && Arc::ptr_eq(d, doc)).map(|(_, _, ids)| ids.clone()) +} + +/// Keeps `list` in place of any earlier list of the same document, dropping the least recently +/// kept list beyond [`ITEM_LISTS`]. +fn keep_items(lists: &mut Vec, list: ItemList) { + lists.retain(|(u, _, _)| *u != list.0); + if lists.len() >= ITEM_LISTS { + lists.remove(0); + } + lists.push(list); +} + +/// Whether node `id` of `st` is on a locked artboard ([`Document::on_locked_artboard`]). Each +/// object of a layer or sublayer is measured once while the document and its new art stay as they +/// are, so the members of a group are answered with one measurement of the group. +fn on_locked_artboard(h: &Host, st: &DocState, id: NodeId) -> bool { + if !st.doc.artboards.iter().any(|a| a.locked) { + return false; + } + let Some(object) = st.doc.layer_object(id).map(|n| n.id) else { + return false; + }; + let new_art = st.doc.new_art.get(); + let mut lists = h.dom.locked.borrow_mut(); + let at = match lists.iter().position(|(u, d, n, _)| *u == st.uid && Arc::ptr_eq(d, &st.doc) && Arc::ptr_eq(n, &new_art)) { + Some(at) => at, + None => { + lists.retain(|(u, ..)| *u != st.uid); + if lists.len() >= ITEM_LISTS { + lists.remove(0); + } + lists.push((st.uid, st.doc.clone(), new_art, HashMap::new())); + lists.len() - 1 + } + }; + match lists.get_mut(at) { + Some((.., held)) => *held.entry(object).or_insert_with(|| st.doc.on_locked_artboard(object)), + None => st.doc.on_locked_artboard(object), + } +} + +type Answer = std::result::Result; + +/// A member function: the run's host and the call's arguments, `this` first. +type Member = fn(&Host, &[Data]) -> Answer; + +fn function(link: &Link, f: Member) -> HostFunction { + let l = link.clone(); + Rc::new(move |a: Vec| { + let h = current(&l)?; + h.charge_call(16 + a.iter().map(data_size).sum::())?; + f(&h, &a) + }) +} + +fn get(link: &Link, f: Member) -> HostMember { + HostMember::Get(function(link, f)) +} + +fn property(link: &Link, g: Member, s: Member) -> HostMember { + HostMember::Property { get: function(link, g), set: function(link, s) } +} + +fn method(link: &Link, f: Member) -> HostMember { + HostMember::Method(function(link, f)) +} + +/// A member the help pages list that is not available yet: reading or assigning it throws, after +/// the check that a document or page item `this` is still there. `hasOwnProperty` is false for it, +/// so a script that checks for the member first skips it. +fn later(link: &Link, class: &'static str, name: &'static str) -> (String, HostMember) { + let message = format!("{class}.{name} is not available yet"); + let l = link.clone(); + let f: HostFunction = Rc::new(move |a: Vec| { + let h = current(&l)?; + h.charge_call(16)?; + match class { + "Document" => { + doc_of(&h, arg(&a, 0), "Document")?; + } + "PageItem" => { + item_of(&h, arg(&a, 0))?; + } + _ => {} + } + Err(HostError::Error(message.clone())) + }); + (name.to_string(), HostMember::Unavailable(f)) +} + +fn text(s: impl Into) -> Data { + Data::String(s.into()) +} + +fn num(n: f64) -> Data { + Data::Number(n) +} + +fn pair(p: [f64; 2]) -> Data { + Data::Array(vec![num(p[0]), num(p[1])]) +} + +fn arg(a: &[Data], i: usize) -> &Data { + a.get(i).unwrap_or(&Data::Undefined) +} + +/// A whole number from a handle or an argument, within 0 and 2^53. +#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] +fn whole(n: f64) -> Option { + (n.is_finite() && n.fract() == 0.0 && (0.0..=9_007_199_254_740_992.0).contains(&n)).then_some(n as u64) +} + +#[allow(clippy::cast_precision_loss)] +fn float(n: u64) -> f64 { + n as f64 +} + +/// A node id in a handle: its high and low 32 bits, each exact as a number. +fn id_parts(id: NodeId) -> [f64; 2] { + [float(id.0 >> 32), float(id.0 & 0xffff_ffff)] +} + +/// The node id [`id_parts`] gave as `high` and `low`. +fn id_of(high: f64, low: f64) -> Option { + let (high, low) = (whole(high)?, whole(low)?); + (high <= 0xffff_ffff && low <= 0xffff_ffff).then_some(NodeId((high << 32) | low)) +} + +/// A finite number argument, or a `TypeError` naming `what`. +fn number(d: &Data, what: &str) -> std::result::Result { + match d { + Data::Number(n) if n.is_finite() => Ok(*n), + _ => Err(HostError::Type(format!("{what} must be a finite number"))), + } +} + +/// A coordinate argument: a finite number within the canvas. +fn coordinate(d: &Data, what: &str) -> std::result::Result { + let n = number(d, what)?; + if n.abs() > crate::MAX_COORD * 2.0 { + return Err(HostError::Range(format!("{what} is outside the canvas"))); + } + Ok(n) +} + +/// A point argument `[x, y]`. +fn point(d: &Data, what: &str) -> std::result::Result<[f64; 2], HostError> { + match d { + Data::Array(a) if a.len() == 2 => Ok([coordinate(&a[0], what)?, coordinate(&a[1], what)?]), + _ => Err(HostError::Type(format!("{what} must be an array of two numbers"))), + } +} + +fn boolean(d: &Data, what: &str) -> std::result::Result { + match d { + Data::Bool(b) => Ok(*b), + _ => Err(HostError::Type(format!("{what} must be true or false"))), + } +} + +/// The handle of `d` when it is an object of `class` (or of a page item class, for `"PageItem"`). +fn handle_of(d: &Data, class: &str) -> Option> { + let (c, handle) = host_ref_parts(d)?; + let matches = if class == "PageItem" { ITEM_CLASSES.contains(&c) } else { c == class }; + matches.then_some(handle) +} + +/// A document an object of the model names: its index among the open documents and its uid. +#[derive(Clone, Copy)] +struct Doc { + index: usize, + uid: u64, +} + +/// A page item: its document and its id. +#[derive(Clone, Copy)] +struct Item { + doc: Doc, + id: NodeId, +} + +/// The open document with `uid`, when the run's number in a handle is this run's. +fn find_doc(h: &Host, run: f64, uid: f64) -> Option { + if whole(run) != Some(h.run) { + return None; + } + let uid = whole(uid)?; + let s = h.session.borrow(); + s.documents().iter().position(|d| d.uid == uid).map(|index| Doc { index, uid }) +} + +/// The document `d` names: a `Document` or a `PageItems` object. +fn doc_of(h: &Host, d: &Data, class: &str) -> std::result::Result { + let Some(handle) = handle_of(d, class) else { return Err(HostError::Type(format!("this is not a {class}"))) }; + match handle.as_slice() { + [run, uid] => find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into())), + _ => Err(HostError::Type(format!("this is not a {class}"))), + } +} + +/// The page item `d` names, which must still be in its document. +fn item_of(h: &Host, d: &Data) -> std::result::Result { + let Some(handle) = handle_of(d, "PageItem") else { return Err(HostError::Type("this is not a page item".into())) }; + let [run, uid, high, low] = handle.as_slice() else { return Err(HostError::Type("this is not a page item".into())) }; + let doc = find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + let id = id_of(*high, *low).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + let s = h.session.borrow(); + let st = &s.documents()[doc.index]; + if st.doc.node(id).is_none_or(|n| typename(n).is_none()) { + return Err(HostError::Error(STALE_ITEM.into())); + } + Ok(Item { doc, id }) +} + +/// The typename of a node, or `None` for one that is not a page item (a layer or a ruler guide). +fn typename(n: &crate::doc::Node) -> Option<&'static str> { + Some(match &n.kind { + NodeKind::Layer { .. } | NodeKind::RulerGuide { .. } => return None, + NodeKind::Group { .. } if n.extras().graph.is_some() => "GraphItem", + NodeKind::Group { .. } => "GroupItem", + NodeKind::Path { .. } => "PathItem", + NodeKind::Compound { .. } => "CompoundPathItem", + NodeKind::Text(_) => "TextFrame", + NodeKind::Image(image) if image.link.is_some() => "PlacedItem", + NodeKind::Image(_) => "RasterItem", + NodeKind::SymbolInstance { .. } => "SymbolItem", + NodeKind::Mesh(_) => "MeshItem", + NodeKind::Blend { .. } => "BlendItem", + NodeKind::Envelope { .. } => "EnvelopeItem", + NodeKind::Repeat(_) => "RepeatItem", + NodeKind::PlacedDocument(_) => "PlacedDocumentItem", + NodeKind::Intertwine { .. } => "IntertwineItem", + }) +} + +fn doc_ref(h: &Host, uid: u64) -> Data { + host_ref("Document", &[float(h.run), float(uid)]) +} + +fn item_ref(h: &Host, st: &DocState, id: NodeId) -> Data { + match st.doc.node(id) { + Some(n) => match typename(n) { + Some(t) => host_ref(t, &[float(h.run), float(st.uid), id_parts(id)[0], id_parts(id)[1]]), + None => host_ref("Layer", &[float(h.run), float(st.uid), id_parts(id)[0], id_parts(id)[1]]), + }, + None => Data::Null, + } +} + +/// The ids of a document's page items, topmost first, each group or compound path before the +/// objects in it ([`State`] keeps the lists of the last documents read). +fn page_items(h: &Host, st: &DocState) -> Rc> { + if let Some(ids) = kept_items(&h.dom.items.borrow(), st.uid, &st.doc) { + return ids; + } + fn walk(nodes: &[Arc], out: &mut Vec) { + for n in nodes.iter().rev() { + match &n.kind { + NodeKind::Layer { children, .. } => walk(children, out), + NodeKind::RulerGuide { .. } => {} + _ => { + out.push(n.id); + if let Some(children) = n.children() { + walk(children, out); + } + } + } + } + } + let mut ids = Vec::new(); + walk(&st.doc.layers, &mut ids); + let ids = Rc::new(ids); + keep_items(&mut h.dom.items.borrow_mut(), (st.uid, st.doc.clone(), ids.clone())); + ids +} + +/// The objects directly in the layers and sublayers of a document: what deleting every page item +/// deletes. +fn top_items(d: &Document) -> Vec { + fn walk(nodes: &[Arc], out: &mut Vec) { + for n in nodes { + match &n.kind { + NodeKind::Layer { children, .. } => walk(children, out), + NodeKind::RulerGuide { .. } => {} + _ => out.push(n.id), + } + } + } + let mut out = Vec::new(); + walk(&d.layers, &mut out); + out +} + +/// Whether `n` and every object inside it are shown and unlocked. +fn all_editable(n: &crate::doc::Node) -> bool { + n.visible && !n.locked && n.children().is_none_or(|c| c.iter().all(|c| all_editable(c))) +} + +/// Whether the object and every layer and group it is in are shown and unlocked. +fn editable(d: &Document, id: NodeId) -> bool { + d.ancestry(id).is_some_and(|a| a.iter().chain(std::iter::once(&id)).all(|i| d.node(*i).is_some_and(|n| n.visible && !n.locked))) +} + +/// The two rectangles script coordinates are measured from. +struct Frame { + /// The first artboard's left edge and bottom edge. + left0: f64, + bottom0: f64, + /// The active artboard's left edge and top edge. + left: f64, + top: f64, +} + +/// The index of the active artboard of `st`, as the view keeps it. +fn active_artboard(st: &DocState) -> usize { + let index_of = |id: u32| st.doc.artboards.iter().position(|a| a.id == id); + st.active_artboard.and_then(index_of).or_else(|| st.doc.opened_artboard.and_then(index_of)).unwrap_or(0) +} + +fn frame(st: &DocState) -> std::result::Result { + let (Some(first), Some(active)) = (st.doc.artboards.first(), st.doc.artboards.get(active_artboard(st))) else { + return Err(HostError::Error("the document has no artboards".into())); + }; + Ok(Frame { left0: first.rect.x0, bottom0: first.rect.y1, left: active.rect.x0, top: active.rect.y0 }) +} + +impl Frame { + /// A point in document coordinates as the script sees it in `c`. + fn to_script(&self, c: Coords, p: Point) -> [f64; 2] { + match c { + Coords::Document => [p.x - self.left0, self.bottom0 - p.y], + Coords::Artboard => [p.x - self.left, p.y - self.top], + } + } + + /// A point the script gave in `c`, in document coordinates. + fn to_document(&self, c: Coords, p: [f64; 2]) -> Point { + match c { + Coords::Document => Point::new(p[0] + self.left0, self.bottom0 - p[1]), + Coords::Artboard => Point::new(p[0] + self.left, p[1] + self.top), + } + } + + /// `[left, top, right, bottom]` of `r` as the script sees it. + fn bounds(&self, c: Coords, r: Rect) -> Data { + let a = self.to_script(c, Point::new(r.x0, r.y0)); + let b = self.to_script(c, Point::new(r.x1, r.y1)); + Data::Array(vec![num(a[0]), num(a[1]), num(b[0]), num(b[1])]) + } +} + +fn coords_of(d: &Data) -> std::result::Result { + match d { + Data::String(s) if s == DOCUMENT_COORDS => Ok(Coords::Document), + Data::String(s) if s == ARTBOARD_COORDS => Ok(Coords::Artboard), + _ => Err(HostError::Type("give a CoordinateSystem value".into())), + } +} + +/// Selects `before` again in the active document `doc` with the selection commands, so that the +/// journal holds the change: a Layers panel target, a dynamic symbol instance's object or an Objects +/// on Path group's object with its own command, else the objects in their order with their +/// direct-selected anchors, then the segments, the ruler guides and the key object, guide or anchor. +/// Objects that are now deleted, hidden or locked are left out. +fn restore_selection(h: &Host, doc: &Document, before: &crate::doc::Selection) -> std::result::Result<(), HostError> { + // Slices selected with the Slice Selection tool are the whole selection when there are any. + let slices: Vec = before.slices.iter().filter(|i| doc.is_slice(**i)).map(|i| i.0).collect(); + if !slices.is_empty() { + command(h, "object.slice.select", &json!({"slices": slices}))?; + return Ok(()); + } + let keep = |id: &NodeId| editable(doc, *id); + // Each of these commands sets the whole selection. One that refuses (its object is no longer + // inside the isolated group, or a symbol's object is now hidden) changes nothing, and the + // objects are selected as below. + if let Some(t) = before.target.filter(keep) + && done_unless_refused(command(h, "layer.target", &json!({"id": t.0})))? + { + return Ok(()); + } + if let Some(p) = before.symbol_part.as_ref().filter(|p| keep(&p.instance)) + && done_unless_refused(command(h, "symbol.instance.selectPart", &json!({"id": p.instance.0, "path": p.path})))? + { + return Ok(()); + } + if let Some(m) = before.on_path_member.filter(keep) + && done_unless_refused(command(h, "object.objectsOnPath.selectMember", &json!({"member": m.0})))? + { + return Ok(()); + } + let partial = |id: &NodeId| before.anchors.contains_key(id) || before.segments.contains_key(id); + let kept: Vec = before.objects.iter().copied().filter(keep).collect(); + if kept.is_empty() { + command(h, "select.none", &json!({}))?; + } else if !kept.iter().any(partial) { + command(h, "select.set", &json!({"ids": kept.iter().map(|i| i.0).collect::>()}))?; + } else { + // One `select.anchorsMany` selects every object in its order: a partly selected path with + // its anchors, a whole path with all of them and any other object with none. + let items: Vec = kept + .iter() + .map(|i| { + let anchors: Vec<[usize; 2]> = match before.anchors.get(i) { + Some(a) => a.iter().map(|(p, k)| [*p, *k]).collect(), + None => doc.node(*i).and_then(|n| n.path_data()).map(|p| p.anchors().map(|(s, k, _)| [s, k]).collect()).unwrap_or_default(), + }; + json!({"id": i.0, "anchors": anchors}) + }) + .collect(); + command(h, "select.anchorsMany", &json!({"items": items, "mode": "set"}))?; + } + for (i, segments) in before.segments.iter().filter(|(i, _)| keep(i)) { + let segments: Vec<[usize; 2]> = segments.iter().map(|(p, k)| [*p, *k]).collect(); + command(h, "select.segments", &json!({"id": i.0, "segments": segments, "mode": "add"}))?; + } + let guides: Vec = doc.ruler_guides().into_iter().filter_map(|g| g.id).collect(); + let index = |id: &NodeId| guides.iter().position(|g| g == id); + let picked: Vec = before.guides.iter().filter_map(index).collect(); + // Guides that are locked now, and a key that no longer qualifies (the objects beside it are + // gone), stay unselected: those commands refuse them and change nothing. + if !picked.is_empty() { + done_unless_refused(command(h, "guide.select", &json!({"indexes": picked, "toggle": true})))?; + } + let key = if let Some((id, (p, k))) = before.key_anchor.filter(|(id, _)| keep(id)) { + Some(json!({"id": id.0, "anchor": [p, k]})) + } else if let Some(id) = before.key.filter(keep) { + Some(json!({"id": id.0})) + } else { + before.key_guide.as_ref().and_then(index).map(|g| json!({"guide": g})) + }; + if let Some(key) = key { + done_unless_refused(command(h, "select.key", &key))?; + } + Ok(()) +} + +/// The result `r` of a selection command that [`restore_selection`] runs: `true` when it ran and +/// `false` when it refused (an `Error`, which changes nothing). Any other error, such as an +/// internal failure or a request to stop, is returned, so the run ends with it. +fn done_unless_refused(r: std::result::Result) -> std::result::Result { + match r { + Ok(_) => Ok(true), + Err(HostError::Error(_)) => Ok(false), + Err(e) => Err(e), + } +} + +/// Makes `layer` the current layer of the active document `uid` again, with `rows` the highlighted +/// Layers panel rows, after selecting objects made the layer of the last of them current and +/// cleared the rows. Nothing runs when `layer` is gone. `layer.highlight` puts the rows back when +/// they changed, and then `layer.setCurrent` with `keepRows` makes `layer` current when it is not. +fn restore_layer(h: &Host, uid: u64, layer: Option, rows: &[NodeId]) -> std::result::Result<(), HostError> { + let Some(layer) = layer else { return Ok(()) }; + let rows = { + let s = h.session.borrow(); + let Some(st) = s.active().filter(|st| st.uid == uid) else { return Ok(()) }; + if st.doc.node(layer).is_none() { + return Ok(()); + } + let rows: Vec = rows.iter().copied().filter(|r| st.doc.node(*r).is_some()).collect(); + (st.highlighted_rows() != rows).then(|| rows.iter().map(|r| r.0).collect::>()) + }; + if let Some(rows) = rows { + command(h, "layer.highlight", &json!({"ids": rows, "mode": "set"}))?; + } + let current = h.session.borrow().active().is_some_and(|st| st.active_layer == Some(layer)); + if !current { + command(h, "layer.setCurrent", &json!({"id": layer.0, "keepRows": true}))?; + } + Ok(()) +} + +/// Runs `f` with the document `uid` active, and makes the document that was active before active +/// again after. With `keep_selection`, the document's selection is put back as it was when `f`'s +/// commands changed it (commands given ids select them first), direct-selected anchors, segments, +/// ruler guides, slices, the key, a Layers panel target and an object chosen inside a dynamic +/// symbol instance or an Objects on Path group included, less the objects that are now deleted, +/// hidden or locked. +fn on_doc( + h: &Host, + uid: u64, + keep_selection: bool, + f: impl FnOnce(&Host) -> std::result::Result, +) -> std::result::Result { + let (index, active, before, layer) = { + let s = h.session.borrow(); + let index = s.documents().iter().position(|d| d.uid == uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?; + let st = &s.documents()[index]; + (index, s.active_index(), st.selection.clone(), (st.active_layer, st.highlighted_rows())) + }; + let switch = active != Some(index); + if switch { + command(h, "document.activate", &json!({"index": index}))?; + } + let r = f(h); + let mut restored = Ok(()); + if keep_selection { + let doc = { + let s = h.session.borrow(); + s.active().filter(|st| st.uid == uid && st.selection != before).map(|st| st.doc.clone()) + }; + if let Some(doc) = doc { + restored = restore_selection(h, &doc, &before); + } + if restored.is_ok() { + restored = restore_layer(h, uid, layer.0, &layer.1); + } + } + // The document that was active is active again before any error is given: `f`'s error first, + // then the selection's, then the switch back's. + let back = match active { + Some(a) if switch => command(h, "document.activate", &json!({"index": a})).map(drop), + _ => Ok(()), + }; + let v = r?; + restored?; + back?; + Ok(v) +} + +/// Runs `id` with `params` on the item's document, its selection kept. +fn edit_item(h: &Host, item: Item, id: &str, params: &Value) -> std::result::Result { + on_doc(h, item.doc.uid, true, |h| command(h, id, params)) +} + +/// Reads the document of `doc` with `f`. +fn with_doc(h: &Host, doc: Doc, f: impl FnOnce(&Session, &DocState) -> T) -> T { + let s = h.session.borrow(); + f(&s, &s.documents()[doc.index]) +} + +// ---- Application ---- + +fn app_documents(_: &Host, _: &[Data]) -> Answer { + Ok(host_ref("Documents", &[])) +} + +fn app_active(h: &Host, _: &[Data]) -> Answer { + let s = h.session.borrow(); + let st = s.active().ok_or_else(|| HostError::Error(NO_ACTIVE_DOCUMENT.into()))?; + Ok(doc_ref(h, st.uid)) +} + +fn app_set_active(h: &Host, a: &[Data]) -> Answer { + let doc = doc_of(h, arg(a, 1), "Document")?; + if h.session.borrow().active_index() != Some(doc.index) { + command(h, "document.activate", &json!({"index": doc.index}))?; + } + Ok(Data::Undefined) +} + +fn app_selection(h: &Host, _: &[Data]) -> Answer { + let uid = h.session.borrow().active().map(|st| st.uid); + match uid { + Some(uid) => selection_of(h, uid), + None => Ok(Data::Null), + } +} + +/// `app.selection = objects`: the active document's selection, as `selection` of that document is +/// assigned. +fn app_set_selection(h: &Host, a: &[Data]) -> Answer { + let doc = { + let s = h.session.borrow(); + let active = s.active_index().and_then(|index| s.documents().get(index).map(|st| Doc { index, uid: st.uid })); + active.ok_or_else(|| HostError::Error(NO_ACTIVE_DOCUMENT.into()))? + }; + let ids = selection_ids(h, doc, arg(a, 1))?; + set_selection(h, doc, ids) +} + +fn app_coords(h: &Host, _: &[Data]) -> Answer { + Ok(text(if h.dom.coords.get() == Coords::Document { DOCUMENT_COORDS } else { ARTBOARD_COORDS })) +} + +fn app_set_coords(h: &Host, a: &[Data]) -> Answer { + h.dom.coords.set(coords_of(arg(a, 1))?); + Ok(Data::Undefined) +} + +/// A path as `getIsFileOpen` compares it: `\` and `/` alike, and on Windows paths (a drive letter +/// or a `\`) letters in one case. +fn path_key(p: &str) -> String { + let windows = p.contains('\\') || p.as_bytes().get(1) == Some(&b':'); + let p = p.replace('\\', "/"); + let p = p.trim_end_matches('/').to_string(); + if windows { p.to_lowercase() } else { p } +} + +/// `app.getIsFileOpen(path)`: whether a document open in the run has the file `path`. The path is +/// compared as text with the documents' files and is not resolved; a document whose file the +/// automation read roots do not allow does not count, and that check can look the file up on disk. +fn app_is_open(h: &Host, a: &[Data]) -> Answer { + let Data::String(path) = arg(a, 1) else { return Err(HostError::Type("getIsFileOpen needs a path, as a string".into())) }; + if path.len() > MAX_TEXT_BYTES { + return Err(HostError::Range("the path is too long".into())); + } + let unc = path.starts_with("\\\\") || path.starts_with("//"); + if path.is_empty() || path.contains('\0') || unc || path.split(['/', '\\']).any(|c| c == "..") { + return Err(HostError::Error("getIsFileOpen cannot check that path".into())); + } + let key = path_key(path); + let s = h.session.borrow(); + let open = s.documents().iter().filter_map(|d| d.path.as_deref()).any(|p| path_key(p) == key && crate::file_access::check_read(p).is_ok()); + Ok(Data::Bool(open)) +} + +// ---- Documents ---- + +fn docs_length(h: &Host, _: &[Data]) -> Answer { + Ok(num(float(h.session.borrow().documents().len() as u64))) +} + +fn app_ref(_: &Host, _: &[Data]) -> Answer { + Ok(host_ref("Application", &[])) +} + +/// `documents[i]`, and `documents["name"]` as `getByName` reads it. +fn docs_at(h: &Host, a: &[Data]) -> Answer { + let s = h.session.borrow(); + let at = match arg(a, 1) { + Data::Number(n) => whole(*n).and_then(|i| usize::try_from(i).ok()).and_then(|i| s.documents().get(i)), + Data::String(name) => match s.documents().iter().find(|d| d.title() == *name) { + None if !probing(a) => return Err(HostError::Error(NOT_FOUND.into())), + found => found, + }, + _ => None, + }; + Ok(at.map_or(Data::Undefined, |st| doc_ref(h, st.uid))) +} + +fn docs_by_name(h: &Host, a: &[Data]) -> Answer { + let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) }; + let s = h.session.borrow(); + let st = s.documents().iter().find(|d| d.title() == *name).ok_or_else(|| HostError::Error(NOT_FOUND.into()))?; + Ok(doc_ref(h, st.uid)) +} + +fn docs_index(h: &Host, a: &[Data]) -> Answer { + match arg(a, 1) { + Data::String(_) => docs_by_name(h, a), + Data::Number(_) => match docs_at(h, a)? { + Data::Undefined => Err(HostError::Error(NOT_FOUND.into())), + d => Ok(d), + }, + _ => Err(HostError::Type("give a name or an index".into())), + } +} + +/// `file.new`'s `artboardLayout.layout` and whether it runs right to left, for a +/// `DocumentArtboardLayout` value. +fn layout_of(d: &Data) -> std::result::Result<(&'static str, bool), HostError> { + let Data::String(s) = d else { return Err(HostError::Type("artboardLayout must be a DocumentArtboardLayout value".into())) }; + Ok(match s.strip_prefix("DocumentArtboardLayout.").unwrap_or("") { + "GridByRow" => ("gridByRow", false), + "GridByCol" => ("gridByColumn", false), + "Row" => ("row", false), + "Column" => ("column", false), + "RLGridByRow" => ("gridByRow", true), + "RLGridByCol" => ("gridByColumn", true), + "RLRow" => ("row", true), + _ => return Err(HostError::Type("artboardLayout must be a DocumentArtboardLayout value".into())), + }) +} + +/// The settings of a new document a script gives, each `None` when it was left out. +#[derive(Default)] +struct NewDoc<'a> { + color_space: Option<&'a Data>, + width: Option<&'a Data>, + height: Option<&'a Data>, + artboards: Option<&'a Data>, + layout: Option<&'a Data>, + spacing: Option<&'a Data>, + rows_or_cols: Option<&'a Data>, + units: Option<&'a Data>, + title: Option<&'a Data>, + preview: Option<&'a Data>, + resolution: Option<&'a Data>, +} + +/// `d`, unless it is `undefined`. +fn given(d: &Data) -> Option<&Data> { + (!matches!(d, Data::Undefined)).then_some(d) +} + +impl NewDoc<'_> { + /// `file.new`'s params for these settings, checked before anything is made. + fn params(&self) -> std::result::Result, HostError> { + let mut p = serde_json::Map::new(); + if let Some(d) = self.color_space { + let mode = match d { + Data::String(s) if s == "DocumentColorSpace.RGB" => "rgb", + Data::String(s) if s == "DocumentColorSpace.CMYK" => "cmyk", + _ => return Err(HostError::Type("colorSpace must be a DocumentColorSpace value".into())), + }; + p.insert("colorMode".into(), json!(mode)); + } + for (d, key) in [(self.width, "width"), (self.height, "height")] { + if let Some(d) = d { + let v = number(d, key)?; + if v <= 0.0 || v > MAX_SIZE { + return Err(HostError::Range(format!("{key} must be more than 0 and at most 3999856 points"))); + } + p.insert(key.into(), json!(v)); + } + } + let count = match self.artboards { + Some(d) => { + let n = number(d, "numArtBoards")?; + if n.fract() != 0.0 || !(1.0..=MAX_ARTBOARDS).contains(&n) { + return Err(HostError::Range("numArtBoards must be a whole number from 1 to 100".into())); + } + p.insert("artboards".into(), json!(n)); + n + } + None => 1.0, + }; + let mut layout = serde_json::Map::new(); + if let Some(d) = self.layout { + let (name, rtl) = layout_of(d)?; + layout.insert("layout".into(), json!(name)); + layout.insert("rightToLeft".into(), json!(rtl)); + } + if let Some(d) = self.spacing { + let v = number(d, "artboardSpacing")?; + if !(0.0..=crate::cmd::newdoc::MAX_SPACING).contains(&v) { + return Err(HostError::Range("artboardSpacing must be from 0 to 100000 points".into())); + } + layout.insert("spacing".into(), json!(v)); + } + if let Some(d) = self.rows_or_cols { + let n = number(d, "artboardRowsOrCols")?; + if n.fract() != 0.0 || n < 1.0 || n > count { + return Err(HostError::Range("artboardRowsOrCols must be a whole number from 1 to numArtBoards".into())); + } + // A grid filled by column takes the number of rows. + let by_column = layout.get("layout").is_some_and(|l| l == "gridByColumn"); + layout.insert((if by_column { "rows" } else { "columns" }).into(), json!(n)); + } + if !layout.is_empty() { + p.insert("artboardLayout".into(), Value::Object(layout)); + } + if let Some(d) = self.units { + let units = match d { + Data::String(s) => match s.strip_prefix("RulerUnits.").unwrap_or("") { + u @ ("Points" | "Picas" | "Inches" | "Millimeters" | "Centimeters" | "Pixels") => u, + "Qs" | "Unknown" => return Err(HostError::Range(format!("a new document cannot have the units {s}"))), + _ => return Err(HostError::Type("units must be a RulerUnits value".into())), + }, + _ => return Err(HostError::Type("units must be a RulerUnits value".into())), + }; + p.insert("units".into(), json!(units)); + } + if let Some(d) = self.title { + let Data::String(t) = d else { return Err(HostError::Type("title must be a string".into())) }; + if t.len() > MAX_TEXT_BYTES { + return Err(HostError::Range("the title is too long".into())); + } + p.insert("name".into(), json!(t)); + } + if let Some(d) = self.preview { + let mode = match d { + Data::String(s) if s == "DocumentPreviewMode.DefaultPreview" => "default", + // Pixel Preview is a setting of the app's view, which a script cannot turn on. + Data::String(s) if s == "DocumentPreviewMode.PixelPreview" => { + return Err(HostError::Error("DocumentPreviewMode.PixelPreview is not available yet".into())); + } + Data::String(s) if s == "DocumentPreviewMode.OverprintPreview" => "overprint", + _ => return Err(HostError::Type("previewMode must be a DocumentPreviewMode value".into())), + }; + p.insert("previewMode".into(), json!(mode)); + } + if let Some(d) = self.resolution { + let ppi = match d { + Data::String(s) if s == "DocumentRasterResolution.ScreenResolution" => 72, + Data::String(s) if s == "DocumentRasterResolution.MediumResolution" => 150, + Data::String(s) if s == "DocumentRasterResolution.HighResolution" => 300, + _ => return Err(HostError::Type("rasterResolution must be a DocumentRasterResolution value".into())), + }; + p.insert("rasterEffectsPpi".into(), json!(ppi)); + } + Ok(p) + } +} + +/// Runs `file.new` with `p`. → the new document, which is the active one. +fn new_document(h: &Host, p: serde_json::Map) -> Answer { + command(h, "file.new", &Value::Object(p))?; + let s = h.session.borrow(); + let st = s.active().ok_or_else(|| HostError::Error(NO_ACTIVE_DOCUMENT.into()))?; + Ok(doc_ref(h, st.uid)) +} + +/// `documents.add(colorSpace?, width?, height?, numArtBoards?, artboardLayout?, artboardSpacing?, +/// artboardRowsOrCols?)`: a new document from `file.new`, which becomes the active one. +fn docs_add(h: &Host, a: &[Data]) -> Answer { + let settings = NewDoc { + color_space: given(arg(a, 1)), + width: given(arg(a, 2)), + height: given(arg(a, 3)), + artboards: given(arg(a, 4)), + layout: given(arg(a, 5)), + spacing: given(arg(a, 6)), + rows_or_cols: given(arg(a, 7)), + ..NewDoc::default() + }; + new_document(h, settings.params()?) +} + +/// The error of `addDocument` with `showOptionsDialog` true: a script cannot open the New +/// Document dialog. +pub const DIALOG_UNAVAILABLE: &str = "Dialog unavailable"; + +/// The New Document profile a startup preset names (`None`: no profile), and the color mode the +/// basic presets give. +fn startup_preset(name: &str) -> Option<(Option<&'static str>, Option<&'static str>)> { + let name = name.strip_prefix("DocumentPresetType.").unwrap_or(name); + let squashed: String = name.chars().filter(|c| !c.is_whitespace()).collect::().to_ascii_lowercase(); + Some(match squashed.as_str() { + "basiccmyk" => (None, Some("cmyk")), + "basicrgb" => (None, Some("rgb")), + "video" | "film&video" => (Some("Film & Video"), None), + _ => { + let same = |p: &&str| p.chars().filter(|c| !c.is_whitespace()).collect::().eq_ignore_ascii_case(&squashed); + (Some(crate::cmd::newdoc::profile_names().find(same)?), None) + } + }) +} + +/// `documents.addDocument(startupPreset, presetSettings?, showOptionsDialog?)`: a new document from +/// the New Document profile `startupPreset` names, with the settings `presetSettings` gives in +/// place of the profile's. +fn docs_add_document(h: &Host, a: &[Data]) -> Answer { + let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("addDocument needs a startup preset's name".into())) }; + if name.len() > MAX_TEXT_BYTES { + return Err(HostError::Range("the startup preset's name is too long".into())); + } + let (profile, mode) = startup_preset(name).ok_or_else(|| HostError::Error(format!("no startup preset called {name}")))?; + // Only an object `new DocumentPreset()` made: a plain object such as `{width: 500}` is refused. + let settings = match given(arg(a, 2)) { + None | Some(Data::Null) => Vec::new(), + Some(d) => { + let i = preset_of(h, d).ok_or_else(|| HostError::Type("presetSettings must be a DocumentPreset".into()))?; + // The settings are charged as data passed to the call before they are copied. + let bytes = h.dom.presets.borrow()[i].iter().map(|(k, v)| k.len() as u64 + 2 + data_size(v)).sum::(); + h.charge_call(bytes)?; + h.dom.presets.borrow()[i].clone() + } + }; + let field = |k: &str| settings.iter().find(|(n, _)| n == k).map(|(_, v)| v).and_then(given); + for k in ["documentBleedLink", "documentBleedOffsetRect", "transparencyGrid"] { + if field(k).is_some_and(|d| !matches!(d, Data::Null)) { + return Err(HostError::Error(format!("DocumentPreset.{k} is not available yet"))); + } + } + let new = NewDoc { + color_space: field("colorMode"), + width: field("width"), + height: field("height"), + artboards: field("numArtboards"), + layout: field("artboardLayout"), + spacing: field("artboardSpacing"), + rows_or_cols: field("artboardRowsOrCols"), + units: field("units"), + title: field("title"), + preview: field("previewMode"), + resolution: field("rasterResolution"), + }; + let mut p = new.params()?; + match given(arg(a, 3)) { + None => {} + Some(Data::Bool(false)) => {} + Some(Data::Bool(true)) => return Err(HostError::Error(DIALOG_UNAVAILABLE.into())), + Some(_) => return Err(HostError::Type("showOptionsDialog must be true or false".into())), + } + // The document starts from the first preset of the profile's category (Print: Letter). + let first = profile.and_then(|n| crate::cmd::newdoc::category(&h.session.borrow(), n)?.into_iter().next()); + if let Some(first) = first { + p.insert("preset".into(), json!(first.name)); + } + p.insert("profile".into(), profile.map_or(Value::Null, |n| json!(n))); + if let Some(m) = mode { + p.entry("colorMode").or_insert_with(|| json!(m)); + } + // A profile whose file could not be read throws, and the document `file.new` made with the + // defaults is put back, with the Recent sizes as they were. + atomically(h, |h| { + let (_, value) = command_value(h, "file.new", &Value::Object(p))?; + if let Some(e) = value.get("profileError") { + let profile = e["profile"].as_str().unwrap_or_default(); + let reason = e["reason"].as_str().unwrap_or_default(); + return Err(HostError::Error(format!("the New Document profile {profile} could not be read: {reason}"))); + } + // Each warning from reading the profile's file goes to the console. + for w in value.get("warnings").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str) { + super::each_line(&format!("addDocument: {w}"), |line, cut| h.line(super::console::Entry::Log(line), cut)); + } + let s = h.session.borrow(); + let st = s.active().ok_or_else(|| HostError::Error(NO_ACTIVE_DOCUMENT.into()))?; + Ok(doc_ref(h, st.uid)) + }) +} + +/// `new DocumentPreset()`: a record of new-document settings with the defaults the help page +/// gives; the other settings are +/// left out. The settings stay with the run, which hands the script an object of the +/// `DocumentPreset` class. +fn new_preset(h: &Host) -> Answer { + let mut presets = h.dom.presets.borrow_mut(); + if presets.len() >= MAX_PRESETS { + return Err(HostError::Range(format!("a script can make at most {MAX_PRESETS} DocumentPresets"))); + } + let item = |k: &str, v: Data| (k.to_string(), v); + presets.push(vec![ + item("artboardLayout", text("DocumentArtboardLayout.GridByRow")), + item("artboardRowsOrCols", num(1.0)), + item("artboardSpacing", num(20.0)), + item("height", num(792.0)), + item("numArtboards", num(1.0)), + item("width", num(612.0)), + ]); + Ok(host_ref("DocumentPreset", &[float(h.run), float(presets.len() as u64 - 1)])) +} + +/// The most `DocumentPreset` objects one run can make. +const MAX_PRESETS: usize = 10_000; + +/// The settings a `DocumentPreset` has, each a property a script reads and assigns. +const PRESET_FIELDS: &[&str] = &[ + "artboardLayout", + "artboardRowsOrCols", + "artboardSpacing", + "colorMode", + "documentBleedLink", + "documentBleedOffsetRect", + "height", + "numArtboards", + "previewMode", + "rasterResolution", + "title", + "transparencyGrid", + "units", + "width", +]; + +/// The index in the run's presets of the `DocumentPreset` `d` is, when it is one this run made. +fn preset_of(h: &Host, d: &Data) -> Option { + let handle = handle_of(d, "DocumentPreset")?; + let [run, i] = handle.as_slice() else { return None }; + if whole(*run) != Some(h.run) { + return None; + } + let i = usize::try_from(whole(*i)?).ok()?; + (i < h.dom.presets.borrow().len()).then_some(i) +} + +/// The getter and setter of the `DocumentPreset` setting `key`: an unset one reads `undefined`, and +/// a value is checked when `addDocument` uses it. +fn preset_field(link: &Link, key: &'static str) -> HostMember { + let not_preset = || HostError::Type("this is not a DocumentPreset".into()); + let l = link.clone(); + let get: HostFunction = Rc::new(move |a: Vec| { + let h = current(&l)?; + // The value handed back is charged as the setter charges it, before it is copied. + let i = preset_of(&h, arg(&a, 0)); + let bytes = i.map_or(0, |i| h.dom.presets.borrow()[i].iter().find(|(k, _)| k == key).map_or(0, |(_, v)| data_size(v))); + h.charge_call(16 + bytes)?; + let i = i.ok_or_else(not_preset)?; + let presets = h.dom.presets.borrow(); + Ok(presets[i].iter().find(|(k, _)| k == key).map_or(Data::Undefined, |(_, v)| v.clone())) + }); + let l = link.clone(); + let set: HostFunction = Rc::new(move |a: Vec| { + let h = current(&l)?; + let value = arg(&a, 1).clone(); + h.charge_call(16 + data_size(&value))?; + let i = preset_of(&h, arg(&a, 0)).ok_or_else(not_preset)?; + let mut presets = h.dom.presets.borrow_mut(); + let fields = &mut presets[i]; + match fields.iter_mut().find(|(k, _)| k == key) { + Some((_, v)) => *v = value, + None => fields.push((key.to_string(), value)), + } + Ok(Data::Undefined) + }); + HostMember::Property { get, set } +} + +// ---- Document ---- + +fn this_doc(h: &Host, a: &[Data]) -> std::result::Result { + doc_of(h, arg(a, 0), "Document") +} + +fn doc_typename(h: &Host, a: &[Data]) -> Answer { + this_doc(h, a)?; + Ok(text("Document")) +} + +fn doc_parent(h: &Host, a: &[Data]) -> Answer { + this_doc(h, a)?; + Ok(host_ref("Application", &[])) +} + +fn doc_name(h: &Host, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + Ok(text(with_doc(h, doc, |_, st| st.title()))) +} + +fn doc_size(h: &Host, a: &[Data], width: bool) -> Answer { + let doc = this_doc(h, a)?; + with_doc(h, doc, |_, st| { + let r = st.doc.artboards.first().map(|b| b.rect).ok_or_else(|| HostError::Error("the document has no artboards".into()))?; + Ok(num(if width { r.width() } else { r.height() })) + }) +} + +fn doc_width(h: &Host, a: &[Data]) -> Answer { + doc_size(h, a, true) +} + +fn doc_height(h: &Host, a: &[Data]) -> Answer { + doc_size(h, a, false) +} + +fn doc_units(h: &Host, a: &[Data]) -> Answer { + use crate::doc::Unit; + let doc = this_doc(h, a)?; + let unit = with_doc(h, doc, |_, st| st.doc.units); + Ok(text(match unit { + Unit::Points => "RulerUnits.Points", + Unit::Picas => "RulerUnits.Picas", + Unit::Inches => "RulerUnits.Inches", + Unit::Millimeters => "RulerUnits.Millimeters", + Unit::Centimeters => "RulerUnits.Centimeters", + Unit::Pixels => "RulerUnits.Pixels", + Unit::Q => "RulerUnits.Qs", + _ => "RulerUnits.Unknown", + })) +} + +fn doc_color_space(h: &Host, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + let cmyk = with_doc(h, doc, |_, st| st.doc.color_mode == crate::doc::ColorMode::Cmyk); + Ok(text(if cmyk { "DocumentColorSpace.CMYK" } else { "DocumentColorSpace.RGB" })) +} + +fn doc_ruler_origin(h: &Host, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + with_doc(h, doc, |_, st| { + let f = frame(st)?; + Ok(pair(f.to_script(Coords::Document, st.doc.ruler_origin_for(active_artboard(st))))) + }) +} + +/// `rulerOrigin = [x, y]`, in document coordinates: `document.setRulerOrigin` for the active +/// artboard. The art stays where it is. +fn doc_set_ruler_origin(h: &Host, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + let p = point(arg(a, 1), "rulerOrigin")?; + let (to, now, artboard) = with_doc(h, doc, |_, st| { + let f = frame(st)?; + let artboard = active_artboard(st); + Ok::<_, HostError>((f.to_document(Coords::Document, p), st.doc.ruler_origin_for(artboard), artboard)) + })?; + if to.distance(now) > 1e-9 { + on_doc(h, doc.uid, false, |h| command(h, "document.setRulerOrigin", &json!({"x": to.x, "y": to.y, "artboard": artboard})))?; + } + Ok(Data::Undefined) +} + +/// `convertCoordinate(point, source, destination)`: `point` from one coordinate system of the +/// document to another. Nothing changes. +fn doc_convert(h: &Host, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + let p = point(arg(a, 1), "point")?; + let (from, to) = (coords_of(arg(a, 2))?, coords_of(arg(a, 3))?); + with_doc(h, doc, |_, st| { + let f = frame(st)?; + Ok(pair(f.to_script(to, f.to_document(from, p)))) + }) +} + +fn doc_page_items(h: &Host, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + Ok(host_ref("PageItems", &[float(h.run), float(doc.uid)])) +} + +fn doc_selection(h: &Host, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + selection_of(h, doc.uid) +} + +/// The selection of the document `uid`: a new list of the selected objects, topmost first as +/// `pageItems` lists them, empty when nothing is selected. +fn selection_of(h: &Host, uid: u64) -> Answer { + let s = h.session.borrow(); + let st = s.documents().iter().find(|d| d.uid == uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?; + let picked: HashSet = st.selection.objects.iter().copied().filter(|i| st.doc.node(*i).and_then(typename).is_some()).collect(); + if picked.len() > MAX_LISTED { + return Err(HostError::Range(format!("the selection has more than {MAX_LISTED} objects"))); + } + // Only the selected objects are ordered, by their place in the tree, so the cost follows the + // size of the selection and not of the document. `pageItems` walks each list of children + // topmost first and puts a group before the objects in it: a higher index comes first, and an + // ancestor's path, a prefix of its descendants' paths, sorts before them. + let mut placed: Vec<(Vec>, NodeId)> = Vec::with_capacity(picked.len()); + let mut unplaced: Vec = Vec::new(); + let mut seen: HashSet = HashSet::with_capacity(picked.len()); + let mut steps = 0u64; + for id in st.selection.objects.iter().copied().filter(|i| picked.contains(i) && seen.insert(*i)) { + match st.doc.index_path(id) { + Some(path) => { + steps += path.len() as u64; + placed.push((path.into_iter().map(std::cmp::Reverse).collect(), id)); + } + // A selected object outside the tree's walk still comes last, in the order it was + // selected. + None => unplaced.push(id), + } + } + placed.sort(); + let ids: Vec = placed.into_iter().map(|(_, id)| id).chain(unplaced).collect(); + h.charge_call(steps + 16 * ids.len() as u64)?; + Ok(Data::Array(ids.iter().map(|i| item_ref(h, st, *i)).collect())) +} + +/// The ids an assignment to a document's selection gives: one page item, a list of them, `null` or +/// `[]`. Every one must be an object of that document that can be selected. +fn selection_ids(h: &Host, doc: Doc, v: &Data) -> std::result::Result, HostError> { + let list: Vec<&Data> = match v { + Data::Null | Data::Undefined => Vec::new(), + Data::Array(a) if a.len() > MAX_LISTED => return Err(HostError::Range(format!("a selection takes at most {MAX_LISTED} objects"))), + Data::Array(a) => a.iter().collect(), + d => vec![d], + }; + let mut ids: Vec = Vec::with_capacity(list.len()); + // The document is read once for every object: nothing changes it while the list is checked. + let (d, isolation, guides_locked) = with_doc(h, doc, |s, st| (st.doc.clone(), st.isolation, s.guides_locked())); + let locks = d.locked_artboards(); + for v in list { + let item = item_of(h, v)?; + // A path made into a guide is not selected while Lock Guides is on, as the selection + // commands leave it out. + let ok = item.doc.uid == doc.uid + && crate::cmd::select::is_selectable(&d, isolation, &locks, item.id) + && !(guides_locked && crate::is_guide_path(&d, item.id)); + if !ok { + let name = with_doc(h, item.doc, |_, st| st.doc.node(item.id).and_then(typename).unwrap_or("page item")); + return Err(HostError::Error(format!("Cannot select {name} {}", item.id.0))); + } + if !ids.contains(&item.id) { + ids.push(item.id); + } + } + Ok(ids) +} + +fn doc_set_selection(h: &Host, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + let ids = selection_ids(h, doc, arg(a, 1))?; + set_selection(h, doc, ids) +} + +/// Makes `ids` the selection of `doc`, with no command when it already is: the same objects, each +/// selected as a whole (no dynamic symbol instance's object or Objects on Path group's object +/// chosen in it), and no ruler guide, slice, key or Layers panel target. +fn set_selection(h: &Host, doc: Doc, ids: Vec) -> Answer { + let same = with_doc(h, doc, |_, st| { + let sel = &st.selection; + sel.objects == ids + && sel.target.is_none() + && sel.symbol_part.is_none() + && sel.on_path_member.is_none() + && sel.anchors.is_empty() + && sel.segments.is_empty() + && sel.guides.is_empty() + && sel.slices.is_empty() + && sel.key.is_none() + && sel.key_guide.is_none() + && sel.key_anchor.is_none() + }); + if same { + return Ok(Data::Undefined); + } + on_doc(h, doc.uid, false, |h| { + if ids.is_empty() { + command(h, "select.none", &json!({})) + } else { + command(h, "select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})) + } + })?; + Ok(Data::Undefined) +} + +// ---- PageItems ---- + +fn items_doc(h: &Host, a: &[Data]) -> std::result::Result { + doc_of(h, arg(a, 0), "PageItems") +} + +fn items_length(h: &Host, a: &[Data]) -> Answer { + let doc = items_doc(h, a)?; + let n = with_doc(h, doc, |_, st| page_items(h, st).len()); + Ok(num(float(n as u64))) +} + +fn items_typename(h: &Host, a: &[Data]) -> Answer { + items_doc(h, a)?; + Ok(text("PageItems")) +} + +fn items_parent(h: &Host, a: &[Data]) -> Answer { + let doc = items_doc(h, a)?; + Ok(doc_ref(h, doc.uid)) +} + +/// Whether an indexer was called for `name in collection` ([`vectorcraft_js::HostClass::index`]), +/// where a name nothing has gives `undefined` instead of the `Not found` error a read throws. +fn probing(a: &[Data]) -> bool { + matches!(arg(a, 2), Data::Bool(true)) +} + +/// `pageItems[i]`, and `pageItems["name"]` as `getByName` reads it. +fn items_at(h: &Host, a: &[Data]) -> Answer { + let doc = items_doc(h, a)?; + if let Data::String(_) = arg(a, 1) { + return match items_by_name(h, a) { + Err(HostError::Error(e)) if e == NOT_FOUND && probing(a) => Ok(Data::Undefined), + r => r, + }; + } + let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) }; + let Some(i) = whole(*n).and_then(|i| usize::try_from(i).ok()) else { return Ok(Data::Undefined) }; + Ok(with_doc(h, doc, |_, st| page_items(h, st).get(i).map_or(Data::Undefined, |id| item_ref(h, st, *id)))) +} + +fn items_by_name(h: &Host, a: &[Data]) -> Answer { + let doc = items_doc(h, a)?; + let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) }; + with_doc(h, doc, |_, st| { + let ids = page_items(h, st); + h.charge_call(ids.len() as u64)?; + let id = ids.iter().find(|i| st.doc.node(**i).and_then(|n| n.name.as_deref()) == Some(name.as_str())); + id.map(|id| item_ref(h, st, *id)).ok_or_else(|| HostError::Error(NOT_FOUND.into())) + }) +} + +fn items_index(h: &Host, a: &[Data]) -> Answer { + match arg(a, 1) { + Data::String(_) => items_by_name(h, a), + Data::Number(_) => match items_at(h, a)? { + Data::Undefined => Err(HostError::Error(NOT_FOUND.into())), + d => Ok(d), + }, + _ => Err(HostError::Type("give a name or an index".into())), + } +} + +/// `pageItems.removeAll()`: deletes every object of the document in one command. A hidden or +/// locked object, or one in a hidden or locked layer or group, stops it before anything is deleted, +/// and so does an object on a locked artboard. +fn items_remove_all(h: &Host, a: &[Data]) -> Answer { + let doc = items_doc(h, a)?; + let (ids, refused, on_locked) = with_doc(h, doc, |_, st| { + let ids = top_items(&st.doc); + let whole = |id: &NodeId| editable(&st.doc, *id) && st.doc.node(*id).is_some_and(all_editable); + let refused: Vec = ids.iter().filter(|i| !whole(i)).map(|i| i.0).take(20).collect(); + let locks = st.doc.locked_artboards(); + let on_locked: Vec = ids.iter().filter(|i| locks.holds_id(**i)).map(|i| i.0).take(20).collect(); + (ids, refused, on_locked) + }); + if !refused.is_empty() { + let list = refused.iter().map(u64::to_string).collect::>().join(", "); + return Err(HostError::Error(format!("cannot delete hidden or locked objects: {list}"))); + } + if !on_locked.is_empty() { + let list = on_locked.iter().map(u64::to_string).collect::>().join(", "); + return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {list}"))); + } + if !ids.is_empty() { + on_doc(h, doc.uid, true, |h| command(h, "edit.clear", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})))?; + } + Ok(Data::Undefined) +} + +// ---- PageItem ---- + +fn this_item(h: &Host, a: &[Data]) -> std::result::Result { + item_of(h, arg(a, 0)) +} + +/// Reads the item `this` names with `f`, given its document and node. +fn read_item(h: &Host, a: &[Data], f: impl FnOnce(&DocState, &crate::doc::Node) -> Answer) -> Answer { + let item = this_item(h, a)?; + with_doc(h, item.doc, |_, st| match st.doc.node(item.id) { + Some(n) => f(st, n), + None => Err(HostError::Error(STALE_ITEM.into())), + }) +} + +fn item_typename(h: &Host, a: &[Data]) -> Answer { + read_item(h, a, |_, n| Ok(text(typename(n).unwrap_or("PageItem")))) +} + +fn item_parent(h: &Host, a: &[Data]) -> Answer { + let item = this_item(h, a)?; + Ok(with_doc(h, item.doc, |_, st| st.doc.parent_of(item.id).map_or(Data::Null, |p| item_ref(h, st, p)))) +} + +fn item_name(h: &Host, a: &[Data]) -> Answer { + read_item(h, a, |_, n| Ok(text(n.name.clone().unwrap_or_default()))) +} + +/// Runs `object.setProps` with `props` for the item, unless `unchanged` says the node has them. +fn set_props(h: &Host, a: &[Data], unchanged: impl FnOnce(&crate::doc::Node) -> bool, props: Value) -> Answer { + let item = this_item(h, a)?; + let same = with_doc(h, item.doc, |_, st| st.doc.node(item.id).is_some_and(unchanged)); + if !same { + let mut p = props; + if let Some(o) = p.as_object_mut() { + o.insert("ids".into(), json!([item.id.0])); + } + edit_item(h, item, "object.setProps", &p)?; + } + Ok(Data::Undefined) +} + +/// The text a string property such as `name` or `note` is given: a number or a Boolean becomes the +/// text `String(value)` gives, and any other value that is not a string is refused. +fn text_arg(v: &Data, what: &str) -> std::result::Result { + match v { + Data::String(s) => Ok(s.clone()), + Data::Number(n) => Ok(vectorcraft_js::number_to_string(*n)), + Data::Bool(b) => Ok(b.to_string()), + _ => Err(HostError::Type(format!("{what} must be a string"))), + } +} + +/// `name = value`: a number or a Boolean becomes the text `String(value)` gives. +fn item_set_name(h: &Host, a: &[Data]) -> Answer { + let name = &text_arg(arg(a, 1), "name")?; + if name.len() > MAX_TEXT_BYTES { + return Err(HostError::Range("the name is too long".into())); + } + set_props(h, a, |n| n.name.as_deref().unwrap_or("") == name, json!({"name": name})) +} + +fn note_of(n: &crate::doc::Node) -> &str { + n.extras().attrs.as_deref().map_or("", |a| a.note.as_str()) +} + +fn item_note(h: &Host, a: &[Data]) -> Answer { + read_item(h, a, |_, n| Ok(text(note_of(n)))) +} + +/// `note = text`: the Attributes panel's note, set with `attributes.set`, which trims it. A number +/// or a Boolean becomes the text `String(value)` gives. +fn item_set_note(h: &Host, a: &[Data]) -> Answer { + let note = &text_arg(arg(a, 1), "note")?; + if note.len() > MAX_TEXT_BYTES { + return Err(HostError::Range("the note is too long".into())); + } + let item = this_item(h, a)?; + let same = with_doc(h, item.doc, |_, st| st.doc.node(item.id).is_some_and(|n| note_of(n) == note.trim())); + if !same { + edit_item(h, item, "attributes.set", &json!({"ids": [item.id.0], "note": note}))?; + } + Ok(Data::Undefined) +} + +/// Refuses a change to the item's appearance, place, stacking order or size while a layer it is in +/// is hidden or locked. Its name and note may still change. +fn refuse_in_closed_layer(h: &Host, item: Item) -> std::result::Result<(), HostError> { + let refused = with_doc(h, item.doc, |_, st| { + let d = &st.doc; + let closed = |i: &NodeId| d.node(*i).is_some_and(|n| matches!(n.kind, NodeKind::Layer { .. }) && (!n.visible || n.locked)); + d.ancestry(item.id).is_some_and(|a| a.iter().any(closed)).then(|| d.node(item.id).and_then(typename).unwrap_or("page item")) + }); + match refused { + Some(name) => Err(HostError::Error(format!("Cannot edit {name} {}: a layer it is in is hidden or locked", item.id.0))), + None => Ok(()), + } +} + +fn item_hidden(h: &Host, a: &[Data]) -> Answer { + read_item(h, a, |_, n| Ok(Data::Bool(!n.visible))) +} + +fn item_set_hidden(h: &Host, a: &[Data]) -> Answer { + let hidden = boolean(arg(a, 1), "hidden")?; + refuse_in_closed_layer(h, this_item(h, a)?)?; + set_props(h, a, |n| n.visible != hidden, json!({"visible": !hidden})) +} + +fn item_locked(h: &Host, a: &[Data]) -> Answer { + read_item(h, a, |_, n| Ok(Data::Bool(n.locked))) +} + +fn item_set_locked(h: &Host, a: &[Data]) -> Answer { + let locked = boolean(arg(a, 1), "locked")?; + refuse_in_closed_layer(h, this_item(h, a)?)?; + set_props(h, a, |n| n.locked == locked, json!({"locked": locked})) +} + +fn item_opacity(h: &Host, a: &[Data]) -> Answer { + read_item(h, a, |_, n| Ok(num((f64::from(n.opacity) * 100.0 * 1e4).round() / 1e4))) +} + +fn item_set_opacity(h: &Host, a: &[Data]) -> Answer { + let v = number(arg(a, 1), "opacity")?; + if !(0.0..=100.0).contains(&v) { + return Err(HostError::Range("opacity must be from 0 to 100".into())); + } + // A value the getter reports for the item's opacity sends the opacity it has, and + // `object.setProps` finds the no-op itself: an opacity a graph mark or label already has still + // replaces the one the graph keeps for its series or kind. + // The opacity the item already has may be assigned while its layer is hidden or locked, unless + // it would still replace the opacity a graph keeps for the item's series or kind. + let item = this_item(h, a)?; + let (now, keeps_other) = with_doc(h, item.doc, |_, st| { + let d = &st.doc; + // Only the exact number the getter reports counts as the same opacity. + let now = d.node(item.id).map(|n| f64::from(n.opacity) * 100.0).filter(|now| (now * 1e4).round() / 1e4 == v); + let keeps_other = + crate::cmd::graph::series_object_opacity_differs(d, &[item.id]) || crate::cmd::graph::label_object_opacity_differs(d, &[item.id]); + (now, keeps_other) + }); + if now.is_none() || keeps_other { + refuse_in_closed_layer(h, item)?; + } + set_props(h, a, |_| false, json!({"opacity": now.unwrap_or(v)})) +} + +fn item_selected(h: &Host, a: &[Data]) -> Answer { + let item = this_item(h, a)?; + Ok(Data::Bool(with_doc(h, item.doc, |_, st| st.selection.objects.contains(&item.id)))) +} + +fn item_set_selected(h: &Host, a: &[Data]) -> Answer { + let item = this_item(h, a)?; + let on = boolean(arg(a, 1), "selected")?; + if with_doc(h, item.doc, |_, st| st.selection.objects.contains(&item.id)) == on { + return Ok(Data::Undefined); + } + // Adding or removing the one object keeps how the others are selected (their direct-selected + // anchors and segments, and the key object). + let ids = if on { selection_ids(h, item.doc, arg(a, 0))? } else { vec![item.id] }; + let id = if on { "select.add" } else { "select.toggle" }; + on_doc(h, item.doc.uid, false, |h| command(h, id, &json!({"ids": ids.iter().map(|i| i.0).collect::>()})))?; + Ok(Data::Undefined) +} + +/// The item's geometric bounds (`visual`: its visible bounds) in document coordinates and the +/// document's [`Frame`]. An object with nothing in it, such as an empty group or a compound path +/// whose paths moved out, has no bounds: its bounds read as zeros, and moving or resizing it does +/// nothing. +fn item_rect(h: &Host, item: Item, visual: bool) -> std::result::Result<(Option, Frame), HostError> { + with_doc(h, item.doc, |_, st| Ok((st.doc.bounds_of(&[item.id], visual), frame(st)?))) +} + +fn bounds(h: &Host, a: &[Data], visual: bool) -> Answer { + let item = this_item(h, a)?; + match item_rect(h, item, visual)? { + (Some(r), f) => Ok(f.bounds(h.dom.coords.get(), r)), + (None, _) => Ok(Data::Array(vec![num(0.0), num(0.0), num(0.0), num(0.0)])), + } +} + +fn item_geometric(h: &Host, a: &[Data]) -> Answer { + bounds(h, a, false) +} + +fn item_visible(h: &Host, a: &[Data]) -> Answer { + bounds(h, a, true) +} + +fn item_position(h: &Host, a: &[Data]) -> Answer { + let item = this_item(h, a)?; + match item_rect(h, item, false)? { + (Some(r), f) => Ok(pair(f.to_script(h.dom.coords.get(), Point::new(r.x0, r.y0)))), + (None, _) => Ok(pair([0.0, 0.0])), + } +} + +fn item_left(h: &Host, a: &[Data]) -> Answer { + match item_position(h, a)? { + Data::Array(p) => Ok(p.into_iter().next().unwrap_or(Data::Undefined)), + d => Ok(d), + } +} + +fn item_top(h: &Host, a: &[Data]) -> Answer { + match item_position(h, a)? { + Data::Array(p) => Ok(p.into_iter().nth(1).unwrap_or(Data::Undefined)), + d => Ok(d), + } +} + +fn item_width(h: &Host, a: &[Data]) -> Answer { + let item = this_item(h, a)?; + Ok(num(item_rect(h, item, false)?.0.map_or(0.0, |r| r.width()))) +} + +fn item_height(h: &Host, a: &[Data]) -> Answer { + let item = this_item(h, a)?; + Ok(num(item_rect(h, item, false)?.0.map_or(0.0, |r| r.height()))) +} + +/// Moves the item so its top-left corner is at `x` and `y` in script coordinates (`None`: that one +/// stays). +fn move_to(h: &Host, a: &[Data], x: Option, y: Option) -> Answer { + let item = this_item(h, a)?; + refuse_in_closed_layer(h, item)?; + let (Some(r), f) = item_rect(h, item, false)? else { return Ok(Data::Undefined) }; + let c = h.dom.coords.get(); + let now = f.to_script(c, Point::new(r.x0, r.y0)); + let to = f.to_document(c, [x.unwrap_or(now[0]), y.unwrap_or(now[1])]); + let (dx, dy) = (to.x - r.x0, to.y - r.y0); + if dx.abs() > 1e-9 || dy.abs() > 1e-9 { + edit_item(h, item, "object.move", &json!({"ids": [item.id.0], "dx": dx, "dy": dy}))?; + } + Ok(Data::Undefined) +} + +fn item_set_position(h: &Host, a: &[Data]) -> Answer { + let p = point(arg(a, 1), "position")?; + move_to(h, a, Some(p[0]), Some(p[1])) +} + +fn item_set_left(h: &Host, a: &[Data]) -> Answer { + let x = coordinate(arg(a, 1), "left")?; + move_to(h, a, Some(x), None) +} + +fn item_set_top(h: &Host, a: &[Data]) -> Answer { + let y = coordinate(arg(a, 1), "top")?; + move_to(h, a, None, Some(y)) +} + +/// Scales the item about its top-left corner along the page's axes to `size` points wide (`width`) +/// or tall, so the page-aligned bounds that `width` and `height` read have that size, rotated +/// objects included. +fn resize(h: &Host, a: &[Data], width: bool) -> Answer { + let what = if width { "width" } else { "height" }; + let size = number(arg(a, 1), what)?; + if size <= 0.0 || size > MAX_SIZE { + return Err(HostError::Range(format!("{what} must be more than 0 and at most 3999856 points"))); + } + let item = this_item(h, a)?; + refuse_in_closed_layer(h, item)?; + let (Some(r), _) = item_rect(h, item, false)? else { return Ok(Data::Undefined) }; + let now = if width { r.width() } else { r.height() }; + if now <= 0.0 { + return Err(HostError::Error(format!("the object has no {what} to scale"))); + } + if (now - size).abs() < 1e-9 { + return Ok(Data::Undefined); + } + let pct = size / now * 100.0; + let (sx, sy) = if width { (pct, 100.0) } else { (100.0, pct) }; + let p = json!({"ids": [item.id.0], "sx": sx, "sy": sy, "origin": [r.x0, r.y0], "basis": "page"}); + edit_item(h, item, "object.scale", &p)?; + Ok(Data::Undefined) +} + +fn item_set_width(h: &Host, a: &[Data]) -> Answer { + resize(h, a, true) +} + +fn item_set_height(h: &Host, a: &[Data]) -> Answer { + resize(h, a, false) +} + +/// `editable`: false for an object that is hidden or locked, in a hidden or locked layer or group, +/// or on a locked artboard. +fn item_editable(h: &Host, a: &[Data]) -> Answer { + let item = this_item(h, a)?; + Ok(Data::Bool(with_doc(h, item.doc, |_, st| editable(&st.doc, item.id) && !on_locked_artboard(h, st, item.id)))) +} + +/// The item's place in its parent's stacking order, from 1 at the bottom. +fn item_z_order_position(h: &Host, a: &[Data]) -> Answer { + let item = this_item(h, a)?; + let at = with_doc(h, item.doc, |_, st| st.doc.position(item.id).map(|(_, i, _)| i)); + at.map(|i| num(float(i as u64 + 1))).ok_or_else(|| HostError::Error(STALE_ITEM.into())) +} + +/// `remove()`: deletes the object. A hidden or locked object, one in a hidden or locked layer or +/// group, a group holding one, or an object on a locked artboard is refused, as [`items_remove_all`] +/// refuses it. A compound path whose last path this is stays, empty. +fn item_remove(h: &Host, a: &[Data]) -> Answer { + let item = this_item(h, a)?; + let (whole, on_locked) = with_doc(h, item.doc, |_, st| { + (editable(&st.doc, item.id) && st.doc.node(item.id).is_some_and(all_editable), st.doc.on_locked_artboard(item.id)) + }); + if !whole { + return Err(HostError::Error(format!("cannot delete hidden or locked objects: {}", item.id.0))); + } + if on_locked { + return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {}", item.id.0))); + } + // A compound path whose last path this is stays, empty, as it does after `move`. + edit_item(h, item, "edit.clear", &json!({"ids": [item.id.0], "keepEmpty": true}))?; + Ok(Data::Undefined) +} + +/// The error of `remove()` and `removeAll()` for an object on a locked artboard. +const ON_LOCKED_ARTBOARD: &str = "cannot delete objects on a locked artboard"; + +/// The error of `move` and `duplicate` given an object of another document. +pub const CROSS_DOCUMENT: &str = "Cross-document placement is not available"; + +/// An `ElementPlacement` value. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Placement { + /// `INSIDE` and `PLACEATBEGINNING`: on top of the container's contents. + Top, + /// `PLACEATEND`: under the container's contents. + Bottom, + /// `PLACEBEFORE`: directly above the relative object, in its parent. + Above, + /// `PLACEAFTER`: directly below the relative object, in its parent. + Below, +} + +fn placement_of(d: &Data) -> std::result::Result { + match d { + Data::Undefined => Ok(Placement::Top), + Data::String(s) => match s.as_str() { + "ElementPlacement.INSIDE" | "ElementPlacement.PLACEATBEGINNING" => Ok(Placement::Top), + "ElementPlacement.PLACEATEND" => Ok(Placement::Bottom), + "ElementPlacement.PLACEBEFORE" => Ok(Placement::Above), + "ElementPlacement.PLACEAFTER" => Ok(Placement::Below), + _ => Err(HostError::Type("insertionLocation must be an ElementPlacement value".into())), + }, + _ => Err(HostError::Type("insertionLocation must be an ElementPlacement value".into())), + } +} + +/// Where `move` and `duplicate` put an object relative to `target`: the parent it goes into and +/// the target it goes beside, checked against the object `item` before anything changes. +struct Destination { + parent: NodeId, + beside: Option, + how: Placement, +} + +/// The object a relative object of `move` or `duplicate` names: a page item or a layer of the +/// same document as `item`. An object may go directly above or below itself: a copy goes there, as +/// `layer.move` puts copies, and a move there leaves the object where it is. +fn destination(h: &Host, item: Item, target: &Data, how: &Data) -> std::result::Result { + let how = placement_of(how)?; + let beside = matches!(how, Placement::Above | Placement::Below); + let handle = handle_of(target, "PageItem").or_else(|| handle_of(target, "Layer")); + let Some(&[run, uid, high, low]) = handle.as_deref() else { + if handle_of(target, "Document").is_some() { + return Err(HostError::Error("a document as the relative object is not available yet".into())); + } + return Err(HostError::Type("the relative object must be a page item or a layer".into())); + }; + let doc = find_doc(h, run, uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + if doc.uid != item.doc.uid { + return Err(HostError::Error(CROSS_DOCUMENT.into())); + } + let target = id_of(high, low).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + with_doc(h, doc, |_, st| { + let d = &st.doc; + let t = d.node(target).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + let inside = d.ancestry(target).is_some_and(|a| a.iter().any(|i| *i == item.id && *i != target)); + if inside || (target == item.id && !beside) { + return Err(HostError::Error("an object cannot go into itself".into())); + } + let (parent, beside) = match how { + Placement::Top | Placement::Bottom => { + if !matches!(t.kind, NodeKind::Layer { .. } | NodeKind::Group { .. }) { + return Err(HostError::Error(format!("{} cannot hold objects", typename(t).unwrap_or("Layer")))); + } + (target, None) + } + Placement::Above | Placement::Below => { + let parent = d.parent_of(target).ok_or_else(|| HostError::Error("an object cannot go beside a top-level layer".into()))?; + (parent, Some(target)) + } + }; + if !editable(d, parent) { + return Err(HostError::Error("the layer or group is hidden or locked".into())); + } + // An object on a locked artboard is not moved, as `editable` reads false for it. + if !editable(d, item.id) || on_locked_artboard(h, st, item.id) { + let name = d.node(item.id).and_then(typename).unwrap_or("page item"); + return Err(HostError::Error(format!("Cannot move {name} {}", item.id.0))); + } + Ok(Destination { parent, beside, how }) + }) +} + +/// Moves the object `id` to `to` with `node.move`, its index worked out once it has left its place. +fn place(h: &Host, doc: Doc, id: NodeId, to: &Destination) -> std::result::Result<(), HostError> { + let index = with_doc(h, doc, |_, st| { + let d = &st.doc; + let from = d.position(id); + let count = d.children(Some(to.parent)).map_or(0, Vec::len) - usize::from(from.is_some_and(|(p, ..)| p == Some(to.parent))); + let clips = d.node(to.parent).is_some_and(crate::doc::Node::clips) && count > 0; + let at = match (to.how, to.beside) { + (Placement::Top, _) => count, + (Placement::Bottom, _) => 0, + (how, Some(b)) => { + let (_, mut i, _) = d.position(b).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + if let Some((Some(p), j, _)) = from + && p == to.parent + && j < i + { + i -= 1; + } + if how == Placement::Above { i + 1 } else { i } + } + (_, None) => count, + }; + Ok::<_, HostError>(if clips { at.max(1) } else { at }) + })?; + let now = with_doc(h, doc, |_, st| st.doc.position(id)); + if now.is_some_and(|(p, i, _)| p == Some(to.parent) && i == index) { + return Ok(()); + } + on_doc(h, doc.uid, true, |h| command(h, "node.move", &json!({"id": id.0, "parent": to.parent.0, "index": index})))?; + Ok(()) +} + +/// `move(relativeObject, insertionLocation?)`: moves the item into or beside `relativeObject`, a +/// page item or a layer of its document (`insertionLocation` defaults to `PLACEATBEGINNING`). An +/// object that is hidden or locked, in a hidden or locked layer or group, or on a locked artboard +/// is refused. Moving an object directly above or below itself leaves it where it is, and a compound +/// path whose last path moves out stays, empty. +fn item_move(h: &Host, a: &[Data]) -> Answer { + let item = this_item(h, a)?; + if matches!(arg(a, 1), Data::Undefined) { + return Err(HostError::Type("move needs a relative object".into())); + } + let to = destination(h, item, arg(a, 1), arg(a, 2))?; + if to.beside != Some(item.id) { + place(h, item.doc, item.id, &to)?; + } + Ok(arg(a, 0).clone()) +} + +/// The error of `duplicate` on a path inside a compound path. +pub const COMPOUND_MEMBER: &str = "Duplicating a path inside a compound path is not available yet"; + +/// The error of `zOrder` on a path inside a compound path. +pub const COMPOUND_MEMBER_ORDER: &str = "Reordering a path inside a compound path is not available yet"; + +/// Whether `item` is a path inside a compound path. +fn in_compound(h: &Host, item: Item) -> bool { + with_doc(h, item.doc, |_, st| st.doc.parent_of(item.id).and_then(|p| st.doc.node(p)).is_some_and(|p| matches!(p.kind, NodeKind::Compound { .. }))) +} + +/// `duplicate(relativeObject?, insertionLocation?)`: a copy of the item, directly above it as +/// Edit › Duplicate makes one, or into or beside `relativeObject` as `move` puts it. → the copy. +/// When `node.move` refuses the place, the copy and every change it made are put back, and the +/// error is thrown. +fn item_duplicate(h: &Host, a: &[Data]) -> Answer { + let item = this_item(h, a)?; + if in_compound(h, item) { + return Err(HostError::Error(COMPOUND_MEMBER.into())); + } + // `edit.duplicate` copies only what it can select. + let refused = with_doc(h, item.doc, |_, st| { + (!editable(&st.doc, item.id) || on_locked_artboard(h, st, item.id)).then(|| st.doc.node(item.id).and_then(typename).unwrap_or("page item")) + }); + if let Some(name) = refused { + return Err(HostError::Error(format!("Cannot duplicate {name} {}", item.id.0))); + } + let to = match arg(a, 1) { + Data::Undefined => { + if !matches!(arg(a, 2), Data::Undefined) { + return Err(HostError::Type("duplicate needs a relative object for an insertionLocation".into())); + } + None + } + target => Some(destination(h, item, target, arg(a, 2))?), + }; + let id = atomically(h, |h| { + let (_, made) = on_doc(h, item.doc.uid, true, |h| command_value(h, "edit.duplicate", &json!({"ids": [item.id.0]})))?; + let id = made["ids"].get(0).and_then(Value::as_u64).ok_or_else(|| HostError::Error("the copy was not made".into()))?; + if let Some(to) = to { + place(h, item.doc, NodeId(id), &to)?; + } + Ok(id) + })?; + let s = h.session.borrow(); + let st = s.documents().iter().find(|d| d.uid == item.doc.uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?; + Ok(item_ref(h, st, NodeId(id))) +} + +/// `zOrder(method)`: one of the four Object › Arrange commands for the item. A path inside a +/// compound path is refused, and so is an object in a hidden or locked layer. +fn item_z_order(h: &Host, a: &[Data]) -> Answer { + let id = match arg(a, 1) { + Data::String(s) if s == "ZOrderMethod.BRINGTOFRONT" => "object.arrange.bringToFront", + Data::String(s) if s == "ZOrderMethod.BRINGFORWARD" => "object.arrange.bringForward", + Data::String(s) if s == "ZOrderMethod.SENDBACKWARD" => "object.arrange.sendBackward", + Data::String(s) if s == "ZOrderMethod.SENDTOBACK" => "object.arrange.sendToBack", + _ => return Err(HostError::Type("zOrder needs a ZOrderMethod value".into())), + }; + let item = this_item(h, a)?; + if in_compound(h, item) { + return Err(HostError::Error(COMPOUND_MEMBER_ORDER.into())); + } + refuse_in_closed_layer(h, item)?; + let (before, after) = with_doc(h, item.doc, |_, st| { + let at = st.doc.position(item.id); + let count = at.and_then(|(p, ..)| st.doc.children(p).map(Vec::len)).unwrap_or(0); + (at.map(|(_, i, _)| i), count) + }); + let Some(i) = before else { return Err(HostError::Error(STALE_ITEM.into())) }; + let top = i + 1 >= after; + let unchanged = match id { + "object.arrange.bringToFront" | "object.arrange.bringForward" => top, + _ => i == 0, + }; + if !unchanged { + edit_item(h, item, id, &json!({"ids": [item.id.0]}))?; + } + Ok(Data::Undefined) +} + +fn layer_name(h: &Host, a: &[Data]) -> Answer { + let Some(handle) = handle_of(arg(a, 0), "Layer") else { return Err(HostError::Type("this is not a Layer".into())) }; + let [run, uid, high, low] = handle.as_slice() else { return Err(HostError::Type("this is not a Layer".into())) }; + let doc = find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?; + let id = id_of(*high, *low).unwrap_or(NodeId(u64::MAX)); + with_doc(h, doc, |_, st| st.doc.node(id).map(|n| text(n.name.clone().unwrap_or_default())).ok_or_else(|| HostError::Error(STALE_ITEM.into()))) +} + +fn layer_typename(h: &Host, a: &[Data]) -> Answer { + layer_name(h, a)?; + Ok(text("Layer")) +} + +/// `toString()` of an object with a name: `[Class name]`, `[PathItem ]` for an object with no name. +fn named_text(class: &str, name: Answer) -> Answer { + match name? { + Data::String(n) => Ok(text(format!("[{class} {n}]"))), + _ => Ok(text(format!("[{class} ]"))), + } +} + +fn item_to_string(h: &Host, a: &[Data]) -> Answer { + read_item(h, a, |_, n| Ok(text(format!("[{} {}]", typename(n).unwrap_or("PageItem"), n.name.as_deref().unwrap_or(""))))) +} + +fn doc_to_string(h: &Host, a: &[Data]) -> Answer { + named_text("Document", doc_name(h, a)) +} + +fn layer_to_string(h: &Host, a: &[Data]) -> Answer { + named_text("Layer", layer_name(h, a)) +} + +/// `toString()` of an object without a name: `[Class]`. +fn class_text(name: &'static str) -> HostMember { + HostMember::Method(Rc::new(move |_| Ok(text(format!("[{name}]"))))) +} + +fn typename_of(name: &'static str) -> HostMember { + HostMember::Get(Rc::new(move |_| Ok(text(name)))) +} + +fn class(name: &str, parent: Option<&str>, members: Vec<(String, HostMember)>, index: Option) -> HostClass { + HostClass { name: name.into(), parent: parent.map(Into::into), members, index, construct: None } +} + +fn named(items: Vec<(&str, HostMember)>) -> Vec<(String, HostMember)> { + items.into_iter().map(|(n, m)| (n.to_string(), m)).collect() +} + +/// The enumerations, as frozen objects whose members are `"Name.MEMBER"` strings. +const ENUMS: &[(&str, &[&str])] = &[ + ("ElementPlacement", &["INSIDE", "PLACEAFTER", "PLACEATBEGINNING", "PLACEATEND", "PLACEBEFORE"]), + ("ZOrderMethod", &["BRINGFORWARD", "SENDBACKWARD", "BRINGTOFRONT", "SENDTOBACK"]), + ("RulerUnits", &["Centimeters", "Qs", "Inches", "Pixels", "Millimeters", "Unknown", "Picas", "Points"]), + ("DocumentColorSpace", &["CMYK", "RGB"]), + ("CoordinateSystem", &["ARTBOARDCOORDINATESYSTEM", "DOCUMENTCOORDINATESYSTEM"]), + ("DocumentArtboardLayout", &["Column", "GridByCol", "GridByRow", "RLGridByCol", "RLGridByRow", "RLRow", "Row"]), + ("DocumentPresetType", &["BasicCMYK", "BasicRGB", "Mobile", "Print", "Video", "Web"]), + ("DocumentPreviewMode", &["DefaultPreview", "OverprintPreview", "PixelPreview"]), + ("DocumentRasterResolution", &["ScreenResolution", "HighResolution", "MediumResolution"]), + ( + "DocumentTransparencyGrid", + &[ + "TransparencyGridBlue", + "TransparencyGridDark", + "TransparencyGridGreen", + "TransparencyGridLight", + "TransparencyGridMedium", + "TransparencyGridNone", + "TransparencyGridOrange", + "TransparencyGridPurple", + "TransparencyGridRed", + ], + ), +]; + +/// Adds `app`, its classes and the enumerations to `realm`; their members act for the run `link` +/// holds. +pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), RunError> { + for (name, members) in ENUMS { + let items = members.iter().map(|m| (m.to_string(), HostItem::Value(text(format!("{name}.{m}"))))).collect(); + realm.define_host_object(name, items)?; + } + let l = link; + let mut application = named(vec![ + ("typename", typename_of("Application")), + ("documents", get(l, app_documents)), + ("activeDocument", property(l, app_active, app_set_active)), + ("selection", property(l, app_selection, app_set_selection)), + ("coordinateSystem", property(l, app_coords, app_set_coords)), + ("getIsFileOpen", method(l, app_is_open)), + ("toString", class_text("Application")), + ]); + application.push(later(l, "Application", "beep")); + let preset = { + let l = link.clone(); + let f: HostFunction = Rc::new(move |_: Vec| { + let h = current(&l)?; + h.charge_call(64)?; + new_preset(&h) + }); + let mut members = vec![("typename".to_string(), typename_of("DocumentPreset")), ("toString".to_string(), class_text("DocumentPreset"))]; + members.extend(PRESET_FIELDS.iter().map(|k| (k.to_string(), preset_field(link, k)))); + HostClass { name: "DocumentPreset".into(), parent: None, members, index: None, construct: Some(f) } + }; + let mut classes = vec![ + class("Application", None, application, None), + preset, + class( + "Documents", + None, + named(vec![ + ("typename", typename_of("Documents")), + ("length", get(l, docs_length)), + ("parent", get(l, app_ref)), + ("index", method(l, docs_index)), + ("getByName", method(l, docs_by_name)), + ("add", method(l, docs_add)), + ("addDocument", method(l, docs_add_document)), + ("toString", class_text("Documents")), + ]), + Some(function(l, docs_at)), + ), + ]; + let mut document = named(vec![ + ("typename", get(l, doc_typename)), + ("parent", get(l, doc_parent)), + ("name", get(l, doc_name)), + ("width", get(l, doc_width)), + ("height", get(l, doc_height)), + ("rulerUnits", get(l, doc_units)), + ("documentColorSpace", get(l, doc_color_space)), + ("rulerOrigin", property(l, doc_ruler_origin, doc_set_ruler_origin)), + ("convertCoordinate", method(l, doc_convert)), + ("pageItems", get(l, doc_page_items)), + ("selection", property(l, doc_selection, doc_set_selection)), + ("toString", method(l, doc_to_string)), + ]); + document.extend( + ["layers", "artboards", "pathItems", "groupItems", "textFrames", "swatches", "symbols", "views", "activeLayer", "saveAs", "close"] + .into_iter() + .map(|m| later(l, "Document", m)), + ); + classes.push(class("Document", None, document, None)); + classes.push(class( + "PageItems", + None, + named(vec![ + ("typename", get(l, items_typename)), + ("length", get(l, items_length)), + ("parent", get(l, items_parent)), + ("index", method(l, items_index)), + ("getByName", method(l, items_by_name)), + ("removeAll", method(l, items_remove_all)), + ("toString", class_text("PageItems")), + ]), + Some(function(l, items_at)), + )); + let mut page_item = named(vec![ + ("typename", get(l, item_typename)), + ("parent", get(l, item_parent)), + ("name", property(l, item_name, item_set_name)), + ("note", property(l, item_note, item_set_note)), + ("hidden", property(l, item_hidden, item_set_hidden)), + ("locked", property(l, item_locked, item_set_locked)), + ("selected", property(l, item_selected, item_set_selected)), + ("opacity", property(l, item_opacity, item_set_opacity)), + ("position", property(l, item_position, item_set_position)), + ("left", property(l, item_left, item_set_left)), + ("top", property(l, item_top, item_set_top)), + ("width", property(l, item_width, item_set_width)), + ("height", property(l, item_height, item_set_height)), + ("geometricBounds", get(l, item_geometric)), + ("visibleBounds", get(l, item_visible)), + ("controlBounds", get(l, item_visible)), + ("editable", get(l, item_editable)), + ("zOrderPosition", get(l, item_z_order_position)), + ("duplicate", method(l, item_duplicate)), + ("move", method(l, item_move)), + ("remove", method(l, item_remove)), + ("zOrder", method(l, item_z_order)), + ("toString", method(l, item_to_string)), + ]); + page_item.extend( + [ + "artworkKnockout", + "blendingMode", + "isIsolated", + "layer", + "pixelAligned", + "sliced", + "tags", + "uRL", + "uuid", + "visibilityVariable", + "wrapInside", + "wrapOffset", + "wrapped", + "bringInPerspective", + "resize", + "rotate", + "transform", + "translate", + ] + .into_iter() + .map(|m| later(l, "PageItem", m)), + ); + classes.push(class("PageItem", None, page_item, None)); + classes.extend(ITEM_CLASSES.iter().map(|c| class(c, Some("PageItem"), Vec::new(), None))); + classes.push(class( + "Layer", + None, + named(vec![("typename", get(l, layer_typename)), ("name", get(l, layer_name)), ("toString", method(l, layer_to_string))]), + None, + )); + realm.define_host_classes(classes, vec![("app".into(), host_ref("Application", &[]))])?; + // The application's members a script may name without `app.`, assigned as `app.` is. + realm.define_host_globals(vec![ + ("activeDocument".into(), function(l, app_active), Some(function(l, app_set_active))), + ("documents".into(), function(l, app_documents), None), + ("selection".into(), function(l, app_selection), Some(function(l, app_set_selection))), + ]) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn restoring_the_selection_falls_back_only_on_a_refusal() { + assert_eq!(done_unless_refused(Ok(Data::Undefined)), Ok(true)); + assert_eq!(done_unless_refused(Err(HostError::Error("refused".into()))), Ok(false)); + // An internal failure or a stop ends the run instead of being taken for a refusal. + assert_eq!(done_unless_refused(Err(HostError::Abort("canceled".into()))), Err(HostError::Abort("canceled".into()))); + assert_eq!(done_unless_refused(Err(HostError::Range("too large".into()))), Err(HostError::Range("too large".into()))); + } + + #[test] + fn page_item_lists_are_kept_for_several_documents() { + let docs: Vec> = (0..=ITEM_LISTS).map(|_| Arc::new(Document::new(100.0, 100.0))).collect(); + let ids = |n: u64| Rc::new(vec![NodeId(n)]); + let mut lists = Vec::new(); + keep_items(&mut lists, (1, docs[0].clone(), ids(1))); + keep_items(&mut lists, (2, docs[1].clone(), ids(2))); + // Reading two documents in turn keeps both lists. + assert_eq!(kept_items(&lists, 1, &docs[0]), Some(ids(1))); + assert_eq!(kept_items(&lists, 2, &docs[1]), Some(ids(2))); + // A changed document has no kept list, and its new list replaces the old one. + let changed = Arc::new(Document::new(100.0, 100.0)); + assert_eq!(kept_items(&lists, 1, &changed), None); + keep_items(&mut lists, (1, changed.clone(), ids(3))); + assert_eq!(lists.len(), 2); + assert_eq!(kept_items(&lists, 1, &changed), Some(ids(3))); + // Past the limit, the list kept longest ago goes. + for (uid, d) in (10..).zip(&docs[2..]) { + keep_items(&mut lists, (uid, d.clone(), ids(uid))); + } + assert_eq!(lists.len(), ITEM_LISTS); + assert_eq!(kept_items(&lists, 2, &docs[1]), None); + assert_eq!(kept_items(&lists, 1, &changed), Some(ids(3))); + } +} diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index fdec594f69..66e2fdb67c 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -51,6 +51,7 @@ pub mod console; pub mod dialogs; pub mod dollar; +pub mod dom; pub mod include; pub use dialogs::{DialogAnswer, DialogKind, ScriptDialog}; @@ -799,6 +800,8 @@ struct Host { dollar: dollar::RunState, /// The run's `args`, which `vc.args` gives, and their size as `vc.args` charges it. args: RefCell<(Data, u64)>, + /// The run's state of the script object model (`app`). + dom: dom::State, /// The documents open when the run began as the person last left them, each with its own file /// and the file it was read from ([`crate::DocState::as_person_left`], /// [`crate::cmd::links::LinkBase::of_files`]), until the run's first command takes the files @@ -1072,7 +1075,7 @@ impl Host { } let bridge = self.bridge.get().saturating_add(bytes); self.bridge.set(bridge); - if bridge > MAX_BRIDGE_BYTES { + if bridge > bridge_bytes() { return Err(self.over(OVER_BRIDGE)); } let n = self.calls_this_slice.get() + 1; @@ -1263,7 +1266,8 @@ fn note_ids(s: &mut Session) { fn step(s: &mut Session, host: &Host, id: &str, params: &Value) -> Result<(Value, u64, u64, Option)> { raise_ids(s); let mutating = waits_for_tool_edit(id); - let save = mutating.then(|| Savepoint::take(s, id)); + // Inside an object-model call's own savepoint ([`dom`]), that savepoint puts a failure back. + let save = (mutating && !host.dom.saving()).then(|| Savepoint::take(s, id)); let before: Vec<(u64, Arc, u64)> = if mutating { s.docs.iter().map(|d| (d.uid, d.doc.clone(), d.doc.peek_next_id())).collect() } else { Vec::new() }; crate::file_access::start_recording_writes(); @@ -1332,6 +1336,20 @@ fn vc_run(host: &Rc, args: Vec) -> std::result::Result std::result::Result { + command_value(host, id, params).map(|(data, _)| data) +} + +/// [`command`], with the command's result as it gave it as well as the script's copy of it. +fn command_value(host: &Host, id: &str, params: &Value) -> std::result::Result<(Data, Value), HostError> { + let id = id.to_string(); + let params = params.clone(); let session = host.session.clone(); let started = clock(); let r = { @@ -1367,7 +1385,7 @@ fn vc_run(host: &Rc, args: Vec) -> std::result::Result &'static str { /// `e`'s message, with what to do about a failure that comes from a script written for another /// program. A message the script supplied itself ([`RunError::authored`]) is given as it is. fn explained(e: &RunError) -> String { - const HOST_OBJECTS: &[&str] = &["app", "Window", "BridgeTalk", "activeDocument", "documents"]; + const HOST_OBJECTS: &[&str] = &["Window", "BridgeTalk"]; let message = &e.message; - let names_host_object = - message.strip_prefix("ReferenceError: ").is_some_and(|m| HOST_OBJECTS.iter().any(|o| m.split_whitespace().next() == Some(o))); + let first = message.strip_prefix("ReferenceError: ").and_then(|m| m.split_whitespace().next()); + let names_host_object = first.is_some_and(|f| HOST_OBJECTS.contains(&f)); if e.kind == RunErrorKind::Thrown && !e.authored && names_host_object { format!("{message} (scripts here use the `vc` object; objects other applications give their scripts are not available)") } else { @@ -2084,6 +2102,7 @@ impl Session { eval_strict: Cell::new(None), dollar: dollar::RunState::new(&request.locale), args: RefCell::new((Data::Undefined, 0)), + dom: dom::State::default(), run_docs: RefCell::new( self.docs .iter() @@ -2130,6 +2149,7 @@ impl Session { .and_then(|()| if fresh { realm.define_host_object("vc", vc_object(&link)) } else { Ok(()) }) .and_then(|()| if fresh { realm.define_host_object("$", dollar_object(&link, info, &localization)) } else { Ok(()) }) .and_then(|()| if fresh { dialogs::install(&mut realm, &link) } else { Ok(()) }) + .and_then(|()| if fresh { dom::install(&mut realm, &link) } else { Ok(()) }) .and_then(|()| if fresh { files::install(&mut realm, &link) } else { realm.reset_folder_current() }) .and_then(|()| { let r = realm.start(&expanded.source); @@ -2537,6 +2557,15 @@ fn growth_objects() -> u64 { GROWTH_OBJECTS } +/// The data a run may pass to and from commands. +fn bridge_bytes() -> u64 { + #[cfg(test)] + if let Some(n) = TEST_BRIDGE_BYTES.with(Cell::get) { + return n; + } + MAX_BRIDGE_BYTES +} + /// The limits of a command's result on its way to the script. fn result_limits() -> DataLimits { #[cfg(test)] @@ -2554,6 +2583,8 @@ thread_local! { pub(crate) static PANIC_IN_SLICE: Cell = const { Cell::new(false) }; /// Tests: the objects a run may add in place of [`GROWTH_OBJECTS`]. pub(crate) static TEST_GROWTH: Cell> = const { Cell::new(None) }; + /// Tests: the data a run may pass to and from commands in place of [`MAX_BRIDGE_BYTES`]. + pub(crate) static TEST_BRIDGE_BYTES: Cell> = const { Cell::new(None) }; /// Tests: the heap of a named engine in place of [`ENGINE_HEAP_BYTES`]. pub(crate) static TEST_ENGINE_HEAP: Cell> = const { Cell::new(None) }; /// Tests: the bytes of source maps a named engine keeps, in place of [`KEPT_MAP_BYTES`]. diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 770cfd2bea..170137028a 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -59,7 +59,8 @@ impl Session { histories_seen: None, tool: vectorcraft_tools::create("selection"), lender: None, - back_to_bucket: false, + back_to_painter: None, + stop_pick: None, held_input: Default::default(), input_count: 0, edit_started_by: None, diff --git a/crates/engine/src/session/edit.rs b/crates/engine/src/session/edit.rs index cc7af44898..c82f7ca32c 100644 --- a/crates/engine/src/session/edit.rs +++ b/crates/engine/src/session/edit.rs @@ -518,6 +518,7 @@ impl Session { used_defaults_only: false, preview_paint: None, color_mode_paints: None, + tool_paints: false, deferred_color_mode: None, active_layer: st.active_layer, layer_rows: st.layer_rows.clone(), @@ -538,10 +539,11 @@ impl Session { if self.script_running() { return Err(EngineError::Busy); } - // While the Live Paint Bucket is active, paint previews change only the bucket's colors, so - // each preview starts from the colors the interaction began with; so does a preview with + // While the active tool paints with the chosen fill or stroke (the Live Paint Bucket, the + // Shape Builder), paint previews of that kind change only the colors it paints with, so each + // preview starts from the colors the interaction began with; so does a preview with // `defaultsOnly: true`, and one after it. - let bucket = self.bucket_paints(); + let tool_paints = self.tool_paints(false) || self.tool_paints(true); let (paint, restore_paint) = { let menu = self.menu.clone(); let st = self.doc_mut()?; @@ -556,7 +558,8 @@ impl Session { // A batch, or a preview that changed the new-art paints (a pattern rename), started from // the paints the interaction began with. it.used_defaults_only |= cmd::asks_defaults_only(params); - let restore_paint = bucket + it.tool_paints |= tool_paints; + let restore_paint = it.tool_paints || cmd == "command.batch" || it.used_defaults_only || it.preview.as_ref().is_some_and(|(id, p)| id == "command.batch" || cmd::asks_defaults_only(p)) @@ -720,15 +723,17 @@ impl Session { self.clear_deferred_overlay_cache(); self.decoded_images.empty(); self.pending_paint = None; - // While the Live Paint Bucket is active, a previewed color is the bucket's color, which the - // cancel puts back as well, as it does a color previewed with `defaultsOnly: true`. - let bucket = self.bucket_paints(); + // A color previewed while the active tool painted with the chosen fill or stroke is the + // tool's color, which the cancel puts back as well, also after another tool was chosen, as + // it does a color previewed with `defaultsOnly: true`. + let tool_paints = self.tool_paints(false) || self.tool_paints(true); let used_defaults_only = self.active().and_then(|st| st.interaction.as_ref()).is_some_and(|it| it.used_defaults_only); if let Some(paint) = self .active() .and_then(|st| st.interaction.as_ref()) .filter(|it| { - bucket + tool_paints + || it.tool_paints || it.used_defaults_only || it.preview.as_ref().is_some_and(|(id, p)| id == "command.batch" || cmd::asks_defaults_only(p)) || it.color_mode_paints.is_some() diff --git a/crates/engine/src/session/execute.rs b/crates/engine/src/session/execute.rs index 1a130d5cbc..eb7de6e7c4 100644 --- a/crates/engine/src/session/execute.rs +++ b/crates/engine/src/session/execute.rs @@ -401,8 +401,18 @@ impl Session { // The params' own values win, except a null: it reads as a key left out, so the // noted value is the one the command resolved. A noted `defaultsOnly` wins too: the // Live Paint Bucket kept the command to the defaults although the params gave `false`. + // An object noted for an object the params give (`effect.apply`'s `params`) is merged + // by the same rule, so the keys the command filled in stay. Value::Object(m) if !note.is_empty() => { for (k, v) in m { + if let (Some(Value::Object(resolved)), Value::Object(given)) = (note.get_mut(k), v) { + for (gk, gv) in given { + if !gv.is_null() || !resolved.contains_key(gk) { + resolved.insert(gk.clone(), gv.clone()); + } + } + continue; + } if (!v.is_null() && k != "defaultsOnly") || !note.contains_key(k) { note.insert(k.clone(), v.clone()); } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index cd3ff27d5d..f581be4dd6 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -32,6 +32,7 @@ mod clipflavours; mod clippaint; mod cmdsplit; mod cmykflatten; +mod colorcontrast; mod colorguide; mod colorguidelib; mod colorize; @@ -176,6 +177,7 @@ mod scalestrokes; mod script_console; mod script_dialogs; mod script_dollar; +mod script_dom; mod script_engines; mod script_folder; mod script_include; diff --git a/crates/engine/src/tests/brushsym.rs b/crates/engine/src/tests/brushsym.rs index 427def6754..7ac6b8c4e2 100644 --- a/crates/engine/src/tests/brushsym.rs +++ b/crates/engine/src/tests/brushsym.rs @@ -1357,10 +1357,7 @@ fn brush_freehand_refuses_unknown_keys() { let spec = crate::cmd::find_command("brush.freehand").unwrap(); let mut keys = crate::cmd::params::accepted_keys(spec.params).expect("the description names every key"); keys.sort_unstable(); - assert_eq!( - keys, - ["brush", "closed", "connect", "extend", "fidelity", "fill", "fit", "keepSelected", "leaveSelection", "points", "redraw", "style"] - ); + assert_eq!(keys, ["brush", "closed", "connect", "extend", "fidelity", "fill", "fit", "keepSelected", "points", "preview", "redraw", "style"]); let mut s = session(); let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0); select(&mut s, &[a]); diff --git a/crates/engine/src/tests/build.rs b/crates/engine/src/tests/build.rs index 22560e5568..320d6ba70f 100644 --- a/crates/engine/src/tests/build.rs +++ b/crates/engine/src/tests/build.rs @@ -1899,6 +1899,303 @@ fn shape_builder_arrow_keys_pass_swatches_of_the_same_color() { assert_eq!(s.paint.fill, after, "the swatch after Twin B"); } +/// While the Shape Builder is active, with either Pick Color From, a fill chosen without `ids`, +/// `id` or `item` (a swatch, a color, Swap, Default) changes only the current fill: the selected +/// paths keep their fills, no undo step is recorded and the Fill proxy shows the chosen fill. A +/// stroke chosen then still paints the selection, since a merge takes no stroke from it. +#[test] +fn shape_builder_fill_choice_leaves_the_selection_unpainted() { + let fills = |s: &Session, ids: [NodeId; 2]| ids.map(|id| node(s, id).appearance.fill_paint()); + for mode in ["artwork", "swatches"] { + let mut s = session(); + let (a, b) = two(&mut s); + s.execute("swatch.new", &json!({"name": "Leaf", "color": "#00ff00"})).unwrap(); + s.select_tool("shapeBuilder", ViewInfo::default()).unwrap(); + s.set_tool_option_cmd(&json!({"tool": "shapeBuilder", "values": {"pickColorFrom": mode}})).unwrap(); + let before = fills(&s, [a, b]); + let steps = s.doc().unwrap().history.undo.len(); + let r = s.execute("paint.setFill", &json!({"swatch": "Leaf"})).unwrap(); + assert_eq!(r["objects"], 0, "{mode}"); + let leaf = s.paint.fill.clone(); + assert_eq!(leaf.color(), Some(Color::from_hex("#00ff00").unwrap()), "{mode}"); + for cmd in ["paint.swap", "paint.swap", "paint.default"] { + s.execute(cmd, &json!({})).unwrap(); + } + s.execute("paint.setFill", &json!({"swatch": "Leaf"})).unwrap(); + assert_eq!(fills(&s, [a, b]), before, "{mode}: the selected paths keep their fills"); + assert_eq!(s.doc().unwrap().history.undo.len(), steps, "{mode}: no undo step"); + assert_eq!(s.proxy_paints().0, leaf, "{mode}: the Fill proxy shows the chosen fill"); + // A stroke goes to the selection, and the Stroke proxy shows the selection's. + let r = s.execute("paint.setStroke", &json!({"color": "#0000ff"})).unwrap(); + assert!(r["objects"].as_u64().unwrap() > 0, "{mode}: {r}"); + let blue = Paint::solid(Color::from_hex("#0000ff").unwrap()); + assert_eq!(node(&s, a).appearance.stroke_paint(), blue, "{mode}"); + s.execute("stroke.set", &json!({"weight": 7})).unwrap(); + assert_eq!(node(&s, b).appearance.stroke_at(None).map(|l| l.width), Some(7.0), "{mode}: the selection takes the weight"); + assert_eq!(fills(&s, [a, b]), before, "{mode}"); + } +} + +/// While the Shape Builder is active, Swap Fill and Stroke gives the current fill the stroke the +/// Stroke proxy shows (the selection's), not a stroke for new art that no proxy shows, and the +/// selected path keeps its fill and stroke. With mixed strokes shown, the fill takes the stroke +/// for new art. +#[test] +fn shape_builder_swap_gives_the_fill_the_shown_stroke() { + let mut s = session(); + let (a, b) = two(&mut s); + s.execute("appearance.setNewArtBasic", &json!({"on": true})).unwrap(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("paint.setStroke", &json!({"color": "#00ff00"})).unwrap(); + let green = Paint::solid(Color::from_hex("#00ff00").unwrap()); + s.paint.stroke = Paint::solid(Color::from_hex("#0000ff").unwrap()); + s.select_tool("shapeBuilder", ViewInfo::default()).unwrap(); + assert_eq!(s.proxy_paints().1, green, "the Stroke proxy shows the selection's stroke"); + // No stroke for new art: the old fill becomes a 1 pt stroke for new art, as without the tool. + (s.paint.stroke, s.paint.stroke_width) = (Paint::None, 0.0); + let before = node(&s, a).appearance; + s.execute("paint.swap", &json!({})).unwrap(); + assert_eq!(s.paint.fill, green, "the current fill takes the stroke the proxy showed"); + assert_eq!(s.paint.stroke_width, 1.0, "the old fill is a stroke that draws"); + assert_eq!(node(&s, a).appearance, before, "the selected path keeps its fill and stroke"); + // The Stroke proxy shows mixed strokes: the current fill takes the stroke for new art. + s.execute("paint.setStroke", &json!({"ids": [b.0], "color": "#ff00ff"})).unwrap(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + assert!(s.proxy_mixed().1, "the selection's strokes differ"); + let blue = Paint::solid(Color::from_hex("#0000ff").unwrap()); + s.paint.stroke = blue.clone(); + s.execute("paint.swap", &json!({})).unwrap(); + assert_eq!(s.paint.fill, blue, "no stroke of the selection was shown"); + // With nothing selected, the stroke for new art (a freeform gradient drawn as lines) moves to + // the fill as it is. + s.execute("select.set", &json!({"ids": []})).unwrap(); + s.execute("paint.editGradient", &json!({"stroke": true, "kind": "freeform", "mode": "lines"})).unwrap(); + let stroke = s.paint.stroke.clone(); + assert!(matches!(&stroke, Paint::Gradient(g) if g.freeform.is_some()), "{stroke:?}"); + s.execute("paint.swap", &json!({})).unwrap(); + assert_eq!(s.paint.fill, stroke, "the stroke for new art, unchanged"); +} + +/// While the Shape Builder is active, the fill chosen for it stays the current fill when the +/// selection changes, with New Art Has Basic Appearance on or off (off, new art still takes the +/// rest of the new selection's appearance), and the freeform point commands refuse the fill's +/// gradient, which lies on no object, instead of editing the selection's. +#[test] +fn shape_builder_fill_stays_across_selections() { + for basic in [false, true] { + let mut s = session(); + let (a, b) = two(&mut s); + s.execute("appearance.setNewArtBasic", &json!({"on": basic})).unwrap(); + // B's own fill is a freeform gradient, whose points the commands could edit. + s.execute("paint.editGradient", &json!({"ids": [b.0], "stroke": false, "kind": "freeform"})).unwrap(); + // B is linked to a graphic style. + s.execute("graphicStyle.new", &json!({"id": b.0, "name": "Bee"})).unwrap(); + s.execute("graphicStyle.apply", &json!({"name": "Bee", "ids": [b.0]})).unwrap(); + s.select_tool("shapeBuilder", ViewInfo::default()).unwrap(); + s.execute("paint.editGradient", &json!({"stroke": false, "kind": "freeform", "mode": "lines"})).unwrap(); + // The tool's freeform gradient has no points yet: its stops take the colors given. + let stops = json!([{"offset": 0, "color": "#ff0000"}, {"offset": 1, "color": "#0000ff"}]); + s.execute("paint.editGradient", &json!({"stroke": false, "stops": stops})).unwrap(); + let Paint::Gradient(g) = &s.paint.fill else { panic!("the tool's fill is not a gradient") }; + assert_eq!(g.gradient.stops[0].color, Color::from_hex("#ff0000").unwrap(), "{basic}: the stop color given"); + let chosen = s.paint.fill.clone(); + assert!(matches!(&chosen, Paint::Gradient(_)), "{basic}"); + s.execute("select.set", &json!({"ids": [b.0]})).unwrap(); + assert_eq!(s.paint.fill, chosen, "basic {basic}: the chosen fill stays"); + assert_eq!(s.paint.inherited, !basic, "basic {basic}: whether new art takes the selection's appearance"); + // New art with the chosen fill does not look like B's style, so it is not linked to it. + assert_eq!(s.paint.style, None, "basic {basic}"); + let before = [a, b].map(|id| node(&s, id)); + let e = s.execute("paint.freeform.setPoint", &json!({"index": 0, "color": "#ff0000"})).unwrap_err().to_string(); + assert!(e.contains("Shape Builder"), "{basic}: {e}"); + assert_eq!([a, b].map(|id| node(&s, id)), before, "basic {basic}: the selection keeps its paint"); + } +} + +/// While the Shape Builder is active with the Fill proxy in front, a gradient preset or edit that +/// names no kind goes to the tool's fill, also while a stroke row of the selection is the +/// Appearance panel's active row; with the Stroke proxy in front, an active fill row still keeps +/// the edit off the selection. +#[test] +fn shape_builder_gradient_edits_follow_the_proxy_in_front() { + let mut s = session(); + let (a, _) = two(&mut s); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + let row = |s: &Session, fill: bool| node(s, a).appearance.items.iter().position(|it| it.is_fill() == fill).unwrap(); + s.select_tool("shapeBuilder", ViewInfo::default()).unwrap(); + let before = node(&s, a); + s.execute("appearance.setActiveItem", &json!({"index": row(&s, false)})).unwrap(); + s.fill_active = true; + s.execute("gradient.presets.apply", &json!({"name": "vignette"})).unwrap(); + assert!(matches!(s.paint.fill, Paint::Gradient(_)), "the tool's fill takes the preset"); + assert_eq!(node(&s, a).appearance, before.appearance, "the selection keeps its paint"); + s.execute("appearance.setActiveItem", &json!({"index": row(&s, true)})).unwrap(); + s.fill_active = false; + for (kind, ids) in [("diamond", None), ("linear", Some(Value::Null))] { + let tool_fill = s.paint.fill.clone(); + let mut p = json!({ "kind": kind }); + if let Some(ids) = ids { + p["ids"] = ids; + } + s.execute("paint.editGradient", &p).unwrap(); + assert_ne!(s.paint.fill, tool_fill, "{p}: the tool's fill takes the edit"); + assert_eq!(node(&s, a).appearance, before.appearance, "{p}: the selection keeps its paint"); + } + // A freeform stroke on the selection, its row active and the Fill proxy in front: a point + // edit without `stroke` is for the tool's fill, which has no points, and changes nothing. + s.execute("paint.editGradient", &json!({"ids": [a.0], "stroke": true, "kind": "freeform"})).unwrap(); + let stroked = node(&s, a); + s.execute("appearance.setActiveItem", &json!({"index": row(&s, false)})).unwrap(); + s.fill_active = true; + assert!(s.execute("paint.freeform.setPoint", &json!({"index": 0, "color": "#ff0000"})).is_err()); + assert_eq!(node(&s, a).appearance, stroked.appearance, "the selection's stroke keeps its points"); + // A `stroke` that is not a switch is reported as such. + let e = s.execute("paint.freeform.setPoint", &json!({"index": 0, "color": "#ff0000", "stroke": "true"})).unwrap_err(); + assert!(e.to_string().contains("stroke"), "{e}"); +} + +/// A fill previewed while the Shape Builder is active (a Color panel drag) is the tool's fill, +/// which a cancel puts back, also after another tool was chosen during the drag. +#[test] +fn shape_builder_fill_preview_is_put_back_by_a_cancel() { + let mut s = session(); + two(&mut s); + s.execute("appearance.setNewArtBasic", &json!({"on": true})).unwrap(); + s.select_tool("shapeBuilder", ViewInfo::default()).unwrap(); + let before = s.paint.fill.clone(); + s.begin_interaction("Color").unwrap(); + s.preview("paint.setFill", &json!({"color": "#ff00ff"})).unwrap(); + assert_eq!(s.paint.fill.color(), Some(Color::from_hex("#ff00ff").unwrap()), "the preview sets the tool's fill"); + s.select_tool("selection", ViewInfo::default()).unwrap(); + s.cancel_interaction().unwrap(); + assert_eq!(s.paint.fill, before, "the cancel puts the fill back"); +} + +/// With Pick Color From Color Swatches, a merge fills with the fill chosen while the Shape Builder +/// is active, and the Gradient panel's eyedropper samples into a stop of that fill's gradient. +#[test] +fn shape_builder_merge_fills_with_the_chosen_fill() { + let mut s = session(); + let (a, b) = two(&mut s); + s.execute("swatch.new", &json!({"name": "Leaf", "color": "#00ff00"})).unwrap(); + let v = ViewInfo::default(); + s.select_tool("shapeBuilder", v).unwrap(); + s.set_tool_option_cmd(&json!({"tool": "shapeBuilder", "values": {"pickColorFrom": "swatches"}})).unwrap(); + let (a0, b0) = (node(&s, a), node(&s, b)); + s.execute("paint.setFill", &json!({"swatch": "Leaf"})).unwrap(); + let leaf = s.paint.fill.clone(); + assert_eq!((node(&s, a), node(&s, b)), (a0, b0), "the selected paths keep their paint"); + // The tool's merge fills with the chosen swatch. + s.pointer(&PointerEvent::new(PointerKind::Down, 25.0, 50.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 75.0, 50.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 75.0, 50.0), v).unwrap(); + assert_eq!(s.journal.last().unwrap().0, "shapeBuilder.merge"); + let d = &s.doc().unwrap().doc; + let fills: Vec = d.children(d.default_layer()).into_iter().flatten().map(|n| n.appearance.fill_paint()).collect(); + assert!(fills.contains(&leaf), "a merged shape filled with the swatch: {fills:?}"); + // A gradient and the Gradient panel's eyedropper sample into a stop of the gradient the tool + // paints with, and the art keeps its paint. + let art = |s: &Session| -> Vec { + let d = &s.doc().unwrap().doc; + d.children(d.default_layer()).into_iter().flatten().map(|n| Node::clone(n)).collect() + }; + let before = art(&s); + s.execute("paint.editGradient", &json!({"stroke": false, "kind": "linear"})).unwrap(); + s.execute("gradient.selectStop", &json!({"index": 1})).unwrap(); + s.select_tool("eyedropper", v).unwrap(); + s.set_tool_option("stop", &json!("shapeBuilder")); + for kind in [PointerKind::Down, PointerKind::Up] { + s.pointer(&PointerEvent::new(kind, 25.0, 50.0), v).unwrap(); + } + let Paint::Gradient(g) = &s.paint.fill else { panic!("the tool's fill is not a gradient") }; + assert_eq!(Paint::solid(g.gradient.stops[1].color), leaf, "the sampled stop"); + assert_eq!(art(&s), before, "the art keeps its paint"); + // Armed again, a pick whose stop went away when the Stroke proxy came to the front (the + // selection's stroke), also after the stop was cleared first, ends without copying an + // appearance onto the art. + for clear in [false, true] { + s.select_tool("shapeBuilder", v).unwrap(); + s.fill_active = true; + s.execute("gradient.selectStop", &json!({"index": 1})).unwrap(); + s.select_tool("eyedropper", v).unwrap(); + s.set_tool_option("stop", &json!("shapeBuilder")); + if clear { + s.execute("gradient.selectStop", &json!({"index": null})).unwrap(); + } + s.fill_active = false; + assert_eq!(s.selected_stop(), None); + for kind in [PointerKind::Down, PointerKind::Up] { + s.pointer(&PointerEvent::new(kind, 25.0, 50.0), v).unwrap(); + } + assert_eq!(art(&s), before, "the art keeps its paint (cleared first: {clear})"); + } + // With the Stroke proxy in front, a stop of the selection's stroke gradient is the selection's, + // and the pick samples into it. + s.execute("paint.editGradient", &json!({"stroke": true, "kind": "linear"})).unwrap(); + assert_ne!(art(&s), before, "the selection takes the stroke gradient"); + s.execute("gradient.selectStop", &json!({"index": 0})).unwrap(); + s.select_tool("eyedropper", v).unwrap(); + s.set_tool_option("stop", &json!("shapeBuilder")); + for kind in [PointerKind::Down, PointerKind::Up] { + s.pointer(&PointerEvent::new(kind, 25.0, 50.0), v).unwrap(); + } + assert_eq!(s.journal.last().unwrap().0, "paint.sampleColor", "the pick samples into the selection's stop"); + // A pick armed for a stop of the tool's fill does not sample into a stop selected since on + // the selection's stroke: it ends. + s.select_tool("shapeBuilder", v).unwrap(); + s.fill_active = true; + s.execute("gradient.selectStop", &json!({"index": 1})).unwrap(); + s.select_tool("eyedropper", v).unwrap(); + s.set_tool_option("stop", &json!("shapeBuilder")); + s.fill_active = false; + let stops = json!([{"offset": 0, "color": "#0000ff"}, {"offset": 1, "color": "#000000"}]); + s.execute("paint.editGradient", &json!({"stroke": true, "stops": stops})).unwrap(); + s.execute("gradient.selectStop", &json!({"index": 0})).unwrap(); + let armed = art(&s); + for kind in [PointerKind::Down, PointerKind::Up] { + s.pointer(&PointerEvent::new(kind, 25.0, 50.0), v).unwrap(); + } + assert_eq!(art(&s), armed, "the selection's stroke keeps its stops"); + s.execute("gradient.selectStop", &json!({"index": null})).unwrap(); + // A pick armed for another tool is not that stop's: with no stop selected, its click copies + // the appearance as usual. + s.select_tool("eyedropper", v).unwrap(); + s.set_tool_option("stop", &json!("selection")); + for kind in [PointerKind::Down, PointerKind::Up] { + s.pointer(&PointerEvent::new(kind, 25.0, 50.0), v).unwrap(); + } + assert_eq!(s.journal.last().unwrap().0, "appearance.copyFrom"); + // Choosing another tool drops the stop a pick was armed for. + s.select_tool("shapeBuilder", v).unwrap(); + s.fill_active = true; + s.execute("paint.editGradient", &json!({"stroke": false, "kind": "linear"})).unwrap(); + s.execute("gradient.selectStop", &json!({"index": 1})).unwrap(); + s.select_tool("eyedropper", v).unwrap(); + s.set_tool_option("stop", &json!("shapeBuilder")); + assert!(s.stop_pick.is_some(), "the pick is armed for the tool's stop"); + s.select_tool("selection", v).unwrap(); + assert!(s.stop_pick.is_none(), "another tool was chosen"); + // Armed while the Eyedropper waits for a Cmd-drag it lent the Selection tool to, the pick + // still ends once the Stroke proxy comes to the front. + s.select_tool("shapeBuilder", v).unwrap(); + s.fill_active = true; + s.execute("gradient.selectStop", &json!({"index": 1})).unwrap(); + s.select_tool("eyedropper", v).unwrap(); + let lent = s.make_tool("selection"); + s.lender = Some(std::mem::replace(&mut s.tool, lent)); + s.set_tool_options(Some("eyedropper"), json!({"stop": "shapeBuilder"}).as_object().unwrap()); + s.give_back_tool(v).unwrap(); + assert_eq!(s.tool_id(), "eyedropper"); + s.fill_active = false; + let (armed, journal) = (art(&s), s.journal.len()); + for kind in [PointerKind::Down, PointerKind::Up] { + s.pointer(&PointerEvent::new(kind, 25.0, 50.0), v).unwrap(); + } + assert_eq!(art(&s), armed, "the art keeps its paint (armed during a loan)"); + let ran: Vec<&str> = s.journal.since(journal).iter().map(|j| j.0.as_str()).collect(); + assert!(!ran.contains(&"appearance.copyFrom"), "{ran:?}"); +} + /// The colors of the cursor swatch preview's chips, left to right, and which one is ringed. fn swatch_chips(s: &mut Session, v: ViewInfo) -> Vec<([u8; 4], bool)> { let mut chips: Vec<(f64, [u8; 4], bool)> = s diff --git a/crates/engine/src/tests/circle_through.rs b/crates/engine/src/tests/circle_through.rs index c9b66f9f06..fe85cb5822 100644 --- a/crates/engine/src/tests/circle_through.rs +++ b/crates/engine/src/tests/circle_through.rs @@ -123,6 +123,63 @@ fn two_points_are_the_ends_of_a_diameter() { assert_eq!((undo_len(&s), object_count(&s)), (undo, count)); } +/// With `center`, the circle is centered there and its edge passes through the one point in +/// `points`: from the bottom-right corner (200, 200) of a 100 pt square through its top-left +/// corner (100, 100), the radius is the square's diagonal, in one undo step. A point on the center +/// and a circle past the canvas are refused, and so is a `center` (null included) or `points` that +/// is not one `[x, y]` pair of finite numbers; nothing is drawn and no undo step is recorded. +#[test] +fn a_center_and_a_point_on_the_edge_give_the_circle() { + let mut s = session(); + let undo = undo_len(&s); + let out = s.execute(C, &json!({"center": [200, 200], "points": [[100, 100]]})).unwrap(); + let r = 100.0 * std::f64::consts::SQRT_2; + assert_eq!((out["cx"].as_f64(), out["cy"].as_f64()), (Some(200.0), Some(200.0)), "{out}"); + assert!((out["radius"].as_f64().unwrap() - r).abs() < 1e-12, "{out}"); + let id = id_of(&out); + assert!(bounds_are(&s, id, vectorcraft_geom::Rect::new(200.0 - r, 200.0 - r, 200.0 + r, 200.0 + r))); + assert!(farthest_from_path(&s, id, &[Point::new(100.0, 100.0)]) < r * 3e-4); + assert_eq!(s.doc().unwrap().selection.objects, [id]); + assert_eq!(undo_len(&s), undo + 1); + let (undo, count) = (undo_len(&s), object_count(&s)); + let e = s.execute(C, &json!({"center": [30, 30], "points": [[30, 30]]})).unwrap_err().to_string(); + assert!(e.contains("the point in `points` is on `center`"), "{e}"); + // Past the canvas, and finite coordinates whose distance overflows to infinity. + for (center, point) in [(json!([0, 0]), json!([4_100_000, 0])), (json!([-1e308, -1e308]), json!([1e308, 1e308]))] { + let e = s.execute(C, &json!({ "center": center, "points": [point] })).unwrap_err().to_string(); + assert!(e.contains("result would exceed the canvas"), "{center} {point}: {e}"); + } + for (center, points) in [ + (json!([0, 0]), json!([[10, 0], [0, 10]])), + (json!([0, 0]), json!([])), + (json!([0, 0]), Value::Null), + (json!([0, 0]), json!([[10, "0"]])), + (json!([0]), json!([[10, 0]])), + (json!("0,0"), json!([[10, 0]])), + (json!([0, 0, 1]), json!([[10, 0]])), + (Value::Null, json!([[10, 0]])), + (Value::Null, json!([[10, 0], [20, 0]])), + ] { + let e = s.execute(C, &json!({ "center": center, "points": points })).unwrap_err().to_string(); + assert!(e.contains("`center` must be an [x, y] pair of numbers, with one [x, y] pair in `points`"), "{center} {points}: {e}"); + } + assert_eq!((undo_len(&s), object_count(&s)), (undo, count)); +} + +/// A circle so small beside its coordinates that its left and right edges round to the same +/// number (radius 10⁻¹¹ pt at x = 1,048,576, where doubles step by about 2.3 × 10⁻¹⁰) is refused, +/// from a center and on a diameter alike; nothing is drawn and no undo step is recorded. +#[test] +fn a_circle_with_no_width_at_document_precision_is_refused() { + let mut s = session(); + let (undo, count) = (undo_len(&s), object_count(&s)); + for p in [json!({"center": [1_048_576, 0], "points": [[1_048_576, 1e-11]]}), json!({"points": [[1_048_576, 0], [1_048_576, 2e-11]]})] { + let e = s.execute(C, &p).unwrap_err().to_string(); + assert!(e.contains("the circle is too small to draw at these coordinates"), "{p}: {e}"); + } + assert_eq!((undo_len(&s), object_count(&s)), (undo, count)); +} + /// Points that are not two or three pairs of finite numbers are an error, not a fallback. #[test] fn malformed_points_are_refused() { @@ -243,6 +300,28 @@ fn click(s: &mut Session, mods: Mods, x: f64, y: f64) { } } +/// The Circle tool with From Center set through `tool.setOption`: a click on the center and a +/// click on the edge draw the circle, in one undo step. `fromCenter` must be true or false, and +/// the tool has no other option; a refused value changes nothing. +#[test] +fn the_circle_tool_draws_from_its_center() { + let mut s = session(); + s.select_tool("circle", view()).unwrap(); + let e = s.set_tool_option_cmd(&json!({"key": "fromCenter", "value": "yes"})).unwrap_err(); + assert!(e.contains("`fromCenter` must be true or false"), "{e}"); + assert!(s.set_tool_option_cmd(&json!({"key": "radius", "value": 5})).is_err()); + assert_eq!(s.tool_options()["fromCenter"], json!(false)); + s.set_tool_option_cmd(&json!({"key": "fromCenter", "value": true})).unwrap(); + assert_eq!(s.tool_options()["fromCenter"], json!(true)); + let undo = undo_len(&s); + click(&mut s, Mods::default(), 200.0, 200.0); + click(&mut s, Mods::default(), 100.0, 100.0); + assert_eq!(undo_len(&s), undo + 1); + let id = *s.doc().unwrap().selection.objects.first().unwrap(); + let r = 100.0 * std::f64::consts::SQRT_2; + assert!(bounds_are(&s, id, vectorcraft_geom::Rect::new(200.0 - r, 200.0 - r, 200.0 + r, 200.0 + r))); +} + /// With the Ellipse tool, three Shift-clicks draw the circle through the three points, in one /// undo step; Escape drops the points placed so far. #[test] diff --git a/crates/engine/src/tests/colorcontrast.rs b/crates/engine/src/tests/colorcontrast.rs new file mode 100644 index 0000000000..39f496557d --- /dev/null +++ b/crates/engine/src/tests/colorcontrast.rs @@ -0,0 +1,854 @@ +//! `color.contrast`: the WCAG 2 contrast of a color against the color behind the selection. + +use serde_json::{Value, json}; + +use crate::*; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + s +} + +fn ratio(r: &Value) -> f64 { + r["ratio"].as_f64().unwrap() +} + +#[test] +fn a_pair_just_under_aa_fails_it() { + let mut s = Session::new(); + let r = s.execute("color.contrast", &json!({"color": "#fdc96e", "against": "#355f78"})).unwrap(); + assert!((ratio(&r) - 4.496).abs() < 1e-3, "{r}"); + assert_eq!(r["against"], "#355f78"); + assert_eq!(r["normalText"], json!({"aa": false, "aaa": false})); + assert_eq!(r["largeText"], json!({"aa": true, "aaa": false})); + assert_eq!(r["graphics"], json!({"aa": true}), "graphics have no AAA level"); + assert_eq!(vectorcraft_color::wcag::ratio_text(ratio(&r)), "4.49:1"); +} + +#[test] +fn black_on_white_is_21_and_grays_fall_either_side_of_aa() { + let mut s = Session::new(); + let r = s.execute("color.contrast", &json!({"color": "#000000", "against": "#ffffff"})).unwrap(); + assert!((ratio(&r) - 21.0).abs() < 1e-6, "{r}"); + assert_eq!(r["normalText"], json!({"aa": true, "aaa": true})); + let pass = s.execute("color.contrast", &json!({"color": "#767676", "against": "#ffffff"})).unwrap(); + assert!((ratio(&pass) - 4.542).abs() < 1e-3 && pass["normalText"]["aa"] == true, "{pass}"); + let fail = s.execute("color.contrast", &json!({"color": "#777777", "against": "#ffffff"})).unwrap(); + assert!((ratio(&fail) - 4.478).abs() < 1e-3 && fail["normalText"]["aa"] == false, "{fail}"); +} + +#[test] +fn the_background_is_the_locked_art_behind_the_selected_type() { + let mut s = session(); + s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 160, "height": 80})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#ffff00"})).unwrap(); + s.execute("object.lock", &json!({})).unwrap(); + s.execute("text.create", &json!({"x": 60, "y": 70, "text": "Label", "size": 24, "color": "#000000"})).unwrap(); + let r = s.execute("color.contrast", &json!({})).unwrap(); + assert_eq!(r["against"], "#ffff00", "{r}"); + let want = vectorcraft_color::wcag::contrast_ratio([0.0; 3], [1.0, 1.0, 0.0]); + assert!((ratio(&r) - want).abs() < 1e-3, "{r}"); +} + +#[test] +fn a_translucent_fill_counts_at_the_opacity_it_is_drawn_with() { + let mut s = session(); + s.execute("shape.rectangle", &json!({"x": 50, "y": 50, "width": 100, "height": 100})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap(); + s.execute("transparency.set", &json!({"opacity": 50})).unwrap(); + let r = s.execute("color.contrast", &json!({})).unwrap(); + assert_eq!(r["against"], "#ffffff", "the selected rectangle is hidden: the artboard's white shows"); + let gray = vectorcraft_color::wcag::contrast_ratio([0.5; 3], [1.0; 3]); + assert!((ratio(&r) - gray).abs() < 1e-3, "{r}"); + // A given opacity replaces it, and a given color is drawn fully opaque. + let full = s.execute("color.contrast", &json!({"opacity": 100})).unwrap(); + assert!((ratio(&full) - 21.0).abs() < 1e-3, "{full}"); + let given = s.execute("color.contrast", &json!({"color": "#000000"})).unwrap(); + assert!((ratio(&given) - 21.0).abs() < 1e-3, "{given}"); +} + +#[test] +fn a_translucent_group_counts_for_the_art_inside_it() { + let mut s = session(); + s.execute("shape.rectangle", &json!({"x": 50, "y": 50, "width": 100, "height": 100})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + s.execute("transparency.set", &json!({"opacity": 50})).unwrap(); + let r = s.execute("color.contrast", &json!({})).unwrap(); + let gray = vectorcraft_color::wcag::contrast_ratio([0.5; 3], [1.0; 3]); + assert!((ratio(&r) - gray).abs() < 1e-3, "the group draws the black at 50 %: {r}"); +} + +#[test] +fn a_blend_mode_counts_as_it_draws_over_the_background() { + let mut s = session(); + s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 160, "height": 160})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + s.execute("object.lock", &json!({})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 50, "y": 50, "width": 100, "height": 100})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#ffffff"})).unwrap(); + s.execute("transparency.set", &json!({"blend": "multiply"})).unwrap(); + let r = s.execute("color.contrast", &json!({})).unwrap(); + assert_eq!(r["against"], "#ff0000", "{r}"); + assert!((ratio(&r) - 1.0).abs() < 1e-3, "white multiplied over red draws red: {r}"); + // A group's blend mode counts for the art inside it, and a given color draws in Normal mode. + s.execute("transparency.set", &json!({"blend": "normal"})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + s.execute("transparency.set", &json!({"blend": "multiply"})).unwrap(); + let r = s.execute("color.contrast", &json!({})).unwrap(); + assert!((ratio(&r) - 1.0).abs() < 1e-3, "{r}"); + let given = s.execute("color.contrast", &json!({"color": "#ffffff"})).unwrap(); + let want = vectorcraft_color::wcag::contrast_ratio([1.0; 3], [1.0, 0.0, 0.0]); + assert!((ratio(&given) - want).abs() < 1e-3, "{given}"); +} + +/// A selected blue square at (50, 50) over locked red art, with its fill row's blend mode set to +/// `row`. +fn blended_over_red(row: &str) -> Session { + let mut s = session(); + s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 160, "height": 160})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + s.execute("object.lock", &json!({})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 50, "y": 50, "width": 100, "height": 100})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#4080c0"})).unwrap(); + s.execute("transparency.set", &json!({"item": fill_index(&s), "blend": row})).unwrap(); + s +} + +/// The index of the selected object's fill row. +fn fill_index(s: &Session) -> usize { + let st = s.active().unwrap(); + let n = st.doc.node(st.selection.objects[0]).unwrap(); + n.appearance.items.iter().position(|i| matches!(i, vectorcraft_doc::AppearanceItem::Fill(_))).unwrap() +} + +/// The contrast against red of the color the canvas draws at the square's center. +fn drawn_ratio(s: &Session) -> f64 { + let doc = &s.doc().unwrap().doc; + let img = vectorcraft_render::Renderer::new().render_region(doc, vectorcraft_geom::Rect::new(99.0, 99.0, 101.0, 101.0), 1.0, true); + let p = img.pixel(1, 1); + vectorcraft_color::wcag::contrast_ratio([p[0], p[1], p[2]].map(|v| f32::from(v) / 255.0), [1.0, 0.0, 0.0]) +} + +#[test] +fn nested_blend_modes_count_as_the_canvas_draws_them() { + let mut s = blended_over_red("multiply"); + s.execute("transparency.set", &json!({"item": null, "blend": "screen"})).unwrap(); + let r = s.execute("color.contrast", &json!({})).unwrap(); + assert_eq!(r["against"], "#ff0000", "{r}"); + let drawn = drawn_ratio(&s); + assert!((ratio(&r) - drawn).abs() < 0.02, "the fill multiplies, then the object screens: {r} against {drawn}"); + // A translucent row and object: the canvas takes the backdrop back out of a group that blends + // through before it blends the group, so the opacities multiply over the nested modes. + s.execute("transparency.set", &json!({"item": fill_index(&s), "opacity": 50})).unwrap(); + s.execute("transparency.set", &json!({"item": null, "blend": "overlay", "opacity": 70})).unwrap(); + let r = s.execute("color.contrast", &json!({})).unwrap(); + let drawn = drawn_ratio(&s); + assert!((ratio(&r) - drawn).abs() < 0.02, "{r} against {drawn}"); + s.execute("transparency.set", &json!({"item": null, "opacity": 100})).unwrap(); + // Grouped, the group's mode blends the result again. + s.execute("transparency.set", &json!({"item": null, "blend": "normal"})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + s.execute("transparency.set", &json!({"blend": "difference"})).unwrap(); + let r = s.execute("color.contrast", &json!({})).unwrap(); + let drawn = drawn_ratio(&s); + assert!((ratio(&r) - drawn).abs() < 0.02, "{r} against {drawn}"); +} + +/// In a 50 % group, a black square over a white one draws black over the black outside: the group's +/// opacity applies to the white behind the square once, not again over it. +#[test] +fn a_translucent_group_draws_the_art_behind_the_object_once() { + let mut s = session(); + let id = |v: Value| vectorcraft_doc::NodeId(v["id"].as_u64().unwrap()); + s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 160, "height": 160})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap(); + s.execute("object.lock", &json!({})).unwrap(); + let white = id(s.execute("shape.rectangle", &json!({"x": 40, "y": 40, "width": 120, "height": 120})).unwrap()); + s.execute("paint.setFill", &json!({"color": "#ffffff"})).unwrap(); + let black = id(s.execute("shape.rectangle", &json!({"x": 60, "y": 60, "width": 80, "height": 80})).unwrap()); + s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap(); + s.execute("object.group", &json!({"ids": [white.0, black.0]})).unwrap(); + s.execute("transparency.set", &json!({"opacity": 50})).unwrap(); + s.active_mut().unwrap().selection.objects = vec![black]; + let r = s.execute("color.contrast", &json!({})).unwrap(); + let doc = &s.doc().unwrap().doc; + let img = vectorcraft_render::Renderer::new().render_region(doc, vectorcraft_geom::Rect::new(99.0, 99.0, 101.0, 101.0), 1.0, true); + let p = img.pixel(1, 1); + let behind = vectorcraft_color::Color::from_hex(r["against"].as_str().unwrap()).unwrap().to_rgb_uncalibrated(); + let drawn = vectorcraft_color::wcag::contrast_ratio([p[0], p[1], p[2]].map(|v| f32::from(v) / 255.0), behind); + assert!(p[0] < 3, "the canvas draws black: {p:?}"); + assert!((ratio(&r) - drawn).abs() < 0.02, "{r} against {drawn}"); +} + +/// The pixel the canvas draws at (100, 100), and its contrast against the answer's `against`. +fn canvas_ratio(s: &Session, r: &Value) -> ([u8; 4], f64) { + let doc = &s.doc().unwrap().doc; + let img = vectorcraft_render::Renderer::new().render_region(doc, vectorcraft_geom::Rect::new(99.0, 99.0, 101.0, 101.0), 1.0, true); + let p = img.pixel(1, 1); + let behind = vectorcraft_color::Color::from_hex(r["against"].as_str().unwrap()).unwrap().to_rgb_uncalibrated(); + (p, vectorcraft_color::wcag::contrast_ratio([p[0], p[1], p[2]].map(|v| f32::from(v) / 255.0), behind)) +} + +/// A selected white Multiply square over a white one in a 50 % group over black: the square +/// multiplies with the white inside the group, and the group's opacity applies once. +#[test] +fn a_blend_mode_in_a_translucent_group_blends_with_the_art_inside_it() { + let mut s = session(); + let id = |v: Value| vectorcraft_doc::NodeId(v["id"].as_u64().unwrap()); + s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 160, "height": 160})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap(); + s.execute("object.lock", &json!({})).unwrap(); + let back = id(s.execute("shape.rectangle", &json!({"x": 40, "y": 40, "width": 120, "height": 120})).unwrap()); + s.execute("paint.setFill", &json!({"color": "#ffffff"})).unwrap(); + let square = id(s.execute("shape.rectangle", &json!({"x": 60, "y": 60, "width": 80, "height": 80})).unwrap()); + s.execute("paint.setFill", &json!({"color": "#ffffff"})).unwrap(); + s.execute("transparency.set", &json!({"blend": "multiply"})).unwrap(); + s.execute("object.group", &json!({"ids": [back.0, square.0]})).unwrap(); + s.execute("transparency.set", &json!({"opacity": 50})).unwrap(); + s.active_mut().unwrap().selection.objects = vec![square]; + let r = s.execute("color.contrast", &json!({})).unwrap(); + let (p, drawn) = canvas_ratio(&s, &r); + assert!((i32::from(p[0]) - 128).abs() < 3, "the canvas draws half gray: {p:?}"); + assert!((ratio(&r) - drawn).abs() < 0.02, "{r} against {drawn}"); +} + +/// In a dynamic symbol instance whose art is a 50 % group of a black square over a white one, over +/// black, the picked black square draws over the black outside the group, not over the group's +/// white. +#[test] +fn a_picked_symbol_object_in_a_translucent_group_of_the_art_draws_over_what_is_outside_it() { + let mut s = session(); + let id = |v: Value| vectorcraft_doc::NodeId(v["id"].as_u64().unwrap()); + s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 160, "height": 160})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap(); + s.execute("object.lock", &json!({})).unwrap(); + let white = id(s.execute("shape.rectangle", &json!({"x": 40, "y": 40, "width": 120, "height": 120})).unwrap()); + s.execute("paint.setFill", &json!({"color": "#ffffff"})).unwrap(); + let black = id(s.execute("shape.rectangle", &json!({"x": 60, "y": 60, "width": 80, "height": 80})).unwrap()); + s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap(); + let group = id(s.execute("object.group", &json!({"ids": [white.0, black.0]})).unwrap()); + s.execute("transparency.set", &json!({"opacity": 50})).unwrap(); + let inst = id(s.execute("symbol.new", &json!({"name": "Pair", "ids": [group.0], "type": "dynamic"})).unwrap()); + let doc = &s.doc().unwrap().doc; + let art = &doc.symbols.iter().find(|x| x.name == "Pair").unwrap().art; + let path = if vectorcraft_doc::symbol_overrides::part(art, &[0, 1]).is_some() { vec![0, 1] } else { vec![1] }; + let st = s.active_mut().unwrap(); + st.selection.objects = vec![inst]; + st.selection.symbol_part = Some(vectorcraft_doc::SymbolPart { instance: inst, path }); + let r = s.execute("color.contrast", &json!({})).unwrap(); + let (p, drawn) = canvas_ratio(&s, &r); + assert!(p[0] < 3, "the canvas draws black: {p:?}"); + assert!((ratio(&r) - drawn).abs() < 0.02, "{r} against {drawn}"); +} + +/// As above with the group's 50 % set by the instance instead of the symbol, and the picked black +/// square itself at 50 %: the square draws over the group's white, read with the instance's +/// opacity for the group taken out, then the group's 50 % applies once over the black outside. +#[test] +fn an_instances_opacity_for_a_group_of_its_art_applies_once() { + let mut s = session(); + let id = |v: Value| vectorcraft_doc::NodeId(v["id"].as_u64().unwrap()); + s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 160, "height": 160})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap(); + s.execute("object.lock", &json!({})).unwrap(); + let white = id(s.execute("shape.rectangle", &json!({"x": 40, "y": 40, "width": 120, "height": 120})).unwrap()); + s.execute("paint.setFill", &json!({"color": "#ffffff"})).unwrap(); + let black = id(s.execute("shape.rectangle", &json!({"x": 60, "y": 60, "width": 80, "height": 80})).unwrap()); + s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap(); + s.execute("transparency.set", &json!({"opacity": 50})).unwrap(); + let group = id(s.execute("object.group", &json!({"ids": [white.0, black.0]})).unwrap()); + let inst = id(s.execute("symbol.new", &json!({"name": "Pair", "ids": [group.0], "type": "dynamic"})).unwrap()); + let doc = &s.doc().unwrap().doc; + let art = &doc.symbols.iter().find(|x| x.name == "Pair").unwrap().art; + let path = if vectorcraft_doc::symbol_overrides::part(art, &[0, 1]).is_some() { vec![0, 1] } else { vec![1] }; + let st = s.active_mut().unwrap(); + let n = std::sync::Arc::make_mut(&mut st.doc).node_mut(inst).unwrap(); + let over = vectorcraft_doc::SymbolOverride { path: path[..path.len() - 1].to_vec(), opacity: Some(0.5), ..Default::default() }; + n.extras_mut().symbol_overrides = vec![over]; + st.selection.objects = vec![inst]; + st.selection.symbol_part = Some(vectorcraft_doc::SymbolPart { instance: inst, path }); + let r = s.execute("color.contrast", &json!({})).unwrap(); + let (p, drawn) = canvas_ratio(&s, &r); + assert!((i32::from(p[0]) - 64).abs() < 3, "the canvas draws a quarter gray: {p:?}"); + assert!((ratio(&r) - drawn).abs() < 0.02, "{r} against {drawn}"); +} + +/// A selected 50 % black square in a 50 % group, over a 50 % white square, all in a Difference group +/// over gray: the inner group's opacity applies to the black square only, and the white beside the +/// inner group counts once in the alpha the Difference group takes the gray back out by. +#[test] +fn a_groups_opacity_leaves_out_the_art_beside_it_in_a_blending_group() { + let mut s = session(); + let id = |v: Value| vectorcraft_doc::NodeId(v["id"].as_u64().unwrap()); + s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 160, "height": 160})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#8c8c8c"})).unwrap(); + s.execute("object.lock", &json!({})).unwrap(); + let white = id(s.execute("shape.rectangle", &json!({"x": 40, "y": 40, "width": 120, "height": 120})).unwrap()); + s.execute("paint.setFill", &json!({"color": "#ffffff"})).unwrap(); + s.execute("transparency.set", &json!({"opacity": 50})).unwrap(); + let black = id(s.execute("shape.rectangle", &json!({"x": 60, "y": 60, "width": 80, "height": 80})).unwrap()); + s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap(); + s.execute("transparency.set", &json!({"opacity": 50})).unwrap(); + let inner = id(s.execute("object.group", &json!({"ids": [black.0]})).unwrap()); + s.execute("transparency.set", &json!({"opacity": 50})).unwrap(); + s.execute("object.group", &json!({"ids": [white.0, inner.0]})).unwrap(); + s.execute("transparency.set", &json!({"blend": "difference"})).unwrap(); + s.active_mut().unwrap().selection.objects = vec![black]; + let r = s.execute("color.contrast", &json!({})).unwrap(); + let (p, drawn) = canvas_ratio(&s, &r); + // The canvas pixel is rounded to 8 bits, which moves this dark gray's ratio by up to 0.04; with + // the white counted twice the answer is 3.15. + assert!((ratio(&r) - drawn).abs() < 0.05, "{r} against {drawn} ({p:?})"); +} + +/// An object that isolates its blending, with a white Multiply fill over a blue one, over red: the +/// white multiplies with the blue row below it. +#[test] +fn a_row_in_an_isolating_object_blends_with_the_rows_below_it() { + let mut s = blended_over_red("normal"); + s.execute("paint.setFill", &json!({"color": "#0000ff"})).unwrap(); + s.execute("appearance.addFill", &json!({})).unwrap(); + let st = s.active().unwrap(); + let items = &st.doc.node(st.selection.objects[0]).unwrap().appearance.items; + let top = items.iter().rposition(|i| matches!(i, vectorcraft_doc::AppearanceItem::Fill(_))).unwrap(); + s.execute("appearance.setItem", &json!({"index": top, "color": "#ffffff", "blend": "multiply"})).unwrap(); + s.execute("appearance.setActiveItem", &json!({"index": null})).unwrap(); + s.execute("transparency.set", &json!({"item": null, "isolate": true})).unwrap(); + let r = s.execute("color.contrast", &json!({})).unwrap(); + let (p, drawn) = canvas_ratio(&s, &r); + assert!(p[0] < 3 && p[2] > 252, "the canvas draws blue: {p:?}"); + assert!((ratio(&r) - drawn).abs() < 0.02, "{r} against {drawn}"); +} + +/// An object that isolates its blending, in a Screen group over black: a 50 % white fill over an +/// opaque white one composites to opaque white inside the object, so the group screens opaque +/// white. With the lower fill removed, the object holds the white at 50 %. +#[test] +fn an_isolating_object_in_a_blending_group_carries_the_alpha_of_its_composite() { + let mut s = session(); + let id = |v: Value| vectorcraft_doc::NodeId(v["id"].as_u64().unwrap()); + s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 160, "height": 160})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap(); + s.execute("object.lock", &json!({})).unwrap(); + let square = id(s.execute("shape.rectangle", &json!({"x": 50, "y": 50, "width": 100, "height": 100})).unwrap()); + s.execute("paint.setFill", &json!({"color": "#ffffff"})).unwrap(); + s.execute("appearance.addFill", &json!({})).unwrap(); + let st = s.active().unwrap(); + let items = &st.doc.node(square).unwrap().appearance.items; + let top = items.iter().rposition(|i| matches!(i, vectorcraft_doc::AppearanceItem::Fill(_))).unwrap(); + let lower = items.iter().position(|i| matches!(i, vectorcraft_doc::AppearanceItem::Fill(_))).unwrap(); + s.execute("appearance.setItem", &json!({"index": top, "color": "#ffffff", "opacity": 50})).unwrap(); + s.execute("appearance.setActiveItem", &json!({"index": null})).unwrap(); + s.execute("transparency.set", &json!({"item": null, "isolate": true})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + s.execute("transparency.set", &json!({"blend": "screen"})).unwrap(); + s.active_mut().unwrap().selection.objects = vec![square]; + let r = s.execute("color.contrast", &json!({})).unwrap(); + let (p, drawn) = canvas_ratio(&s, &r); + assert!(p[0] > 252 && p[1] > 252 && p[2] > 252, "the canvas draws white: {p:?}"); + assert!((ratio(&r) - drawn).abs() < 0.02, "{r} against {drawn}"); + assert_eq!(r["normalText"], json!({"aa": true, "aaa": true}), "{r}"); + s.execute("appearance.removeItem", &json!({"index": lower})).unwrap(); + s.execute("appearance.setActiveItem", &json!({"index": null})).unwrap(); + let r = s.execute("color.contrast", &json!({})).unwrap(); + let (p, drawn) = canvas_ratio(&s, &r); + assert!((i32::from(p[0]) - 128).abs() < 3, "the canvas draws half gray: {p:?}"); + // The canvas pixel is rounded to 8 bits, which moves a ratio near half gray by up to 0.04. + assert!((ratio(&r) - drawn).abs() < 0.05, "{r} against {drawn}"); +} + +/// A 50 % white fill over an opaque blue one draws over the blue, not over the red art behind it. +#[test] +fn a_translucent_row_draws_over_the_rows_below_it() { + let mut s = blended_over_red("normal"); + s.execute("paint.setFill", &json!({"color": "#0000ff"})).unwrap(); + s.execute("appearance.addFill", &json!({})).unwrap(); + let st = s.active().unwrap(); + let items = &st.doc.node(st.selection.objects[0]).unwrap().appearance.items; + let top = items.iter().rposition(|i| matches!(i, vectorcraft_doc::AppearanceItem::Fill(_))).unwrap(); + s.execute("appearance.setItem", &json!({"index": top, "color": "#ffffff", "opacity": 50})).unwrap(); + s.execute("appearance.setActiveItem", &json!({"index": null})).unwrap(); + let r = s.execute("color.contrast", &json!({})).unwrap(); + let (p, drawn) = canvas_ratio(&s, &r); + assert!((i32::from(p[0]) - 128).abs() < 3 && p[2] > 252, "the canvas draws the white at 50 % over the blue: {p:?}"); + assert!((ratio(&r) - drawn).abs() < 0.02, "{r} against {drawn}"); +} + +/// A path's Normal fill row and type's character paint draw one black alike. +#[test] +fn a_normal_fill_row_and_type_of_one_color_leave_one_answer() { + let mut s = session(); + let id = |v: Value| v["id"].as_u64().unwrap(); + let a = id(s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 40, "height": 40})).unwrap()); + s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap(); + let t = id(s.execute("text.create", &json!({"x": 80, "y": 60, "text": "Label", "size": 24, "color": "#000000"})).unwrap()); + s.execute("select.set", &json!({"ids": [a, t]})).unwrap(); + let r = s.execute("color.contrast", &json!({"against": "#ffffff"})).unwrap(); + assert!((ratio(&r) - 21.0).abs() < 1e-6, "{r}"); +} + +/// In a group that isolates its blending, a selected white Multiply square blends with the blue +/// art the group holds, and with nothing outside it. +#[test] +fn a_blend_mode_in_an_isolating_group_blends_with_the_art_inside_it_only() { + let mut s = session(); + let id = |v: Value| vectorcraft_doc::NodeId(v["id"].as_u64().unwrap()); + s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 160, "height": 160})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + s.execute("object.lock", &json!({})).unwrap(); + let back = id(s.execute("shape.rectangle", &json!({"x": 40, "y": 40, "width": 120, "height": 120})).unwrap()); + s.execute("paint.setFill", &json!({"color": "#0000ff"})).unwrap(); + let square = id(s.execute("shape.rectangle", &json!({"x": 60, "y": 60, "width": 80, "height": 80})).unwrap()); + s.execute("paint.setFill", &json!({"color": "#ffffff"})).unwrap(); + s.execute("transparency.set", &json!({"blend": "multiply"})).unwrap(); + s.execute("object.group", &json!({"ids": [back.0, square.0]})).unwrap(); + s.execute("transparency.set", &json!({"isolate": true})).unwrap(); + s.active_mut().unwrap().selection.objects = vec![square]; + let r = s.execute("color.contrast", &json!({})).unwrap(); + let (p, drawn) = canvas_ratio(&s, &r); + assert!(p[0] < 3 && p[2] > 252, "the canvas draws blue: {p:?}"); + assert!((ratio(&r) - drawn).abs() < 0.02, "{r} against {drawn}"); + // With the blue art out of the group, the square blends with nothing and draws white over red. + s.execute("select.set", &json!({"ids": [back.0]})).unwrap(); + s.execute("object.hide", &json!({})).unwrap(); + s.active_mut().unwrap().selection.objects = vec![square]; + let r = s.execute("color.contrast", &json!({})).unwrap(); + let (p, drawn) = canvas_ratio(&s, &r); + assert!(p[1] > 252, "the canvas draws white: {p:?}"); + assert!((ratio(&r) - drawn).abs() < 0.02, "{r} against {drawn}"); +} + +#[test] +fn template_layers_and_guides_are_left_out_of_the_background() { + let mut s = session(); + let first = s.doc().unwrap().doc.layers[0].id; + s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 160, "height": 160})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + s.execute("layer.setProps", &json!({"id": first.0, "template": true})).unwrap(); + s.execute("layer.new", &json!({"top": true})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 40, "y": 40, "width": 120, "height": 120})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#00ff00"})).unwrap(); + s.execute("view.guides.make", &json!({})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 60, "y": 60, "width": 80, "height": 80})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap(); + let r = s.execute("color.contrast", &json!({})).unwrap(); + assert_eq!(r["against"], "#ffffff", "the artboard, without the template's red or the guide: {r}"); +} + +#[test] +fn objects_that_draw_one_color_differently_have_no_one_answer() { + let mut s = session(); + let id = |v: Value| v["id"].as_u64().unwrap(); + let a = id(s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 40, "height": 40})).unwrap()); + let b = id(s.execute("shape.rectangle", &json!({"x": 80, "y": 20, "width": 40, "height": 40})).unwrap()); + s.execute("paint.setFill", &json!({"ids": [a, b], "color": "#000000"})).unwrap(); + s.execute("select.set", &json!({"ids": [a, b]})).unwrap(); + let r = s.execute("color.contrast", &json!({"against": "#ffffff"})).unwrap(); + assert!((ratio(&r) - 21.0).abs() < 1e-6, "{r}"); + s.execute("select.set", &json!({"ids": [b]})).unwrap(); + s.execute("transparency.set", &json!({"opacity": 50})).unwrap(); + s.execute("select.set", &json!({"ids": [a, b]})).unwrap(); + let e = s.execute("color.contrast", &json!({"against": "#ffffff"})).unwrap_err().to_string(); + assert!(e.contains("the selected objects' colors differ: give `opacity` or `color`"), "{e}"); + s.execute("color.contrast", &json!({"color": "#000000", "against": "#ffffff"})).unwrap(); + // A given opacity takes the place of the objects' own. + let r = s.execute("color.contrast", &json!({"against": "#ffffff", "opacity": 100})).unwrap(); + assert!((ratio(&r) - 21.0).abs() < 1e-6, "{r}"); + // A blend mode that differs is not one a given opacity replaces. + s.execute("select.set", &json!({"ids": [b]})).unwrap(); + s.execute("transparency.set", &json!({"opacity": 100, "blend": "multiply"})).unwrap(); + s.execute("select.set", &json!({"ids": [a, b]})).unwrap(); + let e = s.execute("color.contrast", &json!({"against": "#ffffff"})).unwrap_err().to_string(); + assert!(e.contains("the selected objects' colors differ: give `color`"), "{e}"); +} + +/// A 50 % white row over a blue row in an opaque object draws over the blue; an opaque white row in +/// a 50 % object draws over what is behind it, though both draw the white at 50 %. +#[test] +fn a_row_and_an_object_of_one_total_opacity_draw_differently_over_the_rows_below() { + let mut s = session(); + let id = |v: Value| v["id"].as_u64().unwrap(); + let a = id(s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 40, "height": 40})).unwrap()); + s.execute("paint.setFill", &json!({"color": "#0000ff"})).unwrap(); + s.execute("appearance.addFill", &json!({})).unwrap(); + let st = s.active().unwrap(); + let items = &st.doc.node(st.selection.objects[0]).unwrap().appearance.items; + let top = items.iter().rposition(|i| matches!(i, vectorcraft_doc::AppearanceItem::Fill(_))).unwrap(); + s.execute("appearance.setItem", &json!({"index": top, "color": "#ffffff", "opacity": 50})).unwrap(); + s.execute("appearance.setActiveItem", &json!({"index": null})).unwrap(); + let b = id(s.execute("shape.rectangle", &json!({"x": 80, "y": 20, "width": 40, "height": 40})).unwrap()); + s.execute("paint.setFill", &json!({"color": "#ffffff"})).unwrap(); + s.execute("transparency.set", &json!({"opacity": 50})).unwrap(); + s.execute("select.set", &json!({"ids": [a, b]})).unwrap(); + let e = s.execute("color.contrast", &json!({})).unwrap_err().to_string(); + assert!(e.contains("the selected objects' colors differ: give `opacity` or `color`"), "{e}"); + // A given background stands for the rows below, so both draw the white at 50 % over it. + let r = s.execute("color.contrast", &json!({"against": "#000000"})).unwrap(); + let gray = vectorcraft_color::wcag::contrast_ratio([0.5; 3], [0.0; 3]); + assert!((ratio(&r) - gray).abs() < 1e-3, "{r}"); +} + +/// Two squares with the same 50 % white top fill, one over an opaque black fill and one over an +/// opaque white one, draw the white over different rows: no one answer. Over the same lower fill +/// they leave one answer, also when one of them has a lower row with no paint. +#[test] +fn translucent_rows_over_different_lower_rows_have_no_one_answer() { + let mut s = session(); + let id = |v: Value| v["id"].as_u64().unwrap(); + let square = |s: &mut Session, x: i32, lower: &str| { + let n = id(s.execute("shape.rectangle", &json!({"x": x, "y": 50, "width": 50, "height": 100})).unwrap()); + s.execute("paint.setFill", &json!({"color": lower})).unwrap(); + s.execute("appearance.addFill", &json!({})).unwrap(); + let st = s.active().unwrap(); + let items = &st.doc.node(vectorcraft_doc::NodeId(n)).unwrap().appearance.items; + let top = items.iter().rposition(|i| matches!(i, vectorcraft_doc::AppearanceItem::Fill(_))).unwrap(); + s.execute("appearance.setItem", &json!({"index": top, "color": "#ffffff", "opacity": 50})).unwrap(); + s.execute("appearance.setActiveItem", &json!({"index": null})).unwrap(); + n + }; + let a = square(&mut s, 50, "#000000"); + let b = square(&mut s, 100, "#ffffff"); + s.execute("select.set", &json!({"ids": [a, b]})).unwrap(); + let e = s.execute("color.contrast", &json!({})).unwrap_err().to_string(); + assert!(e.contains("the selected objects' colors differ"), "{e}"); + let c = square(&mut s, 150, "#000000"); + s.execute("select.set", &json!({"ids": [a, c]})).unwrap(); + s.execute("color.contrast", &json!({})).unwrap(); + // A row with no paint draws nothing, so it does not count among the rows below. + s.execute("select.set", &json!({"ids": [c]})).unwrap(); + s.execute("appearance.addFill", &json!({})).unwrap(); + let st = s.active().unwrap(); + let items = &st.doc.node(vectorcraft_doc::NodeId(c)).unwrap().appearance.items; + let fills: Vec = items.iter().enumerate().filter(|(_, i)| i.is_fill()).map(|(k, _)| k).collect(); + let (middle, top) = (fills[fills.len() - 2], fills[fills.len() - 1]); + s.execute("appearance.setItem", &json!({"ids": [c], "index": top, "color": "#ffffff", "opacity": 50})).unwrap(); + s.execute("appearance.setItem", &json!({"ids": [c], "index": middle, "none": true})).unwrap(); + s.execute("appearance.setActiveItem", &json!({"index": null})).unwrap(); + s.execute("select.set", &json!({"ids": [a, c]})).unwrap(); + s.execute("color.contrast", &json!({})).unwrap(); +} + +#[test] +fn a_selected_group_whose_objects_draw_one_color_differently_has_no_one_answer() { + let mut s = session(); + let id = |v: Value| v["id"].as_u64().unwrap(); + let a = id(s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 40, "height": 40})).unwrap()); + let b = id(s.execute("shape.rectangle", &json!({"x": 80, "y": 20, "width": 40, "height": 40})).unwrap()); + s.execute("paint.setFill", &json!({"ids": [a, b], "color": "#000000"})).unwrap(); + let g = id(s.execute("object.group", &json!({"ids": [a, b]})).unwrap()); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("color.contrast", &json!({"against": "#ffffff"})).unwrap(); + assert!((ratio(&r) - 21.0).abs() < 1e-6, "{r}"); + s.execute("select.set", &json!({"ids": [b]})).unwrap(); + s.execute("transparency.set", &json!({"opacity": 50})).unwrap(); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let e = s.execute("color.contrast", &json!({"against": "#ffffff"})).unwrap_err().to_string(); + assert!(e.contains("the selected objects' colors differ: give `opacity` or `color`"), "{e}"); +} + +#[test] +fn a_hidden_object_in_a_selected_group_leaves_one_answer() { + let id = |v: Value| v["id"].as_u64().unwrap(); + // The first and then the second object hidden: the hidden one is neither compared nor measured. + for first in [false, true] { + let mut s = session(); + let a = id(s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 40, "height": 40})).unwrap()); + let b = id(s.execute("shape.rectangle", &json!({"x": 80, "y": 20, "width": 40, "height": 40})).unwrap()); + s.execute("paint.setFill", &json!({"ids": [a, b], "color": "#000000"})).unwrap(); + let g = id(s.execute("object.group", &json!({"ids": [a, b]})).unwrap()); + s.execute("select.set", &json!({"ids": [if first { a } else { b }]})).unwrap(); + s.execute("transparency.set", &json!({"opacity": 50})).unwrap(); + s.execute("object.hide", &json!({})).unwrap(); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("color.contrast", &json!({"against": "#ffffff"})).unwrap(); + assert!((ratio(&r) - 21.0).abs() < 1e-6, "first hidden {first}: {r}"); + } +} + +#[test] +fn a_given_color_is_drawn_at_a_given_opacity() { + let mut s = Session::new(); + let r = s.execute("color.contrast", &json!({"color": "#000000", "against": "#ffffff", "opacity": 50})).unwrap(); + let opaque = s.execute("color.contrast", &json!({"color": "#808080", "against": "#ffffff"})).unwrap(); + assert!((ratio(&r) - ratio(&opaque)).abs() < 0.05, "{r} {opaque}"); + assert!(ratio(&r) < 5.0, "{r}"); +} + +#[test] +fn an_opaque_group_around_one_of_the_objects_leaves_one_answer() { + let mut s = session(); + let id = |v: Value| v["id"].as_u64().unwrap(); + let a = id(s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 40, "height": 40})).unwrap()); + let b = id(s.execute("shape.rectangle", &json!({"x": 80, "y": 20, "width": 40, "height": 40})).unwrap()); + s.execute("paint.setFill", &json!({"ids": [a, b], "color": "#000000"})).unwrap(); + s.execute("object.group", &json!({"ids": [b]})).unwrap(); + s.execute("select.set", &json!({"ids": [a, b]})).unwrap(); + let r = s.execute("color.contrast", &json!({"against": "#ffffff"})).unwrap(); + assert!((ratio(&r) - 21.0).abs() < 1e-6, "{r}"); +} + +#[test] +fn objects_in_two_groups_of_one_opacity_answer_against_a_given_color() { + let mut s = session(); + let id = |v: Value| v["id"].as_u64().unwrap(); + let a = id(s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 40, "height": 40})).unwrap()); + let b = id(s.execute("shape.rectangle", &json!({"x": 80, "y": 20, "width": 40, "height": 40})).unwrap()); + s.execute("paint.setFill", &json!({"ids": [a, b], "color": "#000000"})).unwrap(); + for o in [a, b] { + let g = id(s.execute("object.group", &json!({"ids": [o]})).unwrap()); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + s.execute("transparency.set", &json!({"opacity": 50})).unwrap(); + } + s.execute("select.set", &json!({"ids": [a, b]})).unwrap(); + s.execute("color.contrast", &json!({"against": "#ffffff"})).unwrap(); + // Sampled, each group is hidden in turn to read what is outside it, so the two differ. + let e = s.execute("color.contrast", &json!({})).unwrap_err().to_string(); + assert!(e.contains("the selected objects' colors differ: give `opacity` or `color`"), "{e}"); +} + +#[test] +fn a_hidden_fill_row_has_no_color_to_measure() { + let mut s = blended_over_red("normal"); + s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap(); + s.execute("appearance.setItem", &json!({"index": fill_index(&s), "visible": false})).unwrap(); + let e = s.execute("color.contrast", &json!({"against": "#ffffff"})).unwrap_err().to_string(); + assert!(e.contains("the active fill or stroke is hidden: give `color`"), "{e}"); + let given = s.execute("color.contrast", &json!({"color": "#000000", "against": "#ffffff"})).unwrap(); + assert!((ratio(&given) - 21.0).abs() < 1e-6, "{given}"); +} + +/// An opacity mask on the object, or on a group around it, sets how much of the color shows at each +/// point, so the color has no one opacity to measure; a disabled mask draws nothing. +#[test] +fn a_color_drawn_through_an_opacity_mask_has_no_one_answer() { + let mut s = session(); + let rect = |s: &mut Session, color: &str| { + let id = s.execute("shape.rectangle", &json!({"x": 50, "y": 50, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap(); + s.execute("paint.setFill", &json!({"color": color, "ids": [id]})).unwrap(); + id + }; + let masked = |s: &mut Session, owner: u64, color: &str| { + let m = rect(s, color); + s.execute("select.set", &json!({"ids": [owner, m]})).unwrap(); + s.execute("transparency.makeOpacityMask", &json!({})).unwrap(); + s.execute("select.set", &json!({"ids": [owner]})).unwrap(); + }; + let black = rect(&mut s, "#000000"); + masked(&mut s, black, "#000000"); + let e = s.execute("color.contrast", &json!({})).unwrap_err().to_string(); + assert!(e.contains("drawn through an opacity mask: give `color`"), "{e}"); + let e = s.execute("color.contrast", &json!({"against": "#ffffff", "opacity": 100})).unwrap_err().to_string(); + assert!(e.contains("drawn through an opacity mask"), "{e}"); + let given = s.execute("color.contrast", &json!({"color": "#000000", "against": "#ffffff"})).unwrap(); + assert!((ratio(&given) - 21.0).abs() < 1e-6, "{given}"); + s.execute("transparency.disableOpacityMask", &json!({})).unwrap(); + let r = s.execute("color.contrast", &json!({})).unwrap(); + assert!((ratio(&r) - 21.0).abs() < 1e-3, "a disabled mask leaves the black as it is: {r}"); + // A group's mask counts for the objects inside it. + let mut s = session(); + let inner = rect(&mut s, "#000000"); + let group = s.execute("object.group", &json!({"ids": [inner]})).unwrap()["id"].as_u64().unwrap(); + masked(&mut s, group, "#000000"); + s.execute("select.set", &json!({"ids": [inner]})).unwrap(); + let e = s.execute("color.contrast", &json!({})).unwrap_err().to_string(); + assert!(e.contains("drawn through an opacity mask"), "{e}"); +} + +/// A background sampled across an edge averages two colors; the answer's `against` is exactly the +/// background the ratio used, so giving it back answers the same ratio. +#[test] +fn the_background_written_back_answers_the_same_ratio() { + let mut s = session(); + s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 80.3, "height": 160})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#2050a0"})).unwrap(); + s.execute("object.lock", &json!({})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 50, "y": 50, "width": 100, "height": 100})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#808080"})).unwrap(); + let below = s.execute("color.contrast", &json!({})).unwrap(); + let hex = below["against"].as_str().unwrap(); + assert!(hex != "#ffffff" && hex != "#2050a0", "the sample straddles the edge: {below}"); + let given = s.execute("color.contrast", &json!({"against": hex})).unwrap(); + assert!((ratio(&below) - ratio(&given)).abs() < 1e-6, "{below} {given}"); +} + +/// In a 50 % group, a selected black square over a red one draws over the white outside the group, +/// while a given background stands for the art below every level, so giving the answer's `against` +/// back draws the black at 50 % over it instead. +#[test] +fn a_background_given_back_stands_for_the_art_outside_a_translucent_group() { + let mut s = session(); + let id = |v: Value| vectorcraft_doc::NodeId(v["id"].as_u64().unwrap()); + let red = id(s.execute("shape.rectangle", &json!({"x": 40, "y": 40, "width": 120, "height": 120})).unwrap()); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + let black = id(s.execute("shape.rectangle", &json!({"x": 60, "y": 60, "width": 80, "height": 80})).unwrap()); + s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap(); + s.execute("object.group", &json!({"ids": [red.0, black.0]})).unwrap(); + s.execute("transparency.set", &json!({"opacity": 50})).unwrap(); + s.active_mut().unwrap().selection.objects = vec![black]; + let below = s.execute("color.contrast", &json!({})).unwrap(); + let (_, drawn) = canvas_ratio(&s, &below); + assert!((ratio(&below) - drawn).abs() < 0.02, "{below} against {drawn}"); + let hex = below["against"].as_str().unwrap(); + let behind = vectorcraft_color::Color::from_hex(hex).unwrap().to_rgb_uncalibrated(); + let given = s.execute("color.contrast", &json!({"against": hex})).unwrap(); + let want = vectorcraft_color::wcag::contrast_ratio(vectorcraft_color::wcag::over([0.0; 3], 0.5, behind), behind); + assert!((ratio(&given) - want).abs() < 1e-3, "{given}"); + assert!((ratio(&below) - ratio(&given)).abs() > 0.1, "{below} {given}"); +} + +#[test] +fn an_object_that_isolates_its_blending_draws_its_fill_as_it_is() { + let mut s = blended_over_red("multiply"); + s.execute("transparency.set", &json!({"item": null, "isolate": true})).unwrap(); + let r = s.execute("color.contrast", &json!({})).unwrap(); + let drawn = drawn_ratio(&s); + let own = vectorcraft_color::wcag::contrast_ratio(vectorcraft_color::Color::from_hex("#4080c0").unwrap().to_rgb_uncalibrated(), [1.0, 0.0, 0.0]); + assert!((drawn - own).abs() < 0.02, "the canvas draws the fill unblended: {drawn} against {own}"); + assert!((ratio(&r) - drawn).abs() < 0.02, "{r} against {drawn}"); +} + +/// A dynamic symbol instance of a white square in front of a red one, at 50 % opacity, with its +/// white square picked. +fn picked_symbol_part() -> Session { + let mut s = session(); + let id = |v: Value| vectorcraft_doc::NodeId(v["id"].as_u64().unwrap()); + let back = id(s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 160, "height": 160})).unwrap()); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + let front = id(s.execute("shape.rectangle", &json!({"x": 50, "y": 50, "width": 100, "height": 100})).unwrap()); + s.execute("paint.setFill", &json!({"color": "#ffffff"})).unwrap(); + let inst = id(s.execute("symbol.new", &json!({"name": "Pair", "ids": [back.0, front.0], "type": "dynamic"})).unwrap()); + s.execute("transparency.set", &json!({"opacity": 50})).unwrap(); + let st = s.active_mut().unwrap(); + st.selection.objects = vec![inst]; + st.selection.symbol_part = Some(vectorcraft_doc::SymbolPart { instance: inst, path: vec![1] }); + s +} + +#[test] +fn a_picked_symbol_object_is_measured_against_the_rest_of_its_instance() { + let mut s = picked_symbol_part(); + let r = s.execute("color.contrast", &json!({"opacity": 100})).unwrap(); + // The red square at 50 % over the artboard's white (#ff7f7f or #ff8080 as the renderer rounds + // it), not the artboard alone. + let hex = r["against"].as_str().unwrap(); + let gb = vectorcraft_color::Color::from_hex(hex).unwrap().to_rgb_uncalibrated(); + assert!(hex.starts_with("#ff") && (gb[1] - 0.5).abs() < 0.01 && (gb[2] - 0.5).abs() < 0.01, "{r}"); +} + +#[test] +fn a_picked_symbol_object_is_measured_with_its_instances_stain() { + let mut s = picked_symbol_part(); + let inst = s.active().unwrap().selection.symbol_part.as_ref().unwrap().instance; + // The instance's fill stains its art half way to black. + s.active_mut().unwrap().selection.symbol_part = None; + s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap(); + s.execute("transparency.set", &json!({"item": fill_index(&s), "opacity": 50})).unwrap(); + let n = s.doc().unwrap().doc.node(inst).unwrap().clone(); + assert!(vectorcraft_doc::symbol_overrides::stain(&n).is_some_and(|(_, a)| (a - 0.5).abs() < 1e-6)); + s.active_mut().unwrap().selection.symbol_part = Some(vectorcraft_doc::SymbolPart { instance: inst, path: vec![1] }); + let r = s.execute("color.contrast", &json!({"against": "#000000", "opacity": 100})).unwrap(); + let want = vectorcraft_color::wcag::contrast_ratio([0.5; 3], [0.0; 3]); + assert!((ratio(&r) - want).abs() < 1e-3, "white stained half way to black: {r}"); +} + +#[test] +fn a_picked_symbol_object_is_drawn_at_its_instances_opacity() { + let mut s = picked_symbol_part(); + let r = s.execute("color.contrast", &json!({"against": "#000000"})).unwrap(); + let gray = vectorcraft_color::wcag::contrast_ratio(vectorcraft_color::wcag::over([1.0; 3], 0.5, [0.0; 3]), [0.0; 3]); + assert!((ratio(&r) - gray).abs() < 1e-3, "the instance draws the white at 50 %: {r}"); +} + +#[test] +fn type_measures_its_characters_without_an_appearance_rows_opacity() { + let mut s = session(); + s.execute("text.create", &json!({"x": 40, "y": 100, "text": "Label", "size": 24, "color": "#000000"})).unwrap(); + s.execute("appearance.addFill", &json!({})).unwrap(); + let index = s.doc().unwrap().doc.node(s.doc().unwrap().selection.objects[0]).unwrap().appearance.items.len() - 1; + s.execute("appearance.setItem", &json!({"index": index, "opacity": 0})).unwrap(); + s.execute("appearance.setActiveItem", &json!({"index": null})).unwrap(); + let r = s.execute("color.contrast", &json!({})).unwrap(); + assert!((ratio(&r) - 21.0).abs() < 1e-3, "the characters stay opaque black: {r}"); +} + +#[test] +fn a_gradient_stop_counts_with_its_own_opacity() { + let mut s = session(); + s.execute("shape.rectangle", &json!({"x": 50, "y": 50, "width": 100, "height": 100})).unwrap(); + let stops = json!([{"offset": 0, "color": "#000000", "opacity": 0.5}, {"offset": 1, "color": "#ff0000"}]); + s.execute("paint.setFill", &json!({"gradient": {"stops": stops}})).unwrap(); + let r = s.execute("color.contrast", &json!({})).unwrap(); + let gray = vectorcraft_color::wcag::contrast_ratio([0.5; 3], [1.0; 3]); + assert!((ratio(&r) - gray).abs() < 1e-3, "the first stop, black at 50 %: {r}"); +} + +/// Picks the points of the selected gradient mesh inside the box from `a` to `b` with the Lasso tool. +fn pick_points(s: &mut Session, a: (f64, f64), b: (f64, f64)) { + use vectorcraft_tools::{PointerEvent, PointerKind}; + let v = ViewInfo::default(); + s.select_tool("lasso", v).unwrap(); + let pts = [(a.0, a.1), (b.0, a.1), (b.0, b.1), (a.0, b.1), (a.0, b.1)]; + for (i, (x, y)) in pts.iter().enumerate() { + let kind = match i { + 0 => PointerKind::Down, + 4 => PointerKind::Up, + _ => PointerKind::Drag, + }; + s.pointer(&PointerEvent::new(kind, *x, *y), v).unwrap(); + } +} + +#[test] +fn a_picked_mesh_point_counts_with_its_own_opacity() { + let mut s = session(); + s.execute("shape.rectangle", &json!({"x": 50, "y": 50, "width": 100, "height": 100})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap(); + s.execute("object.mesh.create", &json!({"rows": 1, "cols": 1})).unwrap(); + // The top-left point at 50 %, the top-right one opaque. + pick_points(&mut s, (40.0, 40.0), (60.0, 60.0)); + assert_eq!(s.fill_mesh_points().first().map(|(_, v)| v.len()), Some(1), "one point is picked"); + s.execute("transparency.set", &json!({"opacity": 50})).unwrap(); + let r = s.execute("color.contrast", &json!({})).unwrap(); + let gray = vectorcraft_color::wcag::contrast_ratio([0.5; 3], [1.0; 3]); + assert!((ratio(&r) - gray).abs() < 1e-3, "the picked point, black at 50 %: {r}"); + pick_points(&mut s, (140.0, 40.0), (160.0, 60.0)); + let r = s.execute("color.contrast", &json!({})).unwrap(); + assert!((ratio(&r) - 21.0).abs() < 1e-3, "the opaque point: {r}"); + // Both picked: one color at two opacities has no one answer, unless `opacity` is given. + pick_points(&mut s, (40.0, 40.0), (160.0, 60.0)); + let both = s.execute("color.contrast", &json!({})).unwrap_err().to_string(); + assert!(both.contains("the selected objects' colors differ: give `opacity` or `color`"), "{both}"); + assert!(s.execute("color.contrast", &json!({"opacity": 100})).is_ok()); +} + +#[test] +fn below_needs_a_selection_and_bad_params_are_errors() { + let mut s = session(); + let none = s.execute("color.contrast", &json!({})).unwrap_err().to_string(); + assert!(none.contains("nothing selected"), "{none}"); + // A given background needs no selection: the proxy shows the defaults for new art. + assert!(s.execute("color.contrast", &json!({"against": "#ffffff"})).is_ok()); + for bad in [ + json!({"color": "#000000", "against": "behind"}), + json!({"color": "#000000", "against": 3}), + json!({"color": "#00000080", "against": "#ffffff"}), + json!({"color": "nope", "against": "#ffffff"}), + json!({"color": "#000000", "against": "#ffffff", "opacity": 101}), + json!({"color": "#000000", "against": "#ffffff", "opacity": -1}), + json!({"color": "#000000", "against": "#ffffff", "opacity": "50"}), + ] { + assert!(s.execute("color.contrast", &bad).is_err(), "{bad}"); + } +} + +#[test] +fn a_fill_of_none_has_no_color_to_measure() { + let mut s = session(); + s.execute("shape.rectangle", &json!({"x": 50, "y": 50, "width": 100, "height": 100})).unwrap(); + s.execute("paint.setFill", &json!({"none": true})).unwrap(); + let e = s.execute("color.contrast", &json!({})).unwrap_err().to_string(); + assert!(e.contains("has no color"), "{e}"); + assert!(s.execute("color.contrast", &json!({"color": "#000000"})).is_ok()); +} diff --git a/crates/engine/src/tests/draw2.rs b/crates/engine/src/tests/draw2.rs index 5017316c44..6aec396704 100644 --- a/crates/engine/src/tests/draw2.rs +++ b/crates/engine/src/tests/draw2.rs @@ -3,7 +3,7 @@ use serde_json::json; use vectorcraft_doc::{NodeId, NodeKind}; use vectorcraft_geom::{FillRule, PathData, Point}; -use vectorcraft_tools::{Mods, PointerEvent, PointerKind, ToolKey}; +use vectorcraft_tools::{Mods, PenPose, PointerEvent, PointerKind, ToolKey}; use crate::tooling::{UiRequest, ViewInfo}; use crate::*; @@ -552,6 +552,28 @@ fn pencil_redraws_the_shorter_way_round_a_closed_path() { assert!(s.execute("path.freehand", &json!({"points": [[0, 0], [1, 1]], "redraw": {"id": id.0, "within": -1}})).is_err()); } +/// `preview` draws the stroke as a new path on top, beside the selected path, and leaves the +/// selection as it was, in Draw Behind and Draw Inside too, as the Pencil previews a stroke that +/// redraws a selected path. +#[test] +fn pencil_preview_draws_on_top_and_leaves_the_selection_as_it_was() { + for mode in ["normal", "behind", "inside"] { + let mut s = session(); + let r = rect(&mut s, 400.0, 400.0, 50.0, 50.0); + s.execute("select.set", &json!({"ids": [r.0]})).unwrap(); + s.execute("view.drawMode", &json!({ "mode": mode })).unwrap(); + let (parent, _, _) = s.doc().unwrap().doc.position(r).unwrap(); + let out = + s.execute("path.freehand", &json!({"points": [[100, 200], [150, 220], [200, 200]], "keepSelected": false, "preview": true})).unwrap(); + let id = NodeId(out["id"].as_u64().unwrap()); + let d = &s.doc().unwrap().doc; + let ((rp, ri, _), (np, ni, _)) = (d.position(r).unwrap(), d.position(id).unwrap()); + assert!(rp == parent && np == parent, "{mode}: beside the path, in no clip group"); + assert!(ni > ri, "{mode}: on top of the path"); + assert_eq!(s.doc().unwrap().selection.objects, vec![r], "{mode}: the selection as it was"); + } +} + /// With Keep selected off, a new stroke leaves nothing selected (the earlier selection goes too, /// as Illustrator starts the stroke by dropping it, #5752); a continued or redrawn path is /// deselected and the rest of the selection stays. The stroke is one undo step. @@ -617,8 +639,14 @@ fn freehand_with_fit_off_joins_the_points_with_straight_segments() { .unwrap(); let sp = path(&s, r).subpaths[0].clone(); assert!(corners(&sp), "{:?}", sp.anchors); + // Each end's bend stops `within` (4) along the stroke, at a point added on its first and last + // piece; the drawn points beyond stay as drawn. let inner: Vec<_> = at(&sp).into_iter().filter(|p| p.1 < 499.0).collect(); - assert_eq!(inner, [(125.0, 470.0), (150.0, 460.0), (175.0, 470.0)]); + let t = 4.0 / 25f64.hypot(31.0); + let near = |a: (f64, f64), b: (f64, f64)| (a.0 - b.0).abs() < 1e-9 && (a.1 - b.1).abs() < 1e-9; + assert_eq!(inner.len(), 5, "{inner:?}"); + assert!(near(inner[0], (100.0 + 25.0 * t, 501.0 - 31.0 * t)) && near(inner[4], (200.0 - 25.0 * t, 501.0 - 31.0 * t)), "{inner:?}"); + assert_eq!(inner[1..4], [(125.0, 470.0), (150.0, 460.0), (175.0, 470.0)]); assert!(s.execute("path.freehand", &json!({"points": [[0, 0], [1, 1]], "fit": "no"})).is_err()); } @@ -738,6 +766,76 @@ fn blob_brush_size_follows_the_pen_pressure() { assert!(inside(&s, drawn, 290.0, 707.0) && !inside(&s, drawn, 110.0, 703.0), "the tool's stroke follows the pen"); } +/// Blob Brush Tool Options' Size set to Stylus Wheel: the brush is Size − Variation wide where an +/// airbrush pen's finger wheel was at 0 and Size + Variation where it was at 1, in a drag, a click +/// and with a tip that is not round. A stroke without a wheel keeps the Size, pressure does not +/// change it, and an unknown mode or a wheel out of its range is refused with nothing painted. +#[test] +fn blob_brush_size_follows_the_stylus_wheel() { + let mut s = session(); + let inside = |s: &Session, id: NodeId, x: f64, y: f64| { + vectorcraft_geom::hit::fill_contains(&path(s, id).to_bezpath(), FillRule::NonZero, Point::new(x, y)) + }; + let blob = |s: &mut Session, p: serde_json::Value| NodeId(s.execute("path.blob", &p).unwrap()["id"].as_u64().unwrap()); + // The wheel at 0 at the left end and at 1 at the right: about 2 pt wide to 18 pt wide. + let wheeled = |y: f64, wheel: &dyn Fn(f64) -> serde_json::Value| { + (0..=20).map(|i| json!([100.0 + f64::from(i) * 10.0, y, null, null, null, null, wheel(f64::from(i) / 20.0)])).collect::>() + }; + let tip = json!({"size": 10, "sizeMode": "stylusWheel", "sizeVariation": 8, "merge": false}); + let a = blob(&mut s, with(&tip, json!({"points": wheeled(100.0, &|w| json!(w))}))); + assert!(inside(&s, a, 290.0, 107.0) && !inside(&s, a, 110.0, 103.0), "wide where the wheel was at 1, thin where at 0"); + let b = blob(&mut s, with(&tip, json!({"points": wheeled(200.0, &|w| json!(1.0 - w))}))); + assert!(inside(&s, b, 110.0, 207.0) && !inside(&s, b, 290.0, 203.0), "the other way round"); + // No wheel at any point, and pressure without a wheel: 10 pt wide all along. + let none = blob(&mut s, with(&tip, json!({"points": wheeled(300.0, &|_| json!(null))}))); + let pressed = (0..=20).map(|i| json!([100.0 + f64::from(i) * 10.0, 400.0, f64::from(i) / 20.0])).collect::>(); + let pressure = blob(&mut s, with(&tip, json!({"points": pressed}))); + for (id, y) in [(none, 300.0), (pressure, 400.0)] { + assert!(inside(&s, id, 110.0, y + 3.0) && inside(&s, id, 290.0, y + 3.0) && !inside(&s, id, 290.0, y + 7.0), "10 pt at y {y}"); + } + // A click paints one dab as wide as the wheel gives. + let wide = blob(&mut s, with(&tip, json!({"points": [[100, 500, null, null, null, null, 1]]}))); + let thin = blob(&mut s, with(&tip, json!({"points": [[300, 500, null, null, null, null, 0]]}))); + assert!(inside(&s, wide, 100.0, 508.0) && !inside(&s, thin, 300.0, 503.0), "a dab follows the wheel"); + // A stroke whose samples all lie at one point paints a dab sized from its first reading, with + // the wheel and with pressure. + let still = blob(&mut s, with(&tip, json!({"points": [[500, 500, null, null, null, null, 1], [500, 500, null, null, null, null, 0]]}))); + let pressed_still = blob(&mut s, with(&tip, json!({"sizeMode": "pressure", "points": [[700, 500, 1], [700, 500, 0]]}))); + for (id, x) in [(still, 500.0), (pressed_still, 700.0)] { + assert!(inside(&s, id, x, 508.0) && !inside(&s, id, x, 510.0), "a dab from the first reading at x {x}"); + } + // A 25% round tip lying level: about 0.5 pt tall at the left end to 4.5 pt at the right. + let flat = blob(&mut s, with(&tip, json!({"roundness": 25, "points": wheeled(600.0, &|w| json!(w))}))); + assert!(inside(&s, flat, 290.0, 601.9) && !inside(&s, flat, 110.0, 601.0), "a flat tip follows the wheel"); + // Refused, with the document and its undo steps as they were. + let (before, undo) = (paths(&s).len(), s.doc().unwrap().history.undo.len()); + for (bad, key) in [ + (json!({"points": wheeled(700.0, &|w| json!(w)), "sizeMode": "tilt", "sizeVariation": 8}), "sizeMode"), + (json!({"points": [[0, 700, null, null, null, null, 1.5], [10, 700]], "sizeMode": "stylusWheel", "sizeVariation": 8}), "wheel"), + ] { + let err = s.execute("path.blob", &bad).unwrap_err(); + assert!(err.to_string().contains(key), "{err}"); + } + assert_eq!((paths(&s).len(), s.doc().unwrap().history.undo.len()), (before, undo), "nothing changed"); + // The tool records the wheel while its Size varies with it. + let v = view(); + s.select_tool("blobBrush", v).unwrap(); + s.set_tool_option("sizeMode", &json!("stylusWheel")); + s.set_tool_option("sizeVariation", &json!(8)); + assert_eq!(s.tool_options()["sizeMode"], json!("stylusWheel")); + let ev = |kind, i: i32| PointerEvent { + pen: Some(PenPose { wheel: Some(i as f32 / 20.0), ..PenPose::default() }), + ..PointerEvent::new(kind, 100.0 + f64::from(i) * 10.0, 800.0) + }; + s.pointer(&ev(PointerKind::Down, 0), v).unwrap(); + for i in 1..20 { + s.pointer(&ev(PointerKind::Drag, i), v).unwrap(); + } + s.pointer(&ev(PointerKind::Up, 20), v).unwrap(); + let (drawn, _) = paths(&s).into_iter().find(|(_, p)| p.control_bounds().is_some_and(|b| b.y0 > 750.0)).unwrap(); + assert!(inside(&s, drawn, 290.0, 807.0) && !inside(&s, drawn, 110.0, 803.0), "the tool's stroke follows the wheel"); +} + /// Eraser Tool Options' Size set to Pressure (#3961): the tip is Size − Variation across where the /// pen pressed lightest and Size + Variation where it pressed hardest; Fixed erases at the Size. #[test] @@ -1802,6 +1900,64 @@ fn smooth_region_refits_at_the_tolerance_sent_at_any_zoom() { } } +/// A line from (100, 200) to (400, 200) jagged by up to 6 pt either way, the same every time. +fn jagged_line_anchors() -> Vec { + let mut seed = 7u64; + (0..=60) + .map(|i| { + seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + let noise = ((seed >> 11) as f64 / (1u64 << 53) as f64) * 2.0 - 1.0; + json!({"x": 100.0 + f64::from(i) * 5.0, "y": 200.0 + 6.0 * noise}) + }) + .collect() +} + +/// The path a `path.smoothRegion` drag along [`jagged_line_anchors`] leaves with `smoothness` (left +/// out for null), and the mean distance of its points from the line y = 200. +fn smoothed_jagged_line(smoothness: serde_json::Value) -> (PathData, f64) { + let mut s = session(); + let id = smooth_test_path(&mut s, &jagged_line_anchors(), false); + let drag: Vec<_> = (0..=64).map(|i| json!([90.0 + f64::from(i) * 5.0, 200.0])).collect(); + s.execute("path.smoothRegion", &json!({"points": drag, "radius": 12, "fidelity": 2.5, "smoothness": smoothness})).unwrap(); + let p = path(&s, id); + let samples = smooth_test_samples(&p); + let off = samples.iter().map(|q| (q.y - 200.0).abs()).sum::() / samples.len() as f64; + (p, off) +} + +/// Smooth Tool Options' Smoothness: the higher it is, the smoother the path a drag leaves, from +/// 0% to 100%. Left out, a drag smooths at 50%. +#[test] +fn a_higher_smoothness_leaves_a_smoother_path() { + let original = { + let mut s = session(); + let id = smooth_test_path(&mut s, &jagged_line_anchors(), false); + let samples = smooth_test_samples(&path(&s, id)); + samples.iter().map(|q| (q.y - 200.0).abs()).sum::() / samples.len() as f64 + }; + let offs: Vec = [0.0, 25.0, 50.0, 75.0, 100.0].iter().map(|&x| smoothed_jagged_line(json!(x)).1).collect(); + assert!(offs[0] < original, "even 0% refits within Fidelity: {offs:?}, {original} before"); + assert!(offs.windows(2).all(|w| w[1] < w[0]), "each step up smooths more: {offs:?}"); + assert_eq!(smoothed_jagged_line(json!(null)).0, smoothed_jagged_line(json!(50)).0, "left out is 50%"); +} + +/// `path.smoothRegion` refuses a Smoothness outside 0% to 100% and changes nothing. +#[test] +fn smooth_region_refuses_a_smoothness_outside_0_to_100() { + let mut s = session(); + let id = smooth_test_path(&mut s, &jagged_line_anchors(), false); + let drag = json!({"points": [[90, 200], [250, 200], [410, 200]], "radius": 12, "fidelity": 2.5}); + for x in [json!(-1), json!(-0.001), json!(100.5), json!(101), json!(1e300)] { + refuses_with(&mut s, "path.smoothRegion", &with(&drag, json!({"smoothness": x})), "`smoothness` must be from 0 to 100"); + } + for x in [json!(0), json!(100)] { + let before = path(&s, id); + s.execute("path.smoothRegion", &with(&drag, json!({"smoothness": x}))).unwrap_or_else(|e| panic!("smoothness {x}: {e}")); + assert_ne!(path(&s, id), before, "smoothness {x} smoothed nothing"); + s.execute("edit.undo", &json!({})).unwrap(); + } +} + /// A drag of the Smooth tool along a line jagged by up to 6 pt leaves no corner between a curve and /// a line: every anchor between the path's ends turns by at most 1°. #[test] @@ -3484,7 +3640,7 @@ fn smooth_and_join_refuse_a_reach_or_fidelity_outside_its_range() { } /// The Eraser, Path Eraser, Smooth, Join and Blob Brush commands refuse a size, angle, roundness, -/// width, radius, fidelity or tolerance given as text or as another value that is not a number, and change +/// width, radius, fidelity, smoothness or tolerance given as text or as another value that is not a number, and change /// nothing; null is read as the key left out. #[test] fn drawing_commands_refuse_a_size_given_as_text() { @@ -3499,6 +3655,7 @@ fn drawing_commands_refuse_a_size_given_as_text() { ("path.eraseSegments", "width"), ("path.smoothRegion", "radius"), ("path.smoothRegion", "fidelity"), + ("path.smoothRegion", "smoothness"), ("path.joinScrub", "tolerance"), ("path.blob", "size"), ("path.blob", "fidelity"), diff --git a/crates/engine/src/tests/fill_area.rs b/crates/engine/src/tests/fill_area.rs index 0471447010..67de26acd7 100644 --- a/crates/engine/src/tests/fill_area.rs +++ b/crates/engine/src/tests/fill_area.rs @@ -615,6 +615,40 @@ fn fill_area_fills_an_l_whose_empty_corner_holds_a_left_out_path() { assert!((area(&s, id_of(&r)) - 70_000.0).abs() < 1.0, "{}", area(&s, id_of(&r))); } +/// Draws a 100 pt square at the origin and, in front of it, an open path with too many segments +/// that runs from x -20 to 120 at `y` and up to 0.1 pt above it, then clicks at `click` with +/// `gap`. Gives the area of the new path, or None when the click finds no area. +fn square_beside_a_huge_line(y: f64, gap: f64, click: (f64, f64)) -> Option { + let mut s = session(); + rect(&mut s, 0.0, 0.0, 100.0, 100.0); + let n = vectorcraft_pathops::SHAPE_BUILDER_MAX_SEGMENTS; + let pts: Vec = (0..=n).map(|k| Point::new(-20.0 + 140.0 * k as f64 / n as f64, y - (k % 2) as f64 * 0.1)).collect(); + let look = vectorcraft_doc::Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0); + insert_path(&mut s, PathData::single(vectorcraft_geom::SubPath::polyline(&pts, false)), look); + deselect(&mut s); + let r = s.execute("shapeBuilder.copyRegion", &json!({"point": [click.0, click.1], "gap": gap})).ok()?; + Some(area(&s, id_of(&r))) +} + +/// With Gap Detection off, a path with too many segments 0.75 pt outside a square is left out and +/// does not touch the square, so a click in the square fills it. One that crosses the square still +/// stops the fill. +#[test] +fn fill_area_fills_a_square_a_left_out_path_passes_close_to() { + let a = square_beside_a_huge_line(-0.75, 0.0, (50.0, 50.0)).expect("the square"); + assert!((a - 10_000.0).abs() < 1.0, "{a}"); + assert_eq!(square_beside_a_huge_line(60.0, 0.0, (50.0, 25.0)), None); +} + +/// With a gap, a path with too many segments farther from the square than the gap is left out and +/// does not stop the square from being filled. One that crosses the square still stops the fill. +#[test] +fn fill_area_gap_fills_a_square_a_left_out_path_passes_beyond_the_gap() { + let a = square_beside_a_huge_line(-2.75, 2.0, (50.0, 50.0)).expect("the square"); + assert!((a - 10_000.0).abs() < 1.0, "{a}"); + assert_eq!(square_beside_a_huge_line(60.0, 2.0, (50.0, 25.0)), None); +} + /// A filled contour with too many segments on a higher layer surrounds a small square, its outline /// far from it: it is left out of the map, and the new path still goes above it, since it covers /// the area. diff --git a/crates/engine/src/tests/layers.rs b/crates/engine/src/tests/layers.rs index 22edfec458..65fa7951cd 100644 --- a/crates/engine/src/tests/layers.rs +++ b/crates/engine/src/tests/layers.rs @@ -157,6 +157,13 @@ fn clicking_rows_at_any_depth_highlights_them_and_sets_the_current_layer() { let n = rect(&mut s, 50.0); assert_eq!(parent(&s, n), Some(sub)); assert!(s.execute("layer.setCurrent", &json!({"id": 9999})).is_err()); + // `keepRows` makes the layer current and leaves the highlighted rows. + run(&mut s, "layer.setCurrent", json!({"id": b.0})); + run(&mut s, "layer.setCurrent", json!({"id": c.0, "keepRows": true})); + let st = s.doc().unwrap(); + assert_eq!((st.highlighted_rows(), st.current_layer()), (vec![b], Some(layer))); + assert!(s.execute("layer.setCurrent", &json!({"id": a.0, "keepRows": 1})).is_err()); + assert_eq!(s.doc().unwrap().current_layer(), Some(layer), "a bad keepRows changes nothing"); // Shift/Ctrl: several rows. run(&mut s, "layer.highlight", json!({"ids": [a.0, g.0], "mode": "set"})); run(&mut s, "layer.highlight", json!({"ids": [c.0], "mode": "add"})); @@ -390,6 +397,105 @@ fn the_selection_column_selects_a_rows_art_and_shift_adds_or_removes_it() { assert_eq!(ids_sel(&run(&mut s, "layer.target", json!({"id": layer.0}))), vec![c, a, g]); } +/// The selection as a sorted list. +fn sorted_sel(s: &Session) -> Vec { + let mut ids = s.doc().unwrap().selection.objects.clone(); + ids.sort(); + ids +} + +/// The art the selection squares of `rows` select, each clicked alone, put together and sorted. +/// Leaves nothing selected. +fn each_rows_art(s: &mut Session, rows: &[NodeId]) -> Vec { + run(s, "select.none", json!({})); + let mut art = vec![]; + for row in rows { + art.extend(ids_sel(&run(s, "layer.selectAll", json!({"id": row.0})))); + } + art.sort(); + art.dedup(); + run(s, "select.none", json!({})); + art +} + +/// `layer.selectAll` with `range` (a Shift-click from the last selection square clicked) selects +/// the art of every row in the range, across the sublayer and the group, as each row's square +/// selects it; hidden and locked rows are left out, and `add` adds to the selection. The +/// highlighted rows stay, and no undo step is recorded. +#[test] +fn the_selection_column_selects_the_art_of_a_range_of_rows() { + let mut s = session(); + let (layer, sub, a, g, b, c) = tree(&mut s); + run(&mut s, "layer.setCurrent", json!({"id": sub.0})); + let undo = undos(&s); + // The rows top down: the layer, the sublayer, the group, its rectangle, then a and c. + let range = [g, b, a, c]; + let want = each_rows_art(&mut s, &range); + let reply = run(&mut s, "layer.selectAll", json!({"range": range.map(|r| r.0)})); + assert_eq!(sorted_sel(&s), want, "the group, its member's row, the sublayer's rectangle and the top layer's rectangle"); + assert!(want.contains(&a) && want.contains(&c), "{want:?}"); + assert_eq!(ids_sel(&reply).len(), s.doc().unwrap().selection.objects.len()); + assert_eq!(s.doc().unwrap().highlighted_rows(), vec![sub], "the highlighted row stays"); + assert_eq!(undos(&s), undo, "a selection change is not an undo step"); + // A range given bottom up selects the same art. + run(&mut s, "layer.selectAll", json!({"range": [c.0, a.0, b.0, g.0]})); + assert_eq!(sorted_sel(&s), want); + // `add` keeps what was selected. + run(&mut s, "select.set", json!({"ids": [c.0]})); + run(&mut s, "layer.selectAll", json!({"range": [a.0], "add": true})); + let got = sorted_sel(&s); + assert!(got.len() == 2 && got.contains(&a) && got.contains(&c), "{got:?}"); + // A range holding a layer row takes that layer's art, its sublayer's too. + run(&mut s, "layer.selectAll", json!({"range": [layer.0, sub.0]})); + assert_eq!(sorted_sel(&s), each_rows_art(&mut s, &[layer])); + // Locked and hidden rows are left out. + run(&mut s, "layer.setProps", json!({"ids": [a.0], "locked": true})); + run(&mut s, "layer.setProps", json!({"ids": [c.0], "visible": false})); + run(&mut s, "layer.selectAll", json!({"range": range.map(|r| r.0)})); + let got = sorted_sel(&s); + assert!(!got.is_empty() && !got.contains(&a) && !got.contains(&c), "{got:?}"); + // A range of only hidden and locked rows changes nothing and says why. + run(&mut s, "select.set", json!({"ids": [g.0]})); + assert!(s.execute("layer.selectAll", &json!({"range": [a.0, c.0]})).is_err()); + assert_eq!(sorted_sel(&s), vec![g]); +} + +/// `layer.selectHighlighted` selects the art of the highlighted rows, as their selection squares +/// do, leaving out hidden and locked rows; `add` adds it. The highlighted rows stay, no undo step is +/// recorded, and with no row highlighted it is an error. +#[test] +fn select_highlighted_selects_the_art_of_the_highlighted_rows() { + let mut s = session(); + let (_, _, a, g, _, c) = tree(&mut s); + let want = each_rows_art(&mut s, &[g, c]); + run(&mut s, "layer.highlight", json!({"ids": [g.0, c.0], "mode": "set"})); + let rows = s.doc().unwrap().highlighted_rows(); + let undo = undos(&s); + run(&mut s, "layer.selectHighlighted", json!({})); + assert_eq!(sorted_sel(&s), want); + assert_eq!(s.doc().unwrap().highlighted_rows(), rows, "the highlighted rows stay"); + assert_eq!(undos(&s), undo, "a selection change is not an undo step"); + // `add` keeps what was selected. + run(&mut s, "select.set", json!({"ids": [a.0]})); + // Selecting art in another layer let go of the highlighted rows. + run(&mut s, "layer.highlight", json!({"ids": [g.0, c.0], "mode": "set"})); + run(&mut s, "layer.selectHighlighted", json!({"add": true})); + let mut with_a = want.clone(); + with_a.push(a); + with_a.sort(); + assert_eq!(sorted_sel(&s), with_a); + // A hidden row is left out. + run(&mut s, "layer.setProps", json!({"ids": [c.0], "visible": false})); + run(&mut s, "layer.highlight", json!({"ids": [g.0, c.0], "mode": "set"})); + run(&mut s, "layer.selectHighlighted", json!({})); + assert!(!sorted_sel(&s).contains(&c)); + // With no row highlighted, nothing changes. + run(&mut s, "layer.highlight", json!({"ids": [], "mode": "set"})); + run(&mut s, "select.set", json!({"ids": [a.0]})); + assert!(s.execute("layer.selectHighlighted", &json!({})).is_err()); + assert_eq!(sorted_sel(&s), vec![a]); +} + /// The rows of [`column_start`]: [`tree`]'s, plus a rectangle `o` on a second layer and an empty /// third layer `e`. #[derive(Clone, Copy)] diff --git a/crates/engine/src/tests/menucmds.rs b/crates/engine/src/tests/menucmds.rs index a23fab2209..d922be19dd 100644 --- a/crates/engine/src/tests/menucmds.rs +++ b/crates/engine/src/tests/menucmds.rs @@ -4535,6 +4535,115 @@ fn release_guides_turns_ruler_guides_into_paths() { assert_eq!(guides(&s).len(), 1); } +/// The direction of a two-anchor line, in degrees from the page's x axis (y down), from 0 to 180. +fn line_angle(ends: &[(f64, f64)]) -> f64 { + let [(x0, y0), (x1, y1)] = ends[..] else { panic!("not a line of two anchors") }; + (y1 - y0).atan2(x1 - x0).to_degrees().rem_euclid(180.0) +} + +/// A selected ruler guide rotates with `object.rotate` on its own, in one undo step, about the +/// middle of the line Release Guides makes of it. At 30° it becomes a selected guide path along +/// the turned line; Transform Again turns that path on, and undo gives the ruler guide back. +#[test] +fn rotating_a_ruler_guide_makes_an_angled_guide() { + let mut s = session(); + s.execute("guide.add", &json!({"vertical": true, "pos": 100})).unwrap(); + let line = s.doc().unwrap().doc.guide_line(&s.doc().unwrap().doc.ruler_guides()[0]).unwrap(); + s.execute("guide.select", &json!({"indexes": [0]})).unwrap(); + let n = undo_len(&s); + s.execute("object.rotate", &json!({"angle": 30})).unwrap(); + assert_eq!(undo_len(&s), n + 1); + assert!(guides(&s).is_empty(), "the ruler guide is replaced"); + let [path] = selected(&s)[..] else { panic!("one guide path selected") }; + assert!(selected_guides(&s).is_empty()); + let (ends, guide) = line_ends(&s, path); + assert!(guide, "the path is a guide"); + let (mid, len) = (line.0.midpoint(line.1), line.0.distance(line.1)); + let (a, b) = (vectorcraft_geom::Point::new(ends[0].0, ends[0].1), vectorcraft_geom::Point::new(ends[1].0, ends[1].1)); + assert!(a.midpoint(b).distance(mid) < 1e-6 && close(a.distance(b), len), "it turns about its middle"); + // Counter-clockwise on the page: the downward vertical line now points 30° toward the right. + assert!(close(line_angle(&ends), 60.0), "{ends:?}"); + s.execute("object.transformAgain", &json!({})).unwrap(); + assert!(close(line_angle(&line_ends(&s, path).0), 30.0)); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(guides(&s), vec![(true, 100.0)]); + assert!(s.doc().unwrap().doc.node(path).is_none()); +} + +/// A ruler guide turned by a quarter turn stays a ruler guide, horizontal now, through the same +/// middle; a turn of 0 changes nothing and records no undo step; a copy leaves the guide where it +/// was; and locked guides cannot be rotated. +#[test] +fn ruler_guides_turned_square_stay_ruler_guides() { + let mut s = session(); + s.execute("guide.add", &json!({"vertical": true, "pos": 100})).unwrap(); + let mid = { + let d = &s.doc().unwrap().doc; + let (a, b) = d.guide_line(&d.ruler_guides()[0]).unwrap(); + a.midpoint(b) + }; + s.execute("guide.select", &json!({"indexes": [0]})).unwrap(); + let n = undo_len(&s); + s.execute("object.rotate", &json!({"angle": 0})).unwrap(); + assert_eq!((guides(&s), undo_len(&s)), (vec![(true, 100.0)], n)); + // Guides alone have no bounding box angle for `absolute` to set. + assert!(s.execute("object.rotate", &json!({"angle": 90, "absolute": true})).is_err()); + assert_eq!((guides(&s), undo_len(&s)), (vec![(true, 100.0)], n)); + s.execute("object.rotate", &json!({"angle": 90})).unwrap(); + let [(vertical, pos)] = guides(&s)[..] else { panic!("one ruler guide") }; + assert!(!vertical && close(pos, mid.y), "{pos}"); + assert_eq!((selected_guides(&s), undo_len(&s)), (vec![0], n + 1)); + // A copy at 45° adds a guide path and keeps the ruler guide. + s.execute("object.rotate", &json!({"angle": 45, "copy": true})).unwrap(); + assert_eq!(guides(&s).len(), 1); + let [path] = selected(&s)[..] else { panic!("the copy is selected") }; + assert!(line_ends(&s, path).1); + // Locked guides are deselected, and nothing is left to rotate. + s.execute("guide.select", &json!({"indexes": [0]})).unwrap(); + s.execute("view.guides.lock", &json!({"locked": true})).unwrap(); + assert!(s.execute("object.rotate", &json!({"angle": 30})).is_err()); + assert_eq!(guides(&s).len(), 1); +} + +/// Art and a ruler guide selected together rotate about the center of the art's box and the +/// guide's line together, and the angled guide survives a save and reopen as a guide path. +#[test] +fn a_ruler_guide_rotates_with_the_selected_art() { + let mut s = session(); + let a = rect(&mut s, 300.0, 100.0, 100.0, 100.0); + s.execute("guide.add", &json!({"vertical": false, "pos": 50})).unwrap(); + sel(&mut s, &[a]); + s.execute("guide.select", &json!({"indexes": [0], "toggle": true})).unwrap(); + assert_eq!((selected(&s), selected_guides(&s)), (vec![a], vec![0])); + let center = { + let d = &s.doc().unwrap().doc; + let (p, q) = d.guide_line(&d.ruler_guides()[0]).unwrap(); + Rect::from_points(p, q).union(bounds(&s, a)).center() + }; + s.execute("object.rotate", &json!({"angle": 90})).unwrap(); + let [(vertical, pos)] = guides(&s)[..] else { panic!("one ruler guide") }; + assert!(vertical && close(pos, center.x + (50.0 - center.y)), "{pos}"); + let turned = bounds(&s, a); + assert!(close(turned.center().x, center.x + (150.0 - center.y)), "{turned:?}"); + s.execute("object.rotate", &json!({"angle": 20})).unwrap(); + let paths: Vec = selected(&s).into_iter().filter(|id| *id != a).collect(); + let [path] = paths[..] else { panic!("the guide path is selected with the art") }; + let back = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap(); + let saved = back.node(path).unwrap(); + assert!(matches!(&saved.kind, NodeKind::Path { guide: true, path: p, .. } if *p == match &node(&s, path).kind { + NodeKind::Path { path, .. } => path.clone(), + _ => panic!("not a path"), + })); + // With anchors selected with Direct Selection, the selected guide turns with them. + s.execute("guide.add", &json!({"vertical": true, "pos": 600})).unwrap(); + s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 1]], "mode": "set"})).unwrap(); + s.execute("guide.select", &json!({"indexes": [0], "toggle": true})).unwrap(); + assert!(!s.doc().unwrap().selection.anchors.is_empty()); + s.execute("object.rotate", &json!({"angle": 90})).unwrap(); + assert!(!guides(&s)[0].0, "the vertical guide is horizontal now: {:?}", guides(&s)); +} + #[test] fn ruler_guides_and_lock() { let mut s = session(); diff --git a/crates/engine/src/tests/newdoc.rs b/crates/engine/src/tests/newdoc.rs index 53838c9bd7..b65d4a4b9a 100644 --- a/crates/engine/src/tests/newdoc.rs +++ b/crates/engine/src/tests/newdoc.rs @@ -160,7 +160,8 @@ fn ppi_overprint_preview_and_bad_params() { json!({"previewMode": "xray"}), json!({"artboardLayout": {"layout": "spiral"}}), json!({"artboardLayout": {"columns": 0}}), - json!({"artboardLayout": {"rows": 2}}), + json!({"artboardLayout": {"rows": 0}}), + json!({"artboardLayout": {"tiles": 2}}), json!({"units": "furlongs"}), json!({"width": 160000, "artboards": 1000}), ] { @@ -1001,6 +1002,22 @@ fn a_damaged_or_oversized_profile_leaves_the_defaults_and_is_reported() { let _ = std::fs::remove_dir_all(&dir); } +#[cfg(unix)] +#[test] +fn a_profile_that_is_a_link_is_not_followed() { + let (mut s, dir) = with_profiles("link"); + s.execute("file.newProfiles.edit", &json!({"name": "Print"})).unwrap(); + // A profile the folder held, moved out and linked back in. + let outside = std::env::temp_dir().join(format!("vc-newdoc-profile-outside-{}.vectorcraft", std::process::id())); + std::fs::rename(dir.join("Print.vectorcraft"), &outside).unwrap(); + std::os::unix::fs::symlink(&outside, dir.join("Print.vectorcraft")).unwrap(); + let r = s.execute("file.new", &json!({"preset": "Letter"})).unwrap(); + assert_eq!(r["profileError"]["reason"], "not a plain file", "{r}"); + assert!(r.get("profile").is_none(), "{r}"); + let _ = std::fs::remove_file(&outside); + let _ = std::fs::remove_dir_all(&dir); +} + #[test] fn profile_names_are_checked_and_editing_needs_the_folder() { let mut s = Session::new(); diff --git a/crates/engine/src/tests/paintopacity.rs b/crates/engine/src/tests/paintopacity.rs index c2e80f983a..8caada9e72 100644 --- a/crates/engine/src/tests/paintopacity.rs +++ b/crates/engine/src/tests/paintopacity.rs @@ -460,7 +460,7 @@ fn the_eyedropper_armed_for_the_bucket_answers_no_opacity() { s.select_tool("eyedropper", ViewInfo::default()).unwrap(); assert_eq!(proxies(&mut s)["fillOpacity"], 100.0, "the Eyedropper alone shows the selection's"); s.set_tool_option("stop", &json!("livePaintBucket")); - assert!(s.bucket_paints()); + assert!(s.tool_paints(false) && s.tool_paints(true)); assert_eq!(proxies(&mut s)["fillOpacity"], Value::Null); assert_eq!(proxies(&mut s)["strokeOpacity"], Value::Null); } diff --git a/crates/engine/src/tests/pathops.rs b/crates/engine/src/tests/pathops.rs index 60f223334c..6911059b0a 100644 --- a/crates/engine/src/tests/pathops.rs +++ b/crates/engine/src/tests/pathops.rs @@ -1955,6 +1955,31 @@ fn a_pathfinder_effect_keeps_the_options_in_force_when_applied() { assert_eq!(mix, &json!({"mixingRate": 50.0, "precision": 0.5, "removeRedundantPoints": true, "removeUnpainted": true})); } +/// A Pathfinder effect given some of its options in `params` journals every option it used, so +/// replaying the journal with other preferences gives the same effect and art. +#[test] +fn a_pathfinder_effect_given_some_options_journals_every_option_it_used() { + let mut s = session(); + s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 100, "height": 100})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 0, "y": 99.5, "width": 100, "height": 50})).unwrap(); + s.execute("paint.setFill", &json!({"none": true})).unwrap(); + s.execute("select.all", &json!({})).unwrap(); + s.prefs.pathfinder = PathfinderOptions { precision: 1.0, remove_redundant_points: true, remove_unpainted: true }; + s.execute("effect.apply", &json!({"effect": "pathfinder.divide", "params": {"precision": 0.25}})).unwrap(); + let all = json!({"precision": 0.25, "removeRedundantPoints": true, "removeUnpainted": true}); + assert_eq!(first_effect_params(&s), all); + let (id, p) = s.journal.last().unwrap().clone(); + assert_eq!((id.as_str(), &p["params"]), ("effect.apply", &all), "the journal entry gives every option the effect used"); + let mut replay = Session::new(); + for (id, p) in &s.journal { + replay.execute(id, p).unwrap(); + } + assert_eq!(replay.prefs.pathfinder, PathfinderOptions::default()); + let doc = |s: &Session| serde_json::to_value(&*s.doc().unwrap().doc).unwrap(); + assert_eq!(doc(&replay), doc(&s)); +} + /// A live Pathfinder effect evaluates with its own options as the panel's operations do with /// Pathfinder Options: a precision of 1 pt drops a 0.5 pt overlap, Divide leaves out an unfilled /// object's pieces, and Remove Redundant Points drops an anchor that shapes nothing. diff --git a/crates/engine/src/tests/plugins.rs b/crates/engine/src/tests/plugins.rs index 855952fcb2..0a255fb3a3 100644 --- a/crates/engine/src/tests/plugins.rs +++ b/crates/engine/src/tests/plugins.rs @@ -333,6 +333,59 @@ fn failing_plugins_leave_the_document_and_history_alone() { } } +/// A filter's output may report a `notice`, which `plugin.run` returns once the output is applied, +/// escaped and capped by the host, with the plug-in's name as `pluginName`. It needs no permission: a filter granted none reports one too. +/// A `notice` that is not a string refuses the output, and the document and history stay as they +/// were. +#[test] +fn a_filter_s_notice_is_returned_once_its_output_is_applied() { + let mut s = session(); + let id = rect(&mut s, 10.0, "#ff0000").0; + let quiet = "test.engine.notice.none"; + install(&mut s, &asking(quiet, "[]", &json!({"objects": [], "notice": "Nothing to tidy"}))); + let r = run(&mut s, "plugin.run", json!({"id": quiet})); + assert_eq!((&r["plugin"], &r["notice"]), (&json!(quiet), &json!("Nothing to tidy"))); + assert_eq!(r["pluginName"], json!(format!("Test {quiet}"))); + let reading = |s: &mut Session, id: &str, output: &Value| { + let data = vectorcraft_format::base64_encode(&asking(id, r#"["doc.read"]"#, output)); + run(s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"], "replace": true})) + }; + let noisy = "test.engine.notice.escaped"; + let long = format!("Done\u{202E}\n{}", "x".repeat(500)); + reading(&mut s, noisy, &json!({"objects": [{"id": id}], "notice": long})); + let shown = run(&mut s, "plugin.run", json!({"id": noisy, "ids": [id]}))["notice"].as_str().unwrap_or_default().to_string(); + assert!(shown.starts_with("Done\\u{202E}\\u{000A}xx") && shown.ends_with('…'), "{shown}"); + assert_eq!(shown.chars().count(), vectorcraft_plugins::objects::MAX_NOTICE_CHARS); + let plain = "test.engine.notice.plain"; + reading(&mut s, plain, &json!({"objects": [{"id": id}]})); + let r = run(&mut s, "plugin.run", json!({"id": plain, "ids": [id]})); + assert!(r.get("notice").is_none() && r.get("pluginName").is_none(), "{r}"); + let bad = "test.engine.notice.bad"; + install(&mut s, &asking(bad, "[]", &json!({"objects": [], "notice": 3}))); + let before = s.doc().unwrap().doc.clone(); + let undo = s.doc().unwrap().history.undo.len(); + let e = s.execute("plugin.run", &json!({"id": bad})).unwrap_err().to_string(); + assert!(e.contains("`notice` must be a string with visible text"), "{e}"); + assert_eq!(s.doc().unwrap().doc, before); + assert_eq!(s.doc().unwrap().history.undo.len(), undo); +} + +/// A plug-in command's result carries its run's `notice` beside the command's id, and so does the +/// step of a batch that runs it. +#[test] +fn a_plugin_command_returns_its_run_s_notice() { + let mut s = session(); + let id = "test.engine.notice.command"; + let commands = r#"[{"id":"count","label":"Count"}]"#; + install_wat(&mut s, &tpl::returning(&with_commands(id, "filter", commands), r#"{"objects":[],"notice":"Counted 0 objects"}"#)); + let count = crate::cmd::plugin::command_id(id, "count"); + let r = run(&mut s, &count, json!({})); + assert_eq!((&r["command"], &r["notice"]), (&json!("count"), &json!("Counted 0 objects"))); + let batch = run(&mut s, "command.batch", json!({"commands": [{"command": count, "params": {}}]})); + assert!(batch.to_string().contains("Counted 0 objects"), "{batch}"); + run(&mut s, "plugin.remove", json!({"id": id})); +} + #[test] fn live_effect_plugins_reshape_editable_art_and_expand() { let mut s = session(); @@ -2126,6 +2179,42 @@ fn plugin_list_leaves_out_paths_outside_the_read_root() { run(&mut s, "plugin.remove", json!({"id": id})); } +/// A command a script runs loads a plug-in folder's files through the script's read gate also +/// without automation roots: a link in a folder the script may read, to a module outside it, is +/// refused whether or not its name is valid text. +#[cfg(unix)] +#[test] +fn a_script_loads_no_plugin_from_outside_its_folder_through_a_name_that_is_not_text() { + use crate::file_access::{ScriptGate, ScriptScope, with_script_gate}; + use std::os::unix::ffi::OsStrExt; + let _folder = PREFS_FOLDER.lock().unwrap_or_else(|e| e.into_inner()); + let base = crate::tests_links::Folder::new("plugin-script-name-not-text"); + let (inside, outside) = (base.0.join("in"), base.0.join("out")); + std::fs::create_dir_all(&inside).unwrap(); + std::fs::create_dir_all(&outside).unwrap(); + let (text_id, bytes_id) = ("test.engine.script.textname", "test.engine.script.bytesname"); + for (id, file, link) in [(text_id, "text.wasm", &b"a.wasm"[..]), (bytes_id, "bytes.wasm", &b"b\xff.wasm"[..])] { + let src = tpl::returning(&tpl::manifest(id, "filter", "{}"), r#"{"objects":[]}"#); + std::fs::write(outside.join(file), wat::parse_str(src).unwrap()).unwrap(); + std::os::unix::fs::symlink(outside.join(file), inside.join(std::ffi::OsStr::from_bytes(link))).unwrap(); + } + let gate = ScriptGate { + read: ScriptScope::of_folder(&inside), + write: ScriptScope::default(), + documents: vec![], + linked: Default::default(), + also: None, + }; + let mut s = session(); + let folder = inside.to_string_lossy().to_string(); + let r = with_script_gate(gate, || s.execute("plugin.reload", &json!({"path": folder}))); + let installed = [text_id, bytes_id].map(vectorcraft_plugins::registry::remove); + assert_eq!(installed, [false, false], "a script loaded a module from outside its folder: {r:?}"); + let r = r.unwrap(); + assert_eq!(r["loaded"], json!([]), "{r}"); + assert_eq!(r["failed"].as_array().map(Vec::len), Some(2), "{r}"); +} + /// Under automation read roots, a plug-in turned off for the next launch is listed with a file /// outside them named by its file name, and `plugin.setEnabled` turns it on by that name. #[test] diff --git a/crates/engine/src/tests/prefs_file.rs b/crates/engine/src/tests/prefs_file.rs index bfe98b901b..98a756b1f7 100644 --- a/crates/engine/src/tests/prefs_file.rs +++ b/crates/engine/src/tests/prefs_file.rs @@ -197,3 +197,14 @@ fn hold_shortcut_preferences() { assert_eq!(restored.key_hold_delay(), 1.0); assert!(!restored.hold_shortcuts); } + +/// Display Print Size at 100% Zoom is on by default, also for saved preferences that predate the +/// key; a saved choice to turn it off stays off. +#[test] +fn display_print_size_is_on_unless_turned_off() { + assert!(Session::new().prefs.display_print_size); + let older: Prefs = serde_json::from_value(json!({"showToolTips": true})).unwrap(); + assert!(older.display_print_size); + let off: Prefs = serde_json::from_value(json!({"displayPrintSize": false})).unwrap(); + assert!(!off.display_print_size); +} diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs new file mode 100644 index 0000000000..4e705538d9 --- /dev/null +++ b/crates/engine/src/tests/script_dom.rs @@ -0,0 +1,1778 @@ +//! The script object model: `app`, its documents, their selection and page items. + +use serde_json::{Value, json}; + +use crate::*; + +fn run(s: &mut Session, source: &str) -> Result { + s.execute("script.run", &json!({"source": source, "name": "t.js"})) +} + +/// What the run logged. +fn log(s: &mut Session, source: &str) -> Vec { + let r = run(s, source).unwrap_or_else(|e| panic!("{source}: {e}")); + r["log"].as_array().cloned().unwrap_or_default() +} + +/// The message of the run's failure. +fn failure(s: &mut Session, source: &str) -> String { + run(s, source).map(|r| panic!("{source} ran: {r}")).unwrap_err().to_string() +} + +fn rect(s: &mut Session, x: f64, y: f64, w: f64, h: f64) -> NodeId { + NodeId(s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": w, "height": h})).unwrap()["id"].as_u64().unwrap()) +} + +/// A 400 × 300 pt document with two rectangles. +fn doc() -> (Session, NodeId, NodeId) { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let a = rect(&mut s, 10.0, 20.0, 30.0, 40.0); + let b = rect(&mut s, 100.0, 100.0, 50.0, 50.0); + (s, a, b) +} + +fn undo_steps(s: &Session) -> usize { + s.active().unwrap().history.undo.len() +} + +#[test] +fn app_documents_track_active_tab_and_new_document() { + let mut s = Session::new(); + assert_eq!(log(&mut s, "vc.log(app.documents.length); vc.log(app.typename);"), vec![json!(0), json!("Application")]); + assert!(failure(&mut s, "app.activeDocument;").contains("No active document")); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap(); + let out = log( + &mut s, + "var d = app.documents; vc.log(d.length); vc.log(app.activeDocument.width);\ + app.activeDocument = d[0]; vc.log(app.activeDocument.width); vc.log(d[0].parent.typename);\ + vc.log(d[5] === undefined); vc.log(app.activeDocument instanceof Document);\ + var n = d.add(DocumentColorSpace.CMYK, 50, 60, 2);\ + vc.log(d.length); vc.log(app.activeDocument.name === n.name); vc.log(n.documentColorSpace); vc.log(n.height);\ + vc.log(d.getByName(n.name).width);", + ); + let expected = [json!(2), json!(200), json!(400), json!("Application"), json!(true), json!(true), json!(3), json!(true)]; + assert_eq!(out[..8], expected); + assert_eq!(out[8..], [json!("DocumentColorSpace.CMYK"), json!(60), json!(50)]); + assert_eq!(s.documents().len(), 3); + assert_eq!(s.active_index(), Some(2)); + assert_eq!(s.documents()[2].doc.artboards.len(), 2); + // A bad argument changes nothing. + assert!(failure(&mut s, "app.documents.add(DocumentColorSpace.RGB, -5);").contains("width")); + assert!(failure(&mut s, "app.documents.add('RGB');").contains("colorSpace")); + assert!(failure(&mut s, "app.documents.add(undefined, 10, 10, 101);").contains("numArtBoards")); + // The spacing is refused at file.new's limit, with the script's own name for it. + let spacing = "app.documents.add(undefined, 10, 10, 2, DocumentArtboardLayout.Row, 100001);"; + assert!(failure(&mut s, spacing).contains("artboardSpacing must be from 0 to 100000 points")); + assert!(failure(&mut s, "app.documents.index('none');").contains("Not found")); + assert_eq!(s.documents().len(), 3); +} + +#[test] +fn page_items_are_live_and_typed_for_all_node_kinds() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + rect(&mut s, 200.0, 200.0, 10.0, 10.0); + s.execute("guide.add", &json!({"vertical": true, "pos": 120})).unwrap(); + s.execute("text.create", &json!({"x": 10, "y": 250, "text": "hi"})).unwrap(); + let out = log( + &mut s, + "var p = app.activeDocument.pageItems, t = [];\ + for (var i = 0; i < p.length; i++) t.push(p[i].typename);\ + vc.log(t.join(','));\ + vc.log(p[3].parent.typename); vc.log(p[0].parent.typename); vc.log(p.parent.typename);\ + p[1].remove(); vc.log(p.length); vc.log(p[-1] === undefined && p[1.5] === undefined && p[99] === undefined);\ + vc.log(p[2] instanceof PathItem && p[2] instanceof PageItem);", + ); + // Topmost first, each group before the objects in it. + assert_eq!( + out, + vec![ + json!("TextFrame,PathItem,GroupItem,PathItem,PathItem"), + json!("GroupItem"), + json!("Layer"), + json!("Document"), + json!(4), + json!(true), + json!(true) + ] + ); +} + +#[test] +fn page_items_list_the_art_inside_a_blend() { + let (mut s, a, b) = doc(); + log(&mut s, "app.activeDocument.pageItems[0].name = 'first';"); + s.execute("object.blend.make", &json!({"ids": [a.0, b.0], "steps": 2})).unwrap(); + let out = log( + &mut s, + "var p = app.activeDocument.pageItems, t = [];\ + for (var i = 0; i < p.length; i++) t.push(p[i].typename);\ + vc.log(t.join(','));\ + vc.log(p.getByName('first').parent.typename); vc.log(p.index('first').typename);", + ); + assert_eq!(out, vec![json!("BlendItem,PathItem,PathItem"), json!("BlendItem"), json!("PathItem")]); +} + +#[test] +fn page_item_geometry_uses_document_coordinates_with_y_up() { + let (mut s, _, _) = doc(); + let out = log( + &mut s, + "var i = app.activeDocument.pageItems[1];\ + vc.log(i.geometricBounds); vc.log(i.position); vc.log([i.left, i.top, i.width, i.height]);\ + app.coordinateSystem = CoordinateSystem.ARTBOARDCOORDINATESYSTEM; vc.log(i.position);\ + app.coordinateSystem = CoordinateSystem.DOCUMENTCOORDINATESYSTEM;\ + i.position = [20, 250]; i.width = 60; vc.log(i.geometricBounds);", + ); + assert_eq!(out[0], json!([10, 280, 40, 240])); + assert_eq!(out[1], json!([10, 280])); + assert_eq!(out[2], json!([10, 280, 30, 40])); + assert_eq!(out[3], json!([10, 20])); + assert_eq!(out[4], json!([20, 250, 80, 210])); +} + +#[test] +fn page_item_size_setters_on_a_rotated_object_give_the_page_aligned_size() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("object.rotate", &json!({"angle": 30})).unwrap(); + let other = format!("{:?}", s.active().unwrap().doc.node(b)); + let out = log( + &mut s, + "var i = app.activeDocument.selection[0], h = i.height;\ + i.width = 80; vc.log([i.width, i.height - h]);\ + i.height = 90; vc.log([i.width, i.height]);\ + var g = i.geometricBounds; vc.log([g[2] - g[0], g[1] - g[3]]);", + ); + let pairs: Vec<[f64; 2]> = out.iter().map(|v| [v[0].as_f64().unwrap(), v[1].as_f64().unwrap()]).collect(); + for (got, want) in pairs.iter().zip([[80.0, 0.0], [80.0, 90.0], [80.0, 90.0]]) { + assert!((got[0] - want[0]).abs() < 1e-6 && (got[1] - want[1]).abs() < 1e-6, "{out:?}"); + } + assert_eq!(pairs.len(), 3, "{out:?}"); + assert_eq!(format!("{:?}", s.active().unwrap().doc.node(b)), other, "the other object stays as it was"); +} + +#[test] +fn convert_coordinate_pair_is_inverse_and_y_up() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let out = log( + &mut s, + "var d = app.activeDocument, D = CoordinateSystem.DOCUMENTCOORDINATESYSTEM, A = CoordinateSystem.ARTBOARDCOORDINATESYSTEM;\ + var p = d.convertCoordinate([10, 100], A, D); vc.log(p); vc.log(d.convertCoordinate(p, D, A));\ + vc.log(d.convertCoordinate([3, 4], D, D));", + ); + assert_eq!(out, vec![json!([10, 200]), json!([10, 100]), json!([3, 4])]); + assert!( + failure( + &mut s, + "app.activeDocument.convertCoordinate([1, NaN], CoordinateSystem.DOCUMENTCOORDINATESYSTEM, CoordinateSystem.DOCUMENTCOORDINATESYSTEM);" + ) + .contains("finite") + ); + assert!( + failure(&mut s, "app.activeDocument.convertCoordinate([1, 2], 'x', CoordinateSystem.DOCUMENTCOORDINATESYSTEM);").contains("CoordinateSystem") + ); +} + +#[test] +fn ruler_origin_round_trips_without_moving_art() { + let (mut s, a, _) = doc(); + let art = format!("{:?}", s.active().unwrap().doc.layers); + let out = log(&mut s, "var d = app.activeDocument; vc.log(d.rulerOrigin); d.rulerOrigin = [50, 60]; vc.log(d.rulerOrigin);"); + assert_eq!(out, vec![json!([0, 300]), json!([50, 60])]); + assert_eq!(s.active().unwrap().doc.ruler_origin_for(0), vectorcraft_geom::Point::new(50.0, 240.0)); + assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), art); + assert!(s.active().unwrap().doc.node(a).is_some()); + let steps = undo_steps(&s); + log(&mut s, "var d = app.activeDocument; d.rulerOrigin = d.rulerOrigin;"); + assert_eq!(undo_steps(&s), steps, "setting the same origin adds no step"); + assert!(failure(&mut s, "app.activeDocument.rulerOrigin = [1e12, 0];").contains("outside the canvas")); +} + +#[test] +fn page_item_properties_join_one_undo_step() { + let (mut s, a, _) = doc(); + let steps = undo_steps(&s); + let out = log( + &mut s, + "var i = app.activeDocument.pageItems[1];\ + i.name = 'box'; i.opacity = 40; i.locked = true; i.locked = false; i.hidden = true; i.hidden = false;\ + vc.log([i.name, i.opacity, i.locked, i.hidden, i.editable, i.zOrderPosition]);\ + vc.log(app.activeDocument.pageItems.getByName('box').name);", + ); + assert_eq!(out, vec![json!(["box", 40, false, false, true, 1]), json!("box")]); + let st = s.active().unwrap(); + let n = st.doc.node(a).unwrap(); + assert_eq!((n.name.as_deref(), (n.opacity * 100.0).round()), (Some("box"), 40.0)); + assert_eq!(undo_steps(&s), steps + 1, "one undo step for the run"); + let steps = undo_steps(&s); + log(&mut s, "var i = app.activeDocument.pageItems[1]; i.name = 'box'; i.opacity = 40; i.hidden = false;"); + assert_eq!(undo_steps(&s), steps, "values that change nothing add no step"); + for (source, part) in [ + ("app.activeDocument.pageItems[0].opacity = 101;", "opacity"), + ("app.activeDocument.pageItems[0].hidden = 'yes';", "hidden"), + ("app.activeDocument.pageItems[0].width = 0;", "width"), + ("app.activeDocument.pageItems[0].position = [1];", "position"), + ] { + assert!(failure(&mut s, source).contains(part), "{source}"); + } +} + +/// An opacity a graph mark already has still replaces the opacity another mark of its series left on +/// the graph, as `object.setProps` does. +#[test] +fn an_opacity_a_graph_mark_already_has_replaces_the_one_its_series_keeps() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let csv = ",2024,2025\nQ1,3,2\nQ2,5,4"; + let r = s.execute("graph.create", &json!({"type": "column", "x": 100, "y": 100, "width": 300, "height": 200, "csv": csv})).unwrap(); + let id = NodeId(r["id"].as_u64().unwrap()); + let kept = + |s: &Session| s.active().unwrap().doc.node(id).unwrap().extras().graph.as_deref().unwrap().series_paints.first().and_then(|p| p.opacity); + let series = |s: &Session| { + let n = s.active().unwrap().doc.node(id).unwrap().clone(); + let group = n.children().unwrap().iter().find(|c| c.extras().series_index == Some(0)).unwrap().clone(); + group.children().unwrap().iter().map(|m| m.id).collect::>() + }; + let marks = series(&s); + s.execute("object.setProps", &json!({"id": marks[0].0, "opacity": 50})).unwrap(); + assert_eq!(kept(&s), Some(0.5)); + s.execute("object.setProps", &json!({"id": series(&s)[1].0, "name": "mark"})).unwrap(); + // In a hidden or locked layer the same assignment would still change the graph, so it is refused. + let layer = s.active().unwrap().doc.layers[0].id; + for (on, off) in [ + (json!({"ids": [layer.0], "visible": false}), json!({"ids": [layer.0], "visible": true})), + (json!({"ids": [layer.0], "locked": true}), json!({"ids": [layer.0], "locked": false})), + ] { + s.execute("object.setProps", &on).unwrap(); + let steps = undo_steps(&s); + let e = failure(&mut s, "var m = app.activeDocument.pageItems.getByName('mark'); m.opacity = m.opacity;"); + assert!(e.contains("Cannot edit"), "{on}: {e}"); + assert_eq!(kept(&s), Some(0.5), "{on}"); + assert_eq!(undo_steps(&s), steps, "{on}"); + s.execute("object.setProps", &off).unwrap(); + } + log(&mut s, "app.activeDocument.pageItems.getByName('mark').opacity = 100;"); + assert_eq!(kept(&s), None); +} + +/// Assigning an item the opacity it reports, rounded to four decimals, changes nothing. +#[test] +fn assigning_the_reported_opacity_changes_nothing() { + let (mut s, a, _) = doc(); + s.execute("object.setProps", &json!({"id": a.0, "opacity": 100.0 / 3.0})).unwrap(); + let (before, steps) = (s.active().unwrap().doc.node(a).unwrap().opacity, undo_steps(&s)); + let out = log(&mut s, "var i = app.activeDocument.pageItems[1]; vc.log(i.opacity); i.opacity = i.opacity;"); + assert_eq!(out, vec![json!(33.3333)]); + assert_eq!(s.active().unwrap().doc.node(a).unwrap().opacity, before); + assert_eq!(undo_steps(&s), steps); + // A value close to the reported one but not equal to it is still applied. + s.execute("object.setProps", &json!({"id": a.0, "opacity": 50})).unwrap(); + let (before, steps) = (s.active().unwrap().doc.node(a).unwrap().opacity, undo_steps(&s)); + log(&mut s, "app.activeDocument.pageItems[1].opacity = 50.00005;"); + assert!(s.active().unwrap().doc.node(a).unwrap().opacity > before, "the assigned opacity was applied"); + assert_eq!(undo_steps(&s), steps + 1); +} + +#[test] +fn selection_assignment_is_atomic_across_invalid_items() { + let (mut s, a, b) = doc(); + s.execute("object.setProps", &json!({"ids": [b.0], "locked": true})).unwrap(); + let e = failure(&mut s, "var p = app.activeDocument.pageItems; app.activeDocument.selection = [p[0], p[1]];"); + assert!(e.contains("Cannot select PathItem"), "{e}"); + assert!(s.active().unwrap().selection.objects.is_empty()); + s.execute("object.setProps", &json!({"ids": [b.0], "locked": false})).unwrap(); + let out = log( + &mut s, + "var d = app.activeDocument, p = d.pageItems; vc.log(d.selection instanceof Array && d.selection.length === 0);\ + d.selection = [p[1], p[0], p[1]]; vc.log(d.selection.length); vc.log(app.selection[0].selected);\ + p[0].selected = false; vc.log(d.selection.length);\ + d.selection = p[1]; vc.log(d.selection.length);", + ); + assert_eq!(out, vec![json!(true), json!(2), json!(true), json!(1), json!(1)]); + assert_eq!(s.active().unwrap().selection.objects, vec![a]); + // An item of another document cannot be selected here. + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let e = failure(&mut s, "app.activeDocument.selection = app.documents[0].pageItems[0];"); + assert!(e.contains("Cannot select"), "{e}"); +} + +#[test] +fn a_guide_path_is_not_selected_while_guides_are_locked() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("view.guides.make", &json!({})).unwrap(); + s.execute("select.set", &json!({"ids": [b.0]})).unwrap(); + s.execute("view.guides.lock", &json!({"locked": true})).unwrap(); + // The assignment and `selected` refuse the guide path, and the selection stays as it was. + for source in ["app.activeDocument.selection = app.activeDocument.pageItems[1];", "app.activeDocument.pageItems[1].selected = true;"] { + let e = failure(&mut s, source); + assert!(e.contains(&format!("Cannot select PathItem {}", a.0)), "{source}: {e}"); + assert_eq!(s.active().unwrap().selection.objects, vec![b], "{source}"); + } + // With the guides unlocked, the guide path is selected. + s.execute("view.guides.lock", &json!({"locked": false})).unwrap(); + log(&mut s, "app.activeDocument.selection = app.activeDocument.pageItems[1];"); + assert_eq!(s.active().unwrap().selection.objects, vec![a]); +} + +#[test] +fn an_inactive_document_changes_without_switching_tabs() { + let (mut s, a, _) = doc(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + log(&mut s, "var d = app.documents[0]; d.pageItems[1].name = 'far'; d.selection = d.pageItems[0];"); + assert_eq!(s.active_index(), Some(1)); + let first = &s.documents()[0]; + assert_eq!(first.doc.node(a).unwrap().name.as_deref(), Some("far")); + assert_eq!(first.selection.objects.len(), 1); +} + +#[test] +fn move_duplicate_and_zorder_obey_parent_order() { + let (mut s, a, b) = doc(); + let out = log( + &mut s, + "var p = app.activeDocument.pageItems, first = p[1];\ + first.zOrder(ZOrderMethod.BRINGTOFRONT); vc.log(first.zOrderPosition);\ + var c = first.duplicate(); vc.log(c.zOrderPosition); vc.log(p.length); vc.log(app.activeDocument.selection.length);\ + c.zOrder(ZOrderMethod.SENDTOBACK); vc.log(c.zOrderPosition);", + ); + assert_eq!(out, vec![json!(2), json!(3), json!(3), json!(1), json!(1)]); + assert_eq!(s.active().unwrap().selection.objects, vec![b], "the selection stays as it was"); + let layer = &s.active().unwrap().doc.layers[0]; + let order: Vec = layer.children().unwrap().iter().map(|n| n.id).collect(); + assert_eq!(order[1..], [b, a]); + assert!(failure(&mut s, "app.activeDocument.pageItems[0].zOrder('front');").contains("ZOrderMethod")); +} + +/// The ids of the children of the first layer, bottom first. +fn layer_order(s: &Session) -> Vec { + s.active().unwrap().doc.layers[0].children().unwrap().iter().map(|n| n.id).collect() +} + +#[test] +fn move_and_duplicate_place_by_element_placement() { + let (mut s, a, b) = doc(); + let c = rect(&mut s, 300.0, 10.0, 5.0, 5.0); + s.execute("select.none", &json!({})).unwrap(); + let steps = undo_steps(&s); + // Before puts it directly above the relative object, after directly below. + let r = + log(&mut s, "var p = app.activeDocument.pageItems; var a = p[2], c = p[0]; vc.log(a.move(c, ElementPlacement.PLACEBEFORE) === undefined);"); + assert_eq!(r, vec![json!(false)]); + assert_eq!(layer_order(&s), [b, c, a]); + log(&mut s, "var p = app.activeDocument.pageItems; p[0].move(p[2], ElementPlacement.PLACEAFTER);"); + assert_eq!(layer_order(&s), [a, b, c]); + // At the end of a container is under its contents, at the beginning on top. + log(&mut s, "var p = app.activeDocument.pageItems; p[0].move(p[0].parent, ElementPlacement.PLACEATEND);"); + assert_eq!(layer_order(&s), [c, a, b]); + log(&mut s, "var p = app.activeDocument.pageItems; p[2].move(p[2].parent, ElementPlacement.PLACEATBEGINNING);"); + assert_eq!(layer_order(&s), [a, b, c]); + assert_eq!(undo_steps(&s), steps + 4, "one step for each run that changed the order"); + // Moving to where it is runs nothing. + let steps = undo_steps(&s); + log(&mut s, "var p = app.activeDocument.pageItems; p[0].move(p[1], ElementPlacement.PLACEBEFORE);"); + assert_eq!(undo_steps(&s), steps); + // Into a group, and a copy beside an object. + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let g = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.none", &json!({})).unwrap(); + log(&mut s, "var p = app.activeDocument.pageItems; p[0].move(p[1], ElementPlacement.INSIDE);"); + let inside: Vec = s.active().unwrap().doc.node(g).unwrap().children().unwrap().iter().map(|n| n.id).collect(); + assert_eq!(inside, [a, b, c]); + let out = log( + &mut s, + "var g = app.activeDocument.pageItems[0], a = app.activeDocument.pageItems[3];\ + var copy = a.duplicate(g, ElementPlacement.PLACEATEND); vc.log(copy.parent.typename); vc.log(copy.zOrderPosition);", + ); + assert_eq!(out, vec![json!("GroupItem"), json!(1)]); + assert_eq!(s.active().unwrap().doc.node(g).unwrap().children().unwrap().len(), 4); + // Refused moves change nothing. + let before = format!("{:?}", s.active().unwrap().doc.layers); + for (source, part) in [ + ("var g = app.activeDocument.pageItems[0]; g.move(app.activeDocument.pageItems[1], ElementPlacement.INSIDE);", "into itself"), + ("var p = app.activeDocument.pageItems; p[1].move(p[2], ElementPlacement.INSIDE);", "cannot hold objects"), + ("var p = app.activeDocument.pageItems; p[1].move(p[2], 'inside');", "ElementPlacement"), + ("var p = app.activeDocument.pageItems; p[1].move();", "relative object"), + ("var p = app.activeDocument.pageItems; p[1].move(app.activeDocument);", "not available yet"), + ("var p = app.activeDocument.pageItems; p[1].duplicate(undefined, ElementPlacement.INSIDE);", "relative object"), + ] { + let e = failure(&mut s, source); + assert!(e.contains(part), "{source}: {e}"); + } + assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before); + // A locked group takes nothing. + s.execute("object.setProps", &json!({"ids": [g.0], "locked": true})).unwrap(); + rect(&mut s, 0.0, 0.0, 5.0, 5.0); + let e = failure(&mut s, "var p = app.activeDocument.pageItems; p[0].move(p[1], ElementPlacement.INSIDE);"); + assert!(e.contains("hidden or locked"), "{e}"); +} + +#[test] +fn a_copy_goes_beside_its_source() { + let (mut s, a, b) = doc(); + let out = log( + &mut s, + "var a = app.activeDocument.pageItems[1], c = a.duplicate(a, ElementPlacement.PLACEAFTER);\ + vc.log([c.zOrderPosition, a.zOrderPosition]);", + ); + assert_eq!(out, vec![json!([1, 2])]); + let order = layer_order(&s); + assert_eq!(order[1..], [a, b]); + // An object moved directly above or below itself stays where it is with no undo step, and it + // cannot go into itself; a copy cannot go into its source. + let (order, steps) = (layer_order(&s), undo_steps(&s)); + log(&mut s, "var p = app.activeDocument.pageItems; p[1].move(p[1], ElementPlacement.PLACEAFTER); p[0].move(p[0], ElementPlacement.PLACEBEFORE);"); + assert_eq!((layer_order(&s), undo_steps(&s)), (order, steps)); + assert!(failure(&mut s, "var p = app.activeDocument.pageItems; p[1].move(p[1], ElementPlacement.PLACEATBEGINNING);").contains("into itself")); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + let e = failure(&mut s, "var p = app.activeDocument.pageItems, g = p[0]; g.duplicate(g, ElementPlacement.INSIDE);"); + assert!(e.contains("into itself"), "{e}"); +} + +#[test] +fn a_copy_that_cannot_be_placed_is_deleted() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let a = rect(&mut s, 10.0, 10.0, 50.0, 50.0); + let b = rect(&mut s, 30.0, 30.0, 50.0, 50.0); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("livePaint.make", &json!({})).unwrap(); + s.execute("text.create", &json!({"x": 200, "y": 200, "text": "Hi"})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let before = format!("{:?}", s.active().unwrap().doc.layers); + let (steps, step) = (undo_steps(&s), s.active().unwrap().history.step()); + // A Live Paint group takes no type, so the copy is refused after it was made. + let out = log( + &mut s, + "var p = app.activeDocument.pageItems, n = p.length, g = p[1], t = p[0], m = '';\ + try { t.duplicate(g, ElementPlacement.INSIDE); } catch (e) { m = e.message; }\ + vc.log(m); vc.log(p.length === n);", + ); + assert!(out[0].as_str().is_some_and(|m| m.contains("Live Paint takes paths")), "{out:?}"); + assert_eq!(out[1], json!(true)); + assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before); + // The refused copy leaves no undo step and does not change the document's step. + assert_eq!((undo_steps(&s), s.active().unwrap().history.step()), (steps, step)); +} + +#[test] +fn a_path_inside_a_compound_path_is_not_duplicated() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + let before = format!("{:?}", s.active().unwrap().doc.layers); + let steps = undo_steps(&s); + let e = failure(&mut s, "var p = app.activeDocument.pageItems; vc.log(p[0].typename); p[1].duplicate();"); + assert!(e.contains("Duplicating a path inside a compound path is not available yet"), "{e}"); + assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before); + assert_eq!(undo_steps(&s), steps); + // The compound path itself is copied whole. + let out = log(&mut s, "var p = app.activeDocument.pageItems, c = p[0].duplicate(); vc.log([c.typename, p.length]);"); + assert_eq!(out, vec![json!(["CompoundPathItem", 6])]); +} + +#[test] +fn a_path_inside_a_compound_path_is_not_reordered() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + rect(&mut s, 200.0, 200.0, 20.0, 20.0); + let before = format!("{:?}", s.active().unwrap().doc.layers); + let steps = undo_steps(&s); + let out = log( + &mut s, + "var p = app.activeDocument.pageItems, m = [], out = [];\ + for (var i = 0; i < p.length; i++) if (p[i].parent.typename == 'CompoundPathItem') m.push(p[i]);\ + var ways = [ZOrderMethod.BRINGTOFRONT, ZOrderMethod.BRINGFORWARD, ZOrderMethod.SENDBACKWARD, ZOrderMethod.SENDTOBACK];\ + for (var j = 0; j < m.length; j++) for (var k = 0; k < ways.length; k++) {\ + try { m[j].zOrder(ways[k]); out.push('ran'); } catch (e) { out.push(e.message); }\ + }\ + vc.log(m.length); vc.log(out);", + ); + assert_eq!(out[0], json!(2)); + let messages = out[1].as_array().cloned().unwrap_or_default(); + assert_eq!(messages.len(), 8, "{out:?}"); + for m in &messages { + assert!(m.as_str().is_some_and(|m| m.contains("Reordering a path inside a compound path is not available yet")), "{out:?}"); + } + assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before); + assert_eq!(undo_steps(&s), steps); + // The compound path itself still moves. + let out = log( + &mut s, + "var p = app.activeDocument.pageItems, c;\ + for (var i = 0; i < p.length; i++) if (p[i].typename == 'CompoundPathItem') c = p[i];\ + var at = c.zOrderPosition; c.zOrder(ZOrderMethod.BRINGTOFRONT); vc.log([at, c.zOrderPosition]);", + ); + assert_eq!(out, vec![json!([1, 2])]); +} + +#[test] +fn moving_the_last_path_out_of_a_compound_path_keeps_the_compound_path() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + let compound = layer_order(&s)[0]; + let layer = s.active().unwrap().doc.layers[0].id; + let steps = undo_steps(&s); + let out = log( + &mut s, + "var d = app.activeDocument, c = d.pageItems[0], m = [d.pageItems[2], d.pageItems[1]];\ + m[0].move(c, ElementPlacement.PLACEBEFORE); vc.log(d.pageItems.length);\ + m[1].move(c, ElementPlacement.PLACEBEFORE); vc.log(d.pageItems.length);\ + vc.log([c.typename, c === d.pageItems[2]]);\ + var bad = []; for (var k in c) { try { c[k]; } catch (e) { bad.push(k + ': ' + e.message); } } vc.log(bad);\ + vc.log([c.geometricBounds, c.visibleBounds, c.position, c.width, c.height]);\ + c.left = 5; c.top = 5; c.position = [1, 2]; c.width = 10; c.height = 10; vc.log(c.geometricBounds);", + ); + let zeros = json!([0, 0, 0, 0]); + assert_eq!(out[..3], [json!(3), json!(3), json!(["CompoundPathItem", true])]); + // Every property `for`-`in` lists reads, and the emptied compound path has zero bounds that + // moving or resizing leaves as they are. + assert_eq!(out[3..], [json!([]), json!([zeros, zeros, [0, 0], 0, 0]), zeros]); + let doc = &s.active().unwrap().doc; + assert!(doc.node(compound).is_some_and(|n| n.children().is_some_and(|c| c.is_empty())), "the compound path stays, empty"); + // Each path went directly above the compound path, the second above the first. + assert_eq!(layer_order(&s), [compound, b, a]); + assert!([a, b].iter().all(|id| doc.parent_of(*id) == Some(layer))); + assert_eq!(undo_steps(&s), steps + 1, "the run is one undo step"); +} + +/// `remove()` on the last path of a compound path keeps the compound path, empty, as `move` does, +/// and a document holding it saves, reopens, exports and releases it. +#[test] +fn removing_the_last_path_of_a_compound_path_keeps_the_compound_path() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + let compound = layer_order(&s)[0]; + let steps = undo_steps(&s); + let out = log( + &mut s, + "var d = app.activeDocument, c = d.pageItems[0]; d.pageItems[2].remove(); d.pageItems[1].remove();\ + vc.log([c.typename, d.pageItems.length, c === d.pageItems[0]]);", + ); + assert_eq!(out, vec![json!(["CompoundPathItem", 1, true])]); + let doc = s.active().unwrap().doc.clone(); + assert!(doc.node(compound).is_some_and(|n| n.children().is_some_and(|c| c.is_empty())), "the compound path stays, empty"); + assert_eq!(undo_steps(&s), steps + 1, "the run is one undo step"); + assert!(s.execute("edit.clear", &json!({"ids": [compound.0], "keepEmpty": 1})).is_err(), "keepEmpty must be a boolean"); + // The native format keeps it, and the other writers and Release Compound Path accept it. + let back = vectorcraft_format::load(&vectorcraft_format::save(&doc, false)).unwrap(); + assert!(back.node(compound).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. }) && n.children().is_some_and(|c| c.is_empty()))); + for format in ["svg", "pdf", "vectorcraft"] { + s.execute("document.export", &json!({"format": format})).unwrap_or_else(|e| panic!("{format}: {e}")); + } + s.execute("select.set", &json!({"ids": [compound.0]})).unwrap(); + s.execute("object.compoundPath.release", &json!({})).unwrap(); +} + +/// Clear with `keepEmpty` keeps the emptied compound path also when it deletes direct-selected +/// anchors, and without it deletes the compound path as before. +#[test] +fn clearing_anchors_with_keep_empty_keeps_the_compound_path() { + for keep in [true, false] { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + let compound = layer_order(&s)[0]; + for (id, mode) in [(a, "set"), (b, "add")] { + s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 0], [0, 1], [0, 2]], "mode": mode})).unwrap(); + } + s.execute("edit.clear", &json!({"keepEmpty": keep})).unwrap(); + let d = &s.active().unwrap().doc; + assert!(d.node(a).is_none() && d.node(b).is_none(), "keepEmpty {keep}: both paths are deleted"); + assert_eq!(d.node(compound).is_some_and(|n| n.children().is_some_and(|c| c.is_empty())), keep, "keepEmpty {keep}"); + } +} + +#[test] +fn a_copy_of_an_object_with_a_large_id_is_the_copy() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + // The copy's id, 2^53 + 1, is not exact as a number. + let big = 1u64 << 53; + s.active_mut().unwrap().change_unsaved(|d| std::sync::Arc::make_mut(d).raise_next_id(big)); + let a = rect(&mut s, 10.0, 20.0, 30.0, 40.0); + assert_eq!(a.0, big); + let out = log(&mut s, "var i = app.activeDocument.pageItems[0], c = i.duplicate(); c.name = 'copy'; vc.log(c === i); vc.log(i.name);"); + assert_eq!(out, vec![json!(false), json!("")]); + let d = &s.active().unwrap().doc; + assert_eq!(d.node(NodeId(big + 1)).and_then(|n| n.name.clone()).as_deref(), Some("copy")); + assert_eq!(d.node(a).unwrap().name, None); +} + +#[test] +fn a_grid_by_column_takes_the_number_of_rows() { + let mut s = Session::new(); + // With five artboards in four rows, the columns hold four and one. + for (layout, count, given, rows, cols) in + [("GridByCol", 6, 2, 2, 3), ("RLGridByCol", 6, 2, 2, 3), ("GridByRow", 6, 2, 3, 2), ("GridByCol", 5, 4, 4, 2), ("RLGridByCol", 5, 4, 4, 2)] + { + run(&mut s, &format!("app.documents.add(DocumentColorSpace.RGB, 100, 100, {count}, DocumentArtboardLayout.{layout}, 10, {given});")).unwrap(); + let boards = &s.active().unwrap().doc.artboards; + let distinct = |mut v: Vec| { + v.sort_unstable(); + v.dedup(); + v.len() + }; + let tops = distinct(boards.iter().map(|b| b.rect.y0.round() as i64).collect()); + let lefts = distinct(boards.iter().map(|b| b.rect.x0.round() as i64).collect()); + assert_eq!((tops, lefts), (rows, cols), "{layout} {count}"); + } +} + +#[test] +fn file_new_takes_the_rows_of_a_grid_by_column() { + let mut s = Session::new(); + let first_column = |s: &mut Session, layout: Value| { + s.execute("file.new", &json!({"width": 100, "height": 100, "artboards": 5, "artboardLayout": layout})).unwrap(); + let boards = &s.active().unwrap().doc.artboards; + boards.iter().filter(|b| b.rect.x0.round() as i64 == boards[0].rect.x0.round() as i64).count() + }; + assert_eq!(first_column(&mut s, json!({"layout": "gridByColumn", "rows": 4})), 4); + // Rows take the place of columns given beside them. + assert_eq!(first_column(&mut s, json!({"layout": "gridByColumn", "rows": 4, "columns": 1})), 4); + // A preset keeps and lists the rows, with the columns they give. + use crate::cmd::newdoc::{ArtboardLayout, DocSettings}; + let settings = DocSettings { artboards: 5, layout: ArtboardLayout::GridByColumn, ..DocSettings::default() }; + let settings = settings.with_params(&json!({"artboardLayout": {"rows": 4}}), "file.new").unwrap(); + let listed = settings.to_json(); + assert_eq!((&listed["artboardLayout"]["columns"], &listed["artboardLayout"]["rows"]), (&json!(2), &json!(4)), "{listed}"); + let stored: DocSettings = serde_json::from_value(serde_json::to_value(&settings).unwrap()).unwrap(); + assert_eq!(stored.rows, 4); + // More artboards keep the rows; columns alone, or another layout, replace them. + let more = stored.clone().with_params(&json!({"artboards": 9, "artboardLayout": listed["artboardLayout"]}), "file.new").unwrap(); + assert_eq!(more.boards().iter().filter(|b| b.x0 == more.boards()[0].x0).count(), 4); + let by_columns = stored.clone().with_params(&json!({"artboardLayout": {"columns": 1}}), "file.new").unwrap(); + assert_eq!((by_columns.rows, by_columns.boards().iter().filter(|b| b.x0 == by_columns.boards()[0].x0).count()), (0, 5)); + for layout in [json!({"layout": "gridByRow"}), json!("gridByRow")] { + let by_row = stored.clone().with_params(&json!({"artboardLayout": layout}), "file.new").unwrap(); + assert_eq!((by_row.rows, by_row.to_json()["artboardLayout"].get("rows")), (0, None), "{layout}"); + } + let e = s.execute("file.new", &json!({"artboardLayout": {"layout": "gridByColumn", "rows": 0}})).unwrap_err().to_string(); + assert!(e.contains("rows must be 1 or more"), "{e}"); + for layout in ["gridByRow", "row", "column"] { + let e = s.execute("file.new", &json!({"artboardLayout": {"layout": layout, "rows": 2}})).unwrap_err().to_string(); + assert!(e.contains("rows needs the gridByColumn layout"), "{layout}: {e}"); + } +} + +#[test] +fn a_listed_preset_keeps_more_rows_than_artboards() { + use crate::cmd::newdoc::{ArtboardLayout, DocSettings}; + let settings = DocSettings { artboards: 2, layout: ArtboardLayout::GridByColumn, ..DocSettings::default() }; + let settings = settings.with_params(&json!({"artboardLayout": {"rows": 4}}), "file.new").unwrap(); + let listed = settings.to_json(); + assert_eq!((&listed["artboardLayout"]["columns"], &listed["artboardLayout"]["rows"]), (&json!(1), &json!(4)), "{listed}"); + // Five artboards from the listing fill four rows, not two. + let more = settings.with_params(&json!({"artboards": 5, "artboardLayout": listed["artboardLayout"]}), "file.new").unwrap(); + assert_eq!(more.boards().iter().filter(|b| b.x0 == more.boards()[0].x0).count(), 4); +} + +#[test] +fn stale_documents_throw_on_every_member() { + let (mut s, _, _) = doc(); + run(&mut s, "#targetengine keep\nvar d = app.activeDocument, p = d.pageItems, l = p[0].parent;").unwrap(); + for (member, message) in + [("d.typename", "Stale document"), ("d.parent", "Stale document"), ("p.typename", "Stale document"), ("l.typename", "Stale")] + { + let e = failure(&mut s, &format!("#targetengine keep\n{member};")); + assert!(e.contains(message), "{member}: {e}"); + } +} + +#[test] +fn hiding_or_locking_a_selected_item_deselects_it() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + log(&mut s, "app.activeDocument.pageItems[1].hidden = true;"); + assert_eq!(s.active().unwrap().selection.objects, vec![b]); + log(&mut s, "app.activeDocument.pageItems[0].locked = true;"); + assert!(s.active().unwrap().selection.objects.is_empty()); +} + +#[test] +fn an_edit_keeps_direct_selected_anchors() { + let (mut s, a, _) = doc(); + s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 1]], "mode": "set"})).unwrap(); + let before = s.active().unwrap().selection.clone(); + assert!(!before.anchors.is_empty()); + log(&mut s, "var p = app.activeDocument.pageItems; p[1].duplicate(); p[1].zOrder(ZOrderMethod.SENDTOBACK);"); + assert_eq!(s.active().unwrap().selection.anchors, before.anchors); + assert_eq!(s.active().unwrap().selection.objects, before.objects); + assert!(s.journal.iter().any(|(id, _)| id == "select.anchorsMany"), "the journal holds the restore"); +} + +#[test] +fn an_edit_keeps_the_order_of_a_mixed_selection() { + let (mut s, a, b) = doc(); + rect(&mut s, 200.0, 200.0, 20.0, 20.0); + s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 1]], "mode": "set"})).unwrap(); + s.execute("select.add", &json!({"ids": [b.0]})).unwrap(); + let before = s.active().unwrap().selection.clone(); + assert_eq!(before.objects, vec![a, b]); + log(&mut s, "app.activeDocument.pageItems[2].duplicate();"); + let sel = &s.active().unwrap().selection; + assert_eq!((sel.objects.clone(), sel.anchors.clone()), (before.objects, before.anchors)); +} + +#[test] +fn assigning_the_selection_clears_a_layers_panel_target() { + let (mut s, a, _) = doc(); + s.execute("layer.target", &json!({"id": a.0})).unwrap(); + assert_eq!(s.active().unwrap().selection.target, Some(a)); + log(&mut s, "var d = app.activeDocument; d.selection = d.pageItems[1];"); + let sel = &s.active().unwrap().selection; + assert_eq!((sel.objects.clone(), sel.target), (vec![a], None)); +} + +#[test] +fn an_edit_keeps_a_layers_panel_target() { + let (mut s, a, b) = doc(); + s.execute("layer.target", &json!({"id": a.0})).unwrap(); + log(&mut s, "app.activeDocument.pageItems[1].duplicate();"); + let sel = &s.active().unwrap().selection; + assert_eq!((sel.objects.clone(), sel.target), (vec![a], Some(a))); + // A targeted layer stays targeted, with its art selected. + let layer = s.active().unwrap().doc.layers[0].id; + s.execute("layer.target", &json!({"id": layer.0})).unwrap(); + log(&mut s, "app.activeDocument.pageItems[1].duplicate();"); + let sel = &s.active().unwrap().selection; + assert_eq!((sel.target, sel.objects.len(), sel.objects.contains(&b)), (Some(layer), 4, true)); +} + +#[test] +fn an_edit_keeps_the_current_layer() { + let (mut s, a, b) = doc(); + let first = s.active().unwrap().doc.layers[0].id; + let back = NodeId(s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().unwrap()); + let layer = |s: &Session| (s.active().unwrap().active_layer, s.active().unwrap().highlighted_rows()); + assert_eq!(layer(&s), (Some(back), vec![back])); + // Moving an object of the first layer selects it for the command; the new layer stays current. + log(&mut s, "app.activeDocument.pageItems[0].left = 50;"); + assert_eq!(layer(&s), (Some(back), vec![back])); + assert_eq!(s.active().unwrap().selection.objects, vec![b]); + // With nothing selected and no row highlighted, the layer stays current and no row is highlighted. + s.execute("select.none", &json!({})).unwrap(); + s.execute("layer.setCurrent", &json!({"id": back.0})).unwrap(); + s.execute("layer.highlight", &json!({"ids": [], "mode": "set"})).unwrap(); + assert_eq!(layer(&s), (Some(back), vec![])); + log(&mut s, "app.activeDocument.pageItems[1].left = 120;"); + assert_eq!(layer(&s), (Some(back), vec![])); + assert!(s.active().unwrap().selection.objects.is_empty()); + // Targeting a layer makes it current and leaves another layer's row highlighted; both stay. + s.execute("layer.highlight", &json!({"ids": [first.0], "mode": "set"})).unwrap(); + s.execute("layer.target", &json!({"id": back.0})).unwrap(); + assert_eq!(layer(&s), (Some(back), vec![first])); + log(&mut s, "app.activeDocument.pageItems[0].left = 70;"); + assert_eq!(layer(&s), (Some(back), vec![first])); + // Assigning the selection makes the layer of the selected object current, as a click does. + log(&mut s, "app.activeDocument.selection = app.activeDocument.pageItems[1];"); + assert_eq!(s.active().unwrap().active_layer, Some(first)); + assert_eq!(s.active().unwrap().selection.objects, vec![a]); +} + +/// A document with a rectangle at the bottom of the stack, then a dynamic symbol instance of two +/// rectangles and an Objects on Path group of one rectangle: (session, instance, group, the +/// group's rectangle). +fn chosen_parts() -> (Session, NodeId, NodeId, NodeId) { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + rect(&mut s, 300.0, 200.0, 20.0, 20.0); + let (x, y) = (rect(&mut s, 10.0, 10.0, 20.0, 20.0), rect(&mut s, 50.0, 10.0, 20.0, 20.0)); + let id = |v: Value| NodeId(v["id"].as_u64().unwrap()); + let inst = id(s.execute("symbol.new", &json!({"name": "Pair", "ids": [x.0, y.0], "type": "dynamic"})).unwrap()); + let member = rect(&mut s, 10.0, 100.0, 20.0, 20.0); + let line = id(s.execute("shape.line", &json!({"x1": 50, "y1": 250, "x2": 350, "y2": 250})).unwrap()); + s.execute("select.set", &json!({"ids": [member.0]})).unwrap(); + let group = id(s.execute("object.objectsOnPath.attach", &json!({"path": line.0})).unwrap()); + (s, inst, group, member) +} + +#[test] +fn an_edit_keeps_an_object_chosen_inside_a_symbol_or_on_a_path() { + let (mut s, inst, group, member) = chosen_parts(); + s.execute("symbol.instance.selectPart", &json!({"id": inst.0, "path": [1]})).unwrap(); + let before = s.active().unwrap().selection.clone(); + log(&mut s, "app.activeDocument.pageItems[0].duplicate();"); + let sel = &s.active().unwrap().selection; + assert_eq!((sel.objects.clone(), sel.symbol_part.clone()), (before.objects, before.symbol_part)); + s.execute("object.objectsOnPath.selectMember", &json!({"member": member.0})).unwrap(); + log(&mut s, "app.activeDocument.pageItems[0].duplicate();"); + let sel = &s.active().unwrap().selection; + assert_eq!((sel.objects.clone(), sel.on_path_member), (vec![group], Some(member))); +} + +#[test] +fn assigning_the_selection_selects_a_symbol_or_on_path_group_as_a_whole() { + let (mut s, inst, group, member) = chosen_parts(); + s.execute("symbol.instance.selectPart", &json!({"id": inst.0, "path": [1]})).unwrap(); + log(&mut s, "var d = app.activeDocument; d.selection = d.selection[0];"); + let sel = &s.active().unwrap().selection; + assert_eq!((sel.objects.clone(), sel.symbol_part.clone()), (vec![inst], None)); + s.execute("object.objectsOnPath.selectMember", &json!({"member": member.0})).unwrap(); + log(&mut s, "var d = app.activeDocument; d.selection = d.selection[0];"); + let sel = &s.active().unwrap().selection; + assert_eq!((sel.objects.clone(), sel.on_path_member), (vec![group], None)); +} + +#[test] +fn a_held_image_stays_the_same_object_when_it_is_embedded() { + let dir = super::links::Folder::new("dom-embed"); + let photo = dir.file("photo.png"); + super::links::write(&photo, &super::links::png(20, 10, [255, 0, 0])); + let mut s = super::links::session(); + let id = super::links::place(&mut s, &photo); + let out = log( + &mut s, + &format!( + "var i = app.activeDocument.pageItems[0]; vc.log(i.typename); vc.run('links.embed', {{ids: [{}]}});\ + var j = app.activeDocument.pageItems[0]; vc.log([i === j, i.typename, i instanceof RasterItem, i instanceof PlacedItem]);", + id.0 + ), + ); + assert_eq!(out, vec![json!("PlacedItem"), json!([true, "RasterItem", true, false])]); +} + +#[test] +fn an_edit_keeps_the_key_object() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("select.key", &json!({"id": b.0})).unwrap(); + log(&mut s, "var p = app.activeDocument.pageItems; p[0].duplicate();"); + let sel = &s.active().unwrap().selection; + assert_eq!((sel.objects.clone(), sel.key), (vec![a, b], Some(b))); +} + +#[test] +fn an_edit_keeps_selected_slices() { + let (mut s, a, _) = doc(); + s.execute("object.slice.make", &json!({"ids": [a.0]})).unwrap(); + s.execute("object.slice.select", &json!({"slices": [a.0]})).unwrap(); + log(&mut s, "app.activeDocument.pageItems[1].duplicate();"); + let sel = &s.active().unwrap().selection; + assert_eq!((sel.slices.clone(), sel.objects.len()), (vec![a], 0)); +} + +#[test] +fn a_startup_preset_alone_gives_its_first_size() { + let mut s = Session::new(); + for profile in ["Web", "Print", "Mobile"] { + let first = crate::cmd::newdoc::category(&s, profile).unwrap().remove(0); + let out = log(&mut s, &format!("var d = app.documents.addDocument('{profile}'); vc.log([d.width, d.height]);")); + let got = (out[0][0].as_f64(), out[0][1].as_f64()); + assert_eq!(got, (Some(first.width), Some(first.height)), "{profile}"); + } +} + +#[test] +fn page_item_members_not_built_yet_throw_on_read_and_assignment() { + let (mut s, _, _) = doc(); + for source in + ["app.activeDocument.pageItems[0].blendingMode;", "app.activeDocument.pageItems[0].uuid = 'x';", "app.activeDocument.pageItems[0].rotate(5);"] + { + assert!(failure(&mut s, source).contains("is not available yet"), "{source}"); + } + assert!(failure(&mut s, "app.activeDocument.layers = 1;").contains("Document.layers is not available yet")); + // A deleted item or an earlier run's document is stale first. + let e = failure(&mut s, "var i = app.activeDocument.pageItems[0]; i.remove(); i.blendingMode;"); + assert!(e.contains("Stale page item"), "{e}"); + run(&mut s, "#targetengine keep\nvar d = app.activeDocument;").unwrap(); + let e = failure(&mut s, "#targetengine keep\nd.layers;"); + assert!(e.contains("Stale document"), "{e}"); +} + +#[test] +fn assigning_the_same_objects_clears_the_key_and_guides() { + let (mut s, a, b) = doc(); + s.execute("guide.add", &json!({"vertical": true, "pos": 120})).unwrap(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("select.key", &json!({"id": b.0})).unwrap(); + s.execute("guide.select", &json!({"indexes": [0], "toggle": true})).unwrap(); + assert!(!s.active().unwrap().selection.guides.is_empty()); + log(&mut s, "var d = app.activeDocument; d.selection = [d.pageItems[1], d.pageItems[0]];"); + let sel = &s.active().unwrap().selection; + assert_eq!((sel.objects.clone(), sel.key, sel.guides.len()), (vec![a, b], None, 0)); + s.execute("guide.select", &json!({"indexes": [0]})).unwrap(); + log(&mut s, "app.activeDocument.selection = null;"); + assert!(s.active().unwrap().selection.guides.is_empty()); +} + +#[test] +fn a_page_item_with_a_large_id_keeps_its_id() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let big = (1u64 << 53) + 1; + s.active_mut().unwrap().change_unsaved(|d| std::sync::Arc::make_mut(d).raise_next_id(big)); + let a = rect(&mut s, 10.0, 20.0, 30.0, 40.0); + assert_eq!(a.0, big); + let out = log(&mut s, "var i = app.activeDocument.pageItems[0]; i.name = 'big'; vc.log(i.name); i.remove();"); + assert_eq!(out, vec![json!("big")]); + assert!(s.active().unwrap().doc.node(a).is_none()); +} + +#[test] +fn only_class_constructors_construct() { + let (mut s, _, _) = doc(); + let out = log( + &mut s, + "var m = [];\ + try { new app.documents.add(); } catch (e) { m.push(e.name); }\ + try { new app.activeDocument.pageItems[0].remove(); } catch (e) { m.push(e.name); }\ + vc.log(m); vc.log(app.documents.length); vc.log(app.activeDocument.pageItems.length);", + ); + assert_eq!(out, vec![json!(["TypeError", "TypeError"]), json!(1), json!(2)]); +} + +#[test] +fn a_document_preset_is_an_instance_of_its_class() { + let mut s = Session::new(); + let out = log(&mut s, "var p = new DocumentPreset(); vc.log(p instanceof DocumentPreset); vc.log(p.typename); vc.log(p.width);"); + assert_eq!(out, vec![json!(true), json!("DocumentPreset"), json!(612)]); +} + +#[test] +fn the_same_document_or_item_is_the_same_object() { + let (mut s, a, _) = doc(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + let out = log( + &mut s, + "var d = app.activeDocument, p = d.pageItems;\ + vc.log([d === app.documents[0], p[1] === p[1], p[1] === d.selection[0], p[0] !== p[1], p === d.pageItems]);", + ); + assert_eq!(out, vec![json!([true, true, true, true, true])]); +} + +#[test] +fn collection_entries_are_found_by_in_and_array_methods() { + let (mut s, _, _) = doc(); + let out = log( + &mut s, + "var p = app.activeDocument.pageItems, d = app.documents;\ + vc.log([0 in p, '1' in p, 2 in p, 0 in d, 1 in d]);\ + vc.log(Array.prototype.map.call(p, function (i) { return i.typename; }).join(','));", + ); + assert_eq!(out, vec![json!([true, true, false, true, false]), json!("PathItem,PathItem")]); +} + +#[test] +fn placement_in_another_document_is_refused() { + let (mut s, _, _) = doc(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + rect(&mut s, 0.0, 0.0, 5.0, 5.0); + let before: Vec = s.documents().iter().map(|d| format!("{:?}", d.doc.layers)).collect(); + for source in [ + "app.documents[0].pageItems[0].move(app.documents[1].pageItems[0], ElementPlacement.PLACEBEFORE);", + "app.documents[0].pageItems[0].duplicate(app.documents[1].pageItems[0].parent, ElementPlacement.INSIDE);", + ] { + let e = failure(&mut s, source); + assert!(e.contains("Cross-document placement is not available"), "{source}: {e}"); + } + let after: Vec = s.documents().iter().map(|d| format!("{:?}", d.doc.layers)).collect(); + assert_eq!(after, before); +} + +#[test] +fn note_is_the_attributes_note() { + let (mut s, a, _) = doc(); + let steps = undo_steps(&s); + let out = log(&mut s, "var i = app.activeDocument.pageItems[1]; vc.log(i.note); i.note = 'check bleed'; vc.log(i.note);"); + assert_eq!(out, vec![json!(""), json!("check bleed")]); + assert_eq!(s.active().unwrap().doc.node(a).unwrap().extras().attrs.as_ref().unwrap().note, "check bleed"); + assert_eq!(undo_steps(&s), steps + 1); + log(&mut s, "app.activeDocument.pageItems[1].note = 'check bleed';"); + assert_eq!(undo_steps(&s), steps + 1, "the same note adds no step"); + // A number or a Boolean becomes its text, as it does for `name`. + let out = log(&mut s, "var i = app.activeDocument.pageItems[1]; i.note = 5; vc.log([typeof i.note, i.note]); i.note = true; vc.log(i.note);"); + assert_eq!(out, vec![json!(["string", "5"]), json!("true")]); + for value in ["null", "undefined", "{}"] { + assert!(failure(&mut s, &format!("app.activeDocument.pageItems[0].note = {value};")).contains("note must be a string"), "{value}"); + } + assert!(failure(&mut s, "app.activeDocument.pageItems[0].note = new Array(5000).join('n');").contains("too long")); +} + +#[test] +fn document_preset_applies_only_its_given_fields() { + let mut s = Session::new(); + let out = log( + &mut s, + "var p = new DocumentPreset(); vc.log([p.typename, p.width, p.height, p.numArtboards, p.artboardSpacing, p.artboardLayout]);\ + vc.log(p.colorMode === undefined && p.units === undefined);\ + p.width = 300; p.height = 200; p.numArtboards = 2; p.colorMode = DocumentColorSpace.CMYK; p.title = 'Flyer';\ + p.units = RulerUnits.Millimeters; p.rasterResolution = DocumentRasterResolution.HighResolution;\ + var d = app.documents.addDocument('Print', p); vc.log([d.name, d.width, d.height, d.documentColorSpace, d.rulerUnits]);\ + var e = app.documents.addDocument(DocumentPresetType.BasicRGB); vc.log(e.documentColorSpace);", + ); + assert_eq!(out[0], json!(["DocumentPreset", 612, 792, 1, 20, "DocumentArtboardLayout.GridByRow"])); + assert_eq!(out[1], json!(true)); + assert_eq!(out[2], json!(["Flyer", 300, 200, "DocumentColorSpace.CMYK", "RulerUnits.Millimeters"])); + assert_eq!(out[3], json!("DocumentColorSpace.RGB")); + assert_eq!(s.documents().len(), 2); + assert_eq!(s.documents()[0].doc.artboards.len(), 2); + assert!((s.documents()[0].doc.raster_effects_ppi - 300.0).abs() < 1e-9); + for (source, part) in [ + ("app.documents.addDocument('Nope');", "no startup preset"), + ("var p = new DocumentPreset(); p.numArtboards = 101; app.documents.addDocument('Print', p);", "numArtBoards"), + ("var p = new DocumentPreset(); p.units = RulerUnits.Qs; app.documents.addDocument('Print', p);", "units"), + ( + "var p = new DocumentPreset(); p.transparencyGrid = DocumentTransparencyGrid.TransparencyGridRed; app.documents.addDocument('Print', p);", + "not available yet", + ), + ("app.documents.addDocument('Print', 5);", "DocumentPreset"), + ("app.documents.addDocument(7);", "startup preset"), + ] { + let e = failure(&mut s, source); + assert!(e.contains(part), "{source}: {e}"); + } + assert_eq!(s.documents().len(), 2, "a refused preset makes no document"); +} + +#[test] +fn headless_add_document_dialog_fails_without_creating() { + let mut s = Session::new(); + let e = failure(&mut s, "app.documents.addDocument('Print', new DocumentPreset(), true);"); + assert!(e.contains("Dialog unavailable"), "{e}"); + assert!(s.documents().is_empty()); + let out = log(&mut s, "vc.log(app.documents.addDocument('Web', undefined, false).typename);"); + assert_eq!(out, vec![json!("Document")]); + assert_eq!(s.documents().len(), 1); +} + +#[test] +fn setting_selected_keeps_how_the_other_objects_are_selected() { + let (mut s, a, b) = doc(); + let c = rect(&mut s, 200.0, 100.0, 50.0, 50.0); + s.execute("select.set", &json!({"ids": [b.0]})).unwrap(); + s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 0]], "mode": "add"})).unwrap(); + let anchors = s.active().unwrap().selection.anchors.get(&a).cloned(); + assert!(anchors.is_some()); + log( + &mut s, + "var p = app.activeDocument.pageItems;\ + for (var i = 0; i < p.length; i++) { if (p[i].left == 200) p[i].selected = true; if (p[i].left == 100) p[i].selected = false; }", + ); + let sel = &s.active().unwrap().selection; + assert_eq!(sel.objects, vec![a, c]); + assert_eq!(sel.anchors.get(&a).cloned(), anchors, "the direct-selected anchors stay"); +} + +#[test] +fn add_document_takes_only_a_document_preset() { + let mut s = Session::new(); + for source in [ + "app.documents.addDocument('Print', {width: 500});", + "app.documents.addDocument('Print', {});", + "app.documents.addDocument('Print', {typename: 'DocumentPreset', width: 500});", + "var p = new DocumentPreset(); var q = {}; for (var k in p) q[k] = p[k]; app.documents.addDocument('Print', q);", + "app.documents.addDocument('Print', [612, 792]);", + "app.documents.addDocument('Print', 'DocumentPreset');", + ] { + let e = failure(&mut s, source); + assert!(e.contains("TypeError") && e.contains("presetSettings must be a DocumentPreset"), "{source}: {e}"); + } + assert!(s.documents().is_empty(), "a refused preset makes no document"); + let out = log(&mut s, "var p = new DocumentPreset(); p.width = 500; vc.log(app.documents.addDocument('Print', p).width);"); + assert_eq!(out, vec![json!(500)]); +} + +#[test] +fn add_document_applies_the_profile_file_and_throws_when_it_cannot_be_read() { + let dir = std::env::temp_dir().join(format!("vc-script-add-document-profile-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let mut s = Session::new(); + s.attach_new_doc_profiles(dir.clone()); + // A profile with no file gives the defaults. + let out = log(&mut s, "vc.log(app.documents.addDocument('Web').typename);"); + assert_eq!(out, vec![json!("Document")]); + assert_eq!(s.doc().unwrap().links_from, None); + // A script reads the profile's file in the app's own folder. + s.execute("file.newProfiles.edit", &json!({"name": "Print"})).unwrap(); + let file = dir.join("Print.vectorcraft").to_string_lossy().to_string(); + log(&mut s, "app.documents.addDocument('Print');"); + assert_eq!(s.doc().unwrap().links_from.as_deref(), Some(file.as_str())); + while !s.documents().is_empty() { + s.execute("file.close", &json!({})).unwrap(); + } + std::fs::write(dir.join("Print.vectorcraft"), b"not a document").unwrap(); + // file.new itself makes the document with the defaults and reports the profile it could not read. + let r = s.execute("file.new", &json!({"preset": "Letter"})).unwrap(); + assert_eq!(r["profileError"]["profile"], "Print", "{r}"); + s.execute("file.close", &json!({})).unwrap(); + let recent = s.execute("file.newPresets", &json!({"category": "Recent"})).unwrap(); + let e = failure(&mut s, "app.documents.addDocument('Print');"); + assert!(e.contains("Error: the New Document profile Print could not be read"), "{e}"); + assert!(s.documents().is_empty(), "the document made with the defaults is put back"); + // A script that catches the error finds nothing changed. + let out = log( + &mut s, + "var p = new DocumentPreset(); p.width = 333;\ + try { app.documents.addDocument('Print', p); } catch (e) { vc.log(e.name); } vc.log(app.documents.length);", + ); + assert_eq!(out, vec![json!("Error"), json!(0)]); + assert_eq!(s.execute("file.newPresets", &json!({"category": "Recent"})).unwrap(), recent, "the Recent sizes are as they were"); + // A startup preset with no profile reads no file. + let out = log(&mut s, "vc.log(app.documents.addDocument('Basic RGB').documentColorSpace);"); + assert_eq!(out, vec![json!("DocumentColorSpace.RGB")]); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn add_document_names_a_color_profile_of_the_profile_file_that_cannot_be_used() { + let dir = std::env::temp_dir().join(format!("vc-script-add-document-warning-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let mut s = Session::new(); + s.attach_new_doc_profiles(dir.clone()); + s.execute("file.newProfiles.edit", &json!({"name": "Print"})).unwrap(); + while !s.documents().is_empty() { + s.execute("file.close", &json!({})).unwrap(); + } + let file = dir.join("Print.vectorcraft"); + let mut v: Value = serde_json::from_slice(&std::fs::read(&file).unwrap()).unwrap(); + let broken = format!("Script profile broken {}", std::process::id()); + v["profiles"] = json!({ &broken: {"mime": "application/vnd.iccprofile", "data": "AAAA"} }); + std::fs::write(&file, serde_json::to_vec(&v).unwrap()).unwrap(); + let r = run(&mut s, "vc.log(app.documents.addDocument('Print').typename);").unwrap(); + assert_eq!(r["log"], json!(["Document"])); + let lines = r["console"]["lines"].as_array().cloned().unwrap_or_default(); + let named = lines.iter().filter_map(Value::as_str).any(|l| l.starts_with("addDocument: ") && l.contains(&broken)); + assert!(named, "{lines:?}"); + assert_eq!(s.documents().len(), 1); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn add_document_refuses_pixel_preview() { + let mut s = Session::new(); + let e = failure(&mut s, "var p = new DocumentPreset(); p.previewMode = DocumentPreviewMode.PixelPreview; app.documents.addDocument('Web', p);"); + assert!(e.contains("DocumentPreviewMode.PixelPreview is not available yet"), "{e}"); + assert!(s.documents().is_empty()); + let out = log( + &mut s, + "var p = new DocumentPreset(); p.previewMode = DocumentPreviewMode.DefaultPreview; vc.log(app.documents.addDocument('Web', p).typename);", + ); + assert_eq!(out, vec![json!("Document")]); +} + +#[test] +fn document_preset_values_count_toward_the_data_a_run_passes() { + // A 64 KiB title, set once, then read or handed to addDocument 32 times: 2 MiB, over a 1 MiB limit. + crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(1 << 20))); + let mut s = Session::new(); + let set = "var p = new DocumentPreset(); p.title = new Array(65537).join('t');"; + let read = failure(&mut s, &format!("{set} for (var i = 0; i < 32; i++) p.title;")); + let added = failure(&mut s, &format!("{set} for (var i = 0; i < 32; i++) try {{ app.documents.addDocument('Print', p, 5); }} catch (e) {{}}")); + let within = run(&mut s, &format!("{set} for (var i = 0; i < 8; i++) p.title;")); + crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None)); + for e in [read, added] { + assert!(e.contains("passed more data"), "{e}"); + } + within.unwrap(); + assert!(s.documents().is_empty()); +} + +#[test] +fn wrappers_go_stale_after_delete_and_undo() { + let (mut s, _, _) = doc(); + let e = failure(&mut s, "var i = app.activeDocument.pageItems[0]; i.remove(); i.name;"); + assert!(e.contains("Stale page item"), "{e}"); + let e = failure(&mut s, "var c = app.activeDocument.pageItems[0].duplicate(); vc.run('edit.undo'); c.position;"); + assert!(e.contains("Stale page item"), "{e}"); + let e = failure(&mut s, "var p = app.activeDocument.pageItems; p.removeAll(); vc.log(p.length); p[0].name;"); + assert!(e.contains("undefined"), "{e}"); + // A named engine keeps its globals, but an object from an earlier run is stale. + run(&mut s, "#targetengine keep\nvar held = app.activeDocument.pageItems[0];").unwrap(); + let e = failure(&mut s, "#targetengine keep\nheld.name;"); + assert!(e.contains("Stale page item"), "{e}"); +} + +#[test] +fn remove_all_refuses_locked_art_before_deleting_anything() { + let (mut s, a, b) = doc(); + s.execute("object.setProps", &json!({"ids": [b.0], "locked": true})).unwrap(); + let e = failure(&mut s, "app.activeDocument.pageItems.removeAll();"); + assert!(e.contains(&b.0.to_string()), "{e}"); + assert_eq!(s.active().unwrap().doc.layers[0].children().unwrap().len(), 2); + s.execute("object.setProps", &json!({"ids": [b.0], "locked": false})).unwrap(); + // A locked object inside an unlocked group stops it too. + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let g = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.setProps", &json!({"ids": [b.0], "locked": true})).unwrap(); + let e = failure(&mut s, "app.activeDocument.pageItems.removeAll();"); + assert!(e.contains(&g.to_string()), "{e}"); + assert!(s.active().unwrap().doc.node(b).is_some()); + s.execute("object.setProps", &json!({"ids": [b.0], "locked": false})).unwrap(); + let out = log(&mut s, "var p = app.activeDocument.pageItems; p.removeAll(); vc.log(p.length);"); + assert_eq!(out, vec![json!(0)]); +} + +#[test] +fn remove_refuses_hidden_or_locked_art_as_remove_all_does() { + let (mut s, a, b) = doc(); + for (on, off) in [ + (json!({"ids": [b.0], "locked": true}), json!({"ids": [b.0], "locked": false})), + (json!({"ids": [b.0], "visible": false}), json!({"ids": [b.0], "visible": true})), + ] { + s.execute("object.setProps", &on).unwrap(); + let e = failure(&mut s, "app.activeDocument.pageItems[0].remove();"); + assert!(e.contains(&format!("cannot delete hidden or locked objects: {}", b.0)), "{on}: {e}"); + assert!(s.active().unwrap().doc.node(b).is_some(), "{on}"); + s.execute("object.setProps", &off).unwrap(); + } + // A group that holds a locked object is refused too. + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let g = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.setProps", &json!({"ids": [b.0], "locked": true})).unwrap(); + let e = failure(&mut s, "app.activeDocument.pageItems[0].remove();"); + assert!(e.contains(&g.to_string()), "{e}"); + assert!(s.active().unwrap().doc.node(b).is_some()); + s.execute("object.setProps", &json!({"ids": [b.0], "locked": false})).unwrap(); + log(&mut s, "app.activeDocument.pageItems[0].remove();"); + assert!(s.active().unwrap().doc.node(b).is_none()); +} + +/// Art on a locked artboard stays: `remove()` and `removeAll()` throw and delete nothing. +#[test] +fn remove_and_remove_all_refuse_art_on_a_locked_artboard() { + let (mut s, a, b) = doc(); + let lock = |s: &mut Session, locked: bool| { + s.edit("Lock Artboard", |d, _| { + d.artboards[0].locked = locked; + Ok(()) + }) + .unwrap(); + }; + lock(&mut s, true); + // An object on a second, unlocked artboard is not deleted either. + s.execute("artboard.new", &json!({"x": 1000, "y": 0, "width": 400, "height": 300})).unwrap(); + let c = rect(&mut s, 1100.0, 100.0, 50.0, 50.0); + let steps = undo_steps(&s); + let e = failure(&mut s, "app.activeDocument.pageItems[1].remove();"); + assert!(e.contains(&format!("cannot delete objects on a locked artboard: {}", b.0)), "{e}"); + let e = failure(&mut s, "app.activeDocument.pageItems.removeAll();"); + assert!(e.contains("cannot delete objects on a locked artboard") && e.contains(&a.0.to_string()), "{e}"); + let out = + log(&mut s, "try { app.activeDocument.pageItems.removeAll(); } catch (e) { vc.log(e.name); } vc.log(app.activeDocument.pageItems.length);"); + assert_eq!(out, vec![json!("Error"), json!(3)]); + let doc = &s.active().unwrap().doc; + assert!(doc.node(a).is_some() && doc.node(b).is_some() && doc.node(c).is_some()); + assert_eq!(undo_steps(&s), steps); + // `editable` is false for art on the locked artboard and true for art on the unlocked one. + let editable = "var p = app.activeDocument.pageItems; vc.log([p[0].editable, p[1].editable, p[2].editable]);"; + assert_eq!(log(&mut s, editable), vec![json!([true, false, false])]); + lock(&mut s, false); + assert_eq!(log(&mut s, editable), vec![json!([true, true, true])]); + let out = log(&mut s, "var p = app.activeDocument.pageItems; p[1].remove(); p.removeAll(); vc.log(p.length);"); + assert_eq!(out, vec![json!(0)]); +} + +#[test] +fn move_and_duplicate_refuse_art_on_a_locked_artboard() { + let (mut s, a, b) = doc(); + let lock = |s: &mut Session, locked: bool| { + s.edit("Lock Artboard", |d, _| { + d.artboards[0].locked = locked; + Ok(()) + }) + .unwrap(); + }; + lock(&mut s, true); + let (order, steps) = (layer_order(&s), undo_steps(&s)); + let e = failure(&mut s, "var p = app.activeDocument.pageItems; p[1].move(p[0], ElementPlacement.PLACEBEFORE);"); + assert!(e.contains(&format!("Cannot move PathItem {}", a.0)), "{e}"); + assert_eq!((layer_order(&s), undo_steps(&s)), (order.clone(), steps)); + // `duplicate` refuses it too, with or without a relative object. + for source in ["app.activeDocument.pageItems[1].duplicate();", "var p = app.activeDocument.pageItems; p[1].duplicate(p[0]);"] { + let e = failure(&mut s, source); + assert!(e.contains(&format!("Cannot duplicate PathItem {}", a.0)), "{source}: {e}"); + } + assert_eq!((layer_order(&s), undo_steps(&s)), (order, steps)); + lock(&mut s, false); + log(&mut s, "var p = app.activeDocument.pageItems; p[1].move(p[0], ElementPlacement.PLACEBEFORE);"); + assert_eq!(layer_order(&s), [b, a]); +} + +#[test] +fn duplicate_refuses_hidden_or_locked_art() { + let (mut s, a, b) = doc(); + for (on, off) in [ + (json!({"ids": [b.0], "locked": true}), json!({"ids": [b.0], "locked": false})), + (json!({"ids": [b.0], "visible": false}), json!({"ids": [b.0], "visible": true})), + ] { + s.execute("object.setProps", &on).unwrap(); + let (order, steps) = (layer_order(&s), undo_steps(&s)); + // With no argument and with a relative object. + for source in ["app.activeDocument.pageItems[0].duplicate();", "var p = app.activeDocument.pageItems; p[0].duplicate(p[1]);"] { + let e = failure(&mut s, source); + assert!(e.contains(&format!("Cannot duplicate PathItem {}", b.0)), "{on} {source}: {e}"); + } + assert_eq!((layer_order(&s), undo_steps(&s)), (order, steps), "{on}"); + s.execute("object.setProps", &off).unwrap(); + } + log(&mut s, "app.activeDocument.pageItems[0].duplicate();"); + let order = layer_order(&s); + assert_eq!(order.len(), 3); + assert!(order.contains(&a) && order.contains(&b)); +} + +/// Reading `editable` on every member of a group on a locked artboard measures the group once. +#[test] +fn editable_measures_a_group_on_a_locked_artboard_once() { + let (mut s, a, b) = doc(); + let mut ids = vec![a.0, b.0]; + ids.extend((0..20).map(|i| rect(&mut s, 10.0 + f64::from(i), 200.0, 5.0, 5.0).0)); + s.execute("select.set", &json!({"ids": ids})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + s.edit("Lock Artboard", |d, _| { + d.artboards[0].locked = true; + Ok(()) + }) + .unwrap(); + let before = vectorcraft_doc::locked_artboard_measures(); + let out = log(&mut s, "var p = app.activeDocument.pageItems, n = 0; for (var i = 0; i < p.length; i++) if (!p[i].editable) n++; vc.log(n);"); + assert_eq!(out, vec![json!(23)], "the group and its 22 members are on the locked artboard"); + assert_eq!(vectorcraft_doc::locked_artboard_measures() - before, 1); +} + +#[test] +fn get_is_file_open_cannot_probe_outside_script_scope() { + let (mut s, _, _) = doc(); + let path = std::env::temp_dir().join(format!("vc-dom-open-{}.svg", std::process::id())); + s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap(); + let p = path.to_string_lossy().replace('\\', "\\\\"); + let query = format!("vc.log(app.getIsFileOpen('{p}')); vc.log(app.getIsFileOpen('{p}.other'));"); + let out = log(&mut s, &query); + assert_eq!(out, vec![json!(true), json!(false)]); + // Read roots that leave out the document's file: the same path does not count. + let elsewhere = std::env::temp_dir().join(format!("vc-dom-roots-{}", std::process::id())); + std::fs::create_dir_all(&elsewhere).unwrap(); + let roots = crate::file_access::AutomationRoots::new(&[&elsewhere], &[]).unwrap().unwrap(); + let out = crate::file_access::confine(Some(&roots), || log(&mut s, &query)); + assert_eq!(out, vec![json!(false), json!(false)]); + let _ = std::fs::remove_dir_all(&elsewhere); + for bad in ["../x.svg", "a/../b.svg", "\\\\\\\\host\\\\share\\\\x.svg", "//host/share/x.svg", "a\\u0000b", ""] { + assert!(failure(&mut s, &format!("app.getIsFileOpen('{bad}');")).contains("cannot check"), "{bad}"); + } + assert!(failure(&mut s, "app.getIsFileOpen(new Array(5000).join('a'));").contains("too long")); + let _ = std::fs::remove_file(path); +} + +#[test] +fn hostile_dom_values_do_not_reenter_or_exceed_limits() { + let (mut s, _, _) = doc(); + let before = s.active().unwrap().selection.objects.clone(); + // A plain object shaped like an object of the model is not one. + let e = failure(&mut s, "var f = {}; f['\\u0000hostRef'] = ['PathItem', 0, 1, 1]; app.activeDocument.selection = f;"); + assert!(e.contains("not plain data"), "{e}"); + // A getter in a value is refused before it runs. + let out = log( + &mut s, + "var hit = 0, v = {}; Object.defineProperty(v, 0, {get: function () { hit++; return 1; }, enumerable: true});\ + try { app.activeDocument.rulerOrigin = v; } catch (e) { vc.log(e.message); } vc.log(hit);", + ); + assert!(out[0].as_str().is_some_and(|m| m.contains("rulerOrigin")), "{out:?}"); + assert_eq!(out[1], json!(0)); + let e = failure(&mut s, "var a = []; for (var i = 0; i < 10001; i++) a.push(app.activeDocument.pageItems[0]); app.activeDocument.selection = a;"); + assert!(e.contains("at most 10000"), "{e}"); + assert_eq!(s.active().unwrap().selection.objects, before); +} + +#[test] +fn prototype_changes_cannot_forge_a_page_item() { + let (mut s, a, _) = doc(); + let out = log( + &mut s, + "var f = Object.create(PathItem.prototype); var m = '';\ + try { f.name = 'x'; } catch (e) { m = e.message; } vc.log(m);\ + try { PathItem.prototype.name = 'y'; } catch (e) { m = e.message; } vc.log(m); PageItem = null; Document.prototype.pageItems = null;\ + vc.log(Object.isFrozen(PathItem.prototype) || !Object.isExtensible(PathItem.prototype));\ + vc.log(app.activeDocument.pageItems.length);\ + try { new PathItem(); } catch (e) { m = e.name; } vc.log(m);", + ); + assert_eq!(out, vec![json!("this is not a page item"), json!("this is not a page item"), json!(true), json!(2), json!("TypeError")]); + assert_eq!(s.active().unwrap().doc.node(a).unwrap().name, None); +} + +#[test] +fn unsupported_members_say_so() { + let (mut s, _, _) = doc(); + assert!(failure(&mut s, "app.activeDocument.layers;").contains("Document.layers is not available yet")); +} + +/// A script that names each visible selected object after its place in `app.selection`, testing +/// the members it uses with `hasOwnProperty` and `propertyIsEnumerable` first. A member that is not +/// available yet, such as `blendingMode`, is read only when `hasOwnProperty` reports it, so it is +/// never read. +const NAME_PICKED: &str = "\ + var picked = app.selection, k = picked.length, named = 0;\ + if (!k) alert('Select something first.');\ + while (k--) {\ + var obj = picked[k];\ + var usable = obj.propertyIsEnumerable('name') && obj.hasOwnProperty('hidden') && !obj.hidden;\ + if (obj.hasOwnProperty('blendingMode') && obj.blendingMode) usable = false;\ + if (usable) { obj.name = 'picked ' + k; named += 1; }\ + }\ + if (picked.length && named < picked.length) alert('Some objects were skipped.');"; + +#[test] +fn a_script_that_checks_has_own_property_changes_every_kind_of_selected_object() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap(); + let path = rect(&mut s, 10.0, 10.0, 20.0, 20.0); + let (g1, g2) = (rect(&mut s, 50.0, 10.0, 20.0, 20.0), rect(&mut s, 80.0, 10.0, 20.0, 20.0)); + s.execute("select.set", &json!({"ids": [g1.0, g2.0]})).unwrap(); + let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + let text = NodeId(s.execute("text.create", &json!({"x": 10, "y": 100, "text": "hi"})).unwrap()["id"].as_u64().unwrap()); + let (c1, c2) = (rect(&mut s, 150.0, 10.0, 20.0, 20.0), rect(&mut s, 155.0, 15.0, 20.0, 20.0)); + s.execute("select.set", &json!({"ids": [c1.0, c2.0]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + let compound = s.active().unwrap().selection.objects[0]; + let objects = [path, group, text, compound]; + s.execute("select.set", &json!({"ids": objects.iter().map(|n| n.0).collect::>()})).unwrap(); + let names = |s: &Session| -> Vec> { + let d = &s.active().unwrap().doc; + objects.iter().map(|n| d.node(*n).unwrap().name.clone()).collect() + }; + let before = names(&s); + let steps = undo_steps(&s); + // The run shows no alert: without an answer for one, it would stop there. + let r = run(&mut s, NAME_PICKED).unwrap_or_else(|e| panic!("{e}")); + assert_eq!(r["dialogs"], json!([]), "{r}"); + let after = names(&s); + assert!(after.iter().all(|n| n.as_deref().is_some_and(|n| n.starts_with("picked "))), "every kind was named: {after:?}"); + assert_eq!(after.iter().collect::>().len(), objects.len(), "each got its own name: {after:?}"); + assert_eq!(undo_steps(&s), steps + 1, "the run is one undo step"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(names(&s), before); + // Opacity reads and writes on every kind too: each object goes to its own value, read back from the script. + s.execute("select.set", &json!({"ids": objects.iter().map(|n| n.0).collect::>()})).unwrap(); + let opacities = |s: &Session| -> Vec { + let d = &s.active().unwrap().doc; + objects.iter().map(|n| d.node(*n).unwrap().opacity).collect() + }; + let before = opacities(&s); + let steps = undo_steps(&s); + let out = log( + &mut s, + "var sel = app.activeDocument.selection, read = [];\ + for (var i = 0; i < sel.length; i++) { sel[i].opacity = 20 + 10 * i; read.push(sel[i].opacity); }\ + vc.log(read);", + ); + assert_eq!(out, vec![json!([20, 30, 40, 50])]); + let after = opacities(&s); + assert!(after.iter().zip(&before).all(|(a, b)| a < b), "every kind got a lower opacity: {before:?} -> {after:?}"); + assert_eq!(undo_steps(&s), steps + 1, "the run is one undo step"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(opacities(&s), before); +} + +#[test] +fn the_selection_is_an_empty_list_when_nothing_is_selected() { + let (mut s, _, _) = doc(); + s.execute("select.set", &json!({"ids": []})).unwrap(); + let out = log(&mut s, "var d = app.activeDocument; vc.log([d.selection instanceof Array, d.selection.length, app.selection.length]);"); + assert_eq!(out, vec![json!([true, 0, 0])]); + let steps = undo_steps(&s); + let r = s.execute("script.run", &json!({"source": NAME_PICKED, "name": "t.js", "answers": [{"kind": "alert", "value": "ok"}]})).unwrap(); + assert_eq!(r["dialogs"][0]["message"], json!("Select something first."), "{r}"); + assert_eq!(undo_steps(&s), steps); +} + +#[test] +fn page_items_report_their_available_members_as_their_own() { + let (mut s, _, _) = doc(); + let out = log( + &mut s, + "var p = app.activeDocument.pageItems[0], d = app.activeDocument, keys = [];\ + for (var k in p) keys.push(k);\ + vc.log([p.hasOwnProperty('opacity'), p.hasOwnProperty('typename'), p.hasOwnProperty('duplicate'),\ + Object.prototype.hasOwnProperty.call(p, 'name'), p.propertyIsEnumerable('opacity'), d.hasOwnProperty('selection'),\ + app.hasOwnProperty('activeDocument')]);\ + vc.log([p.hasOwnProperty('blendingMode'), p.hasOwnProperty('rotate'), d.hasOwnProperty('layers'),\ + p.hasOwnProperty('nosuch'), p.hasOwnProperty('hasOwnProperty'), p.hasOwnProperty('constructor')]);\ + vc.log([keys.indexOf('opacity') >= 0, keys.indexOf('typename') >= 0, keys.indexOf('duplicate'), keys.indexOf('blendingMode')]);", + ); + assert_eq!(out[0], json!([true, true, true, true, true, true, true])); + // Members that are not available yet, unknown names and inherited ones are not the object's own. + assert_eq!(out[1], json!([false, false, false, false, false, false])); + // `for`-`in` lists the properties, not the methods or the members that are not available yet. + assert_eq!(out[2], json!([true, true, -1, -1])); +} + +/// A name a page item class's prototype has, such as `constructor`, is not an object's own, and a +/// script cannot put a name on the prototype. +#[test] +fn a_property_added_to_a_class_prototype_is_not_an_objects_own() { + let (mut s, _, _) = doc(); + let out = log( + &mut s, + "var p = app.activeDocument.pageItems[0]; PathItem.prototype.foo = 1; PageItem.prototype.bar = 2;\ + vc.log([PathItem.prototype.foo === undefined, PageItem.prototype.bar === undefined, 'foo' in p]);\ + vc.log([p.hasOwnProperty('foo'), p.hasOwnProperty('bar'), p.propertyIsEnumerable('foo'), p.hasOwnProperty('constructor')]);", + ); + assert_eq!(out, vec![json!([true, true, false]), json!([false, false, false, false])]); +} + +/// Reading every property `for`-`in` lists calls each getter, and each call counts against the run: +/// a loop of such reads ends at `maxFuel` and at `script.stop`. +#[test] +fn reading_every_listed_property_is_charged_and_can_be_stopped() { + let (mut s, _, _) = doc(); + let mut calls = |body: &str| { + let source = format!("var p = app.activeDocument.pageItems[0], n = 0; for (var k in p) {{ {body} n++; }} vc.log(n);"); + let r = run(&mut s, &source).unwrap_or_else(|e| panic!("{e}")); + (r["hostCalls"].as_u64().unwrap(), r["log"][0].as_u64().unwrap()) + }; + let (listed, n) = calls(""); + let (read, m) = calls("p[k];"); + assert_eq!(n, m); + assert!(n > 10, "{n} properties"); + assert!(read >= listed + n, "{listed} host calls to list, {read} to read {n} properties"); + let spin = "var p = app.activeDocument.pageItems[0]; while (true) for (var k in p) p[k];"; + let e = s.execute("script.run", &json!({"source": spin, "name": "t.js", "maxFuel": 200_000})).unwrap_err(); + assert!(e.to_string().ends_with("(limit)"), "{e}"); + s.script_frames = true; + assert_eq!(run(&mut s, spin).unwrap()["running"], true); + assert!(s.script_pump().is_none()); + assert_eq!(s.execute("script.stop", &json!({})).unwrap()["stopped"], true); + assert!(s.script_pump().unwrap().is_err()); + assert!(!s.script_running()); +} + +/// `pageItems` lists art topmost first, and the selection lists the selected objects in that +/// order whatever order they were selected or made in. +#[test] +fn page_items_and_the_selection_list_the_topmost_object_first() { + let (mut s, a, b) = doc(); + s.execute("object.setProps", &json!({"ids": [a.0], "name": "bottom"})).unwrap(); + s.execute("object.setProps", &json!({"ids": [b.0], "name": "top"})).unwrap(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("select.add", &json!({"ids": [b.0]})).unwrap(); + assert_eq!(s.active().unwrap().selection.objects, vec![a, b], "picked bottom first"); + let out = log( + &mut s, + "var d = app.activeDocument; vc.log([d.pageItems[0].name, d.pageItems[1].name, d.selection[0].name, d.selection[1].name]);\ + d.selection = [d.pageItems[1], d.pageItems[0]]; vc.log(d.selection[0].name);", + ); + assert_eq!(out, vec![json!(["top", "bottom", "top", "bottom"]), json!("top")]); + // An object made last and sent to the back comes after the others it is selected with. + let c = rect(&mut s, 200.0, 200.0, 20.0, 20.0); + s.execute("object.setProps", &json!({"ids": [c.0], "name": "last"})).unwrap(); + let out = log( + &mut s, + "var d = app.activeDocument, c = d.pageItems.getByName('last'); c.zOrder(ZOrderMethod.SENDTOBACK);\ + d.selection = null; c.selected = true; d.pageItems.getByName('top').selected = true;\ + vc.log([d.selection[0].name, d.selection[1].name, d.pageItems[2].name]);", + ); + assert_eq!(out, vec![json!(["top", "last", "last"])]); +} + +/// The selection lists a group before the objects in it, in `pageItems`' order, and reading it +/// costs as much in a large document as in a small one. +#[test] +fn the_selection_follows_page_items_and_costs_the_same_in_a_large_document() { + let (mut s, a, b) = doc(); + let c = rect(&mut s, 200.0, 200.0, 20.0, 20.0); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let group = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [a.0, c.0, group]})).unwrap(); + let source = "var d = app.activeDocument, want = [], got = [];\ + for (var i = 0; i < d.pageItems.length; i++) if (d.pageItems[i].selected) want.push(d.pageItems[i].typename + i);\ + for (var i = 0; i < d.pageItems.length; i++) for (var j = 0; j < d.selection.length; j++)\ + if (d.selection[j] === d.pageItems[i]) got[j] = d.pageItems[i].typename + i;\ + vc.log([want, got]);"; + let out = log(&mut s, source); + assert_eq!(out[0][0], out[0][1], "the selection is in pageItems' order"); + assert_eq!(out[0][0].as_array().map(Vec::len), Some(3)); + // Each pass edits the document, so nothing kept from the last read can be reused. + let edits = "var d = app.activeDocument; for (var i = 0; i < 50; i++) d.selection[0].opacity = 50 + i % 2;"; + s.execute("select.set", &json!({"ids": [c.0]})).unwrap(); + let small = run(&mut s, edits).unwrap()["fuelUsed"].as_u64().unwrap(); + // 3 objects doubled 11 times: 6,144. + s.execute("select.all", &json!({})).unwrap(); + for _ in 0..11 { + s.execute("edit.duplicate", &json!({})).unwrap(); + s.execute("select.all", &json!({})).unwrap(); + } + s.execute("select.set", &json!({"ids": [c.0]})).unwrap(); + crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(1 << 16))); + let large = run(&mut s, edits); + crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None)); + let large = large.unwrap_or_else(|e| panic!("the reads in a large document went over: {e}"))["fuelUsed"].as_u64().unwrap(); + assert_eq!(small, large); +} + +/// A collection read with a name gives what `getByName` gives, and throws as it does for no match. +#[test] +fn a_collection_read_with_a_name_gives_the_named_object() { + let (mut s, a, _) = doc(); + s.execute("object.setProps", &json!({"ids": [a.0], "name": "n"})).unwrap(); + let out = log( + &mut s, + "var d = app.activeDocument, p = d.pageItems, m = [];\ + vc.log([p['n'] === p.getByName('n'), p['n'].name, 'n' in p, 'nosuch' in p, p['length'] === p.length]);\ + vc.log([app.documents[d.name] === d, d.name in app.documents, 'nosuch' in app.documents]);\ + try { p['nosuch']; } catch (e) { m.push(e.message); }\ + try { app.documents.nosuch; } catch (e) { m.push(e.message); }\ + vc.log(m);", + ); + assert_eq!(out, vec![json!([true, "n", true, false, true]), json!([true, true, false]), json!(["Not found", "Not found"])]); +} + +/// `opacity`, `hidden`, `locked` and the position and size setters on an object in a hidden or +/// locked layer throw and the run changes nothing, while its name and note still change; an object +/// that is hidden or locked itself takes them. +#[test] +fn setters_refuse_art_in_a_hidden_or_locked_layer() { + let (mut s, a, b) = doc(); + let layer = NodeId(s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().unwrap()); + let c = rect(&mut s, 200.0, 200.0, 20.0, 20.0); + rect(&mut s, 300.0, 200.0, 20.0, 20.0); + for (id, name) in [(a, "locked"), (b, "free"), (c, "closed")] { + s.execute("object.setProps", &json!({"ids": [id.0], "name": name})).unwrap(); + } + for (on, off) in [ + (json!({"ids": [layer.0], "visible": false}), json!({"ids": [layer.0], "visible": true})), + (json!({"ids": [layer.0], "locked": true}), json!({"ids": [layer.0], "locked": false})), + ] { + s.execute("object.setProps", &on).unwrap(); + // `hidden` and `locked` are refused even when the value is the one the object has. + for set in [ + "opacity = 50", + "hidden = true", + "hidden = false", + "locked = true", + "locked = false", + "left = 5", + "top = 5", + "position = [5, 5]", + "width = 10", + "height = 10", + "zOrder(ZOrderMethod.BRINGTOFRONT)", + ] { + let (before, steps) = (format!("{:?}", s.active().unwrap().doc.layers), undo_steps(&s)); + // The change made before the refusal is put back with the rest of the run. + let e = failure(&mut s, &format!("var p = app.activeDocument.pageItems; p.getByName('free').opacity = 20; p.getByName('closed').{set};")); + assert!(e.contains(&format!("Cannot edit PathItem {}", c.0)), "{on} {set}: {e}"); + assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before, "{on} {set}"); + assert_eq!(undo_steps(&s), steps, "{on} {set}"); + } + let out = log( + &mut s, + "var c = app.activeDocument.pageItems.getByName('closed'); c.note = 'n'; c.name = 'renamed'; c.opacity = c.opacity;\ + vc.log([c.name, c.note, c.opacity]); c.name = 'closed'; c.note = '';", + ); + assert_eq!(out, vec![json!(["renamed", "n", 100])], "{on}"); + s.execute("object.setProps", &off).unwrap(); + } + s.execute("object.setProps", &json!({"ids": [a.0], "locked": true})).unwrap(); + s.execute("object.setProps", &json!({"ids": [b.0], "visible": false})).unwrap(); + let out = log( + &mut s, + "var p = app.activeDocument.pageItems; p.getByName('locked').opacity = 50; p.getByName('free').opacity = 40;\ + vc.log([p.getByName('locked').opacity, p.getByName('free').opacity]);", + ); + assert_eq!(out, vec![json!([50, 40])]); +} + +/// `name` takes a number or a Boolean as the text `String` gives it, and nothing else. +#[test] +fn a_name_given_as_a_number_or_a_boolean_becomes_its_text() { + let (mut s, a, _) = doc(); + let out = log( + &mut s, + "var i = app.activeDocument.pageItems[1]; i.name = 5; vc.log([typeof i.name, i.name]); i.name = 2.5e-7; vc.log(i.name);\ + i.name = true; vc.log(i.name);", + ); + assert_eq!(out, vec![json!(["string", "5"]), json!("2.5e-7"), json!("true")]); + assert_eq!(s.active().unwrap().doc.node(a).unwrap().name.as_deref(), Some("true")); + for value in ["null", "undefined", "{}"] { + assert!(failure(&mut s, &format!("app.activeDocument.pageItems[1].name = {value};")).contains("name must be a string"), "{value}"); + } +} + +/// `String` of an object of the object model names its class, and its name when it has one. +#[test] +fn objects_of_the_object_model_print_their_class_and_name() { + let (mut s, a, _) = doc(); + s.execute("object.setProps", &json!({"ids": [a.0], "name": "Logo"})).unwrap(); + let out = log( + &mut s, + "var d = app.activeDocument, p = d.pageItems;\ + vc.log([String(p[0]), String(p[1]), '' + p[1], p[1].toString(), String(p[1].parent) === '[Layer ' + p[1].parent.name + ']']);\ + vc.log([String(d) === '[Document ' + d.name + ']', String(app), String(p), String(app.documents)]);", + ); + assert_eq!(out[0], json!(["[PathItem ]", "[PathItem Logo]", "[PathItem Logo]", "[PathItem Logo]", true])); + assert_eq!(out[1], json!([true, "[Application]", "[PageItems]", "[Documents]"])); +} + +/// `activeDocument`, `documents` and `selection` without `app.` read the application's members, and +/// assigning one assigns the member: `selection` selects, `documents` keeps its value. +#[test] +fn the_application_members_can_be_named_without_app() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + let out = log( + &mut s, + "vc.log([activeDocument === app.activeDocument, documents === app.documents, documents.length,\ + selection.length, selection[0] === app.activeDocument.pageItems[1], typeof activeDocument]);", + ); + assert_eq!(out, vec![json!([true, true, 1, 1, true, "object"])]); + let out = log( + &mut s, + "var d = app.activeDocument; selection = null; vc.log(d.selection.length);\ + selection = [d.pageItems[0], d.pageItems[1]]; vc.log(d.selection.length);\ + app.selection = d.pageItems[0]; vc.log([d.selection.length, selection[0] === d.pageItems[0]]);\ + var selection = d.selection; documents = 5; activeDocument = d; vc.log([selection.length, typeof documents]);", + ); + assert_eq!(out, vec![json!(0), json!(2), json!([1, true]), json!([1, "object"])]); + assert_eq!(s.active().unwrap().selection.objects, vec![b]); + // A top-level `var selection = []` clears the selection; a push goes to a list nobody keeps. + let out = log(&mut s, "var selection = []; selection.push(app.activeDocument.pageItems[0]); vc.log(selection.length);"); + assert_eq!(out, vec![json!(0)]); + assert!(s.active().unwrap().selection.objects.is_empty()); + assert!(failure(&mut s, "activeDocument = 5;").contains("not a Document")); + let e = failure(&mut s, "'use strict'; documents = 5;"); + assert!(e.contains("TypeError") && e.contains("cannot assign to property 'documents': it has only a getter"), "{e}"); + // With no document open, reading `activeDocument` throws as `app.activeDocument` does. + let mut s = Session::new(); + assert!(failure(&mut s, "activeDocument;").contains("No active document")); +} + +/// Assigning to a name a collection does not have throws as reading it does, and assigning an +/// index does not replace the object there. +#[test] +fn assigning_a_name_a_collection_lacks_throws() { + let (mut s, _, _) = doc(); + let steps = undo_steps(&s); + for source in ["app.activeDocument.pageItems.qux = 4;", "app.documents.qux = 4;"] { + assert!(failure(&mut s, source).contains("Not found"), "{source}"); + } + let out = log(&mut s, "var p = app.activeDocument.pageItems; p[0] = 3; vc.log(typeof p[0]);"); + assert_eq!(out, vec![json!("object")]); + // On a page item the value is not kept; strict-mode code throws instead. + let out = log(&mut s, "var i = app.activeDocument.pageItems[0]; i.qux = 4; vc.log(typeof i.qux);"); + assert_eq!(out, vec![json!("undefined")]); + let e = failure(&mut s, "'use strict'; app.activeDocument.pageItems[0].qux = 4;"); + assert!(e.contains("TypeError") && e.contains("qux"), "{e}"); + assert_eq!(undo_steps(&s), steps); +} + +/// `JSON.stringify` writes a collection, or data that holds one, without reading a `toJSON` the +/// collection lacks, while a script that reads `toJSON` itself gets `Not found`. +#[test] +fn json_stringify_writes_a_collection() { + let (mut s, _, _) = doc(); + let out = log( + &mut s, + "var p = app.activeDocument.pageItems, m = ''; vc.log([JSON.stringify(p), JSON.stringify({list: [p, app.documents]})]);\ + try { p.toJSON; } catch (e) { m = e.message; } vc.log(m);", + ); + assert_eq!(out, vec![json!(["{}", "{\"list\":[{},{}]}"]), json!("Not found")]); +} diff --git a/crates/engine/src/tests/script_run.rs b/crates/engine/src/tests/script_run.rs index 56bc5854a1..0d766e238a 100644 --- a/crates/engine/src/tests/script_run.rs +++ b/crates/engine/src/tests/script_run.rs @@ -165,7 +165,9 @@ fn an_error_names_the_script_its_place_and_kind() { assert_eq!(e, "t.js: line 2, column 3: TypeError: no (thrown)"); let e = run(&mut s, "var = 1;").unwrap_err().to_string(); assert!(e.starts_with("t.js: line 1,") && e.ends_with("(syntax)"), "{e}"); - assert!(run(&mut s, "app.activeDocument;").unwrap_err().to_string().contains("`vc`")); + assert!(run(&mut s, "new Window('dialog');").unwrap_err().to_string().contains("`vc`")); + // The application's members need no `app.`, so naming one alone is not an error. + assert_eq!(run(&mut s, "activeDocument;").unwrap()["ok"], true); assert!(run(&mut s, "#targetengine 9x\n1").unwrap_err().to_string().contains("#targetengine needs a name of letters, digits and _")); assert_eq!(s.script_report().unwrap()["line"], 1); } @@ -204,7 +206,7 @@ fn failed_script_report_keeps_message_and_adds_origin() { assert_eq!(error, Some(json!(format!("t.js:{line}:{column}: {message}"))), "{source}"); } // The app's own reference error names the `vc` object; the same text a script threw does not. - run(&mut s, "app.activeDocument;").unwrap_err(); + run(&mut s, "new Window('dialog');").unwrap_err(); assert!(s.script_report().unwrap()["message"].as_str().unwrap().contains("`vc`")); assert_eq!(s.script_report().unwrap()["messageOrigin"], "built-in"); // An error in code `eval` compiled keeps where its message came from. diff --git a/crates/engine/src/tests/toolsettings.rs b/crates/engine/src/tests/toolsettings.rs index 69d382f2dc..933ed15874 100644 --- a/crates/engine/src/tests/toolsettings.rs +++ b/crates/engine/src/tests/toolsettings.rs @@ -30,6 +30,55 @@ fn blob_tip_options_report_and_persist() { assert_eq!((next.tool_options()["angle"].as_f64(), next.tool_options()["roundness"].as_f64()), (Some(45.0), Some(0.0))); } +/// The Circle tool's From Center survives a tool switch and is saved with the preferences. +#[test] +fn circle_from_center_persists() { + let mut s = session(); + select(&mut s, "circle"); + let mut want = s.tool_options(); + assert_eq!(want["fromCenter"], json!(false)); + want["fromCenter"] = json!(true); + s.set_tool_option("fromCenter", &json!(true)); + select(&mut s, "selection"); + select(&mut s, "circle"); + assert_eq!(s.tool_options(), want); + select(&mut s, "selection"); + let saved = serde_json::to_string(&s.prefs).unwrap(); + let mut next = session(); + next.apply_prefs(serde_json::from_str(&saved).unwrap()); + select(&mut next, "circle"); + assert_eq!(next.tool_options(), want); +} + +/// An option set during a press (`tool.setOption`, or a Control bar change) is kept when the press +/// is dropped: the drop gives back only what the press itself changed. +#[test] +fn the_circle_from_center_set_during_a_dropped_press_is_kept() { + let v = ViewInfo::default(); + let mut s = session(); + select(&mut s, "circle"); + let mut want = s.tool_options(); + s.set_tool_option("fromCenter", &json!(true)); + s.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 100.0), v).unwrap(); + s.set_tool_option_cmd(&json!({"key": "fromCenter", "value": false})).unwrap(); + s.drop_tool_press(v).unwrap(); + want["fromCenter"] = json!(false); + assert_eq!(s.tool_options(), want); + assert_eq!(s.prefs.tool_settings["circle"]["fromCenter"], json!(false)); + s.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 100.0), v).unwrap(); + s.set_tool_option("fromCenter", &json!(true)); + s.drop_tool_press(v).unwrap(); + want["fromCenter"] = json!(true); + assert_eq!(s.tool_options(), want); + assert_eq!(s.prefs.tool_settings["circle"]["fromCenter"], json!(true)); + // Setting a Parametric Shape's kind also puts its numbers back to that kind's: those are kept too. + select(&mut s, "parametricShape"); + s.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 100.0), v).unwrap(); + let set = s.set_tool_option_cmd(&json!({"key": "kind", "value": "star"})).unwrap(); + s.drop_tool_press(v).unwrap(); + assert_eq!(s.tool_options(), set); +} + #[test] fn options_survive_a_tool_switch() { let mut s = session(); @@ -473,6 +522,54 @@ fn alt_smoothing_takes_the_smooth_tools_fidelity() { } } +/// The Smoothness an Alt smoothing drag sends with `path.smoothRegion` on a selected path. +fn alt_smoothness(s: &mut Session) -> Option { + use vectorcraft_tools::Action; + let mods = Mods { alt: true, ..Default::default() }; + let mut last = vec![]; + for (kind, x, y) in [(PointerKind::Down, 50.0, 150.0), (PointerKind::Drag, 150.0, 150.0), (PointerKind::Up, 250.0, 160.0)] { + let ev = PointerEvent { mods, ..PointerEvent::new(kind, x, y) }; + last = s.with_tool_cx(ViewInfo::default(), |t, cx| t.pointer(cx, &ev)); + } + last.iter().find_map(|a| match a { + Action::Exec(c, v) if c == "path.smoothRegion" => v["smoothness"].as_f64(), + _ => None, + }) +} + +/// Smooth Tool Options' Smoothness is kept with the preferences (50% until it is set), and Alt +/// smoothing with the Pencil, Paintbrush and Blob Brush uses it. A Smoothness outside 0 to 100 is +/// an error that sets nothing. +#[test] +fn the_smooth_tools_smoothness_is_kept_and_alt_smoothing_takes_it() { + let mut s = session(); + s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 100, "height": 100})).unwrap(); + select(&mut s, "smooth"); + assert_eq!(s.tool_options()["smoothness"], json!(50.0)); + for bad in [json!(-1), json!(100.5), json!("30"), json!(null)] { + let e = s.set_tool_option_cmd(&json!({"key": "smoothness", "value": bad})).unwrap_err(); + assert_eq!(e, "tool `smooth`: `smoothness` must be a number from 0 to 100", "{bad}"); + } + assert_eq!(s.tool_options()["smoothness"], json!(50.0)); + s.set_tool_option("smoothness", &json!(80)); + assert_eq!(s.prefs.tool_settings["smooth"]["smoothness"], json!(80.0)); + for id in ["pencil", "paintbrush", "blobBrush"] { + select(&mut s, id); + if id == "pencil" { + s.set_tool_option("altSmooth", &json!(true)); + } + assert_eq!(alt_smoothness(&mut s), Some(80.0), "{id}"); + assert!(s.tool_options().get("smoothness").is_none(), "{id} has no Smoothness of its own"); + } + s.set_tool_option_cmd(&json!({"tool": "smooth", "key": "smoothness", "value": 10})).unwrap(); + assert_eq!(alt_smoothness(&mut s), Some(10.0), "the Blob Brush takes the new Smoothness"); + let saved = serde_json::to_string(&s.prefs).unwrap(); + let mut next = session(); + next.apply_prefs(serde_json::from_str(&saved).unwrap()); + select(&mut next, "smooth"); + assert_eq!(next.tool_options()["smoothness"], json!(10.0)); +} + /// `tool.setOption` with a value of the wrong type, a number out of range, an unknown value or an /// option the tool doesn't have is an error naming the tool and the option. Nothing is set, also /// when another option given with it is good, and nothing is saved or recorded for undo. @@ -489,7 +586,10 @@ fn bad_option_values_are_errors_that_set_nothing() { (json!({"key": "bogus", "value": 1}), "tool `smooth`: unknown option `bogus`"), (json!({"tool": "pencil", "values": {"closeWithin": 5, "fidelity": "x"}}), "tool `pencil`: `fidelity` must be a number from 0.01 to 100"), (json!({"tool": "pencil", "key": "fill", "value": "yes"}), "tool `pencil`: `fill` must be true or false"), - (json!({"tool": "blobBrush", "key": "sizeMode", "value": "huge"}), "tool `blobBrush`: `sizeMode` must be one of `fixed`, `pressure`"), + ( + json!({"tool": "blobBrush", "key": "sizeMode", "value": "huge"}), + "tool `blobBrush`: `sizeMode` must be one of `fixed`, `pressure`, `stylusWheel`", + ), (json!({"tool": "eraser", "key": "fidelity", "value": 4}), "tool `eraser`: unknown option `fidelity`"), (json!({"tool": "polygon", "key": "sides", "value": 2}), "tool `polygon`: `sides` must be a whole number from 3 to 1000"), ( diff --git a/crates/engine/src/tests/webexport.rs b/crates/engine/src/tests/webexport.rs index 39c95da3f6..9ab1aab001 100644 --- a/crates/engine/src/tests/webexport.rs +++ b/crates/engine/src/tests/webexport.rs @@ -163,6 +163,92 @@ fn gif_transparency_index_and_map_to_transparent() { assert_eq!(pixels(&gif).get_pixel(25, 15)[3], 0, "index {i}"); } +/// 40×30: red at 25% opacity on the left half, blue at 75% on the right, nothing behind them. +fn see_through() -> Session { + let mut s = session(40.0, 30.0); + rect(&mut s, [0.0, 0.0, 20.0, 30.0], "#ff0000"); + run(&mut s, "transparency.set", json!({"opacity": 25})); + rect(&mut s, [20.0, 0.0, 20.0, 30.0], "#0000ff"); + run(&mut s, "transparency.set", json!({"opacity": 75})); + s +} + +/// The shares of the left and right halves' pixels that are opaque. +fn opaque_halves(img: &image::RgbaImage) -> [f64; 2] { + [0, 20].map(|x0| (x0..x0 + 20).flat_map(|x| (0..30).map(move |y| (x, y))).filter(|&(x, y)| img.get_pixel(x, y)[3] == 255).count() as f64 / 600.0) +} + +#[test] +fn transparency_dither_keeps_a_share_of_partly_transparent_pixels() { + let mut s = see_through(); + for format in ["gif", "png8"] { + let file = |s: &mut Session, extra: Value| { + let mut p = json!({"format": format, "antiAlias": "none"}); + p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone()); + one(s, p) + }; + // By default the pixels under half opacity are transparent and the others opaque. + let none = file(&mut s, json!({})); + assert_eq!(opaque_halves(&pixels(&none)), [0.0, 1.0], "{format}"); + assert_eq!(file(&mut s, json!({"transparencyDither": "none"})), none, "{format}"); + assert_eq!(file(&mut s, json!({"transparencyDither": "diffusion", "transparencyDitherAmount": 0})), none, "{format}"); + for method in ["diffusion", "pattern", "noise"] { + let p = json!({"transparencyDither": method}); + let dithered = file(&mut s, p.clone()); + let [left, right] = opaque_halves(&pixels(&dithered)); + assert!((left - 0.25).abs() < 0.1 && (right - 0.75).abs() < 0.1, "{format} {method}: {left} {right}"); + if format == "gif" { + assert_eq!(gif_transparent_index(&dithered), Some(0), "{method}"); + } + assert_eq!(file(&mut s, p.clone()), dithered, "{format} {method}: the same art gives the same file"); + // The preview shows what Save writes. + let mut pv = json!({"format": format, "antiAlias": "none", "image": true}); + pv["transparencyDither"] = json!(method); + let shown = run(&mut s, "document.exportForWeb.preview", pv); + assert_eq!(vectorcraft_format::base64_decode(shown["dataBase64"].as_str().unwrap()).unwrap(), dithered, "{format} {method}"); + // Without transparency the dither does nothing. + let opaque = file(&mut s, json!({"transparencyDither": method, "transparency": false})); + assert_eq!(opaque, file(&mut s, json!({"transparency": false})), "{format} {method}"); + } + // A fixed palette keeps the transparent entry for the dithered pixels. + let fixed = file(&mut s, json!({"transparencyDither": "pattern", "colorTable": {"customPalette": ["#ffbfbf", "#4040ff"]}})); + let [left, right] = opaque_halves(&pixels(&fixed)); + assert!(left > 0.0 && left < 1.0 && right > 0.0 && right < 1.0, "{format}: {left} {right}"); + } +} + +#[test] +fn transparency_dither_settings_are_checked_and_remembered() { + let mut s = see_through(); + for bad in [ + json!({"transparencyDither": "spray"}), + json!({"transparencyDither": 3}), + json!({"transparencyDitherAmount": 101}), + json!({"transparencyDitherAmount": -1}), + ] { + assert!(s.execute("document.exportForWeb", &bad).is_err(), "{bad}"); + assert!(s.execute("webExport.settings", &bad).is_err(), "{bad}"); + } + let e = s.execute("document.exportForWeb", &json!({"transparencyDitherAmount": 101})).unwrap_err().to_string(); + assert!(e.contains("`transparencyDitherAmount` must be from 0 to 100"), "{e}"); + assert_eq!(defaults()["transparencyDither"], "none"); + assert_eq!(defaults()["transparencyDitherAmount"], 100); + // The remembered settings and a saved preset keep both. + let set = run(&mut s, "webExport.settings", json!({"transparencyDither": "diffusion", "transparencyDitherAmount": 40})); + assert_eq!((&set["settings"]["transparencyDither"], &set["settings"]["transparencyDitherAmount"]), (&json!("diffusion"), &json!(40))); + let read = run(&mut s, "webExport.settings", json!({})); + assert_eq!(read["settings"], set["settings"]); + run(&mut s, "webExport.presets.save", json!({"name": "Soft edges", "transparencyDither": "noise", "transparencyDitherAmount": 60})); + let list = run(&mut s, "webExport.presets.list", json!({})); + let saved = list["presets"].as_array().unwrap().iter().find(|p| p["name"] == "Soft edges").unwrap(); + assert_eq!((&saved["settings"]["transparencyDither"], &saved["settings"]["transparencyDitherAmount"]), (&json!("noise"), &json!(60))); + let by_preset = one(&mut s, json!({"preset": "Soft edges", "format": "gif", "antiAlias": "none"})); + assert_eq!(by_preset, one(&mut s, json!({"format": "gif", "antiAlias": "none", "transparencyDither": "noise", "transparencyDitherAmount": 60}))); + // Settings saved before the keys existed take the defaults. + let old: cmd::webexport::WebSettings = serde_json::from_value(json!({"format": "png8", "dither": "pattern"})).unwrap(); + assert_eq!((old.transparency_dither.id(), old.transparency_dither_amount), ("none", 100)); +} + #[test] fn jpeg_size_grows_with_quality() { let mut s = many_colours(); diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index 446d441fc4..222657ac1c 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -222,6 +222,8 @@ impl Session { self.deactivate_tool(view)?; self.keep_tool_settings(); self.tool = self.make_tool(id); + // A pick is armed for a stop after its tool is chosen (`note_stop_pick`). + self.stop_pick = None; if let Some(selection) = text_selection { self.tool.set_option("textSelection", &selection); } @@ -460,7 +462,7 @@ impl Session { /// Pen goes on drawing its path), less the work the gesture ended as a command would: a /// Cmd+click that takes the type being edited out of the selection ends its edit (#3779). pub(crate) fn give_back_tool(&mut self, view: ViewInfo) -> Result<()> { - let lent_by_bucket = self.lent_by_bucket(); + let lent_by_painter = self.lent_by_painter(); let Some(lender) = self.lender.take() else { return Ok(()) }; // The points the lent tool left picked go back to the tool it was lent to when that tool // picks mesh points, none when it unpicked them all (#8090). Group Selection and the @@ -470,12 +472,12 @@ impl Session { .then(|| self.tool.options().get("meshPoints").cloned()) .flatten() .filter(|p| lender.options().get("meshPoints") != Some(p)); - // The lent tool's last actions (a drag it cancels or keeps) still count as the Live Paint - // Bucket's when the bucket lent it ([`Session::bucket_paints`]). - let outer_bucket = self.back_to_bucket; - self.back_to_bucket |= lent_by_bucket; + // The lent tool's last actions (a drag it cancels or keeps) still count as those of the tool + // that lent it when that tool paints with the chosen colors ([`Session::tool_paints`]). + let outer_painter = self.back_to_painter; + self.back_to_painter = self.back_to_painter.or(lent_by_painter); let r = self.deactivate_tool(view); - self.back_to_bucket = outer_bucket; + self.back_to_painter = outer_painter; self.keep_tool_settings(); self.tool = lender; // Back with the Selection or Group Selection tool, a symbol part the lent Direct @@ -524,12 +526,17 @@ impl Session { } } } - // Alt switches the Pencil, Paintbrush or Blob Brush to Smooth, using Smooth Tool Options' Fidelity. + // Alt switches the Pencil, Paintbrush or Blob Brush to Smooth, using Smooth Tool Options' Fidelity + // and Smoothness. if matches!(t.id(), "pencil" | "paintbrush" | "blobBrush") && wanted("smooth") - && let Some(v) = prefs.tool_settings.get("smooth").and_then(|s| s.get("fidelity")) + && let Some(saved) = prefs.tool_settings.get("smooth") { - t.set_option("smoothFidelity", v); + for (key, alt) in [("fidelity", "smoothFidelity"), ("smoothness", "smoothSmoothness")] { + if let Some(v) = saved.get(key) { + t.set_option(alt, v); + } + } } } @@ -567,6 +574,7 @@ impl Session { let Some(st) = self.active.and_then(|i| self.docs.get(i)) else { return R::default() }; let (unit, stroke_unit) = (self.general_unit(), self.stroke_unit()); let smart_guides = view.smart_guides && !view.pixel_preview; + let (pick_stop, armed_for_tool) = self.pick_stop(); let cx = ToolContext { doc: &st.doc, ruler_origin: st.doc.ruler_origin_for(view.artboard), @@ -592,7 +600,8 @@ impl Session { corner_widgets: view.corner_widgets, shape_widgets: view.shape_widgets, fill_active: self.fill_active, - gradient_stop: self.selected_stop(), + gradient_stop: pick_stop, + tool_paints: self.tool_paints(!self.fill_active) || armed_for_tool, appearance_item: self.appearance_item(), constrain_angle: self.prefs.constrain_angle, keyboard_increment: self.prefs.keyboard_increment, @@ -1486,6 +1495,7 @@ impl Session { let before_press = self.options_before_press_set(); let sets_pressed = self.press_taken_by(self.tool.id()); self.tool.set_option(key, v); + self.note_stop_pick(key, self.tool.id() == "eyedropper"); self.tool_set_since_reset = true; self.keep_tool_settings(); self.keep_press_set(before_press, |k| sets_pressed && k == key, sets_pressed); @@ -1573,9 +1583,35 @@ impl Session { Self::restore_stores(&self.prefs, self.tool.as_mut(), |store| settings::stores(set).any(|(s, _)| s == store)); } self.keep_press_set(before_press, |k| sets_pressed && values.contains_key(k), sets_pressed); + // The Eyedropper waiting for a Cmd-drag it lent a selection tool to is armed as the active one. + if (active || lender) && values.contains_key("stop") { + let eyedropper = id.unwrap_or(self.tool.id()) == "eyedropper"; + self.note_stop_pick("stop", eyedropper); + } out } + /// After option `key` of the active tool, or of the tool waiting for a Cmd-drag it lent, is set + /// (`eyedropper`: that tool is the Eyedropper): an Eyedropper armed to sample into a stop of the + /// gradient a tool paints with (`stop`) keeps whose gradient that is ([`Session::stop_pick`]). + fn note_stop_pick(&mut self, key: &str, eyedropper: bool) { + if key == "stop" && eyedropper { + let selected = self.selected_stop().is_some(); + self.stop_pick = self.gradient_stop.map(|(_, owner)| owner).filter(|owner| selected && owner.painter().is_some()); + } + } + + /// The stop an armed Eyedropper pick samples into ([`ToolContext::gradient_stop`]): the + /// selected one, and for a pick armed for a stop of the gradient a tool paints with + /// ([`Session::stop_pick`]) only a stop still selected on that gradient. + fn pick_stop(&self) -> (Option, bool) { + let armed = self.stop_pick.filter(|owner| self.tool.returns_to().is_some_and(|id| owner.painter() == Some(id))); + match armed { + Some(owner) => (self.selected_stop().filter(|_| self.gradient_stop.is_some_and(|(_, o)| o == owner)), true), + None => (self.selected_stop(), false), + } + } + /// The tool that took the press under way: the active tool, or the tool that lent a selection /// tool for it (a Cmd-drag), which the dropped press gives its options back to. fn pressed_tool(&self) -> Option<&dyn Tool> { @@ -1743,10 +1779,16 @@ impl Session { self.put_back_interaction(); } let outer = std::mem::replace(&mut self.in_tool_actions, true); - let outer_bucket = self.back_to_bucket; - // The Eyedropper's sample into a stop of the Live Paint Bucket's gradient, which switches back to the bucket. - self.back_to_bucket |= - self.tool.id() == "eyedropper" && acts.iter().any(|a| matches!(a, Action::SwitchTool(t) if t == crate::cmd::LIVE_PAINT_BUCKET)); + let outer_painter = self.back_to_painter; + // The Eyedropper's sample into a stop of the gradient of a tool that paints with the chosen + // colors (the Live Paint Bucket, the Shape Builder), which switches back to that tool. + if self.tool.id() == "eyedropper" { + let back = acts.iter().find_map(|a| match a { + Action::SwitchTool(t) => crate::cmd::painting_tool_of(t, false).or_else(|| crate::cmd::painting_tool_of(t, true)), + _ => None, + }); + self.back_to_painter = self.back_to_painter.or(back); + } // A preview that settling applied (typing kept as its own step before a drag begins) shows // its warning in the status bar, as the tool's own commit shows its preview's. let r = if !outer && self.depth == 0 { @@ -1756,7 +1798,7 @@ impl Session { self.apply_tool_actions(acts) }; self.in_tool_actions = outer; - self.back_to_bucket = outer_bucket; + self.back_to_painter = outer_painter; if !outer && self.depth == 0 { self.trim_histories(); } diff --git a/crates/engine/tests/color_settings.rs b/crates/engine/tests/color_settings.rs index c07d741265..61bfba6fb3 100644 --- a/crates/engine/tests/color_settings.rs +++ b/crates/engine/tests/color_settings.rs @@ -939,6 +939,32 @@ fn saved_color_settings_that_cannot_be_used_leave_the_defaults() { } } +/// With a working RGB space other than sRGB, `color.contrast` writes the background in working RGB, +/// the form `against` takes: a given brown comes back as it was given, and the background read +/// behind the selection, given back, answers the same ratio. +#[test] +fn contrast_writes_the_background_as_against_takes_it_with_another_working_space() { + let _g = settings(); + let before = cms::active_settings(); + let mut s = session(); + exec(&mut s, "edit.colorSettings", json!({"rgb": cms::WIDE_GAMUT_RGB})); + let given = s.execute("color.contrast", &json!({"color": "#000000", "against": "#806040"})); + exec(&mut s, "file.new", json!({"width": 200, "height": 200})); + exec(&mut s, "shape.rectangle", json!({"x": 20, "y": 20, "width": 80.3, "height": 160})); + exec(&mut s, "paint.setFill", json!({"color": "#2050a0"})); + exec(&mut s, "object.lock", json!({})); + exec(&mut s, "shape.rectangle", json!({"x": 50, "y": 50, "width": 100, "height": 100})); + exec(&mut s, "paint.setFill", json!({"color": "#808080"})); + let below = s.execute("color.contrast", &json!({})); + let again = below.as_ref().ok().and_then(|b| s.execute("color.contrast", &json!({"against": b["against"].clone()})).ok()); + cms::set_active(&before).unwrap(); + let given = given.unwrap(); + assert_eq!(given["against"], "#806040", "{given}"); + let (below, again) = (below.unwrap(), again.unwrap()); + assert_eq!(below["against"], again["against"], "{below} {again}"); + assert!((below["ratio"].as_f64().unwrap() - again["ratio"].as_f64().unwrap()).abs() < 1e-9, "{below} {again}"); +} + /// View › Proof Setup › Customize's Preserve CMYK Numbers proofs each color from its own inks: /// with Device CMYK as the working space, C50 M50 Y50 and K50 show as the same gray, and on /// VectorCraft Generic CMYK they print, and so proof, as different grays; a pattern's tile art diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index 2ec927bd48..25067f5c0e 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -41,7 +41,8 @@ const OUTSIDE: &[(&str, &str, &str)] = &[ /// The names the host adds that stay inside the document and the run, by the object that has them. /// Reading a file or a folder, a file dialog and a message to the person do not change anything -/// outside it. +/// outside it. The document model (`app`, its classes and the enumerations) acts on the open +/// documents; `Document.saveAs` and `close` throw "not available yet". const INSIDE: &[(&str, &str)] = &[ ("", "$ File Folder UnitValue alert confirm localize prompt toSource"), ("Object.prototype.", "toSource"), @@ -72,8 +73,70 @@ const INSIDE: &[(&str, &str)] = &[ "absoluteURI alias changePath constructor created displayName error error= exists fsName fullName getFiles \ getRelativeURI localizedName modified name parent path relativeURI resolve selectDlg toString", ), + ( + "", + "activeDocument activeDocument= app Application CoordinateSystem Document DocumentArtboardLayout DocumentColorSpace \ + DocumentPreset DocumentPresetType DocumentPreviewMode DocumentRasterResolution DocumentTransparencyGrid documents \ + Documents ElementPlacement Layer PageItem PageItems RulerUnits selection selection= ZOrderMethod", + ), + ("Application.", "prototype"), + ( + "Application.prototype.", + "activeDocument activeDocument= beep beep= constructor coordinateSystem coordinateSystem= documents getIsFileOpen \ + selection selection= toString typename", + ), + ("DocumentPreset.", "prototype"), + ( + "DocumentPreset.prototype.", + "artboardLayout artboardLayout= artboardRowsOrCols artboardRowsOrCols= artboardSpacing artboardSpacing= colorMode \ + colorMode= constructor documentBleedLink documentBleedLink= documentBleedOffsetRect documentBleedOffsetRect= height \ + height= numArtboards numArtboards= previewMode previewMode= rasterResolution rasterResolution= title title= \ + toString transparencyGrid transparencyGrid= typename units units= width width=", + ), + ("Documents.", "prototype"), + ("Documents.prototype.", "add addDocument constructor getByName index length parent toString typename"), + ("Document.", "prototype"), + ( + "Document.prototype.", + "activeLayer activeLayer= artboards artboards= close close= constructor convertCoordinate documentColorSpace \ + groupItems groupItems= height layers layers= name pageItems parent pathItems pathItems= rulerOrigin rulerOrigin= \ + rulerUnits saveAs saveAs= selection selection= swatches swatches= symbols symbols= textFrames textFrames= toString \ + typename views views= width", + ), + ("Layer.", "prototype"), + ("Layer.prototype.", "constructor name toString typename"), + ("PageItems.", "prototype"), + ("PageItems.prototype.", "constructor getByName index length parent removeAll toString typename"), + ("PageItem.", "prototype"), + ( + "PageItem.prototype.", + "artworkKnockout artworkKnockout= blendingMode blendingMode= bringInPerspective bringInPerspective= constructor \ + controlBounds duplicate editable geometricBounds height height= hidden hidden= isIsolated isIsolated= layer layer= \ + left left= locked locked= move name name= note note= opacity opacity= parent pixelAligned pixelAligned= position \ + position= remove resize resize= rotate rotate= selected selected= sliced sliced= tags tags= toString top top= transform \ + transform= translate translate= typename uRL uRL= uuid uuid= visibilityVariable visibilityVariable= visibleBounds \ + width width= wrapInside wrapInside= wrapOffset wrapOffset= wrapped wrapped= zOrder zOrderPosition", + ), + ("CoordinateSystem.", "ARTBOARDCOORDINATESYSTEM DOCUMENTCOORDINATESYSTEM"), + ("DocumentArtboardLayout.", "Column GridByCol GridByRow RLGridByCol RLGridByRow RLRow Row"), + ("DocumentColorSpace.", "CMYK RGB"), + ("DocumentPresetType.", "BasicCMYK BasicRGB Mobile Print Video Web"), + ("DocumentPreviewMode.", "DefaultPreview OverprintPreview PixelPreview"), + ("DocumentRasterResolution.", "HighResolution MediumResolution ScreenResolution"), + ( + "DocumentTransparencyGrid.", + "TransparencyGridBlue TransparencyGridDark TransparencyGridGreen TransparencyGridLight TransparencyGridMedium \ + TransparencyGridNone TransparencyGridOrange TransparencyGridPurple TransparencyGridRed", + ), + ("ElementPlacement.", "INSIDE PLACEAFTER PLACEATBEGINNING PLACEATEND PLACEBEFORE"), + ("RulerUnits.", "Centimeters Inches Millimeters Picas Pixels Points Qs Unknown"), + ("ZOrderMethod.", "BRINGFORWARD BRINGTOFRONT SENDBACKWARD SENDTOBACK"), ]; +/// The classes the host adds with nothing but a prototype and its constructor: the page item types. +const BARE_CLASSES: &str = "BlendItem CompoundPathItem EnvelopeItem GraphItem GroupItem IntertwineItem MeshItem PathItem \ + PlacedDocumentItem PlacedItem RasterItem RepeatItem SymbolItem TextFrame"; + /// The name the checker does not read, which also stands for its members: `vc` is VectorCraft's /// own API, and what `vc.run` does depends on the command it runs. const NOT_CHECKED: &str = "vc"; @@ -93,6 +156,9 @@ const LIST: &str = r#"(function () { var globals = Object.getOwnPropertyNames(g); add(g, ""); for (var i = 0; i < globals.length; i++) { + // A global with a getter, such as `activeDocument`, is not read: it throws with no document open. + var gd = Object.getOwnPropertyDescriptor(g, globals[i]); + if (gd && gd.get) continue; var v = g[globals[i]]; if (v !== null && (typeof v == "object" || typeof v == "function")) { add(v, globals[i] + "."); @@ -120,7 +186,8 @@ fn language_names() -> BTreeSet { fn table_names() -> BTreeSet { let inside = INSIDE.iter().flat_map(|(prefix, names)| names.split_whitespace().map(move |n| format!("{prefix}{n}"))); - OUTSIDE.iter().map(|(n, ..)| n.to_string()).chain(inside).chain([NOT_CHECKED.to_string()]).collect() + let bare = BARE_CLASSES.split_whitespace().flat_map(|c| [c.to_string(), format!("{c}.prototype"), format!("{c}.prototype.constructor")]); + OUTSIDE.iter().map(|(n, ..)| n.to_string()).chain(inside).chain(bare).chain([NOT_CHECKED.to_string()]).collect() } #[test] diff --git a/crates/engine/tests/plugin_place.rs b/crates/engine/tests/plugin_place.rs new file mode 100644 index 0000000000..e5996c7a36 --- /dev/null +++ b/crates/engine/tests/plugin_place.rs @@ -0,0 +1,323 @@ +//! Importer plug-ins whose manifests set `place` (docs/plugins.md › Importers) through `file.place`: +//! which files they are given, the group their objects become in the open document, and what happens +//! when they fail, decline or are canceled. +//! +//! A test binary of its own: installed plug-ins are process-wide, and the unit tests that check the +//! exact list of formats would see these ones. +// Integration tests: unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness). +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use serde_json::{Value, json}; +use vectorcraft_doc::{NodeId, NodeKind}; +use vectorcraft_engine::cmd::fileio; +use vectorcraft_engine::{EngineError, Session}; +use vectorcraft_plugins::wat::{self as tpl, Given}; + +/// An importer's output: a red rectangle "A" from (10, 20) to (110, 70) under a line "B" from +/// (10, 20) to (60, 20), and a warning. +const ART: &str = r#"{"objects":[{"type":"path","name":"A","path":{"subpaths":[{"closed":true,"anchors":[{"p":[10,20]},{"p":[110,20]},{"p":[110,70]},{"p":[10,70]}]}]},"fills":[{"type":"solid","color":{"model":"rgb","r":1,"g":0,"b":0}}]},{"type":"path","name":"B","path":{"subpaths":[{"closed":false,"anchors":[{"p":[10,20]},{"p":[60,20]}]}]}}],"warnings":["1 layer merged"]}"#; + +/// An importer's output: the rectangle "A" of [`ART`] and a guide "G" from (500, 500) to (900, 500). +const GUIDED: &str = r#"{"objects":[{"type":"path","name":"A","path":{"subpaths":[{"closed":true,"anchors":[{"p":[10,20]},{"p":[110,20]},{"p":[110,70]},{"p":[10,70]}]}]},"fills":[{"type":"solid","color":{"model":"rgb","r":1,"g":0,"b":0}}]},{"type":"path","name":"G","guide":true,"path":{"subpaths":[{"closed":false,"anchors":[{"p":[500,500]},{"p":[900,500]}]}]}}]}"#; + +/// The `vc_run` body of an importer that never returns. +const SPINS: &str = "(loop $l (br $l)) (i64.const 0)"; + +/// The manifest of an importer `id` reading `extensions` (a JSON list) that places its files. +fn placing(id: &str, extensions: &str) -> String { + format!(r#"{{"id":"{id}","name":"Test {id}","version":"1","kind":"importer","extensions":{extensions},"place":true}}"#) +} + +/// Installs the plug-in written in WAT `src` → its `plugin.list` entry. +fn install(s: &mut Session, src: &str) -> Value { + let wasm = wat::parse_str(src).unwrap_or_else(|e| panic!("bad test WAT: {e}")); + s.execute("plugin.install", &json!({"dataBase64": vectorcraft_format::base64_encode(&wasm)})).unwrap() +} + +/// `file.place` of a file `name` holding `bytes`, with more params `extra`. +fn place(s: &mut Session, name: &str, bytes: &[u8], extra: Value) -> Result { + let mut p = json!({"name": name, "dataBase64": vectorcraft_format::base64_encode(bytes)}); + if let (Some(p), Some(extra)) = (p.as_object_mut(), extra.as_object()) { + p.extend(extra.clone()); + } + s.execute("file.place", &p) +} + +/// A session with a new document holding one rectangle, selected. +fn with_document() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 400.0, "y": 400.0, "width": 20.0, "height": 10.0})).unwrap(); + s +} + +/// The active document's undo and redo steps, layers and content. +fn state(s: &mut Session) -> (usize, usize, usize, Value) { + let content = s.execute("document.inspect", &json!({})).unwrap(); + let d = s.doc().unwrap(); + (d.history.undo.len(), d.history.redo.len(), d.doc.layers.len(), content) +} + +/// A placed group: its name, the names of its children, and its bounds as `(x0, y0, x1, y1)`. +type Placed = (Option, Vec>, (f64, f64, f64, f64)); + +/// The group `id` of the active document. +fn object(s: &Session, id: u64) -> Placed { + let d = &s.doc().unwrap().doc; + let n = d.node(NodeId(id)).expect("placed"); + let kids = match &n.kind { + NodeKind::Group { children, clip: false } => children.iter().map(|c| c.name.clone()).collect(), + other => panic!("not a group: {other:?}"), + }; + let b = n.geometric_bounds_with(&d.symbol_boxes()).unwrap(); + (n.name.clone(), kids, (b.x0, b.y0, b.x1, b.y1)) +} + +/// A file only a placing importer reads is placed as one group named after the file, its objects in +/// the order the importer returned them and centered on `at`, embedded (also with `link: true`), as +/// one undo step that undo takes back whole. +#[test] +fn a_placing_importer_places_one_group_as_one_undo_step() { + let mut s = with_document(); + let entry = install(&mut s, &tpl::returning(&placing("test.place.one", r#"["tpo"]"#), ART)); + assert_eq!((&entry["place"], &entry["permissions"]), (&json!(true), &json!(["import.read"]))); + let formats = s.execute("document.formats", &json!({})).unwrap(); + let listed = formats["formats"].as_array().unwrap().iter().find(|f| f["id"] == "plugin.test.place.one").expect("listed"); + assert_eq!(listed["place"], json!(true)); + + let before = state(&mut s); + let r = place(&mut s, "Shapes.tpo", b"?", json!({"at": [300, 400], "link": true})).unwrap(); + assert_eq!( + (&r["format"], &r["linked"], &r["warnings"], &r["name"]), + (&json!("plugin.test.place.one"), &json!(false), &json!(["1 layer merged"]), &json!("Shapes.tpo")) + ); + let ids = r["ids"].as_array().unwrap(); + assert_eq!(ids.len(), 1); + let id = ids[0].as_u64().unwrap(); + let (name, kids, bounds) = object(&s, id); + assert_eq!((name.as_deref(), kids), (Some("Shapes.tpo"), vec![Some("A".to_string()), Some("B".to_string())])); + assert_eq!(bounds, (250.0, 375.0, 350.0, 425.0)); + assert_eq!(s.doc().unwrap().selection.objects, [NodeId(id)]); + let after = state(&mut s); + assert_eq!(after.0, before.0 + 1, "one undo step"); + s.execute("edit.undo", &json!({})).unwrap(); + let undone = state(&mut s); + assert_eq!((undone.0, undone.1, undone.2), (before.0, 1, before.2)); + assert_eq!((&undone.3["layers"], &undone.3["history"]), (&before.3["layers"], &before.3["history"])); +} + +/// `rect` fits the group in with its aspect, Template puts it on a new template layer, Replace swaps +/// the selected object at its center and stacking place, and `file.place.info` and the place cursor +/// read the file the same way. +#[test] +fn placing_follows_rect_template_and_replace() { + let mut s = with_document(); + install(&mut s, &tpl::returning(&placing("test.place.ways", r#"["tpw"]"#), ART)); + let r = place(&mut s, "a.tpw", b"?", json!({"rect": [0, 0, 50, 50]})).unwrap(); + assert_eq!(object(&s, r["ids"][0].as_u64().unwrap()).2, (0.0, 12.5, 50.0, 37.5)); + + let layers = s.doc().unwrap().doc.layers.len(); + let r = place(&mut s, "b.tpw", b"?", json!({"template": true})).unwrap(); + let d = &s.doc().unwrap().doc; + assert_eq!(d.layers.len(), layers + 1); + let layer = d.layer_of(NodeId(r["ids"][0].as_u64().unwrap())).and_then(|l| d.node(l)).unwrap(); + assert!(matches!(layer.kind, NodeKind::Layer { template: true, .. }) && layer.locked); + + let rect = s.execute("shape.rectangle", &json!({"x": 400.0, "y": 100.0, "width": 20.0, "height": 10.0})).unwrap(); + let old = NodeId(rect["id"].as_u64().unwrap()); + let (parent, index, _) = s.doc().unwrap().doc.position(old).unwrap(); + let r = place(&mut s, "c.tpw", b"?", json!({"replace": true})).unwrap(); + let id = NodeId(r["ids"][0].as_u64().unwrap()); + let d = &s.doc().unwrap().doc; + assert!(d.node(old).is_none()); + assert_eq!(d.position(id).map(|(p, i, _)| (p, i)), Some((parent, index))); + assert_eq!(object(&s, id.0).2, (360.0, 80.0, 460.0, 130.0)); + + let info = s.execute("file.place.info", &json!({"name": "d.tpw", "dataBase64": vectorcraft_format::base64_encode(b"?")})).unwrap(); + assert_eq!((&info["format"], &info["width"], &info["height"]), (&json!("plugin.test.place.ways"), &json!(100.0), &json!(50.0))); + let q = s.execute("file.place.queue", &json!({"files": [{"name": "e.tpw", "dataBase64": vectorcraft_format::base64_encode(b"?")}]})).unwrap(); + assert_eq!((&q["count"], &q["files"][0]["format"], &q["skipped"]), (&json!(1), &json!("plugin.test.place.ways"), &json!([]))); +} + +/// Guides the importer returns are left out of the placed group, and its box is that of the art +/// left, so a guide beside the art doesn't move it; output of guides alone places nothing. +#[test] +fn guides_are_left_out_of_what_is_placed() { + let mut s = with_document(); + install(&mut s, &tpl::returning(&placing("test.place.guided", r#"["tpg"]"#), GUIDED)); + let r = place(&mut s, "a.tpg", b"?", json!({"at": [300, 400]})).unwrap(); + let (_, kids, bounds) = object(&s, r["ids"][0].as_u64().unwrap()); + assert_eq!((kids, bounds), (vec![Some("A".to_string())], (250.0, 375.0, 350.0, 425.0))); + let info = s.execute("file.place.info", &json!({"name": "b.tpg", "dataBase64": vectorcraft_format::base64_encode(b"?")})).unwrap(); + assert_eq!((&info["width"], &info["height"]), (&json!(100.0), &json!(50.0))); + + let guides = r#"{"objects":[{"type":"path","guide":true,"path":{"subpaths":[{"closed":false,"anchors":[{"p":[0,0]},{"p":[100,0]}]}]}}]}"#; + install(&mut s, &tpl::returning(&placing("test.place.guides", r#"["tpq"]"#), guides)); + let before = state(&mut s); + let e = place(&mut s, "c.tpq", b"?", json!({})).unwrap_err().to_string(); + assert!(e.contains("`c.tpq` has no art to place"), "{e}"); + assert_eq!(state(&mut s), before); +} + +/// The importer is told it places the file (`_context.mode`), with the file's extension and name, +/// and is given its parameters. +#[test] +fn the_importer_is_told_it_places() { + let mut s = with_document(); + let params = r#"{"density":{"type":"number","min":0,"max":10,"default":4}}"#; + let manifest = placing("test.place.mode", r#"["tpm"]"#).replace(r#""place":true"#, &format!(r#""place":true,"params":{params}"#)); + for (i, needle) in [r#""mode":"place""#, r#""extension":"tpm""#, r#""name":"Shapes""#, r#""density":10.0"#].into_iter().enumerate() { + // ART when the parameters hold the needle; the file, which isn't JSON, otherwise. + let wasm = wat::parse_str(tpl::when_given(&manifest, Given::Params, needle, ART)).unwrap(); + s.execute("plugin.install", &json!({"dataBase64": vectorcraft_format::base64_encode(&wasm), "replace": i > 0})).unwrap(); + let r = place(&mut s, "Shapes.tpm", b"not json", json!({"params": {"density": 12}})); + assert_eq!(r.map(|r| r["format"].clone()).map_err(|e| e.to_string()), Ok(json!("plugin.test.place.mode")), "{needle}"); + } + let before = state(&mut s); + let e = place(&mut s, "Shapes.tpm", b"", json!({"params": {"density": "lots"}})).unwrap_err(); + assert!(matches!(e, EngineError::BadParams { .. }), "{e}"); + assert_eq!(state(&mut s), before); +} + +/// Built-in formats keep their files: an importer that lists `svg` places an `.svg` only when +/// `importer` names it. An importer whose manifest doesn't set `place` opens its files and places +/// none: File › Place doesn't read them, and naming it is an error, as is naming it for a file of an +/// extension it doesn't list. +#[test] +fn built_in_formats_and_open_only_importers_keep_their_files() { + let mut s = with_document(); + install(&mut s, &tpl::returning(&placing("test.place.svg", r#"["tps","svg"]"#), ART)); + install(&mut s, &tpl::returning(&tpl::importer("test.place.openonly", r#"["tpx"]"#, "{}"), ART)); + let svg = br#""#; + assert_eq!(place(&mut s, "a.svg", svg, json!({})).unwrap()["format"], "svg"); + assert_eq!(place(&mut s, "b.svg", svg, json!({"importer": "plugin.test.place.svg"})).unwrap()["format"], "plugin.test.place.svg"); + assert_eq!(place(&mut s, "c.tps", svg, json!({})).unwrap()["format"], "svg", "an SVG named as the importer's file"); + + let before = state(&mut s); + let e = place(&mut s, "d.tpx", b"?", json!({})).unwrap_err().to_string(); + assert!(e.contains("not a format VectorCraft reads"), "{e}"); + let e = place(&mut s, "d.tpx", b"?", json!({"importer": "plugin.test.place.openonly"})).unwrap_err().to_string(); + assert!(e.contains("doesn't place them") && e.contains("Test test.place.openonly"), "{e}"); + let e = place(&mut s, "d.tpx", b"?", json!({"importer": "plugin.test.place.svg"})).unwrap_err().to_string(); + assert!(e.contains(".tps, .svg") && e.contains("d.tpx"), "{e}"); + let e = place(&mut s, "d.tps", b"?", json!({"importer": 3})).unwrap_err().to_string(); + assert!(e.contains("`importer` must be"), "{e}"); + assert_eq!(state(&mut s), before); + // The open-only importer still opens its files. + let r = s.execute("document.open", &json!({"name": "d.tpx", "dataBase64": vectorcraft_format::base64_encode(b"?")})).unwrap(); + assert_eq!(r["format"], "plugin.test.place.openonly"); +} + +/// File › Place's dialog lists a placing importer's extensions, under its name and in "All placeable +/// files", and not an open-only importer's; relinking an image keeps the built-in filters. A file only +/// a placing importer reads is dropped onto the canvas to be placed rather than opened. +#[test] +fn the_place_dialog_lists_placing_importers() { + let mut s = Session::new(); + install(&mut s, &tpl::returning(&placing("test.place.list", r#"["tpl","svg"]"#), ART)); + install(&mut s, &tpl::returning(&tpl::importer("test.place.listopen", r#"["tpy"]"#, "{}"), ART)); + let filters: Vec<_> = fileio::place_dialog_filters().collect(); + assert!(filters.contains(&("Test test.place.list", &["tpl"][..])), "{filters:?}"); + let all = filters.first().unwrap(); + assert_eq!(all.0, "All placeable files"); + assert!(all.1.contains(&"tpl") && !all.1.contains(&"tpy"), "{all:?}"); + assert_eq!(all.1.iter().filter(|e| **e == "svg").count(), 1); + assert!(!filters.iter().any(|(_, exts)| exts.contains(&"tpy"))); + assert!(!fileio::place_filters().any(|(_, exts)| exts.contains(&"tpl"))); + assert!(fileio::places_with_importer("x.TPL") && !fileio::opens_with_importer("x.tpl")); + assert!(!fileio::places_with_importer("x.tpy") && fileio::opens_with_importer("x.tpy")); + assert!(!fileio::places_with_importer("x.svg")); +} + +/// Nothing is placed, and the document keeps its content and undo steps, when the importer declines, +/// returns output that doesn't pass the checks, traps or is canceled, or when the file is larger +/// than an importer reads: that file is refused from its size, before it is read. +#[test] +fn failures_place_nothing() { + let mut s = with_document(); + let far = r#"{"objects":[{"type":"path","path":{"subpaths":[{"closed":false,"anchors":[{"p":[0,0]},{"p":[9000000,0]}]}]}}]}"#; + let cases = [ + ("test.place.fail.declines", r#"{"error":"Not a drawing."}"#, "Not a drawing."), + ("test.place.fail.notjson", "not json", "JSON"), + ("test.place.fail.empty", r#"{"objects":[]}"#, "the importer returned no objects"), + ("test.place.fail.key", r#"{"objects":[],"layers":[]}"#, "not `layers`"), + ("test.place.fail.far", far, "4000000"), + ( + "test.place.fail.point", + r#"{"objects":[{"type":"path","path":{"subpaths":[{"closed":false,"anchors":[{"p":[5,5]}]}]}}]}"#, + "no art to place", + ), + ]; + for (id, output, _) in cases { + install(&mut s, &tpl::returning(&placing(id, r#"["tpf"]"#), output)); + } + install(&mut s, &tpl::module(&placing("test.place.fail.traps", r#"["tpf"]"#), "(unreachable)", "", 1)); + install(&mut s, &tpl::module(&placing("test.place.fail.spins", r#"["tpf"]"#), SPINS, "", 1)); + let before = state(&mut s); + for (id, _, why) in cases { + let e = place(&mut s, "x.tpf", b"?", json!({"importer": format!("plugin.{id}")})).unwrap_err().to_string(); + assert!(e.contains(why) && e.contains("x.tpf"), "{id}: {e}"); + assert_eq!(state(&mut s), before, "{id}"); + } + assert!(place(&mut s, "x.tpf", b"?", json!({"importer": "plugin.test.place.fail.traps"})).is_err()); + assert_eq!(state(&mut s), before, "trapped"); + let token = vectorcraft_doc::cancel::CancelToken::new(); + token.cancel(); + let r = vectorcraft_doc::cancel::scope(&token, None, || place(&mut s, "x.tpf", b"?", json!({"importer": "plugin.test.place.fail.spins"}))); + assert!(matches!(r, Err(EngineError::Cancelled)), "{r:?}"); + assert_eq!(state(&mut s), before, "canceled"); + + // A file one byte past the limit, without data in it: the size alone refuses it. + let dir = std::env::temp_dir().join(format!("vc-plugin-place-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let big = dir.join("big.tpf"); + std::fs::File::create(&big).unwrap().set_len(vectorcraft_plugins::import::MAX_INPUT_BYTES as u64 + 1).unwrap(); + let e = s.execute("file.place", &json!({"path": big.to_string_lossy(), "importer": "plugin.test.place.fail.declines"})).unwrap_err().to_string(); + assert!(e.contains("can't place `big.tpf`") && e.contains("larger than"), "{e}"); + let e = s.execute("file.place", &json!({"path": big.to_string_lossy()})).unwrap_err().to_string(); + assert!(e.contains("larger than"), "by its extension: {e}"); + assert_eq!(state(&mut s), before, "too large"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A file past the limit, placed with `importer` named, is refused from its size before any of it +/// is read: here the file can't be read at all, and the error is still the size. +#[test] +fn a_named_importer_refuses_a_large_file_before_reading_it() { + let mut s = with_document(); + install(&mut s, &tpl::returning(&placing("test.place.unread", r#"["tpu"]"#), ART)); + let dir = std::env::temp_dir().join(format!("vc-plugin-place-unread-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let big = dir.join("big.tpu"); + std::fs::File::create(&big).unwrap().set_len(vectorcraft_plugins::import::MAX_INPUT_BYTES as u64 + 1).unwrap(); + // Unix: no read permission. Windows: another handle that shares nothing. + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&big, std::fs::Permissions::from_mode(0o000)).unwrap(); + } + #[cfg(windows)] + let _held = { + use std::os::windows::fs::OpenOptionsExt; + std::fs::OpenOptions::new().read(true).share_mode(0).open(&big).unwrap() + }; + // A user that reads the file anyway (root) can't show the order of the checks. + if std::fs::File::open(&big).is_ok() { + let _ = std::fs::remove_dir_all(&dir); + return; + } + let before = state(&mut s); + let e = s.execute("file.place", &json!({"path": big.to_string_lossy(), "importer": "plugin.test.place.unread"})).unwrap_err().to_string(); + assert!(e.contains("can't place `big.tpu`") && e.contains("larger than"), "{e}"); + assert_eq!(state(&mut s), before); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let _ = std::fs::set_permissions(&big, std::fs::Permissions::from_mode(0o644)); + } + #[cfg(windows)] + drop(_held); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/engine/tests/script_corpus.rs b/crates/engine/tests/script_corpus.rs index 870bfbabc2..c2ca9a38f6 100644 --- a/crates/engine/tests/script_corpus.rs +++ b/crates/engine/tests/script_corpus.rs @@ -89,9 +89,9 @@ fn a_script_that_ends_well_passes() { fn a_failure_gives_its_kind_and_place() { let r = result(&mut session(), &source("var a = 1;\nvar = ;")); assert_eq!((r["ok"].clone(), r["kind"].clone(), r["line"].clone()), (json!(false), json!("syntax"), json!(2))); - let r = result(&mut session(), &source("var d = app.activeDocument;")); + let r = result(&mut session(), &source("var d = undefinedHost.activeDocument;")); assert_eq!(r["kind"], "thrown"); - assert!(r["message"].as_str().unwrap().starts_with("ReferenceError: app"), "{r}"); + assert!(r["message"].as_str().unwrap().starts_with("ReferenceError: undefinedHost"), "{r}"); let r = result(&mut session(), &source("while (true) {}")); assert_eq!(r["kind"], "limit"); assert!(r["fuelUsed"].as_u64().unwrap() <= FUEL); diff --git a/crates/eps/src/ai_editing/writer.rs b/crates/eps/src/ai_editing/writer.rs index 8065b8cbb5..d95b1279c2 100644 --- a/crates/eps/src/ai_editing/writer.rs +++ b/crates/eps/src/ai_editing/writer.rs @@ -69,7 +69,7 @@ pub(super) const CLIP_PAINT: &str = "the fills and strokes of clipping paths tha pub(super) const CLIP_PAINT_MASKS: &str = "the opacity masks of clipping paths whose fills and strokes are written as paths of their own stay on the clipping path, not on those paths, in the editing data for other apps"; pub(super) const LIVE: &str = "repeats, placed documents, intertwines and distorted images are written as their art in the editing data for other apps"; -pub(super) const DEEP_DISTORTED: &str = "images changed by Perspective Distort or Free Distort more than 8 deep in opacity masks, symbols, live objects and pattern tiles are written as the nearest parallelogram in the editing data for other apps"; +pub(super) const DEEP_DISTORTED: &str = "images changed by Perspective Distort or Free Distort nested 8 deep in opacity masks, symbols, live objects and pattern tiles are written as the nearest parallelogram in the editing data for other apps"; pub(super) const GRAPHS: &str = "graphs are written as their art, without their data or settings, in the editing data for other apps"; pub(super) const STROKES: &str = "strokes a plain line can't draw (inside or outside the path, variable width, dots, dashes fitted to corners, gradients, patterns, arrowheads) are written as filled outlines, and brushed strokes as their brush's art, in the editing data for other apps"; pub(super) const ITEM_TRANSPARENCY: &str = diff --git a/crates/eps/src/legacy_ai.rs b/crates/eps/src/legacy_ai.rs index d1ae8ef9ab..8fbfcf3e83 100644 --- a/crates/eps/src/legacy_ai.rs +++ b/crates/eps/src/legacy_ai.rs @@ -130,7 +130,7 @@ const STROKES: &str = const IMAGE_ALPHA: &str = "transparent image pixels are written over white"; const LIVE: &str = "symbols, blends, envelopes, meshes, repeats, placed documents, intertwines and distorted images are written as their art"; const DEEP_DISTORTED: &str = - "images changed by Perspective Distort or Free Distort more than 8 deep in symbols and live objects are written as the nearest parallelogram"; + "images changed by Perspective Distort or Free Distort nested 8 deep in symbols and live objects are written as the nearest parallelogram"; const GRAPHS: &str = "graphs are written as their art, without their data or settings"; /// The warning for an image left out because it can't be decoded: the note raster exports give /// (`vectorcraft-engine`'s `rasterfx::undecoded_warning`). diff --git a/crates/js/src/builtins.rs b/crates/js/src/builtins.rs index 49eeebf9f4..31414bb517 100644 --- a/crates/js/src/builtins.rs +++ b/crates/js/src/builtins.rs @@ -293,7 +293,7 @@ fn get_at(interp: &mut Interp, o: ObjId, k: f64) -> JsResult { } fn has_at(interp: &mut Interp, o: ObjId, k: f64) -> JsResult { - interp.has_property(o, &key_of(k)) + interp.has_property_indexed(o, &key_of(k)) } /// The estimated bytes a new element adds. @@ -559,7 +559,15 @@ fn object_value_of(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> Js fn has_own_property(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { let k = interp.to_prop_key(&arg(args, 0))?; let o = interp.to_object(&this)?; - Ok(Value::Bool(interp.get_own_pk(o, &k)?.is_some())) + Ok(Value::Bool(interp.get_own_pk(o, &k)?.is_some() || is_host_member_pk(interp, o, &k)?)) +} + +/// [`Interp::is_host_member`] for either kind of key: a Symbol never names a host member. +fn is_host_member_pk(interp: &Interp, o: ObjId, k: &crate::symbol::PropKey) -> JsResult { + match k { + crate::symbol::PropKey::Str(name) => interp.is_host_member(o, name), + crate::symbol::PropKey::Sym(_) => Ok(false), + } } fn is_prototype_of(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { @@ -578,7 +586,7 @@ fn is_prototype_of(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> fn property_is_enumerable(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { let k = interp.to_prop_key(&arg(args, 0))?; let o = interp.to_object(&this)?; - Ok(Value::Bool(interp.get_own_pk(o, &k)?.is_some_and(|p| p.enumerable()))) + Ok(Value::Bool(interp.get_own_pk(o, &k)?.is_some_and(|p| p.enumerable()) || is_host_member_pk(interp, o, &k)?)) } // ---- Function ---- diff --git a/crates/js/src/builtins/json.rs b/crates/js/src/builtins/json.rs index e01a47b085..2b022bc858 100644 --- a/crates/js/src/builtins/json.rs +++ b/crates/js/src/builtins/json.rs @@ -538,7 +538,7 @@ fn resolve_rooted(interp: &mut Interp, settings: &Settings, holder: ObjId, k: &K keep(interp, &v); let name = Value::String(Str::from_rc(k.clone())); if let Value::Object(o) = v { - let to_json = interp.get_from(o, &key("toJSON"), &v)?; + let to_json = interp.get_property_only(o, &key("toJSON"), &v)?; if interp.is_callable(&to_json) { v = interp.call(&to_json, &v, std::slice::from_ref(&name))?; keep(interp, &v); diff --git a/crates/js/src/heap.rs b/crates/js/src/heap.rs index af98f259df..bddab84fd6 100644 --- a/crates/js/src/heap.rs +++ b/crates/js/src/heap.rs @@ -264,6 +264,8 @@ pub(crate) enum Class { }, /// A `.( )` filter in progress. XmlFilter(Box), + /// An object of a class a host defined ([`crate::host_classes`]). + Host(crate::host_classes::HostObj), /// A `UnitValue` object and its measurement ([`crate::unit_value`]). UnitValue(Box), } @@ -332,7 +334,7 @@ impl Class { Class::XmlFilter(_) => "Object", Class::Math => "Math", Class::Json => "JSON", - Class::Ordinary | Class::ForIn(_) | Class::Symbol(_) | Class::Iterator(_) | Class::IterRecord(_) => "Object", + Class::Ordinary | Class::ForIn(_) | Class::Host(_) | Class::Symbol(_) | Class::Iterator(_) | Class::IterRecord(_) => "Object", Class::Array { .. } => "Array", Class::Function(_) => "Function", Class::Error(_) => "Error", diff --git a/crates/js/src/host.rs b/crates/js/src/host.rs index 1f0bcdd0c0..4e0275441a 100644 --- a/crates/js/src/host.rs +++ b/crates/js/src/host.rs @@ -113,6 +113,10 @@ pub(crate) enum ArgRead { Each(Rc<[Arg]>), /// None: the function is given the [`CallSite`] of the code that calls it, as three numbers. Site, + /// A member of a host class ([`crate::host_classes`]): `this` first, then each argument as + /// [`Data`], objects of host classes in them as [`crate::host_ref`] gives them; the objects of + /// host classes in the result are made from theirs. + Hosted, } /// A member of an object the host adds to the global environment. @@ -188,6 +192,9 @@ struct Reading { ancestors: Vec, path: Vec, function: Rc, + /// Objects of host classes are read as [`crate::host_ref`] gives them, and a plain object + /// that has [`crate::HOST_REF_KEY`] is refused. + hosted: bool, } impl Reading { @@ -258,6 +265,10 @@ impl Interp { return Err(self.data_error(r, ErrorType::Range, "is nested too deep")); } let shape = match &self.object(id)?.class { + Class::Host(_) if r.hosted => { + return self.host_ref_of(id)?.ok_or_else(|| Abrupt::Internal("host object without a class".into())); + } + Class::Host(_) => return Err(self.data_error(r, ErrorType::Type, "is an object of a host class, not plain data")), Class::Array { length, .. } => Shape::Array(*length), Class::Ordinary => { let o = self.object(id)?; @@ -313,6 +324,9 @@ impl Interp { self.use_fuel()?; self.charge_reading(r, k.len().saturating_mul(3).saturating_add(8))?; let name = String::from_utf16_lossy(&k); + if r.hosted && name == crate::HOST_REF_KEY { + return Err(self.data_error(r, ErrorType::Type, "is not plain data")); + } r.path.push(Step::Name(k)); let item = match prop { // A property holding `undefined` reads as one left out. @@ -348,6 +362,9 @@ impl Interp { Data::Array(items) => { self.write_container(items.into_iter().enumerate().map(|(i, d)| (Slot::Index(i), d)).collect(), true, depth, frozen)? } + Data::Object(items) if self.write_hosted && matches!(items.as_slice(), [(k, _)] if k == crate::HOST_REF_KEY) => { + self.write_host_ref(&Data::Object(items))? + } Data::Object(items) => self.write_container(items.into_iter().map(|(k, d)| (Slot::Name(k), d)).collect(), false, depth, frozen)?, }) } @@ -387,20 +404,32 @@ impl Interp { /// Calls host function `f`: reads its arguments as `how` says, runs it, and gives its result to /// the script. - pub(crate) fn call_data(&mut self, f: &crate::heap::DataFn, name: &Rc, args: &[Value], how: &ArgRead) -> JsResult { + pub(crate) fn call_data(&mut self, f: &crate::heap::DataFn, name: &Rc, this: &Value, args: &[Value], how: &ArgRead) -> JsResult { let data = match how { ArgRead::Site => site_data(self.call_site()), + ArgRead::Hosted => { + let this = match this { + Value::Object(o) => self.host_ref_of(*o)?.unwrap_or(Data::Undefined), + _ => Data::Undefined, + }; + let mut data = vec![this]; + data.extend(self.read_args(name, args, how)?); + data + } _ => self.read_args(name, args, how)?, }; - // Only the script's own code, in a run that can pause, can wait for a result. - let can_wait = self.in_slice && self.reentry == 0; + // Only the script's own code, in a run that can pause, can wait for a result, and a host + // class's constructor called with `new` cannot. + let can_wait = self.in_slice && self.reentry == 0 && !self.constructing; self.can_wait.set(can_wait); let result = f(data); self.can_wait.set(false); match result { + Ok(d) if matches!(how, ArgRead::Hosted) => self.write_hosted(d), Ok(d) => self.write_data(d, 0, matches!(how, ArgRead::Frozen)), Err(HostError::Wait) if can_wait => { self.waiting = true; + self.waiting_hosted = matches!(how, ArgRead::Hosted); self.pause.set(true); Ok(Value::Undefined) } @@ -478,7 +507,15 @@ impl Interp { /// The arguments of host function `name` as [`Data`], read as `how` says. fn read_args(&mut self, name: &Rc, args: &[Value], how: &ArgRead) -> JsResult> { - let mut reading = Reading { limits: self.data_limits, bytes: 0, entries: 0, ancestors: Vec::new(), path: Vec::new(), function: name.clone() }; + let mut reading = Reading { + limits: self.data_limits, + bytes: 0, + entries: 0, + ancestors: Vec::new(), + path: Vec::new(), + function: name.clone(), + hosted: matches!(how, ArgRead::Hosted), + }; let args = match how { ArgRead::Each(list) => args.get(..list.len().min(args.len())).unwrap_or(args), _ => args, @@ -486,14 +523,14 @@ impl Interp { let mut data = Vec::with_capacity(args.len()); // A conversion can run the script's own `toString`, which may collect garbage. let mark = self.temp_roots.len(); - if !matches!(how, ArgRead::Data | ArgRead::Frozen) { + if !matches!(how, ArgRead::Data | ArgRead::Frozen | ArgRead::Hosted) { self.temp_roots.extend(args.iter().cloned()); } let mut read = Ok(()); for (i, a) in args.iter().enumerate() { reading.path.push(Step::Index(u32::try_from(i).unwrap_or(u32::MAX))); let d = match how { - ArgRead::Data | ArgRead::Frozen | ArgRead::Site => self.read_data(a, &mut reading), + ArgRead::Data | ArgRead::Frozen | ArgRead::Site | ArgRead::Hosted => self.read_data(a, &mut reading), ArgRead::Text => self.read_text(a, &mut reading), ArgRead::Each(list) => match list.get(i) { Some(Arg::TextOrUndefined) if matches!(a, Value::Undefined) => Ok(Data::Undefined), @@ -518,7 +555,7 @@ impl Interp { /// What host error `e` throws, or the limit it ends the run with. A function that waits /// ([`HostError::Wait`]) where its caller does not handle the wait ends the run with an internal /// error. - fn host_error(&mut self, e: HostError) -> JsResult { + pub(crate) fn host_error(&mut self, e: HostError) -> JsResult { match e { HostError::Wait => Ok(Abrupt::Internal("a host function waited for its result where the run cannot pause".into())), HostError::Abort(message) => { diff --git a/crates/js/src/host_classes.rs b/crates/js/src/host_classes.rs new file mode 100644 index 0000000000..206f781ef3 --- /dev/null +++ b/crates/js/src/host_classes.rs @@ -0,0 +1,359 @@ +//! Classes a host defines ([`crate::Realm::define_host_classes`]): objects that stand for something +//! the host keeps, such as an open document or an object in one, with members the host's functions +//! answer. +//! +//! Each object holds the name of its class and a handle, a list of numbers the host chose, in an +//! internal slot that a script cannot read, write or copy onto another object. A host function sees +//! such an object as the [`Data`] that [`host_ref`] makes, and gives one back the same way; a plain +//! object a script made that carries [`HOST_REF_KEY`] is refused, so a script cannot make an object +//! of a host class from its own data. A class's prototype and constructor are frozen. While a +//! script holds the object for a class and handle, each read of that class and handle gives the +//! same object. Classes that descend from the same class without a parent share their objects: a +//! read of another of them with the same handle gives the object the script holds, now of the +//! class that read names. +//! +//! Every member function gets the object it is called on (`this`) as its first argument, or +//! `undefined` when `this` is not an object of a host class, followed by the call's arguments; a +//! setter gets `this` and the value assigned. A class with an indexer answers `object[i]` for each +//! array index `i` with it, called with `this` and the index as a number. Other names are looked up +//! as usual, and a name that the object and its prototypes lack goes to the indexer as a string (as +//! a number when it is the text of one, such as `-1`), so the indexer may throw for a name nothing +//! has. Names the engine looks up itself, such as `toJSON` in `JSON.stringify`, do not go to the +//! indexer. Assigning to such a name reads it with the indexer first, so the assignment throws what +//! the read throws; otherwise the value is not kept. `k in object` calls the indexer with `true` as +//! a third argument, and is true when it gives a value other than `undefined`. +//! +//! `hasOwnProperty` and `propertyIsEnumerable` are true on an object of a host class for each +//! member of its class and of the classes it descends from, apart from the members that are not +//! available yet ([`HostMember::Unavailable`]). `for`-`in` lists the properties among those members, +//! and not the methods. `Object.keys`, `Object.getOwnPropertyNames` and +//! `Object.getOwnPropertyDescriptor` do not report the members. + +use std::collections::HashSet; +use std::rc::Rc; + +use crate::heap::{CONFIGURABLE, Class, ENUMERABLE, Func, Key, ObjId, Object, Prop, key}; +use crate::host::ArgRead; +use crate::interp::{Abrupt, ErrorType, Interp, JsResult}; +use crate::value::Value; +use crate::{Data, HostError, HostFunction}; + +/// The one key of the [`Data`] object that stands for an object of a host class ([`host_ref`]). +pub const HOST_REF_KEY: &str = "\u{0}hostRef"; + +/// A member of a host class's prototype. +#[derive(Clone)] +pub enum HostMember { + /// A read-only property: the function gives its value each time it is read. + Get(HostFunction), + /// A property the function `get` reads and `set` assigns. + Property { get: HostFunction, set: HostFunction }, + /// A method. + Method(HostFunction), + /// A property the class lists that is not available yet: the function answers both a read and + /// an assignment, with an error. It is not reported as the object's own, and `for`-`in` skips it. + Unavailable(HostFunction), +} + +/// A class [`crate::Realm::define_host_classes`] adds. +#[derive(Clone)] +pub struct HostClass { + pub name: String, + /// A class defined before this one, or in the same call before it, whose prototype this + /// class's prototype inherits from. + pub parent: Option, + pub members: Vec<(String, HostMember)>, + /// What `object[i]` gives for an array index `i`. + pub index: Option, + /// What `new Name(...)` and `Name(...)` give; without it both throw a `TypeError`. + pub construct: Option, +} + +/// The internal slot of an object of a host class: its class, as an index into the realm's +/// classes, and its handle. +#[derive(Clone, Debug)] +pub(crate) struct HostObj { + pub(crate) class: u32, + pub(crate) handle: Rc<[f64]>, +} + +/// A class the realm has. +#[derive(Clone)] +pub(crate) struct Entry { + name: Rc, + proto: ObjId, + ctor: ObjId, + index: Option, + /// The class without a parent this class descends from (itself for such a class), as an index + /// into the realm's classes. + family: u32, + /// The class this class's prototype inherits from, as an index into the realm's classes. + parent: Option, + /// The names of the members `hasOwnProperty` reports: every member but the unavailable ones. + own: Rc>, +} + +impl Entry { + pub(crate) fn objects(&self) -> [ObjId; 2] { + [self.proto, self.ctor] + } +} + +/// A family of classes ([`Entry::family`]) and the bits of a handle. +type MadeKey = (u32, Box<[u64]>); + +/// The object made for each family of classes and handle ([`Interp::host_objects`]). +pub(crate) type Made = std::collections::HashMap; + +/// Whether `id` is still the object made for `key`, and not a freed cell or another object that +/// was given its cell. +fn is_made(heap: &crate::heap::Heap, classes: &[Entry], id: ObjId, key: &MadeKey) -> bool { + heap.object(id).is_some_and(|o| match &o.class { + Class::Host(h) => { + classes.get(h.class as usize).is_some_and(|e| e.family == key.0) && h.handle.iter().map(|n| n.to_bits()).eq(key.1.iter().copied()) + } + _ => false, + }) +} + +/// Drops the entries of `made` whose objects the last collection freed. +pub(crate) fn forget_collected(made: &mut Made, heap: &crate::heap::Heap, classes: &[Entry]) { + made.retain(|key, id| is_made(heap, classes, *id, key)); +} + +/// The [`Data`] that stands for the object of host class `class` with `handle`. +pub fn host_ref(class: &str, handle: &[f64]) -> Data { + let mut list = Vec::with_capacity(handle.len() + 1); + list.push(Data::String(class.to_string())); + list.extend(handle.iter().map(|n| Data::Number(*n))); + Data::Object(vec![(HOST_REF_KEY.to_string(), Data::Array(list))]) +} + +/// The class and handle of the object `d` stands for, when it is one [`host_ref`] made. +pub fn host_ref_parts(d: &Data) -> Option<(&str, Vec)> { + let Data::Object(items) = d else { return None }; + let [(k, Data::Array(list))] = items.as_slice() else { return None }; + if k != HOST_REF_KEY { + return None; + } + let (Data::String(class), rest) = list.split_first()? else { return None }; + let handle = rest.iter().map(|d| if let Data::Number(n) = d { Some(*n) } else { None }).collect::>>()?; + Some((class.as_str(), handle)) +} + +impl Interp { + /// Whether `k` is a member that `hasOwnProperty` reports on `id`: `id` is an object of a host + /// class, and `k` names an available member of that class or of a class it descends from. + pub(crate) fn is_host_member(&self, id: ObjId, k: &[u16]) -> JsResult { + let Class::Host(h) = &self.object(id)?.class else { return Ok(false) }; + let mut class = Some(h.class); + while let Some(c) = class { + let Some(e) = self.host_classes.get(c as usize) else { return Err(Abrupt::Internal("host class out of range".into())) }; + if e.own.contains(k) { + return Ok(true); + } + class = e.parent; + } + Ok(false) + } + + /// The [`Data`] for the object of a host class `id`, or `None` when it is not one. + pub(crate) fn host_ref_of(&self, id: ObjId) -> JsResult> { + let Class::Host(h) = &self.object(id)?.class else { return Ok(None) }; + let name = + self.host_classes.get(h.class as usize).map(|e| e.name.clone()).ok_or_else(|| Abrupt::Internal("host class out of range".into()))?; + Ok(Some(host_ref(&name, &h.handle))) + } + + /// The object of a host class that `d`, which a host function gave, stands for. + pub(crate) fn write_host_ref(&mut self, d: &Data) -> JsResult { + let Some((name, handle)) = host_ref_parts(d) else { + return Err(self.throw(ErrorType::Type, "a host value names an object of a host class wrongly")); + }; + let Some((class, entry)) = self.host_classes.iter().enumerate().find(|(_, e)| &*e.name == name) else { + return Err(self.throw(ErrorType::Type, &format!("a host value names the unknown class {name}"))); + }; + let (proto, family) = (entry.proto, entry.family); + let class = u32::try_from(class).unwrap_or(u32::MAX); + let made = (family, handle.iter().map(|n| n.to_bits()).collect::>()); + if let Some(&id) = self.host_objects.get(&made) + && is_made(&self.heap, &self.host_classes, id, &made) + { + // An object of another class of the family becomes one of `class`. + let o = self.object_mut(id)?; + if let Class::Host(h) = &mut o.class + && h.class != class + { + h.class = class; + o.proto = Some(proto); + } + return Ok(Value::Object(id)); + } + self.reserve_heap(crate::heap::OBJECT_BYTES)?; + let mut o = Object::new(Class::Host(HostObj { class, handle: handle.into() }), Some(proto)); + o.extensible = false; + let id = self.heap.alloc_object(o); + self.host_objects.insert(made, id); + Ok(Value::Object(id)) + } + + /// Whether `id` is the constructor of a host class (its other functions are not constructors). + pub(crate) fn is_host_constructor(&self, id: ObjId) -> bool { + self.host_classes.iter().any(|e| e.ctor == id) + } + + /// The indexer of the host class of `id`, when it is an object of a host class that has one. + pub(crate) fn host_indexer(&self, id: ObjId) -> JsResult> { + let Class::Host(h) = &self.object(id)?.class else { return Ok(None) }; + Ok(self.host_classes.get(h.class as usize).and_then(|e| e.index.clone())) + } + + /// `object[k]` of an object of a host class, which its class's indexer `f` answers: `k` is an + /// array index as a number, or a name as a string. With `probe`, for `k in object`, the indexer + /// gets `true` as a third argument. + pub(crate) fn host_index(&mut self, f: &HostFunction, id: ObjId, k: Data, probe: bool) -> JsResult { + self.use_fuel()?; + let Some(this) = self.host_ref_of(id)? else { return Ok(Value::Undefined) }; + let mut args = vec![this, k]; + if probe { + args.push(Data::Bool(true)); + } + match f(args) { + Ok(d) => self.write_hosted(d), + Err(HostError::Wait) => Err(Abrupt::Internal("a host class's indexer waited for its result".into())), + Err(e) => Err(self.host_error(e)?), + } + } + + /// The key an indexer gets for `k`: a number for an array index and for any other key that is + /// the text of a number (`-1`, `1.5`, `NaN`), otherwise the name. + pub(crate) fn indexer_key(k: &[u16]) -> Data { + if let Some(i) = crate::value::array_index(k) { + return Data::Number(f64::from(i)); + } + let name = String::from_utf16_lossy(k); + match name.parse::() { + Ok(n) if crate::number_to_string(n) == name => Data::Number(n), + _ => Data::String(name), + } + } + + /// [[HasProperty]] of `k` on `id`: for an object of a host class with an indexer, an array index, + /// or a name that the object and its prototypes lack, is there when the indexer gives a value other + /// than `undefined` for it. + pub(crate) fn has_property_indexed(&mut self, id: ObjId, k: &[u16]) -> JsResult { + let index = crate::value::array_index(k).is_some(); + if (index || !self.has_property(id, k)?) + && let Some(f) = self.host_indexer(id)? + { + return Ok(!matches!(self.host_index(&f, id, Self::indexer_key(k), true)?, Value::Undefined)); + } + self.has_property(id, k) + } + + /// `d` as a JavaScript value, the objects of host classes in it made from their [`host_ref`]. + pub(crate) fn write_hosted(&mut self, d: Data) -> JsResult { + let was = std::mem::replace(&mut self.write_hosted, true); + let r = self.write_data(d, 0, false); + self.write_hosted = was; + r + } +} + +/// Adds `classes` and the global objects `instances`, each made from the [`host_ref`] given. +pub(crate) fn install(i: &mut Interp, classes: Vec, instances: Vec<(String, Data)>) -> JsResult<()> { + for class in classes { + install_class(i, class)?; + } + for (name, d) in instances { + let v = i.write_hosted(d)?; + let global = i.global; + i.define(global, key(&name), Prop::Data { value: v, flags: 0 })?; + } + Ok(()) +} + +/// Adds the global properties `globals`, each read with its getter and assigned with its setter as +/// a member of a host class is. Assigning one without a setter keeps its value, and throws in strict +/// mode code. +pub(crate) fn install_globals(i: &mut Interp, globals: Vec<(String, HostFunction, Option)>) -> JsResult<()> { + let global = i.global; + for (name, get, set) in globals { + let mark = i.temp_roots.len(); + let get = hosted_function(i, get, &name); + i.temp_roots.push(Value::Object(get)); + let set = set.map(|f| hosted_function(i, f, &name)); + i.temp_roots.truncate(mark); + i.define(global, key(&name), Prop::Accessor { get: Some(get), set, flags: CONFIGURABLE })?; + } + Ok(()) +} + +fn install_class(i: &mut Interp, class: HostClass) -> JsResult<()> { + if i.host_classes.iter().any(|e| *e.name == *class.name) { + return Err(i.throw(ErrorType::Type, &format!("the host class {} is defined twice", class.name))); + } + let own = u32::try_from(i.host_classes.len()).unwrap_or(u32::MAX); + let (parent, family, parent_class) = match &class.parent { + None => (i.intrinsics.object_proto, own, None), + Some(p) => match i.host_classes.iter().enumerate().find(|(_, e)| *e.name == **p) { + Some((n, e)) => (e.proto, e.family, u32::try_from(n).ok()), + None => return Err(i.throw(ErrorType::Type, &format!("the host class {p} is not defined"))), + }, + }; + let proto = i.heap.alloc_object(Object::new(Class::Ordinary, Some(parent))); + let mark = i.temp_roots.len(); + i.temp_roots.push(Value::Object(proto)); + let r = fill_class(i, proto, &class); + i.temp_roots.truncate(mark); + let ctor = r?; + let members = class.members.iter().filter(|(_, m)| !matches!(m, HostMember::Unavailable(_))).map(|(name, _)| key(name)).collect(); + i.host_classes.push(Entry { + name: class.name.as_str().into(), + proto, + ctor, + index: class.index, + family, + parent: parent_class, + own: Rc::new(members), + }); + let global = i.global; + i.define(global, key(&class.name), Prop::Data { value: Value::Object(ctor), flags: crate::heap::HIDDEN }) +} + +/// Puts the members of `class` on `proto` and makes its constructor. → the constructor. +fn fill_class(i: &mut Interp, proto: ObjId, class: &HostClass) -> JsResult { + let path = &class.name; + for (name, member) in &class.members { + let full = format!("{path}.{name}"); + let prop = match member { + HostMember::Get(f) => Prop::Accessor { get: Some(hosted_function(i, f.clone(), &full)), set: None, flags: ENUMERABLE }, + HostMember::Property { get, set } => { + let get = hosted_function(i, get.clone(), &full); + i.temp_roots.push(Value::Object(get)); + Prop::Accessor { get: Some(get), set: Some(hosted_function(i, set.clone(), &full)), flags: ENUMERABLE } + } + HostMember::Method(f) => Prop::Data { value: Value::Object(hosted_function(i, f.clone(), &full)), flags: 0 }, + HostMember::Unavailable(f) => { + let f = hosted_function(i, f.clone(), &full); + Prop::Accessor { get: Some(f), set: Some(f), flags: 0 } + } + }; + i.define(proto, key(name), prop)?; + } + let construct = class.construct.clone().unwrap_or_else(|| { + let message = format!("{path} cannot be constructed by a script"); + Rc::new(move |_| Err(HostError::Type(message.clone()))) + }); + let ctor = hosted_function(i, construct, path); + i.define(ctor, key("prototype"), Prop::Data { value: Value::Object(proto), flags: 0 })?; + i.define(proto, key("constructor"), Prop::Data { value: Value::Object(ctor), flags: 0 })?; + i.object_mut(proto)?.extensible = false; + i.object_mut(ctor)?.extensible = false; + Ok(ctor) +} + +fn hosted_function(i: &mut Interp, f: HostFunction, name: &str) -> ObjId { + let proto = i.intrinsics.function_proto; + i.heap.alloc_object(Object::new(Class::Function(Func::Data { f, name: name.into(), read: ArgRead::Hosted }), Some(proto))) +} diff --git a/crates/js/src/host_tests.rs b/crates/js/src/host_tests.rs index 0a682811ec..8213e989ae 100644 --- a/crates/js/src/host_tests.rs +++ b/crates/js/src/host_tests.rs @@ -675,6 +675,87 @@ fn a_host_function_that_waits_where_it_cannot_ends_the_run() { assert_eq!(e.kind, RunErrorKind::Internal); } +/// The host class `Thing` with the method `fetch`, which waits for its answer where it can, the +/// getter `id`, the first number of the object's handle, and the constructor `make`; and the +/// global `thing`, the `Thing` with the handle `[1]`. +fn with_thing(r: &mut Realm, make: Option) { + let can_wait = r.wait_flag(); + let fetch: HostFunction = Rc::new(move |_| if can_wait.get() { Err(HostError::Wait) } else { Err(HostError::Error("cannot wait here".into())) }); + let id: HostFunction = Rc::new(|a| Ok(a.first().and_then(host_ref_parts).and_then(|(_, h)| h.first().copied()).map_or(Data::Null, Data::Number))); + let members = vec![("fetch".to_string(), HostMember::Method(fetch)), ("id".to_string(), HostMember::Get(id))]; + let class = HostClass { name: "Thing".into(), parent: None, members, index: None, construct: make }; + r.define_host_classes(vec![class], vec![("thing".into(), host_ref("Thing", &[1.0]))]).unwrap(); +} + +#[test] +fn the_answer_to_a_waiting_member_of_a_host_class_is_an_object_of_its_class() { + let mut r = realm(1_000_000); + with_thing(&mut r, None); + r.start("var t = thing.fetch(), u = thing.fetch(); [t instanceof Thing, t.id, t === u, t === thing].join()").unwrap(); + for _ in 0..2 { + assert_eq!(r.advance(1_000).unwrap(), Progress::Paused); + assert!(r.waits()); + r.answer(host_ref("Thing", &[2.0])).unwrap(); + } + assert_eq!(finish(&mut r, 1_000).0.unwrap(), JsValue::String("true,2,true,false".into())); +} + +#[test] +fn a_host_class_constructor_called_with_new_cannot_wait() { + let mut r = realm(1_000_000); + let could: Rc>> = Rc::default(); + let (seen, can_wait) = (could.clone(), r.wait_flag()); + let make: HostFunction = Rc::new(move |_| { + seen.set(Some(can_wait.get())); + if can_wait.get() { Err(HostError::Wait) } else { Ok(Data::Object(Vec::new())) } + }); + with_thing(&mut r, Some(make)); + r.start("var c = new Thing(); c instanceof Thing").unwrap(); + assert_eq!(finish(&mut r, 1_000).0.unwrap(), JsValue::Bool(true)); + assert_eq!(could.get(), Some(false)); +} + +#[test] +fn objects_of_a_host_class_report_its_available_members_as_their_own() { + let mut r = realm(1_000_000); + let value: HostFunction = Rc::new(|_| Ok(Data::Number(1.0))); + let missing: HostFunction = Rc::new(|_| Err(HostError::Error("not here yet".into()))); + let base = HostClass { + name: "Base".into(), + parent: None, + members: vec![ + ("size".to_string(), HostMember::Get(value.clone())), + ("shape".to_string(), HostMember::Property { get: value.clone(), set: value.clone() }), + ("grow".to_string(), HostMember::Method(value.clone())), + ("later".to_string(), HostMember::Unavailable(missing)), + ], + index: None, + construct: None, + }; + let leaf = HostClass { + name: "Leaf".into(), + parent: Some("Base".into()), + members: vec![("leaf".to_string(), HostMember::Get(value))], + index: None, + construct: None, + }; + r.define_host_classes(vec![base, leaf], vec![("it".into(), host_ref("Leaf", &[1.0]))]).unwrap(); + r.start( + "var own = Object.prototype.hasOwnProperty, keys = [];\ + for (var k in it) keys.push(k);\ + [it.hasOwnProperty('size'), it.hasOwnProperty('shape'), it.hasOwnProperty('grow'), it.hasOwnProperty('leaf'),\ + own.call(it, 'size'), it.propertyIsEnumerable('grow'),\ + it.hasOwnProperty('later'), it.propertyIsEnumerable('later'), it.hasOwnProperty('nope'),\ + it.hasOwnProperty('hasOwnProperty'), it.hasOwnProperty('constructor'), 'later' in it,\ + keys.sort().join(' '), Leaf.prototype.hasOwnProperty('size'), ({}).hasOwnProperty('size')].join()", + ) + .unwrap(); + assert_eq!( + finish(&mut r, 1_000_000).0.unwrap(), + JsValue::String("true,true,true,true,true,true,false,false,false,false,false,true,leaf shape size,false,false".into()) + ); +} + #[test] fn a_converted_function_reads_each_argument_as_its_list_says() { let mut r = realm(1_000_000); diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index a64763947f..9edea621c5 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -279,6 +279,14 @@ pub(crate) struct Interp { pub(crate) install_error: Option, /// `File` and `Folder`, once a host has added them ([`crate::Realm::define_file_classes`]). pub(crate) files: Option, + /// The classes a host added ([`crate::Realm::define_host_classes`]), in the order it added them. + pub(crate) host_classes: Vec, + /// Whether [`Self::write_data`] makes objects of host classes from their [`crate::host_ref`]. + pub(crate) write_hosted: bool, + /// The object made for each family of classes and handle ([`crate::host_classes`]), so that two reads of + /// the same one give the same object. It is not a root: an entry whose object was collected is + /// dropped after each collection. + pub(crate) host_objects: crate::host_classes::Made, /// `UnitValue`, once a host has added it ([`crate::Realm::add_unit_values`]). Until then the /// operators take no object as a measurement. pub(crate) unit_values: Option, @@ -302,6 +310,11 @@ pub(crate) struct Interp { pub(crate) can_wait: Rc>, /// A host function's call waits for its result: the value on top of the stack stands in for it. pub(crate) waiting: bool, + /// The call that waits is a member of a host class ([`crate::host::ArgRead::Hosted`]): its + /// answer is read as such a member's result is ([`Interp::write_hosted`]). + pub(crate) waiting_hosted: bool, + /// A host class's constructor runs with `new`: it may not wait for its result. + pub(crate) constructing: bool, /// The built-in that waits with the host's call ([`Pause::Ask`]): it takes the answer before /// the next instruction runs. pub(crate) resuming: Option, @@ -583,6 +596,9 @@ impl Interp { held_bytes: 0, install_error: None, files: None, + host_classes: Vec::new(), + write_hosted: false, + host_objects: crate::host_classes::Made::default(), unit_values: None, date_host: crate::date_builtins::DateHost::default(), held: Rc::default(), @@ -593,6 +609,8 @@ impl Interp { in_slice: false, can_wait: Rc::default(), waiting: false, + waiting_hosted: false, + constructing: false, resuming: None, host_abort: None, data_limits: crate::DataLimits::default(), @@ -857,6 +875,7 @@ impl Interp { roots.objects.push(self.global); roots.objects.extend(self.intrinsics.all()); roots.objects.extend(self.files.iter().flat_map(crate::file_classes::Classes::objects)); + roots.objects.extend(self.host_classes.iter().flat_map(crate::host_classes::Entry::objects)); roots.values.extend(self.symbols.root_values()); roots.objects.extend(self.symbols.root_objects()); roots.objects.extend(self.unit_values.iter().map(crate::unit_value::Classes::object)); @@ -872,6 +891,7 @@ impl Interp { self.template_objects.retain(|(site, _), (code, _)| Rc::strong_count(code) > sites.get(site).copied().unwrap_or(0)); roots.objects.extend(self.template_objects.values().map(|&(_, id)| id)); self.heap.collect(&roots); + crate::host_classes::forget_collected(&mut self.host_objects, &self.heap, &self.host_classes); // The collection counts the live total again, so bytes already released are not in it. self.held.released.set(0); self.flattened.set(0); @@ -1573,6 +1593,28 @@ impl Interp { /// [[Get]] starting at `start`, with `receiver` as `this` for a getter. pub(crate) fn get_from(&mut self, start: ObjId, k: &[u16], receiver: &Value) -> JsResult { + // An array index of an object of a host class with an indexer is the indexer's answer. + if let Some(i) = array_index(k) + && let Some(f) = self.host_indexer(start)? + { + return self.host_index(&f, start, crate::Data::Number(f64::from(i)), false); + } + match self.find_property(start, k)? { + // A name the object and its prototypes lack is the indexer's answer too. + None => match self.host_indexer(start)? { + Some(f) => self.host_index(&f, start, Self::indexer_key(k), false), + None => Ok(Value::Undefined), + }, + Some(Prop::Accessor { get: None, .. }) => Ok(Value::Undefined), + Some(Prop::Data { value, .. }) => Ok(value), + Some(Prop::Accessor { get: Some(g), .. }) => self.call(&Value::Object(g), receiver, &[]), + } + } + + /// [[Get]] of a name that is not an array index, without the indexer of an object of a host + /// class: a name the object and its prototypes lack is `undefined`. For names the engine looks + /// up itself, such as `toJSON`, which a collection's indexer would answer with an error. + pub(crate) fn get_property_only(&mut self, start: ObjId, k: &[u16], receiver: &Value) -> JsResult { match self.find_property(start, k)? { None | Some(Prop::Accessor { get: None, .. }) => Ok(Value::Undefined), Some(Prop::Data { value, .. }) => Ok(value), @@ -1868,10 +1910,17 @@ impl Interp { Some(Prop::Data { flags, .. }) if flags & WRITABLE == 0 => return self.reject(throw, &k, "it is read-only"), _ => {} } - let o = self.object(id)?; - if !o.extensible { + if !self.object(id)?.extensible { + // A name that an object of a host class with an indexer lacks is read with the indexer + // first, so assigning it throws what reading it throws. + if array_index(&k).is_none() + && let Some(f) = self.host_indexer(id)? + { + self.host_index(&f, id, Self::indexer_key(&k), false)?; + } return self.reject(throw, &k, "the object is not extensible"); } + let o = self.object(id)?; if let Class::Array { length, length_writable: false } = o.class && array_index(&k).is_some_and(|i| i >= length) { @@ -2782,7 +2831,7 @@ impl Interp { Func::Data { f, name, read } => { // The arguments are read before the function runs, and a result being built // keeps itself reachable. - return Ok(Prepared::Done(self.call_data(&f, &name, &args, &read)?)); + return Ok(Prepared::Done(self.call_data(&f, &name, &this, &args, &read)?)); } Func::Eval { f, end, strict_writes, name } => { return Ok(Prepared::Done(self.call_evaluator(&f, &end, &strict_writes, &name, &args)?)); @@ -2893,6 +2942,25 @@ impl Interp { self.stack.truncate(start); self.push(v) } + // A host class's constructor ([`crate::host_classes`]) gives the object it makes. A plain + // object it gives inherits from the class's prototype. The class's other functions are + // not constructors. A constructor called with `new` cannot wait for its result. + Some(Func::Data { f: host, name, read: read @ crate::host::ArgRead::Hosted }) + if f.as_object().is_some_and(|o| self.is_host_constructor(o)) => + { + let was = std::mem::replace(&mut self.constructing, true); + let v = self.call_data(&host, &name, &Value::Undefined, &args, &read); + self.constructing = was; + let v = v?; + if let (Some(callee), Value::Object(o)) = (f.as_object(), &v) + && matches!(self.object(*o)?.class, Class::Ordinary) + && let Some(Prop::Data { value: Value::Object(proto), .. }) = self.find_property(callee, &key("prototype"))? + { + self.object_mut(*o)?.proto = Some(proto); + } + self.stack.truncate(start); + self.push(v) + } _ => Err(self.type_error("the value is not a constructor")), } } @@ -3139,7 +3207,7 @@ impl Interp { self.temp_roots.extend(keep.iter().cloned()); let was_waiting = self.waiting; let answer = match self.func_of(&host) { - Some(Func::Data { f, name, read }) => self.call_data(&f, &name, &args, &read), + Some(Func::Data { f, name, read }) => self.call_data(&f, &name, &Value::Undefined, &args, &read), _ => self.call(&host, &Value::Undefined, &args), }; self.temp_roots.truncate(mark); @@ -3836,7 +3904,11 @@ impl Interp { } let Value::Object(o) = b else { return Err(self.type_error("the right side of 'in' is not an object")) }; let k = self.to_prop_key(a)?; - self.has_pk(*o, &k).map(Value::Bool) + match &k { + PropKey::Str(name) => self.has_property_indexed(*o, name), + PropKey::Sym(_) => self.has_pk(*o, &k), + } + .map(Value::Bool) } } } diff --git a/crates/js/src/lib.rs b/crates/js/src/lib.rs index 0086d8ede6..25e16d2337 100644 --- a/crates/js/src/lib.rs +++ b/crates/js/src/lib.rs @@ -90,6 +90,7 @@ mod error; mod file_classes; mod heap; mod host; +mod host_classes; mod interp; mod iteration; mod lexer; @@ -117,6 +118,7 @@ pub use ast::{ pub use builtins::extensions::Localization; pub use error::{SyntaxError, TOO_DEEP, TOO_LONG}; pub use host::{Arg, CallSite, Data, DataLimits, HostError, HostFunction, HostItem, ScriptItem, SiteFunction}; +pub use host_classes::{HOST_REF_KEY, HostClass, HostMember, host_ref, host_ref_parts}; pub use lexer::{Goal, Lexer}; pub use number::to_string as number_to_string; pub use realm::{Interrupt, JsValue, LimitKind, Limits, MAX_UNBROKEN_FUEL, Progress, Realm, RunError, RunErrorKind, SourceLocator, UNKNOWN_SOURCE}; diff --git a/crates/js/src/realm.rs b/crates/js/src/realm.rs index 9daf4b9e9d..71c42e0de0 100644 --- a/crates/js/src/realm.rs +++ b/crates/js/src/realm.rs @@ -271,6 +271,8 @@ impl Realm { interp.last_error = Value::Null; interp.host_abort = None; interp.waiting = false; + interp.waiting_hosted = false; + interp.constructing = false; interp.resuming = None; interp.error_tag = UNKNOWN_SOURCE; interp.thrown_mark = None; @@ -324,6 +326,8 @@ impl Realm { interp.temp_roots.clear(); interp.join_stack.clear(); interp.waiting = false; + interp.waiting_hosted = false; + interp.constructing = false; interp.resuming = None; interp.passing = Value::Undefined; if let Some(es2015) = interp.next_es2015.take() { @@ -442,8 +446,11 @@ impl Realm { }); } interp.waiting = false; + // A member of a host class gets its answer as it gets an immediate result. + let hosted = std::mem::take(&mut interp.waiting_hosted); // The value on top of the stack stood in for the result. - let r = interp.write_data(d, 0, false).and_then(|v| { + let written = if hosted { interp.write_hosted(d) } else { interp.write_data(d, 0, false) }; + let r = written.and_then(|v| { interp.stack.pop(); interp.push(v) }); @@ -546,6 +553,27 @@ impl Realm { } } + /// Adds the host classes `classes` ([`crate::HostClass`]), each a global constructor whose + /// prototype holds its members, and the global objects `instances`, each made from the + /// [`crate::host_ref`] given. Prototypes and constructors are frozen; the instances cannot be + /// replaced. A heap too small for them ends with the error the realm's next run would give. + pub fn define_host_classes(&mut self, classes: Vec, instances: Vec<(String, crate::Data)>) -> Result<(), RunError> { + match crate::host_classes::install(&mut self.interp, classes, instances) { + Ok(()) => Ok(()), + Err(e) => self.outcome(Err(e)).map(drop), + } + } + + /// Adds the global properties `globals`: a name, the function that answers a read, and the + /// function that answers an assignment, each called with `undefined` as `this` (and the value + /// assigned). Assigning one without a setter keeps its value, and throws in strict mode code. + pub fn define_host_globals(&mut self, globals: Vec<(String, crate::HostFunction, Option)>) -> Result<(), RunError> { + match crate::host_classes::install_globals(&mut self.interp, globals) { + Ok(()) => Ok(()), + Err(e) => self.outcome(Err(e)).map(drop), + } + } + /// Sets `Folder.current` back to the host's `current`, for the next run of a realm that has /// `File` and `Folder` ([`Realm::define_file_classes`]); a realm without them keeps its /// `Folder.current`. The files an earlier run opened are no longer open. The last run's uncaught diff --git a/crates/mcp/src/tests.rs b/crates/mcp/src/tests.rs index 7c3d717d5a..c1a661c4e3 100644 --- a/crates/mcp/src/tests.rs +++ b/crates/mcp/src/tests.rs @@ -776,6 +776,15 @@ fn set_paint_reports_how_many_objects_it_painted() { assert_eq!(v["objects"], 2, "{v}"); let v = paint(&mut s, 16, json!({"strokeWidth": 2})); assert_eq!(v["objects"], 2, "{v}"); + + // While the Shape Builder is the active tool, the fill goes to new art only and the stroke to + // the selection: the reply names the command that painted nothing. + let r = call(&mut s, 17, "select_tool", json!({"tool": "shapeBuilder"})); + assert_eq!(r["isError"], false, "{r}"); + let v = paint(&mut s, 18, json!({"fill": "#ff00ff", "stroke": "#00ffff"})); + assert_eq!(v["objects"], 2, "{v}"); + assert_eq!(v["unpainted"], json!(["paint.setFill"]), "{v}"); + assert!(v["note"].as_str().is_some_and(|n| n.contains("Shape Builder")), "{v}"); } /// #1003: type made on or in a path takes add_text's `color` too, over the current fill. @@ -1662,6 +1671,18 @@ fn headless_backend_methods() { assert_eq!(with_enclosing[0][1]["label"], "Enclosing Lasso Tool"); assert!(with_enclosing[0][1]["shortcut"].is_null()); assert_eq!(h.call("ui.tool.select", json!({"tool": enclosing})).unwrap()["tool"], enclosing); + // The Smart Pen Tool is listed once, at the end of the Pen tool's group. + let smart_pen = vectorcraft_tools::addons::smart_pen::ID; + let with_smart_pen: Vec<_> = + groups.iter().map(|group| group.as_array().unwrap()).filter(|group| group.iter().any(|entry| entry["id"] == smart_pen)).collect(); + assert_eq!(with_smart_pen.len(), 1, "{smart_pen} is in one group"); + let ids: Vec<_> = with_smart_pen[0].iter().map(|entry| entry["id"].clone()).collect(); + assert_eq!(ids.first(), Some(&json!("pen"))); + assert_eq!(ids[ids.len().saturating_sub(2)..], [json!("quickPen"), json!(smart_pen)]); + let entry = with_smart_pen[0].iter().find(|entry| entry["id"] == smart_pen).unwrap(); + assert_eq!(entry["label"], "Smart Pen Tool"); + assert!(entry["shortcut"].is_null()); + assert_eq!(h.call("ui.tool.select", json!({"tool": smart_pen})).unwrap()["tool"], smart_pen); let polygonal = groups.iter().flat_map(|group| group.as_array().unwrap()).find(|entry| entry["id"] == "polygonalLasso"); assert_eq!(polygonal.map(|entry| entry["label"].clone()), Some(json!("Polygonal Lasso Tool"))); assert!(h.call("ui.resize", json!({})).is_err()); diff --git a/crates/mcp/src/tools/definitions.rs b/crates/mcp/src/tools/definitions.rs index 931e910315..d8d215b86e 100644 --- a/crates/mcp/src/tools/definitions.rs +++ b/crates/mcp/src/tools/definitions.rs @@ -282,7 +282,7 @@ pub fn tool_definitions() -> Vec { tool( "set_paint", "Set paint", - "Set fill, stroke and/or stroke weight on the selection (or `ids`) and as the default for new art. Returns {applied, objects}: `objects` counts the objects painted, as paint.setFill, paint.setStroke and stroke.set report them (the largest of their counts); when it is 0, a `note` says that only the default for new art changed.", + "Set fill, stroke and/or stroke weight on the selection (or `ids`) and as the default for new art. Returns {applied, objects}: `objects` counts the objects painted, as paint.setFill, paint.setStroke and stroke.set report them (the largest of their counts); when it is 0, a `note` says that only the default for new art changed, and when only some of those commands painted no object, `unpainted` lists them with a `note`.", obj( json!({ "fill": paint_schema("Fill"), diff --git a/crates/mcp/src/tools/dispatch.rs b/crates/mcp/src/tools/dispatch.rs index 12c3b24f37..752f72b928 100644 --- a/crates/mcp/src/tools/dispatch.rs +++ b/crates/mcp/src/tools/dispatch.rs @@ -183,11 +183,16 @@ fn dispatch(b: &mut dyn Backend, name: &str, a: &Args) -> Result Result<(Vec>, Map), Str } /// Sets the paint `a` gives on `ids` (default: the selection) and as the default for new art. -/// Returns the paint applied and the most objects one of its edits painted (the `objects` of the -/// `paint.setFill`, `paint.setStroke` and `stroke.set` replies). -pub(super) fn apply_paint(b: &mut dyn Backend, a: &Args, ids: Option) -> Result<(Value, u64), String> { +/// Returns the paint applied, the most objects one of its edits painted (the `objects` of the +/// `paint.setFill`, `paint.setStroke` and `stroke.set` replies) and the commands among them that +/// painted no object. +pub(super) fn apply_paint(b: &mut dyn Backend, a: &Args, ids: Option) -> Result<(Value, u64, Vec<&'static str>), String> { let (steps, applied) = paint_steps(a)?; - let mut objects = 0; + let (mut objects, mut unpainted) = (0, vec![]); for (cmd, mut p) in steps { if let Some(ids) = &ids { p["ids"] = ids.clone(); } let r = exec(b, cmd, p)?; - objects = objects.max(r.get("objects").and_then(Value::as_u64).unwrap_or(0)); + let n = r.get("objects").and_then(Value::as_u64).unwrap_or(0); + if n == 0 { + unpainted.push(cmd); + } + objects = objects.max(n); } - Ok((Value::Object(applied), objects)) + Ok((Value::Object(applied), objects, unpainted)) } /// Checks `draw_path` / `draw_shape`'s `dash`, `cap`, `join`, `opacity`, `name` and `effects` diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 18d0ebc247..17f665d58f 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -484,7 +484,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "view.actualSize", "Actual Size", "Cmd+1", - "{} 100%: with Display Print Size at 100% Zoom off, one document point per screen point; on, one document inch fills 96 screen points (an inch at the system's reference density, whatever the display scaling); the same at every UI Scaling", + "{} 100%: with Display Print Size at 100% Zoom off, one document point per screen point; on, one document inch fills an inch of the display that shows the window, measured from the physical size the system reports for it, or 96 screen points where it reports none or a size no display has; the same at every UI Scaling", ), ("view.setZoom", "Set Zoom", "", "{zoom: percent, center?: [x,y]}"), ( @@ -994,7 +994,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.recolorDialog", "Recolor Artwork…", "", - "{colors?: n (an n-colour job: n rows, Scale Tints) | [colour] (new colours to assign, in order; with no art selected and no group they are the rows, and OK saves them as a new colour group, field `groupName`: the Color Guide's Edit or Apply Colors), library?: id or name; or \"document\" (Limit to Library; \"\" the first library), group?: colour group (Edit or Apply Color Group: OK rewrites the group with the new colours and recolours the selected art, if any)} open Recolor Artwork (dialog `recolor`; engine: recolor.reduce / recolor.apply)", + "{colors?: n (an n-colour job: n rows, Scale Tints) | [colour] (new colours to assign, in order; with no art selected and no group they are the rows, and OK saves them as a new colour group, field `groupName`: the Color Guide's Edit or Apply Colors), library?: id or name; or \"document\" (Limit to Library; \"\" the first library), group?: colour group (Edit or Apply Color Group: OK rewrites the group with the new colours and recolours the selected art, if any), preset?: bool (Recolor with Preset: first open the `recolorPreset` dialog, whose Limit to Library field `limitTo` starts on `library`; its OK opens Recolor Artwork with `colors` and that library; an error with `group`)} open Recolor Artwork (dialog `recolor`; engine: recolor.reduce / recolor.apply)", ), ( "ui.recolorUndo", @@ -1597,7 +1597,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.colorWheel", "Color Wheel Options", "", - "{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, sliders?: none|oklch|hsl, gamut?: bool, harmony?: bool, harmonyRule?: complementary|splitComplementary|leftComplement|rightComplement|analogous|analogous2|triad|tetrad|tetrad2|tetrad3|compound|compound2|highContrast|highContrast3|pentagram, opacity?: bool, vision?: bool, documentColors?: bool} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, pick the box's channel, as Box Channel does, and show no slider rows under the wheel or the box (none), OKLCH Sliders (oklch) or HSL Sliders (hsl), as the menu items of those names do: the box is a color field with the channel's strip at its right, and the field shows the other two components (hue: saturation across and brightness up; saturation: hue across and brightness up; brightness: hue across and saturation up; red: blue across and green up; green: blue across and red up; blue: red across and green up); OKLCH Sliders edit lightness 0 to 100 %, chroma 0 to 100 % of 0.4 and hue 0 to 360°, CSS Color 4's OKLCH of the display sRGB, and a color outside sRGB keeps L and H and takes the largest chroma that fits; HSL Sliders edit hue 0 to 360°, saturation 0 to 100 % and lightness 0 to 100 %, CSS Color 4's HSL of the display sRGB; gamut true grays out the parts of the wheel's square and the box's field whose colors the CMYK space cannot print (the out-of-gamut warning's test, as color.gamutCheck answers it), as Show Out-of-Gamut Colors does, and false shows them again; the shading is approximate: each cell of a 16 by 16 grid over the square or the field is grayed out or not by the color at its center, so a grayed cell can hold printable colors and a clear cell can hold colors that cannot print; harmony shows a marker on the wheel's ring for each other color of harmonyRule (the Color Guide's rule of that id; a rule's label is taken too), as Show Harmony and Harmony Rule do, and a click on a marker applies its color; opacity checks (true) or unchecks (false) Show Opacity, as the panel menu does: a row under the wheel or the box with a slider and a percent field that set the opacity of what the panel edits (the fill item, as paint.setFill {opacity} sets it, the stroke item, as paint.setStroke {opacity} sets it, the selected gradient stop, or the selected freeform point, the first stop or point when none is selected; gray with nothing selected, for an object selected in a symbol instance, and when the fill or stroke item it would set is on type characters or missing); vision shows Show Color Vision Preview's row under the wheel or the box, four chips with the current color as simulated for protanopia, deuteranopia and tritanopia (the simulations of view.proofSetup's protanopia, deuteranopia and tritanopia targets) and for achromatopsia (the gray with the color's CIE L*), each named with its hex value in its tooltip and to screen readers, and taking the keyboard focus; a click or a key on a chip does not apply its color; documentColors shows or hides the row the panel menu's Show Document Colors adds under the wheel or the box: the colors color.used {} lists, headed Selection Colors when something is selected and Document Colors otherwise, most used first and as many as fit in one row (a chip's tooltip gives its hex value and how many times the art uses it; a click applies it to the active proxy or to the selected gradient stop, keeping its color model and its link to a global swatch, or to the selected freeform point, which takes the color alone, and Alt+click applies it to the other proxy; the row reads the colors again when the document or the selection changes, not during a drag, and in art with more than 5,000 color uses at most once every half second after an edit); keys left out or null keep their values ({} reads them), params that are not an object, another key or a value off the list are an error and change nothing, oklch is an error while the working RGB space is not sRGB, the settings are kept with the preferences, and the command does not open the panel (window.panel {panel: \"colorWheel\"} does) (ui.inspect: ui.color_wheel) → {view, channel, sliders, gamut, harmony, harmonyRule, opacity, vision, documentColors}", + "{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, sliders?: none|oklch|hsl, gamut?: bool, harmony?: bool, harmonyRule?: complementary|splitComplementary|leftComplement|rightComplement|analogous|analogous2|triad|tetrad|tetrad2|tetrad3|compound|compound2|highContrast|highContrast3|pentagram, opacity?: bool, contrast?: bool, contrastFor?: normalText|largeText|graphics, contrastBackground?: a color, or null, vision?: bool, documentColors?: bool} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, pick the box's channel, as Box Channel does, and show no slider rows under the wheel or the box (none), OKLCH Sliders (oklch) or HSL Sliders (hsl), as the menu items of those names do, and set Show Contrast, Contrast For, Contrast Background, Show Color Vision Preview and Show Document Colors: the box is a color field with the channel's strip at its right, and the field shows the other two components (hue: saturation across and brightness up; saturation: hue across and brightness up; brightness: hue across and saturation up; red: blue across and green up; green: blue across and red up; blue: red across and green up); OKLCH Sliders edit lightness 0 to 100 %, chroma 0 to 100 % of 0.4 and hue 0 to 360°, CSS Color 4's OKLCH of the display sRGB, and a color outside sRGB keeps L and H and takes the largest chroma that fits; HSL Sliders edit hue 0 to 360°, saturation 0 to 100 % and lightness 0 to 100 %, CSS Color 4's HSL of the display sRGB; gamut true grays out the parts of the wheel's square and the box's field whose colors the CMYK space cannot print (the out-of-gamut warning's test, as color.gamutCheck answers it), as Show Out-of-Gamut Colors does, and false shows them again; the shading is approximate: each cell of a 16 by 16 grid over the square or the field is grayed out or not by the color at its center, so a grayed cell can hold printable colors and a clear cell can hold colors that cannot print; harmony shows a marker on the wheel's ring for each other color of harmonyRule (the Color Guide's rule of that id; a rule's label is taken too), as Show Harmony and Harmony Rule do, and a click on a marker applies its color; opacity checks (true) or unchecks (false) Show Opacity, as the panel menu does: a row under the wheel or the box with a slider and a percent field that set the opacity of what the panel edits (the fill item, as paint.setFill {opacity} sets it, the stroke item, as paint.setStroke {opacity} sets it, the selected gradient stop, or the selected freeform point, the first stop or point when none is selected; gray with nothing selected, for an object selected in a symbol instance, and when the fill or stroke item it would set is on type characters or missing); contrast shows a row under the wheel or the box with the background's chip, the WCAG 2 contrast ratio cut off at two decimals and the AA and AAA results for contrastFor (AA only for graphics), as color.contrast answers them, and contrastBackground pins the background the row measures against (Contrast Background › Current Color; null: the color drawn behind the selection, Behind Selection); vision shows Show Color Vision Preview's row under the wheel or the box, four chips with the current color as simulated for protanopia, deuteranopia and tritanopia (the simulations of view.proofSetup's protanopia, deuteranopia and tritanopia targets) and for achromatopsia (the gray with the color's CIE L*), each named with its hex value in its tooltip and to screen readers, and taking the keyboard focus; a click or a key on a chip does not apply its color; documentColors shows or hides the row the panel menu's Show Document Colors adds under the wheel or the box: the colors color.used {} lists, headed Selection Colors when something is selected and Document Colors otherwise, most used first and as many as fit in one row (a chip's tooltip gives its hex value and how many times the art uses it; a click applies it to the active proxy or to the selected gradient stop, keeping its color model and its link to a global swatch, or to the selected freeform point, which takes the color alone, and Alt+click applies it to the other proxy; the row reads the colors again when the document or the selection changes, not during a drag, and in art with more than 5,000 color uses at most once every half second after an edit); keys left out or null keep their values ({} reads them), params that are not an object, another key or a value off the list are an error and change nothing, oklch is an error while the working RGB space is not sRGB, the settings are kept with the preferences, and the command does not open the panel (window.panel {panel: \"colorWheel\"} does) (ui.inspect: ui.color_wheel) → {view, channel, sliders, gamut, harmony, harmonyRule, opacity, contrast, contrastFor, contrastBackground, vision, documentColors}", ), ( "ui.savePdfDialog", @@ -1986,7 +1986,19 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "plugin.dialog", "Plug-in…", "", - "{id: an object filter plug-in (plugin.list), params?: {…}} Object › Plug-ins: run the filter at once when it takes no parameters or params are given (plugin.run), else open its dialog (dialog `plugin`: a field per parameter, `__plugin` the id, live preview; OK runs plugin.run as one undo step). A heavy filter, and a filter that lists `progress` and no commandAllowlist, run in the background when they run at once or OK runs them without a kept preview → {background: true, status} (see plugin.cancelRuns)", + "{id: an object filter plug-in (plugin.list), params?: {…}} Object › Plug-ins: run the filter at once when it takes no parameters or params are given (plugin.run), else open its dialog (dialog `plugin`: a field per parameter at the value the filter last ran with in this session, else its default, `__plugin` the id, live preview; OK runs plugin.run as one undo step). A heavy filter, and a filter that lists `progress` and no commandAllowlist, run in the background when they run at once or OK runs them without a kept preview → {background: true, status} (see plugin.cancelRuns)", + ), + ( + "plugin.applyLastFilter", + "Apply Last Filter", + "", + "{} Object › Plug-ins › Apply : run the object filter that last ran in this session (a plugin.run that succeeded: its menu item, its dialog's OK, a request, a command.batch step or an action.batch step; not a plug-in's own commands) again on the selection with the same parameters, without its dialog, as one undo step; it runs in the background where its menu item would → plugin.run's result | {background: true, status}. An error with no document open, when no filter ran yet, when that filter was removed or installed again (the same module too) since, or when its manifest no longer takes those parameters as they are", + ), + ( + "plugin.lastFilter", + "Last Filter…", + "", + "{} Object › Plug-ins › …: open the dialog of the object filter that last ran in this session (see plugin.applyLastFilter) with the parameters it ran with (dialog `plugin`); OK runs it as one undo step and Cancel changes nothing. A filter without parameters runs at once. The same errors as plugin.applyLastFilter", ), ( "ui.installPlugin", diff --git a/crates/pathops/src/pathfinder.rs b/crates/pathops/src/pathfinder.rs index af7bf90231..102d7e7138 100644 --- a/crates/pathops/src/pathfinder.rs +++ b/crates/pathops/src/pathfinder.rs @@ -226,7 +226,7 @@ pub fn pathfinder_with(op: PathfinderOp, shapes: &[Shape], precision: f64) -> Ve ); subpaths.into_iter().zip(shapes).filter(|(sp, _)| !sp.is_empty()).flat_map(|(sp, s)| one(PathData::new(sp), s.key)).collect() } - PathfinderOp::Outline => outline_edges(&arr, shapes), + PathfinderOp::Outline => outline_edges(&arr, shapes, precision), PathfinderOp::HardMix | PathfinderOp::SoftMix => regions_of(&arr) .into_iter() .filter_map(|r| { @@ -971,13 +971,60 @@ fn along(a: &[PathSeg], b: &[PathSeg], tol: f64) -> bool { covers(a, b) && covers(b, a) } -/// Pathfinder Outline: split every shape's boundary at junctions of the arrangement. -fn outline_edges(arr: &Arrangement, shapes: &[Shape]) -> Vec { +/// [`along`] with each piece checked at points no farther apart along its control polygon than +/// `tol`, at most 64 to a piece, so curves that meet at the middles and ends of their pieces but +/// part between them are not one. `a` and `b` run opposite ways. Each piece's samples include its +/// middle. Chains whose pieces pair up with control points within `tol` of each other are one +/// without sampling: each point of such a piece is within `tol` of the point of its pair at the same +/// parameter. +fn along_closely(a: &[PathSeg], b: &[PathSeg], tol: f64) -> bool { + let within = |p: Point, q: Point| p.distance(q) <= tol; + let paired = a.len() == b.len() + && a.iter().zip(b.iter().rev()).all(|(p, q)| match (p, q.reverse()) { + (PathSeg::Line(x), PathSeg::Line(y)) => within(x.p0, y.p0) && within(x.p1, y.p1), + (PathSeg::Quad(x), PathSeg::Quad(y)) => within(x.p0, y.p0) && within(x.p1, y.p1) && within(x.p2, y.p2), + (PathSeg::Cubic(x), PathSeg::Cubic(y)) => within(x.p0, y.p0) && within(x.p1, y.p1) && within(x.p2, y.p2) && within(x.p3, y.p3), + _ => false, + }); + if paired { + return true; + } + let samples = |s: &PathSeg| { + let len = match s { + PathSeg::Line(l) => l.p0.distance(l.p1), + PathSeg::Quad(q) => q.p0.distance(q.p1) + q.p1.distance(q.p2), + PathSeg::Cubic(c) => c.p0.distance(c.p1) + c.p1.distance(c.p2) + c.p2.distance(c.p3), + }; + // An even count puts a sample at the middle of the piece. + let n = if tol > 0.0 { ((len / tol / 2.0).ceil().clamp(1.0, 32.0) as usize) * 2 } else { 64 }; + let s = *s; + (1..=n).map(move |k| s.eval(k as f64 / n as f64)) + }; + let covers = |from: &[PathSeg], to: &[PathSeg]| { + // Each point's search goes back along `to` from the piece the point before it was near. + let mut at = to.len(); + from.iter().flat_map(samples).all(|p| { + let mut order = to.iter().enumerate().take(at).rev().chain(to.iter().enumerate().skip(at).rev()); + let Some((i, _)) = order.find(|(_, t)| t.nearest(p, 1e-12).distance_sq.sqrt() <= tol) else { return false }; + at = i + 1; + true + }) + }; + covers(a, b) && covers(b, a) +} + +/// Pathfinder Outline: split every shape's boundary at junctions of the arrangement. Junctions +/// closer together than `reach` are one, and coincident edges within ten times it are one edge. +/// `reach` is the larger of the arrangement's tolerance for the art's size and `precision` / 10,000, +/// with `precision` kept within 0.001 to 10 pt (Pathfinder Options › Precision's range), so the +/// default precision gives 0.000001 pt as before. Scaling the art and the precision together scales +/// `reach` by the same amount. +fn outline_edges(arr: &Arrangement, shapes: &[Shape], precision: f64) -> Vec { // Sorted by x (then y), so a segment needs only the junctions inside its control box. let junctions = arr.junctions(); let scale = shapes.iter().filter_map(|s| s.path.control_bounds()).map(|r| r.width().max(r.height())).fold(1.0, f64::max); let tol = scale * 1e-7; - let reach = tol.max(1e-6); + let reach = tol.max(1e-6 * (precision / DEFAULT_PRECISION).clamp(0.1, 1000.0)); // (chain, key, source index) let mut chains: Vec<(Vec, u64)> = Vec::new(); for s in shapes { @@ -1054,8 +1101,15 @@ fn outline_edges(arr: &Arrangement, shapes: &[Shape]) -> Vec { // De-duplicate coincident chains, keeping the front-most key (later shapes overwrite). A // match has its midpoint within `near` of this one's, so only the chains in the grid cells // around it are candidates; the first of them in `out` order is the one a scan would find. + // Ends and midpoint only pick the candidates: two chains are one edge when each lies within `d` + // of the other along its whole length. let mut out: Vec<(Vec, u64)> = Vec::new(); let mut sigs: Vec<(Point, Point, Point)> = Vec::new(); + let mut paths: Vec> = Vec::new(); + let as_path = |c: &[Seg]| -> Vec { + c.iter().map(|s| if s.line { PathSeg::Line(Line::new(s.c.p0, s.c.p3)) } else { PathSeg::Cubic(s.c) }).collect() + }; + let reversed = |c: &[PathSeg]| -> Vec { c.iter().rev().map(|s| s.reverse()).collect() }; let sig = |c: &[Seg]| -> (Point, Point, Point) { let a = c[0].c.p0; let b = c[c.len() - 1].c.p3; @@ -1068,6 +1122,7 @@ fn outline_edges(arr: &Arrangement, shapes: &[Shape]) -> Vec { let mut grid: HashMap<(i64, i64), Vec> = HashMap::new(); for (chain, key) in chains { let (a, b, m) = sig(&chain); + let path = as_path(&chain); let (cx, cy) = cell(m); let found = (cx - 1..=cx + 1) .flat_map(|x| (cy - 1..=cy + 1).map(move |y| (x, y))) @@ -1076,7 +1131,21 @@ fn outline_edges(arr: &Arrangement, shapes: &[Shape]) -> Vec { .copied() .filter(|&i| { let (a2, b2, m2) = sigs[i]; - near(m, m2) && ((near(a, a2) && near(b, b2)) || (near(a, b2) && near(b, a2))) + let other = &paths[i]; + let same = near(a, a2) && near(b, b2); + let opposite = near(a, b2) && near(b, a2); + if !near(m, m2) || !(same || opposite) { + return false; + } + // A chain whose ends meet matches both ways round; the end of its first piece shows + // which way the other runs. `along_closely` takes chains that run opposite ways. + let runs_same = same + && (!opposite + || match (path.first(), other.first(), other.last()) { + (Some(p), Some(f), Some(l)) => p.end().distance(f.end()) <= p.end().distance(l.start()), + _ => true, + }); + if runs_same { along_closely(&path, &reversed(other), d) } else { along_closely(&path, other, d) } }) .min(); match found { @@ -1084,6 +1153,7 @@ fn outline_edges(arr: &Arrangement, shapes: &[Shape]) -> Vec { None => { grid.entry((cx, cy)).or_default().push(out.len()); sigs.push((a, b, m)); + paths.push(path); out.push((chain, key)); } } @@ -1711,4 +1781,41 @@ mod tests { assert_eq!(merged.len(), 40); assert!(merged.iter().enumerate().all(|(k, s)| s.key == k as u64)); } + + /// A curve with the ends of a line that passes within 0.25 pt of the line's middle, and whose + /// own middle is within 0.25 pt of the line, but which runs about 23 pt past the line's start: + /// the middles and ends of the two pieces match, and the two are still not one edge. + #[test] + fn along_closely_checks_curves_between_the_middles_of_their_pieces() { + let line = [PathSeg::Line(Line::new((100.0, 0.0), (0.0, 0.0)))]; + let curve = [PathSeg::Cubic(kurbo::CubicBez::new((0.0, 0.0), (-54.56, 0.4537), (198.85, 0.0963), (100.0, 0.0)))]; + assert!(along(&line, &curve, 0.25), "the middles and ends match"); + assert!(!along_closely(&line, &curve, 0.25)); + assert!(!along_closely(&curve, &line, 0.25)); + let same = [PathSeg::Line(Line::new((0.0, 0.0), (100.0, 0.0)))]; + assert!(along_closely(&line, &same, 0.25)); + } + + /// A curve 1.05 pt from a line at its middle and under 1 pt from it at its thirds: with a + /// control polygon under three times the tolerance long, the samples still take in the middle. + #[test] + fn along_closely_samples_the_middle_of_a_short_piece() { + let line = [PathSeg::Line(Line::new((0.15, 0.0), (0.0, 0.0)))]; + let curve = [PathSeg::Cubic(kurbo::CubicBez::new((0.0, 0.0), (0.05, 1.4), (0.1, 1.4), (0.15, 0.0)))]; + assert!(!along_closely(&curve, &line, 1.0)); + } + + /// Pieces whose control points pair up within the tolerance are one edge, copies included. + #[test] + fn along_closely_takes_pieces_whose_control_points_pair_up() { + let a = [ + PathSeg::Cubic(kurbo::CubicBez::new((0.0, 0.0), (10.0, 20.0), (30.0, 20.0), (40.0, 0.0))), + PathSeg::Line(Line::new((40.0, 0.0), (80.0, 0.0))), + ]; + let reversed: Vec = a.iter().rev().map(|s| s.reverse()).collect(); + assert!(along_closely(&a, &reversed, 0.01)); + let shifted: Vec = reversed.iter().map(|s| kurbo::Affine::translate((0.0, 0.2)) * *s).collect(); + assert!(along_closely(&a, &shifted, 0.25)); + assert!(!along_closely(&a, &shifted, 0.1)); + } } diff --git a/crates/pathops/tests/it/ops.rs b/crates/pathops/tests/it/ops.rs index 60410a0d5d..e26d0e69e9 100644 --- a/crates/pathops/tests/it/ops.rs +++ b/crates/pathops/tests/it/ops.rs @@ -237,6 +237,68 @@ fn pf_outline_dedups_shared_edges() { assert!(close(len, 70.0, 1e-9), "len {len}"); } +/// Outline follows Precision: two bars whose left edges cross a square's top edge 0.00005 pt apart +/// leave a piece of that length between the crossings at the default precision, and none at 10 pt, +/// where the two crossings are one junction. +#[test] +fn pf_outline_joins_junctions_closer_than_the_precision() { + let s = vec![shape(rect(0.0, 0.0, 100.0, 100.0), 1), shape(rect(50.0, 90.0, 10.0, 20.0), 2), shape(rect(50.00005, 95.0, 4.99995, 10.0), 3)]; + let shortest = |r: &[Shape]| r.iter().map(|s| s.path.length()).fold(f64::INFINITY, f64::min); + let length = |r: &[Shape]| r.iter().map(|s| s.path.length()).sum::(); + let at_default = pathfinder_with(PathfinderOp::Outline, &s, DEFAULT_PRECISION); + assert_eq!(at_default, pathfinder(PathfinderOp::Outline, &s)); + assert!(shortest(&at_default) < 1e-4, "{at_default:?}"); + let coarse = pathfinder_with(PathfinderOp::Outline, &s, 10.0); + assert!(shortest(&coarse) > 1e-3, "{coarse:?}"); + assert!(coarse.len() < at_default.len(), "{} pieces at 10 pt, {} at the default", coarse.len(), at_default.len()); + assert!(close(length(&coarse), length(&at_default), 1e-6), "{} against {}", length(&coarse), length(&at_default)); +} + +/// Outline at a tenth of the size and a tenth of the precision gives the same pieces at a tenth of +/// the length: crossings 0.05 pt apart on a 1,000 pt square at 10 pt, and 0.005 pt apart on a 100 pt +/// square at 1 pt, stay two junctions in both. +#[test] +fn pf_outline_scales_with_the_art_and_the_precision_together() { + let art = |k: f64| { + vec![ + shape(rect(0.0, 0.0, 1000.0 * k, 1000.0 * k), 1), + shape(rect(500.0 * k, 900.0 * k, 100.0 * k, 200.0 * k), 2), + shape(rect(500.05 * k, 950.0 * k, 49.95 * k, 100.0 * k), 3), + ] + }; + let length = |r: &[Shape]| r.iter().map(|s| s.path.length()).sum::(); + let large = pathfinder_with(PathfinderOp::Outline, &art(1.0), 10.0); + let small = pathfinder_with(PathfinderOp::Outline, &art(0.1), 1.0); + assert_eq!(large.len(), small.len(), "{large:?}\n{small:?}"); + assert!(close(length(&large) / 10.0, length(&small), 1e-6), "{} against {}", length(&large), length(&small)); + let pieces = |r: &[Shape], k: f64| { + let mut l: Vec = r.iter().map(|s| s.path.length() / k).collect(); + l.sort_by(f64::total_cmp); + l + }; + let (a, b) = (pieces(&large, 1.0), pieces(&small, 0.1)); + assert!(a.iter().zip(&b).all(|(x, y)| close(*x, *y, 1e-6)), "{a:?} against {b:?}"); +} + +/// Two boundaries that are close only at their start, end and middle stay two edges at 10 pt: an +/// ellipse 0.005 pt inside a circle at its rightmost and leftmost points, and 30 pt inside it at +/// the top and bottom. Two copies of one boundary are still one edge at that precision. +#[test] +fn pf_outline_keeps_boundaries_that_differ_between_their_ends_at_coarse_precision() { + let ellipse = |rx: f64, ry: f64| PathData::from_bezpath(&kurbo::Ellipse::new((100.0, 100.0), (rx, ry), 0.0).to_path(1e-4)); + let s = vec![shape(ellipse(50.0, 50.0), 1), shape(ellipse(49.995, 20.0), 2)]; + let length = |r: &[Shape]| r.iter().map(|s| s.path.length()).sum::(); + let expected = s[0].path.length() + s[1].path.length(); + for precision in [DEFAULT_PRECISION, 10.0] { + let r = pathfinder_with(PathfinderOp::Outline, &s, precision); + assert_eq!(r.len(), 2, "{precision} pt: {r:?}"); + assert!(close(length(&r), expected, 1e-6), "{precision} pt: {} against {expected}", length(&r)); + } + let copies = vec![shape(ellipse(50.0, 50.0), 1), shape(ellipse(50.0, 50.0), 2)]; + let r = pathfinder_with(PathfinderOp::Outline, &copies, 10.0); + assert!(close(length(&r), copies[0].path.length(), 1e-6), "{r:?}"); +} + #[test] fn regions_and_region_at() { let s = stack(); diff --git a/crates/plugins/src/import.rs b/crates/plugins/src/import.rs index 599470e0aa..453ed75f41 100644 --- a/crates/plugins/src/import.rs +++ b/crates/plugins/src/import.rs @@ -7,6 +7,10 @@ //! sorts first opens it ([`for_extension`]). File › Open With and `document.open {importer}` pick an //! importer by its format id (`plugin.`), also for an extension a built-in format reads. //! +//! An importer whose manifest sets `place` also reads its files for File › Place (`file.place`), +//! by the same rules among the importers that set it ([`placing`]): its objects become one group in +//! the open document, and it is told so in `_context.mode` ([`Mode::Place`]). +//! //! The host hands the importer the file's bytes as they are, at most [`MAX_INPUT_BYTES`] of them, //! and reads back the objects of the new document in the same form filters return them //! ([`crate::objects`]): `{"objects": [...], "warnings"?: ["…"]}`, or `{"error": "…"}` to decline. @@ -61,6 +65,38 @@ pub fn for_extension(ext: &str) -> Vec> { installed().into_iter().filter(|p| p.manifest().extensions.contains(&ext)).collect() } +/// The installed importers whose manifests set `place` and that list extension `ext` (any case, +/// leading dot allowed), by plug-in id: the first is the one File › Place uses. +pub fn placing(ext: &str) -> Vec> { + for_extension(ext).into_iter().filter(|p| p.manifest().place).collect() +} + +/// The error of importer `m`, whose manifest doesn't set `place`, asked to place a file. +pub fn not_placing(m: &crate::Manifest) -> Error { + let shown = crate::permissions::display_text(&m.name, crate::permissions::MAX_SHOWN_NAME); + Error::Params(format!("“{shown}” opens files but doesn't place them: its manifest doesn't set `place`")) +} + +/// What an import is for, which the importer is told as `_context.mode`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Mode { + /// File › Open: the objects become a new document (`"import"`). + Import, + /// File › Place: the objects become one group in the open document (`"place"`). Only an + /// importer whose manifest sets `place` runs for it. + Place, +} + +impl Mode { + /// Its name in `_context.mode`. + pub fn name(self) -> &'static str { + match self { + Mode::Import => "import", + Mode::Place => "place", + } + } +} + /// What an importer returned. #[derive(Clone, Debug, PartialEq)] pub struct Imported { @@ -93,15 +129,24 @@ pub fn limits(plugin: &Plugin) -> Limits { /// Runs importer `plugin` on `file`, the bytes of the file being opened, with `params` (checked /// against its manifest: missing ones take their defaults) for the file `source`. pub fn run(plugin: &Plugin, file: &[u8], params: &Value, source: Source) -> Result { + run_as(plugin, file, params, source, Mode::Import) +} + +/// [`run`] for `mode`. [`Mode::Place`] is refused for an importer whose manifest doesn't set `place` +/// ([`not_placing`]), before it runs. +pub fn run_as(plugin: &Plugin, file: &[u8], params: &Value, source: Source, mode: Mode) -> Result { let m = plugin.manifest(); if m.kind != Kind::Importer { return Err(not_importer(m)); } + if mode == Mode::Place && !m.place { + return Err(not_placing(m)); + } if file.len() > MAX_INPUT_BYTES { return Err(too_large()); } let mut params = Value::Object(m.resolve_params(params)?); - params["_context"] = json!({"mode": "import", "extension": source.extension, "name": source.name}); + params["_context"] = json!({"mode": mode.name(), "extension": source.extension, "name": source.name}); let params = serde_json::to_vec(¶ms).map_err(|e| Error::Params(e.to_string()))?; decode(&plugin.run_limited(file, ¶ms, &limits(plugin))?) } diff --git a/crates/plugins/src/manifest.rs b/crates/plugins/src/manifest.rs index f20756e149..ddbcb86582 100644 --- a/crates/plugins/src/manifest.rs +++ b/crates/plugins/src/manifest.rs @@ -469,6 +469,11 @@ pub struct Manifest { /// the one an exporter's files get. Only exporters and importers declare them. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub extensions: Vec, + /// An importer whose files File › Place also reads (`file.place`), into the open document as one + /// group ([`crate::import::Mode::Place`]): `true` when the manifest has `"place": true`. Only an + /// importer sets it. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub place: bool, /// How much a run may compute: only a filter may be [`Budget::Heavy`]. #[serde(default, skip_serializing_if = "Budget::is_light")] pub budget: Budget, @@ -517,6 +522,7 @@ impl Manifest { context: Vec::new(), params: Vec::new(), extensions: Vec::new(), + place: false, budget: Budget::Light, paint_output: false, commands: Vec::new(), @@ -590,6 +596,9 @@ impl Manifest { return Err(Error::Manifest("`paintOutput` is only for a live effect (`kind` \"effect\") at `api` 2".into())); } self.validate_extensions()?; + if self.place && self.kind != Kind::Importer { + return Err(Error::Manifest("`place` is only for an importer (`kind` \"importer\")".into())); + } match (self.budget, self.kind) { (Budget::Light, _) | (Budget::Heavy, Kind::Filter) => {} (Budget::Heavy, Kind::Effect) => { @@ -1258,6 +1267,33 @@ mod tests { } } + /// Only an importer sets `place`, to a boolean, and it asks for no permission beyond + /// `import.read`; false, the default, isn't written back. + #[test] + fn only_an_importer_places_its_files() { + let m = Manifest::parse(br#"{"id":"a","name":"x","kind":"importer","extensions":["plt"],"place":true}"#).unwrap(); + assert!(m.place); + assert_eq!(m.permissions(), [Permission::ImportRead]); + assert_eq!(serde_json::to_value(&m).unwrap()["place"], json!(true)); + for open_only in [ + r#"{"id":"a","name":"x","kind":"importer","extensions":["plt"]}"#, + r#"{"id":"a","name":"x","kind":"importer","extensions":["plt"],"place":false}"#, + ] { + let m = Manifest::parse(open_only.as_bytes()).unwrap(); + assert!(!m.place && serde_json::to_value(&m).unwrap().get("place").is_none(), "{open_only}"); + } + for (bad, says) in [ + (r#"{"id":"a","name":"x","kind":"filter","place":true}"#, "`place` is only for an importer"), + (r#"{"id":"a","name":"x","kind":"exporter","extensions":["plt"],"place":true}"#, "`place` is only for an importer"), + (r#"{"id":"a","name":"x","kind":"effect","place":true}"#, "`place` is only for an importer"), + (r#"{"id":"a","name":"x","kind":"importer","extensions":["plt"],"place":"yes"}"#, "invalid type"), + (r#"{"id":"a","name":"x","kind":"importer","extensions":["plt"],"place":1}"#, "invalid type"), + ] { + let e = Manifest::parse(bad.as_bytes()).unwrap_err().to_string(); + assert!(e.contains(says), "{bad}: {e}"); + } + } + /// A filter may ask for a heavy budget; a live effect runs while the document is drawn and an /// exporter has an export's budget, so they can't. Light, the default, isn't written back. #[test] diff --git a/crates/plugins/src/objects.rs b/crates/plugins/src/objects.rs index ad69c25720..4057af3eda 100644 --- a/crates/plugins/src/objects.rs +++ b/crates/plugins/src/objects.rs @@ -38,6 +38,8 @@ pub const MITER_LIMIT: std::ops::RangeInclusive = 1.0..=500.0; pub const MAX_EFFECT_ID: usize = 128; /// Largest data a plug-in may keep with a document (`documentData`), in bytes of JSON. pub const MAX_DOCUMENT_DATA: usize = 1 << 20; +/// Most characters of a filter's `notice` as the host shows it, its escapes counted. +pub const MAX_NOTICE_CHARS: usize = 200; /// Most text a filter is given of one type object, in bytes of UTF-8 over all its runs: longer /// type comes with `truncated` and no runs or paragraphs. pub const MAX_INPUT_TEXT: usize = 256 * 1024; @@ -794,10 +796,12 @@ pub struct Output { /// (what the plug-in keeps stays as it is), `Some(None)` for `null` (it forgets it), else what /// it keeps from now on, at most [`MAX_DOCUMENT_DATA`] bytes of JSON. pub document_data: Option>, + /// `notice`, the run's report for the status bar, as [`decode_notice`] reads it. + pub notice: Option, } -/// Parses a filter's output: `{"objects": [...], "documentData"?: …}`, or `{"error": "message"}` -/// when the plug-in declined (the message reaches the user). +/// Parses a filter's output: `{"objects": [...], "documentData"?: …, "notice"?: "…"}`, or +/// `{"error": "message"}` when the plug-in declined (the message reaches the user). pub fn decode_output(bytes: &[u8]) -> Result { decode_output_with(bytes, &[], &HashMap::new()) } @@ -822,7 +826,70 @@ pub fn decode_output_with(bytes: &[u8], input: &[u8], read_only: &ReadOnlySpans) Some(Some(data)) } }; - Ok(Output { objects, document_data }) + let notice = decode_notice(&v)?; + Ok(Output { objects, document_data, notice }) +} + +/// The `notice` of output `v`: `None` when it has none (or `null`), else its text without the +/// white space around it, as [`crate::permissions::display_text`] shows plug-in text (control, +/// bidirectional formatting and separator characters escaped) and at most [`MAX_NOTICE_CHARS`] +/// characters. A `notice` that is not a string, or whose shown part has no character besides white +/// space, control characters and the default-ignorable characters the host does not escape, is an +/// error. +pub fn decode_notice(v: &Value) -> Result> { + match v.get("notice") { + None | Some(Value::Null) => Ok(None), + Some(Value::String(s)) if shown_part_is_visible(s.trim()) => Ok(Some(crate::permissions::display_text(s.trim(), MAX_NOTICE_CHARS))), + Some(_) => Err(Error::Output("`notice` must be a string with visible text".into())), + } +} + +/// Does the part of notice `s` that [`crate::permissions::display_text`] keeps within +/// [`MAX_NOTICE_CHARS`], escapes counted and room left for the `…` when it cuts, hold a character +/// that draws something? +fn shown_part_is_visible(s: &str) -> bool { + let shows = |c: char| !c.is_whitespace() && !c.is_control() && !draws_nothing(c); + let width = |c: char| crate::permissions::display_text(c.encode_utf8(&mut [0; 4]), usize::MAX).chars().count(); + // Characters written through the end of `c`, and through the first visible character. + let mut used = 0; + let mut visible_by = None; + for c in s.chars() { + used += width(c); + if visible_by.is_none() && shows(c) { + visible_by = Some(used); + } + if used > MAX_NOTICE_CHARS { + break; + } + } + visible_by.is_some_and(|end| used <= MAX_NOTICE_CHARS || end < MAX_NOTICE_CHARS) +} + +/// Is `c` one of Unicode's default-ignorable characters (soft hyphen, zero-width and invisible +/// characters, fillers, variation selectors, tags) that [`crate::permissions::display_text`] keeps +/// as it is, so it draws nothing? The bidirectional ones it escapes are not among them. +fn draws_nothing(c: char) -> bool { + matches!( + c, + '\u{00AD}' + | '\u{034F}' + | '\u{115F}' + | '\u{1160}' + | '\u{17B4}' + | '\u{17B5}' + | '\u{180B}'..='\u{180F}' + | '\u{200B}'..='\u{200D}' + | '\u{2060}'..='\u{2065}' + | '\u{206A}'..='\u{206F}' + | '\u{3164}' + | '\u{FE00}'..='\u{FE0F}' + | '\u{FEFF}' + | '\u{FFA0}' + | '\u{FFF0}'..='\u{FFF8}' + | '\u{1BCA0}'..='\u{1BCA3}' + | '\u{1D173}'..='\u{1D17A}' + | '\u{E0000}'..='\u{E0FFF}' + ) } /// Parses a plug-in's objects: `{"objects": [...]}`, or `{"error": "message"}` when the plug-in diff --git a/crates/plugins/src/objects/tests.rs b/crates/plugins/src/objects/tests.rs index 58159c3370..39d2d78776 100644 --- a/crates/plugins/src/objects/tests.rs +++ b/crates/plugins/src/objects/tests.rs @@ -1172,3 +1172,52 @@ fn document_data_is_kept_forgotten_or_refused() { // A decline is still a decline. assert!(matches!(decode_output(br#"{"error": "No pens.", "documentData": 1}"#), Err(Error::Failed(_)))); } + +/// A filter's `notice`: absent or `null` is none; a string is trimmed, its control, bidirectional +/// and separator characters escaped, and cut at [`MAX_NOTICE_CHARS`] with an ellipsis; anything +/// else, and text with nothing visible, refuses the whole output. +#[test] +fn notice_is_escaped_capped_and_checked() { + let out = |notice: Option| { + let mut v = json!({"objects": []}); + if let Some(n) = notice { + v["notice"] = n; + } + decode_output(v.to_string().as_bytes()).map(|o| o.notice) + }; + assert_eq!(out(None).unwrap(), None); + assert_eq!(out(Some(Value::Null)).unwrap(), None); + assert_eq!(out(Some(json!(" Selected 12 objects \n"))).unwrap().as_deref(), Some("Selected 12 objects")); + let shown = out(Some(json!("Saved\u{202E}txt.exe\nError: disk full\u{7}"))).unwrap().unwrap_or_default(); + assert_eq!(shown, "Saved\\u{202E}txt.exe\\u{000A}Error: disk full\\u{0007}"); + let long = out(Some(json!("y".repeat(10_000)))).unwrap().unwrap_or_default(); + assert_eq!(long.chars().count(), MAX_NOTICE_CHARS); + assert!(long.ends_with('…')); + // Escapes count toward the limit, so a notice of right-to-left overrides stays within it too. + let escaped = out(Some(json!("\u{202E}".repeat(10_000)))).unwrap().unwrap_or_default(); + assert!(escaped.chars().count() <= MAX_NOTICE_CHARS && !escaped.contains('\u{202E}'), "{escaped}"); + for bad in [ + json!(""), + json!(" \t\n "), + json!("\u{200B}\u{FEFF}"), + json!("\u{034F}"), + json!("\u{3164}\u{FE0F}\u{E0041}"), + // The visible text comes after the cut, so the status bar would show only the `…`. + json!(format!("{}AB", "\u{200B}".repeat(MAX_NOTICE_CHARS - 1))), + json!(format!("{}A", "\u{7}".repeat(MAX_NOTICE_CHARS / 8))), + json!(12), + json!(["a"]), + json!({"text": "a"}), + json!(true), + ] { + assert!(matches!(out(Some(bad.clone())), Err(Error::Output(ref e)) if e.contains("`notice`")), "{bad}"); + } + // Text with a visible character keeps the invisible ones, and its bidirectional ones escaped. + assert_eq!(out(Some(json!("\u{2067}Done\u{034F}"))).unwrap().as_deref(), Some("\\u{2067}Done\u{034F}")); + // A visible character in the last place the limit shows, whole or before the `…`, is enough. + let pad = "\u{200B}".repeat(MAX_NOTICE_CHARS - 2); + assert_eq!(out(Some(json!(format!("{pad}\u{200B}A")))).unwrap(), Some(format!("{pad}\u{200B}A"))); + assert_eq!(out(Some(json!(format!("{pad}ABC")))).unwrap(), Some(format!("{pad}A…"))); + // A decline is still a decline. + assert!(matches!(decode_output(br#"{"error": "No pens.", "notice": "Done"}"#), Err(Error::Failed(_)))); +} diff --git a/crates/plugins/src/painted.rs b/crates/plugins/src/painted.rs index 484e761677..e7ed51e225 100644 --- a/crates/plugins/src/painted.rs +++ b/crates/plugins/src/painted.rs @@ -47,8 +47,8 @@ pub enum Scope { } /// Parses and checks a painted result: `{"objects": [...]}`, or `{"error": "message"}` when the -/// plug-in declined. `rule` is the fill rule a piece without `fillRule` takes. Any other top-level -/// key, an unknown key in a piece, stroke or paint, a list or count past its limit, a number out of +/// plug-in declined. `rule` is the fill rule a piece without `fillRule` takes. A top-level `notice` +/// is ignored. Any other top-level key, an unknown key in a piece, stroke or paint, a list or count past its limit, a number out of /// range or a paint of the wrong form refuses the whole result, naming the field. pub fn decode(bytes: &[u8], scope: Scope, rule: FillRule) -> Result> { let v: Value = serde_json::from_slice(bytes).map_err(|e| out_err("output", format!("not JSON: {e}")))?; @@ -56,8 +56,8 @@ pub fn decode(bytes: &[u8], scope: Scope, rule: FillRule) -> Result> return Err(e); } let top = v.as_object().ok_or_else(|| out_err("output", "expected {\"objects\": [...]}"))?; - if let Some(k) = top.keys().find(|k| !matches!(k.as_str(), "objects" | "error")) { - return Err(out_err(k, "a painted live effect returns only `objects`")); + if let Some(k) = top.keys().find(|k| !matches!(k.as_str(), "objects" | "error" | "notice")) { + return Err(out_err(k, "a painted live effect returns only `objects` and `notice`")); } let objects = top.get("objects").and_then(Value::as_array).ok_or_else(|| out_err("objects", "expected {\"objects\": [...]}"))?; if objects.len() > MAX_OBJECTS { diff --git a/crates/plugins/src/painted/tests.rs b/crates/plugins/src/painted/tests.rs index 59acf18521..471c12ea48 100644 --- a/crates/plugins/src/painted/tests.rs +++ b/crates/plugins/src/painted/tests.rs @@ -154,6 +154,21 @@ fn faults_refuse_the_whole_result_by_field() { assert_eq!(declined, Error::Failed("nothing to do".into())); } +/// A top-level `notice` is ignored, as a filter-only key a live effect may hand back; other +/// unknown top-level keys still refuse the result. +#[test] +fn a_notice_is_ignored_and_other_top_level_keys_refused() { + let ok = json!({"path": square(), "fills": [red()]}); + let decode_top = |top: Value| decode(&serde_json::to_vec(&top).unwrap(), Scope::Object, FillRule::NonZero); + let pieces = decode_top(json!({"objects": [ok], "notice": "Done"})).unwrap(); + assert_eq!(pieces.len(), 1); + assert_eq!(decode_top(json!({"objects": [ok], "notice": 12})).unwrap().len(), 1); + for key in ["note", "notices", "message"] { + let e = decode_top(json!({"objects": [ok], key: "Done"})).unwrap_err().to_string(); + assert!(e.contains(&format!("{key}:")) && e.contains("returns only `objects` and `notice`"), "{key}: {e}"); + } +} + /// A key a paint does not have, at any level of it, refuses the result and is named; it is not /// dropped. #[test] diff --git a/crates/render/src/encode/quantize.rs b/crates/render/src/encode/quantize.rs index cad3127abd..ae2a5c2fdc 100644 --- a/crates/render/src/encode/quantize.rs +++ b/crates/render/src/encode/quantize.rs @@ -1,8 +1,9 @@ //! Colour reduction for palette formats (PNG-8, GIF): a palette of at most 256 colours chosen by //! median cut over a 15-bit histogram (refined by a few k-means passes) or a fixed palette, then //! each pixel mapped to its nearest entry with optional dithering (Floyd–Steinberg diffusion, an -//! 8×8 ordered pattern, or noise). Pixels under half opacity can become one transparent entry; -//! the others are blended over the matte colour. +//! 8×8 ordered pattern, or noise). Pixels under half opacity can become one transparent entry, or +//! with a transparency dither a share of the partly transparent pixels that follows their +//! opacity; the others are blended over the matte color. use std::collections::HashMap; @@ -111,11 +112,18 @@ pub struct PaletteOptions { pub dither: Dither, /// Dither strength 0–100. pub dither_amount: u8, - /// Pixels under half opacity become a transparent entry; otherwise every pixel is opaque. + /// Pixels under half opacity become a transparent entry (see `transparency_dither`); + /// otherwise every pixel is opaque. pub transparency: bool, /// The colour partly transparent pixels are blended over. `None`: with transparency, they /// keep their own colour (hard edges); without, white. pub matte: Option<[u8; 3]>, + /// With `transparency`, how partly transparent pixels are split between the transparent entry + /// and their color ([`clear_mask`]); `Dither::None` cuts them at half opacity. + pub transparency_dither: Dither, + /// The strength of the diffusion transparency dither, 0–100 (0 cuts at half opacity); the + /// pattern and noise methods do not use it. + pub transparency_dither_amount: u8, } impl Default for PaletteOptions { @@ -127,6 +135,8 @@ impl Default for PaletteOptions { dither_amount: 100, transparency: true, matte: Some([255; 3]), + transparency_dither: Dither::None, + transparency_dither_amount: 100, } } } @@ -153,12 +163,12 @@ pub fn quantize(rgba: &[u8], width: u32, height: u32, o: &PaletteOptions) -> Ind /// them all anyway; locked colours no pixel ends up using are left out. pub fn quantize_locked(rgba: &[u8], width: u32, height: u32, o: &PaletteOptions, locked: &[[u8; 3]]) -> Indexed { let px = rgba.as_chunks::<4>().0; - let clear = |p: &[u8; 4]| o.transparency && p[3] < 128; + let clear = clear_mask(rgba, width, o); let matte = o.matte.unwrap_or([255; 3]); let colors = opaque_colors(px, o, matches!(o.reduction, Reduction::Gray | Reduction::BlackWhite)); - let has_clear = px.iter().any(clear); + let has_clear = clear.contains(&true); let k = (o.colors.clamp(2, 256) as usize - usize::from(has_clear)).max(1); - let opaque = || colors.iter().zip(px).filter(|(_, p)| !clear(p)).map(|(c, _)| *c); + let opaque = || colors.iter().zip(&clear).filter(|(_, c)| !**c).map(|(c, _)| *c); // Locked colours take their slots first (at least one is left for the reduction). let mut lock: Vec<[u8; 3]> = Vec::with_capacity(locked.len().min(k)); for c in locked { @@ -168,6 +178,22 @@ pub fn quantize_locked(rgba: &[u8], width: u32, height: u32, o: &PaletteOptions, } let free = k - lock.len(); let (mut palette, exact) = match o.reduction { + // With one entry left (two colors and a transparent entry, or the others locked): black or + // white, whichever leaves the opaque pixels nearer the palette, the locked colors included. + Reduction::BlackWhite if free < 2 => { + let mut hist = [0u64; 256]; + for c in opaque() { + hist[c[0] as usize] += 1; + } + let w = o.reduction.weights(); + let cost = |end: [u8; 3]| -> f32 { + let entries: Vec<[f32; 3]> = lock.iter().chain([&end]).map(|c| c.map(f32::from)).collect(); + let near = |g: f32| entries.iter().map(|&e| dist([g; 3], e, w)).fold(f32::INFINITY, f32::min); + hist.iter().enumerate().filter(|(_, n)| **n > 0).map(|(g, &n)| n as f32 * near(g as f32)).sum() + }; + let ends = [[0; 3], [255; 3]].into_iter().filter(|c| !lock.contains(c)); + (ends.min_by(|a, b| cost(*a).total_cmp(&cost(*b))).into_iter().collect(), false) + } Reduction::BlackWhite => (vec![[0; 3], [255; 3]], false), Reduction::Gray => ((0..free).map(|i| [(i * 255 / (free - 1).max(1)) as u8; 3]).collect(), false), Reduction::Web => (web(opaque(), free), false), @@ -185,7 +211,7 @@ pub fn quantize_locked(rgba: &[u8], width: u32, height: u32, o: &PaletteOptions, if palette.is_empty() { palette.push(matte); } - finish(px, &colors, width, height, &palette, o, if exact { Dither::None } else { o.dither }) + finish(&clear, &colors, width, height, &palette, o, if exact { Dither::None } else { o.dither }) } /// [`quantize`] to the fixed `palette`: each pixel takes its nearest entry, with `o`'s dither, @@ -195,26 +221,92 @@ pub fn quantize_locked(rgba: &[u8], width: u32, height: u32, o: &PaletteOptions, pub fn quantize_to(rgba: &[u8], width: u32, height: u32, o: &PaletteOptions, palette: &[[u8; 3]]) -> Indexed { let px = rgba.as_chunks::<4>().0; let colors = opaque_colors(px, o, false); - let has_clear = o.transparency && px.iter().any(|p| p[3] < 128); + let clear = clear_mask(rgba, width, o); + let has_clear = clear.contains(&true); let mut palette: Vec<[u8; 3]> = palette.iter().take(256 - usize::from(has_clear)).copied().collect(); if palette.is_empty() { palette.push(o.matte.unwrap_or([255; 3])); } - finish(px, &colors, width, height, &palette, o, o.dither) + finish(&clear, &colors, width, height, &palette, o, o.dither) } -/// For each pixel of `rgba`, the entry of `palette` nearest its color, as [`quantize_to`] measures -/// it (the matte, transparency and `o.reduction`'s distance weights) without dither; `None` for a -/// pixel that becomes transparent, and for every pixel when `palette` is empty. `f` gets each -/// pixel's entry in pixel order, worked out one pixel at a time. -pub fn nearest_entries(rgba: &[u8], o: &PaletteOptions, palette: &[[u8; 3]], mut f: impl FnMut(Option)) { +/// For each pixel of `rgba` (`width` pixels a row), the entry of `palette` nearest its color, as +/// [`quantize_to`] measures it (the matte, transparency and `o.reduction`'s distance weights) +/// without dither; `None` for a pixel that becomes transparent ([`clear_mask`]), and for every +/// pixel when `palette` is empty. `f` gets each pixel's entry in pixel order, worked out one pixel +/// at a time. +pub fn nearest_entries(rgba: &[u8], width: u32, o: &PaletteOptions, palette: &[[u8; 3]], mut f: impl FnMut(Option)) { + let clear = clear_mask(rgba, width, o); let pal: Vec<[f32; 3]> = palette.iter().map(|c| c.map(f32::from)).collect(); let index = PaletteIndex::new(&pal, o.reduction.weights()); - for p in rgba.as_chunks::<4>().0 { - f(if pal.is_empty() || (o.transparency && p[3] < 128) { None } else { Some(index.nearest(opaque_color(p, o, false).map(f32::from))) }); + for (p, &clear) in rgba.as_chunks::<4>().0.iter().zip(&clear) { + f(if pal.is_empty() || clear { None } else { Some(index.nearest(opaque_color(p, o, false).map(f32::from))) }); } } +/// Which pixels of `rgba` (`width` pixels a row) become the transparent entry. Without +/// `o.transparency`, none. Otherwise fully transparent pixels always do and opaque ones never; a +/// partly transparent pixel does under half opacity with no transparency dither, and else by +/// `o.transparency_dither`. With pattern, noise, or diffusion at amount 100, about as many of an +/// area's pixels stay opaque as its opacity says; a lower diffusion amount moves the result toward +/// the cut at half opacity. Diffusion spreads each partly transparent pixel's opacity error to the +/// pixels right of it and below it (Floyd–Steinberg, scaled by `o.transparency_dither_amount`), and +/// fully transparent and opaque pixels pass on the error they receive; pattern compares the +/// opacity with the 8×8 ordered pattern and noise with a noise threshold. The result depends only +/// on the pixels and the options, so exports are reproducible. +pub fn clear_mask(rgba: &[u8], width: u32, o: &PaletteOptions) -> Vec { + let px = rgba.as_chunks::<4>().0; + if !o.transparency { + return vec![false; px.len()]; + } + let width = (width as usize).min(px.len()).max(1); + let amount = f32::from(o.transparency_dither_amount.min(100)) / 100.0; + let dither = match o.transparency_dither { + Dither::Diffusion if amount == 0.0 => Dither::None, + d => d, + }; + // Two rows of opacity error for diffusion (the current one and the next), one pixel of margin + // on each side. + let mut err = vec![0f32; if dither == Dither::Diffusion { 2 * (width + 2) } else { 0 }]; + let half = err.len() / 2; + let mut out = Vec::with_capacity(px.len()); + for (y, row) in px.chunks(width).enumerate() { + let (cur, next) = err.split_at_mut(half); + next.fill(0.0); + for (x, p) in row.iter().enumerate() { + let a = f32::from(p[3]); + let clear = match (p[3], dither) { + (0, _) => true, + (255, _) => false, + (_, Dither::None) => p[3] < 128, + (_, Dither::Pattern) => a < 255.0 * bayer(x % 8, y % 8), + // Another noise than the color dither's, so the two do not line up. + (_, Dither::Noise) => a < 255.0 * noise(x ^ 0x5a5a, y ^ 0xa5a5), + (_, Dither::Diffusion) => a + cur[x + 1] < 127.5, + }; + if dither == Dither::Diffusion { + // A partly transparent pixel spreads its own opacity error. A fully transparent or + // opaque pixel keeps its state and passes on the error it received unchanged, so + // the partly transparent pixels around it keep their share of opacity + // (VectorCraft's own rule). + let got = cur[x + 1]; + let e = match p[3] { + 0 | 255 => got, + _ => (a + got - if clear { 0.0 } else { 255.0 }) * amount, + }; + // 7/16 right, 3/16 below left, 5/16 below, 1/16 below right. + cur[x + 2] += e * 7.0 / 16.0; + next[x] += e * 3.0 / 16.0; + next[x + 1] += e * 5.0 / 16.0; + next[x + 2] += e / 16.0; + } + out.push(clear); + } + cur.copy_from_slice(next); + } + out +} + /// The color of each pixel when opaque: blended over the matte, and gray when `gray`. fn opaque_colors(px: &[[u8; 4]], o: &PaletteOptions, gray: bool) -> Vec<[u8; 3]> { px.iter().map(|p| opaque_color(p, o, gray)).collect() @@ -229,20 +321,20 @@ fn opaque_color(p: &[u8; 4], o: &PaletteOptions, gray: bool) -> [u8; 3] { if gray { [luma(c); 3] } else { c } } -/// Map the pixels `px` (their opaque `colors`) to `palette` with `dither`, then drop the entries -/// no pixel uses and put the transparent entry first when a pixel is transparent. -fn finish(px: &[[u8; 4]], colors: &[[u8; 3]], width: u32, height: u32, palette: &[[u8; 3]], o: &PaletteOptions, dither: Dither) -> Indexed { - let clear = |p: &[u8; 4]| o.transparency && p[3] < 128; +/// Map the pixels (their opaque `colors`, transparent where `clear` says) to `palette` with +/// `dither`, then drop the entries no pixel uses and put the transparent entry first when a pixel +/// is transparent. +fn finish(clear: &[bool], colors: &[[u8; 3]], width: u32, height: u32, palette: &[[u8; 3]], o: &PaletteOptions, dither: Dither) -> Indexed { + let clear = |i: usize| clear.get(i).copied().unwrap_or(false); let matte = o.matte.unwrap_or([255; 3]); - let has_clear = px.iter().any(clear); + let has_clear = (0..colors.len()).any(clear); let weights = o.reduction.weights(); // (A width past the pixels there are would size the error rows from a number nothing checked.) - let mut indices = - map(colors, (width as usize).min(colors.len()), palette, weights, dither, f32::from(o.dither_amount.min(100)) / 100.0, |i| clear(&px[i])); + let mut indices = map(colors, (width as usize).min(colors.len()), palette, weights, dither, f32::from(o.dither_amount.min(100)) / 100.0, clear); // Drop the entries no pixel uses (fixed palettes), keeping the order. let mut used = [false; 256]; for (i, &ix) in indices.iter().enumerate() { - if !clear(&px[i]) { + if !clear(i) { used[ix as usize] = true; } } @@ -258,7 +350,7 @@ fn finish(px: &[[u8; 4]], colors: &[[u8; 3]], width: u32, height: u32, palette: } } for (i, ix) in indices.iter_mut().enumerate() { - *ix = if clear(&px[i]) { 0 } else { remap[*ix as usize] }; + *ix = if clear(i) { 0 } else { remap[*ix as usize] }; } Indexed { width, height, palette: kept, transparent: has_clear.then_some(0), indices } } diff --git a/crates/render/src/encode/tests_palette.rs b/crates/render/src/encode/tests_palette.rs index d9a8a2fc0f..837c62f359 100644 --- a/crates/render/src/encode/tests_palette.rs +++ b/crates/render/src/encode/tests_palette.rs @@ -3,7 +3,7 @@ use vectorcraft_doc::{Appearance, Node}; use vectorcraft_geom::shapes; use super::png::{PngOptions, encode_indexed}; -use super::quantize::{Dither, Indexed, PaletteOptions, Reduction, quantize, quantize_to}; +use super::quantize::{Dither, Indexed, PaletteOptions, Reduction, clear_mask, nearest_entries, quantize, quantize_to}; use super::*; /// A `w`×`h` opaque image of `f(x, y)` colours. @@ -71,7 +71,7 @@ fn colours_cap_the_palette() { let px = ramps(64, 48); for colors in [2, 16, 64, 256] { for dither in Dither::ALL { - for reduction in [Reduction::Perceptual, Reduction::Selective, Reduction::Adaptive, Reduction::Web, Reduction::Gray] { + for reduction in Reduction::ALL { let ix = quantize(&px, 64, 48, &PaletteOptions { colors, dither, reduction, ..Default::default() }); assert!(ix.palette.len() <= colors as usize, "{colors} {dither:?} {reduction:?}: {}", ix.palette.len()); assert!(ix.indices.iter().all(|&i| (i as usize) < ix.palette.len())); @@ -252,3 +252,104 @@ fn ids_round_trip() { assert_eq!(Dither::from_id(d.id()), Some(d)); } } + +/// A `w`×`h` red image whose pixels have the opacity `alpha(x, y)`. +fn see_through(w: u32, h: u32, alpha: impl Fn(u32, u32) -> u8) -> Vec { + (0..h).flat_map(|y| (0..w).map(move |x| (x, y))).flat_map(|(x, y)| [255, 0, 0, alpha(x, y)]).collect() +} + +/// The share of the pixels of `ix` that are not transparent. +fn opaque_share(ix: &Indexed) -> f64 { + ix.indices.iter().filter(|&&i| ix.transparent != Some(i)).count() as f64 / ix.indices.len() as f64 +} + +fn alpha_dither(d: Dither, amount: u8) -> PaletteOptions { + PaletteOptions { transparency_dither: d, transparency_dither_amount: amount, ..Default::default() } +} + +#[test] +fn transparency_dither_keeps_about_as_many_pixels_as_their_opacity() { + let (w, h) = (32, 32); + for alpha in [64u8, 128, 191] { + let px = see_through(w, h, |_, _| alpha); + // No transparency dither cuts at half opacity, and so does Diffusion at 0. + let none = quantize(&px, w, h, &alpha_dither(Dither::None, 100)); + assert_eq!(opaque_share(&none), if alpha < 128 { 0.0 } else { 1.0 }, "none at {alpha}"); + assert_eq!(quantize(&px, w, h, &alpha_dither(Dither::Diffusion, 0)), none, "diffusion at 0, {alpha}"); + for d in [Dither::Diffusion, Dither::Pattern, Dither::Noise] { + let ix = quantize(&px, w, h, &alpha_dither(d, 100)); + let share = opaque_share(&ix); + assert!((share - f64::from(alpha) / 255.0).abs() < 0.08, "{d:?} at {alpha}: {share}"); + assert_eq!(ix.transparent, Some(0), "{d:?} at {alpha}"); + // The same pixels and options give the same image. + assert_eq!(quantize(&px, w, h, &alpha_dither(d, 100)), ix, "{d:?} at {alpha}"); + // A fixed palette and the nearest entries make the same pixels transparent. + let fixed = quantize_to(&px, w, h, &alpha_dither(d, 100), &[[255, 0, 0], [0, 0, 255]]); + assert_eq!(opaque_share(&fixed), share, "{d:?} at {alpha}, fixed palette"); + let mut near = Vec::new(); + nearest_entries(&px, w, &alpha_dither(d, 100), &[[255, 0, 0]], |n| near.push(n)); + let mask = clear_mask(&px, w, &alpha_dither(d, 100)); + assert_eq!(near.iter().map(Option::is_none).collect::>(), mask, "{d:?} at {alpha}"); + } + // Diffusion at half strength keeps fewer pixels of a light area opaque than at full. + if alpha < 128 { + let half = opaque_share(&quantize(&px, w, h, &alpha_dither(Dither::Diffusion, 50))); + let full = opaque_share(&quantize(&px, w, h, &alpha_dither(Dither::Diffusion, 100))); + assert!(0.0 < half && half < full, "{alpha}: {half} {full}"); + } + } + // The methods arrange the pixels differently. + let px = see_through(w, h, |_, _| 96); + let masks: Vec> = [Dither::Diffusion, Dither::Pattern, Dither::Noise].map(|d| clear_mask(&px, w, &alpha_dither(d, 100))).into(); + assert!(masks[0] != masks[1] && masks[1] != masks[2] && masks[0] != masks[2]); +} + +#[test] +fn transparency_dither_leaves_clear_and_opaque_pixels_and_needs_transparency() { + let (w, h) = (16, 8); + // Fully transparent on the left, opaque on the right: every method keeps them as they are. + let hard = see_through(w, h, |x, _| if x < 8 { 0 } else { 255 }); + let none = clear_mask(&hard, w, &alpha_dither(Dither::None, 100)); + assert_eq!(none.iter().filter(|c| **c).count(), 64); + for d in Dither::ALL { + assert_eq!(clear_mask(&hard, w, &alpha_dither(d, 100)), none, "{d:?}"); + } + // Without transparency nothing is transparent, whatever the transparency dither. + let soft = see_through(w, h, |x, _| (x * 16) as u8); + for d in Dither::ALL { + let o = PaletteOptions { transparency: false, ..alpha_dither(d, 100) }; + assert!(!clear_mask(&soft, w, &o).contains(&true), "{d:?}"); + assert_eq!(quantize(&soft, w, h, &o).transparent, None, "{d:?}"); + } + // A palette of two entries keeps one for the transparent pixels and one for the others. + let o = PaletteOptions { colors: 2, ..alpha_dither(Dither::Pattern, 100) }; + let ix = quantize(&see_through(w, h, |_, _| 128), w, h, &o); + assert_eq!((ix.palette.len(), ix.transparent), (2, Some(0))); + // So does Black & White, with black and white pixels both left opaque. + let bw = PaletteOptions { reduction: Reduction::BlackWhite, matte: None, ..o }; + let px: Vec = (0..64u32).flat_map(|i| if i % 8 < 4 { [0, 0, 0, 128] } else { [255, 255, 255, 128] }).collect(); + let ix = quantize(&px, 8, 8, &bw); + assert_eq!(ix.transparent, Some(0)); + assert!(ix.palette.len() <= 2, "{:?}", ix.palette); + // No pixels, and a width past the pixels there are. + assert!(clear_mask(&[], 0, &alpha_dither(Dither::Diffusion, 100)).is_empty()); + assert_eq!(clear_mask(&see_through(3, 1, |_, _| 200), 1000, &alpha_dither(Dither::Diffusion, 100)).len(), 3); +} + +#[test] +fn transparency_diffusion_passes_error_through_clear_and_opaque_pixels() { + // Half-opaque pixels between fully transparent or fully opaque ones, in one row and in a + // checkerboard: about half of them stay opaque, and the others keep their state. + for other in [0u8, 255] { + for (w, h, half) in [(64, 1, (|x, _| x % 2 == 0) as fn(u32, u32) -> bool), (32, 32, |x, y| (x + y) % 2 == 0)] { + let px = see_through(w, h, |x, y| if half(x, y) { 128 } else { other }); + let mask = clear_mask(&px, w, &alpha_dither(Dither::Diffusion, 100)); + let at = |x: u32, y: u32| mask[(y * w + x) as usize]; + let cells: Vec<(u32, u32)> = (0..h).flat_map(|y| (0..w).map(move |x| (x, y))).collect(); + assert!(cells.iter().filter(|&&(x, y)| !half(x, y)).all(|&(x, y)| at(x, y) == (other == 0)), "{other} {w}x{h}"); + let halves: Vec<_> = cells.iter().filter(|&&(x, y)| half(x, y)).collect(); + let share = halves.iter().filter(|&&&(x, y)| !at(x, y)).count() as f64 / halves.len() as f64; + assert!((share - 128.0 / 255.0).abs() < 0.1, "{other} {w}x{h}: {share}"); + } + } +} diff --git a/crates/render/src/encode/tests_web.rs b/crates/render/src/encode/tests_web.rs index 79e36b3f5f..3eb10c364b 100644 --- a/crates/render/src/encode/tests_web.rs +++ b/crates/render/src/encode/tests_web.rs @@ -22,6 +22,15 @@ fn locked_colours_survive_a_reduction() { let ix = quantize_locked(&px, 64, 16, &o, &[rare]); assert!(ix.palette.contains(&rare) && ix.palette.len() <= 4, "{:?}", ix.palette); assert_eq!(colours(&ix)[0], rare); + // Black & White with black locked and one entry left: white takes it, though most pixels are black. + let px = image(8, 8, |x, _| if x == 7 { [255; 3] } else { [0; 3] }); + let o = PaletteOptions { colors: 2, dither: Dither::None, reduction: Reduction::BlackWhite, ..Default::default() }; + let ix = quantize_locked(&px, 8, 8, &o, &[[0; 3]]); + assert_eq!(ix.palette, [[0; 3], [255; 3]]); + // With a light gray locked, black takes the entry left, though most pixels are white. + let px = image(10, 1, |x, _| if x < 4 { [0; 3] } else { [255; 3] }); + let ix = quantize_locked(&px, 10, 1, &o, &[[200; 3]]); + assert_eq!(ix.palette, [[200; 3], [0; 3]]); } #[test] diff --git a/crates/render/src/proof.rs b/crates/render/src/proof.rs index ed38102f61..d8e3aae26d 100644 --- a/crates/render/src/proof.rs +++ b/crates/render/src/proof.rs @@ -669,6 +669,5 @@ pub fn active_proof() -> Option { /// Whether [`RenderOptions::overprint_preview`] should be on (Separations Preview implies it). pub fn overprint_preview_on() -> bool { - let v = view(); - v.overprint || v.separations.is_some() + VIEW.read().unwrap_or_else(|e| e.into_inner()).as_ref().is_some_and(|v| v.overprint || v.separations.is_some()) } diff --git a/crates/tools/src/addons.rs b/crates/tools/src/addons.rs index db983759b9..d62bc0bd62 100644 --- a/crates/tools/src/addons.rs +++ b/crates/tools/src/addons.rs @@ -1,9 +1,9 @@ //! The tools of VectorCraft's built-in add-ons. They aren't in the toolbars as they ship: the All //! Tools drawer lists them (under their add-on's heading) so they can be added, and each add-on's -//! submenu selects them. Tool gestures emit engine commands. Two tools are the exceptions: the Trim -//! at Crossings Tool is in the Scissors tool's group and the Enclosing Lasso Tool is in the Lasso -//! tool's group ([`crate::TOOL_GROUPS`]), where the toolbars and the All Tools drawer show them, as -//! well as in their add-ons' submenus. +//! submenu selects them. Tool gestures emit engine commands. Three tools are the exceptions: the +//! Trim at Crossings Tool is in the Scissors tool's group, the Enclosing Lasso Tool is in the Lasso +//! tool's group and the Smart Pen Tool is in the Pen tool's group ([`crate::TOOL_GROUPS`]), where +//! the toolbars and the All Tools drawer show them, as well as in their add-ons' submenus. pub mod anchor_eraser; pub mod box3d; @@ -35,9 +35,6 @@ pub const PATH_TOOLS: &[ToolInfo] = &[ ToolInfo { id: tangent_circle::ID, label: "Tangent Circle Tool", shortcut: None, icon: "dc-tangent-circle" }, ]; -/// Smart Pen's tool, a flyout group of its own. -pub const SMART_PEN: &[ToolInfo] = &[ToolInfo { id: smart_pen::ID, label: "Smart Pen Tool", shortcut: None, icon: "spline-pointer" }]; - pub const CONTOUR: &[ToolInfo] = &[ToolInfo { id: contour::ID, label: "Contour Tool", shortcut: None, icon: "tool-contour" }]; pub const BOX_3D: &[ToolInfo] = &[ToolInfo { id: box3d::ID, label: "3D Box Tool", shortcut: None, icon: "dc-cube" }]; @@ -48,10 +45,10 @@ pub const POLYGONAL_LASSO: &[ToolInfo] = /// The add-ons' tool groups, after the toolbar's own ([`crate::TOOL_GROUPS`]), each with the /// heading the All Tools drawer lists it under (its add-on's name). const HEADED: &[(&[ToolInfo], &str)] = - &[(PATH_TOOLS, "Path Precision Tools"), (SMART_PEN, "Smart Pen"), (CONTOUR, "Contour"), (BOX_3D, "3D Box"), (POLYGONAL_LASSO, "Polygonal Lasso")]; + &[(PATH_TOOLS, "Path Precision Tools"), (CONTOUR, "Contour"), (BOX_3D, "3D Box"), (POLYGONAL_LASSO, "Polygonal Lasso")]; /// The add-ons' tool groups, after the toolbar's own ([`crate::TOOL_GROUPS`]). -pub const GROUPS: &[&[ToolInfo]] = &[PATH_TOOLS, SMART_PEN, CONTOUR, BOX_3D, POLYGONAL_LASSO]; +pub const GROUPS: &[&[ToolInfo]] = &[PATH_TOOLS, CONTOUR, BOX_3D, POLYGONAL_LASSO]; /// The heading the All Tools drawer lists tool `id` under: its add-on's name. pub fn heading(id: &str) -> Option<&'static str> { @@ -93,7 +90,6 @@ mod tests { assert!(!crate::TOOL_GROUPS.iter().any(|g| g.iter().any(|x| x.id == t.id)), "{} is not in the toolbar's groups", t.id); } assert!(PATH_TOOLS.iter().all(|t| heading(t.id) == Some("Path Precision Tools"))); - assert_eq!(heading(smart_pen::ID), Some("Smart Pen")); assert_eq!(heading(contour::ID), Some("Contour")); assert_eq!(heading(box3d::ID), Some("3D Box")); assert_eq!(heading(polygonal_lasso::ID), Some("Polygonal Lasso")); @@ -135,4 +131,22 @@ mod tests { assert!(heading(id).is_none(), "not listed again under the add-on"); assert_eq!(crate::catalog::all_tools().filter(|t| t.id == id).count(), 1); } + + /// The Smart Pen Tool is in the Pen tool's group, after the Pen family's own tools, with no + /// default shortcut, listed once, and still made by its add-on. + #[test] + fn smart_pen_is_in_the_pen_group_once() { + let id = smart_pen::ID; + let groups: Vec<_> = crate::TOOL_GROUPS.iter().filter(|g| g.iter().any(|t| t.id == id)).collect(); + assert_eq!(groups.len(), 1); + let ids: Vec<_> = groups[0].iter().map(|t| t.id).collect(); + assert_eq!(ids.first(), Some(&"pen"), "the Pen stays the group's default"); + assert_eq!(ids[ids.len().saturating_sub(2)..], [crate::quickpen::ID, id], "right after the Quick Pen, last"); + let info = crate::tool_info(id).expect("catalogued"); + assert_eq!((info.label, info.shortcut), ("Smart Pen Tool", None)); + assert_eq!(crate::tool_info("pen").and_then(|t| t.shortcut), Some("P"), "the Pen keeps its shortcut"); + assert_eq!(create(id).map(|tool| tool.id()), Some(id)); + assert!(heading(id).is_none(), "not listed again under the add-on"); + assert_eq!(crate::catalog::all_tools().filter(|t| t.id == id).count(), 1); + } } diff --git a/crates/tools/src/addons/tangent_circle.rs b/crates/tools/src/addons/tangent_circle.rs index b40cffd8e7..9ae74c0936 100644 --- a/crates/tools/src/addons/tangent_circle.rs +++ b/crates/tools/src/addons/tangent_circle.rs @@ -16,6 +16,16 @@ //! document, or a change to the first segment that leaves no undo step (a live preview, or one that //! was canceled) forgets the first segment. The circles are looked for again whenever either //! segment's shape differs from the one they were found on. +//! +//! The tool's options (its options dialog, `tool.setOption`; kept with the preferences): `radius`; +//! `center` and `radii` show or hide the circle's center cross and the lines from its center to the +//! two points it touches; `color` is the color of the circle, the cross, those lines and the note +//! (one of [`COLORS`]); `snapTolerance` is how near (screen pixels) the pointer picks a segment +//! with Smart Guides on, where Smart Guides' Snapping Tolerance counts instead when it is larger, +//! or with Smart Guides off while `snapWithoutGuides` is on. Without snapping a segment is picked +//! within the selection tolerance, as a click on a path picks it, and that is also the least reach +//! snapping has. Of the segments within reach the nearest is picked ([`pick_at`]). By default the +//! cross and the lines show, the color is red, the tolerance is 3 px and `snapWithoutGuides` is on. use kurbo::{CubicBez, Shape}; use serde_json::{Value, json}; @@ -42,6 +52,22 @@ pub const NO_CIRCLE: &str = "No tangent circle here"; const BLUE: [u8; 3] = [0x4f, 0x9d, 0xff]; const RED: [u8; 3] = [0xe0, 0x3c, 0x3c]; const GREY: [u8; 3] = [0x80, 0x80, 0x80]; +/// The colors the `color` option takes, by option value, with the color the circle, its center +/// cross, its radii and the note are drawn in. Red is the first. +pub const COLORS: &[(&str, [u8; 3])] = &[ + ("red", RED), + ("blue", crate::draw2::FEEDBACK), + ("magenta", [0xd6, 0x2c, 0xd6]), + ("green", [0x1f, 0xb4, 0x4b]), + ("black", [0x00, 0x00, 0x00]), + ("gray", GREY), +]; +/// The snapping tolerance the tool starts with (screen pixels). +pub const SNAP_PX: f64 = 3.0; +/// The snapping tolerance the `snapTolerance` option takes (screen pixels). +pub const SNAP_RANGE: (f64, f64) = (0.0, 25.0); +/// The option keys that are true or false. +const SWITCHES: &[&str] = &["center", "radii", "snapWithoutGuides"]; /// A segment under the pointer: where on it, and the segment itself. #[derive(Clone, Debug, PartialEq)] @@ -72,6 +98,14 @@ struct Press { pub struct TangentCircleTool { radius: f64, + /// Whether the preview shows the center cross and the radii. + center: bool, + radii: bool, + /// An entry of [`COLORS`]. + color: usize, + /// The snapping tolerance (screen pixels), and whether the tool snaps with Smart Guides off. + snap_px: f64, + snap_without_guides: bool, first: Option, hover: Option, press: Option, @@ -91,13 +125,45 @@ type CacheKey = (NodeId, usize, usize, Option, CubicBez, Vec); impl Default for TangentCircleTool { fn default() -> Self { - Self { radius: RADIUS, first: None, hover: None, press: None, picking: false, found: None, looked: false, pointer: Point::ZERO, cache: None } + Self { + radius: RADIUS, + center: true, + radii: true, + color: 0, + snap_px: SNAP_PX, + snap_without_guides: true, + first: None, + hover: None, + press: None, + picking: false, + found: None, + looked: false, + pointer: Point::ZERO, + cache: None, + } } } -/// The path segment under `p`, of any editable path. -fn pick_at(cx: &ToolContext, p: Point) -> Option { - let (id, subpath, segment, t) = crate::draw2::hit_segment(cx, p, cx.pick_tol())?; +/// The nearest path segment within `reach` of `p`, of any editable path; of segments at the same +/// distance, one of a selected path, then the one on top. +fn pick_at(cx: &ToolContext, p: Point, reach: f64) -> Option { + let mut best: Option<((NodeId, usize, usize, f64), f64)> = None; + for id in crate::draw2::candidate_paths(cx) { + let Some(pd) = cx.doc.node(id).and_then(|n| n.path_data()) else { continue }; + // A path whose control points' box, with its edges, lies out of reach holds no point within + // reach. + let near = |b: vectorcraft_geom::Rect| p.x >= b.x0 - reach && p.x <= b.x1 + reach && p.y >= b.y0 - reach && p.y <= b.y1 + reach; + if pd.control_bounds().is_none_or(|b| !near(b)) { + continue; + } + if let Some((subpath, segment, t, _, d)) = pd.nearest(p) + && d <= reach + && best.is_none_or(|(_, b)| d < b) + { + best = Some(((id, subpath, segment, t), d)); + } + } + let ((id, subpath, segment, t), _) = best?; let sp = cx.doc.node(id)?.path_data()?.subpaths.get(subpath)?; if segment >= sp.segment_count() { return None; @@ -197,6 +263,26 @@ fn segment_path(c: &CubicBez) -> BezPath { } impl TangentCircleTool { + /// How near (document units) the pointer picks a segment: with Smart Guides on, the snapping + /// tolerance or Smart Guides' Snapping Tolerance, whichever is larger; with them off, the + /// snapping tolerance while `snapWithoutGuides` is on, and otherwise none. Never less than the + /// selection tolerance. + fn reach(&self, cx: &ToolContext) -> f64 { + let pick = cx.pick_tol(); + if cx.smart_guides { + pick.max(cx.tol(self.snap_px)).max(cx.snap_tol()) + } else if self.snap_without_guides { + pick.max(cx.tol(self.snap_px)) + } else { + pick + } + } + + /// The color the preview is drawn in. + fn preview_color(&self) -> [u8; 3] { + COLORS.get(self.color).map_or(RED, |(_, rgb)| *rgb) + } + /// The radius a drag gives, with Shift in round steps. fn shown_radius(cx: &ToolContext, r: f64, shift: bool) -> f64 { if !shift { @@ -304,12 +390,12 @@ impl Tool for TangentCircleTool { self.pointer = ev.pos; match ev.kind { PointerKind::Move => { - self.hover = pick_at(cx, ev.pos); + self.hover = pick_at(cx, ev.pos, self.reach(cx)); self.look(cx, ev.pos, ev.mods); vec![] } PointerKind::Down => { - let Some(pick) = pick_at(cx, ev.pos) else { return vec![] }; + let Some(pick) = pick_at(cx, ev.pos, self.reach(cx)) else { return vec![] }; self.forget_if_changed(cx); let Some(first) = self.first.clone() else { self.first = Some(pick); @@ -415,21 +501,26 @@ impl Tool for TangentCircleTool { { out.push(Overlay::Line { a: press.at, b: self.pointer, color: GREY, dashed: false }); } + let color = self.preview_color(); if let Some(c) = &self.found { let (at, r) = (c.circle.center, c.circle.radius); // A tolerance of at least a ten-thousandth of the radius keeps a huge circle to a few // dozen segments. let tol = cx.tol(0.1).max(r * 1e-4); - out.push(Overlay::Path { path: kurbo::Circle::new(at, r).to_path(tol), color: RED, width: 1.0, dashed: false }); - let arm = cx.tol(4.0); - out.push(Overlay::Line { a: at - kurbo::Vec2::new(arm, 0.0), b: at + kurbo::Vec2::new(arm, 0.0), color: RED, dashed: false }); - out.push(Overlay::Line { a: at - kurbo::Vec2::new(0.0, arm), b: at + kurbo::Vec2::new(0.0, arm), color: RED, dashed: false }); - out.push(Overlay::Line { a: at, b: c.first, color: RED, dashed: true }); - out.push(Overlay::Line { a: at, b: c.second, color: RED, dashed: true }); + out.push(Overlay::Path { path: kurbo::Circle::new(at, r).to_path(tol), color, width: 1.0, dashed: false }); + if self.center { + let arm = cx.tol(4.0); + out.push(Overlay::Line { a: at - kurbo::Vec2::new(arm, 0.0), b: at + kurbo::Vec2::new(arm, 0.0), color, dashed: false }); + out.push(Overlay::Line { a: at - kurbo::Vec2::new(0.0, arm), b: at + kurbo::Vec2::new(0.0, arm), color, dashed: false }); + } + if self.radii { + out.push(Overlay::Line { a: at, b: c.first, color, dashed: true }); + out.push(Overlay::Line { a: at, b: c.second, color, dashed: true }); + } out.push(Overlay::Measure { p: self.pointer, text: format!("R: {}", cx.len(r)) }); } else if self.looked { // A label, which the canvas shows in the interface language. - out.push(Overlay::Label { p: self.pointer, text: NO_CIRCLE.into(), color: RED }); + out.push(Overlay::Label { p: self.pointer, text: NO_CIRCLE.into(), color }); } out } @@ -439,14 +530,29 @@ impl Tool for TangentCircleTool { } fn options(&self) -> Value { - json!({ "radius": self.radius }) + json!({ + "radius": self.radius, + "center": self.center, + "radii": self.radii, + "color": COLORS.get(self.color).map_or("red", |(name, _)| *name), + "snapTolerance": self.snap_px, + "snapWithoutGuides": self.snap_without_guides, + }) } + /// Sets one option; a value the option does not take leaves it as it was. fn set_option(&mut self, key: &str, v: &Value) { - if key == "radius" - && let Some(r) = v.as_f64().filter(|r| (RADIUS_RANGE.0..=RADIUS_RANGE.1).contains(r)) - { - self.radius = r; + if self.check_option(key, v).is_err() { + return; + } + match key { + "radius" => self.radius = v.as_f64().unwrap_or(self.radius), + "center" => self.center = v.as_bool().unwrap_or(self.center), + "radii" => self.radii = v.as_bool().unwrap_or(self.radii), + "color" => self.color = v.as_str().and_then(|s| COLORS.iter().position(|(name, _)| *name == s)).unwrap_or(self.color), + "snapTolerance" => self.snap_px = v.as_f64().unwrap_or(self.snap_px), + "snapWithoutGuides" => self.snap_without_guides = v.as_bool().unwrap_or(self.snap_without_guides), + _ => {} } } @@ -454,6 +560,9 @@ impl Tool for TangentCircleTool { use crate::option_check as c; match key { "radius" => c::number(key, v, RADIUS_RANGE.0, RADIUS_RANGE.1), + "snapTolerance" => c::number(key, v, SNAP_RANGE.0, SNAP_RANGE.1), + "color" => c::one_of(key, v, &COLORS.iter().map(|(name, _)| *name).collect::>()), + k if SWITCHES.contains(&k) => c::boolean(key, v), _ => Err(c::unknown(key)), } } @@ -598,6 +707,123 @@ mod tests { assert!(close(drawn(&released), (130.0, 100.0, 40.0, 40.0)), "{released:?}"); } + #[test] + fn the_preview_options_set_its_cross_radii_and_color() { + let d = doc(); + let (sel, p) = (Selection::default(), paint()); + let cx = cx(&d, &sel, &p); + let green = COLORS.iter().find(|(name, _)| *name == "green").map(|(_, rgb)| *rgb); + let lines = + |ov: &[Overlay], dashed_lines: bool| ov.iter().filter(|o| matches!(o, Overlay::Line { dashed, .. } if *dashed == dashed_lines)).count(); + let mut t = TangentCircleTool::default(); + t.pointer(&cx, &ev(PointerKind::Down, 150.0, 101.0)); + t.pointer(&cx, &ev(PointerKind::Up, 150.0, 101.0)); + t.pointer(&cx, &ev(PointerKind::Move, 200.0, 139.0)); + // By default: the red circle, its center cross (two lines) and its two radii. + let ov = t.overlays(&cx); + assert_eq!((lines(&ov, false), lines(&ov, true)), (2, 2), "{ov:?}"); + assert!(ov.iter().any(|o| matches!(o, Overlay::Path { color, width, .. } if *color == RED && *width == 1.0)), "{ov:?}"); + t.set_option("center", &json!(false)); + let ov = t.overlays(&cx); + assert_eq!((lines(&ov, false), lines(&ov, true)), (0, 2), "no cross: {ov:?}"); + t.set_option("radii", &json!(false)); + t.set_option("color", &json!("green")); + let ov = t.overlays(&cx); + assert_eq!((lines(&ov, false), lines(&ov, true)), (0, 0), "no radii: {ov:?}"); + assert!(ov.iter().any(|o| matches!(o, Overlay::Path { color, .. } if Some(*color) == green)), "{ov:?}"); + assert!(ov.iter().any(|o| matches!(o, Overlay::Measure { text, .. } if text.starts_with("R: 20.00"))), "the radius still shows: {ov:?}"); + // The note takes the color too. + t.set_option("radius", &json!(5)); + t.pointer(&cx, &shifted(PointerKind::Move, 200.0, 140.0)); + assert!(t.overlays(&cx).iter().any(|o| matches!(o, Overlay::Label { text, color, .. } if text == NO_CIRCLE && Some(*color) == green))); + } + + #[test] + fn the_preview_and_snap_options_take_only_their_values() { + let mut t = TangentCircleTool::default(); + let o = t.options(); + assert_eq!( + (&o["center"], &o["radii"], &o["color"], &o["snapTolerance"], &o["snapWithoutGuides"]), + (&json!(true), &json!(true), &json!("red"), &json!(3.0), &json!(true)) + ); + for (key, good) in [ + ("center", json!(false)), + ("radii", json!(false)), + ("snapWithoutGuides", json!(false)), + ("color", json!("gray")), + ("snapTolerance", json!(0)), + ("snapTolerance", json!(25)), + ("snapTolerance", json!(7.5)), + ] { + assert_eq!(t.check_option(key, &good), Ok(()), "{key} {good}"); + t.set_option(key, &good); + let now = t.options()[key].clone(); + assert!(now == good || (good.is_number() && now.as_f64() == good.as_f64()), "{key}: {now} for {good}"); + } + let colors = "`color` must be one of `red`, `blue`, `magenta`, `green`, `black`, `gray`"; + for (key, bad, error) in [ + ("center", json!(1), "`center` must be true or false"), + ("radii", json!("no"), "`radii` must be true or false"), + ("snapWithoutGuides", Value::Null, "`snapWithoutGuides` must be true or false"), + ("color", json!("orange"), colors), + ("color", json!("Red"), colors), + ("color", json!(0), colors), + ("snapTolerance", json!(-1), "`snapTolerance` must be a number from 0 to 25"), + ("snapTolerance", json!(26), "`snapTolerance` must be a number from 0 to 25"), + ("snapTolerance", json!("3"), "`snapTolerance` must be a number from 0 to 25"), + ] { + assert_eq!(t.check_option(key, &bad), Err(error.into()), "{key} {bad}"); + let before = t.options(); + t.set_option(key, &bad); + assert_eq!(t.options(), before, "{key} {bad}"); + } + } + + #[test] + fn the_snap_options_set_how_near_a_segment_is_picked() { + let d = doc(); + let (sel, p) = (Selection::default(), paint()); + // At 100%, Selection Tolerance 3 px; the first line is at y = 100. + let picks = |t: &mut TangentCircleTool, cx: &ToolContext, y: f64| { + t.forget(); + t.pointer(cx, &ev(PointerKind::Down, 150.0, y)); + t.pointer(cx, &ev(PointerKind::Up, 150.0, y)); + t.first.is_some() + }; + let guides = |tolerance: f64| ToolContext { smart_guides: true, snapping_tolerance: tolerance, ..cx(&d, &sel, &p) }; + let no_guides = ToolContext { smart_guides: false, ..cx(&d, &sel, &p) }; + let mut t = TangentCircleTool::default(); + // Smart Guides on: their Snapping Tolerance when it is larger than the tool's. + assert!(picks(&mut t, &guides(10.0), 109.0)); + assert!(!picks(&mut t, &guides(10.0), 111.0)); + t.set_option("snapTolerance", &json!(12)); + assert!(picks(&mut t, &guides(4.0), 111.0), "the tool's when it is larger"); + assert!(!picks(&mut t, &guides(4.0), 113.0)); + // Smart Guides off: the tool's tolerance while it snaps without them. + t.set_option("snapTolerance", &json!(8)); + assert!(picks(&mut t, &no_guides, 107.0)); + assert!(!picks(&mut t, &no_guides, 109.0)); + // Without snapping, only the Selection Tolerance; a tolerance below it does not shrink it. + t.set_option("snapWithoutGuides", &json!(false)); + assert!(!picks(&mut t, &no_guides, 105.0)); + assert!(picks(&mut t, &no_guides, 102.5)); + t.set_option("snapWithoutGuides", &json!(true)); + t.set_option("snapTolerance", &json!(0)); + assert!(picks(&mut t, &no_guides, 102.5)); + // Over the gap between the two lines, the nearer one is picked, though both are in reach. + t.set_option("snapTolerance", &json!(25)); + t.forget(); + t.pointer(&no_guides, &ev(PointerKind::Move, 150.0, 122.0)); + assert!(t.hover.as_ref().is_some_and(|h| (h.p.y - 140.0).abs() < 1e-9), "{:?}", t.hover); + t.pointer(&no_guides, &ev(PointerKind::Move, 150.0, 118.0)); + assert!(t.hover.as_ref().is_some_and(|h| (h.p.y - 100.0).abs() < 1e-9), "{:?}", t.hover); + // A segment exactly at the reach is in reach, on either side of it. + t.pointer(&no_guides, &ev(PointerKind::Move, 150.0, 75.0)); + assert!(t.hover.as_ref().is_some_and(|h| (h.p.y - 100.0).abs() < 1e-9), "{:?}", t.hover); + t.pointer(&no_guides, &ev(PointerKind::Move, 150.0, 165.0)); + assert!(t.hover.as_ref().is_some_and(|h| (h.p.y - 140.0).abs() < 1e-9), "{:?}", t.hover); + } + #[test] fn a_drag_sets_the_radius_with_shift_steps_and_a_slow_drag() { let d = doc(); diff --git a/crates/tools/src/builder/fill_area.rs b/crates/tools/src/builder/fill_area.rs index 367ff09318..2ce72b15f3 100644 --- a/crates/tools/src/builder/fill_area.rs +++ b/crates/tools/src/builder/fill_area.rs @@ -74,7 +74,8 @@ struct Reach<'a> { face: &'a PathData, bez: &'a vectorcraft_geom::kurbo::BezPath, zone: Rect, - /// How close (pt) to the outline a path may come and still change the area: the gap and 1 pt. + /// How close (pt) to the outline a path may come and still change the area: the gap and + /// [`CONTACT`]. reach: f64, } @@ -359,13 +360,15 @@ impl AreaFinder { let before = window; match bounds { // A path left out that crosses the area or comes within its reach could cut it, and - // only the map of every path holds both. + // only the map of every path holds both. A bridge reaches at most `gap`, so a path + // farther than that from the outline, give or take [`CONTACT`], does not change it. Some(rb) if within(&rb, &window) => { - let reached = rb.inflate(reach, reach); + let contact = self.gap + CONTACT; + let reached = rb.inflate(contact, contact); let mut budget = CUT_BUDGET; let cut = any_left_out && face.is_none_or(|(region, bez, _)| { - let area = Reach { face: ®ion.path, bez, zone: reached, reach }; + let area = Reach { face: ®ion.path, bez, zone: reached, reach: contact }; self.inputs.iter().zip(&left_out).any(|((s, b, _), out)| *out && meet(b, &reached) && cuts(&s.path, &area, &mut budget)) }); if !cut { diff --git a/crates/tools/src/catalog.rs b/crates/tools/src/catalog.rs index 54b50f0aa6..eb18001b19 100644 --- a/crates/tools/src/catalog.rs +++ b/crates/tools/src/catalog.rs @@ -35,6 +35,8 @@ pub const TOOL_GROUPS: &[&[ToolInfo]] = &[ t("deleteAnchor", "Delete Anchor Point Tool", Some("-"), "tool-pen-delete"), t("anchorPoint", "Anchor Point Tool", Some("Shift+C"), "tool-anchor"), t(crate::quickpen::ID, "Quick Pen Tool", Some("Alt+P"), "tool-quick-pen"), + // Smart Pen's tool, kept out of `addons::GROUPS` so that `all_tools` lists it once. + t(crate::addons::smart_pen::ID, "Smart Pen Tool", None, "spline-pointer"), ], &[t("curvature", "Curvature Tool", Some("Shift+~"), "tool-curvature")], &[ diff --git a/crates/tools/src/circle.rs b/crates/tools/src/circle.rs index e50e595e26..37c0e33bcd 100644 --- a/crates/tools/src/circle.rs +++ b/crates/tools/src/circle.rs @@ -17,6 +17,16 @@ //! reach past the canvas, the tool shows none and the release draws nothing; for three different //! points on one line, or a circle past the canvas, the pointer shows "Circle too large". //! +//! With the option From Center (`fromCenter`, in the Control bar) on, the first point is the +//! circle's center and the outline passes through the second: a drag from the center, or a click +//! on the center and then on a point of the outline, draws the circle whose radius is the distance +//! between them (`shape.circleThroughPoints` with `center`). The second point snaps to anchors and +//! Smart Guides as the others do, so the outline can pass exactly through another object's anchor. +//! Shift keeps the second point at 45° steps from the center, and Alt rounds the diameter to the +//! rulers' ticks. The option in force when the first point is placed applies to that circle, and +//! `dragThird` does not apply to it, since it has only two points. With `standardAnchors` off, its +//! one anchor on the outline is the second point. +//! //! The tool's options (Circle Tool Options, `tool.setOption`; kept with the preferences): //! `center`, `radii` and `diameter` show or hide the center cross, the radius lines and the //! diameter label; `color` is the color of the cross and the lines (one of [`COLORS`]); @@ -24,7 +34,7 @@ //! at 0°, 90°, 180° and 270° (`anchors: "points"`); `dragThird` off places the second point with //! a click and draws the circle through three points with a third click, and a click on the second //! point again (as a double-click there does) draws the circle on the two points. Every option is -//! on by default, and `color` is blue. +//! on by default except `fromCenter`, which is off, and `color` is blue. use serde_json::{Map, Value, json}; use vectorcraft_doc::MAX_COORD; @@ -56,7 +66,7 @@ pub const COLORS: &[(&str, [u8; 3])] = &[ ]; /// The option keys that are true or false. -const SWITCHES: &[&str] = &["center", "radii", "diameter", "standardAnchors", "dragThird"]; +const SWITCHES: &[&str] = &["center", "radii", "diameter", "standardAnchors", "dragThird", "fromCenter"]; /// The tool's options (see the module comment). #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -68,11 +78,13 @@ struct Options { color: usize, standard_anchors: bool, drag_third: bool, + /// The option From Center: the first point is the center. + from_center: bool, } impl Default for Options { fn default() -> Self { - Options { center: true, radii: true, diameter: true, color: 1, standard_anchors: true, drag_third: true } + Options { center: true, radii: true, diameter: true, color: 1, standard_anchors: true, drag_third: true, from_center: false } } } @@ -84,6 +96,7 @@ impl Options { "diameter" => &mut self.diameter, "standardAnchors" => &mut self.standard_anchors, "dragThird" => &mut self.drag_third, + "fromCenter" => &mut self.from_center, _ => return None, }) } @@ -143,48 +156,79 @@ pub struct CircleTool { press: Option, /// Where the pointer is, snapped: the point the next press or release places. pointer: Option, + /// Is the circle being drawn drawn from its center (From Center when its first point was + /// placed)? + centered: bool, } -/// The command the tool runs for `points`; with `standard_anchors` off, the circle's anchors are -/// at the points. -fn command(points: &[Point], standard_anchors: bool) -> (String, Value) { - let pairs: Vec = points.iter().map(|p| json!([p.x, p.y])).collect(); - let params = if standard_anchors { json!({ "points": pairs }) } else { json!({ "points": pairs, "anchors": "points" }) }; +/// The command the tool runs for `points`: with `centered`, the first point is the center and +/// the second is on the outline. With `standard_anchors` off, the circle's anchors are at the +/// points (from a center, the one point on the outline). +fn command(points: &[Point], centered: bool, standard_anchors: bool) -> (String, Value) { + let pair = |p: &Point| json!([p.x, p.y]); + let mut params = match points { + [c, p] if centered => json!({ "center": pair(c), "points": [pair(p)] }), + _ => json!({ "points": points.iter().map(pair).collect::>() }), + }; + if !standard_anchors { + params["anchors"] = json!("points"); + } ("shape.circleThroughPoints".into(), params) } +/// Is the circle at `c` with radius `r` inside the canvas, with its opposite edges on different +/// numbers (as `shape.circleThroughPoints` requires)? +fn on_canvas(c: Point, r: f64) -> bool { + [c.x - r, c.y - r, c.x + r, c.y + r].iter().all(|v| v.abs() <= MAX_COORD) && c.x - r < c.x + r && c.y - r < c.y + r +} + /// The circle through two points (the ends of a diameter) or three, as `shape.circleThroughPoints` /// draws it: none where no circle passes through them or it would reach past the canvas. pub fn circle_of(points: &[Point]) -> Option<(Point, f64)> { - let on_canvas = |(c, r): &(Point, f64)| [c.x - r, c.y - r, c.x + r, c.y + r].iter().all(|v| v.abs() <= MAX_COORD); - shapes::circle_through_points(points).filter(on_canvas) + shapes::circle_through_points(points).filter(|(c, r)| on_canvas(*c, *r)) } -/// [`circle_of`], as the tool draws it: with `standard_anchors` off, also none where the path with -/// an anchor at each point ([`shapes::circle_with_anchors_at`]) reaches past the canvas, since its -/// curves can reach slightly outside the circle. -fn drawn_circle(points: &[Point], standard_anchors: bool) -> Option<(Point, f64)> { +/// The circle `points` give: with `centered`, the circle at the first point whose outline passes +/// through the second, as `shape.circleThroughPoints` with `center` draws it (none for a second +/// point on the center or a circle past the canvas); otherwise [`circle_of`]. +fn circle_for(points: &[Point], centered: bool) -> Option<(Point, f64)> { + match *points { + [c, p] if centered => { + let r = c.distance(p); + (c.is_finite() && r.is_finite() && r > 0.0 && on_canvas(c, r)).then_some((c, r)) + } + _ if centered => None, + _ => circle_of(points), + } +} + +/// [`circle_for`], as the tool draws it: with `standard_anchors` off, also none where the path with +/// an anchor at each point ([`shapes::circle_with_anchors_at`]; from a center, the one point on the +/// outline) reaches past the canvas, since its curves can reach slightly outside the circle. +fn drawn_circle(points: &[Point], centered: bool, standard_anchors: bool) -> Option<(Point, f64)> { + let anchors = if centered { points.get(1..).unwrap_or(&[]) } else { points }; let fits = |(c, r): &(Point, f64)| { - let b = vectorcraft_geom::Shape::bounding_box(&shapes::circle_with_anchors_at(*c, *r, points).to_bezpath()); + let b = vectorcraft_geom::Shape::bounding_box(&shapes::circle_with_anchors_at(*c, *r, anchors).to_bezpath()); [b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite() && v.abs() <= MAX_COORD) }; - circle_of(points).filter(|c| standard_anchors || fits(c)) + circle_for(points, centered).filter(|c| standard_anchors || fits(c)) } -/// With Alt, `p` moved along the line from `first` so that their distance (the diameter) is on -/// the nearest ruler tick at the current zoom, in the General unit; `p` itself without Alt, and -/// when that rounding leaves no distance. -fn round_diameter(cx: &ToolContext, first: Point, p: Point, mods: Mods) -> Point { - let d = first.distance(p); +/// With Alt, `p` moved along the line from `first` so that the diameter (their distance, or twice +/// it from a center) is on the nearest ruler tick at the current zoom, in the General unit; `p` +/// itself without Alt, and when that rounding leaves no distance. +fn round_diameter(cx: &ToolContext, first: Point, p: Point, mods: Mods, centered: bool) -> Point { + let per = if centered { 2.0 } else { 1.0 }; + let d = first.distance(p) * per; let rounded = cx.unit.snap_to_ruler_tick(d, cx.zoom); if mods.alt && d > 0.0 && rounded > 0.0 && rounded.is_finite() { first + (p - first) * (rounded / d) } else { p } } /// Are the points two or more different points through which no circle is drawn: three on one /// line, or a circle that would reach past the canvas? -fn too_large(points: &[Point], standard_anchors: bool) -> bool { +fn too_large(points: &[Point], centered: bool, standard_anchors: bool) -> bool { let distinct = points.iter().enumerate().all(|(i, p)| !points.iter().take(i).any(|q| q == p)); - points.len() >= 2 && distinct && drawn_circle(points, standard_anchors).is_none() + points.len() >= 2 && distinct && drawn_circle(points, centered, standard_anchors).is_none() } impl CircleTool { @@ -193,9 +237,21 @@ impl CircleTool { self.second = None; self.press = None; self.pointer = None; + self.centered = false; self.snap.clear(); } + /// [`round_diameter`] for the circle being drawn. + fn round(&self, cx: &ToolContext, first: Point, p: Point, mods: Mods) -> Point { + round_diameter(cx, first, p, mods, self.centered) + } + + /// Does a drag place the third point? A circle drawn from its center has no third point, so + /// `dragThird` does not apply to it. + fn drag_third(&self) -> bool { + self.options.drag_third || self.centered + } + /// How the second point keeps to the first: Shift's 45° steps and the construction guides. A /// third point keeps to neither. fn leave(&self, cx: &ToolContext, mods: Mods) -> Option { @@ -222,9 +278,12 @@ impl CircleTool { Some(Press::First { .. }) | None => out.extend(self.pointer.filter(|_| self.first.is_some())), // A press on the first point adds no point: a drag from it drags out a diameter. Some(Press::Second { on_first: true, dragged, .. }) => out.extend(self.pointer.filter(|_| dragged)), + // From a center, the second point follows the pointer once the press has been dragged; + // until then it is the pressed point, which a release within DRAG_PX draws through. + Some(Press::Second { dragged: true, .. }) if self.centered => out.extend(self.pointer), Some(Press::Second { at, dragged: false, .. }) => out.push(at), // With `dragThird` off, a drag moves the second point. - Some(Press::Second { at, .. }) if !self.options.drag_third => out.push(at), + Some(Press::Second { at, .. }) if !self.drag_third() => out.push(at), Some(Press::Second { snapped, dragged: true, .. }) => { out.push(snapped); out.extend(self.pointer); @@ -234,13 +293,17 @@ impl CircleTool { out } - /// The second point as the tool shows it: none for a press on the first point. + /// The second point as the tool shows it: none for a press on the first point, nor for a + /// circle drawn from its center, whose second point follows the pointer. fn second(&self) -> Option { + if self.centered { + return None; + } if let Some((b, _)) = self.second { return Some(b); } match self.press { - Some(Press::Second { on_first: false, at, .. }) if !self.options.drag_third => Some(at), + Some(Press::Second { on_first: false, at, .. }) if !self.drag_third() => Some(at), Some(Press::Second { on_first: false, dragged: false, at, .. }) => Some(at), Some(Press::Second { on_first: false, dragged: true, snapped, .. }) => Some(snapped), _ => None, @@ -250,11 +313,12 @@ impl CircleTool { /// Runs the circle through `points` and starts afresh; where no circle is drawn through them /// (the tool showed none), it only starts afresh. fn draw(&mut self, points: &[Point]) -> Vec { + let centered = self.centered; self.clear(); - if drawn_circle(points, self.options.standard_anchors).is_none() { + if drawn_circle(points, centered, self.options.standard_anchors).is_none() { return vec![]; } - let (c, v) = command(points, self.options.standard_anchors); + let (c, v) = command(points, centered, self.options.standard_anchors); vec![Action::Exec(c, v)] } @@ -267,7 +331,7 @@ impl CircleTool { if on_second && !dragged { return self.draw(&[a, b]); } - if (on_first && !dragged) || drawn_circle(&[a, b, at], self.options.standard_anchors).is_none() { + if (on_first && !dragged) || drawn_circle(&[a, b, at], false, self.options.standard_anchors).is_none() { self.snap.clear(); return vec![]; } @@ -329,7 +393,7 @@ impl Tool for CircleTool { let p = self.snap.hover(cx, ev.pos, &[], leave.as_ref()); // Alt's rounding of the diameter is for the second point only. let rounds = self.first.filter(|_| self.second.is_none()); - self.pointer = Some(rounds.map_or(p, |a| round_diameter(cx, a, p, ev.mods))); + self.pointer = Some(rounds.map_or(p, |a| self.round(cx, a, p, ev.mods))); vec![] } PointerKind::Down => { @@ -352,13 +416,14 @@ impl Tool for CircleTool { None => { let at = self.snap.press(cx, ev.pos, &[], None); self.first = Some(at); + self.centered = self.options.from_center; self.press = Some(Press::First { at, from: ev.pos, dragged: false }); self.pointer = Some(at); } Some(a) => { let leave = self.leave(cx, ev.mods); let snapped = self.snap.press(cx, ev.pos, &[], leave.as_ref()); - let at = round_diameter(cx, a, snapped, ev.mods); + let at = self.round(cx, a, snapped, ev.mods); let on_first = snapped == a || ev.pos.distance(a) <= cx.tol(REACH_PX); self.press = Some(Press::Second { at, snapped, from: ev.pos, on_first, dragged: false }); self.pointer = Some(at); @@ -367,7 +432,8 @@ impl Tool for CircleTool { vec![] } PointerKind::Drag => { - let drag_third = self.options.drag_third; + let centered = self.centered; + let drag_third = self.drag_third(); let first = self.first; match &mut self.press { // With `dragThird` off, the second point follows the pointer as it does before @@ -378,7 +444,7 @@ impl Tool for CircleTool { if *dragged { let leave = first.map(|a| Leave::segment(cx, a, ev.mods.shift)); *snapped = self.snap.drag(cx, ev.pos, leave.as_ref()); - *at = first.map_or(*snapped, |a| round_diameter(cx, a, *snapped, ev.mods)); + *at = first.map_or(*snapped, |a| round_diameter(cx, a, *snapped, ev.mods, false)); self.pointer = Some(*at); } } @@ -392,15 +458,16 @@ impl Tool for CircleTool { Some(Press::First { at, from, dragged }) => { *dragged |= ev.pos.distance(*from) >= cx.tol(DRAG_PX); let leave = Leave::segment(cx, *at, ev.mods.shift); - self.pointer = Some(round_diameter(cx, *at, self.snap.drag(cx, ev.pos, Some(&leave)), ev.mods)); + self.pointer = Some(round_diameter(cx, *at, self.snap.drag(cx, ev.pos, Some(&leave)), ev.mods, centered)); } // Dragged from the first point, the pointer is the other end of a diameter, as - // for a drag from a first press. - Some(Press::Second { from, on_first: true, dragged, .. }) => { + // for a drag from a first press; from a center, the second point is always the + // pointer. + Some(Press::Second { from, dragged, on_first, .. }) if *on_first || centered => { *dragged |= ev.pos.distance(*from) >= cx.tol(DRAG_PX); let leave = self.first.map(|a| Leave::segment(cx, a, ev.mods.shift)); let p = self.snap.drag(cx, ev.pos, leave.as_ref()); - self.pointer = Some(self.first.map_or(p, |a| round_diameter(cx, a, p, ev.mods))); + self.pointer = Some(self.first.map_or(p, |a| round_diameter(cx, a, p, ev.mods, centered))); } Some(Press::Second { from, dragged, .. }) => { *dragged |= ev.pos.distance(*from) >= cx.tol(DRAG_PX); @@ -414,15 +481,22 @@ impl Tool for CircleTool { (Some(Press::Third { at, on_first, on_second, dragged, .. }), ..) => self.third_up(at, on_first, on_second, dragged), // With `dragThird` off, the release places the second point; let go on the first // point, as a press there is, it places nothing. - (Some(Press::Second { at, snapped, on_first: false, .. }), Some(a), _) if !self.options.drag_third => { + (Some(Press::Second { at, snapped, on_first: false, .. }), Some(a), _) if !self.drag_third() => { if !(at == a || snapped == a || ev.pos.distance(a) <= cx.tol(REACH_PX)) { self.second = Some((at, ev.pos)); } self.snap.clear(); vec![] } - (Some(Press::First { at, dragged: true, .. }), _, Some(b)) if b.distance(at) >= cx.tol(DRAG_PX) => self.draw(&[at, b]), - // A click places the first point; the guides of the press go. + // A release DRAG_PX or more from the press draws the circle the tool shows; where it + // shows none, the release draws nothing and starts afresh. + (Some(Press::First { at, dragged: true, .. }), _, Some(b)) + if b.distance(at) >= cx.tol(DRAG_PX) || circle_for(&[at, b], self.centered).is_some() => + { + self.draw(&[at, b]) + } + // A click, or a drag back onto the press, places the first point; the guides of the + // press go. (Some(Press::First { .. }), ..) => { self.snap.clear(); vec![] @@ -431,6 +505,9 @@ impl Tool for CircleTool { // a drag from there draws the circle on the diameter it drags out. (Some(Press::Second { on_first: true, dragged: false, .. }), ..) => vec![], (Some(Press::Second { on_first: true, dragged: true, .. }), Some(a), Some(c)) => self.draw(&[a, c]), + // From a center: the outline passes through the point the tool shows it on, where + // the drag ends or, within DRAG_PX of the press, the pressed point. + (Some(Press::Second { .. }), Some(a), Some(c)) if self.centered => self.draw(&[a, c]), (Some(Press::Second { at, dragged: false, .. }), Some(a), _) => self.draw(&[a, at]), // Three points: Alt's rounding of the diameter does not apply. (Some(Press::Second { snapped, dragged: true, .. }), Some(a), Some(c)) => self.draw(&[a, snapped, c]), @@ -487,12 +564,14 @@ impl Tool for CircleTool { let mut o = self.snap.guides().to_vec(); let points = self.points(); let color = crate::draw2::FEEDBACK; - if let Some((c, r)) = drawn_circle(&points, self.options.standard_anchors) { - // The path the release draws: with `standardAnchors` off, the one with an anchor at each point. + if let Some((c, r)) = drawn_circle(&points, self.centered, self.options.standard_anchors) { + // The path the release draws: with `standardAnchors` off, the one with an anchor at each + // point (from a center, at the one point on the outline). let path = if self.options.standard_anchors { shapes::ellipse(Rect::new(c.x - r, c.y - r, c.x + r, c.y + r)).to_bezpath() } else { - shapes::circle_with_anchors_at(c, r, &points).to_bezpath() + let on_outline = if self.centered { points.get(1..).unwrap_or(&[]) } else { &points[..] }; + shapes::circle_with_anchors_at(c, r, on_outline).to_bezpath() }; // The canvas draws a dashed outline dash by dash along its whole length: a circle longer // than DASHED_PX on screen is drawn solid instead. @@ -501,7 +580,8 @@ impl Tool for CircleTool { let opts = self.options; let lines = COLORS.get(opts.color).map_or(color, |(_, rgb)| *rgb); if opts.radii { - for p in &points { + // A circle drawn from its center has one radius, to the point on its outline. + for p in points.iter().filter(|p| **p != c) { o.push(Overlay::Line { a: c, b: *p, color: lines, dashed: false }); } } @@ -513,7 +593,7 @@ impl Tool for CircleTool { if let Some(p) = self.pointer.filter(|_| cx.measurement_labels && opts.diameter) { o.push(Overlay::Measure { p: p + Vec2::new(cx.tol(12.0), cx.tol(12.0)), text: format!("D: {}", cx.len(2.0 * r)) }); } - } else if let Some(p) = self.pointer.filter(|_| too_large(&points, self.options.standard_anchors)) { + } else if let Some(p) = self.pointer.filter(|_| too_large(&points, self.centered, self.options.standard_anchors)) { o.push(Overlay::Label { p, text: "Circle too large".into(), color }); } for p in self.first.into_iter().chain(self.second()) { @@ -536,6 +616,7 @@ impl Tool for CircleTool { "color": color, "standardAnchors": o.standard_anchors, "dragThird": o.drag_third, + "fromCenter": o.from_center, }) } @@ -545,7 +626,8 @@ impl Tool for CircleTool { } /// Sets one option; a value the option does not take leaves it as it was. Switching - /// `dragThird` drops the points placed so far. + /// `dragThird` drops the points placed so far; a circle being drawn keeps the `fromCenter` mode + /// it started with. fn set_option(&mut self, key: &str, value: &Value) { if key == "color" { if let Some(i) = value.as_str().and_then(|s| COLORS.iter().position(|(name, _)| *name == s)) { @@ -558,7 +640,8 @@ impl Tool for CircleTool { if let Some(switch) = self.options.switch(key) { *switch = on; } - if self.options.drag_third != was { + // A circle drawn from its center has no third point, so its center stays placed. + if self.options.drag_third != was && !self.centered { self.clear(); } } diff --git a/crates/tools/src/circle/tests.rs b/crates/tools/src/circle/tests.rs index 4e700b6c3b..3264a771e8 100644 --- a/crates/tools/src/circle/tests.rs +++ b/crates/tools/src/circle/tests.rs @@ -140,7 +140,10 @@ fn the_options_show_or_hide_the_center_radii_and_diameter_in_their_color() { let o = t.overlays(&cx); assert_eq!(annotations(&o, c), (vec![red; 2], vec![red; 2])); assert!(o.iter().any(|o| matches!(o, Overlay::Path { color, .. } if *color == blue)), "{o:?}"); - assert_eq!(t.options(), json!({"center": true, "radii": true, "diameter": false, "color": "red", "standardAnchors": true, "dragThird": true})); + assert_eq!( + t.options(), + json!({"center": true, "radii": true, "diameter": false, "color": "red", "standardAnchors": true, "dragThird": true, "fromCenter": false}) + ); // A value an option does not take leaves it as it was. for (key, value) in [("color", json!("orange")), ("center", json!("no")), ("radii", json!(0))] { t.set_option(key, &value); @@ -192,8 +195,8 @@ fn anchors_at_the_points_keep_the_path_on_the_canvas() { let at = |deg: f64| (r * deg.to_radians().cos(), r * deg.to_radians().sin()); let points = [at(0.0), at(70.0), at(180.0)]; let geom: Vec = points.iter().map(|(x, y)| Point::new(*x, *y)).collect(); - assert!(drawn_circle(&geom, true).is_some()); - assert_eq!(drawn_circle(&geom, false), None); + assert!(drawn_circle(&geom, false, true).is_some()); + assert_eq!(drawn_circle(&geom, false, false), None); let mut t = CircleTool::default(); t.set_option("standardAnchors", &json!(false)); click(&mut t, &cx, points[0]); @@ -584,8 +587,8 @@ fn points_on_one_line_say_the_circle_is_too_large() { assert_eq!(label(&t), None, "a circle is shown"); t.pointer(&cx, &ev(PointerKind::Drag, (200.0, 200.0), Mods::default())); assert_eq!(label(&t), None, "the third point is on the second"); - assert!(too_large(&[Point::new(0.0, 0.0), Point::new(4.1e6, 0.0)], true)); - assert!(!too_large(&[Point::new(0.0, 0.0)], true) && !too_large(&[Point::new(1.0, 0.0), Point::new(1.0, 0.0)], true)); + assert!(too_large(&[Point::new(0.0, 0.0), Point::new(4.1e6, 0.0)], false, true)); + assert!(!too_large(&[Point::new(0.0, 0.0)], false, true) && !too_large(&[Point::new(1.0, 0.0), Point::new(1.0, 0.0)], false, true)); } /// Escape drops the first point; so do a dropped press and an edit made outside the tool. A @@ -698,6 +701,193 @@ fn a_huge_circle_is_previewed_solid() { assert!(preview(&t.overlays(&cx)).is_some()); } +/// The command the tool runs for a circle at `c` whose outline passes through `p`. +fn centered(c: (f64, f64), p: (f64, f64)) -> Vec { + vec![Action::Exec("shape.circleThroughPoints".into(), json!({ "center": [c.0, c.1], "points": [[p.0, p.1]] }))] +} + +fn from_center() -> CircleTool { + let mut t = CircleTool::default(); + t.set_option("fromCenter", &json!(true)); + t +} + +/// With From Center, a drag from the corner anchor of the rectangle at (200, 200) to next to the +/// opposite corner at (100, 100) snaps both ends to the anchors: the circle is centered on one +/// corner, its outline passes through the other, and its radius is the diagonal. Until the release +/// the outline passes through the pointer, with one radius drawn to it. +#[test] +fn from_center_the_outline_passes_through_the_opposite_corner() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = cx(&d, &s, &p); + let mut t = from_center(); + assert_eq!(t.options()["fromCenter"], json!(true)); + t.pointer(&cx, &ev(PointerKind::Move, (201.0, 199.5), Mods::default())); + t.pointer(&cx, &ev(PointerKind::Down, (201.0, 199.5), Mods::default())); + t.pointer(&cx, &ev(PointerKind::Drag, (150.0, 150.0), Mods::default())); + t.pointer(&cx, &ev(PointerKind::Drag, (101.0, 101.5), Mods::default())); + let r = 100.0 * std::f64::consts::SQRT_2; + let o = t.overlays(&cx); + let shown = o + .iter() + .find_map(|o| match o { + Overlay::Path { path, .. } => Some(vectorcraft_geom::Shape::bounding_box(path)), + _ => None, + }) + .expect("the circle is shown"); + assert!(near(shown, Rect::new(200.0 - r, 200.0 - r, 200.0 + r, 200.0 + r)), "{o:?}"); + let center = Point::new(200.0, 200.0); + let radii: Vec = o + .iter() + .filter_map(|o| match o { + Overlay::Line { a, b, .. } if *a == center => Some(*b), + _ => None, + }) + .collect(); + assert_eq!(radii, vec![Point::new(100.0, 100.0)], "one radius, to the pointer: {o:?}"); + assert!(o.iter().any(|o| matches!(o, Overlay::Measure { text, .. } if text.starts_with("D: 282.84"))), "{o:?}"); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, (101.0, 101.5), Mods::default())), centered((200.0, 200.0), (100.0, 100.0))); + assert_eq!(circle_for(&[center, Point::new(100.0, 100.0)], true), Some((center, r))); +} + +/// With From Center, a click places the center and a second click the point the outline passes +/// through; a second click on the center places nothing, and the center stays. +#[test] +fn from_center_two_clicks_draw_the_circle_through_the_second() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = from_center(); + assert_eq!(click(&mut t, &cx, (300.0, 300.0)), vec![]); + assert_eq!(click(&mut t, &cx, (300.5, 300.0)), vec![], "a double-click places the center alone"); + assert!(t.ends_on_escape(&cx)); + t.pointer(&cx, &ev(PointerKind::Move, (330.0, 340.0), Mods::default())); + // Center (300, 300), radius 50. + assert!(near(preview(&t.overlays(&cx)).expect("the circle is shown"), Rect::new(250.0, 250.0, 350.0, 350.0)), "{:?}", t.overlays(&cx)); + assert_eq!(click(&mut t, &cx, (330.0, 340.0)), centered((300.0, 300.0), (330.0, 340.0))); + // A second press dragged from elsewhere moves the point the outline passes through. + click(&mut t, &cx, (300.0, 300.0)); + assert_eq!(drag(&mut t, &cx, (330.0, 340.0), &[(360.0, 300.0)], Mods::default()), centered((300.0, 300.0), (360.0, 300.0))); +} + +/// With From Center, the release draws the circle the tool shows: a drag from the center ends +/// where it is let go, and a second press moved less than 2 screen points shows and draws the +/// outline through the point of the press. +#[test] +fn from_center_the_release_draws_the_circle_shown() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = from_center(); + t.pointer(&cx, &ev(PointerKind::Down, (300.0, 300.0), Mods::default())); + t.pointer(&cx, &ev(PointerKind::Drag, (380.0, 300.0), Mods::default())); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, (400.0, 300.0), Mods::default())), centered((300.0, 300.0), (400.0, 300.0))); + click(&mut t, &cx, (300.0, 300.0)); + t.pointer(&cx, &ev(PointerKind::Down, (330.0, 340.0), Mods::default())); + t.pointer(&cx, &ev(PointerKind::Drag, (331.0, 340.0), Mods::default())); + let shown = preview(&t.overlays(&cx)).expect("the circle is shown"); + let r = Point::new(300.0, 300.0).distance(Point::new(330.0, 340.0)); + assert!(near(shown, Rect::new(300.0 - r, 300.0 - r, 300.0 + r, 300.0 + r)), "{:?}", t.overlays(&cx)); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, (331.0, 340.0), Mods::default())), centered((300.0, 300.0), (330.0, 340.0))); +} + +/// A first press let go within 2 screen points of where it was pressed is a click also after a +/// drag that came back to it, from a center and on a diameter: it places the first point. +#[test] +fn a_first_press_dragged_back_near_its_press_places_the_first_point() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = from_center(); + assert_eq!(drag(&mut t, &cx, (300.0, 300.0), &[(320.0, 300.0), (301.0, 300.0)], Mods::default()), vec![]); + assert!(t.ends_on_escape(&cx), "the center is placed"); + assert_eq!(click(&mut t, &cx, (380.0, 300.0)), centered((300.0, 300.0), (380.0, 300.0))); + let mut t = CircleTool::default(); + assert_eq!(drag(&mut t, &cx, (300.0, 300.0), &[(320.0, 300.0), (301.0, 300.0)], Mods::default()), vec![]); + assert!(t.ends_on_escape(&cx), "the first point is placed"); + t.key(&cx, ToolKey::Escape, Mods::default()); + // A drag to a circle past the canvas draws nothing and leaves no point behind. + assert_eq!(drag(&mut t, &cx, (300.0, 300.0), &[(4.1e6, 300.0)], Mods::default()), vec![]); + assert!(!t.ends_on_escape(&cx), "nothing is left pending"); +} + +/// With From Center, Shift keeps the point at 45° steps from the center, and Alt rounds the +/// diameter, twice the radius, to the rulers' ticks (every 5 pt at 100% in points). +#[test] +fn from_center_shift_and_alt_keep_to_the_center() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = from_center(); + let shift = Mods { shift: true, ..Mods::default() }; + let acts = drag(&mut t, &cx, (300.0, 300.0), &[(400.0, 310.0)], shift); + let [Action::Exec(_, v)] = acts.as_slice() else { panic!("one circle: {acts:?}") }; + assert!((v["points"][0][1].as_f64().unwrap() - 300.0).abs() < 1e-9, "level with the center: {v}"); + // Near the diagonal, the point keeps to the 45° line through the center. + let acts = drag(&mut t, &cx, (300.0, 300.0), &[(380.0, 372.0)], shift); + let [Action::Exec(_, v)] = acts.as_slice() else { panic!("one circle: {acts:?}") }; + let (x, y) = (v["points"][0][0].as_f64().unwrap(), v["points"][0][1].as_f64().unwrap()); + assert!(((x - 300.0) - (y - 300.0)).abs() < 1e-9 && x > 300.0, "on the 45° line from the center: {v}"); + let alt = Mods { alt: true, ..Mods::default() }; + // A radius of 26 is a diameter of 52, which Alt makes 50. + assert_eq!(drag(&mut t, &cx, (0.0, 0.0), &[(0.0, 26.0)], alt), centered((0.0, 0.0), (0.0, 25.0))); +} + +/// The option in force when the first point is placed applies to that circle: turning From Center +/// off part way keeps the circle being drawn centered, and the next circle is drawn on a diameter. +/// A point on the center draws nothing. +#[test] +fn from_center_holds_for_the_circle_being_drawn() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = from_center(); + click(&mut t, &cx, (100.0, 100.0)); + t.set_option("fromCenter", &json!(false)); + assert_eq!(click(&mut t, &cx, (100.0, 150.0)), centered((100.0, 100.0), (100.0, 150.0))); + assert_eq!(drag(&mut t, &cx, (300.0, 300.0), &[(380.0, 360.0)], Mods::default()), circle(&[(300.0, 300.0), (380.0, 360.0)])); + assert_eq!(circle_for(&[Point::new(1.0, 1.0), Point::new(1.0, 1.0)], true), None); + assert!(too_large(&[Point::new(0.0, 0.0), Point::new(4.1e6, 0.0)], true, true)); + // Edges that round to one number at document precision, as `shape.circleThroughPoints` refuses. + let x = 1_048_576.0; + assert_eq!(circle_for(&[Point::new(x, 0.0), Point::new(x, 1e-11)], true), None); + assert_eq!(circle_of(&[Point::new(x, 0.0), Point::new(x, 2e-11)]), None); + t.set_option("fromCenter", &json!("yes")); + assert_eq!(t.options()["fromCenter"], json!(false), "a value that is not true or false is ignored"); +} + +/// Switching `dragThird` while a center is placed keeps the center: the circle from it is still +/// drawn. Without From Center, the switch drops the point placed. +#[test] +fn switching_third_point_by_dragging_keeps_a_placed_center() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = from_center(); + click(&mut t, &cx, (100.0, 100.0)); + t.set_option("dragThird", &json!(false)); + assert!(t.ends_on_escape(&cx), "the center is still placed"); + assert_eq!(click(&mut t, &cx, (100.0, 150.0)), centered((100.0, 100.0), (100.0, 150.0))); + let mut t = CircleTool::default(); + click(&mut t, &cx, (100.0, 100.0)); + t.set_option("dragThird", &json!(false)); + assert!(!t.ends_on_escape(&cx), "the first point is dropped"); +} + +/// `tool.setOption` takes `fromCenter` as true or false, and no other key. +#[test] +fn the_options_are_checked() { + let map = |v: Value| v.as_object().cloned().unwrap(); + assert_eq!(check_options(&map(json!({ "fromCenter": true }))), Ok(())); + assert_eq!(check_options(&map(json!({ "fromCenter": 1 }))), Err("`fromCenter` must be true or false".into())); + assert_eq!(check_options(&map(json!({ "radius": 5 }))), Err("unknown Circle tool option `radius`".into())); + let t = CircleTool::default(); + assert_eq!(t.check_option("fromCenter", &json!(false)), Ok(())); + assert_eq!(t.check_option("fromCenter", &json!(1)), Err("`fromCenter` must be true or false".into())); + assert_eq!(t.check_option("radius", &json!(5)), Err("unknown Circle tool option `radius`".into())); +} + /// The tool is in the Ellipse tool's group, after the Ellipse tool. #[test] fn the_circle_tool_follows_the_ellipse_tool() { diff --git a/crates/tools/src/context.rs b/crates/tools/src/context.rs index bc0f822c06..67658b4ea9 100644 --- a/crates/tools/src/context.rs +++ b/crates/tools/src/context.rs @@ -228,8 +228,16 @@ pub struct ToolContext<'a> { pub shape_widgets: bool, /// Which paint proxy is in front (true = Fill): the one the Gradient tool edits. pub fill_active: bool, - /// The selected gradient stop (`gradient.selectStop`), marked on the gradient annotator. + /// The selected gradient stop (`gradient.selectStop`), marked on the gradient annotator. For + /// an Eyedropper pick armed for a stop of the gradient a tool paints with, only a stop still + /// selected on that gradient. pub gradient_stop: Option, + /// Is [`Self::paint`]'s paint behind the proxy in front ([`Self::fill_active`]) the color the + /// active tool, or the tool an armed one-shot pick returns to, paints with (the Live Paint + /// Bucket's fill and stroke, the Shape Builder's fill), or was the pick armed for a stop of + /// that tool's paint? A pick armed for such a stop then ends once [`Self::gradient_stop`] no + /// longer names it, also after the stop was cleared or the other proxy came to the front. + pub tool_paints: bool, /// The Appearance panel's active fill/stroke (paint-order index into the first selected /// object's stack); paint tools show and edit that item. pub appearance_item: Option, diff --git a/crates/tools/src/draw2.rs b/crates/tools/src/draw2.rs index 0c032e0684..7e334ce31f 100644 --- a/crates/tools/src/draw2.rs +++ b/crates/tools/src/draw2.rs @@ -92,6 +92,11 @@ pub fn pressure_size(size: f64, variation: f64, pressure: f64) -> f64 { /// The narrowest a Blob Brush or Eraser stroke gets, in points (their Size field's minimum). pub const MIN_BRUSH_SIZE: f64 = 0.1; +/// The modes the Blob Brush's Size takes (`sizeMode`). The Eraser's Size takes every +/// [`vectorcraft_brush::Variation`]. +pub const BLOB_SIZE_MODES: [vectorcraft_brush::Variation; 3] = + [vectorcraft_brush::Variation::Fixed, vectorcraft_brush::Variation::Pressure, vectorcraft_brush::Variation::StylusWheel]; + /// A pen's tilt as a lean on the page (each tilt's tangent) and its angle from upright in degrees, /// as Pointer Events' tiltX and tiltY convert to an altitude and an azimuth. fn pen_lean(tilt: [f32; 2]) -> ([f64; 2], f64) { diff --git a/crates/tools/src/draw2/gesture.rs b/crates/tools/src/draw2/gesture.rs index 4f2fb7b463..6bbdc737d2 100644 --- a/crates/tools/src/draw2/gesture.rs +++ b/crates/tools/src/draw2/gesture.rs @@ -85,6 +85,9 @@ const BAND_WORK_PER_CALL: usize = 20_000; const PREVIEW_FIDELITY_PX: f64 = 0.5; /// The Smooth tool's Fidelity (screen pixels) until Smooth Tool Options sets another. const SMOOTH_FIDELITY: f64 = 2.5; +/// The Smooth tool's Smoothness (percent) until Smooth Tool Options sets another: the strength +/// `path.smoothRegion` smooths with when a drag leaves it out. VectorCraft's own value. +const SMOOTH_SMOOTHNESS: f64 = 50.0; /// How far the pointer goes from the press point, in screen pixels, before a Shift-drag of the /// Eraser takes the 45° step it lies nearest to. const ERASER_SHIFT_PX: f64 = 3.0; @@ -146,9 +149,10 @@ pub struct GestureTool { pub fidelity: f64, /// Brush / eraser diameter in points (the Eraser's across its tip's long axis). pub size: f64, - /// Blob Brush and Eraser Tool Options' Size mode: Fixed or Pressure for the Blob Brush (with - /// Pressure the tip is `size` − `size_variation` wide at the lightest pen pressure and `size` + - /// `size_variation` at the heaviest), and any [`Variation`] for the Eraser. + /// Blob Brush and Eraser Tool Options' Size mode: Fixed, Pressure or Stylus Wheel for the Blob + /// Brush (with Pressure the tip is `size` − `size_variation` wide at the lightest pen pressure + /// and `size` + `size_variation` at the heaviest, and with Stylus Wheel from one end of an + /// airbrush pen's finger wheel travel to the other), and any [`Variation`] for the Eraser. pub size_mode: Variation, /// Blob Brush and Eraser Tool Options' Size Variation, in points. pub size_variation: f64, @@ -182,6 +186,11 @@ pub struct GestureTool { /// The Smooth tool's Fidelity (screen pixels), used when Alt switches the Pencil, Paintbrush or /// Blob Brush to Smooth. The engine sets it from Smooth Tool Options (`smoothFidelity`). smooth_fidelity: f64, + /// Smooth Tool Options' Smoothness (percent, 0 to 100): how strongly a Smooth drag smooths the + /// path before it is refitted. The Smooth tool's own (`smoothness`), and for the Pencil, + /// Paintbrush and Blob Brush the one an Alt smoothing drag uses, which the engine sets from + /// Smooth Tool Options (`smoothSmoothness`). + smoothness: f64, /// Active drag is smoothing with the Pencil, Paintbrush or Blob Brush (Alt held). smoothing: bool, /// The pointer has moved from the press point, by any distance (a move too short to add a @@ -907,6 +916,7 @@ impl GestureTool { live_preview: true, live_fit: true, smooth_fidelity: SMOOTH_FIDELITY, + smoothness: SMOOTH_SMOOTHNESS, smoothing: false, moved: false, marquee: false, @@ -1001,12 +1011,13 @@ impl GestureTool { } } - /// Give the Eraser's last stroke sample the pen's tilt and rotation of the event `ev`, a drag - /// within a pixel of that sample that adds none: a pen turned or tilted in place turns its tip - /// there, in the outline and in what the release erases. The sample keeps its pressure, which - /// the area outline of the drag was built with, and its pose when `ev` reads none. + /// Give the Eraser's or the Blob Brush's last stroke sample the pen's tilt, rotation and wheel + /// of the event `ev`, a drag within a pixel of that sample that adds none: a pen turned or + /// tilted in place, or its wheel turned there, changes its tip there, in the outline and in + /// what the release erases or paints. The sample keeps its pressure, which the area outline of + /// the drag was built with, and its pose when `ev` reads none. fn refresh_last_pose(&mut self, ev: &PointerEvent) { - if self.id != "eraser" || self.poses.len() != self.points.len() || ev.pen.is_none() { + if !matches!(self.id, "eraser" | "blobBrush") || self.poses.len() != self.points.len() || ev.pen.is_none() { return; } let pose = ev.pen.map(PenPose::sanitized); @@ -1126,8 +1137,8 @@ impl GestureTool { } /// The Blob Brush's or the Eraser's tip at the pointer, before and while painting: its outline - /// `size` across at its angle and roundness (the Eraser's as the pen varies them while it - /// erases, [`Self::tip_now`]), at the zoom, black on a white halo so it reads on + /// `size` across at its angle and roundness (as the pen varies them while it erases or + /// paints, [`Self::tip_now`]), at the zoom, black on a white halo so it reads on /// any art. Precise cursors show only the crosshair, and smoothing shows no tip. fn tip_outline(&self, cx: &ToolContext) -> Vec { let Some(at) = self.tip_at.filter(|_| !self.smoothing && !cx.precise_cursors) else { return vec![] }; @@ -1275,7 +1286,7 @@ impl GestureTool { outline.filter(|o| !o.elements().is_empty()) } - /// Does the tool's Size take Fixed or Pressure (the Blob Brush and the Eraser)? + /// Does the tool's Size take a variation mode (the Blob Brush and the Eraser)? fn varies_size(&self) -> bool { matches!(self.id, "blobBrush" | "eraser") } @@ -1365,14 +1376,23 @@ impl GestureTool { /// value on a mode that follows the pen goes from the value less its Variation to the value /// plus it as the pen reads now (the pressure once the pen has pressed less than fully, the /// tilt, rotation and wheel of the last point, and the bearing of the last point the pen leaned 1° or - /// more at), as `path.eraseRegion` reads the stroke; before a press, and for Random, Fixed and a - /// pen that gives no reading, the values themselves. The Blob Brush's are its own values. + /// more at), as `path.eraseRegion` reads the stroke; before a press, and for Random, Fixed, a + /// pen that gives no reading and a reading the release does not send (a mode set during the + /// drag), the values themselves. The Blob Brush's size follows the pen the + /// same way while it paints, as `path.blob` reads the stroke, and its angle and roundness are + /// its own values (a roundness of 0 included). fn tip_now(&self) -> [f64; 3] { - if self.id != "eraser" || !self.active { + if !matches!(self.id, "eraser" | "blobBrush") || !self.active { return [self.angle, self.roundness, self.size]; } - let pressure = if self.light { self.pressures.last().map_or(0.5, |p| f64::from(*p)) } else { 0.5 }; - self.tip_for(pressure, self.poses.last().copied().flatten(), self.bearing) + // What the release does not read ([`Self::reads_pressures`], [`Self::reads_poses`]) reads ½. + let pressure = if self.reads_pressures() { self.pressures.last().map_or(0.5, |p| f64::from(*p)) } else { 0.5 }; + let (pose, bearing) = if self.reads_poses() { (self.poses.last().copied().flatten(), self.bearing) } else { (None, None) }; + let tip = self.tip_for(pressure, pose, bearing); + if self.id == "blobBrush" { + return [self.angle, self.roundness, tip[2]]; + } + tip } /// The tip's angle, roundness and size for a pen at `pressure` held as `pose`, leaning toward @@ -1563,8 +1583,9 @@ impl GestureTool { /// The preview of a stroke being drawn: [`Self::freehand_params`], except that a stroke that /// redraws a selected path is shown as it is drawn, joined at its start to the point of the - /// path nearest to it, with no fill, and leaves the path and the selection as they are: where - /// the stroke ends is only known at the release, which redraws the path (`finish`). + /// path nearest to it, with no fill, on top in any drawing mode, and leaves the path and the + /// selection as they are: where the stroke ends is only known at the release, which redraws + /// the path (`finish`). fn drawing_params(&self, cx: &ToolContext) -> Value { let mut v = self.freehand_params(cx, false); let Some((id, _)) = self.redraw else { return v }; @@ -1573,7 +1594,7 @@ impl GestureTool { } v["fill"] = json!(false); v["keepSelected"] = json!(false); - v["leaveSelection"] = json!(true); + v["preview"] = json!(true); let on = self.points.first().and_then(|&p| cx.doc.node(id)?.path_data()?.nearest(p)).map(|n| n.3); if let (Some(on), Some(pts)) = (on, v["points"].as_array_mut()) { pts.insert(0, json!([on.x, on.y])); @@ -1590,7 +1611,7 @@ impl GestureTool { if pts.len() >= 2 && has_selected_smooth_path(cx) { return vec![Action::Exec( "path.smoothRegion".into(), - json!({"points": points_json(pts), "radius": radius, "fidelity": smooth_tolerance(cx, self.smooth_fidelity)}), + json!({"points": points_json(pts), "radius": radius, "fidelity": smooth_tolerance(cx, self.smooth_fidelity), "smoothness": self.smoothness}), )]; } return vec![]; @@ -1655,7 +1676,7 @@ impl GestureTool { "smooth" if pts.len() >= 2 && has_selected_smooth_path(cx) => { vec![Action::Exec( "path.smoothRegion".into(), - json!({"points": points_json(pts), "radius": radius, "fidelity": smooth_tolerance(cx, self.fidelity)}), + json!({"points": points_json(pts), "radius": radius, "fidelity": smooth_tolerance(cx, self.fidelity), "smoothness": self.smoothness}), )] } "pathEraser" if has_sel => vec![Action::Exec("path.eraseSegments".into(), json!({"points": points_json(pts), "width": reach(cx, 8.0)}))], @@ -2089,7 +2110,7 @@ impl Tool for GestureTool { "closeWithin": self.close_within }) } - "smooth" => json!({"fidelity": self.fidelity}), + "smooth" => json!({"fidelity": self.fidelity, "smoothness": self.smoothness}), "blobBrush" => { json!({ "fidelity": self.fidelity, @@ -2120,10 +2141,10 @@ impl Tool for GestureTool { match key { "fidelity" => self.fidelity = v.as_f64().unwrap_or(self.fidelity).clamp(super::min_fidelity(self.id), 100.0), "size" => self.size = v.as_f64().unwrap_or(self.size).clamp(0.1, 1000.0), - // The Blob Brush's Size is Fixed or Pressure; the Eraser's Angle, Roundness and Size - // take any mode. + // The Blob Brush's Size is Fixed, Pressure or Stylus Wheel; the Eraser's Angle, + // Roundness and Size take any mode. "sizeMode" if self.varies_size() => match v.as_str().and_then(Variation::parse) { - Some(m) if self.id == "eraser" || matches!(m, Variation::Fixed | Variation::Pressure) => self.size_mode = m, + Some(m) if self.id == "eraser" || super::BLOB_SIZE_MODES.contains(&m) => self.size_mode = m, _ => {} }, "angleMode" if self.id == "eraser" => self.angle_mode = v.as_str().and_then(Variation::parse).unwrap_or(self.angle_mode), @@ -2142,6 +2163,11 @@ impl Tool for GestureTool { "smoothFidelity" if matches!(self.id, "pencil" | "paintbrush" | "blobBrush") => { self.smooth_fidelity = v.as_f64().unwrap_or(self.smooth_fidelity).clamp(super::min_fidelity("smooth"), 100.0) } + // A value that is not a number from 0 to 100 leaves the Smoothness as it is. + "smoothness" if self.id == "smooth" => self.smoothness = v.as_f64().filter(|n| (0.0..=100.0).contains(n)).unwrap_or(self.smoothness), + "smoothSmoothness" if matches!(self.id, "pencil" | "paintbrush" | "blobBrush") => { + self.smoothness = v.as_f64().filter(|n| (0.0..=100.0).contains(n)).unwrap_or(self.smoothness) + } "keepSelected" => self.keep_selected = v.as_bool().unwrap_or(self.keep_selected), "mergeOnlySelection" => self.merge_only_selection = v.as_bool().unwrap_or(self.merge_only_selection), "editWithin" => self.edit_within = v.as_f64().unwrap_or(self.edit_within).clamp(0.0, 100.0), @@ -2149,17 +2175,19 @@ impl Tool for GestureTool { _ => {} } } - /// The options the tool shows ([`Self::options`]), and the Smooth tool's Fidelity that the - /// Pencil, Paintbrush and Blob Brush smooth with while Alt is held (`smoothFidelity`). + /// The options the tool shows ([`Self::options`]), and the Smooth tool's Fidelity and Smoothness + /// that the Pencil, Paintbrush and Blob Brush smooth with while Alt is held (`smoothFidelity`, + /// `smoothSmoothness`). fn check_option(&self, key: &str, v: &Value) -> Result<(), String> { use crate::option_check as c; - let smooth_store = key == "smoothFidelity" && matches!(self.id, "pencil" | "paintbrush" | "blobBrush"); + let smooth_store = matches!(key, "smoothFidelity" | "smoothSmoothness") && matches!(self.id, "pencil" | "paintbrush" | "blobBrush"); if !smooth_store && self.options().get(key).is_none() { return Err(c::unknown(key)); } match key { "fidelity" => c::number(key, v, super::min_fidelity(self.id), 100.0), "smoothFidelity" => c::number(key, v, super::min_fidelity("smooth"), 100.0), + "smoothness" | "smoothSmoothness" => c::number(key, v, 0.0, 100.0), "size" => c::number(key, v, 0.1, 1000.0), "sizeVariation" => c::number(key, v, 0.0, 1000.0), "angle" => c::number(key, v, -180.0, 180.0), @@ -2167,9 +2195,9 @@ impl Tool for GestureTool { "editWithin" | "closeWithin" => c::number(key, v, 0.0, 100.0), "angleVariation" => c::number(key, v, 0.0, 180.0), "roundnessVariation" => c::number(key, v, 0.0, 100.0), - // The Blob Brush's Size is Fixed or Pressure; the Eraser's Angle, Roundness and Size - // take any mode (`set_option`). - "sizeMode" if self.id != "eraser" => c::one_of(key, v, &[Variation::Fixed.id(), Variation::Pressure.id()]), + // The Blob Brush's Size is Fixed, Pressure or Stylus Wheel; the Eraser's Angle, + // Roundness and Size take any mode (`set_option`). + "sizeMode" if self.id != "eraser" => c::one_of(key, v, &super::BLOB_SIZE_MODES.map(Variation::id)), "sizeMode" | "angleMode" | "roundnessMode" => c::one_of(key, v, &Variation::ALL.map(Variation::id)), "fill" | "altSmooth" | "livePreview" | "liveFit" | "keepSelected" | "mergeOnlySelection" => c::boolean(key, v), _ => Err(c::unknown(key)), diff --git a/crates/tools/src/draw2/gesture/tests.rs b/crates/tools/src/draw2/gesture/tests.rs index 24a0e1e5e6..db755ccae5 100644 --- a/crates/tools/src/draw2/gesture/tests.rs +++ b/crates/tools/src/draw2/gesture/tests.rs @@ -690,7 +690,10 @@ fn blob_brush_alt_switches_to_the_smooth_tool() { let acts = drag_held(&mut t, &cx, &stroke, alt); assert!(acts[..acts.len() - 1].iter().all(|a| a.is_empty()), "{acts:?}"); let v = smoothed(&acts).unwrap_or_else(|| panic!("{acts:?}")); - assert_eq!(v, json!({"points": [[50.0, 150.0], [150.0, 150.0], [250.0, 160.0]], "radius": cx.tol(12.0), "fidelity": cx.tol(SMOOTH_FIDELITY)})); + assert_eq!( + v, + json!({"points": [[50.0, 150.0], [150.0, 150.0], [250.0, 160.0]], "radius": cx.tol(12.0), "fidelity": cx.tol(SMOOTH_FIDELITY), "smoothness": SMOOTH_SMOOTHNESS}) + ); // Mid-drag the cursor stays the Smooth tool's when Alt is let go, and the line is thin with // no length label. t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 50.0, 150.0).with_mods(alt)); @@ -882,7 +885,7 @@ fn pencil_previews_a_redraw_as_the_stroke_drawn_and_redraws_at_the_release() { let previews: Vec<&Value> = drawing.iter().flatten().filter_map(|a| if let Action::Preview(_, v) = a { Some(v) } else { None }).collect(); assert!(!previews.is_empty(), "{acts:?}"); for v in previews { - assert!(v.get("redraw").is_none() && v["fill"] == false && v["keepSelected"] == false && v["leaveSelection"] == true, "{v}"); + assert!(v.get("redraw").is_none() && v["fill"] == false && v["keepSelected"] == false && v["preview"] == true, "{v}"); assert_eq!(v["points"][0], json!([350.0, 300.0]), "joined to the path where it starts: {v}"); assert_eq!(v["points"][1], json!([350.0, 304.0]), "{v}"); } @@ -1783,6 +1786,50 @@ fn alt_smoothing_uses_the_smooth_tools_fidelity() { } } +/// The Smooth tool sends Smooth Tool Options' Smoothness (50% until it is set) with each drag, and +/// an Alt smoothing drag with the Pencil, Paintbrush or Blob Brush sends the one the engine gives it +/// (`smoothSmoothness`). A value that is not a number from 0 to 100 is refused and sets nothing. +#[test] +fn smooth_drags_send_the_smoothness() { + let (d, id) = doc_with_rect(); + let mut s = Selection::default(); + s.set([id]); + let p = paint(); + let mut cx = cx(&d, &s, &p); + cx.smart_guides = false; + let pts = [(50.0, 150.0), (150.0, 150.0), (250.0, 160.0)]; + let smoothness = |acts: &[Vec]| match acts.last().and_then(|a| a.first()) { + Some(Action::Exec(c, v)) if c == "path.smoothRegion" => v["smoothness"].as_f64(), + a => panic!("expected path.smoothRegion, got: {a:?}"), + }; + let mut t = GestureTool::new("smooth"); + assert_eq!(t.options()["smoothness"], json!(50.0)); + assert_eq!(smoothness(&drag(&mut t, &cx, &pts, Mods::default())), Some(50.0)); + for bad in [json!(-1), json!(100.5), json!("30"), json!(true)] { + assert_eq!(t.check_option("smoothness", &bad), Err("`smoothness` must be a number from 0 to 100".into()), "{bad}"); + t.set_option("smoothness", &bad); + assert_eq!(t.options()["smoothness"], json!(50.0), "{bad}"); + } + for ok in [0.0, 75.0, 100.0] { + assert_eq!(t.check_option("smoothness", &json!(ok)), Ok(())); + t.set_option("smoothness", &json!(ok)); + assert_eq!(smoothness(&drag(&mut t, &cx, &pts, Mods::default())), Some(ok)); + } + let alt = Mods { alt: true, ..Default::default() }; + for (id, alt_smooth) in [("pencil", true), ("blobBrush", false), ("paintbrush", false)] { + let mut t = GestureTool::new(id); + t.set_option("altSmooth", &json!(alt_smooth)); + assert_eq!(smoothness(&drag_held(&mut t, &cx, &pts, alt)), Some(50.0), "{id}"); + assert_eq!(t.check_option("smoothSmoothness", &json!(101)), Err("`smoothSmoothness` must be a number from 0 to 100".into()), "{id}"); + t.set_option("smoothSmoothness", &json!(101)); + t.set_option("smoothness", &json!(20.0)); + assert_eq!(smoothness(&drag_held(&mut t, &cx, &pts, alt)), Some(50.0), "{id}: only smoothSmoothness sets it"); + t.set_option("smoothSmoothness", &json!(20.0)); + assert_eq!(smoothness(&drag_held(&mut t, &cx, &pts, alt)), Some(20.0), "{id}"); + assert!(t.options().get("smoothness").is_none() && t.options().get("smoothSmoothness").is_none(), "{id}"); + } +} + /// The Smooth tool's Fidelity is in screen pixels: the Smooth tool and an Alt smoothing drag with /// the Pencil, Paintbrush or Blob Brush send it in points at Fidelity / zoom, so a drag smooths as /// much on screen at any zoom. @@ -3314,7 +3361,10 @@ fn the_eraser_tip_follows_its_variation_modes() { assert_eq!(t.check_option("angleMode", &json!("wheel")), Err(format!("`angleMode` {modes}"))); assert_eq!(t.check_option("angleVariation", &json!(181)), Err("`angleVariation` must be a number from 0 to 180".into())); assert_eq!(t.check_option("roundnessVariation", &json!(500)), Err("`roundnessVariation` must be a number from 0 to 100".into())); - assert_eq!(GestureTool::new("blobBrush").check_option("sizeMode", &json!("tilt")), Err("`sizeMode` must be one of `fixed`, `pressure`".into())); + assert_eq!( + GestureTool::new("blobBrush").check_option("sizeMode", &json!("tilt")), + Err("`sizeMode` must be one of `fixed`, `pressure`, `stylusWheel`".into()) + ); // A mode it does not have leaves the mode as it was; a Variation is kept within its range. t.set_option("angleMode", &json!("wheel")); t.set_option("roundnessVariation", &json!(500)); @@ -3352,7 +3402,7 @@ fn the_eraser_tip_follows_its_variation_modes() { t.pointer(&cx, &PointerEvent { pressure: 0.5, ..PointerEvent::new(PointerKind::Drag, 200.0, 50.0) }); near(tip(&t), (190.0, 47.5, 210.0, 52.5)); t.pointer(&cx, &PointerEvent { pressure: 0.5, ..PointerEvent::new(PointerKind::Up, 200.0, 50.0) }); - // The Blob Brush's Size is Fixed or Pressure, and its Angle and Roundness have no menus. + // The Blob Brush's Size is Fixed, Pressure or Stylus Wheel, and its Angle and Roundness have no menus. let mut b = GestureTool::new("blobBrush"); b.set_option("sizeMode", &json!("tilt")); b.set_option("angleMode", &json!("rotation")); @@ -3362,6 +3412,77 @@ fn the_eraser_tip_follows_its_variation_modes() { assert_eq!(b.options()["sizeMode"], json!("pressure")); } +/// The Blob Brush's Size on Stylus Wheel follows the wheel the pen recorded, in the tip outline +/// while it paints (its roundness kept as set, 0% included) and in the points the release sends; +/// a pen that gives no wheel keeps the Size. +#[test] +fn the_blob_brush_size_follows_the_stylus_wheel() { + let (d, _) = doc_with_rect(); + let s = Selection::default(); + let p = paint(); + let cx = cx(&d, &s, &p); + let tip = |t: &GestureTool| match &t.overlays(&cx)[..] { + [.., Overlay::Path { path, color: [0, 0, 0], width: 1.0, .. }] => vectorcraft_geom::Shape::bounding_box(path), + o => panic!("{o:?}"), + }; + let near = |b: vectorcraft_geom::Rect, want: (f64, f64, f64, f64)| { + assert!([b.x0 - want.0, b.y0 - want.1, b.x1 - want.2, b.y1 - want.3].iter().all(|e| e.abs() < 0.01), "{b:?} vs {want:?}"); + }; + let mut t = GestureTool::new("blobBrush"); + assert_eq!(t.check_option("sizeMode", &json!("stylusWheel")), Ok(())); + for (k, v) in [("size", json!(20)), ("roundness", json!(50)), ("sizeMode", json!("stylusWheel")), ("sizeVariation", json!(8))] { + t.set_option(k, &v); + } + assert_eq!((t.options()["sizeMode"].clone(), t.options()["sizeVariation"].clone()), (json!("stylusWheel"), json!(8.0))); + // Before a press the outline is the set tip, 20 by 10 pt. + t.pointer(&cx, &PointerEvent::new(PointerKind::Move, 100.0, 50.0)); + near(tip(&t), (90.0, 45.0, 110.0, 55.0)); + // The wheel at the far end of its travel gives 28 by 14 pt, and half way 20 by 10. + let wheel = |w: Option| Some(PenPose { tilt: None, rotation: None, wheel: w }); + t.pointer(&cx, &PointerEvent { pen: wheel(Some(1.0)), ..PointerEvent::new(PointerKind::Down, 100.0, 50.0) }); + t.pointer(&cx, &PointerEvent { pen: wheel(Some(1.0)), ..PointerEvent::new(PointerKind::Drag, 200.0, 50.0) }); + near(tip(&t), (186.0, 43.0, 214.0, 57.0)); + t.pointer(&cx, &PointerEvent { pen: wheel(Some(0.5)), ..PointerEvent::new(PointerKind::Drag, 300.0, 50.0) }); + near(tip(&t), (290.0, 45.0, 310.0, 55.0)); + // The wheel turned with the pen held in place: the tip there and the release follow it. + t.pointer(&cx, &PointerEvent { pen: wheel(Some(0.0)), ..PointerEvent::new(PointerKind::Drag, 300.0, 50.0) }); + near(tip(&t), (294.0, 47.0, 306.0, 53.0)); + let acts = t.pointer(&cx, &PointerEvent { pen: wheel(Some(0.0)), ..PointerEvent::new(PointerKind::Up, 300.0, 50.0) }); + let Some(Action::Exec(c, v)) = acts.first() else { panic!("{acts:?}") }; + assert_eq!((c.as_str(), &v["sizeMode"], &v["sizeVariation"]), ("path.blob", &json!("stylusWheel"), &json!(8.0))); + assert_eq!( + v["points"], + json!([[100.0, 50.0, null, null, null, null, 1.0], [200.0, 50.0, null, null, null, null, 1.0], [300.0, 50.0, null, null, null, null, 0.0]]) + ); + // A pen without a wheel keeps the set tip. + t.pointer(&cx, &PointerEvent { pen: wheel(None), ..PointerEvent::new(PointerKind::Down, 100.0, 50.0) }); + t.pointer(&cx, &PointerEvent { pen: wheel(None), ..PointerEvent::new(PointerKind::Drag, 200.0, 50.0) }); + near(tip(&t), (190.0, 45.0, 210.0, 55.0)); + t.pointer(&cx, &PointerEvent { pen: wheel(None), ..PointerEvent::new(PointerKind::Up, 200.0, 50.0) }); + // A 0% round tip stays as flat as set while the wheel widens it. + t.set_option("roundness", &json!(0)); + t.pointer(&cx, &PointerEvent { pen: wheel(Some(1.0)), ..PointerEvent::new(PointerKind::Down, 100.0, 50.0) }); + t.pointer(&cx, &PointerEvent { pen: wheel(Some(1.0)), ..PointerEvent::new(PointerKind::Drag, 200.0, 50.0) }); + let flat = tip(&t); + assert!((flat.width() - 28.0).abs() < 0.01 && flat.height() < 0.1, "{flat:?}"); + t.pointer(&cx, &PointerEvent { pen: wheel(Some(1.0)), ..PointerEvent::new(PointerKind::Up, 200.0, 50.0) }); + // Size set from Fixed to Stylus Wheel or Pressure during a drag: the release reads no wheel or + // pressure for the points before it, so the tip keeps the Size, as the release paints. + t.set_option("roundness", &json!(50)); + for (mode, pressure) in [("stylusWheel", 1.0), ("pressure", 0.25)] { + t.set_option("sizeMode", &json!("fixed")); + let ev = |kind, x| PointerEvent { pen: wheel(Some(1.0)), pressure, ..PointerEvent::new(kind, x, 50.0) }; + t.pointer(&cx, &ev(PointerKind::Down, 100.0)); + t.pointer(&cx, &ev(PointerKind::Drag, 200.0)); + t.set_option("sizeMode", &json!(mode)); + t.pointer(&cx, &ev(PointerKind::Drag, 300.0)); + near(tip(&t), (290.0, 45.0, 310.0, 55.0)); + let acts = t.pointer(&cx, &ev(PointerKind::Up, 300.0)); + let Some(Action::Exec(_, v)) = acts.first() else { panic!("{acts:?}") }; + assert_eq!(v["points"], json!([[100.0, 50.0], [200.0, 50.0], [300.0, 50.0]]), "{mode}"); + } +} + /// An Eraser value on Stylus Wheel follows the wheel the pen recorded, in the tip outline while it /// erases and in the points the release sends; a pen that gives no wheel reads half way, the value /// itself. diff --git a/crates/tools/src/lib.rs b/crates/tools/src/lib.rs index 486de86876..acc5ff594e 100644 --- a/crates/tools/src/lib.rs +++ b/crates/tools/src/lib.rs @@ -639,6 +639,7 @@ pub(crate) mod testutil { shape_widgets: true, fill_active: true, gradient_stop: None, + tool_paints: false, appearance_item: None, constrain_angle: 0.0, keyboard_increment: 1.0, diff --git a/crates/tools/src/settings.rs b/crates/tools/src/settings.rs index 1d9d8c4a54..97b3c75cd2 100644 --- a/crates/tools/src/settings.rs +++ b/crates/tools/src/settings.rs @@ -63,7 +63,7 @@ const ROWS: &[Row] = &[ // Pencil Tool Options' Alt key toggles to Smooth Tool, Live preview and Live curve fitting (the // Paintbrush has none of them). (&["pencil"], None, &["altSmooth", "livePreview", "liveFit"]), - (&["smooth"], None, &["fidelity"]), + (&["smooth"], None, &["fidelity", "smoothness"]), (&["blobBrush", "eraser"], None, &["size", "sizeMode", "sizeVariation"]), (&["blobBrush"], None, &["fidelity", "keepSelected", "mergeOnlySelection"]), // Eraser Tool Options' tip shape. @@ -78,8 +78,8 @@ const ROWS: &[Row] = &[ (&["star"], None, &["points"]), // The Ellipse dialog's Anchors. (&["ellipse"], None, &["anchors"]), - // Circle Tool Options (`circle::CircleTool`). - (&[crate::circle::ID], None, &["center", "radii", "diameter", "color", "standardAnchors", "dragThird"]), + // Circle Tool Options (`circle::CircleTool`) and the Control bar's From Center. + (&[crate::circle::ID], None, &["center", "radii", "diameter", "color", "standardAnchors", "dragThird", "fromCenter"]), (&["freeTransform"], None, &["constrain"]), // Shape Builder Tool Options (`builder::ShapeBuilderOptions`). ( @@ -108,7 +108,7 @@ const ROWS: &[Row] = &[ (&[crate::addons::extend_path::ID], None, &["mode"]), (&[crate::addons::corner_tool::ID], None, &["radius", "kind"]), (&[crate::addons::shared_edge::ID], None, &["diameter", "tolerance", "together"]), - (&[crate::addons::tangent_circle::ID], None, &["radius"]), + (&[crate::addons::tangent_circle::ID], None, &["radius", "center", "radii", "color", "snapTolerance", "snapWithoutGuides"]), (&[crate::addons::smart_pen::ID], None, &["next"]), // The kind first: a new kind resets the values after it. (&[crate::addons::parametric_shape::ID], None, &["kind", "count", "a", "b", "radius", "width", "height", "rotation"]), diff --git a/crates/tools/src/xform/eyedropper.rs b/crates/tools/src/xform/eyedropper.rs index 0c63f2f21c..134b9b6069 100644 --- a/crates/tools/src/xform/eyedropper.rs +++ b/crates/tools/src/xform/eyedropper.rs @@ -16,8 +16,9 @@ //! //! The Gradient panel's eyedropper sets the `stop` option (the tool to return to): the next click //! samples the colour under the cursor into the selected gradient stop (`paint.sampleColor -//! {stop}`) and switches back to that tool. Armed for the Live Paint Bucket, a click once its stop -//! is no longer selected ends the pick without sampling and switches back to the bucket. +//! {stop}`) and switches back to that tool. Armed for a stop of the gradient a tool paints with +//! (the Live Paint Bucket's, the Shape Builder's fill), a click once its stop is no longer +//! selected ends the pick without sampling and switches back to that tool. //! //! Gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso before switching //! to the Eyedropper stay picked (its `meshPoints` option), and go back to one of those tools @@ -559,9 +560,9 @@ impl Tool for EyedropperTool { self.brush_key_color = false; vec![Action::Dialog("brushKeyColor".into(), json!({ "color": color_json(&c) })), Action::SwitchTool(back)] } - Click::BackToBucket => { + Click::Back(back) => { self.stop = None; - vec![Action::SwitchTool("livePaintBucket".into())] + vec![Action::SwitchTool(back)] } Click::MeshPoints(id, points, color) => { let params = json!({ "id": id.0, "points": points, "color": color_json(&color), "keepModel": true }); @@ -691,8 +692,9 @@ enum Click { ImageTrace(Value), /// Brush Options › Key Color: this color, sampled from this object. BrushKeyColor(Color, NodeId), - /// A pick for a Live Paint Bucket stop that is no longer selected switches back unsampled. - BackToBucket, + /// A pick for a stop of the gradient a tool paints with (the Live Paint Bucket's, the Shape + /// Builder's fill) that is no longer selected switches back to that tool unsampled. + Back(String), /// The fill color goes to these points of this selected gradient mesh. MeshPoints(NodeId, Vec, Color), /// `appearance.copyFrom` this source, with `reverse` or `append` or neither. @@ -707,7 +709,7 @@ impl Click { /// The object of the document the click reads from or writes to. fn object(&self) -> Option { match self { - Click::ImageTrace(_) | Click::BackToBucket => None, + Click::ImageTrace(_) | Click::Back(_) => None, Click::BrushKeyColor(_, id) | Click::MeshPoints(id, ..) | Click::CopyFrom(id, _) | Click::Sample { source: id, .. } => Some(*id), } } @@ -728,13 +730,17 @@ impl EyedropperTool { let (c, source) = sample_at(cx, p)?; return Some(Click::BrushKeyColor(c, source)); } - // A pick for a stop of the Live Paint Bucket's gradient (the default paint's) ends without + // A pick for a stop of the gradient of a tool that paints with the chosen colors (the + // default paint's: the Live Paint Bucket's, or the Shape Builder's fill) ends without // sampling once that stop is no longer selected (a Cmd-click selected another object) or no // longer there (another paint was chosen): the click switches back. - let bucket_paint = if cx.fill_active { &cx.paint.fill } else { &cx.paint.stroke }; - let bucket_stop = cx.gradient_stop.filter(|i| matches!(bucket_paint, Paint::Gradient(g) if *i < g.gradient.stops.len())); - if self.stop.as_deref() == Some("livePaintBucket") && bucket_stop.is_none() { - return Some(Click::BackToBucket); + let tool_paint = if cx.fill_active { &cx.paint.fill } else { &cx.paint.stroke }; + let tool_stop = cx.gradient_stop.filter(|i| matches!(tool_paint, Paint::Gradient(g) if *i < g.gradient.stops.len())); + if cx.tool_paints + && tool_stop.is_none() + && let Some(back) = &self.stop + { + return Some(Click::Back(back.clone())); } let stop = self.stop.clone().zip(cx.gradient_stop); // A plain click on a selected gradient mesh gives the fill color to the point there, else @@ -934,19 +940,23 @@ mod tests { ] ); assert_eq!(t.options(), json!({"stop": null, "brushKeyColor": false}), "one sample only"); - // Armed for the Live Paint Bucket with its stop no longer selected, a click ends the pick. - cx.gradient_stop = None; - t.set_option("stop", &json!("livePaintBucket")); - let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 100.0, 150.0)); - assert_eq!(a, vec![Action::SwitchTool("livePaintBucket".into())]); - assert_eq!(t.returns_to(), None); - // So does a click once the default paint has no such stop (here, a solid fill). - cx.gradient_stop = Some(1); - assert!(!matches!(cx.paint.fill, Paint::Gradient(_))); - t.set_option("stop", &json!("livePaintBucket")); - assert_eq!(t.returns_to(), Some("livePaintBucket")); - let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 100.0, 150.0)); - assert_eq!(a, vec![Action::SwitchTool("livePaintBucket".into())]); + // Armed for a tool that paints with the chosen colors (the Live Paint Bucket, or the Shape + // Builder's fill) with its stop no longer selected, a click ends the pick. + cx.tool_paints = true; + for back in ["livePaintBucket", "shapeBuilder"] { + cx.gradient_stop = None; + t.set_option("stop", &json!(back)); + let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 100.0, 150.0)); + assert_eq!(a, vec![Action::SwitchTool(back.into())]); + assert_eq!(t.returns_to(), None); + // So does a click once the default paint has no such stop (here, a solid fill). + cx.gradient_stop = Some(1); + assert!(!matches!(cx.paint.fill, Paint::Gradient(_))); + t.set_option("stop", &json!(back)); + assert_eq!(t.returns_to(), Some(back)); + let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 100.0, 150.0)); + assert_eq!(a, vec![Action::SwitchTool(back.into())]); + } // Neither a Key Color pick nor an Image Trace ignored-color pick is a gradient stop's. t.set_option("brushKeyColor", &json!(true)); t.set_option("stop", &json!("livePaintBucket")); diff --git a/crates/tools/src/xform/transform.rs b/crates/tools/src/xform/transform.rs index d0ff487af8..9483dea88f 100644 --- a/crates/tools/src/xform/transform.rs +++ b/crates/tools/src/xform/transform.rs @@ -128,6 +128,11 @@ pub struct TransformTool { snap: Option, } +/// The selected objects and ruler guides, which a reference point set by a click belongs to. +fn selected_ids(cx: &ToolContext) -> Vec { + cx.selection.objects.iter().chain(&cx.selection.guides).copied().collect() +} + fn about(o: Point, a: Affine) -> Affine { Affine::translate(o.to_vec2()) * a * Affine::translate(-o.to_vec2()) } @@ -170,10 +175,11 @@ impl TransformTool { } /// The effective reference point: the custom one if it belongs to the current selection, - /// otherwise the centre of its bounding box (rotated with rotated objects). + /// otherwise the centre of its bounding box (rotated with rotated objects). With ruler guides + /// selected, it is the center of the objects' box and the guides' lines together. pub fn reference_point(&self, cx: &ToolContext) -> Option { if let Some((p, ids)) = &self.origin - && *ids == cx.selection.objects + && *ids == selected_ids(cx) && !ids.is_empty() { return Some(*p); @@ -181,7 +187,29 @@ impl TransformTool { // Anchors selected with Direct Selection transform alone, about their own centre. vectorcraft_effects::preview::anchor_bounds_with(cx.selection, cx.doc, cx.bounds_measure()) .map(|b| b.center()) - .or_else(|| selection_box(cx).map(|b| b.center())) + .or_else(|| if self.guide_lines(cx).is_empty() { selection_box(cx).map(|b| b.center()) } else { self.bounds(cx).map(|b| b.center()) }) + } + + /// The selected ruler guides the tool transforms, as the boxes of the lines they stand for + /// ([`vectorcraft_doc::Document::guide_line`]): those that can be edited, with objects + /// selected, and with the Rotate tool also without. + fn guide_lines(&self, cx: &ToolContext) -> Vec { + if cx.selection.is_empty() && self.kind != TransformKind::Rotate { + return vec![]; + } + let d = cx.doc; + let guides = cx.selection.guides.iter().filter_map(|id| d.ruler_guide(*id)).filter(|g| d.guide_editable(g)); + guides.filter_map(|g| d.guide_line(&g)).map(|(a, b)| Rect::from_points(a, b)).collect() + } + + /// The bounding box of the selected objects and the lines of the guides the tool transforms. + fn bounds(&self, cx: &ToolContext) -> Option { + self.guide_lines(cx).into_iter().fold(selection_bounds(cx), |acc, r| Some(acc.map_or(r, |acc| acc.union(r)))) + } + + /// Is there anything selected for the tool to transform? + fn has_target(&self, cx: &ToolContext) -> bool { + !cx.selection.is_empty() || !self.guide_lines(cx).is_empty() } /// Transform for dragging from `start` to `p` about `o`; returns the matrix and a readout. @@ -331,7 +359,7 @@ impl Tool for TransformTool { let p = ev.pos; match ev.kind { PointerKind::Down => { - let Some(bounds) = selection_bounds(cx) else { return vec![] }; + let Some(bounds) = self.bounds(cx) else { return vec![] }; self.hover.clear(); let (pick, _) = snap_pick(cx, p); // Alt: decided on release. A click sets the point and opens the dialog; a drag @@ -422,7 +450,7 @@ impl Tool for TransformTool { } else { // A click sets the reference point; with Alt, it opens the dialog too. With the // Reflect tool, a plain click also sets the first point of an axis. - self.origin = Some((d.pick, cx.selection.objects.clone())); + self.origin = Some((d.pick, selected_ids(cx))); self.drop_axis(); if d.alt { vec![self.dialog(d.pick)] @@ -450,7 +478,7 @@ impl Tool for TransformTool { PointerKind::TripleClick => vec![], PointerKind::Move => { if self.drag.is_none() { - let (pick, hover) = if cx.selection.is_empty() { (p, vec![]) } else { snap_pick(cx, p) }; + let (pick, hover) = if self.has_target(cx) { snap_pick(cx, p) } else { (p, vec![]) }; self.hover = hover; self.axis_to = self.axis_first(cx).map(|_| pick); } @@ -525,7 +553,7 @@ impl Tool for TransformTool { } fn cursor(&self, cx: &ToolContext, _p: Point, _m: Mods) -> Cursor { - if cx.selection.is_empty() { + if !self.has_target(cx) { return Cursor::NotAllowed; } match self.kind { @@ -657,6 +685,35 @@ mod tests { assert_eq!(up.last(), Some(&Action::Commit)); } + /// With only a ruler guide selected, the Rotate tool drags about the middle of the guide's + /// line, and Alt-click opens its dialog; the Scale tool still needs objects. + #[test] + fn the_rotate_tool_turns_a_selected_ruler_guide_alone() { + let mut d = vectorcraft_doc::Document::new(500.0, 500.0); + let g = d.add_ruler_guide(&vectorcraft_doc::Guide::new(true, 100.0)); + let mut s = Selection::default(); + s.guides.push(g); + let p = paint(); + let cx = cx(&d, &s, &p); + let mut t = TransformTool::new(TransformKind::Rotate); + assert_eq!(t.reference_point(&cx), Some(Point::new(100.0, 250.0))); + assert_ne!(t.cursor(&cx, Point::ZERO, Mods::default()), Cursor::NotAllowed); + assert!(t.pointer(&cx, &ev(PointerKind::Down, 200.0, 250.0)).is_empty()); + let a = t.pointer(&cx, &ev(PointerKind::Drag, 100.0, 350.0)); + assert_eq!(a[0], Action::Begin("Rotate".into())); + let m = matrix(&a[1]); + assert!((m * Point::new(100.0, 250.0)).distance(Point::new(100.0, 250.0)) < 1e-9); + assert!((m * Point::new(200.0, 250.0)).distance(Point::new(100.0, 350.0)) < 1e-9); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, 100.0, 350.0)).last(), Some(&Action::Commit)); + t.pointer(&cx, &ev(PointerKind::Down, 50.0, 60.0).with_mods(alt())); + let up = t.pointer(&cx, &ev(PointerKind::Up, 50.0, 60.0).with_mods(alt())); + assert!(matches!(up.as_slice(), [Action::Dialog(id, _)] if id == "rotate"), "{up:?}"); + let mut scale = TransformTool::new(TransformKind::Scale); + assert_eq!(scale.reference_point(&cx), None); + assert!(scale.pointer(&cx, &ev(PointerKind::Down, 200.0, 250.0)).is_empty()); + assert!(scale.pointer(&cx, &ev(PointerKind::Drag, 100.0, 350.0)).is_empty()); + } + #[test] fn click_sets_reference_point_then_drag_uses_it() { let (d, id) = doc_with_rect(); diff --git a/crates/ui-egui/src/addons/pathtools.rs b/crates/ui-egui/src/addons/pathtools.rs index 307d4a3e29..8765b57c00 100644 --- a/crates/ui-egui/src/addons/pathtools.rs +++ b/crates/ui-egui/src/addons/pathtools.rs @@ -301,7 +301,18 @@ fn options_params(tool: &str, lengths: LengthUnits) -> Vec { if tool == tangent_circle_tool::ID { let (lo, hi) = tangent_circle_tool::RADIUS_RANGE; let kind = ParamKind::number(Some(lo), Some(hi), tangent_circle_tool::RADIUS, 1.0, 2); - return vec![Param::new("radius", tl!("Radius"), kind).length(lengths)]; + let colors = + tangent_circle_tool::COLORS.iter().zip(TANGENT_CIRCLE_COLORS).map(|((name, _), label)| ((*name).to_owned(), tl!(label).into())).collect(); + let (snap_lo, snap_hi) = tangent_circle_tool::SNAP_RANGE; + let snap = ParamKind::number(Some(snap_lo), Some(snap_hi), tangent_circle_tool::SNAP_PX, 1.0, 2); + return vec![ + Param::new("radius", tl!("Radius"), kind).length(lengths), + Param::new("center", tl!("Circle Center"), ParamKind::bool(true)), + Param::new("radii", tl!("Circle Radii Lines"), ParamKind::bool(true)), + Param::new("color", tl!("Color"), ParamKind::choice(colors, Some("red".into()))), + Param::new("snapTolerance", tl!("Snap Tolerance"), snap).unit(UnitKind::Pixels), + Param::new("snapWithoutGuides", tl!("Snap When Smart Guides Are Off"), ParamKind::bool(true)), + ]; } let (size, tolerance) = (anchor_eraser::SIZE_RANGE, anchor_eraser::TOLERANCE_RANGE); vec![ @@ -311,6 +322,9 @@ fn options_params(tool: &str, lengths: LengthUnits) -> Vec { ] } +/// The labels of the Tangent Circle tool's colors ([`tangent_circle_tool::COLORS`]), in its order. +const TANGENT_CIRCLE_COLORS: [&str; 6] = ["Red", "Blue", "Magenta", "Green", "Black", "Gray"]; + /// Open the options of add-on tool `tool` with its current values. OK sets them; when the tool refuses one, the dialog /// stays open with the reason. pub fn open_options(app: &mut VectorcraftApp, tool: &str) -> Result { diff --git a/crates/ui-egui/src/addons/pathtools/shape.rs b/crates/ui-egui/src/addons/pathtools/shape.rs index e32ece3450..7a666e695e 100644 --- a/crates/ui-egui/src/addons/pathtools/shape.rs +++ b/crates/ui-egui/src/addons/pathtools/shape.rs @@ -70,6 +70,13 @@ pub(super) fn target(app: &VectorcraftApp) -> (Option, ParametricShape) (None, apply(fallback, &app.session.tool_options_of(tool::ID)).unwrap_or(fallback)) } +/// Whether anchors are direct-selected, so that the selection's box is the box around them. +fn anchors_selected(app: &VectorcraftApp) -> bool { + app.session + .active() + .is_some_and(|st| vectorcraft_effects::preview::anchor_bounds_with(&st.selection, &st.doc, app.session.bounds_measure()).is_some()) +} + /// Whether something is selected and none of it is a parametric shape Convert could take. pub(super) fn plain_selected(app: &VectorcraftApp) -> bool { app.session.active().is_some_and(|st| !st.selection.is_empty()) && selected(app).is_none() @@ -143,6 +150,12 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { match (change, id) { (Some(mut p), Some(id)) => { p["id"] = json!(id.0); + // The Transform panel and the Control bar share one reference point locator. W and H + // keep the point of the shape's bounding box chosen there in place. With anchors + // direct-selected the locator shows their box, so the shape keeps its center instead. + if p.get("width").or_else(|| p.get("height")).is_some() && !anchors_selected(app) { + p["reference"] = json!(app.ui.transform_panel.reference_point); + } run(app, "addon.pathtools.shape.set", p); } (Some(values), None) => run(app, "tool.setOption", json!({ "tool": tool::ID, "values": values })), diff --git a/crates/ui-egui/src/addons/pathtools/tests.rs b/crates/ui-egui/src/addons/pathtools/tests.rs index 464ce72f42..3c7af267e9 100644 --- a/crates/ui-egui/src/addons/pathtools/tests.rs +++ b/crates/ui-egui/src/addons/pathtools/tests.rs @@ -93,6 +93,90 @@ fn double_clicking_the_brush_opens_its_options_and_ok_sets_them() { assert_eq!(KIND, "pathToolOptions"); } +/// The Tangent Circle tool's options dialog shows the preview and snapping options, OK sets them, +/// and a value the tool refuses sets none of them and keeps the dialog open. +#[test] +fn the_tangent_circle_options_set_the_preview_and_snapping() { + let mut app = app_with_window(); + let ctx = host::ctx(&app); + let ok = |app: &mut VectorcraftApp, set: &[(&str, FieldValue)]| { + held(app, |d| { + let d = d.expect("the held dialog"); + for (key, value) in set { + d.set_field(*key, value.clone()); + } + }); + app.dialogs().expect("the window's dialogs").with(|h| h.confirm::(&ctx)); + crate::dialogs::host::pump(app, &ctx); + crate::tests_synthetic::key_frame(app, &ctx, vec![]); + }; + app.run("tool.options", json!({"tool": "tangentCircle"})).unwrap(); + let shown = held(&app, |d| { + let f = d.expect("the held dialog").fields(); + (f.bool("center"), f.bool("radii"), f.text("color").map(str::to_owned), f.number("snapTolerance"), f.bool("snapWithoutGuides")) + }); + assert_eq!(shown, (Some(true), Some(true), Some("red".to_owned()), Some(3.0), Some(true))); + ok( + &mut app, + &[ + ("center", FieldValue::Bool(false)), + ("radii", FieldValue::Bool(false)), + ("color", FieldValue::Text("magenta".into())), + ("snapTolerance", FieldValue::Number(9.0)), + ("snapWithoutGuides", FieldValue::Bool(false)), + ], + ); + assert!(held(&app, |d| d.is_none()), "OK closes the dialog"); + let o = app.session.tool_options_of("tangentCircle"); + assert_eq!((&o["center"], &o["radii"], &o["color"], &o["snapWithoutGuides"]), (&json!(false), &json!(false), &json!("magenta"), &json!(false))); + assert_eq!(o["snapTolerance"].as_f64(), Some(9.0)); + // A negative tolerance is refused: nothing changes and the dialog stays open. + app.run("tool.options", json!({"tool": "tangentCircle"})).unwrap(); + ok(&mut app, &[("center", FieldValue::Bool(true)), ("snapTolerance", FieldValue::Number(-2.0))]); + assert!(held(&app, |d| d.is_some()), "a refusal keeps the dialog open"); + let o = app.session.tool_options_of("tangentCircle"); + assert_eq!((&o["center"], o["snapTolerance"].as_f64()), (&json!(false), Some(9.0))); +} + +/// The Tangent Circle tool's options dialog has a row for each option, a fractional snapping +/// tolerance opens as it is, and every color has a label, in the tool's order. +#[test] +fn the_tangent_circle_options_have_their_rows_and_a_fractional_tolerance() { + use craft::ui::patterns::form_dialogs::ParamKind; + let mut app = app_with_window(); + let params = super::options_params("tangentCircle", crate::canvas::rulers::general_lengths(&app)); + let rows: Vec<(&str, &str)> = params.iter().map(|p| (p.key.as_str(), p.label.as_str())).collect(); + assert_eq!( + rows, + [ + ("radius", "Radius"), + ("center", "Circle Center"), + ("radii", "Circle Radii Lines"), + ("color", "Color"), + ("snapTolerance", "Snap Tolerance"), + ("snapWithoutGuides", "Snap When Smart Guides Are Off"), + ] + ); + let colors = params.iter().find_map(|p| match &p.kind { + ParamKind::Choice { options, .. } if p.key == "color" => { + Some(options.iter().map(|(id, label)| (id.clone(), label.as_str().to_owned())).collect::>()) + } + _ => None, + }); + let expected: Vec<(String, String)> = vectorcraft_tools::addons::tangent_circle::COLORS + .iter() + .zip(super::TANGENT_CIRCLE_COLORS) + .map(|((name, _), label)| ((*name).to_owned(), label.to_owned())) + .collect(); + assert_eq!(colors, Some(expected)); + for (name, _) in vectorcraft_tools::addons::tangent_circle::COLORS { + assert!(super::TANGENT_CIRCLE_COLORS.iter().any(|label| label.to_lowercase() == *name), "{name} has a label"); + } + app.run("tool.setOption", json!({"tool": "tangentCircle", "values": {"snapTolerance": 7.5}})).unwrap(); + app.run("tool.options", json!({"tool": "tangentCircle"})).unwrap(); + assert_eq!(held(&app, |d| d.expect("the held dialog").fields().number("snapTolerance")), Some(7.5)); +} + #[test] fn the_parametric_shape_panel_edits_the_selected_shape_or_the_tools_next_one() { let mut app = app(); @@ -112,6 +196,44 @@ fn the_parametric_shape_panel_edits_the_selected_shape_or_the_tools_next_one() { assert!(id.is_none() && super::shape::plain_selected(&app)); } +/// The panel's W and H keep the point of the selection's box that the Transform panel and the +/// Control bar share in place, as their own W and H do, on upright and turned shapes. +#[test] +fn the_parametric_shape_panels_size_fields_keep_the_shared_reference_point() { + for (refi, rotation) in [(0usize, 0.0), (8, 0.0), (2, 30.0), (0, 180.0)] { + let mut app = app(); + let params = json!({"kind": "rectangle", "center": [150, 150], "width": 100, "height": 60, "rotation": rotation}); + let id = vectorcraft_doc::NodeId(app.run("addon.pathtools.shape.create", params).unwrap()["id"].as_u64().unwrap()); + let shape = + |app: &VectorcraftApp| vectorcraft_tools::addons::parametric_shape::read(app.session.active().unwrap().doc.node(id).unwrap()).unwrap(); + app.ui.transform_panel.reference_point = refi; + let (before, was) = (shape(&app), app.selection_box().unwrap().reference_point(refi)); + let mut panel = Panel::new(app, super::shape::show); + panel.type_into("W", "160"); + panel.type_into("H", "20"); + let mut app = panel.app(); + let after = shape(&app); + assert!(after.width > before.width && after.height < before.height, "reference {refi}: W and H took {after:?}"); + let moved = app.selection_box().unwrap().reference_point(refi).distance(was); + assert!(moved < 1e-6, "reference {refi}, rotation {rotation}: the reference point moved {moved} pt"); + } + // With an anchor direct-selected the locator shows the anchors' box, so W keeps the shape's center. + let mut app = app(); + let params = json!({"kind": "rectangle", "center": [150, 150], "width": 100, "height": 60}); + let id = vectorcraft_doc::NodeId(app.run("addon.pathtools.shape.create", params).unwrap()["id"].as_u64().unwrap()); + app.session + .select(|_, sel| { + sel.anchors.insert(id, [(0, 1)].into_iter().collect()); + }) + .unwrap(); + app.ui.transform_panel.reference_point = 0; + let mut panel = Panel::new(app, super::shape::show); + panel.type_into("W", "160"); + let app = panel.app(); + let after = vectorcraft_tools::addons::parametric_shape::read(app.session.active().unwrap().doc.node(id).unwrap()).unwrap(); + assert!((after.width - 160.0).abs() < 1e-6 && after.center.distance(vectorcraft_geom::Point::new(150.0, 150.0)) < 1e-6, "{after:?}"); +} + /// The Corner Tool and Shared Edge Merge Tool items leave a floating Anchor Inspector showing /// instead of closing it, and in Presentation Mode they choose the tool without failing. #[test] diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 2f25c3ea4d..6c4f808359 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -185,6 +185,7 @@ impl VectorcraftApp { titlebar_inset: 0.0, last_effect: None, last_pathfinder: None, + last_filters: Default::default(), character_focus: None, run_count: 0, channel: None, @@ -382,7 +383,8 @@ impl VectorcraftApp { self.host = Arc::new(self.host.with_lang(lang)); } let native_ppp = self.ui_ctx.as_ref().map_or(1.0, |ctx| ctx.pixels_per_point() / ctx.zoom_factor()); - let root = root_env(&self.session.prefs, native_ppp); + // The canvas steps through the zoom stops of the current window's display. + let root = root_env(&self.session.prefs, native_ppp, self.print_ppi()); FrameInput::new(root).commands(menus::model::command_input(self)).host(self.host.clone()) } @@ -441,6 +443,9 @@ impl VectorcraftApp { let now = self.now(); self.perf.fps = self.frame_rate.frame(now, self.perf.frame_ms / 1000.0); self.sync_views(); + // A document that moved between the main window and a floating OS window, or opened, takes + // the density of the display that shows it. + self.settle_screen_ppi_if_changed(); self.refresh_replace_font_warning(false); updates_ui::tick(self, ctx); // Read the system clipboard only when that alone decides whether Paste is enabled. A @@ -692,15 +697,16 @@ impl VectorcraftApp { } /// The root values the preferences give every frame: the theme, the interface scale (UI Scaling -/// over the display's `native_ppp`), Show Tool Tips, the zoom stops and which drags scrub a value -/// (Scrub Numeric Fields: the side label only, or nothing). -pub(crate) fn root_env(prefs: &vectorcraft_engine::Prefs, native_ppp: f32) -> RootEnv { +/// over the display's `native_ppp`), Show Tool Tips, the zoom stops (100% at `print` screen points +/// to an inch, [`crate::state::print_ppi`]) and which drags scrub a value (Scrub Numeric Fields: the +/// side label only, or nothing). +pub(crate) fn root_env(prefs: &vectorcraft_engine::Prefs, native_ppp: f32, print: Option) -> RootEnv { let (theme, mode, accent) = theme::root_theme(prefs); // A hand-edited preferences file must not scale the interface to nothing. let scaling = if prefs.ui_scaling.is_finite() && prefs.ui_scaling > 0.0 { prefs.ui_scaling as f32 } else { 1.0 }; let mut root = RootEnv::new().theme(theme).mode(mode).accent(accent).scale(Scale::new(scaling)).tooltips(prefs.show_tool_tips); root.sizes = theme::app_sizes(); - root.values.set(view::zoom_scheme(prefs, native_ppp)); + root.values.set(view::zoom_scheme(print, native_ppp)); root.values.set(if prefs.scrub_numeric_fields { ScrubDrags::LabelOnly } else { ScrubDrags::Off }); // Number fields as production drew them: the value and its unit one run at the start ("720 pt"), percentages // whole and lengths to a thousandth of a point (357.114 pt). diff --git a/crates/ui-egui/src/app/commands.rs b/crates/ui-egui/src/app/commands.rs index c912a62fa7..23332c10cd 100644 --- a/crates/ui-egui/src/app/commands.rs +++ b/crates/ui-egui/src/app/commands.rs @@ -81,6 +81,9 @@ impl VectorcraftApp { if id == "prefs.import" && result.is_ok() { crate::prefs_dialog::imported(self, touch_workspace); } + if let Ok(r) = &result { + crate::plugin_runs::show_notice(self, id, r); + } placing::settle_swatch_paste(self); result } @@ -234,6 +237,7 @@ impl VectorcraftApp { return Err(e); } let spot_base = panels::color_guide::before_command(self); + let plugins_before = dialogs::plugin::before_command(); let r = self.session.execute(id, ¶ms).map_err(|e| e.to_string()); let r = panels::actions::after_recorded_command(self, r); if r.is_ok() @@ -241,6 +245,8 @@ impl VectorcraftApp { { self.last_pathfinder = Some(op.to_string()); } + // A filter plug-in run becomes Object › Plug-ins › Apply Last Filter. + dialogs::plugin::after_command(self, id, ¶ms, &r, plugins_before); let copied = r.is_ok() && self.publish_copy(id); self.sync_views(); self.refresh_replace_font_warning(false); diff --git a/crates/ui-egui/src/app/view.rs b/crates/ui-egui/src/app/view.rs index 4d27ffa98d..874146e102 100644 --- a/crates/ui-egui/src/app/view.rs +++ b/crates/ui-egui/src/app/view.rs @@ -19,10 +19,21 @@ pub(crate) fn navigation(p: &Prefs) -> NavigationOptions { options } -/// The zoom rungs and range of the app, with 100 % at the device zoom Display Print Size at 100 % -/// Zoom gives on a display of `native_ppp` pixels per point. -pub(crate) fn zoom_scheme(p: &Prefs, native_ppp: f32) -> ZoomScheme { - ZoomScheme::ILLUSTRATOR.with_hundred(crate::state::zoom_baseline(p.display_print_size) * f64::from(native_ppp)) +/// The zoom rungs and range of the app, with 100 % at the device zoom that shows a document inch in +/// `print` screen points ([`crate::state::print_ppi`]; one document point per screen point when +/// `None`) on a display of `native_ppp` pixels per point. +pub(crate) fn zoom_scheme(print: Option, native_ppp: f32) -> ZoomScheme { + ZoomScheme::ILLUSTRATOR.with_hundred(crate::state::zoom_baseline(print) * f64::from(native_ppp)) +} + +/// Whether view command `command` fits the view to the window (`Some(true)`), sets a zoom +/// percentage (`Some(false)`), or leaves the zoom alone (`None`). +pub(crate) fn fits_window(command: ViewCommands) -> Option { + match command { + ViewCommands::FitOnScreen | ViewCommands::FillScreen | ViewCommands::FitArtboard | ViewCommands::FitLayers => Some(true), + ViewCommands::RotateClockwise | ViewCommands::RotateCounterclockwise | ViewCommands::ResetRotation => None, + _ => Some(false), + } } impl VectorcraftApp { @@ -47,8 +58,11 @@ impl VectorcraftApp { } self.views.truncate(docs.len()); self.views.extend(docs.iter().skip(self.views.len()).map(View::of)); + // A new view counts its zoom from the main window's display, where it is first shown. + let main = self.main_ppi(); for (view, doc) in self.views.iter_mut().zip(docs) { view.artboard = view.artboard.min(doc.doc.artboards.len().saturating_sub(1)); + view.shown_ppi.get_or_insert(main); } let uids: Vec = docs.iter().map(|d| d.uid).collect(); if let Some(ctx) = &self.ui_ctx { @@ -135,6 +149,169 @@ impl VectorcraftApp { self.session.active().map_or(vectorcraft_geom::Point::ZERO, |d| d.doc.ruler_origin_for(artboard)) } + /// The screen points an inch takes at 100% zoom with Display Print Size at 100% Zoom on, for + /// the current window's display; `None` with it off ([`crate::state::print_ppi`]). + pub(crate) fn print_ppi(&self) -> Option { + self.print_ppi_of(crate::doc_windows::current(self)) + } + + /// [`Self::print_ppi`] for window `w`: the density its view's zoom counts from, which is the + /// density of the display that shows it once [`Self::settle_screen_ppi`] has run. + pub(crate) fn print_ppi_of(&self, w: Option) -> Option { + let counted = w.and_then(|w| crate::doc_windows::view(self, w)?.shown_ppi); + let ppi = counted.unwrap_or_else(|| w.map_or(self.main_ppi(), |w| self.window_ppi(w))); + crate::state::print_ppi(self.session.prefs.display_print_size, ppi.ppi()) + } + + /// The density of the display that shows window `w`: its own OS window's when it floats in one + /// that the host found on a display, else the main window's ([`Self::main_ppi`]). + fn window_ppi(&self, w: crate::doc_windows::Win) -> crate::ScreenPpi { + crate::doc_windows::screen_ppi(self, w).unwrap_or(self.main_ppi()) + } + + /// The density the main window's views count from: the host's reading, or while the main + /// window's display has not answered, the last reading, so every view there counts from the + /// same density. + fn main_ppi(&self) -> crate::ScreenPpi { + match self.services.screen_ppi { + crate::ScreenPpi::Unread => self.canvas.windows.main_read.unwrap_or(crate::ScreenPpi::Unread), + read => read, + } + } + + /// Takes `ppi` as the density the host read for the main window's display, `None` for a + /// display that reports no size ([`crate::Services::screen_ppi`]), and settles the views + /// ([`Self::settle_screen_ppi`]). Returns whether the density changed. + pub fn set_screen_ppi(&mut self, ppi: Option) -> bool { + self.set_screen_reading(crate::ScreenPpi::Read(ppi)) + } + + /// [`Self::set_screen_ppi`] with the host's reading, [`crate::ScreenPpi::Unread`] while the + /// main window's display is unknown or has not answered. + pub fn set_screen_reading(&mut self, ppi: crate::ScreenPpi) -> bool { + if self.services.screen_ppi == ppi { + return false; + } + // A switch of the preference made since the last frame applies before the reading does. + self.follow_print_size_switch(); + self.services.screen_ppi = ppi; + if ppi != crate::ScreenPpi::Unread && self.session.prefs.display_print_size { + self.canvas.windows.main_read = Some(ppi); + } + self.settle_screen_ppi(); + true + } + + /// Gives each window's view the density of the display that shows it. With Display Print Size + /// at 100% Zoom on, a view moved between two displays the host has read keeps its zoom + /// percentage (a display that reports no size counts 96 points to an inch), so the art keeps + /// its physical size on the new display; the views of other displays keep their zoom. At the + /// first reading of a view's display, a view that still has the zoom a fit or the document's + /// saved view gave it keeps that zoom, and any other view keeps its percentage, counted from + /// 96 points to an inch until then. + pub(crate) fn settle_screen_ppi(&mut self) { + for w in crate::doc_windows::windows(self) { + self.settle_window_ppi(w, true); + } + } + + /// [`Self::settle_screen_ppi`] for window `w` alone. With `keep` false (a fit made for the + /// window), the view counts from the display's reading, without a change of zoom; while the + /// display is being read, it counts from the last reading, and the reading still to come + /// leaves its zoom alone. + pub(crate) fn settle_window_ppi(&mut self, w: crate::doc_windows::Win, keep: bool) { + let on = self.session.prefs.display_print_size; + let now = self.window_ppi(w); + let reading = crate::doc_windows::screen_ppi(self, w).unwrap_or(self.services.screen_ppi); + let Some(v) = crate::doc_windows::view_mut(self, w) else { return }; + // Off, a view counts from no reading, so the first one after the preference is turned on + // keeps the zoom chosen meanwhile. + if !on { + v.shown_ppi = Some(crate::ScreenPpi::Unread); + v.fit_unread = false; + return; + } + if !keep { + // While the display is being read, the fit counts from the last reading, as the other + // views there do, and the reading keeps its zoom. A floating window whose display has + // not answered keeps counting from the density it was last shown at. + match now { + crate::ScreenPpi::Unread => { + v.shown_ppi.get_or_insert(now); + } + read => v.shown_ppi = Some(read), + } + v.fit_unread = reading == crate::ScreenPpi::Unread; + return; + } + // A fit made while its display is being read waits for that reading. + if v.fit_unread && reading == crate::ScreenPpi::Unread { + return; + } + // A display that has not answered yet leaves the view counting from the last one read, so + // the answer, when it comes, keeps the zoom percentage. + let crate::ScreenPpi::Read(after) = now else { + v.shown_ppi.get_or_insert(now); + return; + }; + let fitted = v.fit_zoom == Some(v.zoom); + let before = match v.shown_ppi { + _ if fitted && v.fit_unread => None, + Some(crate::ScreenPpi::Read(before)) => Some(before), + _ if fitted => None, + _ => Some(None), + }; + v.fit_unread = false; + if let Some(before) = before + && before != after + && let (Some(b), Some(a)) = (crate::state::print_ppi(on, before), crate::state::print_ppi(on, after)) + { + v.zoom = (v.zoom * a / b).clamp(0.0313, 640.0); + } + v.shown_ppi = Some(now); + } + + /// [`Self::settle_screen_ppi`] when the main window's density or a floating window's changed + /// since it last ran from here, or a window started or stopped floating, or Presentation Mode + /// started or ended. With Display Print Size at 100% Zoom off, the desktop host does not read + /// the displays: every density read before is forgotten, so the readings after the preference + /// is turned on again count as first readings. + pub(crate) fn settle_screen_ppi_if_changed(&mut self) { + self.follow_print_size_switch(); + let key = (self.services.screen_ppi, crate::doc_windows::floating_ppi(self)); + if self.canvas.windows.settled.as_ref() != Some(&key) { + self.settle_screen_ppi(); + self.canvas.windows.settled = Some(key); + } + } + + /// Takes in a change of Display Print Size at 100% Zoom since this last ran: turned off, every + /// density read before is forgotten; turned on, every view's zoom counts as the one its first + /// reading keeps. + fn follow_print_size_switch(&mut self) { + let off = !self.session.prefs.display_print_size; + let was_off = std::mem::replace(&mut self.canvas.windows.print_size_off, off); + if off && !was_off { + crate::doc_windows::forget_ppi(self); + self.services.screen_ppi = crate::ScreenPpi::Unread; + self.canvas.windows.main_read = None; + self.services.screens.clear(); + for w in crate::doc_windows::windows(self) { + if let Some(v) = crate::doc_windows::view_mut(self, w) { + v.shown_ppi = Some(crate::ScreenPpi::Unread); + } + } + } + if was_off && !off { + // The zoom chosen while it was off stays when the displays are read. + for w in crate::doc_windows::windows(self) { + if let Some(v) = crate::doc_windows::view_mut(self, w) { + v.fit_zoom = Some(v.zoom); + } + } + } + } + pub fn view_mut(&mut self) -> Option<&mut View> { self.sync_views(); let i = self.session.active_index()?; @@ -178,17 +355,38 @@ impl VectorcraftApp { }; let target = crate::canvas::view_target(self, win); let (scaling, ppp) = (self.ui_scaling(), ctx.pixels_per_point()); - let scheme = zoom_scheme(&self.session.prefs, ppp / ctx.zoom_factor()); + self.before_view_command(win, command); + let scheme = zoom_scheme(self.print_ppi_of(Some(win)), ppp / ctx.zoom_factor()); let Some(v) = self.view_mut() else { return }; let before = *v; let mut cv = v.canvas(scaling, v.rect); let layers = move || bounds; if command.apply(&mut cv, &target, Some(&layers), ppp, &scheme) { v.set_canvas(&cv, scaling); + self.after_view_command(win, command); self.ease_view(before); } } + /// Before view command `command` runs on window `w`'s view: a fit to the window is made for the + /// display the window is on now, and a zoom percentage (Actual Size) counts from the density the + /// view counts from, which a reading still to come rescales (Display Print Size at 100% Zoom). + pub(crate) fn before_view_command(&mut self, w: crate::doc_windows::Win, command: ViewCommands) { + if let Some(fit) = fits_window(command) { + self.settle_window_ppi(w, !fit); + } + } + + /// After view command `command` ran on window `w`'s view: a fit to the window is kept at the + /// first reading of its display; a zoom percentage keeps its percentage then. + pub(crate) fn after_view_command(&mut self, w: crate::doc_windows::Win, command: ViewCommands) { + if let Some(fit) = fits_window(command) + && let Some(v) = crate::doc_windows::view_mut(self, w) + { + v.fit_zoom = fit.then_some(v.zoom); + } + } + pub fn view_info(&self) -> ViewInfo { ViewInfo { // The tools measure their tolerances and widgets in the interface's points. diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 596cb119f0..e0bc44b304 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -147,9 +147,19 @@ pub(crate) fn show_document(app: &mut VectorcraftApp, ui: &mut Ui, win: Win, kin // A measuring run applies no view request: the view, its request and its fit wait for the pass // that shows the canvas. let measuring = craft::ui::runtime::measure::active(ui.ctx()); - let Some(view) = doc_windows::view_mut(app, win) else { return false }; // Presentation Mode shows the active artboard on the whole screen: it fits again when the screen changes. - let refit = !view.fitted || (presenting && view.rect != area); + let refits = |v: &crate::state::View| !v.fitted || (presenting && v.rect != area); + // The view command this pass runs, made for the display the window is on (Display Print Size at 100% Zoom). + let command = doc_windows::view(app, win) + .filter(|_| !measuring) + .and_then(|v| v.request.map(|(r, _)| r.command()).or_else(|| refits(v).then_some(ViewCommands::FitArtboard))); + if let Some(command) = command { + app.before_view_command(win, command); + } + let ppp = ui.ctx().pixels_per_point(); + let scheme = crate::app::view::zoom_scheme(app.print_ppi_of(Some(win)), ppp / ui.ctx().zoom_factor()); + let Some(view) = doc_windows::view_mut(app, win) else { return false }; + let refit = refits(view); let (request, moved) = if measuring { (view.request, view.moved) } else { @@ -165,6 +175,16 @@ pub(crate) fn show_document(app: &mut VectorcraftApp, ui: &mut Ui, win: Win, kin } let mut cv = view.canvas(scaling, area); let given = cv; + // A zoom percentage (Actual Size) counts from the density of the display that shows this + // window: it runs here with that display's zoom stops, which the canvas's own may not be. + let mut moved = moved; + if let Some(request) = queued.first().copied().filter(|r| crate::app::view::fits_window(r.command()) == Some(false)) { + let layers = move || bounds; + if request.command().apply(&mut cv, &target, Some(&layers), ppp, &scheme) && matches!(request, ViewRequest::Command(_)) { + moved = Some(ViewMove::Ease(given)); + } + queued.clear(); + } let (x, y, zero) = rulers::texts(app, win); let strips = if app.ui.view.rulers && !presenting { Some(rulers::strips(zero, kind)) @@ -223,6 +243,9 @@ pub(crate) fn show_document(app: &mut VectorcraftApp, ui: &mut Ui, win: Win, kin // An edit of the compass or a scroll bar reaches the next pass, which stops a running ease. view.moved = jumped.then_some(ViewMove::Jump); } + if let Some(command) = command { + app.after_view_command(win, command); + } if kind == BodyKind::Pane || presenting { return pressed; } @@ -333,7 +356,7 @@ fn grids(app: &VectorcraftApp, ui: &mut Ui, space: &CanvasSpace, win: Win) { if let Some((grid, in_back)) = app.session.documents().get(win.0).and_then(|st| grid::document_grid(app, st)) { let _ = if in_back { grid.picture() } else { grid }.show_at(ui, space.view.rect); } - if let Some(grid) = grid::pixel_grid(app) { + if let Some(grid) = grid::pixel_grid(app, app.print_ppi_of(Some(win))) { let _ = grid.show_at(ui, space.view.rect); } } diff --git a/crates/ui-egui/src/canvas/artboards.rs b/crates/ui-egui/src/canvas/artboards.rs index e493bbc561..605e7108d2 100644 --- a/crates/ui-egui/src/canvas/artboards.rs +++ b/crates/ui-egui/src/canvas/artboards.rs @@ -61,18 +61,28 @@ pub(super) fn frames(app: &VectorcraftApp, st: &vectorcraft_engine::DocState, vi .collect() } -/// A line round each artboard in Outline, the drop shadow in Preview. +/// A line round each artboard in Outline, the drop shadow in Preview, and no border in Overprint Preview (and +/// Separations Preview, which turns it on). pub(super) fn border(outline: bool) -> PageBorder { - if outline { PageBorder::Line } else { PageBorder::DropShadow } + if outline { + PageBorder::Line + } else if vectorcraft_render::proof::overprint_preview_on() { + PageBorder::None + } else { + PageBorder::DropShadow + } } -/// The pasteboard's color: white in Outline, the paper under Hide Artboards, else User Interface › Canvas Color, or the -/// interface's when that matches the interface brightness. +/// The pasteboard's color: white in Outline, the paper under Hide Artboards, white in Overprint Preview (and Separations +/// Preview, which turns it on), else User Interface › Canvas Color, or the interface's when that matches the interface +/// brightness. pub(super) fn pasteboard_color(app: &VectorcraftApp, st: &vectorcraft_engine::DocState, outline: bool) -> PasteboardColor { if outline { PasteboardColor::Custom(DataColor::new(Color32::WHITE)) } else if !shows_artboards(app) { PasteboardColor::Custom(DataColor::new(paper_color(&st.doc.setup))) + } else if vectorcraft_render::proof::overprint_preview_on() { + PasteboardColor::Custom(DataColor::new(Color32::WHITE)) } else { crate::prefs_dialog::canvas_color(&app.session.prefs.canvas_color) .map_or(PasteboardColor::Default, |c| PasteboardColor::Custom(DataColor::new(c))) diff --git a/crates/ui-egui/src/canvas/artboards/tests.rs b/crates/ui-egui/src/canvas/artboards/tests.rs index 54cc9aedec..742e798e63 100644 --- a/crates/ui-egui/src/canvas/artboards/tests.rs +++ b/crates/ui-egui/src/canvas/artboards/tests.rs @@ -48,6 +48,7 @@ fn shift_clicking_a_name_toggles_selection_and_a_plain_click_activates() { #[test] fn outline_has_a_white_canvas_line_edges_and_no_paper() { + let _view = crate::testing::DefaultProofView::new(); let app = app_with(2); let st = app.session.active().unwrap(); assert_eq!(pasteboard_color(&app, st, true), PasteboardColor::Custom(DataColor::new(Color32::WHITE))); @@ -58,9 +59,43 @@ fn outline_has_a_white_canvas_line_edges_and_no_paper() { assert!(frames_of(&app, false).iter().all(|f| f.fill.is_some())); } +/// Overprint Preview, and Separations Preview, which turns it on, draw a white canvas around the artboards and no +/// shadows, in every Canvas Color; the artboards keep their paper. Outline keeps its line edges, and Hide Artboards its +/// paper canvas. Turning the preview off brings back the pasteboard color and the shadows. +#[test] +fn overprint_preview_draws_a_white_canvas_without_shadows() { + let _view = crate::testing::DefaultProofView::new(); + let mut app = app_with(2); + let white = PasteboardColor::Custom(DataColor::new(Color32::WHITE)); + let (overprint, separations) = ("view.overprintPreview", "view.separationsPreview"); + for canvas_color in ["matchUi", "darkGray", "lightGray"] { + app.run("prefs.set", json!({"key": "canvasColor", "value": canvas_color})).unwrap(); + let before = pasteboard_color(&app, app.session.active().unwrap(), false); + for (id, on) in [(overprint, true), (overprint, false), (separations, true), (separations, false)] { + app.run(id, json!({"on": on})).unwrap(); + let st = app.session.active().unwrap(); + let at = format!("{id} {on}, canvas color {canvas_color}"); + if on { + assert_eq!(pasteboard_color(&app, st, false), white, "{at}"); + assert_eq!(border(false), PageBorder::None, "{at}"); + } else { + assert_eq!(pasteboard_color(&app, st, false), before, "{at}"); + assert_eq!(border(false), PageBorder::DropShadow, "{at}"); + } + assert_eq!(border(true), PageBorder::Line, "{at}"); + assert!(frames_of(&app, false).iter().all(|f| f.fill.is_some()), "{at}"); + } + } + app.run("view.overprintPreview", json!({"on": true})).unwrap(); + app.ui.view.artboards = false; + let st = app.session.active().unwrap(); + assert_eq!(pasteboard_color(&app, st, false), PasteboardColor::Custom(DataColor::new(paper_color(&st.doc.setup)))); +} + /// User Interface › Canvas Color paints the pasteboard in Preview; Outline keeps its white one. #[test] fn the_canvas_color_preference_paints_the_pasteboard() { + let _view = crate::testing::DefaultProofView::new(); let mut app = app_with(1); app.run("prefs.set", json!({"key": "canvasColor", "value": "darkGray"})).unwrap(); let st = app.session.active().unwrap(); diff --git a/crates/ui-egui/src/canvas/grid.rs b/crates/ui-egui/src/canvas/grid.rs index 71641858c1..6ee138bd34 100644 --- a/crates/ui-egui/src/canvas/grid.rs +++ b/crates/ui-egui/src/canvas/grid.rs @@ -44,13 +44,15 @@ pub(super) fn grid_look(prefs: &vectorcraft_engine::Prefs) -> (GridLine, Color32 } /// The pixel grid (Guides & Grid › Show Pixel Grid (Above 600% Zoom)): a line at every document -/// pixel in Pixel Preview, which the control draws from [`PIXEL_GRID_ZOOM`] on (its `min_zoom` is -/// the device zoom, as the view's). -pub(super) fn pixel_grid(app: &VectorcraftApp) -> Option { +/// pixel in Pixel Preview, which the control draws from [`PIXEL_GRID_ZOOM`] on as the zoom field +/// counts it, with `print` screen points to an inch at 100% ([`crate::state::print_ppi`]; its +/// `min_zoom` is the device zoom, as the view's). +pub(super) fn pixel_grid(app: &VectorcraftApp, print: Option) -> Option { if app.ui.screen_mode >= 3 || !app.ui.view.pixel_preview || !app.session.prefs.show_pixel_grid { return None; } - Some(CanvasGrid::new("Pixel grid").spacing((1.0, 1.0).into()).subdivisions(1).color(DataColor::new(PIXEL_GRID)).min_zoom(PIXEL_GRID_ZOOM)) + let min_zoom = PIXEL_GRID_ZOOM * crate::state::zoom_baseline(print); + Some(CanvasGrid::new("Pixel grid").spacing((1.0, 1.0).into()).subdivisions(1).color(DataColor::new(PIXEL_GRID)).min_zoom(min_zoom)) } /// A `#rrggbb` colour preference, `fallback` when it doesn't parse. diff --git a/crates/ui-egui/src/canvas/guides/tests.rs b/crates/ui-egui/src/canvas/guides/tests.rs index a989261d4d..dd0adb2963 100644 --- a/crates/ui-egui/src/canvas/guides/tests.rs +++ b/crates/ui-egui/src/canvas/guides/tests.rs @@ -105,9 +105,9 @@ fn trim_view_hides_the_guides_and_the_grid() { #[test] fn pixel_grid_shows_in_pixel_preview_from_600_percent() { let mut app = app(); - assert!(pixel_grid(&app).is_none(), "not in Pixel Preview"); + assert!(pixel_grid(&app, None).is_none(), "not in Pixel Preview"); app.ui.view.pixel_preview = true; - assert!(pixel_grid(&app).is_some()); + assert!(pixel_grid(&app, None).is_some()); app.session.execute("prefs.set", &json!({"key": "showPixelGrid", "value": false})).unwrap(); - assert!(pixel_grid(&app).is_none(), "the preference is off"); + assert!(pixel_grid(&app, None).is_none(), "the preference is off"); } diff --git a/crates/ui-egui/src/canvas/overlays.rs b/crates/ui-egui/src/canvas/overlays.rs index 7be8250984..8f9bd6f663 100644 --- a/crates/ui-egui/src/canvas/overlays.rs +++ b/crates/ui-egui/src/canvas/overlays.rs @@ -9,7 +9,7 @@ use craft::draw::ui::{HandleStyle, PathOptionsSettings}; use craft::ui::canvas::{CanvasSpace, canvas_space, hud}; use craft::ui::canvas_controls::{Marquee, MarqueeLook, Measure, SelectionOutline, SmartGuides, path_runs}; use craft::ui::contract::{Common, Component, Cx, Input, MeasureCx, PaintUi, PartsCx, Role, Show as _}; -use craft::ui::primitives::{DataWidth, Draw, PaintShape, StrokeWidth, TextRun}; +use craft::ui::primitives::{Dashes, DataWidth, Draw, PaintShape, StrokeWidth, TextRun}; use craft::ui::runtime::env::Label; use craft::ui::style::{ComponentStyle, DataColor, Metrics, StyleColor, StyleCx, TypeRole, UiTokens}; use egui::{Color32, CornerRadius, Pos2, Rect as ScreenRect, Response, Vec2}; @@ -191,8 +191,15 @@ fn paint(draw: &Draw<'_>, view: &CanvasView, overlays: &[Overlay], options: &Pat stroke_run(draw, points, closed, *dashed, DataWidth::points(*width), data(*color)); } } - Overlay::Line { a, b, color, dashed } => { - stroke_run(draw, vec![view.to_screen(*a), view.to_screen(*b)], false, *dashed, StrokeWidth::Thin, data(*color)); + Overlay::Line { a, b, color, dashed: true } => { + let pattern = draw.dashes(); + let margin = pattern.dash + pattern.gap + draw.width(StrokeWidth::Thin); + if let Some((run, from)) = visible_run(view, *a, *b, view.rect.expand(margin)) { + draw.dashed(&run, dashes_from(pattern, from), StrokeWidth::Thin, data(*color)); + } + } + Overlay::Line { a, b, color, dashed: false } => { + stroke_run(draw, vec![view.to_screen(*a), view.to_screen(*b)], false, false, StrokeWidth::Thin, data(*color)); } Overlay::GridLine { a, b, color } => { stroke_run(draw, vec![view.to_screen(*a), view.to_screen(*b)], false, false, StrokeWidth::Thin, data_rgba(*color)); @@ -262,6 +269,69 @@ fn stroke_run( } } +/// The part inside `clip` of the screen line that `view` draws from document point `a` to `b`, with how far along the +/// whole line that part starts, in points. The line is clipped in `f64`, so a line millions of points long keeps its +/// part on the canvas. None when no part of it is inside `clip`, or when an end does not map to a finite point. +fn visible_run(view: &CanvasView, a: vectorcraft_geom::Point, b: vectorcraft_geom::Point, clip: ScreenRect) -> Option<([Pos2; 2], f64)> { + let affine = view.affine(); + let (a, b) = (affine * a, affine * b); + if !(a.is_finite() && b.is_finite()) { + return None; + } + let screen = |p: vectorcraft_geom::Point| Pos2::new(p.x as f32, p.y as f32); + // Halved, so ends near the largest `f64` do not overflow. + let half = b.to_vec2() * 0.5 - a.to_vec2() * 0.5; + let length = half.hypot(); + if length == 0.0 { + let c = screen(a); + return clip.contains(c).then_some(([c, c], 0.0)); + } + let u = half / length; + // The run is measured from the point of the line nearest the middle of `clip`, so the clipped ends keep their + // precision when the line's ends are far off. + // That point is found from the line's distance to the middle, taken from the cross product of its ends, so a line + // whose ends are far off and not on one diagonal keeps its place on the canvas. + let c = vectorcraft_geom::Point::new(f64::from(clip.center().x), f64::from(clip.center().y)); + let offset = (half.cross(c.to_vec2()) + 2.0 * exact_cross(a.to_vec2() * 0.5, b.to_vec2() * 0.5)) / length; + let origin = if offset.is_finite() { c - vectorcraft_geom::Vec2::new(-u.y, u.x) * offset } else { a + u * (c - a).dot(u) }; + let (mut s0, mut s1) = ((a - origin).dot(u), (b - origin).dot(u)); + let start = s0; + let axes = [(origin.x, u.x, f64::from(clip.left()), f64::from(clip.right())), (origin.y, u.y, f64::from(clip.top()), f64::from(clip.bottom()))]; + for (at, step, lo, hi) in axes { + if step == 0.0 { + if at < lo || at > hi { + return None; + } + } else { + let (enter, leave) = ((lo - at) / step, (hi - at) / step); + s0 = s0.max(enter.min(leave)); + s1 = s1.min(enter.max(leave)); + } + } + if s0 > s1 { + return None; + } + Some(([screen(origin + u * s0), screen(origin + u * s1)], s0 - start)) +} + +/// `p.x * q.y - p.y * q.x`, with the rounding error of the second product added back (Kahan's method), so two far-off +/// points whose products nearly cancel keep the small difference between them. +fn exact_cross(p: vectorcraft_geom::Vec2, q: vectorcraft_geom::Vec2) -> f64 { + let w = p.y * q.x; + let error = (-p.y).mul_add(q.x, w); + p.x.mul_add(q.y, -w) + error +} + +/// `pattern` for a run that starts `from` points along its line, so its dashes fall where the whole line has them. +fn dashes_from(pattern: Dashes, from: f64) -> Dashes { + let period = f64::from(pattern.dash) + f64::from(pattern.gap); + if !(period.is_finite() && period > 0.0 && from.is_finite()) { + return pattern; + } + let phase = (f64::from(pattern.phase) - from).rem_euclid(period); + pattern.phase(phase as f32) +} + /// An anchor or curve point: filled in `color` when selected, else a white body with a `color` edge. fn marker(draw: &Draw<'_>, shape: &PaintShape, color: DataColor, filled: bool) { draw.data_fill(shape, if filled { color } else { DataColor::new(Color32::WHITE) }); diff --git a/crates/ui-egui/src/canvas/overlays/tests.rs b/crates/ui-egui/src/canvas/overlays/tests.rs index c154dc8f77..6c7d8e21d1 100644 --- a/crates/ui-egui/src/canvas/overlays/tests.rs +++ b/crates/ui-egui/src/canvas/overlays/tests.rs @@ -61,3 +61,127 @@ fn a_tip_disc_is_scaled_by_the_zoom_and_never_empty() { fn empty_tip() -> Overlay { Overlay::HoverText { center: Point::new(f64::NAN, 0.0), radius: 5.0, text: "Tip" } } + +/// The dashes of `points` in `pattern`, as `Draw::dashed` lays them out. +fn dashes_along(points: &[Pos2], pattern: Dashes) -> Vec { + let s = egui::Stroke::new(1.0, Color32::WHITE); + egui::Shape::dashed_line_with_offset(points, s, &[pattern.dash], &[pattern.gap], pattern.phase) +} + +/// The stretches of x that horizontal dashes cover inside `lo..hi`, in order. +fn spans(shapes: &[egui::Shape], lo: f32, hi: f32) -> Vec<(f32, f32)> { + let mut out: Vec<(f32, f32)> = shapes + .iter() + .map(|s| match s { + egui::Shape::LineSegment { points: [a, b], .. } => (a.x.min(b.x).max(lo), a.x.max(b.x).min(hi)), + other => panic!("{other:?}"), + }) + .filter(|(a, b)| b > a) + .collect(); + out.sort_by(|a, b| a.0.total_cmp(&b.0)); + out +} + +/// A dashed line much longer than the canvas is dashed only where it shows, with the dashes on the canvas where the +/// whole line dashed in one go has them, for any phase of the pattern. +#[test] +fn a_long_dashed_line_is_dashed_only_on_the_canvas() { + let view = view(); + let clip = view.rect.expand(8.0); + let (lo, hi) = (view.rect.left(), view.rect.right()); + // From 1,000 points left of the canvas to 1,740 points right of it. + let (a, b) = (Point::new(-1000.0, 100.0), Point::new(1900.0, 100.0)); + for phase in [0.0, 2.5, 6.9] { + let pattern = Dashes::new(4.0, 3.0).phase(phase); + let whole = dashes_along(&[view.to_screen(a), view.to_screen(b)], pattern); + let (run, from) = visible_run(&view, a, b, clip).unwrap(); + let drawn = dashes_along(&run, dashes_from(pattern, from)); + let (want, got) = (spans(&whole, lo, hi), spans(&drawn, lo, hi)); + assert_eq!(want.len(), got.len(), "{phase}: {want:?} {got:?}"); + assert!(want.iter().zip(&got).all(|(w, g)| (w.0 - g.0).abs() < 1e-2 && (w.1 - g.1).abs() < 1e-2), "{phase}: {want:?} {got:?}"); + assert!(drawn.len() <= 30, "only the dashes on the canvas: {}", drawn.len()); + } +} + +/// Ends 10,000,000,000 points away on both sides still keep the part on the canvas, dashed in whole dashes. +#[test] +fn a_dashed_line_with_far_ends_keeps_its_part_on_the_canvas() { + let view = view(); + let pattern = Dashes::new(4.0, 3.0); + let (run, from) = visible_run(&view, Point::new(-1e10, 100.0), Point::new(1e10, 100.0), view.rect.expand(8.0)).unwrap(); + assert!(from > 1e9, "{from}"); + let drawn = spans(&dashes_along(&run, dashes_from(pattern, from)), view.rect.left(), view.rect.right()); + assert!((20..=26).contains(&drawn.len()), "{drawn:?}"); + assert!(drawn.iter().all(|(a, b)| b - a <= 4.0 + 1e-3), "{drawn:?}"); + // Ends so far off that the clipped ends round to one point along the line still keep the canvas's width. + let clip = view.rect.expand(8.0); + let (run, _) = visible_run(&view, Point::new(-1e20, 100.0), Point::new(1e20, 100.0), clip).unwrap(); + assert_eq!(run, [Pos2::new(clip.left(), 100.0), Pos2::new(clip.right(), 100.0)]); + // A slanted line keeps its slant there too. + let (run, _) = visible_run(&view, Point::new(-1e20, -1e20), Point::new(1e20, 1e20), clip).unwrap(); + assert!(run.iter().all(|p| (p.x - p.y).abs() < 1e-3 && clip.expand(1e-2).contains(*p)), "{run:?}"); + assert!(run[0].distance(run[1]) > 200.0, "{run:?}"); + // Far-off ends off one diagonal keep the line's offset: these ends, as `f64` holds them, give a line that + // crosses x = 0 at y = 72.35. + let (run, _) = visible_run(&view, Point::new(-1e18, -1e18 + 100.0), Point::new(1.3e18, 1.3e18 + 100.0), clip).unwrap(); + assert!(run.iter().all(|p| (p.y - p.x - 72.35).abs() < 1e-2 && clip.expand(1e-2).contains(*p)), "{run:?}"); +} + +/// The line segments in `shapes`, with nested shape lists opened. +fn segments(shapes: &[egui::Shape]) -> Vec<[Pos2; 2]> { + let mut out = Vec::new(); + for s in shapes { + match s { + egui::Shape::LineSegment { points, .. } => out.push(*points), + egui::Shape::Vec(inner) => out.extend(segments(inner)), + other => panic!("{other:?}"), + } + } + out +} + +/// A long dashed line overlay painted through `paint` gives only the dashes near the canvas, each on the line. +#[test] +fn a_long_dashed_line_overlay_paints_only_its_dashes_on_the_canvas() { + use craft::i18n::Direction; + use craft::theme::{Contrast, Mode}; + use craft::ui::style::Ink; + use craft::ui::testing::Frames; + use craft::ui::testing::style::{paint_frame, tokens}; + + let view = view(); + let tokens = tokens(Mode::Light, Contrast::Standard); + let style = ToolMarksStyle { + metrics: Metrics::new(), + dark: StyleColor(Color32::BLACK), + ink: StyleColor(Color32::WHITE), + accent: StyleColor(Color32::BLUE), + pad: Vec2::ZERO, + radius: CornerRadius::ZERO, + handle: 3.0, + }; + let line = Overlay::Line { a: Point::new(-1000.0, 100.0), b: Point::new(1900.0, 100.0), color: [255, 0, 255], dashed: true }; + let mut frames = Frames::new(); + let (shapes, _) = paint_frame(&mut frames, &tokens, Direction::Ltr, Ink::OnPanel, |draw| { + paint(draw, &view, std::slice::from_ref(&line), &PathOptionsSettings::default(), &style); + }); + let drawn = segments(&shapes); + assert!(!drawn.is_empty(), "the part on the canvas is drawn"); + assert!(drawn.len() <= 40, "only the dashes near the canvas: {}", drawn.len()); + let near = view.rect.expand(32.0); + assert!(drawn.iter().flatten().all(|p| near.contains(*p) && (p.y - 100.0).abs() < 1e-3), "{drawn:?}"); +} + +/// A turned view clips the line to the canvas too, and a line off the canvas or with an end that is not finite draws +/// nothing. +#[test] +fn a_dashed_line_off_the_canvas_draws_nothing() { + let mut view = view(); + view.rotation = 0.3; + let clip = view.rect.expand(8.0); + let (run, _) = visible_run(&view, Point::new(-1e6, 100.0), Point::new(1e6, 100.0), clip).unwrap(); + assert!(run.iter().all(|p| clip.expand(1e-2).contains(*p)), "{run:?}"); + assert!(visible_run(&view, Point::new(-1e6, 5000.0), Point::new(1e6, 5000.0), clip).is_none()); + assert!(visible_run(&view, Point::new(0.0, 100.0), Point::new(f64::INFINITY, 100.0), clip).is_none()); + assert!(visible_run(&view, Point::new(f64::NAN, 100.0), Point::new(10.0, 100.0), clip).is_none()); +} diff --git a/crates/ui-egui/src/canvas/panes.rs b/crates/ui-egui/src/canvas/panes.rs index a7e971a747..9cf1965cfc 100644 --- a/crates/ui-egui/src/canvas/panes.rs +++ b/crates/ui-egui/src/canvas/panes.rs @@ -415,6 +415,36 @@ fn art_area(app: &VectorcraftApp, w: Win, cell: egui::Rect) -> egui::Rect { crate::doc_windows::view(app, w).map(|v| v.rect).filter(|r| r.is_positive()).unwrap_or(cell) } +/// Whether window `w`'s view is still where a pane fit left it, in a pane of `size`. +pub(crate) fn follows_fit(app: &VectorcraftApp, w: Win, size: Option) -> bool { + let fit = slot(app, w).and_then(|s| app.canvas.panes.fits.get(&s).copied()); + crate::doc_windows::view(app, w).is_some_and(|v| v.fitted && fit.is_some_and(|(s, z, c)| Some(s) == size && z == v.zoom && c == v.center)) +} + +/// Records window `w`'s view as fitted to a pane of `size` at its zoom and center now, as +/// [`note_fits`] does after a fit. +#[cfg(test)] +pub(crate) fn note_fit(app: &mut VectorcraftApp, w: Win, size: egui::Vec2) { + if let (Some(s), Some(v)) = (slot(app, w), crate::doc_windows::view(app, w).copied()) { + app.canvas.panes.fits.insert(s, (size, v.zoom, v.center)); + } +} + +/// The pane fit recorded for window `w` ([`note_fits`]). +#[cfg(test)] +pub(crate) fn fit_of(app: &VectorcraftApp, w: Win) -> Option<(egui::Vec2, f64, Point)> { + slot(app, w).and_then(|s| app.canvas.panes.fits.get(&s).copied()) +} + +/// Window `w`'s view, rescaled while it still fitted its pane ([`follows_fit`]), keeps fitting the +/// pane at its new zoom and center. +pub(crate) fn refollow_fit(app: &mut VectorcraftApp, w: Win) { + let (Some(s), Some(v)) = (slot(app, w), crate::doc_windows::view(app, w).copied()) else { return }; + if let Some(fit) = app.canvas.panes.fits.get_mut(&s) { + *fit = (fit.0, v.zoom, v.center); + } +} + /// Unfit each window whose view is still where a pane fit left it when its view's area (`areas`, /// by window) has changed size, as when the window or a panel is resized: it fits its pane again. /// A view zoomed or scrolled since keeps its place. → which of `areas`' views are unfitted now. @@ -454,16 +484,24 @@ fn fit_pane(v: &mut View, doc: &vectorcraft_doc::Document, area: egui::Rect, (ui craft::behavior::canvas::zoom::fit_rect(&mut view, target, target.size(), pixels_per_point, Vec2::new(FIT_MARGIN, FIT_MARGIN), scheme); v.set_canvas(&view, ui_zoom); v.fitted = true; + v.fit_zoom = Some(v.zoom); } } -/// Fit window `w`'s view to its pane when it is unfitted, with the zoom stops of `ui`'s scope. +/// Fit window `w`'s view to its pane when it is unfitted, with the zoom stops of the display that +/// shows the pane (Display Print Size at 100% Zoom). fn fit_window(app: &mut VectorcraftApp, ui: &Ui, w: Win, cell: egui::Rect) { + if !crate::doc_windows::view(app, w).is_some_and(|v| !v.fitted) { + return; + } let area = art_area(app, w, cell); let Some(doc) = app.session.documents().get(w.0).map(|st| st.doc.clone()) else { return }; - let scheme = Env::of(ui).get::(); - let scaling = (app.ui_scaling(), ui.ctx().pixels_per_point()); - if let Some(v) = crate::doc_windows::view_mut(app, w).filter(|v| !v.fitted) { + // The fit is made for the display the pane is on. + app.settle_window_ppi(w, false); + let ctx = ui.ctx(); + let scheme = crate::app::view::zoom_scheme(app.print_ppi_of(Some(w)), ctx.pixels_per_point() / ctx.zoom_factor()); + let scaling = (app.ui_scaling(), ctx.pixels_per_point()); + if let Some(v) = crate::doc_windows::view_mut(app, w) { fit_pane(v, &doc, area, scaling, &scheme); } } diff --git a/crates/ui-egui/src/canvas/raster.rs b/crates/ui-egui/src/canvas/raster.rs index 711fe29187..8243444d39 100644 --- a/crates/ui-egui/src/canvas/raster.rs +++ b/crates/ui-egui/src/canvas/raster.rs @@ -816,7 +816,8 @@ pub(super) fn backdrop( let paper = paper_color(setup); let b = if shows_artboards(app) { crate::display_profile::Backdrop { - everywhere: None, + // In Overprint Preview the canvas around the artboards is white paper. + everywhere: vectorcraft_render::proof::overprint_preview_on().then_some([255; 3]), artboards: st.doc.artboards.iter().map(|ab| (ab.rect, rgb(artboard_paper(ab, paper)))).collect(), grid: shows_transparency_grid(st).then(|| (setup.grid_colors.map(|c| rgb(crate::panels::c32(&c))), setup.grid_size.cell())), } diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 8722616ac2..4d11dc884d 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -905,6 +905,88 @@ fn the_canvas_is_drawn_through_the_display_profile_while_the_preference_is_on() assert_eq!(count(&mut app, red), Some(srgb)); } +/// With a display profile, in Overprint Preview translucent art around the artboards is blended +/// with the white canvas before the conversion, as art over the paper is. With the preview off it +/// converts alone, over the pasteboard. +#[test] +fn translucent_art_around_the_artboards_is_blended_with_overprint_previews_white_canvas() { + keeping_color_settings(translucent_art_around_the_artboards); +} + +fn translucent_art_around_the_artboards() { + use crate::display_profile::{Found, Reading}; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.ui.task_bar = false; + app.ui.view.rulers = false; + app.canvas.worker_started = true; // every frame on this thread + // Left of the artboard. + let outside = app.run("shape.rectangle", json!({"x": -60, "y": 100, "width": 40, "height": 40})).unwrap()["id"].clone(); + app.run("paint.setFill", json!({"ids": [outside], "color": "#00ff00"})).unwrap(); + app.run("transparency.set", json!({"ids": [outside], "opacity": 50})).unwrap(); + app.run("select.none", json!({})).unwrap(); + let ctx = crate::testing::ui_context(); + // The whole art raster one frame uploads: its width and its pixels. + let upload = |app: &mut VectorcraftApp| -> Option<(usize, Vec)> { + let (_, mut delta) = frame_output(app, &ctx); + let art = app.canvas.texture.as_ref()?.id(); + let up = delta.set.iter().find(|e| e.0.eq(&art)).and_then(|e| e.1.last()).filter(|d| d.pos.is_none()).map(|d| { + let egui::ImageData::Color(img) = &d.image; + (img.width(), img.pixels.clone()) + }); + delta.clear(); + up + }; + upload(&mut app).expect("the first frame"); + let v = app.view_mut().unwrap(); + (v.zoom, v.center) = (1.0, Point::new(120.0, 150.0)); + upload(&mut app).expect("the view at 100%"); + let p3 = crate::display_profile::tests::p3(); + let t = crate::display_profile::tests::transform(); + app.display_profile.report(Reading { display: Some("DP-1".into()), found: Found::Profile { icc: p3, from: "test".into() } }); + upload(&mut app).expect("drawn again, converted"); + let white = convert8(&t, [255; 3]); + // What the canvas shows of pixel `c` over the converted paper `under`, as egui blends it. + let over = |c: egui::Color32, under: [u8; 3]| { + let k = 255 - u32::from(c.a()); + [0, 1, 2].map(|i| u32::from(c.to_array()[i]) + (u32::from(under[i]) * k + 127) / 255) + }; + let plain = |s: egui::Color32| { + let mut px = s.to_array(); + t.apply_premultiplied_rgba8(&mut px); + egui::Color32::from_rgba_premultiplied(px[0], px[1], px[2], px[3]) + }; + // The pixel at the translucent rectangle's center, in sRGB (the display profile's preference + // off) and as the canvas shows it (on). + let pixel = |app: &mut VectorcraftApp| { + app.session.prefs.monitor_profile_display = false; + let (width, srgb) = upload(app).expect("drawn in sRGB"); + let key = app.canvas.key.clone().unwrap(); + let (_, _, view) = + frame_view(None, (key.w, key.h), &CanvasView::new(egui::Rect::NOTHING, Point::new(key.cx, key.cy), key.zoom).rotation(key.rot), key.ppp); + let at = view * Point::new(-40.0, 120.0); + let at = at.y as usize * width + at.x as usize; + app.session.prefs.monitor_profile_display = true; + let (_, shown) = upload(app).expect("drawn again, converted"); + (srgb[at], shown[at], app.canvas.key.clone().unwrap()) + }; + let (s, c, key) = pixel(&mut app); + assert!((50..=205).contains(&s.a()), "the 50% fill: {s:?}"); + assert!(key.backdrop.as_ref().is_some_and(|b| b.everywhere.is_none()), "Preview: the pasteboard is no paper"); + assert_eq!(c, plain(s), "over the pasteboard the art converts alone"); + app.run("view.overprintPreview", json!({"on": true})).unwrap(); + let (s, c, key) = pixel(&mut app); + assert!((50..=205).contains(&s.a()), "the 50% fill: {s:?}"); + assert_eq!(key.backdrop.as_ref().and_then(|b| b.everywhere), Some([255; 3]), "the white canvas is paper"); + let k = 255 - u32::from(s.a()); + let mix = [0, 1, 2].map(|j| (u32::from(s.to_array()[j]) + (255 * k + 127) / 255).min(255) as u8); + let (want, got) = (convert8(&t, mix), over(c, white)); + assert!((0..3).all(|j| got[j].abs_diff(u32::from(want[j])) <= 1), "{got:?} shown, {want:?} wanted"); + // The test tells the two apart: the fill converted alone shows another color over the white canvas. + let alone = over(plain(s), white); + assert!((0..3).any(|j| alone[j].abs_diff(got[j]) > 2), "{alone:?} and {got:?}"); +} + /// With a display profile, translucent art and the anti-aliased edges of art over the paper are /// blended with the paper in sRGB before the conversion: drawn over the converted paper, each such /// pixel shows the converted blend. Opaque art, and art over the pasteboard, convert as before. The @@ -2864,12 +2946,14 @@ fn hidden_characters_mark_no_space_at_a_bullet() { assert_eq!((plain, dots(&t)), (2, 2)); } -/// General › Display Print Size at 100% Zoom (#394): Actual Size shows the document larger with it -/// on (an inch at 96 screen points) than off (a point at a point), and reads 100% either way. +/// General › Display Print Size at 100% Zoom (#394, #9051): Actual Size shows the document larger +/// with it on (an inch at 96 screen points where no display was measured) than off (a point at a +/// point), and reads 100% either way. #[test] fn view_actual_size_follows_display_print_size() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); app.session.execute("file.new", &json!({"width": 200, "height": 100})).unwrap(); + app.session.execute("prefs.set", &json!({"key": "displayPrintSize", "value": false})).unwrap(); let ctx = crate::testing::ui_context(); // Frames as the hosts run them: the zoom stops come from the preferences through the app's frame input. let frame = |app: &mut VectorcraftApp, ctx: &egui::Context, _: Vec| { @@ -2884,7 +2968,7 @@ fn view_actual_size_follows_display_print_size() { app.run("view.actualSize", json!({})).unwrap(); frame(app, &ctx, vec![]); let view = app.canvas_view().unwrap(); - let scheme = crate::app::view::zoom_scheme(&app.session.prefs, ctx.pixels_per_point() / ctx.zoom_factor()); + let scheme = crate::app::view::zoom_scheme(app.print_ppi(), ctx.pixels_per_point() / ctx.zoom_factor()); (view.zoom, scheme.percent(craft::behavior::canvas::zoom::device(&view, ctx.pixels_per_point()))) }; let (off, off_percent) = actual(&mut app); @@ -2894,6 +2978,42 @@ fn view_actual_size_follows_display_print_size() { assert!((off_percent - 100.0).abs() < 1e-9 && (on_percent - 100.0).abs() < 1e-9, "both read 100%: {off_percent}, {on_percent}"); } +/// #9051: with Display Print Size on, Actual Size shows a document inch in an inch of the display +/// the window is on, from the density the host measured for it. When the window moves to a display +/// of another density, the view keeps its zoom percentage, so the art keeps its physical size there. +#[test] +fn view_actual_size_fills_an_inch_of_the_measured_display() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 200, "height": 100})).unwrap(); + app.session.execute("prefs.set", &json!({"key": "displayPrintSize", "value": true})).unwrap(); + let ctx = crate::testing::ui_context(); + let frame = |app: &mut VectorcraftApp, ctx: &egui::Context| { + let raw = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0))), ..Default::default() }; + crate::testing::part_frame(app, ctx, raw, show); + }; + let run = |app: &mut VectorcraftApp, id: &str| { + app.run(id, json!({})).unwrap(); + frame(app, &ctx); + }; + frame(&mut app, &ctx); + run(&mut app, "view.fitArtboard"); + let fitted = app.view().unwrap().zoom; + assert!(app.set_screen_ppi(Some(127.0))); + assert_eq!(app.view().unwrap().zoom, fitted, "the first measurement leaves a fitted view alone"); + run(&mut app, "view.actualSize"); + assert!((app.view().unwrap().zoom * 72.0 - 127.0).abs() < 1e-6, "72 pt take the display's 127 points to an inch"); + assert!(app.set_screen_ppi(Some(91.0)), "the window moved to a sparser display"); + assert!(!app.set_screen_ppi(Some(91.0)), "the same reading changes nothing"); + assert!((app.view().unwrap().zoom * 72.0 - 91.0).abs() < 1e-6, "100% still fills an inch"); + assert_eq!(crate::state::zoom_label(app.view().unwrap().zoom, app.print_ppi()), "100%"); + assert!(app.set_screen_ppi(None), "the window moved to a display that reports no size"); + assert!((app.view().unwrap().zoom * 72.0 - 96.0).abs() < 1e-6, "100% there is 96 points to an inch"); + app.session.execute("prefs.set", &json!({"key": "displayPrintSize", "value": false})).unwrap(); + let zoom = app.view().unwrap().zoom; + assert!(app.set_screen_ppi(Some(110.0))); + assert_eq!(app.view().unwrap().zoom, zoom, "off, a move leaves the zoom alone"); +} + /// Fit Artboard in Window fits the active artboard as a turned view shows it: with the second of /// two artboards active, at 45° all of it is on the canvas, and the two together are not. #[test] @@ -2948,11 +3068,7 @@ fn space_types_a_space_while_editing_text_and_does_not_pan() { assert_ne!(shown(&mut app), editing, "Cmd+Space shows the magnifier"); typing_frame(&mut app, &ctx, vec![button(at, true, Modifiers::COMMAND)]); typing_frame(&mut app, &ctx, vec![button(at, false, Modifiers::COMMAND)]); - assert_eq!( - app.view().unwrap().zoom, - crate::state::next_zoom(before.zoom, true, app.session.prefs.display_print_size), - "Cmd+Space click zooms in" - ); + assert_eq!(app.view().unwrap().zoom, crate::state::next_zoom(before.zoom, true, app.print_ppi()), "Cmd+Space click zooms in"); typing_frame(&mut app, &ctx, vec![space(false, Modifiers::COMMAND), Event::ModifiersChanged(Modifiers::NONE)]); assert_eq!(plain(&app, id), "a ", "the text is as typed"); } diff --git a/crates/ui-egui/src/canvas/tests_ui_scaling.rs b/crates/ui-egui/src/canvas/tests_ui_scaling.rs index 230bf917ff..0ccc63be2c 100644 --- a/crates/ui-egui/src/canvas/tests_ui_scaling.rs +++ b/crates/ui-egui/src/canvas/tests_ui_scaling.rs @@ -27,10 +27,12 @@ fn frame(app: &mut VectorcraftApp, ctx: &egui::Context, (native, ui_zoom): (f32, } /// A 512 × 512 pt document shown at `native` device pixels a point and UI Scaling `ui_zoom`, with a -/// controlled render worker, and the receiver of the frames it is asked to render. +/// controlled render worker, and the receiver of the frames it is asked to render. Display Print +/// Size at 100% Zoom is off, so 100% is one document point per screen point. fn shown(native: f32, ui_zoom: f32) -> (VectorcraftApp, egui::Context, std::sync::mpsc::Receiver) { let ctx = crate::testing::ui_context(); let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("prefs.set", &json!({"key": "displayPrintSize", "value": false})).unwrap(); app.run("file.new", json!({"width": 512, "height": 512})).unwrap(); // The app's frames zoom the interface by the preference. app.session.prefs.ui_scaling = f64::from(ui_zoom); diff --git a/crates/ui-egui/src/chrome/status_bar.rs b/crates/ui-egui/src/chrome/status_bar.rs index 0751e2802b..c4b6f8a5fe 100644 --- a/crates/ui-egui/src/chrome/status_bar.rs +++ b/crates/ui-egui/src/chrome/status_bar.rs @@ -20,7 +20,7 @@ pub fn status_bar(app: &mut VectorcraftApp, ui: &mut Ui) { if let Some(secs) = next { ui.ctx().request_repaint_after(std::time::Duration::from_secs(secs)); } - let print = app.session.prefs.display_print_size; + let print = app.print_ppi(); let nab = app.session.active().map(|d| d.doc.artboards.len()).unwrap_or(0); let cur = crate::panels::artboards::selected(app, nab); // PLAN: assumed Artboard::rect has `width()` and `height()`. @@ -310,15 +310,22 @@ fn date_time_now() -> (String, u64) { } /// The status message in the interface language. While it is the error of the last script run -/// and that error's message is text the script supplied, that text is shown as it is and only the -/// words around it are translated. +/// and that error's message is text the script supplied, or a plug-in run's notice +/// ([`crate::state::UiState::status_kept`]), that text is shown as it is and only the words around +/// it are translated. pub(crate) fn status_message(app: &VectorcraftApp) -> String { let status = app.ui.status.as_str(); + let is = |before: &str, kept: &str, after: &str| status.strip_prefix(before).and_then(|rest| rest.strip_suffix(after)) == Some(kept); if let Some((before, kept, after)) = app.session.script_authored_failure() - && status.strip_prefix(before.as_str()).and_then(|rest| rest.strip_suffix(after.as_str())) == Some(kept) + && is(&before, kept, &after) { return crate::i18n::msg_keeping(&before, kept, &after); } + if let Some((before, kept, after)) = &app.ui.status_kept + && is(before, kept, after) + { + return crate::i18n::msg_keeping(before, kept, after); + } crate::i18n::msg(status) } diff --git a/crates/ui-egui/src/chrome/tabs.rs b/crates/ui-egui/src/chrome/tabs.rs index 59f0dda7ce..0fbfa24fd4 100644 --- a/crates/ui-egui/src/chrome/tabs.rs +++ b/crates/ui-egui/src/chrome/tabs.rs @@ -9,22 +9,22 @@ use craft::ui::tabs::{DocumentTab, DocumentTabs, DocumentTabsEvent}; /// [`view_tab_title`] for a document with one view. #[cfg(test)] -pub(super) fn tab_title(d: &vectorcraft_engine::DocState, zoom: f64, outline: bool, display_print_size: bool) -> String { - view_tab_title(d, None, true, zoom, outline, display_print_size) +pub(super) fn tab_title(d: &vectorcraft_engine::DocState, zoom: f64, outline: bool, print: Option) -> String { + view_tab_title(d, None, true, zoom, outline, print) } /// A document tab's title: "Name* @ 66.67 % (RGB/Preview)", or while an opacity mask is edited /// "Name* @ 66.67 % (/Opacity Mask)". For a view of a document with more than one /// view, the view's `number` follows the name: "Name:2* @ 66.67 % (RGB/Preview)". The `*` of unsaved changes shows /// when `marked`; a document tab shows its own modified mark instead. -fn view_tab_title(d: &vectorcraft_engine::DocState, number: Option, marked: bool, zoom: f64, outline: bool, display_print_size: bool) -> String { +fn view_tab_title(d: &vectorcraft_engine::DocState, number: Option, marked: bool, zoom: f64, outline: bool, print: Option) -> String { let mode = if d.doc.mask_edit.is_some() { format!("<{0}>/{0}", tl!("Opacity Mask")) } else { let color = if d.doc.color_mode == vectorcraft_doc::ColorMode::Cmyk { "CMYK" } else { "RGB" }; format!("{color}/{}", if outline { tl!("Outline") } else { tl!("Preview") }) }; - format!("{} @ {} ({mode})", view_tab_name(d, number, marked), zoom_label(zoom, display_print_size).replace('%', " %")) + format!("{} @ {} ({mode})", view_tab_name(d, number, marked), zoom_label(zoom, print).replace('%', " %")) } /// The start of [`view_tab_title`], which an inactive document tab shows alone (#8582): "Name*", @@ -39,7 +39,7 @@ fn view_tab_name(d: &vectorcraft_engine::DocState, number: Option, marked: fn window_tab_title(app: &VectorcraftApp, w: crate::doc_windows::Win, d: &vectorcraft_engine::DocState, marked: bool) -> String { let view = crate::doc_windows::view(app, w); let zoom = view.map_or(1.0, |v| v.zoom); - view_tab_title(d, crate::doc_windows::label(app, w), marked, zoom, view.is_some_and(|v| v.outline), app.session.prefs.display_print_size) + view_tab_title(d, crate::doc_windows::label(app, w), marked, zoom, view.is_some_and(|v| v.outline), app.print_ppi_of(Some(w))) } /// The title of window `w`'s tab and floating window ([`crate::doc_windows`]). diff --git a/crates/ui-egui/src/chrome/tests.rs b/crates/ui-egui/src/chrome/tests.rs index 532c6ffef0..2c3b214c69 100644 --- a/crates/ui-egui/src/chrome/tests.rs +++ b/crates/ui-egui/src/chrome/tests.rs @@ -500,6 +500,59 @@ fn german_script_status_preserves_authored_error_and_translates_native_error() { assert_eq!(app.session.script_authored_failure(), None); } +/// A plug-in run's notice shows in the status bar after the plug-in's name once its output is +/// applied: the words around it are translated and the notice itself never is, even when it reads +/// like one of the app's own messages. A run whose output is refused shows no notice, and the next +/// status message replaces the notice. +#[test] +fn plugin_notice_shows_after_the_plug_in_s_name_and_is_never_translated() { + use vectorcraft_plugins::wat as tpl; + let mut app = crate::VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + let install = |app: &mut crate::VectorcraftApp, id: &str, output: &str| { + let module = wat::parse_str(tpl::returning(&tpl::manifest(id, "filter", "{}"), output)).unwrap(); + app.run("plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&module), "replace": true})).unwrap(); + }; + let id = "test.ui.notice"; + install(&mut app, id, r#"{"objects":[],"notice":"invalid array length"}"#); + let r = app.run("plugin.run", json!({"id": id})).unwrap(); + assert_eq!(r["notice"], json!("invalid array length")); + assert_eq!(app.ui.status, format!("Plug-in “Test {id}”: invalid array length")); + crate::i18n::set_current(crate::i18n::Lang::from_code("de").expect("de registered")); + assert_eq!(super::status_bar::status_message(&app), format!("Plug-in „Test {id}“: invalid array length")); + // The same words as an ordinary message are translated. + app.status("invalid array length"); + assert_eq!(super::status_bar::status_message(&app), "ungültige Array-Länge"); + crate::i18n::set_current(crate::i18n::Lang::EN); + // An output refused for its notice shows no notice. + let bad = "test.ui.notice.bad"; + install(&mut app, bad, r#"{"objects":[],"notice":"\u0007"}"#); + app.status(""); + assert!(app.run("plugin.run", json!({"id": bad})).is_err()); + assert!(!app.ui.status.starts_with("Plug-in “"), "{}", app.ui.status); + // A plug-in step of a batch, as an action plays it, shows its notice too. + app.status(""); + app.replay("command.batch", json!({"commands": [{"command": "plugin.run", "params": {"id": id}}, {"command": "select.none"}]})).unwrap(); + assert_eq!(app.ui.status, format!("Plug-in “Test {id}”: invalid array length")); + // A batch without a plug-in step leaves the status bar as it is. + app.status("kept"); + app.run("command.batch", json!({"commands": [{"command": "select.none"}]})).unwrap(); + assert_eq!(app.ui.status, "kept"); + // The notice keeps the plug-in's name when a later step of the batch removes the plug-in. + app.status(""); + let run_and_remove = json!({"commands": [{"command": "plugin.run", "params": {"id": id}}, {"command": "plugin.remove", "params": {"id": id}}]}); + app.run("command.batch", run_and_remove).unwrap(); + assert!(vectorcraft_plugins::registry::get(id).is_none()); + assert_eq!(app.ui.status, format!("Plug-in “Test {id}”: invalid array length")); + // A name's closing ellipsis is dropped, and a name that is only an ellipsis shows the plug-in's id. + for (name, shown) in [("Resize…", "Resize"), (" … ", id)] { + let r = json!({"plugin": id, "ids": [], "notice": "done", "pluginName": name}); + crate::plugin_runs::show_notice(&mut app, "plugin.run", &r); + assert_eq!(app.ui.status, format!("Plug-in “{shown}”: done")); + } + app.run("plugin.remove", json!({"id": bad})).unwrap(); +} + /// The message of an open that starts with a line about its linked files lists the open's notes on /// hover and for screen readers, in a wide and in a narrow window. A later message leaves the list /// out. @@ -733,7 +786,8 @@ fn the_artboard_navigator_goes_to_artboards_and_fitting_shows_the_current_one() assert_eq!(at(&mut bar), (1, Point::new(320.0, 50.0))); bar.app().run("view.actualSize", json!({})).unwrap(); let center = at(&mut bar).1; - assert_eq!((center, bar.app().view().unwrap().zoom), (Point::new(320.0, 50.0), 1.0)); + let baseline = crate::state::zoom_baseline(bar.app().print_ppi()); + assert_eq!((center, bar.app().view().unwrap().zoom), (Point::new(320.0, 50.0), baseline)); bar.click("First Artboard"); assert_eq!(at(&mut bar), (0, Point::new(100.0, 50.0)), "first"); // The command also takes an index, clamped to the last artboard. @@ -1085,7 +1139,7 @@ fn the_tab_title_names_the_opacity_mask_while_it_is_edited() { let mut s = Session::new(); s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 50, "height": 50})).unwrap(); - let title = |s: &Session| super::tab_title(s.active().unwrap(), 1.0, false, false); + let title = |s: &Session| super::tab_title(s.active().unwrap(), 1.0, false, None); assert!(title(&s).ends_with("(RGB/Preview)"), "{}", title(&s)); s.execute("transparency.makeOpacityMask", &json!({})).unwrap(); assert!(title(&s).ends_with("(/Opacity Mask)"), "{}", title(&s)); @@ -1110,6 +1164,27 @@ fn control_shown(app: crate::VectorcraftApp) -> Shown { Shown::new(app, egui::vec2(1600.0, 300.0), super::control_bar) } +/// With the Circle tool, the Control bar shows From Center unchecked; a click on it turns the option on and checks +/// it, and a second click turns it off and unchecks it. +#[test] +fn the_circle_tool_s_from_center_checkbox_sets_the_option() { + crate::i18n::set_current(crate::i18n::Lang::EN); + let mut app = crate::VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 200})).unwrap(); + app.select_tool("circle"); + let mut bar = control_shown(app); + let from_center = |bar: &Shown| bar.app().session.tool_options()["fromCenter"].clone(); + assert_eq!(from_center(&bar), json!(false)); + let target = bar.named("From Center"); + assert!(!bar.checked(&target), "From Center starts unchecked"); + for want in [true, false] { + bar.click("From Center").settle(); + assert_eq!(from_center(&bar), json!(want)); + let target = bar.named("From Center"); + assert_eq!(bar.checked(&target), want, "the checkbox shows the option"); + } +} + /// The Control bar's isolation button, if it shows: Isolate Selected Object, Exit Isolation Mode or Exit Symbol /// Editing Mode. fn isolation_button(bar: &mut Shown) -> Option { diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index b7914c350f..813ed31d97 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -171,6 +171,12 @@ pub fn inspect(app: &VectorcraftApp, ctx: &egui::Context) -> Value { // The display profile the canvas is drawn through, or why none (Preferences › // Performance › Use Monitor Profile for Canvas). "displayProfile": app.display_profile.status(app.session.prefs.monitor_profile_display), + // With Preferences › General › Display Print Size at 100% Zoom on, the measured density of + // the main window's display in points per inch (null where none was measured), and the + // points an inch takes at 100% in the current window. Both are null with it off, when the + // desktop app does not measure the displays. + "screenPpi": app.session.prefs.display_print_size.then(|| app.services.screen_ppi.ppi()).flatten(), + "printPpi": app.print_ppi(), // Window › Arrange › Tile and its layout (not saved, so not in `ui`) and the panes the // last frame drew: each one's document index, view number (Window › New Window) and rect. // Canvas coordinates map to the current window's pane, inside its rulers and scroll bars diff --git a/crates/ui-egui/src/control/tests.rs b/crates/ui-egui/src/control/tests.rs index fdda88b384..e7e617a74e 100644 --- a/crates/ui-egui/src/control/tests.rs +++ b/crates/ui-egui/src/control/tests.rs @@ -4,7 +4,7 @@ use vectorcraft_tools::{Mods, PointerEvent, PointerKind}; use craft::automation::{ControlRequest, Reply}; -use super::handle; +use super::{handle, inspect}; use crate::{Services, VectorcraftApp}; /// Whether a dialog is open on the app's window. @@ -785,7 +785,24 @@ fn the_method_table_routes_each_method_and_checks_its_params() { assert_eq!(after, before, "{id} {params}: nothing changes"); } app.run("view.setZoom", json!({"zoom": null, "center": null})).unwrap(); - assert_eq!(app.view().map(|v| v.zoom), Some(crate::state::zoom_from_display_percent(100.0, app.session.prefs.display_print_size))); + assert_eq!(app.view().map(|v| v.zoom), Some(crate::state::zoom_from_display_percent(100.0, app.print_ppi()))); +} + +/// `ui.inspect` gives the measured density of the main window's display and the points an inch +/// takes at 100% while Display Print Size at 100% Zoom is on, and neither with it off (#9051). +#[test] +fn inspect_reports_the_display_density() { + let mut app = VectorcraftApp::new(Session::new(), Services::default()); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + let ctx = egui::Context::default(); + let got = inspect(&app, &ctx); + assert_eq!((got["screenPpi"].clone(), got["printPpi"].as_f64()), (Value::Null, Some(96.0)), "nothing measured: an inch is 96 points"); + app.set_screen_ppi(Some(127.0)); + let got = inspect(&app, &ctx); + assert_eq!((got["screenPpi"].as_f64(), got["printPpi"].as_f64()), (Some(127.0), Some(127.0))); + app.session.execute("prefs.set", &json!({"key": "displayPrintSize", "value": false})).unwrap(); + let got = inspect(&app, &ctx); + assert_eq!((got["screenPpi"].clone(), got["printPpi"].clone()), (Value::Null, Value::Null)); } #[test] diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 7ce5c83baa..86e918f876 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -117,6 +117,7 @@ mod psd_options; pub mod raster_effects; pub mod rearrange_artboards; pub mod recolor; +pub mod recolor_preset; pub mod relink; pub mod rename_artboards; pub(crate) mod revolve; diff --git a/crates/ui-egui/src/dialogs/brush_art_options.rs b/crates/ui-egui/src/dialogs/brush_art_options.rs index 13261028e5..3bb0d3c8c8 100644 --- a/crates/ui-egui/src/dialogs/brush_art_options.rs +++ b/crates/ui-egui/src/dialogs/brush_art_options.rs @@ -528,13 +528,18 @@ fn art_rows(object: bool) -> Vec { rows } -/// The direction of the art along the stroke: a segment per direction in [`DIRECTIONS`] order. +/// The direction of the art along the stroke: an arrow segment per direction in [`DIRECTIONS`] order, +/// named by its tooltip. fn direction_row() -> Param { - // PLAN: the arrows are text until sh.S5's `APP_ICONS` names its arrow icons (with the tooltips Left to Right, Right to Left, Top to Bottom, Bottom to Top); a screen reader reads each segment as its glyph. - let arrows = ["→", "←", "↓", "↑"]; + let arrows = [ + ("dc-arrow-right", tl!("Left to Right")), + ("dc-arrow-left", tl!("Right to Left")), + ("dc-arrow-down", tl!("Top to Bottom")), + ("dc-arrow-up", tl!("Bottom to Top")), + ]; Param::custom("direction", tl!("Direction"), move |ui, f, _| { let current = DIRECTIONS.iter().position(|d| *d == parse_field::(f, "direction")).unwrap_or(0); - let entries: Vec> = arrows.iter().enumerate().map(|(i, arrow)| Entry::new(i, *arrow)).collect(); + let entries: Vec> = arrows.iter().enumerate().map(|(i, (icon, tip))| Entry::new(i, *tip).icon(IconId::new(icon))).collect(); let shown = Segmented::new(tl!("Direction"), Bind::given(current), &entries).show(ui); if let Some(dir) = shown.value().and_then(|i| DIRECTIONS.get(*i)) { f.set("direction", id_of(dir)); diff --git a/crates/ui-egui/src/dialogs/brush_options/tests.rs b/crates/ui-egui/src/dialogs/brush_options/tests.rs index 0f2db21d46..34e11865cf 100644 --- a/crates/ui-egui/src/dialogs/brush_options/tests.rs +++ b/crates/ui-egui/src/dialogs/brush_options/tests.rs @@ -278,6 +278,26 @@ fn ok_redraws_the_strokes_painted_with_the_brush() { assert!((drawn_height(&app, id) - before).abs() < 1e-6); } +/// Art Brush Options draws each Direction segment as an arrow icon named by its tooltip, so the +/// accessibility tree reads the direction instead of an arrow glyph. +#[test] +fn art_brush_direction_segments_are_named_by_their_tooltips() { + let mut app = app(); + open(&mut app, "Arrow"); + crate::dialogs::tests::settle(&mut app); + let out = crate::dialogs::tests::frame(&mut app, vec![]); + let nodes = out.platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default(); + // Segmented gives each segment the radio button role. + let segments: Vec<&str> = + nodes.iter().filter(|(_, node)| node.role() == egui::accesskit::Role::RadioButton).filter_map(|(_, node)| node.label()).collect(); + for tip in ["Left to Right", "Right to Left", "Top to Bottom", "Bottom to Top"] { + assert!(segments.contains(&tip), "no segment is named {tip} in {segments:?}"); + } + for glyph in ["→", "←", "↓", "↑"] { + assert!(!segments.contains(&glyph), "a segment is named {glyph}"); + } +} + #[test] fn a_taken_name_keeps_the_dialog_open() { let mut app = app(); diff --git a/crates/ui-egui/src/dialogs/confirm.rs b/crates/ui-egui/src/dialogs/confirm.rs index 9584166098..12e13a36b3 100644 --- a/crates/ui-egui/src/dialogs/confirm.rs +++ b/crates/ui-egui/src/dialogs/confirm.rs @@ -7,6 +7,7 @@ use craft::ui::dialog::{Alert, DialogHost, DialogId, DialogResult, HostedAlert, PromptChoice, StackDialog, StandardPrompt, StartupStage}; use egui::Context; use serde_json::{Value, json}; +use vectorcraft_engine::file_access::ScopeHandle; use crate::VectorcraftApp; @@ -81,8 +82,18 @@ macro_rules! wrapped_dialog { } pub(crate) use wrapped_dialog; -/// A confirmation: its tag is the command OK runs and that command's params. +/// A confirmation: its tag is an [`Asked`]. pub(crate) struct Question(StandardPrompt); + +/// The tag of a confirmation ([`ask`]): the command OK runs, and the access it runs under. +struct Asked { + command: String, + params: Value, + /// The automation roots in force when asked: the command runs under them. + scope: ScopeHandle, + /// Automation asked ([`VectorcraftApp::automation_asked`]): the command runs as automation. + automated: bool, +} wrapped_dialog!(Question, StandardPrompt, KIND); /// A message with a Close button. @@ -110,6 +121,10 @@ pub(crate) struct ReplaceFiles { pub(crate) command: String, /// Its params. pub(crate) params: Value, + /// The automation roots in force when asked: the command runs again under them. + pub(crate) scope: ScopeHandle, + /// Automation asked ([`VectorcraftApp::automation_asked`]): the command runs again as automation. + pub(crate) automated: bool, } /// Ask `message` (with an optional `detail` line), both in the UI language; OK runs `command` @@ -123,7 +138,8 @@ pub fn ask(app: &mut VectorcraftApp, message: &str, detail: &str, command: &str, if !detail.is_empty() { prompt = prompt.paragraph(detail.to_string()); } - let prompt = prompt.button(PromptChoice::Proceed, tl!("OK")).button(PromptChoice::Cancel, tl!("Cancel")).tag((command.to_string(), params)); + let asked = Asked { command: command.to_string(), params, scope: ScopeHandle::capture(), automated: app.automation_asked() }; + let prompt = prompt.button(PromptChoice::Proceed, tl!("OK")).button(PromptChoice::Cancel, tl!("Cancel")).tag(asked); dialogs.with(|host| host.open(Question(prompt))); } @@ -184,6 +200,8 @@ pub(crate) fn ask_replace_files(app: &mut VectorcraftApp, doc: u64, files: &[Str allowed: allowed.to_vec(), command: command.to_string(), params, + scope: ScopeHandle::capture(), + automated: app.automation_asked(), }); // Asked when a Background Save or Export ends: a dialog open then stays, and this waits its turn // (however many messages wait: the save or export needs the answer). @@ -240,8 +258,8 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &Context) { }; if let Some(DialogResult::Ok(mut answer)) = dialogs.with(|host| host.take::()) && answer.choice == PromptChoice::Proceed - && let Some((command, params)) = answer.take_tag::<(String, Value)>() - && let Err(e) = app.run(&command, params) + && let Some(Asked { command, params, scope, automated }) = answer.take_tag::() + && let Err(e) = scope.run(|| crate::file_asks::as_automated(app, automated, |app| app.run(&command, params))) { app.status(e); } @@ -273,8 +291,8 @@ pub(crate) fn pump_missing_font(app: &mut VectorcraftApp, _ctx: &Context) { pub(crate) fn open_question(app: &VectorcraftApp) -> Option<(String, String, String)> { app.dialogs()?.with(|host| { let prompt = &host.get::()?.0; - let (command, _) = prompt.tag_as::<(String, Value)>()?; - Some((prompt.shown_message(&app.host), prompt.shown_paragraphs(&app.host).join("\n"), command.clone())) + let asked = prompt.tag_as::()?; + Some((prompt.shown_message(&app.host), prompt.shown_paragraphs(&app.host).join("\n"), asked.command.clone())) }) } @@ -290,3 +308,13 @@ pub(crate) fn open_message(app: &VectorcraftApp) -> Option<(String, String)> { pub(crate) fn open_replace_files(app: &VectorcraftApp) -> Option> { app.dialogs()?.with(|host| host.get::().and_then(|q| q.0.tag_as::().map(|tag| tag.files.clone()))) } + +/// Whether the open question about replacing files runs its command confined to automation roots, +/// and whether as automation, while it is open. +#[cfg(test)] +pub(crate) fn open_replace_files_access(app: &VectorcraftApp) -> Option<(bool, bool)> { + app.dialogs()?.with(|host| { + let tag = host.get::()?.0.tag_as::()?; + Some((tag.scope.clone().run(vectorcraft_engine::file_access::current).is_some(), tag.automated)) + }) +} diff --git a/crates/ui-egui/src/dialogs/dxf_options.rs b/crates/ui-egui/src/dialogs/dxf_options.rs index d1a66945ff..a23a07e757 100644 --- a/crates/ui-egui/src/dialogs/dxf_options.rs +++ b/crates/ui-egui/src/dialogs/dxf_options.rs @@ -9,9 +9,11 @@ //! (asking where when there is no path); bad options keep the dialog open. use craft::ui::contract::{Bind, Entry, Show as _, ShowContainer as _}; +use craft::ui::display::{Shade, Text}; use craft::ui::layout_components::Row; use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind}; use craft::ui::pickers::Select; +use craft::ui::style::TypeRole; use craft::ui::text::NumberField; use serde_json::{Map, Value, json}; use vectorcraft_cad::{ColorDepth, DxfPreset, DxfVersion, Preserve, RasterFormat}; @@ -145,11 +147,11 @@ pub(crate) fn scale_param(disabled_when: Option<(&str, FieldValue)>) -> Param { let (lo, hi) = (*vectorcraft_cad::SCALE_RANGE.start(), *vectorcraft_cad::SCALE_RANGE.end()); let shown = Row::new() .show(ui, |ui, _| { - ui.label("1"); + Text::new("1").show(ui); Select::new(tl!("Unit"), Bind::bound(&mut unit), &units).show(ui); - ui.label("="); + Text::new("=").show(ui); NumberField::new(tl!("Scale"), Bind::bound(&mut scale)).range(lo..=hi).show(ui); - ui.label(tl!("Units")); + Text::new(tl!("Units")).show(ui); }) .output; let scale = scale.unwrap_or(1.0); @@ -200,10 +202,13 @@ pub fn open_with(app: &mut VectorcraftApp, params: &Value, selection: bool) { .values(Bind::bound(fields)) .ok_label(tl!("Export").into()) .below(|ui, fields| { - ui.weak(match fields.text("preserve").and_then(Preserve::from_id).unwrap_or_default() { + Text::new(match fields.text("preserve").and_then(Preserve::from_id).unwrap_or_default() { Preserve::Appearance => tl!("Type becomes outlines, and strokes a CAD line can't draw become filled shapes."), Preserve::Editability => tl!("Type stays text, and every stroke is a line with its lineweight and dashes."), - }); + }) + .role(TypeRole::Caption) + .shade(Shade::Muted) + .show(ui); }) }); export_host::open(app, Export::Dxf, selection, dialog); diff --git a/crates/ui-egui/src/dialogs/eps_options.rs b/crates/ui-egui/src/dialogs/eps_options.rs index 2a1ee5ec8b..eda7ff4724 100644 --- a/crates/ui-egui/src/dialogs/eps_options.rs +++ b/crates/ui-egui/src/dialogs/eps_options.rs @@ -17,8 +17,10 @@ use std::sync::Arc; use craft::ui::buttons::Button; use craft::ui::contract::{Bind, Show as _, ShowContainer as _, TooltipSpec}; use craft::ui::dialog::DialogId; +use craft::ui::display::{Shade, Text}; use craft::ui::layout_components::Row; use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind}; +use craft::ui::style::TypeRole; use serde_json::{Map, Value, json}; use vectorcraft_engine::cmd::{FlattenOptions, FlattenerPreset, fileio}; use vectorcraft_eps::{Level, Overprint, Preview}; @@ -139,11 +141,14 @@ pub fn open_with(app: &mut VectorcraftApp, params: &Value, selection: bool) { builtin_label(fields); normalise_level(fields); ParamDialog::new(KIND, tl!("EPS Options"), rows(&presets)).values(Bind::bound(fields)).ok_label(tl!("Export").into()).below(|ui, fields| { - ui.weak(if fields.text("level").and_then(Level::from_id) == Some(Level::Two) || fields.bool("compatibleGradients") == Some(true) { + Text::new(if fields.text("level").and_then(Level::from_id) == Some(Level::Two) || fields.bool("compatibleGradients") == Some(true) { tl!("Transparency is flattened with the preset. Type is written as outlines; gradients as bands of colour.") } else { tl!("Transparency is flattened with the preset. Type is written as outlines; gradients stay smooth.") - }); + }) + .role(TypeRole::Caption) + .shade(Shade::Muted) + .show(ui); }) }); export_host::open(app, Export::Eps, selection, dialog); @@ -198,7 +203,10 @@ pub(super) fn custom_dialog(app: &VectorcraftApp, parent: DialogId, fields: &Dia ParamDialog::new(CUSTOM_KIND, tl!("Custom Transparency Flattener Options"), flatten::option_params(&FIXED, FIXED_REASON)) .values(Bind::bound(fields)) .below(|ui, _| { - ui.weak(tl!("EPS has no alpha transparency, and Overprints sets whether overprints are kept.")); + Text::new(tl!("EPS has no alpha transparency, and Overprints sets whether overprints are kept.")) + .role(TypeRole::Caption) + .shade(Shade::Muted) + .show(ui); }) }) } diff --git a/crates/ui-egui/src/dialogs/export_as.rs b/crates/ui-egui/src/dialogs/export_as.rs index 3c76dea90e..6e8f8bc1d2 100644 --- a/crates/ui-egui/src/dialogs/export_as.rs +++ b/crates/ui-egui/src/dialogs/export_as.rs @@ -11,9 +11,11 @@ use std::sync::LazyLock; -use craft::ui::contract::Bind; +use craft::ui::contract::{Bind, Show as _}; +use craft::ui::display::{Shade, Text}; use craft::ui::patterns::form_dialogs::{DialogFields, HostedParamDialog, Param, ParamDialog, ParamKind}; use craft::ui::runtime::env::Label; +use craft::ui::style::TypeRole; use serde_json::{Value, json}; use vectorcraft_engine::cmd::fileio::{self, ArtboardPick, Format}; @@ -127,7 +129,7 @@ fn open_dialog(app: &mut VectorcraftApp, format: Option<&str>, p: &Value) -> Res ParamDialog::new(KIND, tl!("Export As"), params()) .values(Bind::bound(fields)) .below(|ui, fields| { - ui.weak(summary(fields)); + Text::new(summary(fields)).role(TypeRole::Caption).shade(Shade::Muted).show(ui); }) .ok_label(Label::from("Export…")) }); diff --git a/crates/ui-egui/src/dialogs/flattener_presets.rs b/crates/ui-egui/src/dialogs/flattener_presets.rs index b59f3b2a15..5346bf06f6 100644 --- a/crates/ui-egui/src/dialogs/flattener_presets.rs +++ b/crates/ui-egui/src/dialogs/flattener_presets.rs @@ -90,10 +90,7 @@ fn run(app: &mut VectorcraftApp, event: &ManagerEvent, current: &str) -> Result< Ok(app.session.flattener_presets().get(above).map(|p| p.name.clone())) } ManagerEvent::Action(ManagerAction::Import) => preset_manager::import(app, KEY, "flattener.presets.import", "Flattener presets", PRESET_EXTS), - ManagerEvent::Action(ManagerAction::Export) => { - crate::io::save_command_output(app, "flattener.presets.export", PRESET_FORMAT, json!({ "names": [current] }), |_, _| Ok(Value::Null))?; - Ok(None) - } + ManagerEvent::Action(ManagerAction::Export) => preset_manager::export(app, "flattener.presets.export", PRESET_FORMAT, current), // A new name that is taken or a built-in one is refused by the command. ManagerEvent::Rename(name) if name.trim() == current => Ok(None), ManagerEvent::Rename(name) => Ok(select(app.run("flattener.presets.save", json!({ "name": current, "newName": name }))?)), @@ -216,6 +213,8 @@ mod tests { let picker = crate::tests::picks::scripted(&mut app); open(&mut app, Some("Mine")); press(&mut app, ManagerAction::Export); + // The save panel suggests the preset's name. + assert_eq!(picker.requests().last().and_then(|r| r.file_name.clone()).as_deref(), Some("Mine.vcflattener")); // The answered save panel writes the file in the next frame. picker.answer_saved(&file, None); frame(&mut app); diff --git a/crates/ui-egui/src/dialogs/freehand.rs b/crates/ui-egui/src/dialogs/freehand.rs index d4b411dc90..d38a4eb35a 100644 --- a/crates/ui-egui/src/dialogs/freehand.rs +++ b/crates/ui-egui/src/dialogs/freehand.rs @@ -4,14 +4,14 @@ //! (Live curve fitting, on: its preview fits the stroke while it is drawn). //! //! Fields: `tool`; `fidelity` (screen pixels for the Pencil, Paintbrush and Smooth, points for the -//! Blob Brush), `fill` (Pencil and +//! Blob Brush), `smoothness` (percent, 0 to 100; Smooth), `fill` (Pencil and //! Paintbrush), `keepSelected` (Pencil, Paintbrush and Blob Brush), `mergeOnlySelection` (Blob //! Brush), `closeWithin` and `editWithin` (screen pixels, 0 turns it off; Pencil and Paintbrush), //! `angle` (degrees) and `roundness` (percent; Blob Brush and Eraser), `livePreview` (Pencil: the stroke shows //! with its fill and stroke while it is drawn, or as a thin line until the release), `size` //! (points; Blob Brush and Eraser), and `sizeMode` and `sizeVariation` (points; Blob Brush and //! Eraser: with Pressure the tip is Size − Variation wide at the lightest pen pressure and Size + -//! Variation at the heaviest). The Blob Brush's `sizeMode` is `fixed` or `pressure`. The Eraser's +//! Variation at the heaviest). The Blob Brush's `sizeMode` is `fixed`, `pressure` or `stylusWheel`. The Eraser's //! Angle, Roundness and Size each have a menu (`angleMode`, `roundnessMode`, `sizeMode`: `fixed`, //! `random`, `pressure`, `tilt`, `bearing` or `rotation`) before the field and a Variation field //! under it (`angleVariation` in degrees, `roundnessVariation` in percent, `sizeVariation`), @@ -45,8 +45,9 @@ pub const KIND: &str = "freehandOptions"; pub const TOOLS: [&str; 5] = ["pencil", "paintbrush", "smooth", "blobBrush", "eraser"]; /// The options the dialog edits, in the order it shows them (a tool has those it reports). -const KEYS: [&str; 18] = [ +const KEYS: [&str; 19] = [ "fidelity", + "smoothness", "angle", "angleMode", "angleVariation", @@ -227,6 +228,12 @@ fn params(tool: &str, present: &[&str]) -> Vec { .full_width(), ); } + if has("smoothness") { + // The Smooth tool's Smoothness: a slider from 0% to 100% with the field at its end, in whole percent. + rows.push( + Param::new("smoothness", tl!("Smoothness:"), ParamKind::range(0.0, 100.0, 50.0, SliderScale::Linear)).decimals(0).unit(UnitKind::Percent), + ); + } if eraser { rows.push(variation_param("angle", tl!("Angle:"), UnitKind::Degrees, 0, (-180.0, 180.0), (0.0, 180.0), &Variation::ALL)); rows.push(variation_param("roundness", tl!("Roundness:"), UnitKind::Percent, 0, (1.0, 100.0), (0.0, 100.0), &Variation::ALL)); @@ -244,7 +251,7 @@ fn params(tool: &str, present: &[&str]) -> Vec { rows.push(Param::custom("tip", "", |ui, fields, _| tip_row(ui, fields, 0.0)).full_width()); } if has("sizeMode") { - let offered = &[Variation::Fixed, Variation::Pressure]; + let offered = &vectorcraft_tools::draw2::BLOB_SIZE_MODES; rows.push(variation_param("size", tl!("Size:"), UnitKind::Points, 1, (0.1, 1000.0), (0.0, 1000.0), offered)); } else if has("size") { rows.push(Param::number("size", tl!("Size:"), 10.0, 1.0, 1).unit(UnitKind::Points).bounds(Some(0.1), Some(1000.0))); diff --git a/crates/ui-egui/src/dialogs/freehand/tests.rs b/crates/ui-egui/src/dialogs/freehand/tests.rs index 38b911f0b5..300d5543a3 100644 --- a/crates/ui-egui/src/dialogs/freehand/tests.rs +++ b/crates/ui-egui/src/dialogs/freehand/tests.rs @@ -43,6 +43,32 @@ fn the_fidelity_keys_step_finely_at_the_low_end() { assert_eq!((fidelity_step(0.035, 1.0), fidelity_step(0.035, -1.0), fidelity_step(1.5, 1.0), fidelity_step(1.5, -1.0)), (0.04, 0.03, 2.0, 1.0)); } +/// Smooth Tool Options shows Smoothness under Fidelity, at 50% until it is set, and OK sets it from 0% to 100%; a +/// Smoothness past 100% is refused and sets nothing. The other freehand tools have no Smoothness. +#[test] +fn smooth_tool_options_set_the_smoothness() { + let mut app = app(); + let smooth = app.session.tool_options_of("smooth"); + assert_eq!(smooth["smoothness"], json!(50.0)); + let present: Vec<&str> = KEYS.iter().copied().filter(|key| smooth.get(*key).is_some()).collect(); + let keys: Vec = params("smooth", &present).iter().map(|p| p.key.to_string()).collect(); + let (fidelity, smoothness) = (keys.iter().position(|k| k == "fidelity"), keys.iter().position(|k| k == "smoothness")); + assert!(fidelity.is_some() && fidelity < smoothness, "{keys:?}"); + for value in [30.0, 0.0, 100.0] { + set_through_dialog(&mut app, "smooth", &[("smoothness", json!(value))]); + assert_eq!(app.session.tool_options_of("smooth")["smoothness"], json!(value)); + } + let key = app.run("tool.options", json!({"tool": "smooth"})).unwrap()["dialog"].as_str().unwrap().to_owned(); + let (ctx, id) = (app.ui_ctx.clone().expect("a window"), open_id(&app, &key)); + let host = app.dialogs().expect("a window"); + assert!(host.with(|host| host.set_json_field(&ctx, id, "smoothness", json!(120))).is_err(), "120% is refused"); + host.with(|host| host.cancel_by_id(&ctx, id)); + assert_eq!(app.session.tool_options_of("smooth")["smoothness"], json!(100.0)); + for tool in ["pencil", "paintbrush", "blobBrush", "eraser"] { + assert!(app.session.tool_options_of(tool).get("smoothness").is_none(), "{tool}"); + } +} + /// Each tool's dialog, opened as the user opens it, stores the values set in it as the tool's options: the field /// keys, the units (Liquify's percent is a fraction) and the companion keys of the variation rows. #[test] @@ -60,7 +86,7 @@ fn ok_sets_each_tools_options() { json!({"fidelity": 6.5, "fill": true, "altSmooth": true, "closeWithin": 0.0, "editWithin": 20.0, "liveFit": false}), ), ("paintbrush", json!({"fidelity": 3, "keepSelected": false}), "paintbrush", json!({"fidelity": 3.0, "keepSelected": false})), - ("smooth", json!({"fidelity": 5}), "smooth", json!({"fidelity": 5.0})), + ("smooth", json!({"fidelity": 5, "smoothness": 75}), "smooth", json!({"fidelity": 5.0, "smoothness": 75.0})), ( "blobBrush", json!({"angle": 45, "roundness": 0, "sizeMode": "pressure", "sizeVariation": 6, "fidelity": 0.01, "keepSelected": true, "mergeOnlySelection": true}), @@ -306,3 +332,30 @@ fn the_blob_brush_and_eraser_size_can_follow_the_pen_pressure() { let o = app.session.tool_options_of("pencil"); assert!(o.get("sizeMode").is_none() && o.get("sizeVariation").is_none()); } + +/// The names and values the window's access tree shows. +fn shown_text(app: &mut VectorcraftApp) -> String { + crate::dialogs::tests::settle(app); + let out = crate::dialogs::tests::frame(app, vec![]); + let update = out.platform_output.accesskit_update.expect("an accessibility tree"); + update.nodes.iter().flat_map(|(_, node)| [node.label(), node.value()]).flatten().collect::>().join("\n") +} + +/// The Blob Brush's Size menu offers Stylus Wheel beside Fixed and Pressure, Fixed still the +/// default; the menu shows it once chosen, and OK sets it with the Variation. +#[test] +fn the_blob_brush_size_offers_the_stylus_wheel() { + let mut app = app(); + app.run("tool.options", json!({"tool": "blobBrush"})).unwrap(); + assert_eq!(crate::dialogs::tests::fields(&app)["sizeMode"], json!("fixed"), "Fixed by default"); + crate::dialogs::tests::set(&mut app, "sizeMode", json!("stylusWheel")); + crate::dialogs::tests::set(&mut app, "sizeVariation", json!(5)); + let text = shown_text(&mut app); + assert!(text.contains("Stylus Wheel"), "{text}"); + assert!(crate::dialogs::tests::confirm(&mut app), "OK closes the dialog"); + let o = app.session.tool_options_of("blobBrush"); + assert_eq!((o["sizeMode"].clone(), o["sizeVariation"].as_f64()), (json!("stylusWheel"), Some(5.0))); + app.run("tool.options", json!({"tool": "blobBrush"})).unwrap(); + let text = shown_text(&mut app); + assert!(text.contains("Stylus Wheel"), "it shows again on the next open: {text}"); +} diff --git a/crates/ui-egui/src/dialogs/gradient_stop.rs b/crates/ui-egui/src/dialogs/gradient_stop.rs index d38eae5bb0..3ba900ff01 100644 --- a/crates/ui-egui/src/dialogs/gradient_stop.rs +++ b/crates/ui-egui/src/dialogs/gradient_stop.rs @@ -30,12 +30,12 @@ use craft::ui::text::NumberField; use egui::{Pos2, Ui, vec2}; use serde_json::{Value, json}; use vectorcraft_color::gradient::move_stop; -use vectorcraft_color::{Color, FreeformPoint, GradientKind, GradientStop, Paint}; +use vectorcraft_color::{Color, FreeformPoint, GradientStop, Paint}; use vectorcraft_geom::{Point, Rect}; use vectorcraft_tools::params::color_json; use crate::VectorcraftApp; -use crate::panels::gradient::{edit_point, set_stops, set_stops_keeping_models, shown_points}; +use crate::panels::gradient::{edit_point, edits_points, set_stops, set_stops_keeping_models, shown_points}; use crate::panels::{Live, active_paint, c32}; /// The dialog kind of the gradient stop popover. @@ -82,7 +82,7 @@ impl Target { fn selected(app: &VectorcraftApp) -> Option { let Paint::Gradient(g) = active_paint(app) else { return None }; - if g.gradient.kind == GradientKind::Freeform { + if edits_points(app, &g) { let f = shown_points(&g); let i = app.session.selected_freeform_point().filter(|i| *i < f.points.len())?; return Some(Target::Point(f.points[i], i)); @@ -390,7 +390,7 @@ pub(crate) fn open_at(app: &mut VectorcraftApp, index: usize, anchor: Anchor) { let Some(ctx) = app.ui_ctx.clone() else { return }; let Some(dialogs) = app.dialogs() else { return }; if let Paint::Gradient(g) = active_paint(app) - && g.gradient.kind != GradientKind::Freeform + && !edits_points(app, &g) && app.session.selected_stop() != Some(index) { // An index past the last stop selects nothing, and `selected` then finds nothing to edit. diff --git a/crates/ui-egui/src/dialogs/hpgl_options.rs b/crates/ui-egui/src/dialogs/hpgl_options.rs index 50eab143f5..90d17d4f6f 100644 --- a/crates/ui-egui/src/dialogs/hpgl_options.rs +++ b/crates/ui-egui/src/dialogs/hpgl_options.rs @@ -12,15 +12,16 @@ //! nothing. use craft::behavior::IconId; +use craft::theme::variant::Tone; use craft::theme::{Rgba, Srgba}; use craft::ui::buttons::{Button, IconButton}; use craft::ui::choice::{Radio, RadioGroup, Swatch}; -use craft::ui::contract::{Bind, Props as _, Scroll, Show as _, ShowContainer as _}; +use craft::ui::contract::{Bind, Politeness, Props as _, Scroll, Show as _, ShowContainer as _}; use craft::ui::dialog::DialogId; +use craft::ui::display::Text; use craft::ui::layout_components::{Row, Stack}; +use craft::ui::notices::{Notice, NoticeLayout}; use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog}; -use craft::ui::runtime::env::Env; -use craft::ui::style::rgba_color; use craft::ui::text::TextField; use serde_json::{Map, Value, json}; use vectorcraft_cad::hpgl::write::{DEFAULT_TOLERANCE, MAX_PENS, TOLERANCE_RANGE}; @@ -209,8 +210,10 @@ fn pens_ui(ui: &mut egui::Ui, fields: &DialogFields) -> PensAsked { asked.table = Some(on); } if let Some(e) = fields.text(PEN_ERROR).filter(|_| asked.table != Some(false)) { - let error = rgba_color(Env::of(ui).tokens.tokens().color.status.bad.fg); - ui.colored_label(error, crate::i18n::message(crate::i18n::current(), e)); + Notice::new(Tone::Bad, crate::i18n::message(crate::i18n::current(), e).to_string()) + .layout(NoticeLayout::Inline) + .announce(Politeness::Assertive) + .show(ui); } // A table longer than a plot takes (set through `ui.dialog.set`) draws no rows: OK refuses it. let Some(mut pens) = list.filter(|a| asked.table.is_none() && a.len() <= MAX_PENS) else { return asked }; @@ -225,7 +228,7 @@ fn pens_ui(ui: &mut egui::Ui, fields: &DialogFields) -> PensAsked { (remove, asked.pick) = (None, None); for (i, pen) in pens.iter().enumerate() { Row::new().id_salt(("hpgl-pen-row", i)).show(ui, |ui, _| { - ui.label((i + 1).to_string()); + Text::new((i + 1).to_string()).show(ui); let mut color = pen.as_str().and_then(Rgba::from_hex).unwrap_or(Rgba::rgb(0, 0, 0)); if Swatch::new(tl!("Pen color"), Srgba::from(color)).show(ui).clicked { asked.pick = Some((i, Srgba::from(color))); diff --git a/crates/ui-egui/src/dialogs/kinsoku_sets.rs b/crates/ui-egui/src/dialogs/kinsoku_sets.rs index c2c334f148..1aac4c28b8 100644 --- a/crates/ui-egui/src/dialogs/kinsoku_sets.rs +++ b/crates/ui-egui/src/dialogs/kinsoku_sets.rs @@ -15,12 +15,14 @@ //! Behavior reference: the help page //! . +use craft::theme::variant::Tone; use craft::ui::buttons::Button; -use craft::ui::contract::{Bind, Entry, Props as _, Show as _, ShowContainer as _}; +use craft::ui::contract::{Bind, Entry, Politeness, Props as _, Show as _, ShowContainer as _}; use craft::ui::dialog::{Dialog, DialogId, DialogResult, DialogStack, FieldRefusal, HeldAnswer, HeldOk, StackDialog, dialog_id}; use craft::ui::display::Text; use craft::ui::form::{Field, FieldGroup}; use craft::ui::layout_components::{Row, Stack}; +use craft::ui::notices::{Notice, NoticeLayout}; use craft::ui::patterns::presets::{ NameCheck, NamedPresetEvent, NamedPresetRow, PickerField, PresetError, PresetPicker, PresetRow, PresetSource, PresetState, }; @@ -408,9 +410,8 @@ impl KinsokuDialog { } fn show_problem(&self, ui: &mut Ui) { - // PLAN: craft_ui does not re-export `Tone`, which `Notice` needs, so the reason shows as plain text. if let Some(problem) = &self.problem { - Text::new(problem.clone()).show(ui); + Notice::new(Tone::Bad, problem.clone()).layout(NoticeLayout::Inline).announce(Politeness::Assertive).show(ui); } } } diff --git a/crates/ui-egui/src/dialogs/new_document.rs b/crates/ui-egui/src/dialogs/new_document.rs index e60e9e0b3a..f45d77ab38 100644 --- a/crates/ui-egui/src/dialogs/new_document.rs +++ b/crates/ui-egui/src/dialogs/new_document.rs @@ -479,7 +479,7 @@ fn more_settings(ui: &mut egui::Ui, s: &mut DocSettings, lengths: LengthUnits) { Field::new(layout.clone()).show(ui, |ui, _| { let entries: Vec> = ArtboardLayout::ALL.iter().map(|l| Entry::new(*l, text(tl!(l.label())))).collect(); if let Some(l) = Segmented::new(layout.clone(), Bind::given(s.layout), &entries).enabled(several).show(ui).value().copied() { - s.layout = l; + choose_layout(s, l); } }); let rtl = Checkbox::new(Bind::given(s.right_to_left)).label(right_to_left).enabled(several).show(ui); @@ -494,14 +494,37 @@ fn more_settings(ui: &mut egui::Ui, s: &mut DocSettings, lengths: LengthUnits) { }); Field::new(columns.clone()).show(ui, |ui, _| { let n = f64::from(s.artboards.max(1)); - let shown = f64::from(s.columns.max(1)).min(n); + let shown = f64::from(shown_columns(s)); let field = NumberField::new(columns.clone(), Bind::given(Some(shown))).range(1.0..=n).step(1.0).commit_decimals(0).enabled(several && grid); if let Some(v) = field.show(ui).value().copied().flatten().filter(|v| v.is_finite()) { + // A column count replaces a preset's rows. s.columns = v.round().clamp(1.0, n) as u32; + s.rows = 0; } }); } +/// The columns More Settings shows: for a grid by column made with `file.new`'s `rows`, the columns +/// those rows give the current number of artboards, as `file.new` lays them out; otherwise the +/// stored count. At most one for each artboard. +fn shown_columns(s: &DocSettings) -> u32 { + let n = s.artboards.max(1); + if s.layout == ArtboardLayout::GridByColumn && s.rows > 0 { u32::try_from(s.grid_columns()).unwrap_or(n) } else { s.columns.max(1).min(n) } +} + +/// Chooses a layout in More Settings. Another layout replaces a preset's rows and keeps the column +/// count those rows showed; choosing the layout that is already selected keeps the rows. +fn choose_layout(s: &mut DocSettings, l: ArtboardLayout) { + if l == s.layout { + return; + } + if s.rows > 0 { + s.columns = shown_columns(s); + s.rows = 0; + } + s.layout = l; +} + /// Manage Profiles' pop-up: a row per New Document profile with Edit, which opens the profile as a /// document, and Reset, which brings back the shipped profile. The button pressed is put in `action`. fn manage_profiles(ui: &mut egui::Ui, setup: &Setup, action: &mut Option) { @@ -885,6 +908,53 @@ mod tests { assert_eq!((saved.layout, saved.spacing), (ArtboardLayout::Column, 30.0)); } + /// A grid by column with a preset's rows. + fn by_rows(artboards: u32, rows: u32) -> DocSettings { + DocSettings { artboards, layout: ArtboardLayout::GridByColumn, columns: 2, rows, ..DocSettings::default() } + } + + /// Columns shows what a preset's rows give the current number of artboards, and the stored + /// count without rows. + #[test] + fn columns_follow_a_presets_rows_as_artboards_change() { + for (artboards, shown) in [(5, 2), (9, 3), (2, 1)] { + assert_eq!(shown_columns(&by_rows(artboards, 4)), shown, "{artboards} artboards"); + } + assert_eq!(shown_columns(&by_rows(9, 0)), 2); + } + + /// Another layout replaces a preset's rows and keeps the columns they showed, so Create lays out + /// what the dialog showed; the layout already selected keeps the rows. + #[test] + fn a_new_layout_keeps_the_columns_a_presets_rows_showed() { + for to in [ArtboardLayout::GridByRow, ArtboardLayout::Row, ArtboardLayout::Column] { + let mut s = by_rows(9, 4); + choose_layout(&mut s, to); + assert_eq!((s.layout, s.columns, s.rows), (to, 3, 0), "{to:?}"); + } + let mut s = by_rows(9, 4); + choose_layout(&mut s, ArtboardLayout::GridByColumn); + assert_eq!(s, by_rows(9, 4)); + let mut s = by_rows(9, 0); + choose_layout(&mut s, ArtboardLayout::GridByRow); + assert_eq!((s.columns, s.rows), (2, 0)); + } + + /// A preset's rows reach the dialog's fields and Create puts that many artboards in each column. + #[test] + fn a_presets_rows_reach_the_document_create_makes() { + let mut app = app(); + open(&mut app); + set(&app, "artboards", json!(5)).unwrap(); + set(&app, "artboardLayout", json!({"layout": "gridByColumn", "rows": 3.6, "spacing": 10})).unwrap(); + assert_eq!(fields(&app)["artboardLayout"]["rows"], json!(4)); + create(&mut app); + let st = app.session.active().unwrap(); + assert_eq!(st.doc.artboards.len(), 5); + let first: Vec<_> = st.doc.artboards.iter().filter(|a| a.rect.x0 == 0.0).map(|a| a.rect.y0).collect(); + assert_eq!(first.len(), 4, "four artboards in the first column: {first:?}"); + } + /// Align New Objects to Pixel Grid reaches a saved preset and the document Create makes. #[test] fn align_new_objects_checkbox_follows_the_preset_and_reaches_the_document() { diff --git a/crates/ui-egui/src/dialogs/path_ops.rs b/crates/ui-egui/src/dialogs/path_ops.rs index a17ddcb027..72fb260ee2 100644 --- a/crates/ui-egui/src/dialogs/path_ops.rs +++ b/crates/ui-egui/src/dialogs/path_ops.rs @@ -7,6 +7,7 @@ // runtime; the form-dialog items live under `patterns::form_dialogs`; `Field` and `NumberField` under craft-ui-widgets). use craft::ui::contract::{Bind, FieldLabelRole, Show as _, ShowContainer as _, SideLabel}; use craft::ui::dialog::DialogId; +use craft::ui::display::Text; use craft::ui::form::Field; use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind}; use craft::ui::runtime::env::{LengthUnits, UnitKind}; @@ -286,7 +287,7 @@ fn counts_row(ui: &mut egui::Ui, f: &DialogFields) { if let Some(FieldValue::Json(c)) = f.get(COUNTS) && let (Some(before), Some(after)) = (c["before"].as_u64(), c["after"].as_u64()) { - ui.label(format!("{} {before} → {after}", crate::i18n::colon(tl!("Anchor Points")))); + Text::new(format!("{} {before} → {after}", crate::i18n::colon(tl!("Anchor Points")))).show(ui); } } diff --git a/crates/ui-egui/src/dialogs/pdf_presets.rs b/crates/ui-egui/src/dialogs/pdf_presets.rs index a097f11537..e0e68d0eda 100644 --- a/crates/ui-egui/src/dialogs/pdf_presets.rs +++ b/crates/ui-egui/src/dialogs/pdf_presets.rs @@ -105,10 +105,7 @@ fn run(app: &mut VectorcraftApp, event: &ManagerEvent, current: &str) -> Result< Ok(app.session.pdf_presets().get(above).map(|p| p.name.clone())) } ManagerAction::Import => preset_manager::import(app, KEY, "pdf.preset.import", "PDF presets", PRESET_EXTS), - ManagerAction::Export => { - crate::io::save_command_output(app, "pdf.preset.export", PRESET_FORMAT, json!({ "names": [current] }), |_, _| Ok(Value::Null))?; - Ok(None) - } + ManagerAction::Export => preset_manager::export(app, "pdf.preset.export", PRESET_FORMAT, current), } } @@ -234,6 +231,8 @@ mod tests { app.run("pdf.preset.save", json!({"name": "Mine", "thumbnails": true})).unwrap(); open(&mut app, Some("Mine")); press(&mut app, ManagerAction::Export); + // The save panel suggests the preset's name. + assert_eq!(picker.requests().last().and_then(|r| r.file_name.clone()).as_deref(), Some("Mine.vcpdfpresets")); picker.answer_saved(&file, None); let ctx = ctx(&app); crate::tests_picks::poll(&mut app, &ctx); diff --git a/crates/ui-egui/src/dialogs/perspective_presets.rs b/crates/ui-egui/src/dialogs/perspective_presets.rs index c6d7ecb778..9d3f81d15d 100644 --- a/crates/ui-egui/src/dialogs/perspective_presets.rs +++ b/crates/ui-egui/src/dialogs/perspective_presets.rs @@ -307,7 +307,7 @@ pub(super) fn run(app: &mut VectorcraftApp, act: Action, current: &str) -> Resul }); } Action::Export => { - crate::io::save_command_output(app, "perspective.presets.export", PRESET_FORMAT, json!({ "names": [current] }), |_, _| Ok(Value::Null))?; + super::preset_manager::export(app, "perspective.presets.export", PRESET_FORMAT, current)?; } } Ok(()) diff --git a/crates/ui-egui/src/dialogs/plugin.rs b/crates/ui-egui/src/dialogs/plugin.rs index ff52df3db8..94b82a5259 100644 --- a/crates/ui-egui/src/dialogs/plugin.rs +++ b/crates/ui-egui/src/dialogs/plugin.rs @@ -12,6 +12,9 @@ //! filter or live effect with commands of its own is a submenu named after it, holding its item and //! then its commands; a command with parameters opens the same dialog for them ([`open_command`]). //! A command whose manifest names another menu is listed in that menu instead ([`place_commands`]). +//! Object › Plug-ins starts with Apply Last Filter and Last Filter…, which run the filter that last +//! ran again with the same parameters or open its dialog with them, and a filter's dialog opens with +//! the parameters it last ran with in the session ([`LastFilters`]). //! Exporters are formats of File › Export › Export As; one with parameters opens dialog //! `pluginExport` once the file is picked, and its Export button writes the file. Importers open the //! files File › Open finds no built-in format for, and File › Open With lists them; one with @@ -335,14 +338,20 @@ fn build(key: &'static str, m: Manifest, all: Arc<[Param]>, look: Look) -> impl } } -/// Opens the hosted dialog `key` for plug-in manifest `m` (an instance per `instance`), closing the -/// one open before → its id on the host and its rows. -fn open_hosted(app: &mut VectorcraftApp, key: &'static str, instance: &str, m: Manifest, look: Look) -> Result<(DialogId, Arc<[Param]>), String> { +/// Opens the hosted dialog `key` for plug-in manifest `m` (an instance per `instance`) with its rows +/// at `values`, closing the one open before → its id on the host and its rows. +fn open_hosted( + app: &mut VectorcraftApp, + key: &'static str, + instance: &str, + m: Manifest, + values: Map, + look: Look, +) -> Result<(DialogId, Arc<[Param]>), String> { let (Some(ctx), Some(dialogs)) = (app.ui_ctx.clone(), app.dialogs()) else { return Err("no window".into()) }; close_open(app); - let defaults = m.defaults(); - let all: Arc<[Param]> = form::plugin_params(&m, &defaults).into(); - let fields = form::fields_of(&all, &defaults); + let all: Arc<[Param]> = form::plugin_params(&m, &values).into(); + let fields = form::fields_of(&all, &values); let dialog = HostedParamDialog::new(&ctx, key, fields, build(key, m, Arc::clone(&all), look)).instance(instance.to_string()); let id = dialogs.with(|host| host.open(dialog)); Ok((id, all)) @@ -359,8 +368,186 @@ fn close_open(app: &mut VectorcraftApp) { } } +/// Object › Plug-ins' first items: Apply Last Filter, which runs the filter that last ran again with +/// the same parameters, and Last Filter…, which opens its dialog with them. Each is named after the +/// filter once one has run ([`last_filter_name`]). +pub fn last_filter_menu() -> Vec { + vec![c("Apply Last Filter", APPLY_LAST), c("Last Filter…", LAST), Sep] +} + +/// Apply Last Filter's command id. +pub const APPLY_LAST: &str = "plugin.applyLastFilter"; + +/// Last Filter…'s command id. +pub const LAST: &str = "plugin.lastFilter"; + +/// The error of Apply Last Filter and Last Filter… when no filter can run again: none ran in this +/// session, or the one that ran last was removed or installed again, or its parameters no longer fit it. +pub const NO_LAST_FILTER: &str = "no plug-in filter to repeat: run one from Object › Plug-ins first"; + +/// The most filters whose last parameters [`LastFilters`] keeps. +const MAX_REMEMBERED: usize = 64; + +/// The parameters filter `id` last ran with, as its manifest resolved them, and the installation +/// that ran with them (its [`Plugin::serial`]; installing the plug-in again gives it a new one). +#[derive(Clone, Debug, PartialEq)] +struct Used { + id: String, + serial: u64, + params: Map, +} + +/// The parameters each object filter last ran with in this session (`plugin.run`), the filter that +/// ran last at the end, for at most [`MAX_REMEMBERED`] filters. They are never saved. +#[derive(Default)] +pub struct LastFilters { + used: Vec, +} + +impl LastFilters { + /// The id of the filter that ran last, whether or not it can run again. + pub fn last_id(&self) -> Option<&str> { + self.used.last().map(|u| u.id.as_str()) + } +} + +/// Notes a `plugin.run` with params `p` that succeeded: its filter ran last, with the +/// parameters its manifest resolves from `p`. Anything else (not a filter, parameters the manifest +/// refuses) is not noted. +pub(crate) fn record(app: &mut VectorcraftApp, p: &Value) { + let Some(plugin) = p.get("id").and_then(Value::as_str).and_then(registry::get) else { return }; + let m = plugin.manifest(); + if m.kind != Kind::Filter { + return; + } + let Ok(params) = m.resolve_params(&vectorcraft_engine::cmd::plugin::plugin_params(p)) else { return }; + let used = &mut app.last_filters.used; + used.retain(|u| u.id != m.id); + used.push(Used { id: m.id.clone(), serial: plugin.serial(), params }); + if used.len() > MAX_REMEMBERED { + used.remove(0); + } +} + +/// The plug-in registry's revision before a command runs, for [`after_command`]. +pub(crate) fn before_command() -> u64 { + registry::revision() +} + +/// After command `id` with `params` ran with result `r`, the registry at revision `before` when it +/// started: a `plugin.run` that succeeded, or each `plugin.run` step of a batch that succeeded +/// (`command.batch`, or `action.batch` on at least one file or data set) in the order they ran, is +/// noted ([`record`]), so the last one is the filter that ran last. +pub(crate) fn after_command(app: &mut VectorcraftApp, id: &str, params: &Value, r: &Result, before: u64) { + let Ok(reply) = r else { return }; + // Action Batch returns success even when files or data sets fail, and runs every step on each + // one that doesn't. + let played = |v: &Value| v.get("count").and_then(Value::as_u64).unwrap_or(0) > v.get("failed").and_then(Value::as_u64).unwrap_or(0); + match id { + CMD => record(app, params), + "command.batch" | "action.batch" if id == "command.batch" || played(reply) => { + let steps = params.get("commands").and_then(Value::as_array).map(Vec::as_slice).unwrap_or_default(); + // `command.batch` returns each step's result; Action Batch returns none. + let results = reply.get("results").and_then(Value::as_array); + // Every filter step is noted in the order the steps ran, so the last one is the filter + // that ran last and a filter that ran twice keeps its newest parameters. + for (at, s) in steps.iter().enumerate().filter(|(_, s)| step_id(s) == Some(CMD)) { + let p = s.get("params").unwrap_or(&Value::Null); + let ran = p.get("id").and_then(Value::as_str).unwrap_or_default(); + // The plug-in installed under the id now is the one that ran when no later step may + // have changed it, or when it was installed before the batch (installing gives a new + // serial). + let changed_later = (at + 1..steps.len()).any(|i| may_change(&steps[i], results.and_then(|r| r.get(i)), ran)); + let installed_before = registry::get(ran).is_some_and(|q| q.serial() <= before); + match changed_later && !installed_before { + true => forget(app, p), + false => record(app, p), + } + } + } + _ => {} + } +} + +/// The command id of batch step `s`. +fn step_id(s: &Value) -> Option<&str> { + s.get("command").and_then(Value::as_str) +} + +/// Whether batch step `s`, which returned `result` if the batch reports it, may have installed, +/// removed or reloaded plug-in `id`: a removal names its id, an install reports the id it installed, +/// and a reload, or an install whose result is not known, may change any plug-in. +fn may_change(s: &Value, result: Option<&Value>, id: &str) -> bool { + match step_id(s) { + Some("plugin.remove") => s.get("params").and_then(|p| p.get("id")).and_then(Value::as_str) == Some(id), + Some("plugin.install") => result.and_then(|r| r.get("id")).and_then(Value::as_str).is_none_or(|i| i == id), + Some("plugin.reload") => true, + _ => false, + } +} + +/// Notes the filter `plugin.run` params `p` name as the one that ran last, without parameters or a +/// module, so that Apply Last Filter and Last Filter… stay off until a filter runs again. +fn forget(app: &mut VectorcraftApp, p: &Value) { + let Some(id) = p.get("id").and_then(Value::as_str) else { return }; + let used = &mut app.last_filters.used; + used.retain(|u| u.id != id); + // Serial 0 belongs to no installed plug-in. + used.push(Used { id: id.to_string(), serial: 0, params: Map::new() }); + if used.len() > MAX_REMEMBERED { + used.remove(0); + } +} + +/// Filter `id`'s last parameters, while the installation that ran with them is still installed under +/// its id and its manifest takes them as they are. +fn remembered(app: &VectorcraftApp, id: &str) -> Option<(Arc, Map)> { + let used = app.last_filters.used.iter().find(|u| u.id == id)?; + let plugin = registry::get(id).filter(|p| p.manifest().kind == Kind::Filter && p.serial() == used.serial)?; + let params = Value::Object(used.params.clone()); + plugin.manifest().resolve_params(¶ms).ok().filter(|r| *r == used.params)?; + Some((plugin, used.params.clone())) +} + +/// The filter that ran last and its parameters, while it can run again with them ([`remembered`]). +pub(crate) fn last_filter(app: &VectorcraftApp) -> Option<(Arc, Map)> { + remembered(app, app.last_filters.last_id()?) +} + +/// The name Apply Last Filter and Last Filter… show once a filter ran that can run again +/// ([`last_filter`]): the filter's own name, without an ellipsis at its end and with hidden +/// characters shown as escapes, as a submenu named after a plug-in shows it. `None` before. +pub(crate) fn last_filter_name(app: &VectorcraftApp) -> Option { + let (plugin, _) = last_filter(app)?; + let name = plugin.manifest().name.trim().trim_end_matches('…').trim_end().to_string(); + Some(permissions::display_text(&name, permissions::MAX_SHOWN_NAME)) +} + +/// `plugin.applyLastFilter`: runs the filter that ran last again, with the same parameters, on the +/// selection, without its dialog, as its menu item runs it ([`run`]). +pub fn apply_last(app: &mut VectorcraftApp) -> Result { + app.session.active().ok_or("no document open")?; + let (plugin, params) = last_filter(app).ok_or(NO_LAST_FILTER)?; + let p = json!({"id": plugin.id(), "params": params}); + run(app, &plugin, p) +} + +/// `plugin.lastFilter`: opens the dialog of the filter that ran last with the parameters it ran +/// with; one without parameters runs at once, as its menu item runs it. +pub fn open_last(app: &mut VectorcraftApp) -> Result { + app.session.active().ok_or("no document open")?; + let (plugin, params) = last_filter(app).ok_or(NO_LAST_FILTER)?; + if plugin.manifest().params.is_empty() { + return run(app, &plugin, json!({"id": plugin.id(), "params": params})); + } + let m = plugin.manifest(); + open_filter(app, &plugin, m.clone(), None, m.name.trim_end_matches('…').to_string(), params)?; + Ok(Value::Null) +} + /// `plugin.dialog {id, params?}`: run filter `id` at once when it takes no parameters or `params` -/// are given, else open its dialog prefilled with its defaults. +/// are given, else open its dialog prefilled with the parameters it last ran with in this session +/// ([`remembered`]), or with its defaults. pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { let id = p.get("id").and_then(Value::as_str).ok_or("missing `id` (see plugin.list)")?; let plugin = registry::get(id).ok_or_else(|| format!("no plug-in {id:?} is installed"))?; @@ -375,18 +562,26 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { if m.params.is_empty() || given.is_some() { return run(app, &plugin, json!({"id": id, "params": given.cloned().unwrap_or(Value::Null)})); } - open_filter(app, &plugin, m.clone(), None, m.name.trim_end_matches('…').to_string())?; + let values = remembered(app, id).map(|(_, params)| params).unwrap_or_else(|| m.defaults()); + open_filter(app, &plugin, m.clone(), None, m.name.trim_end_matches('…').to_string(), values)?; Ok(Value::Null) } /// Opens the dialog of filter `plugin`, or of its command `command`, with `m` the manifest it runs -/// with, headed `heading`: the rows at their defaults, with a live Preview for a light filter. -fn open_filter(app: &mut VectorcraftApp, plugin: &Plugin, m: Manifest, command: Option, heading: String) -> Result<(), String> { +/// with, headed `heading`: the rows at `values`, with a live Preview for a light filter. +fn open_filter( + app: &mut VectorcraftApp, + plugin: &Plugin, + m: Manifest, + command: Option, + heading: String, + values: Map, +) -> Result<(), String> { let own = plugin.manifest(); let light = own.budget == Budget::Light; let look = Look { title: heading.clone(), description: own.description.clone(), previews: light, note: !light, ok: None }; let instance = command.as_deref().unwrap_or(plugin.id()).to_string(); - let (id, params) = open_hosted(app, KIND, &instance, m, look)?; + let (id, params) = open_hosted(app, KIND, &instance, m, values, look)?; let kind = Opened::Filter { plugin: plugin.id().to_string(), command, @@ -409,7 +604,9 @@ pub fn open_command(app: &mut VectorcraftApp, id: &str) -> bool { if c.params.is_empty() || app.session.active().is_none() { return false; } - if let Err(e) = open_filter(app, &plugin, plugin.manifest().for_command(&c), Some(id.to_string()), c.shown_label().to_string()) { + let m = plugin.manifest().for_command(&c); + let defaults = m.defaults(); + if let Err(e) = open_filter(app, &plugin, m, Some(id.to_string()), c.shown_label().to_string(), defaults) { app.status(e); } true @@ -457,7 +654,7 @@ pub fn open_export(app: &mut VectorcraftApp, plugin: &Plugin, export: Value) { note: false, ok: Some(tl!("Export")), }; - match open_hosted(app, EXPORT_KIND, plugin.id(), m.clone(), look) { + match open_hosted(app, EXPORT_KIND, plugin.id(), m.clone(), m.defaults(), look) { Ok((id, params)) => app.plugin_dialog = Some(PluginDialog { id, kind: Opened::Export { plugin: plugin.id().to_string(), export, params } }), Err(e) => app.status(e), } @@ -475,7 +672,7 @@ pub fn open_import(app: &mut VectorcraftApp, plugin: &Plugin, open: Value) { note: false, ok: Some(tl!("Open")), }; - match open_hosted(app, IMPORT_KIND, plugin.id(), m.clone(), look) { + match open_hosted(app, IMPORT_KIND, plugin.id(), m.clone(), m.defaults(), look) { Ok((id, params)) => app.plugin_dialog = Some(PluginDialog { id, kind: Opened::Import { plugin: plugin.id().to_string(), open, params } }), Err(e) => app.status(e), } @@ -511,7 +708,15 @@ fn confirm_filter(app: &mut VectorcraftApp, kind: Opened, values: Map preview.commit(app, &cmd, p), + _ => { + let r = preview.commit(app, &cmd, p.clone()); + // A kept preview commits without running `plugin.run` again ([`after_command`]); for + // the filter's own run, `p` is `plugin.run`'s `{id, params}`. + if r.is_ok() && own.is_none() { + record(app, &p); + } + r + } } } diff --git a/crates/ui-egui/src/dialogs/png_options.rs b/crates/ui-egui/src/dialogs/png_options.rs index 8bf05fe7d8..954aaac274 100644 --- a/crates/ui-egui/src/dialogs/png_options.rs +++ b/crates/ui-egui/src/dialogs/png_options.rs @@ -248,7 +248,7 @@ fn resolution_row() -> Param { fn size_row(w: f64, h: f64) -> Param { Param::custom("__sizeText", tl!("Size:"), move |ui, fields, _| { let (pw, ph) = vectorcraft_render::region_pixels(vectorcraft_geom::Rect::new(0.0, 0.0, w, h), fields.number("ppi").unwrap_or(72.0) / 72.0); - ui.label(format!("{pw} × {ph} px")) + Text::new(format!("{pw} × {ph} px")).show(ui) }) } diff --git a/crates/ui-egui/src/dialogs/preset_manager.rs b/crates/ui-egui/src/dialogs/preset_manager.rs index 1ec0cead83..319d3a49b3 100644 --- a/crates/ui-egui/src/dialogs/preset_manager.rs +++ b/crates/ui-egui/src/dialogs/preset_manager.rs @@ -183,6 +183,23 @@ pub(crate) fn import( Ok(None) } +/// Export…: run `command` on the preset `name` and write its file through a save panel that suggests +/// [`export_file_name`] (the web downloads it under that name). Returns at once: the answer arrives later. +pub(crate) fn export(app: &mut VectorcraftApp, command: &str, ext: &str, name: &str) -> Result, String> { + let file = export_file_name(name, ext); + crate::io::save_command_output_named(app, command, &file, serde_json::json!({ "names": [name] }), |_, _| Ok(Value::Null))?; + Ok(None) +} + +/// The file name Export… suggests for the preset `name`: the name without a built-in preset's brackets +/// (`[Default]`), made safe as a file name as Export Library… makes a library's +/// (`library::file_stem_for`), with the extension `ext`; "Preset" when no name is left. +pub(crate) fn export_file_name(name: &str, ext: &str) -> String { + let stem = name.trim().trim_start_matches('[').trim_end_matches(']').trim(); + let stem = if stem.is_empty() { "Preset" } else { stem }; + format!("{}.{ext}", vectorcraft_engine::cmd::library::file_stem_for(stem)) +} + /// Opens the manager of `source` on the preset `selected` (the first one when none has that name). pub(crate) fn open(app: &mut VectorcraftApp, source: &'static Source, selected: &str) { let rows = (source.rows)(app); diff --git a/crates/ui-egui/src/dialogs/preview.rs b/crates/ui-egui/src/dialogs/preview.rs index 2ef2bd99e7..c65dc15f45 100644 --- a/crates/ui-egui/src/dialogs/preview.rs +++ b/crates/ui-egui/src/dialogs/preview.rs @@ -48,8 +48,8 @@ impl LivePreview { Some(answer) } - /// OK: keeps the previewed `cmd` as one undo step (or runs it when no preview runs); the command's warning shows - /// in the status bar either way. On an error the dialog stays open. + /// OK: keeps the previewed `cmd` as one undo step (or runs it when no preview runs); the command's warning, or a + /// plug-in run's notice, shows in the status bar either way. On an error the dialog stays open. pub(crate) fn commit(self, app: &mut VectorcraftApp, cmd: &str, params: Value) -> Result { if !app.session.in_interaction() { return app.run(cmd, params); @@ -61,6 +61,9 @@ impl LivePreview { { app.status(w.to_string()); } + if r.is_ok() { + crate::plugin_runs::show_notice(app, cmd, &v); + } r } diff --git a/crates/ui-egui/src/dialogs/print.rs b/crates/ui-egui/src/dialogs/print.rs index 255495d286..e911e7c0a2 100644 --- a/crates/ui-egui/src/dialogs/print.rs +++ b/crates/ui-egui/src/dialogs/print.rs @@ -35,7 +35,7 @@ use craft::ui::pickers::{Anchor9, ReferencePoint, ReferencePointLook}; use craft::ui::primitives::IconSpec; use craft::ui::runtime::env::{LengthUnits, UnitKind}; use craft::ui::shell::WindowDialogs; -use craft::ui::text::{LinkMode, LinkedFields, NumberField}; +use craft::ui::text::{LinkMode, LinkedFields, NumberField, SelectableText}; use serde_json::{Map, Value, json}; use vectorcraft_color::cms::Intent; use vectorcraft_engine::cmd::printpresets::DEFAULT_PRESET; @@ -669,9 +669,9 @@ fn scaling_ids(tiles: bool) -> Vec<&'static str> { PrintScaling::ALL.iter().filter(|s| s.tiles() == tiles).map(|s| s.id()).collect() } -/// A summary line that the pump fills (`key` is a `__` companion of the fields). -fn shown(key: &'static str) -> Param { - Param::custom(key, "", move |ui, fields, _| ui.label(fields.text(key).unwrap_or_default())) +/// A summary line that the pump fills (`key` is a `__` companion of the fields), selectable and named `label`. +fn shown(key: &'static str, label: &'static str) -> Param { + Param::custom(key, "", move |ui, fields, _| SelectableText::new(label, fields.text(key).unwrap_or_default()).multiline().show(ui)) } /// The sections of the dialog, with the rows of each. @@ -827,11 +827,11 @@ fn sections(lists: &Lists) -> Vec { ]; let summary = vec![ Param::section(tl!("Pages")), - shown("__summary.pages"), + shown("__summary.pages", tl!("Pages")), Param::section(tl!("Options")), - shown("__summary.options"), + shown("__summary.options", tl!("Options")), Param::section(tl!("Warnings")), - shown("__summary.warnings"), + shown("__summary.warnings", tl!("Warnings")), ]; [general, marks, output, graphics, color, advanced, summary] .into_iter() diff --git a/crates/ui-egui/src/dialogs/print_presets.rs b/crates/ui-egui/src/dialogs/print_presets.rs index e69e7f5e7e..fc5e1b1d0b 100644 --- a/crates/ui-egui/src/dialogs/print_presets.rs +++ b/crates/ui-egui/src/dialogs/print_presets.rs @@ -77,9 +77,6 @@ fn run(app: &mut VectorcraftApp, event: &ManagerEvent, current: &str) -> Result< Ok(rows(app).get(preset_manager::above(i, 1)).map(|row| row.name.clone())) } ManagerAction::Import => preset_manager::import(app, KEY, "print.presets.import", "Print presets", PRESET_EXTS), - ManagerAction::Export => { - crate::io::save_command_output(app, "print.presets.export", PRESET_FORMAT, json!({ "names": [current] }), |_, _| Ok(Value::Null))?; - Ok(None) - } + ManagerAction::Export => preset_manager::export(app, "print.presets.export", PRESET_FORMAT, current), } } diff --git a/crates/ui-egui/src/dialogs/recolor.rs b/crates/ui-egui/src/dialogs/recolor.rs index 9d2ca82832..c219fe1eed 100644 --- a/crates/ui-egui/src/dialogs/recolor.rs +++ b/crates/ui-egui/src/dialogs/recolor.rs @@ -262,16 +262,45 @@ pub(crate) struct Open { pub preview: LivePreview, } -/// Open Recolor Artwork (`ui.recolorDialog {colors?, library?, group?}`) on the selected art and, -/// with `group`, on that colour group: art is reduced to as many rows as the group has colours, -/// which become their new colours; without art the rows are the group's colours. `colors` is a -/// count (an n-colour job) or the new colours to assign (without art or a group they are the +/// Open Recolor Artwork (`ui.recolorDialog {colors?, library?, group?, preset?}`) on the selected +/// art and, with `group`, on that colour group: art is reduced to as many rows as the group has +/// colours, which become their new colours; without art the rows are the group's colours. `colors` +/// is a count (an n-colour job) or the new colours to assign (without art or a group they are the /// rows, which OK saves as a new colour group); `library` limits to a library or "document" ("" -/// picks the first library). +/// picks the first library). With `preset: true` the Recolor with Preset dialog opens first. pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { + match p.get("preset") { + None | Some(Value::Bool(false)) => {} + Some(Value::Bool(true)) => return super::recolor_preset::open(app, p), + Some(_) => return Err("`preset` must be true or false".into()), + } let st = app.session.active().ok_or("no document open")?; let art = !st.selection.is_empty(); - let group = p.get("group").and_then(Value::as_str); + let group = match p.get("group") { + None | Some(Value::Null) => None, + Some(Value::String(g)) => Some(g.as_str()), + Some(_) => return Err("`group` must be a colour group name".into()), + }; + // The group is looked for in the document without the preview of a Recolor Artwork this one + // replaces (which can rename the group), as that dialog's rollback below leaves it. + let unpreviewed = match &st.interaction { + Some(it) if app.color_dialogs.recolor.is_some() => &it.doc, + _ => &st.doc, + }; + if let Some(g) = group + && !unpreviewed.swatch_groups.iter().any(|x| x.name == g) + { + return Err(format!("no colour group `{g}`")); + } + // Colours alone (no art, no group) become a new colour group. + let new_group = !art && group.is_none(); + if new_group && !matches!(p.get("colors"), Some(Value::Array(cs)) if cs.iter().any(|c| color_value(c).is_some())) { + return Err("select artwork (or a colour group) to recolor".into()); + } + let limit = library_param(app, p)?; + // A Recolor Artwork still open is replaced: its preview goes before the group's colours are read. + cancel_open(app); + let st = app.session.active().ok_or("no document open")?; let group_colors: Option> = match group { Some(g) => { let g = st.doc.swatch_groups.iter().find(|x| x.name == g).ok_or_else(|| format!("no colour group `{g}`"))?; @@ -284,21 +313,11 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { (None, Some(Value::Array(cs))) => cs.iter().filter_map(color_value).map(|c| key(&c)).collect(), _ => vec![], }; - // Colours alone (no art, no group) become a new colour group. - let new_group = !art && group.is_none(); - if new_group && assign.is_empty() { - return Err("select artwork (or a colour group) to recolor".into()); - } let count = match p.get("colors").and_then(Value::as_u64) { Some(n) => json!(n.max(1)), None if !assign.is_empty() => json!(assign.len()), None => Value::Null, }; - let limit = match p.get("library").and_then(Value::as_str) { - Some("") => first_library(app).unwrap_or_default(), - Some(l) => limit_key(app, l)?, - None => String::new(), - }; // Without art the rows are the group's colours, as they are. let mut start: Vec = if art { vec![] } else { assign.iter().map(|k| json!({"from": [k], "to": k})).collect() }; number_slots(&mut start); @@ -317,10 +336,6 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { let mut rs = rows(&d); snap(app, &d, &mut rs); d.fields.insert("rows".into(), Value::Array(rs)); - // A Recolor Artwork still open is replaced: its preview goes before this one's starts. - if let Some(old) = app.color_dialogs.recolor.take() { - old.preview.cancel(app); - } let dialog = RecolorDialog::new(app, d); let options = HeldOptions { cancel: Some(Box::new(cancelled)), ..HeldOptions::default() }; let id = open_held_with(app, dialog, confirm, options).ok_or("no window to show Recolor Artwork in")?; @@ -346,10 +361,43 @@ fn key(c: &Color) -> Value { /// The name a new colour group (opened on colours alone) starts with. const NEW_GROUP: &str = "Color Group"; +/// Ends an open Recolor Artwork as Cancel ends it: its preview is rolled back and it closes. +pub(super) fn cancel_open(app: &mut VectorcraftApp) { + let Some(old) = app.color_dialogs.recolor.take() else { return }; + let id = old.id; + old.preview.cancel(app); + if let (Some(dialogs), Some(ctx)) = (app.dialogs(), app.ui_ctx.clone()) { + dialogs.with(|host| { + host.cancel_by_id(&ctx, id); + }); + } +} + fn first_library(app: &VectorcraftApp) -> Option { colour_libraries(app).into_iter().next().map(|l| l.id) } +/// Limit to Library's choices: the key `limitTo` takes and the name the menu shows. None, the +/// document's swatches, then the colour libraries: the built-in ones translated, those the user +/// saved or loaded by their names. +pub(super) fn library_choices(app: &VectorcraftApp) -> Vec<(String, String)> { + let libs = colour_libraries(app); + let fixed = [("", tl!("None")), (swatchlib::DOCUMENT_SWATCHES, tl!(DOCUMENT_SWATCHES))].map(|(k, n)| (k.to_owned(), n.to_owned())); + let named = libs.iter().map(|l| (l.id.clone(), library_panel::library_name(&l.id, &l.name).to_owned())); + fixed.into_iter().chain(named).collect() +} + +/// The `limitTo` key of `ui.recolorDialog`'s `library`: none without it or for null, the first +/// library for ""; a `library` that is not a string is an error. +pub(super) fn library_param(app: &VectorcraftApp, p: &Value) -> Result { + match p.get("library") { + Some(Value::String(l)) if l.is_empty() => Ok(first_library(app).unwrap_or_default()), + Some(Value::String(l)) => limit_key(app, l), + None | Some(Value::Null) => Ok(String::new()), + Some(_) => Err("`library` must be a library id or name".into()), + } +} + /// `recolor.reduce` parameters (Method only picks each row's colour, so changing it keeps the rows). fn reduce_params(d: &Fields) -> Value { json!({ @@ -1441,15 +1489,11 @@ struct Feed { impl Feed { fn of(app: &VectorcraftApp, d: &Fields) -> Feed { - // None, the document's swatches, then the colour libraries: the built-in ones translated, - // those the user saved or loaded by their names. - let libs = colour_libraries(app); - let fixed = [("", tl!("None")), (swatchlib::DOCUMENT_SWATCHES, tl!(DOCUMENT_SWATCHES))].map(|(k, n)| (k.to_owned(), n.to_owned())); - let named = libs.iter().map(|l| (l.id.clone(), library_panel::library_name(&l.id, &l.name).to_owned())); - let libraries = fixed.into_iter().chain(named).collect(); + let libraries = library_choices(app); Feed { + // The colour libraries follow None and the document's swatches. + first_library: libraries.get(2).map(|(k, _)| k.clone()), libraries, - first_library: libs.first().map(|l| l.id.clone()), groups: doc_groups(app), other_paints: other_paint_groups(app), previewing: app.session.in_interaction(), diff --git a/crates/ui-egui/src/dialogs/recolor_preset.rs b/crates/ui-egui/src/dialogs/recolor_preset.rs new file mode 100644 index 0000000000..0d3020abb5 --- /dev/null +++ b/crates/ui-egui/src/dialogs/recolor_preset.rs @@ -0,0 +1,61 @@ +//! Edit → Edit Colors → Recolor with Preset: before Recolor Artwork opens on a preset (an n-color +//! job or Color Library), this dialog asks whether to limit the new colors to a swatch library +//! (`ui.recolorDialog {preset: true, colors?, library?}`, without `group`). OK opens Recolor Artwork with the +//! preset's colors and the library chosen (None: no limit); Cancel opens nothing. +//! +//! Fields: `limitTo` (a library id, `"document"` for the document's swatches, `""` for None), as +//! Recolor Artwork's. + +use craft::ui::patterns::form_dialogs::{DialogFields, Param, ParamKind, ParamResult}; +use craft::ui::runtime::env::Label; +use serde_json::{Value, json}; + +use super::recolor::{cancel_open, library_choices, library_param}; +use super::swatch_options::{NO_WINDOW, field_label, hosted}; +use crate::VectorcraftApp; + +/// The dialog kind of Recolor with Preset. +pub const KIND: &str = "recolorPreset"; + +/// Open the dialog for the preset of `p` (`colors`: a count; `library`: the library it starts on, +/// "" the first library) on the selected art. +pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { + let st = app.session.active().ok_or("no document open")?; + if st.selection.is_empty() { + return Err("select artwork to recolor".into()); + } + if p.get("group").is_some_and(|g| !g.is_null()) { + return Err("`group` does not apply to a preset".into()); + } + let colors = count(p.get("colors"))?; + let limit = library_param(app, p)?; + let ctx = app.ui_ctx.clone().ok_or(NO_WINDOW)?; + // A Recolor Artwork this one opens over ends as Cancel ends it, its preview rolled back. + cancel_open(app); + let options = library_choices(app).into_iter().map(|(key, name)| (key, Label::from(name))).collect(); + let mut fields = DialogFields::new(); + fields.set("limitTo", limit.clone()); + let rows = vec![Param::new("limitTo", field_label(tl!("Limit to Library:")), ParamKind::choice(options, Some(limit)))]; + let dialog = hosted(&ctx, KIND, tl!("Recolor with Preset"), fields, rows, false); + // Recolor Artwork takes the dialog's place; when it cannot open, this dialog stays. + let ok = move |app: &mut VectorcraftApp, answer: &ParamResult| -> Result<(), String> { + let mut p = serde_json::Map::new(); + if let Some(n) = colors { + p.insert("colors".into(), json!(n)); + } + if let Some(limit) = answer.fields.text("limitTo").filter(|l| !l.is_empty()) { + p.insert("library".into(), json!(limit)); + } + super::recolor::open(app, &Value::Object(p)).map(|_| ()) + }; + super::host::open_held(app, dialog, ok).ok_or(NO_WINDOW)?; + Ok(Value::Null) +} + +/// The preset's count of new colors: none for Color Library, else at least 1. +fn count(v: Option<&Value>) -> Result, String> { + match v { + None | Some(Value::Null) => Ok(None), + Some(n) => n.as_u64().filter(|n| *n >= 1).map(Some).ok_or_else(|| "`colors` must be a count of at least 1".into()), + } +} diff --git a/crates/ui-egui/src/dialogs/revolve.rs b/crates/ui-egui/src/dialogs/revolve.rs index a61190970e..a20c8c720b 100644 --- a/crates/ui-egui/src/dialogs/revolve.rs +++ b/crates/ui-egui/src/dialogs/revolve.rs @@ -721,7 +721,7 @@ pub(crate) fn light_editor(_data: &Data, place: Place, classic: bool) -> Param { fields.remove("__lightPick"); set_light_value(fields, "lightColor", json!(hex)); } - ui.vertical(|ui| { + super::form::stacked(ui, fields, |ui, fields| { let mut list = explicit_lights(fields).unwrap_or_else(|| vec![light_record(fields)]); let mut index = light_index(fields, list.len()); let titles: Vec = (1..=list.len()).map(|i| format!("{} {i}", c3("Light"))).collect(); @@ -767,7 +767,6 @@ pub(crate) fn light_editor(_data: &Data, place: Place, classic: bool) -> Param { store_selected(fields, &selected); } }) - .response }) .companions(LIGHT_KEYS.iter().map(|(_, k)| *k).chain(["__light", "__lightPick"])) .on_set(set_light_field) diff --git a/crates/ui-egui/src/dialogs/revolve_lights.rs b/crates/ui-egui/src/dialogs/revolve_lights.rs index 992ccf44ae..342f032808 100644 --- a/crates/ui-egui/src/dialogs/revolve_lights.rs +++ b/crates/ui-egui/src/dialogs/revolve_lights.rs @@ -272,8 +272,8 @@ impl Component for LightSphere<'_> { /// The row's width and the height of the sphere that fits it, with its suns. fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 { - let width = cx.picture_width((24.0 + SUN + 8.0) * 2.0, f32::INFINITY); - Vec2::new(width, (radius_in(width) + SUN + 6.0) * 2.0) + // The height follows the width: a column that measures the sphere with no room measures it again at its width. + cx.picture_size((24.0 + SUN + 8.0) * 2.0, f32::INFINITY, |width| (radius_in(width) + SUN + 6.0) * 2.0) } fn sense(&self) -> Sense { diff --git a/crates/ui-egui/src/dialogs/save_for_web.rs b/crates/ui-egui/src/dialogs/save_for_web.rs index aaaf3d4e1c..0dd9edc19b 100644 --- a/crates/ui-egui/src/dialogs/save_for_web.rs +++ b/crates/ui-egui/src/dialogs/save_for_web.rs @@ -49,6 +49,19 @@ pub(crate) struct WebExport { optimized: Option, /// The engine's `colorTable` value: the edits the colour table's buttons made. table: Value, + /// The engine's settings the dialog has no option for ([`KEPT`]), as the dialog opened on them + /// or Optimize to File Size found them: the previews, Save… and the presets use them. A preset + /// picked in the dialog does not change them. + kept: Value, +} + +/// The engine's settings keys the dialog does not show; they pass through it unchanged. +const KEPT: [&str; 2] = ["transparencyDither", "transparencyDitherAmount"]; + +/// The [`KEPT`] keys of the engine's settings `s`. +fn kept_of(s: &WebSettings) -> Value { + let engine = s.to_json(); + Value::Object(KEPT.iter().filter_map(|k| engine.get(*k).map(|v| ((*k).to_string(), v.clone()))).collect()) } /// The key of the Original pane's texture in the pump's [`TextureStore`]; the panes use their index. @@ -129,11 +142,15 @@ pub(super) fn options_of(s: &WebSettings, natural: Option) -> SaveFor serde_json::from_value(v).unwrap_or_default() } -/// The engine's settings JSON for the dialog's `options`, the edited colour `table` and an optional -/// `path`: what `webExport.settings`, `document.exportForWeb` and `file.saveForWeb` read. -fn settings_of(options: &SaveForWebOptions, table: &Value, path: Option<&str>) -> Value { +/// The engine's settings JSON for the dialog's `options`, the edited colour `table`, the `kept` +/// settings the dialog does not show ([`WebExport::kept`]) and an optional `path`: what +/// `webExport.settings`, `document.exportForWeb` and `file.saveForWeb` read. +fn settings_of(options: &SaveForWebOptions, table: &Value, kept: &Value, path: Option<&str>) -> Value { let mut v = serde_json::to_value(options).unwrap_or(Value::Null); if let Some(o) = v.as_object_mut() { + if let Some(kept) = kept.as_object() { + o.extend(kept.clone()); + } let [r, g, b] = options.matte; o.insert("matte".into(), json!(format!("#{r:02x}{g:02x}{b:02x}"))); o.remove("colorTable"); @@ -170,7 +187,7 @@ pub fn open(app: &mut VectorcraftApp) -> Result { let host = app.dialogs().ok_or("no window")?; let ctx = app.ui_ctx.clone().ok_or("no window")?; let s = remembered(app); - app.web_export = WebExport { table: serde_json::to_value(&s.color_table).unwrap_or_default(), ..WebExport::default() }; + app.web_export = WebExport { table: serde_json::to_value(&s.color_table).unwrap_or_default(), kept: kept_of(&s), ..WebExport::default() }; let (name, artboards, slices) = { let st = app.session.active().ok_or("no document")?; let slices: Vec = st @@ -472,7 +489,7 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { on_dialog(&host, |d| d.answer_optimize(answer.map_err(Into::into))); } if asked.browser { - let p = settings_of(&asked.options, &app.web_export.table, None); + let p = settings_of(&asked.options, &app.web_export.table, &app.web_export.kept, None); if let Err(e) = browser_preview(app, &p) { app.status(e); } @@ -488,11 +505,11 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { /// The encodes the dialog wants, as pictures, and the Original pane's picture when the rendering is new. fn answer_variants(app: &mut VectorcraftApp, ctx: &egui::Context, host: &craft::ui::shell::WindowDialogs, wanted: &[WantedVariant]) { - let table = app.web_export.table.clone(); + let (table, kept) = (app.web_export.table.clone(), app.web_export.kept.clone()); let mut answers = Vec::with_capacity(wanted.len()); for w in wanted { let (index, revision) = (w.index, w.request.revision); - let settings = app.session.web_settings(&settings_of(&w.request.options, &table, None)); + let settings = app.session.web_settings(&settings_of(&w.request.options, &table, &kept, None)); let rendered = settings.and_then(|s| render_for(app, &s).map(|(key, r)| (s, key, r))); answers.push(match (rendered, app.session.active()) { (Ok((s, key, r)), Some(st)) => optimise(ctx, &st.doc, &r, &key, &s, w), @@ -532,7 +549,7 @@ fn edit_table(app: &mut VectorcraftApp, ctx: &egui::Context, host: &craft::ui::s /// The source colours of the palette the dialog's settings `options` show, with the table as it stands. fn shown_colors(app: &mut VectorcraftApp, options: &SaveForWebOptions) -> Result, String> { - let settings = app.session.web_settings(&settings_of(options, &app.web_export.table, None))?; + let settings = app.session.web_settings(&settings_of(options, &app.web_export.table, &app.web_export.kept, None))?; Ok(encoded(app, &settings)?.colors.iter().map(|c| c.source).collect()) } @@ -565,7 +582,7 @@ fn store_presets(app: &mut VectorcraftApp, events: Vec) { for event in events { let r = match event { WebPresetEvent::Saved(p) => { - let mut v = settings_of(&p.options, &app.web_export.table, None); + let mut v = settings_of(&p.options, &app.web_export.table, &app.web_export.kept, None); v["name"] = json!(p.name); app.run("webExport.presets.save", v) } @@ -596,7 +613,7 @@ fn has_slices(app: &VectorcraftApp) -> bool { /// The `webExport.optimizeToFileSize` params: `options`, the desired size and, with slices, what it covers. fn optimize_params(app: &VectorcraftApp, options: &SaveForWebOptions, desired_k: f64, start: Option<&str>, scope: &str) -> Value { - let mut p = settings_of(options, &app.web_export.table, None); + let mut p = settings_of(options, &app.web_export.table, &app.web_export.kept, None); if let Some(o) = p.as_object_mut() { o.insert("desiredK".into(), json!(desired_k)); if let Some(start) = start { @@ -617,7 +634,7 @@ fn optimize_start(app: &mut VectorcraftApp, options: &SaveForWebOptions) -> Opti let r = app.run("webExport.optimizeToFileSize", p).ok()?; return r["achieved"].as_bool().filter(|a| *a).and_then(|_| r["bytes"].as_u64()); } - let s = app.session.web_settings(&settings_of(options, &app.web_export.table, None)).ok()?; + let s = app.session.web_settings(&settings_of(options, &app.web_export.table, &app.web_export.kept, None)).ok()?; encoded(app, &s).ok().map(|o| o.bytes.len() as u64) } @@ -637,6 +654,7 @@ fn run_optimize(app: &mut VectorcraftApp, req: &OptimizeRequest) -> Result Result s, Err(e) => { on_dialog(host, HostedSaveForWeb::cancel_requests); @@ -698,8 +716,9 @@ fn answer_path(app: &VectorcraftApp, id: DialogId, key: &str, path: PathBuf) { /// written. Failures show in the status line; the dialog has closed. fn finish(app: &mut VectorcraftApp, result: SaveForWebResult) { let table = std::mem::take(&mut app.web_export.table); + let kept = std::mem::take(&mut app.web_export.kept); app.web_export = WebExport::default(); - let params = settings_of(&result.options, &table, None); + let params = settings_of(&result.options, &table, &kept, None); if let Err(e) = app.run("webExport.settings", params.clone()) { return app.status(e); } diff --git a/crates/ui-egui/src/dialogs/save_for_web/tests.rs b/crates/ui-egui/src/dialogs/save_for_web/tests.rs index 400e43fe82..85cba5810d 100644 --- a/crates/ui-egui/src/dialogs/save_for_web/tests.rs +++ b/crates/ui-egui/src/dialogs/save_for_web/tests.rs @@ -312,6 +312,31 @@ fn save_remembers_and_writes_and_done_only_remembers() { assert!(!dir.join("Untitled-1.png").exists()); } +/// The remembered Transparency Dither, which the dialog does not show, reaches the file Save writes +/// and stays remembered after Done. +#[test] +fn save_keeps_the_remembered_transparency_dither() { + let dir = vectorcraft_testkit::temp_dir("sfw-tdither"); + let (mut app, _) = app(&dir, false); + let mut written = vec![]; + for method in ["none", "noise"] { + app.run("webExport.settings", json!({"format": "gif", "transparency": true, "transparencyDither": method})).unwrap(); + app.run("file.saveForWeb", json!({})).unwrap(); + save(&mut app); + let path = dir.join("Untitled-1.gif"); + written.push(std::fs::read(&path).unwrap()); + std::fs::remove_file(&path).unwrap(); + assert_eq!(app.session.last_web_settings().transparency_dither.id(), method, "remembered"); + let expected = app.session.execute("document.exportForWeb", &json!({"format": "gif", "transparencyDither": method})).unwrap(); + assert_eq!(expected["files"][0]["dataBase64"].as_str().and_then(vectorcraft_format::base64_decode).as_ref(), written.last()); + } + assert_ne!(written[0], written[1], "the partly transparent edge is dithered"); + app.run("file.saveForWeb", json!({})).unwrap(); + set(&mut app, "choice", json!("done")); + confirm(&mut app); + assert_eq!(app.session.last_web_settings().transparency_dither.id(), "noise"); +} + #[test] fn html_output_with_slices_saves_the_page_and_images() { let dir = vectorcraft_testkit::temp_dir("sfw-html"); diff --git a/crates/ui-egui/src/dialogs/save_options.rs b/crates/ui-egui/src/dialogs/save_options.rs index b65a1f40cb..5713d3d27e 100644 --- a/crates/ui-egui/src/dialogs/save_options.rs +++ b/crates/ui-egui/src/dialogs/save_options.rs @@ -36,6 +36,7 @@ use vectorcraft_eps::{Level, Overprint, Preview}; use craft::theme::variant::Tone; use craft::ui::buttons::Button; use craft::ui::contract::{Bind, CollectionEvent, Show as _, ShowCollection as _, ShowContainer as _, TooltipSpec}; +use craft::ui::display::Text; use craft::ui::layout_components::{Row, Stack}; use craft::ui::list::{ThumbAspect, ToggleState}; use craft::ui::notices::Notice; @@ -404,7 +405,7 @@ fn boards_picker(ui: &mut egui::Ui, fields: &mut DialogFields, menus: &Menus) -> .show(ui, |ui, _| { // Each run of the body starts from the checks as they stood: a check flips them, and the body may run twice. boards.clone_from(&before); - ui.label(tl!("A legacy .ai file holds one artboard: each artboard you check is saved as a separate file.")); + Notice::new(Tone::Info, tl!("A legacy .ai file holds one artboard: each artboard you check is saved as a separate file.")).show(ui); Row::new().show(ui, |ui, _| { if Button::new(tl!("Select All")).show(ui).clicks > 0 { boards.iter_mut().for_each(|b| *b = true); @@ -414,7 +415,7 @@ fn boards_picker(ui: &mut egui::Ui, fields: &mut DialogFields, menus: &Menus) -> } let checked = boards.iter().filter(|b| **b).count(); let (count, total) = (checked.to_string(), n.to_string()); - ui.label(crate::i18n::fmt(tl!("{count} of {total} artboards"), &[("count", &count), ("total", &total)])); + Text::new(crate::i18n::fmt(tl!("{count} of {total} artboards"), &[("count", &count), ("total", &total)])).show(ui); }); if !boards.iter().any(|b| *b) { Notice::new(Tone::Warn, tl!("Check an artboard to save.")).show(ui); diff --git a/crates/ui-egui/src/dialogs/save_options/tests.rs b/crates/ui-egui/src/dialogs/save_options/tests.rs index a0e5dbbd56..8227766b4a 100644 --- a/crates/ui-egui/src/dialogs/save_options/tests.rs +++ b/crates/ui-egui/src/dialogs/save_options/tests.rs @@ -247,6 +247,29 @@ fn legacy_ai_saves_the_artboards_checked_in_its_picker() { assert_eq!(boards_in(&dialog(&mut app)), Some(vec![true, false, true, false])); } +/// The legacy picker's note and its count of checked artboards are in the window's accessibility tree, and the count +/// follows the checks. +#[test] +fn legacy_ai_names_its_note_and_artboard_count_in_the_accessibility_tree() { + let (mut app, _, _) = desktop("art.ai"); + app.run("artboard.new", json!({"x": 200, "y": 0, "width": 100, "height": 80})).unwrap(); + save_as(&mut app, "file.saveAs"); + set(&mut app, "aiVersion", json!("7")); + let labels = |app: &mut VectorcraftApp| -> Vec { + frame(app); + let ctx = app.ui_ctx.clone().unwrap(); + let out = crate::testing::part_frame(app, &ctx, egui::RawInput::default(), |app, ui| app.ui(ui)); + let nodes = out.platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default(); + nodes.iter().filter_map(|(_, node)| node.label()).map(str::to_owned).collect() + }; + let shown = labels(&mut app); + assert!(shown.iter().any(|l| l.starts_with("A legacy .ai file holds one artboard")), "{shown:?}"); + assert!(shown.iter().any(|l| l == "2 of 2 artboards"), "{shown:?}"); + set(&mut app, "boards", json!([true, false])); + let shown = labels(&mut app); + assert!(shown.iter().any(|l| l == "1 of 2 artboards") && !shown.iter().any(|l| l == "2 of 2 artboards"), "{shown:?}"); +} + #[test] fn save_a_copy_and_template_suggest_their_names() { let (mut app, written, picks) = desktop("copy.vectorcraft"); diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index 273853c045..1eeec2d52d 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -429,6 +429,53 @@ fn the_transform_effect_dialog_has_its_controls_previews_them_and_shows_them_aga assert_eq!((flag(&app, "objects"), flag(&app, "strokes")), (true, true)); } +/// The names of the sliders and number fields in the window's access tree. +fn slider_and_field_names(app: &mut VectorcraftApp) -> Vec { + let out = frame(app, vec![]); + let update = out.platform_output.accesskit_update.expect("an accessibility tree"); + update + .nodes + .iter() + .filter(|(_, node)| matches!(node.role(), Role::TextInput | Role::SpinButton | Role::Slider)) + .filter_map(|(_, node)| node.label()) + .map(str::to_owned) + .collect() +} + +/// Each Scale and Move slider and number field carries its row in its name, so the two Horizontal and two Vertical +/// labels are told apart; the visible labels only describe them. +fn assert_scale_and_move_names(names: &[String]) { + for name in ["Scale Horizontal:", "Scale Vertical:", "Move Horizontal:", "Move Vertical:"] { + let count = names.iter().filter(|n| n.as_str() == name).count(); + assert_eq!(count, 2, "a slider and a number field named {name}: {names:?}"); + } + for bare in ["Horizontal:", "Vertical:"] { + assert!(!names.iter().any(|n| n == bare), "no control named only {bare}: {names:?}"); + } +} + +/// Effect > Distort & Transform > Transform names its Scale and Move controls by their row. +#[test] +fn the_transform_effect_names_scale_and_move_controls_by_their_row() { + let mut app = app(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap(); + app.run("select.all", json!({})).unwrap(); + app.run("effect.dialog", json!({"effect": "distort.transform"})).unwrap(); + settle(&mut app); + assert_scale_and_move_names(&slider_and_field_names(&mut app)); +} + +/// Object > Transform > Transform Each shares the rows, and so the names. +#[test] +fn transform_each_names_scale_and_move_controls_by_their_row() { + let mut app = app(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 60, "height": 20})).unwrap(); + app.run("select.all", json!({})).unwrap(); + open_each(&mut app, false); + settle(&mut app); + assert_scale_and_move_names(&slider_and_field_names(&mut app)); +} + /// Transform Each opened by its menu item, on Absolute when `absolute` (as it was last confirmed). fn open_each(app: &mut VectorcraftApp, absolute: bool) { if absolute { diff --git a/crates/ui-egui/src/dialogs/tests_export.rs b/crates/ui-egui/src/dialogs/tests_export.rs index e81e7a81e4..016cf865aa 100644 --- a/crates/ui-egui/src/dialogs/tests_export.rs +++ b/crates/ui-egui/src/dialogs/tests_export.rs @@ -206,6 +206,67 @@ fn export_as_png_picks_the_file_then_shows_png_options() { assert_eq!(&written.borrow()[0].1[16..20], 120u32.to_be_bytes(), "60 pt at 144 ppi"); } +/// PNG Options' pixel size is in the window's accessibility tree, and it follows the resolution. +#[test] +fn png_options_name_the_pixel_size_in_the_accessibility_tree() { + let (mut app, _) = app(1); + app.run("file.export.png", json!({})).unwrap(); + answer_saves(&mut app); + let sizes = |app: &mut VectorcraftApp| -> Vec { + super::tests::settle(app); + let out = super::tests::frame(app, vec![]); + let nodes = out.platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default(); + nodes.iter().filter_map(|(_, node)| node.label()).filter(|label| label.ends_with(" px")).map(str::to_owned).collect() + }; + let at_72 = sizes(&mut app); + assert_eq!(at_72, ["60 × 40 px"]); + set(&mut app, "ppi", json!(144)); + assert_eq!(sizes(&mut app), ["120 × 80 px"]); +} + +/// The role and name of each node of the window's accessibility tree, in a frame drawn once the dialogs have settled. +fn access_names(app: &mut VectorcraftApp) -> Vec<(egui::accesskit::Role, String)> { + super::tests::settle(app); + let out = super::tests::frame(app, vec![]); + let nodes = out.platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default(); + nodes.iter().filter_map(|(_, node)| node.label().map(|label| (node.role(), label.to_owned()))).collect() +} + +/// The hints under Export As, DXF Options and EPS Options, the words of the DXF scale row and the HP-GL pen numbers +/// are in the window's accessibility tree, and the HP-GL pen error is announced as an alert. +#[test] +fn export_dialogs_name_their_hints_rows_and_errors_in_the_accessibility_tree() { + let names = |app: &mut VectorcraftApp| -> Vec { access_names(app).into_iter().map(|(_, name)| name).collect() }; + let (mut app, _) = app(1); + app.run("file.exportAs", json!({"format": "png", "useArtboards": false})).unwrap(); + let shown = names(&mut app); + assert!(shown.iter().any(|n| n == "The bounds of the visible art."), "{shown:?}"); + cancel(&mut app); + + crate::menus::invoke(&mut app, "ui.dxfOptionsDialog", json!({})); + let shown = names(&mut app); + for word in ["=", "Units"] { + assert!(shown.iter().any(|n| n == word), "{word} is not named in {shown:?}"); + } + assert!(shown.iter().any(|n| n.starts_with("Type becomes outlines")), "{shown:?}"); + cancel(&mut app); + + crate::menus::invoke(&mut app, "ui.epsOptionsDialog", json!({})); + let shown = names(&mut app); + assert!(shown.iter().any(|n| n.starts_with("Transparency is flattened with the preset.")), "{shown:?}"); + cancel(&mut app); + + app.run("ui.hpglOptionsDialog", json!({})).unwrap(); + set(&mut app, "pens", json!(["#ff0000", "#000000"])); + set(&mut app, "__penError", json!("The pens could not be listed.")); + let shown = access_names(&mut app); + assert!(shown.iter().any(|(_, n)| n == "2"), "the second pen's number is not named in {shown:?}"); + assert!( + shown.iter().any(|(role, n)| *role == egui::accesskit::Role::Alert && n.contains("The pens could not be listed.")), + "the pen error is not an alert in {shown:?}" + ); +} + /// File › Export › Export As PNG… exports the artboard in use, not the first (#5502), and each /// artboard the Artboard tool has selected, one file each. #[test] diff --git a/crates/ui-egui/src/dialogs/tests_modal.rs b/crates/ui-egui/src/dialogs/tests_modal.rs index f558c6690f..e551e71627 100644 --- a/crates/ui-egui/src/dialogs/tests_modal.rs +++ b/crates/ui-egui/src/dialogs/tests_modal.rs @@ -115,6 +115,18 @@ fn simplify_opens_a_slider_whose_drag_previews_fewer_or_more_points() { assert_eq!(anchor_count(&app), 2); } +/// The Simplify dialog's count of anchor points before and after is in the window's accessibility tree. +#[test] +fn the_simplify_dialog_names_its_anchor_point_counts() { + let mut app = app_with_dense_path(); + open_simplify_dialog(&mut app); + settle(&mut app); + let out = frame(&mut app, vec![]); + let nodes = out.platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default(); + let names: Vec<&str> = nodes.iter().filter_map(|(_, node)| node.label()).collect(); + assert!(names.iter().any(|n| n.starts_with("Anchor Points:") && n.contains('→')), "{names:?}"); +} + /// A wave of 20 anchors `width` pt wide and `width / 5` pt high, selected. fn app_with_wave(width: f64) -> VectorcraftApp { let mut app = window(VectorcraftApp::new(Session::new(), Default::default())); diff --git a/crates/ui-egui/src/dialogs/tests_perspective.rs b/crates/ui-egui/src/dialogs/tests_perspective.rs index 81ecca1d9b..775b3e1374 100644 --- a/crates/ui-egui/src/dialogs/tests_perspective.rs +++ b/crates/ui-egui/src/dialogs/tests_perspective.rs @@ -187,6 +187,23 @@ fn the_presets_manager_creates_edits_and_deletes_presets() { assert!(app.run("ui.perspectiveUserPreset3.1", json!({})).is_err()); } +/// Export… suggests the selected preset's name as the file name, a built-in one's without its brackets. +#[test] +fn the_presets_manager_exports_to_a_file_named_after_the_preset() { + use super::perspective_presets::{self, Action}; + let mut app = app(); + let picker = crate::tests_picks::scripted(&mut app); + app.run("perspective.presets.save", json!({"name": "Street"})).unwrap(); + app.run("ui.perspectivePresetsDialog", json!({"selected": "Street"})).unwrap(); + frame(&mut app); + for (preset, file) in [("Street", "Street.vcperspective"), ("[2P-High View]", "2P-High View.vcperspective")] { + perspective_presets::run(&mut app, Action::Export, preset).unwrap(); + assert_eq!(picker.requests().last().and_then(|r| r.file_name.clone()).as_deref(), Some(file), "{preset}"); + picker.cancel(); + frame(&mut app); + } +} + #[test] fn perspective_preset_menus_list_the_views_of_each_type() { let app = app(); diff --git a/crates/ui-egui/src/dialogs/tests_plugin_import.rs b/crates/ui-egui/src/dialogs/tests_plugin_import.rs index 2fad4cf5dc..7a42d96f9f 100644 --- a/crates/ui-egui/src/dialogs/tests_plugin_import.rs +++ b/crates/ui-egui/src/dialogs/tests_plugin_import.rs @@ -8,7 +8,7 @@ use serde_json::json; use vectorcraft_engine::Session; use vectorcraft_plugins::wat::{self as tpl, Given}; -use super::tests_export::{fields, frame, kind, set, try_confirm}; +use super::tests_export::{cancel, fields, frame, kind, set, try_confirm}; use super::*; use crate::Services; use crate::VectorcraftApp; @@ -237,6 +237,180 @@ fn a_dropped_file_only_an_importer_reads_opens() { app.run("plugin.remove", json!({"id": "test.ui.dropshare"})).unwrap(); } +/// A file only an importer that places its files reads, dropped on the canvas, is placed there as +/// one group by that importer, as one undo step; dropped where the platform gives no position, it +/// opens as its own document, as a vector file does. +#[test] +fn a_dropped_file_a_placing_importer_reads_is_placed_on_the_canvas() { + use crate::place::{DropSpot, DropTarget, drop_files}; + let mut app = app(); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.view_mut().unwrap().rect = egui::Rect::from_min_size(egui::pos2(0.0, 0.0), egui::vec2(800.0, 600.0)); + let on_canvas = DropSpot::Canvas(vectorcraft_geom::Point::new(400.0, 300.0)); + let manifest = tpl::importer("test.ui.dropplace", r#"["tdp"]"#, "{}").replace(r#""kind":"importer""#, r#""kind":"importer","place":true"#); + assert!(manifest.contains(r#""place":true"#), "{manifest}"); + install(&mut app, &tpl::returning(&manifest, RECT)); + + let target = app.drop_target("Drawing.tdp", on_canvas, false); + assert!(matches!(target, DropTarget::Place(_)), "{target:?}"); + assert_eq!(app.drop_target("Drawing.tdp", DropSpot::Unknown, false), DropTarget::Open); + let steps = app.session.active().unwrap().history.undo.len(); + drop_files(&mut app, vec![(target, ("Drawing.tdp".into(), None, b"?".to_vec()))]); + let st = app.session.active().unwrap(); + assert_eq!(st.history.undo.len(), steps + 1, "one undo step"); + let [id] = st.selection.objects[..] else { panic!("one placed object: {:?}", st.selection.objects) }; + let n = st.doc.node(id).unwrap(); + assert!(matches!(n.kind, vectorcraft_doc::NodeKind::Group { .. }) && n.name.as_deref() == Some("Drawing.tdp"), "{n:?}"); + + app.run("plugin.remove", json!({"id": "test.ui.dropplace"})).unwrap(); +} + +/// A text file or DXF drawing placed with the importer `importer` names goes to that importer, +/// without the text or DXF import options File › Place asks for those formats. +#[test] +fn a_named_placing_importer_skips_built_in_import_options() { + let mut app = app(); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let manifest = tpl::importer("test.ui.namedplace", r#"["txt","dxf"]"#, "{}").replace(r#""kind":"importer""#, r#""kind":"importer","place":true"#); + install(&mut app, &tpl::returning(&manifest, RECT)); + for name in ["Notes.txt", "Plan.dxf"] { + let steps = app.session.active().unwrap().history.undo.len(); + let p = json!({"name": name, "dataBase64": vectorcraft_format::base64_encode(b"0\nSECTION\n"), "importer": "plugin.test.ui.namedplace"}); + let r = app.run("file.place", p).unwrap(); + assert!(kind(&app).is_none(), "{name}: no import options dialog"); + assert_eq!(r["format"], "plugin.test.ui.namedplace", "{name}: {r}"); + assert_eq!(app.session.active().unwrap().history.undo.len(), steps + 1, "{name}"); + } + app.run("plugin.remove", json!({"id": "test.ui.namedplace"})).unwrap(); +} + +/// `file.place` with `paths`, `importer` and `params` opens the Place dialog, and its OK places the +/// files with that importer and those parameters: one file at once, several through the place +/// cursor. The files are SVG files by their extension, which the built-in reader can't read. +#[test] +fn the_place_dialog_places_paths_with_the_importer_and_params_given() { + let dir = tmp_dir("placepaths"); + let mut app = app(); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let params = r#"{"density":{"type":"number","min":0,"max":10,"default":4}}"#; + let manifest = tpl::importer("test.ui.placepaths", r#"["svg"]"#, params).replace(r#""kind":"importer""#, r#""kind":"importer","place":true"#); + install(&mut app, &tpl::when_given(&manifest, Given::Params, r#""density":7.0"#, RECT)); + let paths: Vec = ["a.svg", "b.svg"] + .iter() + .map(|n| { + let p = dir.join(n); + std::fs::write(&p, b"?").unwrap(); + p.to_string_lossy().into_owned() + }) + .collect(); + let given = + |paths: &[String]| json!({"paths": paths, "importer": "plugin.test.ui.placepaths", "params": {"density": 7}, "showImportOptions": false}); + + app.run("file.place", given(&paths[..1])).unwrap(); + assert_eq!(kind(&app).as_deref(), Some(crate::dialogs::place::KIND)); + let steps = app.session.active().unwrap().history.undo.len(); + try_confirm(&mut app).unwrap(); + assert_eq!(placed_group(&app).as_deref(), Some("a.svg"), "{}", app.ui.status); + assert_eq!(app.session.active().unwrap().history.undo.len(), steps + 1); + + app.run("file.place", given(&paths)).unwrap(); + try_confirm(&mut app).unwrap(); + assert_eq!(app.session.tool_options()["count"], 2, "{}", app.ui.status); + + app.run("plugin.remove", json!({"id": "test.ui.placepaths"})).unwrap(); +} + +/// A PDF file placed with an importer plug-in named is not read to tell whether Link would place it +/// as a document: the Place dialog counts it as a file the importer embeds. The file here doesn't +/// exist, which counts as a document when its start is read. +#[test] +fn the_place_dialog_does_not_read_a_file_a_named_importer_places() { + let dir = tmp_dir("placenamedpdf"); + let mut app = app(); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let manifest = tpl::importer("test.ui.placepdf", r#"["pdf"]"#, "{}").replace(r#""kind":"importer""#, r#""kind":"importer","place":true"#); + install(&mut app, &tpl::returning(&manifest, RECT)); + let path = dir.join("missing.pdf").to_string_lossy().into_owned(); + let counted = |app: &mut VectorcraftApp, p: serde_json::Value| { + app.run("file.place", p).unwrap(); + assert_eq!(kind(app).as_deref(), Some(crate::dialogs::place::KIND)); + let f = fields(app); + cancel(app); + (f["__documents"].clone(), f["__others"].clone()) + }; + assert_eq!(counted(&mut app, json!({"paths": [path]})), (json!(true), json!(false))); + assert_eq!(counted(&mut app, json!({"paths": [path], "importer": "plugin.test.ui.placepdf"})), (json!(false), json!(true))); + app.run("plugin.remove", json!({"id": "test.ui.placepdf"})).unwrap(); +} + +/// `file.place` with `importer` and `params` and no file asks for the files, and the Place dialog's +/// OK places the picked files with that importer and those parameters: files the picker gives by +/// their contents (the web) and by their paths. A pick without them places with neither, also while +/// a pick with them is open. +#[test] +fn a_pick_places_with_the_importer_and_params_given() { + let dir = tmp_dir("placepick"); + let mut app = app(); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let params = r#"{"density":{"type":"number","min":0,"max":10,"default":4}}"#; + let manifest = tpl::importer("test.ui.placepick", r#"["svg"]"#, params).replace(r#""kind":"importer""#, r#""kind":"importer","place":true"#); + install(&mut app, &tpl::when_given(&manifest, Given::Params, r#""density":7.0"#, RECT)); + let picker = scripted(&mut app); + let ctx = crate::testing::ui_context(); + let with = json!({"importer": "plugin.test.ui.placepick", "params": {"density": 7}, "showImportOptions": false}); + + // The web: the picker answers with the files' contents. + app.run("file.place", with.clone()).unwrap(); + picker.answer_contents(&[("a.svg", b"?")]); + poll(&mut app, &ctx); + assert_eq!(fields(&app)["files"], json!([{"name": "a.svg", "importer": "plugin.test.ui.placepick", "params": {"density": 7}}])); + let steps = app.session.active().unwrap().history.undo.len(); + try_confirm(&mut app).unwrap(); + assert_eq!(placed_group(&app).as_deref(), Some("a.svg"), "{}", app.ui.status); + assert_eq!(app.session.active().unwrap().history.undo.len(), steps + 1); + + // The desktop: the picker answers with paths. + let path = dir.join("b.svg"); + std::fs::write(&path, b"?").unwrap(); + let path = path.to_string_lossy().into_owned(); + app.run("file.place", with.clone()).unwrap(); + picker.answer(&[&path]); + poll(&mut app, &ctx); + assert_eq!(fields(&app)["files"], json!([{"path": path, "importer": "plugin.test.ui.placepick", "params": {"density": 7}}])); + try_confirm(&mut app).unwrap(); + assert_eq!(placed_group(&app).as_deref(), Some("b.svg"), "{}", app.ui.status); + + app.run("file.place", json!({})).unwrap(); + picker.answer_contents(&[("c.svg", b"?")]); + poll(&mut app, &ctx); + assert_eq!(fields(&app)["files"], json!([{"name": "c.svg"}])); + cancel(&mut app); + + // Two picks open at once: each one's files keep that pick's importer and parameters, also when + // the later pick is answered first. + app.run("file.place", with).unwrap(); + app.run("file.place", json!({})).unwrap(); + picker.answer_contents(&[("e.svg", b"?")]); + poll(&mut app, &ctx); + assert_eq!(fields(&app)["files"], json!([{"name": "e.svg"}])); + cancel(&mut app); + picker.answer_contents(&[("d.svg", b"?")]); + poll(&mut app, &ctx); + assert_eq!(fields(&app)["files"], json!([{"name": "d.svg", "importer": "plugin.test.ui.placepick", "params": {"density": 7}}])); + try_confirm(&mut app).unwrap(); + assert_eq!(placed_group(&app).as_deref(), Some("d.svg"), "{}", app.ui.status); + + app.run("plugin.remove", json!({"id": "test.ui.placepick"})).unwrap(); +} + +/// The name of the one selected object when it is a group: what an importer places. +fn placed_group(app: &VectorcraftApp) -> Option { + let st = app.session.active()?; + let [id] = st.selection.objects[..] else { return None }; + let n = st.doc.node(id)?; + matches!(n.kind, vectorcraft_doc::NodeKind::Group { .. }).then(|| n.name.clone()).flatten() +} + /// The extensions File › Open's filters leave out of importers' (`fileio::opens_as_other`) are the /// ones File › Open installs, imports, checks or loads as something other than a document. #[test] diff --git a/crates/ui-egui/src/dialogs/tests_print.rs b/crates/ui-egui/src/dialogs/tests_print.rs index 3429cf323e..f4e4136188 100644 --- a/crates/ui-egui/src/dialogs/tests_print.rs +++ b/crates/ui-egui/src/dialogs/tests_print.rs @@ -399,6 +399,23 @@ fn the_control_channel_fills_and_confirms_the_dialog() { assert_eq!(jobs.borrow().len(), 1); } +/// The Summary section's Pages, Options and Warnings are each named in the window's accessibility tree, with their +/// summary text as the value. +#[test] +fn the_summary_names_its_pages_options_and_warnings() { + let (mut app, _) = app(); + app.run("file.print", json!({})).unwrap(); + pump(&mut app); + set(&mut app, "section", json!("Summary")); + pump(&mut app); + let ctx = ctx(&app); + let out = crate::testing::app_frame(&mut app, &ctx, Default::default()); + let nodes = out.platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default(); + for name in ["Pages", "Options", "Warnings"] { + assert!(nodes.iter().any(|(_, n)| n.label() == Some(name) && n.value().is_some_and(|v| !v.is_empty())), "{name} has no summary"); + } +} + /// Scale W and H of the open dialog, and its link. fn scale(app: &VectorcraftApp) -> (f64, f64, bool) { let f = fields(app); diff --git a/crates/ui-egui/src/dialogs/tests_print_presets.rs b/crates/ui-egui/src/dialogs/tests_print_presets.rs index 65f4d2217f..a14ad40635 100644 --- a/crates/ui-egui/src/dialogs/tests_print_presets.rs +++ b/crates/ui-egui/src/dialogs/tests_print_presets.rs @@ -131,6 +131,8 @@ fn presets_files_import_and_export() { app.run("ui.printPresetsDialog", json!({"selected": "Mine"})).unwrap(); pump(&mut app); press(&mut app, ManagerAction::Export); + // The save panel suggests the preset's name. + assert_eq!(picker.requests().last().and_then(|r| r.file_name.clone()).as_deref(), Some("Mine.vcprintpresets")); picker.answer_saved(&file, None); let ctx = app.ui_ctx.clone().expect("the test app has a window"); crate::tests_picks::poll(&mut app, &ctx); @@ -141,5 +143,11 @@ fn presets_files_import_and_export() { assert_eq!(names, ["Mine", "Mine 2"]); assert_eq!(app.session.prefs.print_presets[1].settings.copies, 2); assert!(app.ui.status.contains("print presets"), "{}", app.ui.status); + // The built-in preset's file is named without its brackets. + app.run("ui.printPresetsDialog", json!({"selected": DEFAULT_PRESET})).unwrap(); + pump(&mut app); + press(&mut app, ManagerAction::Export); + assert_eq!(picker.requests().last().and_then(|r| r.file_name.clone()).as_deref(), Some("Default.vcprintpresets")); + picker.cancel(); let _ = std::fs::remove_dir_all(dir); } diff --git a/crates/ui-egui/src/dialogs/three_d_classic.rs b/crates/ui-egui/src/dialogs/three_d_classic.rs index 8f1d65807f..577ece6fb1 100644 --- a/crates/ui-egui/src/dialogs/three_d_classic.rs +++ b/crates/ui-egui/src/dialogs/three_d_classic.rs @@ -13,7 +13,7 @@ use craft::ui::canvas::Canvas; use craft::ui::canvas::{CanvasSpace, canvas_space}; use craft::ui::canvas_controls::SelectionOutline; use craft::ui::contract::{Bind, Entry, Props as _, Show as _, ShowContainer as _}; -use craft::ui::display::Picture; +use craft::ui::display::{Picture, Text}; use craft::ui::layout_components::Row; use craft::ui::list::ThumbAspect; use craft::ui::patterns::form_dialogs::{CustomContext, DialogFields, FieldValue, HostedParamDialog, Param, ParamKind}; @@ -315,7 +315,7 @@ fn navigator(count: usize, seen: Vec) -> Param { } } if !seen.get(current - 1).copied().unwrap_or(true) { - ui.label(tl!("Hidden")); + Text::new(tl!("Hidden")).show(ui); } }); let shown = next.map_or(current, |n| n.clamp(1, count)); diff --git a/crates/ui-egui/src/dialogs/transform_each.rs b/crates/ui-egui/src/dialogs/transform_each.rs index 0ca75cd8e0..3672552552 100644 --- a/crates/ui-egui/src/dialogs/transform_each.rs +++ b/crates/ui-egui/src/dialogs/transform_each.rs @@ -17,7 +17,7 @@ use craft::behavior::Mixed; use craft::ui::choice::{Checkbox, Radio, RadioGroup}; -use craft::ui::contract::{Bind, Props as _, Show as _, ShowContainer as _}; +use craft::ui::contract::{Bind, FieldLabelRole, Props as _, Show as _, ShowContainer as _, SideLabel}; use craft::ui::dialog::{DialogHost, DialogId, FieldRefusal}; use craft::ui::display::Text; use craft::ui::form::Field; @@ -290,30 +290,32 @@ enum Measure { } /// One captioned side: a slider over `rail` and a number field in ±`limit`, `value` being none -/// while the objects differ (the field reads Mixed). Returns the value the user set this pass. +/// while the objects differ (the field reads Mixed). `caption` is the row (Scale or Move) and the +/// visible label; the label repeats in each row, so it only describes the controls, and their +/// names start with the row. Returns the value the user set this pass. fn side( ui: &mut Ui, key: &'static str, - label: impl Into