From 0fd757c6b840438308a9cad7cd7e14b6d0b4b09d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 04:33:41 -0800 Subject: [PATCH 01/25] Clipboard: the window closes at once and quitting waits up to 27 s for the Paste check On Linux the Paste menu's background check holds its own clipboard handle. When the app quit while that check's X11 text read was still unanswered, quitting stopped waiting for the check's thread after 5 s, but the handle's read worker holds arboard's handle until 25 s after the read was sent. The app's own handle was then dropped first, so it was not the last one alive to hand what was copied to a clipboard manager. - CLIPBOARD_PROBE_STOP_WAIT (27 s, exported from vectorcraft-ui-egui) replaces the 5 s bound: the 25 s X11 read limit plus LOAD_WAIT, the 2 s limit on waiting for a reader to stop. Quitting still ends after it when a host's handle never lets go. - On Linux and the BSDs, on_exit hides the main window before eframe drops the app, so the window closes at once while the process waits for the clipboard handles. The window is hidden, not closed, and the connection the clipboards use stays open. winit hides X11 windows, XWayland ones included; it cannot hide a native Wayland window, which stays on screen until the wait ends. macOS and Windows are unchanged. - Probe's Drop waits through an injectable function, so a test drives the wait with a controllable clock while the probe's handle is still being dropped and checks that it is dropped before the app's. - A Linux test in the app checks the bound against X11_READ_LIMIT and LOAD_WAIT, so raising either fails it. - Comments and docs/development.md describe the wait. --- apps/vectorcraft/src/app.rs | 27 ++++++++ apps/vectorcraft/src/clipboard.rs | 10 +++ apps/vectorcraft/src/host_services.rs | 5 +- apps/vectorcraft/src/main.rs | 5 +- apps/vectorcraft/src/tests.rs | 18 +++++ crates/ui-egui/src/clipboard_probe.rs | 35 ++++++---- crates/ui-egui/src/lib.rs | 9 +-- crates/ui-egui/src/sysclip.rs | 6 ++ crates/ui-egui/src/tests/sysclip_probe.rs | 83 ++++++++++++++++++++++- docs/development.md | 2 +- docs/target-app-parity.md | 1 + 11 files changed, 180 insertions(+), 21 deletions(-) diff --git a/apps/vectorcraft/src/app.rs b/apps/vectorcraft/src/app.rs index 0391b7534b..4827772444 100644 --- a/apps/vectorcraft/src/app.rs +++ b/apps/vectorcraft/src/app.rs @@ -108,10 +108,37 @@ impl eframe::App for App { self.app.start_pending_update(); #[cfg(target_os = "macos")] super::mac_cursor::release(); + #[cfg(not(any(target_os = "macos", windows)))] + hide_before_teardown(self.winit_window.as_deref()); end_before_teardown(self.frames); } } +/// The main window as [`hide_before_teardown`] sees it. +#[cfg(not(any(target_os = "macos", windows)))] +pub(crate) trait QuittingWindow { + fn hide(&self); +} + +#[cfg(not(any(target_os = "macos", windows)))] +impl QuittingWindow for winit::window::Window { + fn hide(&self) { + self.set_visible(false); + } +} + +/// On Linux and the BSDs, hide the main window before eframe drops the app. Dropping the app waits +/// up to [`vectorcraft_ui_egui::CLIPBOARD_PROBE_STOP_WAIT`] for the clipboard handles to let go, and +/// the window would stay on screen for that time. The window is hidden, not closed: the Wayland +/// clipboard reads text on the window's connection. winit hides X11 windows (XWayland included) and +/// cannot hide a Wayland window. +#[cfg(not(any(target_os = "macos", windows)))] +pub(crate) fn hide_before_teardown(window: Option<&W>) { + if let Some(window) = window { + window.hide(); + } +} + impl App { /// The frame's times for the hang report, and its last stage ([`hang_beacon::after_frame`]): a /// focused, shown window whose windows had input waits for the renderer and the next frame, diff --git a/apps/vectorcraft/src/clipboard.rs b/apps/vectorcraft/src/clipboard.rs index c5ef4d5579..1daccc22f1 100644 --- a/apps/vectorcraft/src/clipboard.rs +++ b/apps/vectorcraft/src/clipboard.rs @@ -1504,6 +1504,16 @@ mod portable { assert_eq!(finish(true), Duration::ZERO); } + #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] + #[test] + fn quitting_waits_for_the_paste_checks_handle_as_long_as_its_reads_last() { + // The Paste check's handle is one of these: when the app quits, its unanswered X11 read + // ends `X11_READ_LIMIT` after it was sent, and an idle worker stops within `LOAD_WAIT`. + // Quitting waits for that handle until both are over. + assert!(vectorcraft_ui_egui::CLIPBOARD_PROBE_STOP_WAIT >= finish(false) + super::super::loads::LOAD_WAIT); + assert!(vectorcraft_ui_egui::CLIPBOARD_PROBE_STOP_WAIT >= finish(true) + super::super::loads::LOAD_WAIT); + } + #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] #[test] fn a_bitmap_paste_waits_for_the_owner_off_the_ui_thread() { diff --git a/apps/vectorcraft/src/host_services.rs b/apps/vectorcraft/src/host_services.rs index 03a9b8848c..94419b1049 100644 --- a/apps/vectorcraft/src/host_services.rs +++ b/apps/vectorcraft/src/host_services.rs @@ -393,8 +393,9 @@ pub(crate) fn services(parent: Parent, ui: egui::Context) -> Services { // Its calls are marked for the hang report (`hang_watch`). system_clipboard: Some(Box::new(vectorcraft_ui_egui::hang_beacon::Marked(clipboard::system_clipboard(clip)))), // Linux checks whether Paste has something to take on a background thread: an X11 clipboard - // owner that never answers holds a read for up to 4 s. Windows only asks which formats the - // clipboard holds and macOS asks the pasteboard server, so they check in line. + // owner that never answers holds a text read for up to 4 s for each format it tries, and + // quitting waits up to `CLIPBOARD_PROBE_STOP_WAIT` for that thread. Windows only asks which + // formats the clipboard holds and macOS asks the pasteboard server, so they check in line. // The probe's handle is made on its own thread, from the window (`Send`), not its raw display. clipboard_probe: cfg!(target_os = "linux").then(|| Box::new(move || clipboard::system_clipboard(clip_probe)) as ClipboardProbeFactory), // Help → Discord / website / GitHub, the Discord button, About and Home links. diff --git a/apps/vectorcraft/src/main.rs b/apps/vectorcraft/src/main.rs index c2b40e37e6..33e962c0aa 100644 --- a/apps/vectorcraft/src/main.rs +++ b/apps/vectorcraft/src/main.rs @@ -87,6 +87,8 @@ mod titlebar; use app::bring_window_forward; use app::native_input_hook; use app::open_or_hold; +#[cfg(all(test, not(any(target_os = "macos", windows))))] +use app::{QuittingWindow, hide_before_teardown}; use host_services::services; #[cfg(all(test, feature = "wgpu"))] use prefs::{KEEP_UI_PREFS, decode_saved_prefs, keep_prefs_copy, prefs_bytes}; @@ -116,7 +118,8 @@ struct App { frames: u64, /// Keeps the custom title bar's window borderless (Windows, #1758). window_frame: Option, - /// The main window; used to read and set maximized state the UI layer does not see on Linux (#3635). + /// The main window; used to read and set maximized state the UI layer does not see on Linux (#3635), + /// and to hide the window on quit before the clipboard handles let go (`app::hide_before_teardown`). winit_window: Option>, /// A saved or fitted geometry asked for maximize once the window is mapped (Linux). pending_maximize: bool, diff --git a/apps/vectorcraft/src/tests.rs b/apps/vectorcraft/src/tests.rs index 6e61cbe31f..6ae80944a6 100644 --- a/apps/vectorcraft/src/tests.rs +++ b/apps/vectorcraft/src/tests.rs @@ -460,3 +460,21 @@ fn the_linux_desktop_entry_opens_every_readable_format() { } } } + +/// On Linux and the BSDs, quitting hides the main window before eframe drops the app, whose +/// clipboard handles may take up to `CLIPBOARD_PROBE_STOP_WAIT` to let go. +#[cfg(not(any(target_os = "macos", windows)))] +#[test] +fn quitting_hides_the_window_before_the_clipboards_let_go() { + struct Window(std::cell::Cell); + impl QuittingWindow for Window { + fn hide(&self) { + self.0.set(self.0.get() + 1); + } + } + let window = Window(std::cell::Cell::new(0)); + hide_before_teardown(Some(&window)); + assert_eq!(window.0.get(), 1, "the window was not hidden"); + // Without a window (none was made), there is nothing to hide. + hide_before_teardown::(None); +} diff --git a/crates/ui-egui/src/clipboard_probe.rs b/crates/ui-egui/src/clipboard_probe.rs index d492893ce0..5028125e03 100644 --- a/crates/ui-egui/src/clipboard_probe.rs +++ b/crates/ui-egui/src/clipboard_probe.rs @@ -9,17 +9,11 @@ use std::time::{Duration, Instant}; use vectorcraft_engine::cmd::clipboard::PASTE_ORDER; -use crate::sysclip::ClipboardProbeFactory; +use crate::sysclip::{CLIPBOARD_PROBE_STOP_WAIT as STOP_WAIT, ClipboardProbeFactory}; /// How often the worker looks at the clipboard while the UI wants to know. const PROBE_INTERVAL: Duration = Duration::from_millis(250); -/// How long dropping the probe (when the app quits) waits for the worker to let go of its clipboard -/// handle (VectorCraft's own bound). arboard's X11 reads wait up to 4 s for each text format they -/// ask for; when a look is still waiting after this bound, the app quits without waiting longer, -/// and what it copied may not reach the clipboard manager. -const STOP_WAIT: Duration = Duration::from_secs(5); - /// The background clipboard check ([`crate::VectorcraftApp`]'s `clipboard_probe`). pub(crate) struct Probe { /// Tells the worker whether Paste depends on the system clipboard; dropped to stop it. @@ -28,8 +22,14 @@ pub(crate) struct Probe { verdicts: Receiver, /// The worker's last verdict. last: bool, + /// How `Drop` waits for the worker: [`wait_for_worker`], or a controllable clock in tests. + pub(crate) stop: StopWait, } +/// Waits on the worker's verdicts, from the quit to the deadline [`stop_by`] gives, until the worker +/// is gone or the deadline passes. +pub(crate) type StopWait = Box, Instant, Instant) + Send>; + impl Probe { /// Start the worker. `None` on wasm, or when the thread can't be spawned: the caller then falls /// back to the in-line check. @@ -65,13 +65,14 @@ impl Probe { Err(RecvTimeoutError::Disconnected) => break, } } - // The handle goes before the app stops waiting (`Drop`): on X11 the last one alive - // hands what the app copied to the clipboard manager, which must finish before exit. + // The handle goes before `Drop` stops waiting, unless dropping it takes longer than + // `STOP_WAIT`: on X11 the last one alive hands what the app copied to the clipboard + // manager, which must finish before exit. drop(clipboard); drop(tx); }) .ok()?; - Some(Self { wants: Some(wants), wanted: false, verdicts, last: false }) + Some(Self { wants: Some(wants), wanted: false, verdicts, last: false, stop: Box::new(wait_for_worker) }) } /// Paste can take from the system clipboard: `wanted` (nothing copied in the app, a document @@ -96,7 +97,17 @@ impl Drop for Probe { /// never answers) until it has let go of its clipboard handle. fn drop(&mut self) { self.wants = None; - let end = Instant::now() + STOP_WAIT; - while self.verdicts.recv_timeout(end.saturating_duration_since(Instant::now())).is_ok() {} + let quit = Instant::now(); + (self.stop)(&self.verdicts, quit, stop_by(quit)); } } + +/// When dropping the probe at `quit` stops waiting for its worker. +pub(crate) fn stop_by(quit: Instant) -> Instant { + quit + STOP_WAIT +} + +/// Waits until the worker has dropped its sender (it has let go of its clipboard handle) or `end`. +fn wait_for_worker(verdicts: &Receiver, _quit: Instant, end: Instant) { + while verdicts.recv_timeout(end.saturating_duration_since(Instant::now())).is_ok() {} +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index c4c6ded189..41bd3b3b1e 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -108,7 +108,7 @@ use vectorcraft_engine::{Session, ViewInfo}; pub use control::{ControlRequest, ControlResponse, Ticket as ControlTicket}; pub use state::{UiState, View}; -pub use sysclip::{ClipboardProbeFactory, ClipboardRead, MakeFlavour, SystemClipboard}; +pub use sysclip::{CLIPBOARD_PROBE_STOP_WAIT, ClipboardProbeFactory, ClipboardRead, MakeFlavour, SystemClipboard}; mod app; mod caches; @@ -138,9 +138,10 @@ pub struct VectorcraftApp { pub(crate) view_uids: Vec, /// The thread that checks the system clipboard for `system_paste` instead /// ([`Services::clipboard_probe`]). It is declared before `services` so that it is dropped - /// first: on X11 the last clipboard handle alive hands what the app copied to the clipboard - /// manager, and that must be the app's own handle in `services`, dropped on the UI thread - /// before the process exits. + /// first, waiting up to [`CLIPBOARD_PROBE_STOP_WAIT`] for its thread to let go of its handle: on + /// X11 the last clipboard handle alive hands what the app copied to the clipboard manager, and + /// that should be the app's own handle in `services`, dropped on the UI thread before the + /// process exits. clipboard_probe: Option, pub services: Services, pub canvas: CanvasCache, diff --git a/crates/ui-egui/src/sysclip.rs b/crates/ui-egui/src/sysclip.rs index ac382547de..28ffc812a6 100644 --- a/crates/ui-egui/src/sysclip.rs +++ b/crates/ui-egui/src/sysclip.rs @@ -85,6 +85,12 @@ impl ClipboardRead { /// thread and the handle lives and dies there, so the handle needn't be `Send`. pub type ClipboardProbeFactory = Box Box + Send>; +/// How long quitting waits for the probe's thread ([`ClipboardProbeFactory`]) to drop its handle +/// before the app drops its own: 27 s, VectorCraft's own bound. A host's handle should finish a +/// look and its own teardown within it, or the app's handle may not be the last one dropped; a +/// handle that never lets go still lets the app quit after this wait. +pub const CLIPBOARD_PROBE_STOP_WAIT: std::time::Duration = std::time::Duration::from_secs(27); + /// The Copy or Cut whose formats go to the system clipboard ([`VectorcraftApp::publish_clipboard`]). #[derive(Default)] pub(crate) struct Publishing { diff --git a/crates/ui-egui/src/tests/sysclip_probe.rs b/crates/ui-egui/src/tests/sysclip_probe.rs index 05cab31bf7..1566b2bc8a 100644 --- a/crates/ui-egui/src/tests/sysclip_probe.rs +++ b/crates/ui-egui/src/tests/sysclip_probe.rs @@ -12,7 +12,7 @@ use vectorcraft_engine::Session; use vectorcraft_engine::cmd::clipboard::Flavour; use crate::tests_sysclip::{copy_rect, run}; -use crate::{Services, SystemClipboard, VectorcraftApp, menus}; +use crate::{Services, SystemClipboard, VectorcraftApp, clipboard_probe, menus}; /// What the clipboard handles saw: the thread each `has()` ran on, how many handles are alive, and /// the thread each handle was dropped on, in order. @@ -206,6 +206,87 @@ fn quitting_drops_the_probes_clipboard_before_the_apps() { assert_eq!(drops, vec![Some("vectorcraft-clip".to_owned()), ui], "handles dropped on: {drops:?}"); } +/// The probe's clipboard: dropping it tells `dropping` it started, then waits until `release` sends +/// (a handle that lets go only once an unanswered read ends), and tells `dropped` once it is gone. +struct Releasing { + rec: Arc, + dropping: std::sync::mpsc::Sender<()>, + release: std::sync::mpsc::Receiver<()>, + dropped: std::sync::mpsc::Sender<()>, +} + +impl Drop for Releasing { + fn drop(&mut self) { + let _ = self.dropping.send(()); + let _ = self.release.recv(); + self.rec.drops.lock().unwrap().push(std::thread::current().name().map(str::to_owned)); + let _ = self.dropped.send(()); + } +} + +impl SystemClipboard for Releasing { + fn write(&mut self, _flavours: &[Flavour]) -> Result<(), String> { + Ok(()) + } + fn holds_ours(&mut self) -> bool { + false + } + fn read(&mut self, _mimes: &[&'static str]) -> Option { + None + } + fn has(&mut self, _mimes: &[&'static str]) -> bool { + false + } +} + +#[test] +fn quitting_waits_while_the_probes_clipboard_is_still_letting_go() { + let rec = Arc::new(Recorder::default()); + let (dropping, dropping_seen) = std::sync::mpsc::channel(); + let (release, released) = std::sync::mpsc::channel(); + let (dropped, dropped_seen) = std::sync::mpsc::channel(); + let make = { + let rec = Arc::clone(&rec); + move || -> Box { Box::new(Releasing { rec, dropping, release: released, dropped }) } + }; + let services = Services { + system_clipboard: Some(Slow::boxed(&rec, Duration::ZERO, Some(false))), + clipboard_probe: Some(Box::new(make)), + ..Default::default() + }; + let mut app = VectorcraftApp::new(Session::new(), services); + frame(&mut app); + // A controllable clock: the probe's handle lets go 26 s after the quit (a text read unanswered + // just before it, and the worker's teardown). The wait sees the handle start to drop, then + // either reaches that time and waits for the worker, or ends at its deadline first. + let lets_go = Duration::from_secs(26); + let release_at_deadline = release.clone(); + app.clipboard_probe.as_mut().expect("the probe started").stop = Box::new(move |verdicts, quit, end| { + dropping_seen.recv().expect("the probe's handle was never dropped"); + if end >= quit + lets_go { + let _ = release_at_deadline.send(()); + while verdicts.recv().is_ok() {} + } + }); + drop(app); + // A wait that ended first left the handle dropping: let it finish to read the order. + let _ = release.send(()); + dropped_seen.recv().expect("the probe's handle was never dropped"); + let drops = rec.drops.lock().unwrap().clone(); + let ui = std::thread::current().name().map(str::to_owned); + assert_eq!(drops, vec![Some("vectorcraft-clip".to_owned()), ui], "handles dropped on: {drops:?}"); +} + +#[test] +fn quitting_waits_out_an_unanswered_x11_read_and_its_teardown() { + let quit = Instant::now(); + // A look whose text read went unanswered just before the quit: the Linux host's worker holds its + // handle until 25 s after the read was sent, and an idle worker's teardown takes 2 s at most. + assert!(clipboard_probe::stop_by(quit) >= quit + Duration::from_secs(25) + Duration::from_secs(2)); + // A handle that never lets go still lets the app quit. + assert_eq!(clipboard_probe::stop_by(quit), quit + Duration::from_secs(27)); +} + #[test] fn without_its_thread_the_check_runs_in_line_again() { let rec = Arc::new(Recorder::default()); diff --git a/docs/development.md b/docs/development.md index 37f2b770ac..171ffc981b 100644 --- a/docs/development.md +++ b/docs/development.md @@ -126,7 +126,7 @@ On GNOME/Wayland, enable **Preferences › User Interface › System Title Bar** The window runs natively on Wayland (eframe's `wayland` feature) and on X11. On machines with two GPUs it renders on the one the desktop runs on unless Preferences say otherwise; see [Desktop graphics processor](#desktop-graphics-processor) (#502). The system clipboard (`apps/vectorcraft/src/clipboard.rs`) is arboard with its `wayland-data-control` feature: - **Clipboard:** under Wayland arboard talks to the compositor through the data-control protocol (wlroots compositors such as Sway and Hyprland, KDE Plasma), so bitmaps (`image/png`), SVG markup and text copied in any app paste (#398). Where the compositor lacks the protocol (GNOME's Mutter, [arboard#223](https://github.com/1Password/arboard/issues/223)), arboard falls back to the X11 clipboard through XWayland, which only holds what X11 apps copied. Where there is no X11 either (the Flatpak on a Wayland session: `--socket=fallback-x11` gives it none), Copy and Paste use the compositor's core data-device protocol on the window's own connection through smithay-clipboard: text only (a copy's text or its SVG markup), and only while the window has focus. smithay-clipboard waits for the owner's data with no limit, so its reads run on a worker thread and the UI thread waits 2 s at most: an owner that never sends its data costs one read 2 s, and later reads return at once until it answers. When a read gets no answer in its 2 s, such as a paste's check whether the clipboard still holds what VectorCraft copied, the paste waits on its background thread for that read's answer, up to 10 s after the read was sent, and pastes the text unless it is empty or what VectorCraft copied. A clipboard neither backend opens is tried again after 1 s, doubling to a minute (a Copy or Paste of the user's at most once a second), and logged once when it goes and once when it comes back: before, the background Paste check reconnected and logged a warning every 250 ms. egui's own text paste into fields goes through smithay-clipboard and works either way. -- **Clipboard owners that never answer (#510):** reading the clipboard waits on the app that owns it: arboard gives up on an X11 owner after 4 s for each format it tries, and a Wayland read waits for the owner to send its data. So on Linux the check that enables the Paste menu items runs on a background thread with a second clipboard handle (`crates/ui-egui/src/clipboard_probe.rs`, installed as `Services::clipboard_probe`), only while nothing is copied in the app and a document is open, and the window keeps drawing. Every arboard read on Linux and the BSDs, including the UI thread's (a paste, and a Copy or Cut checking what the clipboard held), runs on a worker thread with a handle of its own and waits 2 s at most: an owner that never sends its data costs one read that wait, and later reads fail at once until it answers. A paste's bitmap read waits up to 10 s on the paste's background thread, so the UI thread does not wait for it. When one of a paste's reads gets no answer in its 2 s, or a paste follows a read that has not been answered yet, such as the paste's own check whether the clipboard still holds what VectorCraft copied, the paste waits on that thread for that read's answer, up to 10 s after the read was sent, and pastes what it holds. When the answer is what VectorCraft copied, holds nothing to paste, or does not come, the paste takes the internal clipboard. On X11, quitting within 25 s of a read that got no answer waits for that read to end, so the app's own handle is the last one and hands what it copied to the clipboard manager. Windows and macOS keep the check on the UI thread: Windows only asks which formats the clipboard holds, macOS asks the pasteboard server. +- **Clipboard owners that never answer (#510):** reading the clipboard waits on the app that owns it: arboard gives up on an X11 owner after 4 s for each format it tries, and a Wayland read waits for the owner to send its data. So on Linux the check that enables the Paste menu items runs on a background thread with a second clipboard handle (`crates/ui-egui/src/clipboard_probe.rs`, installed as `Services::clipboard_probe`), only while nothing is copied in the app and a document is open, and the window keeps drawing. Every arboard read on Linux and the BSDs, including the UI thread's (a paste, and a Copy or Cut checking what the clipboard held), runs on a worker thread with a handle of its own and waits 2 s at most: an owner that never sends its data costs one read that wait, and later reads fail at once until it answers. A paste's bitmap read waits up to 10 s on the paste's background thread, so the UI thread does not wait for it. When one of a paste's reads gets no answer in its 2 s, or a paste follows a read that has not been answered yet, such as the paste's own check whether the clipboard still holds what VectorCraft copied, the paste waits on that thread for that read's answer, up to 10 s after the read was sent, and pastes what it holds. When the answer is what VectorCraft copied, holds nothing to paste, or does not come, the paste takes the internal clipboard. On X11, quitting within 25 s of a read that got no answer waits for that read to end, so the app's own handle is the last one and hands what it copied to the clipboard manager when one runs. That includes a read of the Paste menu check's handle: quitting waits up to 27 s for the background thread to drop it before the app drops its own, and quits after that wait even when the handle has not been dropped. The app hides its main window before these waits (`hide_before_teardown` in `apps/vectorcraft/src/app.rs`), so an X11 window, an XWayland one included, closes at once; winit cannot hide a native Wayland window, which stays on screen until the waits end. Windows and macOS keep the check on the UI thread: Windows only asks which formats the clipboard holds, macOS asks the pasteboard server. - **Copied files:** files copied in a file manager (`text/uri-list`; `CF_HDROP` on Windows, file URLs on macOS) paste as the first one that is art (SVG, PDF, EPS, EMF/WMF or a bitmap; a `.ai` or `.ait` file from the editing data it holds, else as the PDF or PostScript it holds), before the clipboard's other formats (which include the files' paths as text). - **Dropping files on the window does not work under Wayland:** winit 0.30, which eframe 0.37 runs on, has no Wayland drag and drop ([winit#1881](https://github.com/rust-windowing/winit/issues/1881), added in winit 0.31; [egui#1563](https://github.com/emilk/egui/issues/1563)), so no `dropped_files` arrive. Until eframe moves to winit 0.31: copy the files in the file manager and paste them, use File › Place or Open, or open the window through XWayland, where drops work: set **Preferences › Performance › Linux Display Server** to **X11 (XWayland)** and restart (#1151), or start the app with `WAYLAND_DISPLAY= vectorcraft`. The preference (`linuxDisplayServer`, read at startup in `apps/vectorcraft/src/main.rs`, shown on Linux only) has winit open the window on X11 (`EventLoopBuilderExtX11::with_x11`) when the session is Wayland, `DISPLAY` is set and the X11 libraries winit loads are installed (`apps/vectorcraft/src/xwayland.rs` reads `ldconfig -p` and the usual library directories); otherwise the window opens on Wayland and the log says why. Unlike clearing `WAYLAND_DISPLAY`, it leaves the clipboard on the compositor's own. - **Pens and pen displays under Wayland (#491, #2028):** winit 0.30 doesn't bind the Wayland tablet protocol (`zwp_tablet_v2`; tablet input arrives in winit 0.31, [winit#4318](https://github.com/rust-windowing/winit/pull/4318), [egui#7731](https://github.com/emilk/egui/pull/7731)). Since Plasma 6.3, KWin no longer turns tablet input into pointer input for such apps ([kwin!6336](https://invent.kde.org/plasma/kwin/-/merge_requests/6336), commit [25c65abd](https://invent.kde.org/plasma/kwin/-/commit/25c65abddd95eb87fb892a8594faccbf509ff62f)), and GNOME's Mutter does not turn it into pointer input either (that commit's message): on KWin the pen moves the compositor's cursor over the window, but the app gets no motion or presses and shows none of its own cursors. Until eframe moves to winit 0.31, the app runs under XWayland, which supports the tablet protocol and hands the pen to X11 apps as a pointer: Preferences › Performance › Linux Display Server's Automatic (the default) and X11 (XWayland) When a Pen Is Attached (`x11WithPen`) open the window through XWayland when `/proc/bus/input/devices` lists a pen as the app starts, a device with the `BTN_TOOL_PEN` key and the `ABS_X` and `ABS_Y` axes, and log `pen found: opening the window through XWayland`, as PhotoCraft does (#4967; `VECTORCRAFT_NATIVE_WAYLAND=1` keeps the window on Wayland). For a pen attached after the app started, either run the app under XWayland (Preferences › Performance › Linux Display Server › X11 (XWayland); `WAYLAND_DISPLAY= vectorcraft`, or `env -u WAYLAND_DISPLAY vectorcraft`; for a desktop launcher, put `env WAYLAND_DISPLAY=` before the command in its `Exec=` line), or turn KWin's deprecated emulation back on for the whole session by setting `KWIN_WAYLAND_EMULATE_TABLET=1` in KWin's environment (for example in a file under `~/.config/environment.d/` or in `/etc/environment`) and logging in again. The pen then works as a mouse. Under XWayland the app also reads the pen's pressure (next item); with KWin's emulation on native Wayland the pen has no pressure. Other compositors that don't emulate a pointer for tablets behave the same way. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f04ee3c910..d7312a2596 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1631,6 +1631,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - `file.print`, `print.preview` and `print.setup` take a print preset by name (`preset`: `[Default]` or a saved preset, in any case): its settings are used instead of the document's, with `settings` over them, `print.setup` saves them with the document, and an unknown name is refused with the list of presets. - Print's Copies per Sheet (`copiesPerSheet`, `gutter`; off by default) prints as many copies of each artboard, with its bleed and marks, as fit the imageable area, across then down, as one grid placed like a single copy; the preview shows them, and an artboard that does not fit prints one copy per sheet with a warning (#1283). - Place and the Links panel, Package (placed `.vectorcraft` documents packaged with their own linked files and fonts, relinked to the copies: #777), File Info, Print with print presets, PostScript output and print tiling, slices and Save for Web, Export for Screens and Asset Export, CSS Properties, PNG/PDF/SVG/text clipboard flavours; files copied in a file manager paste as art (SVG, PDF, EMF/WMF, bitmaps) on every desktop platform, and Linux/Wayland reads the compositor's clipboard (#398); on Linux the Paste menu checks the clipboard off the UI thread, so an X11 owner that never answers can't freeze the window (#510); screenshots and other copied pictures paste as embedded images at the view centre everywhere, the web included (#457). + - On X11, quitting while the Paste menu's background check waits on a clipboard owner that never answers waits up to 27 s for that check to drop its clipboard handle, so the app's own handle is still the last one dropped; the window is hidden before that wait, so an X11 window closes at once (`crates/ui-egui/src/tests/sysclip_probe.rs`, `apps/vectorcraft/src/clipboard.rs`, `apps/vectorcraft/src/tests.rs`). - File › Place reads RTF files as area type with their formatting: each run's font, size, bold and italic, underline, strikethrough, caps, superscript or subscript, baseline shift and color, and each paragraph's alignment, indents, space before and after and direction. Table cells are separated by tabs; hidden text, pictures, headers, footers and notes are left out (`file.place`, `crates/engine/src/tests/textimport.rs`). - File › Place reads Word `.docx` documents as area type with the same formatting, taken from the document defaults, the paragraph and character styles (their toggle properties reversing each other) and direct formatting, the theme's fonts included. Table rows are paragraphs with their cells separated by tabs; hidden and deleted text, field instructions, pictures, headers, footers and notes are left out (`file.place`, `crates/engine/src/tests/textimport.rs`). - A Word paragraph justified with a low, medium or high kashida length places justified with Insert Kashidas set to Short, Medium or Long (`file.place`, `crates/engine/src/tests/textimport.rs`). From 6e361b0becfe1df739bfeda1d84c7747733fb3b8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 04:35:29 -0800 Subject: [PATCH 02/25] Pencil: Fidelity keeps its screen size at low zoom The Pencil and the Paintbrush send their Fidelity in points at the current zoom, but path.freehand read at most 100 pt. At 3.13% zoom a 20 px Fidelity (639 pt) was fitted at 100 pt, the same as 3.13 px on screen, so a stroke drawn zoomed out kept far more anchors than the same stroke at 100%. - path.freehand, and brush.freehand, which runs it, take a Fidelity from MIN_FIT_TOLERANCE to MAX_FIT_TOLERANCE (100 / 0.0313 pt, the 100 px field maximum at the lowest zoom). A value outside that range is now rejected with an error instead of being read as the nearer end. The default stays 1.5 pt and path.blob keeps its 100 pt bound. - The Pencil and the Paintbrush keep the value they send within that range, so a stroke draws at any zoom. - An extending stroke still closes the path within four Fidelities of its other end, at most 400 pt, as before. It conflicts with open #7089 in crates/tools/src/draw2.rs. Docs: docs/mcp.md, docs/target-app-parity.md, path.freehand params. --- crates/engine/src/cmd/draw2/commands.rs | 2 +- crates/engine/src/cmd/draw2/freehand.rs | 10 ++- crates/engine/src/tests/draw2.rs | 104 ++++++++++++++++++++++-- crates/tools/src/draw2.rs | 5 ++ crates/tools/src/draw2/gesture.rs | 11 ++- crates/tools/src/draw2/gesture/tests.rs | 46 +++++++++++ docs/mcp.md | 7 ++ docs/target-app-parity.md | 1 + 8 files changed, 176 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/cmd/draw2/commands.rs b/crates/engine/src/cmd/draw2/commands.rs index 8946aa4351..400e13baab 100644 --- a/crates/engine/src/cmd/draw2/commands.rs +++ b/crates/engine/src/cmd/draw2/commands.rs @@ -11,7 +11,7 @@ pub fn specs() -> Vec { "Pencil", [], None, - "{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (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: the stroke keeps how far the pen leaned, which way and how far its barrel turned, for brushes with Tilt, Bearing and Rotation variation; null for what a point lacks), fidelity?: pt (1.5), 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\"|\"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), extend?: {id, end: \"start\"|\"end\"}, connect?: {id, end: \"start\"|\"end\"}, redraw?: {id, within?: pt (12)}} fit a freehand stroke → {id}. extend continues the path from that end; 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 shorter way round a closed one), and draws a new path when the stroke doesn't end on it", + "{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (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: the stroke keeps how far the pen leaned, which way and how far its barrel turned, for brushes with Tilt, Bearing and Rotation variation; null for what a point lacks), 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\"|\"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), extend?: {id, end: \"start\"|\"end\"}, connect?: {id, end: \"start\"|\"end\"}, redraw?: {id, within?: pt (12)}} fit a freehand stroke → {id}. extend continues the path from that end; 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 shorter way round a closed one), and draws a new path when the stroke doesn't end on it", has_doc, freehand ), diff --git a/crates/engine/src/cmd/draw2/freehand.rs b/crates/engine/src/cmd/draw2/freehand.rs index f13b0a0ba4..31e184e195 100644 --- a/crates/engine/src/cmd/draw2/freehand.rs +++ b/crates/engine/src/cmd/draw2/freehand.rs @@ -151,7 +151,11 @@ pub(super) fn freehand(s: &mut Session, p: &Value) -> Result { } let pen = PenRecord::of_samples(&samples); let mut pts: Vec = samples.into_iter().map(|s| s.pt).collect(); - let tol = number_or(p, "fidelity", 1.5, C)?.clamp(vectorcraft_tools::draw2::MIN_FIT_TOLERANCE, 100.0); + let tol = number_or(p, "fidelity", 1.5, C)?; + let (lo, hi) = (vectorcraft_tools::draw2::MIN_FIT_TOLERANCE, vectorcraft_tools::draw2::MAX_FIT_TOLERANCE); + if !(lo..=hi).contains(&tol) { + return Err(bad(C, format!("`fidelity` must be from {lo} to {hi} pt"))); + } // The tolerance the stroke is fitted at; with `fit: false` it is not fitted. let fit_tol = switch_or(p, "fit", true, C)?.then_some(tol); let closed = switch_or(p, "closed", false, C)?; @@ -200,7 +204,9 @@ pub(super) fn freehand(s: &mut Session, p: &Value) -> Result { } None => None, }; - let close_tol = (tol * 4.0).max(6.0); + // An extending stroke that ends within four Fidelities of the path's other end closes it: + // at least 6 pt and at most 400 pt, whatever the Fidelity it is fitted at. + let close_tol = (tol * 4.0).clamp(6.0, 400.0); let closing = connect.is_none() && sp.anchors.len() >= 2 && pts.last().is_some_and(|p| p.distance(first) <= close_tol); if closing && let Some(l) = pts.last_mut() { *l = first; diff --git a/crates/engine/src/tests/draw2.rs b/crates/engine/src/tests/draw2.rs index 5986b618fd..58193f1852 100644 --- a/crates/engine/src/tests/draw2.rs +++ b/crates/engine/src/tests/draw2.rs @@ -4458,6 +4458,12 @@ fn blob_anchors(s: &mut Session, fidelity: f64) -> usize { /// [`blob_anchors`] with the blob scaled by `scale`: drawn the same on screen zoomed in 1 / `scale` /// times. fn scaled_blob_anchors(s: &mut Session, fidelity: f64, scale: f64) -> usize { + blob_anchors_through(s, "path.freehand", &json!({}), Some(fidelity), scale) +} + +/// [`scaled_blob_anchors`] drawn with `command` and the params in `extra`, at `fidelity` (with none, +/// the command's default). +fn blob_anchors_through(s: &mut Session, command: &str, extra: &serde_json::Value, fidelity: Option, scale: f64) -> usize { let pts: Vec<_> = (0..1200) .map(|i| { let a = i as f64 / 1200.0 * std::f64::consts::TAU; @@ -4465,7 +4471,14 @@ fn scaled_blob_anchors(s: &mut Session, fidelity: f64, scale: f64) -> usize { json!([(400.0 + r * a.cos()) * scale, (300.0 + r * a.sin()) * scale]) }) .collect(); - let r = s.execute("path.freehand", &json!({"points": pts, "closed": true, "fidelity": fidelity, "keepSelected": false})).unwrap(); + let mut p = json!({"points": pts, "closed": true, "keepSelected": false}); + if let Some(f) = fidelity { + p["fidelity"] = json!(f); + } + if let (Some(p), Some(extra)) = (p.as_object_mut(), extra.as_object()) { + p.extend(extra.clone()); + } + let r = s.execute(command, &p).unwrap(); path(s, NodeId(r["id"].as_u64().unwrap())).subpaths.iter().map(|sp| sp.anchors.len()).sum() } @@ -4477,13 +4490,11 @@ fn pencil_fidelity_goes_down_to_a_hundredth_and_lower_keeps_more() { assert!(counts.windows(2).all(|w| w[0] <= w[1]), "{counts:?}"); // Below the old floor of 0.05 the stroke keeps more of itself. assert!(counts[4] > counts[2], "{counts:?}"); - // Below the floor, the lowest Fidelity (0.01 px) at the highest zoom (64000 %), is read as the - // floor (#5729). + // The floor is the lowest Fidelity (0.01 px) at the highest zoom (64000 %) (#5729); below it, + // `pencil_takes_fidelity_within_its_range_and_rejects_the_rest`. let floor = vectorcraft_tools::draw2::MIN_FIDELITY / 640.0; let at_floor = blob_anchors(&mut s, floor); assert!(at_floor >= counts[4], "{counts:?}"); - assert_eq!(blob_anchors(&mut s, floor / 10.0), at_floor); - assert_eq!(blob_anchors(&mut s, 0.0), at_floor); } /// #5729: the tools send Fidelity / zoom, so a stroke drawn the same on screen zoomed in keeps as @@ -4499,6 +4510,89 @@ fn pencil_fit_keeps_its_anchors_on_a_stroke_drawn_zoomed_in() { } } +/// The tools send Fidelity / zoom up to the highest Fidelity (100 px) at the lowest zoom (3.13 %): +/// a stroke drawn the same on screen zoomed out keeps as many anchors as at 100 %, as a Pencil or a +/// Paintbrush stroke and through `brush.freehand` with a brush. A tolerance above +/// `MAX_FIT_TOLERANCE` is an error, and a stroke given no Fidelity is fitted at 1.5 pt. +#[test] +fn pencil_fit_keeps_its_anchors_on_a_stroke_drawn_zoomed_out() { + let mut s = session(); + let max = vectorcraft_tools::draw2::MAX_FIT_TOLERANCE; + // The blob six times the size, so that 100 px still keeps some of its waves. + let big = 6.0; + for (command, extra) in [ + ("path.freehand", json!({})), + ("path.freehand", json!({"style": "brush"})), + ("brush.freehand", json!({"style": "brush", "brush": "3 pt. Round"})), + ] { + for fidelity in [20.0, 100.0] { + let want = blob_anchors_through(&mut s, command, &extra, Some(fidelity), big); + for zoom in [0.2, 0.0313] { + let got = blob_anchors_through(&mut s, command, &extra, Some(fidelity / zoom), big / zoom); + assert_eq!(got, want, "{command} {extra}: {fidelity} px at {zoom}x"); + // Fitted at 100 pt, the stroke on screen would keep the detail of a finer Fidelity. + if fidelity / zoom > 100.0 { + let at_100 = blob_anchors_through(&mut s, command, &extra, Some(100.0), big / zoom); + assert!(at_100 > want, "{command} {extra}: {fidelity} px at {zoom}x, 100 pt keeps {at_100} of {want}"); + } + } + } + let mut p = json!({"points": [[0, 0], [100, 50], [200, 0]], "fidelity": max * 10.0}); + if let (Some(p), Some(extra)) = (p.as_object_mut(), extra.as_object()) { + p.extend(extra.clone()); + } + let err = s.execute(command, &p).unwrap_err().to_string(); + assert!(err.contains("`fidelity` must be from"), "{command} {extra}: {err}"); + let default = blob_anchors_through(&mut s, command, &extra, None, 1.0); + assert_eq!(default, blob_anchors_through(&mut s, command, &extra, Some(1.5), 1.0), "{command} {extra}"); + } +} + +/// `path.freehand` and `brush.freehand` take a `fidelity` from `MIN_FIT_TOLERANCE` (the lowest +/// Fidelity at the highest zoom) to `MAX_FIT_TOLERANCE` (the highest at the lowest zoom), both ends +/// included, and reject a value just outside either end, a tenth of the lowest, 0, a negative one or +/// a huge one, leaving the document as it was. +#[test] +fn pencil_takes_fidelity_within_its_range_and_rejects_the_rest() { + let (lo, hi) = (vectorcraft_tools::draw2::MIN_FIT_TOLERANCE, vectorcraft_tools::draw2::MAX_FIT_TOLERANCE); + let points = json!([[0, 0], [100, 50], [200, 0], [300, 50]]); + for (command, extra) in [("path.freehand", json!({})), ("brush.freehand", json!({"style": "brush", "brush": "3 pt. Round"}))] { + let run = |s: &mut Session, fidelity: f64| { + let mut p = json!({"points": points, "fidelity": fidelity}); + if let (Some(p), Some(extra)) = (p.as_object_mut(), extra.as_object()) { + p.extend(extra.clone()); + } + s.execute(command, &p) + }; + let mut s = session(); + for fidelity in [100.0 / 0.0313, hi, lo, 0.01 / 640.0] { + let r = run(&mut s, fidelity); + assert!(r.as_ref().is_ok_and(|r| r["id"].is_u64()), "{command}: {fidelity} pt: {r:?}"); + } + let before = s.doc().unwrap().doc.clone(); + for fidelity in [f64::from_bits(hi.to_bits() + 1), f64::from_bits(lo.to_bits() - 1), lo / 10.0, 0.0, -1.5, 1e300] { + let err = run(&mut s, fidelity).unwrap_err().to_string(); + assert!(err.contains("`fidelity` must be from"), "{command}: {fidelity} pt: {err}"); + } + assert_eq!(s.doc().unwrap().doc, before, "{command}"); + } +} + +/// A stroke that continues an open path closes it when it ends within four Fidelities of the path's +/// other end, at most 400 pt away: at the coarsest Fidelity one ending 1000 pt away leaves it open, +/// and one ending 300 pt away closes it. +#[test] +fn pencil_extend_closes_within_400_pt_at_any_fidelity() { + let mut s = session(); + let max = vectorcraft_tools::draw2::MAX_FIT_TOLERANCE; + for (end, closed) in [([0, 1000], false), ([0, 300], true)] { + let l = line(&mut s, 0.0, 0.0, 2000.0, 0.0); + let points = json!([[2000, 0], [2000, 1000], [1000, 1500], end]); + s.execute("path.freehand", &json!({"points": points, "fidelity": max, "extend": {"id": l.0}, "keepSelected": false})).unwrap(); + assert_eq!(path(&s, l).subpaths[0].closed, closed, "ending at {end:?}"); + } +} + /// At Fidelity 0.01 short, one-point and repeated-point strokes still draw or are refused, never /// crash, and what they draw has finite anchors. #[test] diff --git a/crates/tools/src/draw2.rs b/crates/tools/src/draw2.rs index 123082aa25..f586650200 100644 --- a/crates/tools/src/draw2.rs +++ b/crates/tools/src/draw2.rs @@ -34,6 +34,11 @@ pub const MIN_FIDELITY: f64 = 0.01; /// Fidelity at the highest zoom (64000 %), whose screen pixels the tools send in points (#5729). pub const MIN_FIT_TOLERANCE: f64 = MIN_FIDELITY / 640.0; +/// The coarsest tolerance (points) `path.freehand` fits a Pencil or Paintbrush stroke at: the highest +/// Fidelity the tools and their Tool Options take (100 px) at the lowest zoom (3.13 %), about 3195 pt. +/// A change to either range changes this bound with it. +pub const MAX_FIT_TOLERANCE: f64 = 100.0 / 0.0313; + /// The lowest Fidelity (points) the Smooth tool takes. pub const SMOOTH_MIN_FIDELITY: f64 = 0.05; diff --git a/crates/tools/src/draw2/gesture.rs b/crates/tools/src/draw2/gesture.rs index e4811418c7..0cd5ca37df 100644 --- a/crates/tools/src/draw2/gesture.rs +++ b/crates/tools/src/draw2/gesture.rs @@ -42,6 +42,13 @@ const PREVIEW_FIDELITY_PX: f64 = 0.5; /// The Smooth tool's Fidelity until Smooth Tool Options sets another. const SMOOTH_FIDELITY: f64 = 2.5; +/// The `fidelity` (points) the Pencil and the Paintbrush send `path.freehand` for `px` screen pixels +/// at the current zoom, within the range the command takes +/// ([`super::MIN_FIT_TOLERANCE`]..[`super::MAX_FIT_TOLERANCE`]). +fn fit_tolerance(cx: &ToolContext, px: f64) -> f64 { + cx.tol(px).clamp(super::MIN_FIT_TOLERANCE, super::MAX_FIT_TOLERANCE) +} + pub struct GestureTool { /// How many points the last preview of the stroke had ([`crate::previews_at`]); 0 when it was /// fitted coarser than the stroke kept ([`PREVIEW_FIDELITY_PX`]). @@ -460,7 +467,7 @@ impl GestureTool { pub fn freehand_params(&self, cx: &ToolContext, closed: bool) -> Value { let mut v = json!({ "points": self.stroke_json(), - "fidelity": cx.tol(self.fidelity), + "fidelity": fit_tolerance(cx, self.fidelity), "closed": closed, "style": if self.id == "paintbrush" { "brush" } else { "pencil" }, "fill": self.fill, @@ -654,7 +661,7 @@ impl Tool for GestureTool { if self.previews() && crate::previews_at(self.points.len()) { let mut v = self.freehand_params(cx, false); let fidelity = self.fidelity.max(PREVIEW_FIDELITY_PX); - v["fidelity"] = json!(cx.tol(fidelity)); + v["fidelity"] = json!(fit_tolerance(cx, fidelity)); // A preview fitted coarser than the stroke kept is stale (`deactivate`). self.previewed = if fidelity > self.fidelity { 0 } else { self.points.len() }; if !self.live_fit { diff --git a/crates/tools/src/draw2/gesture/tests.rs b/crates/tools/src/draw2/gesture/tests.rs index a0fe487289..12c39684d9 100644 --- a/crates/tools/src/draw2/gesture/tests.rs +++ b/crates/tools/src/draw2/gesture/tests.rs @@ -215,6 +215,52 @@ fn fidelity_is_in_screen_pixels_at_any_zoom() { } } +/// The highest Fidelity (100 px) at the lowest zoom (3.13 %) is sent, while the stroke is drawn and +/// at its release, as [`crate::draw2::MAX_FIT_TOLERANCE`], the coarsest tolerance `path.freehand` +/// reads. +#[test] +fn highest_fidelity_at_the_lowest_zoom_sends_the_coarsest_tolerance() { + let (d, _) = doc_with_rect(); + let s = Selection::default(); + let p = paint(); + let mut cx = cx(&d, &s, &p); + cx.zoom = 0.0313; + let stroke: Vec<_> = [(0.0, 0.0), (40.0, 20.0), (80.0, 0.0), (120.0, 20.0)].iter().map(|&(x, y)| (x / cx.zoom, y / cx.zoom)).collect(); + for id in ["pencil", "paintbrush"] { + let mut t = GestureTool::new(id); + t.set_option("fidelity", &json!(100.0)); + let acts = drag(&mut t, &cx, &stroke, Mods::default()); + let sent: Vec<_> = + acts.concat().into_iter().filter_map(|a| if let Action::Preview(_, v) = a { v["fidelity"].as_f64() } else { None }).collect(); + assert_eq!(sent, [crate::draw2::MAX_FIT_TOLERANCE; 4], "{id}"); + } +} + +/// `path.freehand` rejects a `fidelity` outside `MIN_FIT_TOLERANCE..=MAX_FIT_TOLERANCE`, so at a zoom +/// beyond the view's range the Pencil and the Paintbrush send the nearer end of it, while the stroke +/// is drawn and at its release. +#[test] +fn fidelity_sent_stays_within_what_path_freehand_takes() { + let (d, _) = doc_with_rect(); + let s = Selection::default(); + let p = paint(); + let mut cx = cx(&d, &s, &p); + let (lo, hi) = (crate::draw2::MIN_FIT_TOLERANCE, crate::draw2::MAX_FIT_TOLERANCE); + for (zoom, fidelity, release) in [(0.01, 100.0, hi), (1000.0, 0.01, lo)] { + cx.zoom = zoom; + let stroke: Vec<_> = [(0.0, 0.0), (40.0, 20.0), (80.0, 0.0), (120.0, 20.0)].iter().map(|&(x, y)| (x / zoom, y / zoom)).collect(); + for id in ["pencil", "paintbrush"] { + let mut t = GestureTool::new(id); + t.set_option("fidelity", &json!(fidelity)); + let acts = drag(&mut t, &cx, &stroke, Mods::default()); + let sent: Vec<_> = + acts.concat().into_iter().filter_map(|a| if let Action::Preview(_, v) = a { v["fidelity"].as_f64() } else { None }).collect(); + assert!(sent.iter().all(|f| (lo..=hi).contains(f)), "{id} at {zoom}x: {sent:?}"); + assert_eq!(sent.last(), Some(&release), "{id} at {zoom}x: {sent:?}"); + } + } +} + /// The Blob Brush's Fidelity stays in points (#5729 is the Pencil's and the Paintbrush's): its /// stroke, and another tool chosen while it is drawn, send it as set at any zoom. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 274db05a34..b1dae8f109 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2916,6 +2916,13 @@ already walks Image Trace. Short agent entry points: Tilt goes from its first value with the pen lying flat to its second upright, and on Bearing or Rotation from its first value at −180° to its second at 180°. A stroke without that input draws the brush's own value (a Scatter brush's value half way between the two). +- Freehand Fidelity: the `fidelity` of `path.freehand` and `brush.freehand` is in points, 1.5 pt when left out. A + value must be from 0.000015625 pt (0.01 / 640) to 100 / 0.0313 pt (about 3194.89 pt), and a value outside that range + is rejected with an error. The Pencil and the Paintbrush give Fidelity in screen pixels, 0.01 to 100 px, and send it + divided by the zoom (0.0313 to 640) and kept within that range, so a stroke is fitted at the same tolerance on screen + at every zoom. A stroke + that continues a path (`extend`) closes it when it ends within four times the Fidelity of the path's other end, at + least 6 pt and at most 400 pt. The Blob Brush's `path.blob` Fidelity stays in points, 0.01 to 100 pt. - Variables: `variable.list`, `variable.define {name, kind: text|visibility|image|graph}`, `variable.bind {variable, ids?}`, `variable.makeTextDynamic`, `variable.makeVisibilityDynamic`, `variable.makeImageDynamic`, `variable.makeGraphDynamic` (`variable.bind` and `variable.makeTextDynamic` refuse type that already has another text variable and name it), diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f04ee3c910..ad13314a89 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1086,6 +1086,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Live curve fitting in the Pencil Tool Options is on by default; while it is off, the path shown while a stroke is drawn joins the stroke's points with straight segments, and the release fits the curve, as [Pencil Tool Options](https://web.archive.org/web/20261002104400/https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/pencil-tool-options.html) describes (`path.freehand` `fit`). In the Pencil and Paintbrush Tool Options, Edit selected paths within 0 px turns editing off, so a stroke that starts exactly on an end of a selected open path draws a new path; Close paths when ends are within 0 px turns closing off, so a stroke that ends exactly where it started stays open. The Pencil's and the Paintbrush's Fidelity is in screen pixels, the same at any zoom: their Tool Options give it in px, from 0.01 px on the logarithmic slider to 20 px and up to 100 px in the field, and the tool sends `path.freehand` the value in points at the current zoom (#5729). The Smooth tool's and the Blob Brush's Fidelity stays in points. + `path.freehand` and `brush.freehand` take a Fidelity of up to 100 / 0.0313 pt (about 3194.89 pt), the 100 px field maximum at the lowest zoom (3.13 %), and reject a value outside their range with an error, so a Pencil or Paintbrush stroke drawn zoomed out keeps the Fidelity set in pixels (engine tests `pencil_fit_keeps_its_anchors_on_a_stroke_drawn_zoomed_out` and `pencil_takes_fidelity_within_its_range_and_rejects_the_rest`). Before a press that draws a new path, the Pencil cursor shows a small star, as [Draw freeform paths with the Pencil tool](https://web.archive.org/web/20260926095638/https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/draw-freeform-paths-with-the-pencil-tool.html) describes; over a selected path within Edit selected paths' distance, which the press continues from an end or redraws, the star is not shown ([Reshape paths with the Pencil tool](https://web.archive.org/web/20260106004407/https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/reshape-paths-with-the-pencil-tool.html)). Keep selected in the Pencil and Paintbrush Tool Options is on by default: while it is on, a stroke selects the path it draws or continues and replaces the earlier selection. While it is off, a new stroke leaves nothing selected, the earlier selection included, as the reference application starts the stroke by dropping it (#5752); a continued or redrawn path is deselected while the rest of the selection stays (`path.freehand` `keepSelected`). With two open paths selected, a Pencil stroke from an end of one that ends within Edit selected paths' distance of an end of the other connects them into one path with the first path's appearance, in one undo step, as [Connect two paths with the Pencil tool](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/connect-two-paths-with-the-pencil-tool.html) describes (`path.freehand` `connect`). From 51eea7ecfb15aa1d10cd3c53e631283ef3bd9c8c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 04:37:30 -0800 Subject: [PATCH 03/25] Tabs: the ruler shows when a non-text object is first in the selection With the Selection tool, the Tabs panel showed "No text selected" when the first selected object was a shape, or a group holding text, even with text selected. It now shows the ruler and stops of the first paragraph of the first selected text object, looking into selected groups as the Character and Paragraph panels do. A stop set on that ruler goes to every selected text object, as text.tabs.set already did; other objects are left as they were. A selection without text still shows the empty state. --- crates/ui-egui/src/panels/character.rs | 15 +++-- crates/ui-egui/src/panels/tabs.rs | 8 ++- crates/ui-egui/src/panels/tabs/tests.rs | 77 +++++++++++++++++++++++++ docs/target-app-parity.md | 1 + 4 files changed, 94 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/panels/character.rs b/crates/ui-egui/src/panels/character.rs index 2ad678bf62..e21d6dd2de 100644 --- a/crates/ui-egui/src/panels/character.rs +++ b/crates/ui-egui/src/panels/character.rs @@ -42,14 +42,21 @@ pub(crate) fn text_style(app: &VectorcraftApp) -> Option<(CharStyle, vectorcraft /// The first selected text descendant, shared by Character and Paragraph controls. pub(crate) fn first_selected_text(app: &VectorcraftApp) -> Option<&vectorcraft_doc::TextObject> { + match &first_selected_text_node(app)?.kind { + NodeKind::Text(t) => Some(t.as_ref()), + _ => None, + } +} + +/// The node of [`first_selected_text`]: the first text object among the selected objects and +/// their descendants, in selection order, then paint order within each selected object. +pub(crate) fn first_selected_text_node(app: &VectorcraftApp) -> Option<&vectorcraft_doc::Node> { let st = app.session.active()?; for node in st.selection.objects.iter().filter_map(|id| st.doc.node(*id)) { let mut text = None; node.walk(&mut |n| { - if text.is_none() - && let NodeKind::Text(t) = &n.kind - { - text = Some(t.as_ref()); + if text.is_none() && matches!(n.kind, NodeKind::Text(_)) { + text = Some(n); } }); if text.is_some() { diff --git a/crates/ui-egui/src/panels/tabs.rs b/crates/ui-egui/src/panels/tabs.rs index 77dd07e15f..bc1f9352c3 100644 --- a/crates/ui-egui/src/panels/tabs.rs +++ b/crates/ui-egui/src/panels/tabs.rs @@ -10,7 +10,7 @@ use egui::{Sense, Stroke, Ui, vec2}; use serde_json::{Value, json}; use vectorcraft_doc::{Document, Node, NodeId, NodeKind, ParaStyle, TabAlign, TabStop, TextKind, TextObject}; -use super::{first_selected, pstate, set_pstate}; +use super::{pstate, set_pstate}; use crate::VectorcraftApp; use crate::theme::Tokens; use crate::widgets::{self, menu_item}; @@ -330,12 +330,14 @@ fn current(app: &VectorcraftApp) -> Option<(Node, Vec, f64)> { /// As [`current`], with all the attributes of the paragraph whose stops the panel shows, its left /// indent as laid out ([`ParaStyle::laid_out_left_indent`]: its list level's indent added), where -/// the ruler shows it. +/// the ruler shows it. Without the Type tool editing text, the panel shows the first paragraph of +/// the first selected text object, also when that text is in a selected group or follows a +/// selected object that is not text. fn current_para(app: &VectorcraftApp) -> Option<(Node, ParaStyle, f64)> { let editing = super::character::text_editing(app); let n = match editing { Some((id, _, _)) => app.session.active()?.doc.node(id)?.clone(), - None => first_selected(app)?, + None => super::character::first_selected_text_node(app)?.clone(), }; let NodeKind::Text(t) = &n.kind else { return None }; let para = editing.map_or(0, |(_, a, _)| t.paragraphs_in(a, a).start); diff --git a/crates/ui-egui/src/panels/tabs/tests.rs b/crates/ui-egui/src/panels/tabs/tests.rs index d6bcef15f1..6472b1017b 100644 --- a/crates/ui-egui/src/panels/tabs/tests.rs +++ b/crates/ui-egui/src/panels/tabs/tests.rs @@ -27,6 +27,83 @@ fn panel_draws_empty_with_text_and_with_stops() { assert_eq!(back[1]["align"], json!("decimal")); } +/// A rectangle and two area texts, the first with a stop at 40 pt and the second with one at +/// 90 pt, nothing selected. → the app and the ids of the rectangle and the two texts. +fn mixed_selection_app() -> (VectorcraftApp, [u64; 3]) { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({})).unwrap(); + let id = |v: serde_json::Value| v["id"].as_u64().unwrap(); + let rect = id(app.run("shape.rectangle", json!({"x": 10, "y": 200, "width": 40, "height": 40})).unwrap()); + let a = id(app.run("text.create", json!({"x": 10, "y": 20, "text": "a\tb", "area": {"width": 300, "height": 60}})).unwrap()); + let b = id(app.run("text.create", json!({"x": 10, "y": 100, "text": "c\td", "area": {"width": 250, "height": 60}})).unwrap()); + for (text, position) in [(a, 40), (b, 90)] { + app.run("select.set", json!({"ids": [text]})).unwrap(); + app.run("text.tabs.set", json!({"stops": [{"position": position}]})).unwrap(); + } + app.run("select.set", json!({"ids": []})).unwrap(); + (app, [rect, a, b]) +} + +/// With a rectangle selected first and a text after it, the panel shows the text's stops on its +/// ruler, not the "No text selected" state. +#[test] +fn the_ruler_shows_text_selected_after_an_object_that_is_not_text() { + let (mut app, [rect, a, _]) = mixed_selection_app(); + app.run("select.set", json!({"ids": [rect, a]})).unwrap(); + let (node, stops, span) = current(&app).unwrap(); + assert_eq!(node.id.0, a); + assert_eq!(stops.iter().map(|s| s.position).collect::>(), [40.0]); + assert_eq!(span, 300.0); + let ctx = egui::Context::default(); + assert_eq!(ruler_labels(&ctx, &mut app).first().map(String::as_str), Some("0")); +} + +/// With a group selected first whose text follows a rectangle in it, the panel shows that text's +/// stops, ahead of a text selected after the group. +#[test] +fn the_ruler_shows_text_inside_a_selected_group() { + let (mut app, [rect, a, b]) = mixed_selection_app(); + app.run("select.set", json!({"ids": [rect, b]})).unwrap(); + let group = app.run("object.group", json!({})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [group, a]})).unwrap(); + let (node, stops, span) = current(&app).unwrap(); + assert_eq!(node.id.0, b); + assert_eq!(stops.iter().map(|s| s.position).collect::>(), [90.0]); + assert_eq!(span, 250.0); + let ctx = egui::Context::default(); + assert_eq!(ruler_labels(&ctx, &mut app).first().map(String::as_str), Some("0")); +} + +/// A stop added on the ruler of a mixed selection sets the first text's stops plus the new one on +/// every selected text, and leaves the rectangle as it was. +#[test] +fn a_stop_added_on_a_mixed_selection_sets_every_selected_text() { + let (mut app, [rect, a, b]) = mixed_selection_app(); + let shape = |app: &VectorcraftApp| app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(rect)).unwrap().clone(); + let before = shape(&app); + app.run("select.set", json!({"ids": [rect, a, b]})).unwrap(); + let ctx = egui::Context::default(); + drag_on_ruler(&ctx, &mut app, 60.0, 60.0, false); + for text in [a, b] { + assert_eq!(text_of(&app, text).para_at(0).tabs.iter().map(|s| s.position).collect::>(), [40.0, 60.0], "text {text}"); + } + assert_eq!(shape(&app), before); +} + +/// A selection without text keeps the "No text selected" state and draws no ruler. +#[test] +fn a_selection_without_text_shows_no_ruler() { + let (mut app, [rect, ..]) = mixed_selection_app(); + let id = app.run("shape.rectangle", json!({"x": 100, "y": 200, "width": 40, "height": 40})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [rect, id]})).unwrap(); + let group = app.run("object.group", json!({})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [group]})).unwrap(); + assert!(current(&app).is_none()); + let ctx = egui::Context::default(); + assert!(ruler_labels(&ctx, &mut app).is_empty()); + assert!(crate::tests_labels::painted_text(&mut app, show).contains("No text selected")); +} + /// In vertical type the Left and Right alignment buttons are named Top-Justified Tab and /// Bottom-Justified Tab, in their tool tips and for screen readers, and the position field is /// labeled Y. Horizontal type keeps Left-Justified Tab, Right-Justified Tab and X. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f04ee3c910..9f590f4055 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1288,6 +1288,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur With Snap to Unit off and Shift not held, a tab stop placed by a click on the Tabs panel's ruler or dragged on it lands on the nearest whole point. A position typed in the X or Y field keeps its hundredths of a point. The Tabs ruler's upper first-line marker and lower left-indent marker show absolute positions and set paragraph indents (`text.setFormat`). Dragging the lower marker keeps the upper position, while Ctrl-dragging it (Command on macOS) moves both; marker drags snap like tab stops, and each release is one undo step. With differing left indents, only the upper marker is shown and its absolute target applies to every touched paragraph. When a drag on the Tabs panel's ruler or a value typed in its X field moves a tab stop past another stop, the moved stop stays selected. + With the Selection tool, the Tabs panel shows the ruler and stops of the first paragraph of the first selected text object, also when the text is inside a selected group or a shape is selected before it; a selection without text shows "No text selected". A stop set on that ruler is set on every selected text object and the text in selected groups, and other objects are left as they were. This is VectorCraft's own rule. Tests `panels::tabs::tests::the_ruler_shows_text_selected_after_an_object_that_is_not_text`, `the_ruler_shows_text_inside_a_selected_group`, `a_stop_added_on_a_mixed_selection_sets_every_selected_text` and `a_selection_without_text_shows_no_ruler`. The Tabs panel menu's Clear All Tabs (`text.tabs.clear`), Delete Tab and Repeat Tab (`text.tabs.set`) can be chosen while the panel's ruler shows tab stops. Delete Tab removes the stop selected on the ruler. Repeat Tab replaces the stops after the selected stop with up to 20 copies of it. The copies are spaced by the selected stop's distance from the stop before it, or from the paragraph's left indent (18 pt further in for each list level past the first) when it is the first stop, and no copy is placed at 2,000 pt or beyond. Clear All Tabs removes every stop, so the default stops every ½ inch apply again. - **Interface languages, vertical type:** Preferences ▸ User Interface (or VectorCraft ▸ Language on macOS) picks Automatic (the system locale) or a registered language, persisted as `interfaceLanguage`. Translations come from per-language catalogs (`i18n/*.tsv`): Traditional and Simplified Chinese, Japanese, German (every `de-*` locale), Spanish (neutral international Spanish, for every `es-*` locale), French (every `fr-*` locale), Italian (every `it-*` locale), Russian (every `ru-*` locale) and Ukrainian (every `uk-*` locale), Catalan (every `ca-*` locale) and Polish (every `pl-*` locale; AI-drafted, native review pending) cover the whole interface, Czech every menu label; Czech, German, Greek, Spanish, French, Hungarian, Italian, Japanese, Korean, Vietnamese, Polish, Brazilian Portuguese, Russian, Simplified Chinese, Traditional Chinese, Swedish, Ukrainian and Finnish also translate status-bar and error messages as they are shown (`@msg` templates, every message literal tested; the messages themselves stay English for agents); untranslated text stays English. Japanese and Chinese glyphs come from the craft-fonts build input (release builds) or the installed fonts, Czech, German, Spanish, French, Italian, Russian and Ukrainian ones from the bundled UI fonts. The web app follows the browser's languages (or `?lang=`). The Basic toolbar's Type button holds Vertical Type in its flyout. Vertical Type, Vertical Area Type and Vertical Type on a Path create vertical text (columns right to left, upright CJK glyphs and marks with `vert` alternates, Latin and longer numbers on their side, two- and three-digit numbers set as tate-chu-yoko in one em of the column (kept whole when justified), upright glyphs centred on the column (tracked or justified too), point type's anchor on the first column's centre line; on a vertical path, upright glyphs and tate-chu-yoko blocks face the path's start, and letters on their side are a quarter turn clockwise from them (with Skew, 3D Ribbon and Stair Step only on a path that runs to the right), in one column that Align to Path Baseline or Center centers on the path and that the caret and selection span); kinsoku applies to horizontal and vertical Japanese (Paragraph panel › Kinsoku Set, `text.setFormat {kinsoku}`: Hard, the default, keeps closing marks, iteration marks, the prolonged sound mark and small kana off the line start and opening brackets off its end; Soft lets 々, ー and small kana start a line as JLREQ's level 3 rules do; None turns it off), and justified Japanese lines spread their room between characters (not inside Latin words); Paragraph panel › Mojikumi Set (shown with Preferences › Type › Show East Asian Options, `text.setFormat {mojikumi}`): None or Line-end Punctuation Half Width (new type's default, as in Illustrator; older documents and imported text keep None) shares one half-em space between consecutive punctuation, sets a closing mark ending a line half width and an opening bracket starting a line flush with its start (a paragraph's first line at its first-line indent, JIS X 4051's principle in JLREQ 3.1.5), and puts a quarter em between Japanese and Latin letters or digits; Paragraph panel menu › Top-to-Top / Bottom-to-Bottom Leading measures leading from em box top to top (area type's first line touches the frame) or from baseline to baseline (new type in a Japanese interface starts top to top, with em box centre character alignment, #432); Paragraph panel menu › Burasagari None / Regular / Force (`text.setFormat {burasagari: "none"|"standard"|"forced"}`) hangs an East Asian comma or full stop (、。,.、。) ending an area type line outside it, Regular (new type's default) when it doesn't fit and Force always (the rest of the line then fills the measure; closing brackets and Latin punctuation don't hang); Character panel menu › Character Alignment (with the East Asian options; `text.setFormat` or `text.setRangeStyle {charAlign}`) lines characters smaller than the largest on their line up on the Roman baseline, the em box top/right, centre or bottom/left, or the ICF (ideographic character face) top/right or bottom/left, from the font's BASE table or, without one, the average ink box of some ideographs and kana; Proportional Metrics (the same menu; `{proportionalMetrics}`) sets full-width glyphs on the font's proportional widths (OpenType `palt`) in horizontal type and upright glyphs on its proportional heights (`vpal`, shaped top to bottom; fonts without vertical metrics keep their cells) in vertical type, and Line-end Punctuation Half Width takes nothing more off the punctuation they re-spaced; Type ▸ Type Orientation switches existing text; caret, selection, hit testing and arrow keys follow the writing direction. Vertical text exports to PDF as real text and to SVG as outlines. The interface is available in Polish (`pl`): menus, panels, dialogs and messages, with one/few/many plurals; AI-drafted, native review pending (#1498). With Line-end Punctuation Half Width, both composers measure a line with its last character set as narrow as Mojikumi sets it ([the help page](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/use-mojikumi-for-japanese-text-composition.html)): a closing bracket, comma or full stop that fits at half width ends the line, and the character before it no longer goes to the next line with it. A mark that already lost its half to the punctuation after it and a line that ends in a hyphen take nothing more off, and the quarter em between Japanese and Latin text counts only where the line ends there. Kinsoku Shori Type and Burasagari Regular measure lines the same way; right-to-left lines and Mojikumi None break as before. In a frame that is not a rectangle, or with text wrap, a line's first word is measured as it is set (an opening bracket at its start flush, its last character narrowed) when layout looks for a line wide enough for it, and it ends only where the line may break, so kinsoku keeps an opening bracket with the character after it and a No Break run counts whole (`crates/text/src/layout/wrapping_tests.rs`, `crates/text/src/tests/vertical.rs`). Scores and estimates are unchanged. From 39f66f3870a9b766b0ad03a266ed6c040dbdd942 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 04:33:49 -0800 Subject: [PATCH 04/25] Effects: a later painted effect runs on every fill and stroke a piece returns When a painted live effect on a fill or stroke returned several fills or strokes, the next effect in that stack ran only on the first of them and the others took its geometry. A later live-effect plug-in, and a later geometry effect on strokes, now runs once on each of them in paint order, given the piece's fills and strokes and its own `_context.item`. Each run's pieces replace only that fill or stroke; a run that fails, is refused, is deferred or would pass the effects' budget leaves only its own fill or stroke as it was. Fills and strokes that keep the same path stay on one path, and a deferred run is listed at the source fill's or stroke's place. The results that are kept share the effects' budget, and each run's result is kept or left out whole. They are first placed with all the room the art leaves, and placed again with room kept for the piece's path when a fill or stroke left on that path finds no room. A result on the path before it costs nothing and is taken whatever room is left; a built-in effect that finds no room is built again with all the room the art leaves, and that result is taken only when it is on the path before it. A plug-in result is held only while it is placed: one that does not fit, or that moves onto the path before it, is let go at once, so the results held at one time stay within the budget however many fills and strokes the piece has. A result kept in the first placing is reused in the second without running the plug-in again. A painted piece's share of the budget is counted once at each later effect. --- Cargo.lock | 1 + crates/effects/Cargo.toml | 2 + crates/effects/src/reshape.rs | 416 ++++++++++++++++++++++++---- crates/effects/src/tests.rs | 1 + crates/effects/src/tests/painted.rs | 270 ++++++++++++++++++ crates/engine/src/tests/plugins.rs | 296 +++++++++++++++++++- crates/plugins/src/wat.rs | 27 +- docs/plugins.md | 5 + docs/target-app-parity.md | 1 + 9 files changed, 944 insertions(+), 75 deletions(-) create mode 100644 crates/effects/src/tests/painted.rs diff --git a/Cargo.lock b/Cargo.lock index ce5569cde9..0c34a6a952 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6477,6 +6477,7 @@ dependencies = [ "vectorcraft-text", "vectorcraft-three-d", "vectorcraft-trace", + "wat", ] [[package]] diff --git a/crates/effects/Cargo.toml b/crates/effects/Cargo.toml index 14f9a0d08f..6d58ad9d74 100644 --- a/crates/effects/Cargo.toml +++ b/crates/effects/Cargo.toml @@ -29,3 +29,5 @@ serde_json = { workspace = true } vectorcraft-color = { workspace = true } # A face built in code from the bundled Source Sans 3 (no font file is committed). vectorcraft-text = { workspace = true, features = ["test-fonts"] } +# Test live-effect plug-ins written in WebAssembly text. +wat = { workspace = true } diff --git a/crates/effects/src/reshape.rs b/crates/effects/src/reshape.rs index 2bda0aa88f..c2f1c1c466 100644 --- a/crates/effects/src/reshape.rs +++ b/crates/effects/src/reshape.rs @@ -1858,22 +1858,30 @@ fn paint_leaf( /// effects' budget for the object it becomes, so that a budget of [`Budget::EFFECTS`] holds at most /// [`MAX_OBJECTS`](vectorcraft_plugins::objects::MAX_OBJECTS) pieces however small their paths. fn piece_cost(path: &PathData) -> Budget { + Budget::of(path).plus(piece_share()) +} + +/// The share of the effects' budget each painted piece costs besides its path ([`piece_cost`]). +fn piece_share() -> Budget { let max = vectorcraft_plugins::objects::MAX_OBJECTS; - Budget::of(path).plus(Budget { anchors: Budget::EFFECTS.anchors / max, lines: Budget::EFFECTS.lines / max }) + Budget { anchors: Budget::EFFECTS.anchors / max, lines: Budget::EFFECTS.lines / max } } /// Live-effect plug-in `plugin` (one that paints what it returns) with `params`, a later effect of -/// `item`, run on `leaf`, a path of [`transform_piece`] painted by copies of `item`, with reference -/// box `bounds`: `leaf` becomes a group of one path for each piece returned, in order. A piece that -/// gives fills (on a fill) or strokes (on a stroke) is painted by copies of `item`, the leaf's first -/// fill or stroke, with those paints ([`vectorcraft_plugins::painted::items`]), under the leaf's -/// other fills and strokes; one that gives none keeps the leaf's. Returns +/// `item`, run on `leaf`, a path of [`transform_piece`] painted by `item` (its first fill or stroke), +/// with reference box `bounds`: `leaf` becomes a group of one path for each piece returned, in +/// order. The plug-in is given `appearance`'s fills and strokes and told that it is on item `index` +/// of them. A piece that gives fills (on a fill) or strokes (on a stroke) is painted by copies of +/// `item` with those paints ([`vectorcraft_plugins::painted::items`]), under the leaf's other fills +/// and strokes; one that gives none keeps the leaf's. Returns /// what the paths cost ([`piece_cost`]); `None` (the leaf stays as it is) when the plug-in fails, /// the pieces are refused (a swatch or pattern not in `doc`, or any without one), or they would pass /// `budget`. A deferred run is listed by `at`. +#[allow(clippy::too_many_arguments)] fn paint_piece( leaf: &mut Node, item: &AppearanceItem, + (appearance, index): (&Appearance, usize), (plugin, params): (&str, &serde_json::Value), bounds: Rect, budget: Budget, @@ -1881,7 +1889,7 @@ fn paint_piece( at: Option, ) -> Option { let (path, rule) = leaf_geometry(leaf)?; - let paints = vectorcraft_plugins::effect::Paints { appearance: Some(&leaf.appearance), item: Some(0), at }; + let paints = vectorcraft_plugins::effect::Paints { appearance: Some(appearance), item: Some(index), at }; let pieces = vectorcraft_plugins::effect::apply_painted(plugin, params, &path, bounds, rule, paints, doc)?; let made = pieces.iter().map(|p| piece_cost(&p.path)).fold(Budget { anchors: 0, lines: 0 }, Budget::plus); if !budget.fits(made) { @@ -2050,7 +2058,7 @@ fn transform_item_leaf(leaf: &mut Node, max: Budget, used: &mut Budget, doc: Opt group.push(Arc::new(p)); } let mut p = Node::group(leaf.id, group); - transform_piece(&mut p, (ctx.seed, i, &kept), crate::raster::held_back(before), limit, used, doc); + transform_piece(&mut p, (ctx.seed, i, &kept), crate::raster::held_back(before), true, limit, used, doc); pieces.push(Arc::new(p)); continue; } @@ -2073,7 +2081,7 @@ fn transform_item_leaf(leaf: &mut Node, max: Budget, used: &mut Budget, doc: Opt if moved && !held_later { follow_piece(&mut p, kept_before.get(from..).unwrap_or_default(), from, &fx[at]); } - transform_piece(&mut p, (ctx.seed, i, &kept), crate::raster::held_back(&fx[..=at]), limit, used, doc); + transform_piece(&mut p, (ctx.seed, i, &kept), crate::raster::held_back(&fx[..=at]), false, limit, used, doc); pieces.push(Arc::new(p)); } if !plain.is_empty() { @@ -2086,7 +2094,7 @@ fn transform_item_leaf(leaf: &mut Node, max: Budget, used: &mut Budget, doc: Opt leaf.kind = NodeKind::Group { children: pieces, clip: false }; } -/// Apply the visible geometry effects left on the one fill or stroke of each path under `p` (a +/// Apply the visible geometry effects left on the fills or strokes of each path under `p` (a /// transformed piece of [`transform_item_leaf`] and its copies) to all of `p`'s paths as one piece: /// each effect takes the bounds of all the paths as its reference box and `seed`, as an object's /// own effects reshape all its paths ([`reshape_leaves_carrying`]). Each path applies its own copy of @@ -2095,19 +2103,32 @@ fn transform_item_leaf(leaf: &mut Node, max: Budget, used: &mut Budget, doc: Opt /// the effects after it, and with Transform Objects off those before it, as they are /// ([`keep_listed`]). /// A live-effect plug-in that paints what it returns ([`painted_plugin`]) makes each path one path -/// for each piece it returns ([`paint_piece`]). The raster effects before a Transform effect -/// follow it ([`follow_piece`]), except the first `held` effects, which a Transform effect before -/// the piece's effects that makes copies or moves at random holds back, and the effects before -/// such a Transform effect among the piece's effects. The geometry effects then +/// for each piece it returns ([`paint_piece`]). A path with several fills or strokes (those a +/// painted plug-in returned) takes such an effect, a live-effect plug-in or a geometry effect on +/// strokes once for each of them, in paint order, given its own place among them +/// ([`shares_stage`]): each run's pieces replace only that fill or stroke, and a run that fails or +/// would pass the budget leaves that fill or stroke on the path as it was. The raster effects +/// before a Transform effect follow it ([`follow_piece`]), except the first `held` effects, which +/// a Transform effect before the piece's effects that makes copies or moves at random holds back, +/// and the effects before such a Transform effect among the piece's effects. The geometry effects then /// leave the fills and strokes; their other effects stay. The paths keep to `max` together with /// the rest of the art (`used`), and the swatches and patterns painted pieces name must be in /// `doc`. `(seed, source, kept)`: the object's seed, the index in the object's appearance of the /// fill or stroke the piece was made from, and the index among that item's effects of each effect -/// the piece kept, which a deferred live-effect plug-in is listed by. -fn transform_piece(p: &mut Node, (seed, source, kept): (u64, usize, &[usize]), held: usize, max: Budget, used: &mut Budget, doc: Option<&Document>) { +/// the piece kept, which a deferred live-effect plug-in is listed by. `painted`: `p`'s paths are +/// the pieces of a painted run, each of which `used` counts at [`piece_cost`]. +fn transform_piece( + p: &mut Node, + (seed, source, kept): (u64, usize, &[usize]), + held: usize, + painted: bool, + max: Budget, + used: &mut Budget, + doc: Option<&Document>, +) { let mut count = 0; for_each_leaf(p, &mut |l| { - if let Some(item) = l.appearance.items.first() { + for item in &l.appearance.items { count = count.max(item.effects().len()); } }); @@ -2115,60 +2136,207 @@ fn transform_piece(p: &mut Node, (seed, source, kept): (u64, usize, &[usize]), h // random are held back from the Transform effects before it too. let mut held = held; for_each_leaf(p, &mut |l| { - if let Some(last) = l.appearance.items.first().and_then(|item| item.effects().iter().rposition(crate::raster::holds_back)) { - held = held.max(last); + for item in &l.appearance.items { + if let Some(last) = item.effects().iter().rposition(crate::raster::holds_back) { + held = held.max(last); + } } }); + // Whether `used` counts each path under `p`, in the order `for_each_leaf` visits them, at + // [`piece_cost`] (its geometry and a painted piece's share) rather than at its geometry alone. + // The pieces of a painted run are counted so, and so is the first path an effect makes of one + // that was: the paths of a Transform effect's copies share their original's share. + let mut shares = vec![painted; leaf_count(p)]; for j in 0..count { let Some(bounds) = p.geometric_bounds() else { break }; let from = held.min(j); let mut holds = false; - for_each_leaf(p, &mut |leaf| { - let Some(item) = leaf.appearance.items.first().cloned() else { return }; - let Some(e) = item.effects().get(j).filter(|e| e.visible && is_geometry(&e.id)).cloned() else { return }; - holds |= crate::raster::holds_back(&e); - // The effects before this one as they were before it moved the path. - let was = item.effects().get(from..j).unwrap_or_default(); - let Some((path, rule)) = leaf_geometry(leaf) else { return }; - // What the other paths leave of the budget. - let before = Budget::of(&path); - let room = max.minus(used.minus(before)); - let stage = vectorcraft_plugins::deferred::Stage { object: seed, effect: kept.get(j).copied().unwrap_or(j), item: Some(source) }; - if let Some(plugin) = painted_plugin(&e) { - if let Some(made) = paint_piece(leaf, &item, (plugin, &merged_params(&e.id, &e.params)), bounds, room, doc, Some(stage)) { - *used = used.minus(before).plus(made); - } - return; - } - if reaches_appearance(&e) { - let params = merged_params(&e.id, &e.params); - let (_, copies) = crate::distort::transform_map(bounds, ¶ms, seed); - let options = crate::distort::TransformOptions::of(¶ms); - let map = crate::distort::transform_affine(bounds, ¶ms, seed); - let keep = |k: usize| k > j || (k < j && !options.objects); - let (made, moved) = transform_leaf(leaf, &path, map, copies, options, room, false, Some((item.effects(), &keep))); + let stage = vectorcraft_plugins::deferred::Stage { object: seed, effect: kept.get(j).copied().unwrap_or(j), item: Some(source) }; + let at = PieceStage { j, from, seed, bounds, doc, stage }; + // Stage `j` on `leaf`, a path `used` counts at `piece_cost` when `share`: whether `used` + // counts each path it became so, or `None` when it stays as it was. + let mut on_leaf = |leaf: &mut Node, share: bool| -> Option> { + let effect = |item: &AppearanceItem| item.effects().get(j).filter(|e| e.visible && is_geometry(&e.id)).cloned(); + let items = &leaf.appearance.items; + let first = items.first()?; + let (path, _) = leaf_geometry(leaf)?; + // What `used` counts the path at; what the other paths leave of the budget is the rest. + let geometry = Budget::of(&path); + let counted = if share { piece_cost(&path) } else { geometry }; + if shares_stage(items, j) { + let e = effect(first)?; + holds |= crate::raster::holds_back(&e); + let appearance = leaf.appearance.clone(); + // A painted run's pieces each cost a share of their own ([`paint_piece`]); the + // paths of any other effect keep the leaf's. + let painted = painted_plugin(&e).is_some(); + let before = if painted { counted } else { geometry }; + let room = max.minus(used.minus(before)); + let made = piece_stage(leaf, &e, &at, (&appearance, 0), room)?; *used = used.minus(before).plus(made); - if moved { - follow_piece(leaf, was, from, &e); - } - return; + return Some((0..leaf_count(leaf)).map(|k| painted || (share && k == 0)).collect()); } + // Each fill or stroke takes the effect on its own path, given the leaf's fills and + // strokes and its own place among them; those left with the same path as the one + // before them stay on it. Each path costs its geometry and a painted piece's share. + // Each run is first given all the room the art leaves. When a fill or stroke that keeps + // the leaf's path then finds no room for its copy of it, the results are placed again, + // each but the last leaving room for one more copy of the leaf's own path; a result + // that does not fit that room is left out. Only a fill or stroke that keeps the leaf's + // path right after one that changed costs such a copy (the ones after it stay on that + // copy), so every copy fits but the first fill's or stroke's, when the art leaves no + // room for it: the leaf then stays as it was. A live-effect plug-in is given all the + // room the art leaves, and each placing checks that its result fits; a built-in effect + // builds within the room of each placing. let appearance = leaf.appearance.clone(); - let stroke = match &item { - AppearanceItem::Stroke(s) => Some(s), - AppearanceItem::Fill(_) => None, + let one = piece_cost(&path); + let n = appearance.items.len(); + let base = used.minus(counted); + let alone = |item: &AppearanceItem| { + let mut sub = leaf.clone(); + sub.appearance.items = vec![item.clone()]; + sub }; - let ctx = GeomContext { stroke, rule, seed, appearance: Some(&appearance), item: Some(0), doc, stage: Some(stage) }; - let mut carry = crate::Carry::default(); - let out = crate::geometry::apply_geometry_carrying_within(std::slice::from_ref(&e), &path, bounds, &ctx, room, Some(&mut carry)); - *used = used.minus(before).plus(Budget::of(&out)); - // The fill's or stroke's gradient follows the effect as the object's does. - if carry.moves(&leaf.appearance) { - carry.apply(&mut leaf.appearance); - } - set_geometry(leaf, out, rule); - follow_piece(leaf, was, from, &e); + // `item`, the `k`th fill or stroke, alone on the leaf's path with effect `e` applied + // within `room`, and what its paths cost; `None` when it failed or found no room. + let apply = |item: &AppearanceItem, k: usize, e: &Effect, room: Budget| { + let painted = painted_plugin(e).is_some(); + let room = if painted { room } else { room.minus(piece_share()) }; + let mut sub = alone(item); + let made = piece_stage(&mut sub, e, &at, (&appearance, k), room)?; + Some((sub, if painted { made } else { made.plus(piece_share()) })) + }; + // Each fill's or stroke's live-effect plug-in run. A result is kept only while a + // placing places it on a path of its own; one that does not fit is dropped, with what + // it cost, and the plug-in runs again in the second placing only when that much room + // is left there (a result small enough to cache comes back from the cache). A result + // with the same path as the one before it costs nothing: it is placed on that path + // whatever room is left, and dropped once its fill or stroke is moved there. The + // results kept at once cost at most what the two placings place. + let mut runs: Vec = vec![PluginRun::Not; n]; + let mut kept_cost = Budget { anchors: 0, lines: 0 }; + // Each placing gives the paths, whether `used` counts each of the paths they hold at + // `piece_cost` (all of a painted run's, and the first of any other result's), and what + // the art then spends. + let mut split = |reserve: bool| -> Option<(Vec, Vec, Budget)> { + let mut spent = base; + let mut out: Vec = vec![]; + let mut counts: Vec = vec![]; + for (k, (item, ran)) in appearance.items.iter().zip(runs.iter_mut()).enumerate() { + let room = if reserve && k + 1 < n { max.minus(spent).minus(one) } else { max.minus(spent) }; + let e = effect(item); + let paints = e.as_ref().is_some_and(|e| painted_plugin(e).is_some()); + // Does `sub` stay on the path of the result before it, at no cost? + let merges = |sub: &Node| out.last().is_some_and(|last| same_path(last, sub)); + // What the kept plug-in result this fill or stroke takes cost. + let mut taken = None; + let result = match e { + None => None, + Some(e) => { + holds |= crate::raster::holds_back(&e); + if vectorcraft_plugins::effect::plugin_id(&e.id).is_some() { + let again = match ran { + PluginRun::Not | PluginRun::Merged => true, + PluginRun::Left(cost) => room.fits(*cost), + PluginRun::Kept(..) | PluginRun::Failed => false, + }; + if again { + #[cfg(test)] + PLUGIN_RUNS.with(|n| n.set(n.get() + 1)); + *ran = match apply(item, k, &e, max.minus(base)) { + None => PluginRun::Failed, + Some((sub, cost)) if !room.fits(cost) && !merges(&sub) => PluginRun::Left(cost), + Some((sub, cost)) => { + kept_cost = kept_cost.plus(cost); + PluginRun::Kept(sub, cost) + } + }; + } + match ran { + PluginRun::Kept(sub, cost) if room.fits(*cost) || merges(sub) => { + taken = Some(*cost); + Some((sub.clone(), *cost)) + } + PluginRun::Kept(_, cost) => { + let cost = *cost; + kept_cost = kept_cost.minus(cost); + *ran = PluginRun::Left(cost); + None + } + PluginRun::Not | PluginRun::Merged | PluginRun::Left(_) | PluginRun::Failed => None, + } + } else { + // A built-in effect that finds no room within `room` leaves the + // leaf's path. When its result is not on the path before it, it + // is built again with all the room the art leaves and taken only + // when that result is on the path before it, which costs nothing. + let made = apply(item, k, &e, room); + let short = match &made { + None => true, + Some((sub, cost)) => !merges(sub) && (!room.fits(*cost) || same_path(sub, leaf)), + }; + match out.last() { + Some(_) if short => match apply(item, k, &e, max.minus(base)) { + Some((sub, cost)) if merges(&sub) => Some((sub, cost)), + _ => made, + }, + _ => made, + } + } + } + }; + let placed = match result { + Some((sub, cost)) if room.fits(cost) || merges(&sub) => Some((sub, cost, paints)), + _ => None, + }; + // A fill or stroke whose result is not placed stays on the leaf's path, which + // is copied only when the path before it is another. + let (mut sub, cost, all) = match placed { + Some(placed) => placed, + None => match out.last_mut() { + Some(last) if same_path(last, leaf) => { + last.appearance.items.push(item.clone()); + continue; + } + _ => (alone(item), one, true), + }, + }; + match out.last_mut() { + Some(last) if same_path(last, &sub) => { + last.appearance.items.append(&mut sub.appearance.items); + if let Some(cost) = taken { + kept_cost = kept_cost.minus(cost); + *ran = PluginRun::Merged; + } + } + _ if !max.minus(spent).fits(cost) => return None, + _ => { + spent = spent.plus(cost); + counts.extend((0..leaf_count(&sub)).map(|k| all || k == 0)); + out.push(sub); + } + } + #[cfg(test)] + HELD_PEAK.with(|p| p.set(p.get().at_least(kept_cost))); + } + Some((out, counts, spent)) + }; + let (mut out, counts, spent) = split(false).or_else(|| split(true))?; + *used = spent; + *leaf = match out.len() { + 1 => out.pop().unwrap_or_else(|| leaf.clone()), + _ => Node::group(leaf.id, out.into_iter().map(Arc::new).collect()), + }; + Some(counts) + }; + let mut next: Vec = vec![]; + let mut visited = 0; + for_each_leaf(p, &mut |leaf| { + let share = shares.get(visited).copied().unwrap_or(false); + visited += 1; + next.extend(on_leaf(leaf, share).unwrap_or_else(|| vec![share])); }); + shares = next; if holds { held = held.max(j); } @@ -2180,6 +2348,134 @@ fn transform_piece(p: &mut Node, (seed, source, kept): (u64, usize, &[usize]), h }); } +/// A fill's or stroke's live-effect plug-in run in a placing of [`transform_piece`]: not run yet, +/// its result and what that costs while a placing places it on a path of its own, what a result +/// that did not fit cost (the result itself is dropped), a result dropped once its fill or stroke +/// was placed on the path before it, or failed. +#[derive(Clone)] +enum PluginRun { + Not, + Kept(Node, Budget), + Left(Budget), + Merged, + Failed, +} + +#[cfg(test)] +thread_local! { + /// The most the live-effect plug-in results [`transform_piece`] keeps from one fill or stroke + /// to the next have cost at once on this thread. + pub(crate) static HELD_PEAK: std::cell::Cell = const { std::cell::Cell::new(Budget { anchors: 0, lines: 0 }) }; + /// How many times [`transform_piece`] has run a fill's or stroke's live-effect plug-in on this + /// thread when they did not share the stage. + pub(crate) static PLUGIN_RUNS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// Where a stage of [`transform_piece`] runs: `j`, the index of its effect among the piece's +/// effects; `from`, the first of the effects before it whose raster effects follow a Transform +/// effect; the object's `seed`; the reference box `bounds` of all the piece's paths; the document +/// that painted pieces' swatches and patterns must be in; and the `stage` a deferred live-effect +/// plug-in is listed by. +struct PieceStage<'a> { + j: usize, + from: usize, + seed: u64, + bounds: Rect, + doc: Option<&'a Document>, + stage: vectorcraft_plugins::deferred::Stage, +} + +/// Can stage `j` of [`transform_piece`] run once for all of a path's `items`: there is at most one, +/// or they hold the same effects and the effect at `j` is not a visible geometry effect, is a +/// Transform effect, or is a built-in geometry effect and they are all fills (an effect that +/// changes a fill's path does not depend on which fill it is on)? +fn shares_stage(items: &[AppearanceItem], j: usize) -> bool { + let Some(first) = items.first() else { return true }; + if items.len() == 1 { + return true; + } + if !items.iter().all(|i| i.effects() == first.effects()) { + return false; + } + match first.effects().get(j) { + Some(e) if e.visible && is_geometry(&e.id) => { + vectorcraft_plugins::effect::plugin_id(&e.id).is_none() && (reaches_appearance(e) || items.iter().all(AppearanceItem::is_fill)) + } + _ => true, + } +} + +/// Effect `e`, a visible geometry effect at stage `at` of [`transform_piece`], applied to `leaf`, a +/// path painted by its first fill or stroke (and, when they share the stage, [`shares_stage`], the +/// others): `appearance` is what the effect is given of the path's fills and strokes and `index` +/// which of them it is on. A live-effect plug-in that paints what it returns makes `leaf` a group +/// of its pieces ([`paint_piece`]), and a Transform effect that reaches its appearance transforms +/// it ([`transform_leaf`]). Returns what the new paths cost, within `room`; `None` when `leaf` +/// stays as it is. +fn piece_stage(leaf: &mut Node, e: &Effect, at: &PieceStage, (appearance, index): (&Appearance, usize), room: Budget) -> Option { + let item = leaf.appearance.items.first()?.clone(); + // The effects before this one as they were before it moved the path. + let was = item.effects().get(at.from..at.j).unwrap_or_default(); + let (path, rule) = leaf_geometry(leaf)?; + if let Some(plugin) = painted_plugin(e) { + let params = merged_params(&e.id, &e.params); + return paint_piece(leaf, &item, (appearance, index), (plugin, ¶ms), at.bounds, room, at.doc, Some(at.stage)); + } + if reaches_appearance(e) { + let params = merged_params(&e.id, &e.params); + let (_, copies) = crate::distort::transform_map(at.bounds, ¶ms, at.seed); + let options = crate::distort::TransformOptions::of(¶ms); + let map = crate::distort::transform_affine(at.bounds, ¶ms, at.seed); + let j = at.j; + let keep = |k: usize| k > j || (k < j && !options.objects); + let (made, moved) = transform_leaf(leaf, &path, map, copies, options, room, false, Some((item.effects(), &keep))); + if moved { + follow_piece(leaf, was, at.from, e); + } + return Some(made); + } + let stroke = match &item { + AppearanceItem::Stroke(s) => Some(s), + AppearanceItem::Fill(_) => None, + }; + let ctx = GeomContext { stroke, rule, seed: at.seed, appearance: Some(appearance), item: Some(index), doc: at.doc, stage: Some(at.stage) }; + let mut carry = crate::Carry::default(); + let out = crate::geometry::apply_geometry_carrying_within(std::slice::from_ref(e), &path, at.bounds, &ctx, room, Some(&mut carry)); + let made = Budget::of(&out); + // The fill's or stroke's gradient follows the effect as the object's does. + if carry.moves(&leaf.appearance) { + carry.apply(&mut leaf.appearance); + } + set_geometry(leaf, out, rule); + follow_piece(leaf, was, at.from, e); + Some(made) +} + +/// Are `a` and `b` paths or compound paths that differ only in their fills and strokes? +fn same_path(a: &Node, b: &Node) -> bool { + let leaf = |n: &Node| matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }); + if !leaf(a) || !leaf(b) { + return false; + } + // Every field but the fills and strokes, compared in place; the geometry last. + let Node { id, name, visible, locked, opacity, blend, isolate, knockout, knockout_shape, appearance, kind, bbox_angle, extras } = a; + let Appearance { items: _, effects, contents_index } = &**appearance; + *id == b.id + && *name == b.name + && *visible == b.visible + && *locked == b.locked + && *opacity == b.opacity + && *blend == b.blend + && *isolate == b.isolate + && *knockout == b.knockout + && *knockout_shape == b.knockout_shape + && *bbox_angle == b.bbox_angle + && *extras == b.extras + && *effects == b.appearance.effects + && *contents_index == b.appearance.contents_index + && *kind == b.kind +} + /// The effects a Transform effect in a fill's or stroke's own list leaves as they were /// ([`keep_listed`]): the list as it was before the Transform effect was applied, and which of its /// indices keep their values. `None` for an object's own Transform effect. diff --git a/crates/effects/src/tests.rs b/crates/effects/src/tests.rs index 56f9d40633..48665539d9 100644 --- a/crates/effects/src/tests.rs +++ b/crates/effects/src/tests.rs @@ -5,6 +5,7 @@ use vectorcraft_geom::{Affine, PathData, Point, Rect, Shape, SubPath, shapes}; use super::*; mod imageoutline; +mod painted; mod rasterfollow; mod scale; mod transformfx; diff --git a/crates/effects/src/tests/painted.rs b/crates/effects/src/tests/painted.rs new file mode 100644 index 0000000000..31dadc865e --- /dev/null +++ b/crates/effects/src/tests/painted.rs @@ -0,0 +1,270 @@ +//! Live-effect plug-ins that paint what they return, run on each fill a painted effect returned. + +use serde_json::json; +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::{Appearance, Effect, Node, NodeId, NodeKind}; +use vectorcraft_geom::{Anchor, PathData, Point, Rect, SubPath, shapes}; +use vectorcraft_plugins::wat as tpl; + +use crate::geometry::Budget; +use crate::reshape; +use crate::reshape::{HELD_PEAK, PLUGIN_RUNS}; + +/// Installs live-effect plug-in `id`, which paints what it returns, replacing one with the same id: +/// its effect returns `output` whatever it is given. +fn install_painting(id: &str, output: &serde_json::Value) { + let manifest = format!(r#"{{"id":"{id}","name":"Test {id}","version":"1","kind":"effect","api":2,"paintOutput":true,"params":{{}}}}"#); + let module = wat::parse_str(tpl::returning(&manifest, &output.to_string())).unwrap(); + vectorcraft_plugins::registry::install_bytes(&module).unwrap(); +} + +/// An open path of `curves` tall curves, each drawn with about 5,200 lines. +fn tall_curves(curves: u32) -> PathData { + let h = 3_000_000.0; + let anchors = (0..=curves) + .map(|i| { + let x = 40.0 + f64::from(i); + Anchor::with_handles(Point::new(x, 0.0), Point::new(x, -h), Point::new(x, h)) + }) + .collect(); + PathData::single(SubPath::new(anchors, false)) +} + +/// Installs live-effect plug-in `id`, which reshapes the path it is given: its effect returns +/// `output` whatever it is given. +fn install_reshaping(id: &str, output: &serde_json::Value) { + let manifest = format!(r#"{{"id":"{id}","name":"Test {id}","version":"1","kind":"effect","params":{{}}}}"#); + let module = wat::parse_str(tpl::returning(&manifest, &output.to_string())).unwrap(); + vectorcraft_plugins::registry::install_bytes(&module).unwrap(); +} + +/// `curves` curves from `x`, each `h` tall at its handles. +fn curves_at(x: f64, curves: u32, h: f64) -> SubPath { + let anchors = (0..=curves) + .map(|i| { + let x = x + f64::from(i); + Anchor::with_handles(Point::new(x, 0.0), Point::new(x, -h), Point::new(x, h)) + }) + .collect(); + SubPath::new(anchors, false) +} + +/// An open path, `dx` to the right of 40, drawn with about `lines` lines: tall curves and one +/// curve that makes up the rest. +fn drawn_with(lines: usize, dx: f64) -> PathData { + let h = 3_000_000.0; + let per = Budget::of(&PathData::single(curves_at(0.0, 1, h))).lines; + let tall = u32::try_from(lines / per).unwrap(); + let rest = lines % per; + let mut subpaths = vec![curves_at(40.0 + dx, tall, h)]; + if rest > 0 { + // A curve `h` tall at its handles is drawn with about √(9h) lines. + let rest = rest as f64; + subpaths.push(curves_at(40.0 + dx + f64::from(tall) + 2.0, 1, rest * rest / 9.0)); + } + PathData::new(subpaths) +} + +/// Stacks a painted effect that returns `first` on a path drawn with about `lines` lines with five +/// later effects on a square's fill, the `k`th returning that path `k` to the right (`later` +/// installs each). Each piece's share of the budget is counted once, so every effect fits, and the +/// art ends on the last effect's path, painted by `paints`. +fn later_effects_count_each_piece_once(name: &str, lines: usize, first: &serde_json::Value, later: fn(&str, &serde_json::Value), paints: &[Paint]) { + let near = drawn_with(lines, 0.0); + let drawn = Budget::of(&near).lines; + assert!(drawn.abs_diff(lines) <= 2, "the path is drawn with {drawn} lines"); + let first_id = format!("test.effects.{name}.first"); + let mut first = first.clone(); + first["objects"][0]["path"] = serde_json::to_value(&near).unwrap(); + install_painting(&first_id, &first); + let mut ids = vec![format!("plugin.{first_id}")]; + for k in 1..=5u8 { + let id = format!("test.effects.{name}.later{k}"); + later(&id, &json!({"objects": [{"path": drawn_with(lines, f64::from(k))}]})); + ids.push(format!("plugin.{id}")); + } + let mut n = + Node::path(NodeId(9), shapes::rectangle(Rect::new(0.0, 0.0, 20.0, 20.0)), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0)); + let fill = n.appearance.items.iter().position(|i| i.is_fill()).unwrap(); + for id in ids { + n.appearance.items[fill].effects_mut().push(Effect { id, params: json!({}), visible: true }); + } + let art = reshape(None, &n, None).unwrap(); + let mut paths = vec![]; + // The path is a compound path of two (the tall curves and the one that makes up the rest). + art.walk(&mut |c| { + let bounds = match &c.kind { + NodeKind::Compound { children, .. } => children.iter().filter_map(|k| k.path_data().and_then(PathData::bounds)).reduce(|a, b| a.union(b)), + _ => c.path_data().and_then(PathData::bounds), + }; + let paints: Vec = c.appearance.items.iter().map(|i| i.paint().clone()).filter(|p| !p.is_none()).collect(); + if bounds.is_some() && !paints.is_empty() { + paths.push((bounds, paints)); + } + }); + assert_eq!(paths, [(drawn_with(lines, 5.0).bounds(), paints.to_vec())]); +} + +/// Later geometry effects on the two fills a painted effect returned run on each fill, and the +/// path they both stay on counts its piece's share of the budget once: each fill's result, drawn +/// with about 200 lines fewer than half the budget allows, fits at every stage. +#[test] +fn later_geometry_effects_on_two_fills_count_the_piece_once() { + let colors = [Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::solid(Color::rgb(0.0, 1.0, 0.0))]; + let fills: Vec<_> = colors.iter().map(|p| serde_json::to_value(p).unwrap()).collect(); + let lines = Budget::EFFECTS.lines / 2 - 200; + later_effects_count_each_piece_once("twofills", lines, &json!({"objects": [{"fills": fills}]}), install_reshaping, &colors); +} + +/// Later painted effects on a painted effect's piece count the piece's share of the budget once: +/// each run's pieces take the place of the piece they were made of, so a result drawn with about +/// 300 lines fewer than the budget allows fits at every stage. +#[test] +fn later_painted_effects_on_a_painted_piece_count_it_once() { + let lines = Budget::EFFECTS.lines - 300; + later_effects_count_each_piece_once("painted", lines, &json!({"objects": [{}]}), install_painting, &[Paint::solid(Color::BLACK)]); +} + +/// A path's bounds and the paints of its fills and strokes. +type PaintedPath = (Option, Vec); + +/// The paths of the art a painted effect `name` that returns `square` with eight fills makes, each +/// path with its paints, when a later effect returns `first` on the first fill and `rest` on the +/// others, painting what it returns when `paints`; and the eight paints. Checks that the plug-in +/// results kept from one fill to the next never cost more than the effects' budget together. +fn eight_fills_then(name: &str, square: &PathData, paints: bool, results: (&PathData, &PathData)) -> (Vec, Vec) { + let (paths, colors, _) = fills_then(name, 8, square, paints, results); + (paths, colors) +} + +/// [`eight_fills_then`] with `n` fills, and how many times the later effect ran on a fill. +fn fills_then(name: &str, n: u8, square: &PathData, paints: bool, (first, rest): (&PathData, &PathData)) -> (Vec, Vec, usize) { + let colors: Vec = (0..n).map(|i| Paint::solid(Color::rgb(f32::from(i) / f32::from(n), 0.0, 0.0))).collect(); + let fills: Vec<_> = colors.iter().map(|p| serde_json::to_value(p).unwrap()).collect(); + let fills_id = format!("test.effects.{name}.fills"); + install_painting(&fills_id, &json!({"objects": [{"path": square, "fills": fills}]})); + let each_id = format!("test.effects.{name}.each"); + let declared = if paints { r#","api":2,"paintOutput":true"# } else { "" }; + let manifest = format!(r#"{{"id":"{each_id}","name":"Test {each_id}","version":"1","kind":"effect"{declared},"params":{{}}}}"#); + let (on_first, on_rest) = (json!({"objects": [{"path": first}]}).to_string(), json!({"objects": [{"path": rest}]}).to_string()); + let module = wat::parse_str(tpl::when_given_else(&manifest, tpl::Given::Params, r#""item":{"fill":0}"#, &on_first, &on_rest)).unwrap(); + vectorcraft_plugins::registry::install_bytes(&module).unwrap(); + let mut n = + Node::path(NodeId(9), shapes::rectangle(Rect::new(0.0, 0.0, 20.0, 20.0)), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0)); + let fill = n.appearance.items.iter().position(|i| i.is_fill()).unwrap(); + for id in [fills_id, each_id] { + n.appearance.items[fill].effects_mut().push(Effect { id: format!("plugin.{id}"), params: json!({}), visible: true }); + } + HELD_PEAK.with(|p| p.set(Budget { anchors: 0, lines: 0 })); + PLUGIN_RUNS.with(|r| r.set(0)); + let art = reshape(None, &n, None).unwrap(); + let runs = PLUGIN_RUNS.with(std::cell::Cell::get); + let mut paths = vec![]; + art.walk(&mut |c| { + if let Some(p) = c.path_data() { + let paints: Vec = c.appearance.items.iter().map(|i| i.paint().clone()).filter(|p| !p.is_none()).collect(); + if !paints.is_empty() { + paths.push((p.bounds(), paints)); + } + } + }); + let peak = HELD_PEAK.with(std::cell::Cell::get); + assert!(Budget::EFFECTS.fits(peak), "the results kept cost {peak:?}"); + (paths, colors, runs) +} + +/// A later painted effect's results on eight fills, each costing more than half the effects' +/// budget and the first fill's on another path than the rest: only the first fill's result fits, +/// the other fills stay together on the square, and the results kept never cost more than the +/// budget together. +#[test] +fn painted_results_that_do_not_fit_are_not_kept() { + let square = shapes::rectangle(Rect::new(40.0, 40.0, 60.0, 60.0)); + let (large, other) = (tall_curves(900), PathData::single(curves_at(3_000.0, 900, 3_000_000.0))); + let (paths, colors) = eight_fills_then("held", &square, true, (&large, &other)); + assert_eq!(paths, [(large.bounds(), colors[..1].to_vec()), (square.bounds(), colors[1..].to_vec())]); +} + +/// A later effect that reshapes each of eight painted fills to the same path, drawn with about a +/// fifth of the effects' budget: the fills share that one path, and the results that move onto it +/// are not kept as well, so what is kept never costs more than the budget. +#[test] +fn results_on_one_path_are_not_kept_for_each_fill() { + let square = shapes::rectangle(Rect::new(40.0, 40.0, 60.0, 60.0)); + let same = tall_curves(300); + let (paths, colors) = eight_fills_then("merged", &square, false, (&same, &same)); + assert_eq!(paths, [(same.bounds(), colors)]); +} + +/// A later effect that reshapes each of eight painted fills to the same path, drawn with more than +/// half the effects' budget: the path costs the art once, so every fill moves onto it, although a +/// second copy of it would not fit. +#[test] +fn results_on_one_path_share_it_near_the_budget() { + let square = shapes::rectangle(Rect::new(40.0, 40.0, 60.0, 60.0)); + let large = tall_curves(900); + let (paths, colors) = eight_fills_then("shared", &square, false, (&large, &large)); + assert_eq!(paths, [(large.bounds(), colors)]); +} + +/// An open path of tall curves `dx` to the right of 40, drawn with about `share` of the effects' +/// budget's lines. +fn drawn_share(share: f64, dx: f64) -> PathData { + let h = 3_000_000.0; + let per = Budget::of(&PathData::single(curves_at(0.0, 1, h))).lines as f64; + let curves = (Budget::EFFECTS.lines as f64 * share / per) as u32; + PathData::single(curves_at(40.0 + dx, curves, h)) +} + +/// A later painted effect runs once on each of three fills although the results are placed twice: +/// a result that fits both placings is kept between them, and one that did not fit in the first is +/// not run again when it does not fit the second either. The first fill's result (a tenth of the +/// budget) and the second's (half of it) fit, the third's (half of it) does not, and the square +/// (45%) left for the third fill then has no room; in the second placing the second fill's result +/// does not fit beside the square kept for the fills after it. +#[test] +fn a_later_plug_in_runs_once_on_each_fill_across_both_placings() { + let (square, first, rest) = (drawn_share(0.45, 0.0), drawn_share(0.1, 2_000.0), drawn_share(0.5, 4_000.0)); + let (paths, colors, runs) = fills_then("once", 3, &square, true, (&first, &rest)); + assert_eq!(paths, [(first.bounds(), colors[..1].to_vec()), (square.bounds(), colors[1..].to_vec())]); + assert_eq!(runs, 3, "the later effect ran {runs} times on three fills"); +} + +/// A built-in geometry effect on two strokes that a painted effect returned, which doubles the lines +/// of a path drawn with 30% of the budget: the second stroke's result does not fit beside the +/// first's, but it is the same path, so it is built again with all the room the art leaves and +/// both strokes are drawn on that one path. +#[test] +fn a_built_in_result_on_the_path_before_it_is_taken_near_the_budget() { + let square = drawn_share(0.3, 0.0); + let transform = json!({"scaleV": 400}); + let tall = crate::distort::transform_within(&square, square.bounds().unwrap(), &transform, 0, usize::MAX); + let (s, t) = (Budget::of(&square).lines, Budget::of(&tall).lines); + let lines = Budget::EFFECTS.lines; + assert!(t > lines / 2 + lines / 20 && t < lines - lines / 20 && s + t < lines, "the paths are drawn with {s} and {t} lines"); + let colors = [Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::solid(Color::rgb(0.0, 1.0, 0.0))]; + let strokes: Vec<_> = colors.iter().map(|p| json!({"paint": p, "width": 1})).collect(); + let id = "test.effects.builtin.strokes"; + install_painting(id, &json!({"objects": [{"path": square, "strokes": strokes}]})); + let mut n = + Node::path(NodeId(9), shapes::rectangle(Rect::new(0.0, 0.0, 20.0, 20.0)), Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0)); + let stroke = n.appearance.items.iter().position(|i| !i.is_fill()).unwrap(); + n.appearance.items[stroke].effects_mut().push(Effect { id: format!("plugin.{id}"), params: json!({}), visible: true }); + n.appearance.items[stroke].effects_mut().push(Effect { id: "distort.transform".into(), params: transform, visible: true }); + let art = reshape(None, &n, None).unwrap(); + let mut paths = vec![]; + art.walk(&mut |c| { + if let Some(p) = c.path_data() { + let paints: Vec = c.appearance.items.iter().map(|i| i.paint().clone()).filter(|p| !p.is_none()).collect(); + if !paints.is_empty() { + paths.push((p.bounds(), paints)); + } + } + }); + // One path, scaled about a reference point of the piece's own, painted by both strokes. + assert_eq!(paths.len(), 1, "{paths:?}"); + let (bounds, paints) = &paths[0]; + assert_eq!(paints, &colors.to_vec()); + let height = |b: Option| b.map_or(0.0, |b| b.height()); + assert!((height(*bounds) - height(tall.bounds())).abs() < 1.0, "{bounds:?} is not {:?} tall", tall.bounds()); +} diff --git a/crates/engine/src/tests/plugins.rs b/crates/engine/src/tests/plugins.rs index cc4460d250..13271f99e4 100644 --- a/crates/engine/src/tests/plugins.rs +++ b/crates/engine/src/tests/plugins.rs @@ -796,30 +796,269 @@ fn expanding_a_pattern_fill_keeps_each_piece_s_own_paint() { assert_eq!(patterns, 0, "the tiles are objects"); } -/// Two painted effects on one fill, the first returning a piece with two fills: the second replaces -/// the first of them and the other fill stays over it. +/// A path's bounds and the paints of its fills and strokes, each stroke with its weight. +type PaintedPath = (Option, Vec<(Paint, Option)>); + +/// The paths of `id`'s reshaped art that paint, in paint order, each with the fills and strokes of +/// it that paint. +fn painted_paths(s: &Session, id: NodeId) -> Vec { + let st = s.doc().unwrap(); + let art = vectorcraft_render::effects::reshape(Some(&st.doc), st.doc.node(id).unwrap(), None).unwrap(); + let mut paths = vec![]; + art.walk(&mut |n| { + if let Some(p) = n.path_data() { + let items: Vec<_> = n + .appearance + .items + .iter() + .map(|i| match i { + vectorcraft_doc::AppearanceItem::Fill(f) => (f.paint.clone(), None), + vectorcraft_doc::AppearanceItem::Stroke(st) => (st.paint.clone(), Some(st.width)), + }) + .filter(|(paint, _)| !paint.is_none()) + .collect(); + if !items.is_empty() { + paths.push((p.bounds(), items)); + } + } + }); + paths +} + +fn paint(hex: &str) -> Paint { + Paint::solid(Color::from_hex(hex).unwrap()) +} + +/// Two painted effects on one fill, the first returning a piece with two fills: the second runs on +/// each of them, told which fill it is on. On the second fill it returns a blue square at 80 pt; on +/// the first it returns a result that is refused, which leaves only that fill, red, on the square at +/// 40 pt. #[test] -fn a_second_painted_effect_on_a_fill_keeps_the_piece_s_other_fills() { +fn a_later_painted_effect_runs_on_every_fill_a_piece_returns() { let mut s = session(); let id = rect(&mut s, 10.0, "#ff0000"); let two = json!({"objects": [{"path": square_at(40.0), "fills": [solid("#ff0000"), solid("#00ff00")]}]}).to_string(); - let one = json!({"objects": [{"path": square_at(40.0), "fills": [solid("#0000ff")]}]}).to_string(); + let blue = json!({"objects": [{"path": square_at(80.0), "fills": [solid("#0000ff")]}]}).to_string(); install_wat(&mut s, &tpl::returning(&painting("test.engine.twofills", true), &two)); - install_wat(&mut s, &tpl::returning(&painting("test.engine.onefill", true), &one)); + install_wat(&mut s, &tpl::when_given(&painting("test.engine.onsecond", true), tpl::Given::Params, r#""item":{"fill":1}"#, &blue)); let fill = node(&s, id).appearance.items.iter().position(|i| i.is_fill()).unwrap(); run(&mut s, "effect.apply", json!({"ids": [id.0], "effect": "plugin.test.engine.twofills", "item": fill})); - run(&mut s, "effect.apply", json!({"ids": [id.0], "effect": "plugin.test.engine.onefill", "item": fill})); - assert_eq!(drawn(&s).pixel(50, 50), GREEN, "the other fill paints over the replaced one"); + run(&mut s, "effect.apply", json!({"ids": [id.0], "effect": "plugin.test.engine.onsecond", "item": fill})); + let img = drawn(&s); + assert_eq!((img.pixel(50, 50), img.pixel(90, 50)), (RED, BLUE), "the first fill as it was, the second moved and blue"); + let (a, b) = (square_at(40.0).bounds(), square_at(80.0).bounds()); + assert_eq!(painted_paths(&s, id), [(a, vec![(paint("#ff0000"), None)]), (b, vec![(paint("#0000ff"), None)])]); + // The same result for both fills: each is replaced. + let one = json!({"objects": [{"path": square_at(40.0), "fills": [solid("#0000ff")]}]}).to_string(); + install_wat(&mut s, &tpl::returning(&painting("test.engine.onsecond", true), &one)); + assert_eq!(painted_paths(&s, id), [(a, vec![(paint("#0000ff"), None)]), (a, vec![(paint("#0000ff"), None)])]); +} + +/// On a stroke, a later painted effect runs on each stroke the first returns, with its own weight +/// and place among them, and keeps their order. +#[test] +fn a_later_painted_effect_runs_on_every_stroke_a_piece_returns() { + let mut s = session(); + let id = rect(&mut s, 10.0, "#ff0000"); + run(&mut s, "paint.setStroke", json!({"ids": [id.0], "color": "#000000"})); + let two = json!({"objects": [{"path": square_at(40.0), "strokes": [{"paint": solid("#ff0000"), "width": 2}, {"paint": solid("#00ff00"), "width": 6}]}]}) + .to_string(); + let blue = json!({"objects": [{"path": square_at(80.0), "strokes": [{"paint": solid("#0000ff"), "width": 4}]}]}).to_string(); + install_wat(&mut s, &tpl::returning(&painting("test.engine.twostrokes", true), &two)); + install_wat(&mut s, &tpl::when_given(&painting("test.engine.onsecondstroke", true), tpl::Given::Params, r#""item":{"stroke":1}"#, &blue)); + let stroke = node(&s, id).appearance.items.iter().position(|i| !i.is_fill()).unwrap(); + for effect in ["plugin.test.engine.twostrokes", "plugin.test.engine.onsecondstroke"] { + run(&mut s, "effect.apply", json!({"ids": [id.0], "effect": effect, "item": stroke})); + } + let stroked: Vec<_> = painted_paths(&s, id).into_iter().filter(|(_, items)| items.iter().any(|(_, w)| w.is_some())).collect(); + let (a, b) = (square_at(40.0).bounds(), square_at(80.0).bounds()); + assert_eq!(stroked, [(a, vec![(paint("#ff0000"), Some(2.0))]), (b, vec![(paint("#0000ff"), Some(4.0))])]); +} + +/// A third painted effect runs on every fill the second returned, for each fill the first returned. +#[test] +fn a_third_painted_effect_visits_every_fill_from_the_second() { + let mut s = session(); + let id = rect(&mut s, 10.0, "#ff0000"); + let first = json!({"objects": [{"path": square_at(40.0), "fills": [solid("#ff0000"), solid("#00ff00")]}]}).to_string(); + let second = json!({"objects": [{"path": square_at(40.0), "fills": [solid("#0000ff"), solid("#00ffff")]}]}).to_string(); + let third = json!({"objects": [{"path": square_at(80.0), "fills": [solid("#ffff00")]}]}).to_string(); + install_wat(&mut s, &tpl::returning(&painting("test.engine.third.a", true), &first)); + install_wat(&mut s, &tpl::returning(&painting("test.engine.third.b", true), &second)); + install_wat(&mut s, &tpl::when_given(&painting("test.engine.third.c", true), tpl::Given::Params, r#""item":{"fill":1}"#, &third)); + let fill = node(&s, id).appearance.items.iter().position(|i| i.is_fill()).unwrap(); + for effect in ["a", "b", "c"] { + run(&mut s, "effect.apply", json!({"ids": [id.0], "effect": format!("plugin.test.engine.third.{effect}"), "item": fill})); + } + let (a, b) = (square_at(40.0).bounds(), square_at(80.0).bounds()); + let pair = [(a, vec![(paint("#0000ff"), None)]), (b, vec![(paint("#ffff00"), None)])]; + assert_eq!(painted_paths(&s, id), [pair.clone(), pair].concat()); +} + +/// A later live effect that changes geometry only runs on each fill a painted effect returned, told +/// which fill it is on: on the second it moves the square to 80 pt, and the first stays at 40 pt. +#[test] +fn a_later_geometry_effect_uses_each_generated_fill_s_context() { + let mut s = session(); + let id = rect(&mut s, 10.0, "#ff0000"); + let two = json!({"objects": [{"path": square_at(40.0), "fills": [solid("#ff0000"), solid("#00ff00")]}]}).to_string(); + let moved = json!({"objects": [{"path": square_at(80.0)}]}).to_string(); + install_wat(&mut s, &tpl::returning(&painting("test.engine.geomfills", true), &two)); + install_wat(&mut s, &tpl::when_given(&painting("test.engine.geomsecond", false), tpl::Given::Params, r#""item":{"fill":1}"#, &moved)); + let fill = node(&s, id).appearance.items.iter().position(|i| i.is_fill()).unwrap(); + for effect in ["plugin.test.engine.geomfills", "plugin.test.engine.geomsecond"] { + run(&mut s, "effect.apply", json!({"ids": [id.0], "effect": effect, "item": fill})); + } + let (a, b) = (square_at(40.0).bounds(), square_at(80.0).bounds()); + assert_eq!(painted_paths(&s, id), [(a, vec![(paint("#ff0000"), None)]), (b, vec![(paint("#00ff00"), None)])]); +} + +/// A later Outline Stroke effect runs on each stroke a painted effect returned, with that stroke's +/// weight: the 2 pt stroke's outline is 22 pt wide and the 6 pt stroke's 26 pt, in their order. +#[test] +fn a_later_outline_stroke_uses_each_generated_stroke_s_weight() { + let mut s = session(); + let id = rect(&mut s, 10.0, "#ff0000"); + run(&mut s, "paint.setStroke", json!({"ids": [id.0], "color": "#000000"})); + let two = json!({"objects": [{"path": square_at(40.0), "strokes": [{"paint": solid("#ff0000"), "width": 2}, {"paint": solid("#00ff00"), "width": 6}]}]}) + .to_string(); + install_wat(&mut s, &tpl::returning(&painting("test.engine.outlinestrokes", true), &two)); + let stroke = node(&s, id).appearance.items.iter().position(|i| !i.is_fill()).unwrap(); + run(&mut s, "effect.apply", json!({"ids": [id.0], "effect": "plugin.test.engine.outlinestrokes", "item": stroke})); + run(&mut s, "effect.apply", json!({"ids": [id.0], "effect": "path.outlineStroke", "params": {}, "item": stroke})); let st = s.doc().unwrap(); let art = vectorcraft_render::effects::reshape(Some(&st.doc), st.doc.node(id).unwrap(), None).unwrap(); - let mut paints = vec![]; + // Each outline is a compound path (the ring around the square): its width and its strokes. + let mut outlines = vec![]; art.walk(&mut |n| { - if n.path_data().is_some() { - paints.push(n.appearance.items.iter().filter(|i| i.is_fill()).map(|i| i.paint().clone()).collect::>()); + if let vectorcraft_doc::NodeKind::Compound { children, .. } = &n.kind { + let bounds = children.iter().filter_map(|c| c.path_data().and_then(PathData::bounds)).reduce(|a, b| a.union(b)); + let strokes: Vec<_> = n + .appearance + .items + .iter() + .filter_map(|i| match i { + vectorcraft_doc::AppearanceItem::Stroke(st) => Some((st.paint.clone(), st.width)), + vectorcraft_doc::AppearanceItem::Fill(_) => None, + }) + .collect(); + outlines.push((bounds.map(|b| (b.width() * 1000.0).round() / 1000.0), strokes)); } }); - let fill = |hex: &str| Paint::solid(Color::from_hex(hex).unwrap()); - assert!(paints.contains(&vec![fill("#0000ff"), fill("#00ff00")]), "{paints:?}"); + assert_eq!( + outlines, + [(Some(22.0), vec![(paint("#ff0000"), 2.0)]), (Some(26.0), vec![(paint("#00ff00"), 6.0)])], + "each stroke is outlined at its own weight" + ); +} + +/// A later painted effect's runs on the fills a piece returned share the effects' budget: each run +/// that fits gives all its pieces, and once the budget is spent the remaining fills stay together +/// on the piece's path, with none of their run's pieces. +#[test] +fn painted_fills_share_the_budget_without_partial_results() { + let mut s = session(); + let id = rect(&mut s, 10.0, "#ff0000"); + let fills = vec![solid("#ff0000"); vectorcraft_plugins::objects::MAX_ITEMS]; + let first = json!({"objects": [{"path": square_at(40.0), "fills": fills}]}).to_string(); + let tiny = PathData::single(SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(0.1, 0.0), Point::new(0.0, 0.1)], true)); + let many = json!({"objects": vec![json!({"path": tiny}); 400]}).to_string(); + install_wat(&mut s, &tpl::returning(&painting("test.engine.budget.fills", true), &first)); + install_wat(&mut s, &tpl::returning(&painting("test.engine.budget.many", true), &many)); + let fill = node(&s, id).appearance.items.iter().position(|i| i.is_fill()).unwrap(); + for effect in ["plugin.test.engine.budget.fills", "plugin.test.engine.budget.many"] { + run(&mut s, "effect.apply", json!({"ids": [id.0], "effect": effect, "item": fill})); + } + let paths = painted_paths(&s, id); + let tinies = paths.iter().filter(|(b, _)| *b == tiny.bounds()).count(); + let kept: Vec<_> = paths.iter().filter(|(b, _)| *b == square_at(40.0).bounds()).collect(); + assert_eq!(kept.len(), 1, "the fills left out stay together"); + let ran = vectorcraft_plugins::objects::MAX_ITEMS - kept[0].1.len(); + assert!(ran > 1 && !kept[0].1.is_empty(), "{ran} runs gave their pieces"); + assert_eq!(tinies, ran * 400, "every run that fit gave all its pieces"); + assert!(paths.len() <= vectorcraft_plugins::objects::MAX_OBJECTS, "{} paths", paths.len()); +} + +/// A later painted effect runs on each of 256 fills a painted effect returned on an 8,000-anchor +/// path, although 256 copies of that path would pass the effects' budget, when what it returns +/// fits. +#[test] +fn a_later_painted_effect_runs_on_many_fills_of_a_large_piece_when_its_results_fit() { + let mut s = session(); + let id = rect(&mut s, 10.0, "#ff0000"); + let zigzag: Vec = (0..8_000).map(|i| Point::new(40.0 + f64::from(i) * 20.0 / 8_000.0, if i % 2 == 0 { 40.0 } else { 60.0 })).collect(); + let large = PathData::single(SubPath::polyline(&zigzag, true)); + let fills = vec![solid("#ff0000"); vectorcraft_plugins::objects::MAX_ITEMS]; + let first = json!({"objects": [{"path": large, "fills": fills}]}).to_string(); + let tiny = PathData::single(SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(0.1, 0.0), Point::new(0.0, 0.1)], true)); + let small = json!({"objects": [{"path": tiny}]}).to_string(); + install_wat(&mut s, &tpl::returning(&painting("test.engine.large.fills", true), &first)); + install_wat(&mut s, &tpl::returning(&painting("test.engine.large.small", true), &small)); + let fill = node(&s, id).appearance.items.iter().position(|i| i.is_fill()).unwrap(); + for effect in ["plugin.test.engine.large.fills", "plugin.test.engine.large.small"] { + run(&mut s, "effect.apply", json!({"ids": [id.0], "effect": effect, "item": fill})); + } + let paths = painted_paths(&s, id); + let tinies = paths.iter().filter(|(b, _)| *b == tiny.bounds()).count(); + assert_eq!(tinies, vectorcraft_plugins::objects::MAX_ITEMS, "every fill's run"); + assert!(paths.iter().all(|(b, _)| *b != large.bounds()), "no fill left on the large path"); +} + +/// An open path of `curves` tall curves, each drawn with about 5,200 lines. +fn tall_curves(curves: u32) -> PathData { + let h = 3_000_000.0; + let anchors = (0..=curves) + .map(|i| { + let x = 40.0 + f64::from(i); + vectorcraft_geom::Anchor::with_handles(Point::new(x, 0.0), Point::new(x, -h), Point::new(x, h)) + }) + .collect(); + PathData::single(SubPath::new(anchors, false)) +} + +/// A later painted effect's run on the first of two fills a painted effect returned on a path that +/// takes most of the effects' budget gives its result when it and the second fill's result fit +/// together, although the result and another copy of the path would not. +#[test] +fn a_later_painted_run_counts_the_results_after_it_before_keeping_room_for_its_input() { + let mut s = session(); + let id = rect(&mut s, 10.0, "#ff0000"); + let (large, result) = (tall_curves(1_000), tall_curves(600)); + let tiny = PathData::single(SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(0.1, 0.0), Point::new(0.0, 0.1)], true)); + let two = json!({"objects": [{"path": large, "fills": [solid("#ff0000"), solid("#00ff00")]}]}).to_string(); + let on_first = json!({"objects": [{"path": result}]}).to_string(); + let on_second = json!({"objects": [{"path": tiny}]}).to_string(); + install_wat(&mut s, &tpl::returning(&painting("test.engine.tall.fills", true), &two)); + let second = painting("test.engine.tall.each", true); + install_wat(&mut s, &tpl::when_given_else(&second, tpl::Given::Params, r#""item":{"fill":0}"#, &on_first, &on_second)); + let fill = node(&s, id).appearance.items.iter().position(|i| i.is_fill()).unwrap(); + for effect in ["plugin.test.engine.tall.fills", "plugin.test.engine.tall.each"] { + run(&mut s, "effect.apply", json!({"ids": [id.0], "effect": effect, "item": fill})); + } + let want = [(result.bounds(), vec![(paint("#ff0000"), None)]), (tiny.bounds(), vec![(paint("#00ff00"), None)])]; + assert_eq!(painted_paths(&s, id), want, "both runs give their results"); +} + +/// When the results of a later painted effect's runs on the two fills of a large path do not fit +/// together, and the first fill's result and another copy of the path do not fit either, the first +/// fill stays on the path and the second fill's result, which fits beside the path, is drawn. +#[test] +fn a_later_painted_run_that_did_not_fit_beside_an_earlier_result_fits_once_that_is_left_out() { + let mut s = session(); + let id = rect(&mut s, 10.0, "#ff0000"); + let (large, first, second) = (tall_curves(577), tall_curves(1_058), tall_curves(770)); + let two = json!({"objects": [{"path": large, "fills": [solid("#ff0000"), solid("#00ff00")]}]}).to_string(); + let on_first = json!({"objects": [{"path": first}]}).to_string(); + let on_second = json!({"objects": [{"path": second}]}).to_string(); + install_wat(&mut s, &tpl::returning(&painting("test.engine.refit.fills", true), &two)); + let each = painting("test.engine.refit.each", true); + install_wat(&mut s, &tpl::when_given_else(&each, tpl::Given::Params, r#""item":{"fill":0}"#, &on_first, &on_second)); + let fill = node(&s, id).appearance.items.iter().position(|i| i.is_fill()).unwrap(); + for effect in ["plugin.test.engine.refit.fills", "plugin.test.engine.refit.each"] { + run(&mut s, "effect.apply", json!({"ids": [id.0], "effect": effect, "item": fill})); + } + let want = [(large.bounds(), vec![(paint("#ff0000"), None)]), (second.bounds(), vec![(paint("#00ff00"), None)])]; + assert_eq!(painted_paths(&s, id), want, "the second fill's result is drawn"); } /// A Transform effect before a painted effect on a fill moves the fill's placed gradient: a piece @@ -1183,6 +1422,39 @@ fn the_first_view_defers_plug_in_effects_past_its_budget() { assert_eq!(fx_c.take_report(), Some(0)); } +/// A later painted effect deferred on the fills a piece returned is listed once, at its place among +/// the object's fill's effects, and a refresh of the object runs it on each of them. +#[test] +fn deferred_runs_on_the_fills_a_piece_returned_keep_the_fill_s_stage() { + let mut s = session(); + let id = rect(&mut s, 10.0, "#ff0000"); + let two = json!({"objects": [{"path": square_at(40.0), "fills": [solid("#ff0000"), solid("#00ff00")]}]}).to_string(); + let blue = json!({"objects": [{"path": square_at(80.0), "fills": [solid("#0000ff")]}]}).to_string(); + install_wat(&mut s, &tpl::returning(&painting("test.engine.deferred.two", true), &two)); + install_wat(&mut s, &tpl::returning(&painting("test.engine.deferred.later", true), &blue)); + let fill = node(&s, id).appearance.items.iter().position(|i| i.is_fill()).unwrap(); + run(&mut s, "effect.apply", json!({"ids": [id.0], "effect": "plugin.test.engine.deferred.two", "item": fill})); + // The first effect's result is kept from a drawing outside a view's budget. + assert_eq!(drawn(&s).pixel(50, 50), GREEN); + run(&mut s, "effect.apply", json!({"ids": [id.0], "effect": "plugin.test.engine.deferred.later", "item": fill})); + let step = std::sync::Arc::new(std::sync::atomic::AtomicU64::new(3_000)); + let fx = vectorcraft_plugins::deferred::Deferrals::with_clock(stepping_clock(&step)); + s.doc_mut().unwrap().plugin_effects = fx.clone(); + let img = fx.view(|| drawn(&s)); + assert_eq!((img.pixel(50, 50), img.pixel(90, 50)), (GREEN, WHITE), "the fills on the first effect's piece"); + let places = run(&mut s, "effect.deferredStatus", json!({}))["effects"] + .as_array() + .unwrap() + .iter() + .map(|e| (e["objectId"].as_u64().unwrap(), e["item"].as_u64(), e["effectIndex"].as_u64().unwrap())) + .collect::>(); + assert_eq!(places, [(id.0, Some(fill as u64), 1)], "the fill's stage, listed once"); + step.store(0, std::sync::atomic::Ordering::Relaxed); + assert_eq!(run(&mut s, "effect.refreshDeferred", json!({"ids": [id.0]})), json!({"refreshed": 1, "stillDeferred": 0, "failed": 0})); + let img = fx.view(|| drawn(&s)); + assert_eq!((img.pixel(50, 50), img.pixel(90, 50)), (WHITE, BLUE), "both fills replaced"); +} + /// Deferred stages are listed where their effects are: after an effect that changes no geometry, /// and on a fill after a Transform effect that reaches its appearance, each of two instances of /// one plug-in at its own place. diff --git a/crates/plugins/src/wat.rs b/crates/plugins/src/wat.rs index 0beabd34cb..936d5d9e53 100644 --- a/crates/plugins/src/wat.rs +++ b/crates/plugins/src/wat.rs @@ -127,11 +127,31 @@ const NEEDLE_AT: usize = 0x8000; /// its input unchanged otherwise. A live effect made from it draws one shape or the other, so a /// test sees from the geometry whether the host handed the plug-in something. pub fn when_given(manifest: &str, given: Given, needle: &str, output: &str) -> String { + given_or(manifest, given, needle, output, None) +} + +/// A plug-in that returns `output` when what it is given (`given`) holds the text `needle`, and +/// `otherwise` when it does not. +pub fn when_given_else(manifest: &str, given: Given, needle: &str, output: &str, otherwise: &str) -> String { + given_or(manifest, given, needle, output, Some(otherwise)) +} + +/// [`when_given`], returning `otherwise` in place of the input when it is given. +fn given_or(manifest: &str, given: Given, needle: &str, output: &str, otherwise: Option<&str>) -> String { let (src, len) = match given { Given::Input => ("$in", "$il"), Given::Params => ("$pp", "$pl"), }; let n = needle.len(); + // `otherwise` sits right after `output`. + let other_at = OUTPUT_AT + output.len(); + let (none, other) = match otherwise { + Some(o) => ( + format!("(i64.or (i64.shl (i64.const {}) (i64.const 32)) (i64.const {other_at}))", o.len()), + format!(r#" (data (i32.const {other_at}) "{}")"#, string(o)), + ), + None => (ECHO.to_string(), String::new()), + }; // For each place `$i` the needle fits, compare it byte by byte (`$j`). let run = format!( r#"(local $i i32) (local $j i32) @@ -149,12 +169,13 @@ pub fn when_given(manifest: &str, given: Given, needle: &str, output: &str) -> S (br $cmp))) (local.set $i (i32.add (local.get $i) (i32.const 1))) (br $at))) - (return {ECHO})) + (return {none})) (i64.or (i64.shl (i64.const {out}) (i64.const 32)) (i64.const {OUTPUT_AT}))"#, out = output.len(), ); - let extra = format!(r#"(data (i32.const {NEEDLE_AT}) "{}") (data (i32.const {OUTPUT_AT}) "{}")"#, string(needle), string(output)); - module(manifest, &run, &extra, (OUTPUT_AT + output.len()).div_ceil(0x1_0000) as u32 + 1) + let extra = format!(r#"(data (i32.const {NEEDLE_AT}) "{}") (data (i32.const {OUTPUT_AT}) "{}"){other}"#, string(needle), string(output)); + let end = other_at + otherwise.map_or(0, str::len); + module(manifest, &run, &extra, end.div_ceil(0x1_0000) as u32 + 1) } /// The manifest of a test plug-in `id` of `kind` with `params` (a JSON object of specs). diff --git a/docs/plugins.md b/docs/plugins.md index 124cc76174..f28809789a 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -773,6 +773,11 @@ is a piece drawn by itself, in the order returned, with paints of its own: starts at 1 pt, miter join, butt cap, miter limit 10. - An effect on a fill (`_context.item` `{"fill": i}`) returns only `fills`, which replace that fill on each piece; an effect on a stroke returns only `strokes`. The object's other fills and strokes stay where they are. +- Each fill or stroke such an effect returns keeps the effects after it in that fill's or stroke's stack. A later + live effect, and a later geometry effect on strokes, runs once on each of them in paint order: it is given the + piece's `fills` and `strokes` with `_context.item` naming that one (`{"fill": 1}` for the second fill on the + piece), and its result replaces only that fill or stroke. A run that fails, is refused, is deferred or would pass + the budget leaves its own fill or stroke as it was, and the others still run. - The effects after it in the stack apply to the pieces together, the reference box being the bounds of all of them. Bounds, raster effects, Pathfinder effects, compound shapes and Envelope Options › Distort Appearance use the pieces as they are drawn. Outside outline mode, an image is also hit where the pieces of its own fills and strokes paint; a diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f04ee3c910..8bf9be01b4 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1818,6 +1818,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **A drag ended by a command with Real-time Drawing off:** when Undo, Redo, a filter that calls commands or a plug-in command that calls commands ends a drag whose preview Real-time Drawing off has not applied yet, the preview is applied first and kept as an undo step of its own, as releasing the drag keeps it; a preview that fails cancels the drag. The filter or plug-in command is then given the objects where the drag left them. Regressions: `crates/engine/src/tests/plugins.rs`, `crates/engine/src/tests/prefs.rs`. Scores and hours unchanged. - **Plug-in progress, Cancel and log lines (G17):** at plug-in API level 2 a plug-in with the `progress` permission imports `env.vc_progress`, `env.vc_cancelled` and `env.vc_log`. A heavy filter's and an export's progress windows show its progress as a percentage bar, their Cancel reaches it through `vc_cancelled`, a light filter with `progress` and no `commandAllowlist` runs in the background with the same progress window when it runs at once or OK runs it with Preview off, and its log lines go to the app's log with its id, capped per line and per run. Installing checks every import and names the one it refuses. Regressions: `crates/plugins/src/host.rs`, `crates/plugins/tests/abi.rs`, `crates/engine/src/tests/plugins.rs`, `crates/engine/tests/plugin_fuzz.rs`, `crates/ui-egui/src/tests/plugin_runs.rs`. Scores and hours unchanged. - **Live-effect plug-ins paint their output (G17, #121):** a live effect whose manifest has `"api": 2` and `"paintOutput": true` returns pieces, each drawn by itself in order with fills and strokes of its own in the filter's paint forms (a piece without them keeps the object's; an empty list paints none; an effect on a fill returns only fills, one on a stroke only strokes). The whole result is checked first: limits, numbers in range with nothing clamped, known keys only, and the swatches and patterns it names in the document; one fault draws that step of the stack unchanged, keeps the effect record and puts the plug-in's name and the field in `plugin.info`'s `lastError`. The pieces are drawn, measured and exported to PDF and SVG from the appearance stack without changing the document, and Expand Appearance writes them as ordinary paths in one undo step. Effects without the key behave as before. Regressions: `crates/plugins/src/painted/tests.rs`, `crates/plugins/src/manifest.rs`, `crates/engine/src/tests/plugins.rs`, `crates/engine/tests/plugin_fuzz.rs`. Scores and hours unchanged. +- **Later effects on every fill or stroke a painted effect returns (G17):** when a painted effect on a fill or stroke returns several fills or strokes, a later live-effect plug-in in that fill's or stroke's stack, and a later geometry effect on strokes, runs once on each of them in paint order, given its own paint and its own `_context.item` among them. Each run's pieces replace only that fill or stroke. A run that fails, is refused, is deferred or would pass the effects' budget leaves only its own fill or stroke as it was, and the others still run; a deferred stage is listed once, at the source fill's or stroke's place. Regressions: `crates/engine/src/tests/plugins.rs`, `crates/effects/src/tests/painted.rs`. Scores and hours unchanged. - **Live-effect plug-ins while a document opens (G17):** the live-effect plug-in runs of a document's first view on screen share a 2,000 ms budget (VectorCraft's own value). A stage left out for time, or one that times out, fails, has no plug-in or meets Safe Mode, draws its input unchanged and is deferred; the status bar says how many, `effect.deferredStatus` lists them with their object, effect and reason, and Effect › Refresh Deferred Effects (`effect.refreshDeferred`) runs them again with a fresh budget. Each document has its own budget, an edit runs the stages it changes, and exports, Expand Appearance and commands run every stage under the 5 s limit of each run. The web build times the budget and each run's limit with the page's `performance.now()`. Regressions: `crates/plugins/src/deferred.rs`, `crates/plugins/src/effect.rs`, `crates/plugins/src/host.rs`, `crates/engine/src/tests/plugins.rs`, `crates/ui-egui/src/canvas/tests.rs`. Scores and hours unchanged. - **Refreshing many deferred effects (G17):** Refresh Deferred Effects (`effect.refreshDeferred`) looks up the objects asked for, the stages reached, the objects drawn whole and the inputs that ran in hash sets, so its time no longer grows with the square of the number of deferred stages. The deferred records are indexed by stage and input, so asking whether a stage stays deferred, replacing a stage's records when it runs, and ending a drawing after the first view look at that stage's records only, and the records keep the order they were made in. With 40,000 deferred stages, one refresh in a release build took 38 ms, down from 1,036 ms, and asking about and running each stage once took 16 ms, down from 2,287 ms (wall-clock time on a computer busy with other builds, one run each). Regressions: `crates/plugins/src/deferred.rs`. Scores and hours unchanged. - **Refresh Deferred Effects by object (G17):** `effect.refreshDeferred` takes `ids`, or `id` for one, naming objects in the layers or in the art of a symbol, pattern, brush or opacity mask, the objects `effect.deferredStatus` lists; an object without a deferred stage adds nothing to the counts, and an id of no object in the document is an error. Regressions: `crates/engine/src/tests/plugins.rs`. Scores and hours unchanged. From 1517c8126241693a6f2f39b55a0fef21a5adde1e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 21:56:19 -0800 Subject: [PATCH 05/25] 3D and Materials: wrap graphics around the side of Revolve objects The Materials tab and threeD.mapGraphic now map graphics onto Revolve's swept side, unrolled flat: x runs around the axis (the angle times the profile's distance from the axis at that point) and y along the profile. A graphic keeps its size at every distance from the axis, so it reaches farther around where the profile comes nearer the axis. Each face of the side draws the part that falls on it: a graphic narrows toward the silhouette, follows the profile along its length, is shaded with the surface (several lights included) and is hidden where the side faces away. A part that runs past the end of the profile reaches the curved rim and stops there. The middle of the side faces the viewer with the axis on either edge. On a compound profile or a group the graphics go on the longest contour. - three-d: with Revolve::map_surface set, side faces carry a SurfaceCell (corners on the page and on the unrolled side, whether the outside faces the viewer) and a closed profile off the axis takes an anchor where its side is cut; without it the faces are as before. revolve_surface_size gives the side's size for a new graphic's fit. - effects: Revolve takes `graphics` (front only); surface_parts cuts and maps them per face; curves are cut into straight pieces one at a time, and commands refuse graphics past the point limits; switching between Extrude, Plane and Revolve keeps the front's graphics. - The Materials tab hides Face for Revolve; params text, docs/mcp.md, docs/three-d.md and the progress docs describe the change. - i18n: the complete-message catalogs translate the three new refusals in place of the planar-faces refusal they replace, and ja, es, zh-hans and zh-hant translate the Materials tab's label. --- crates/effects/src/catalog.rs | 4 +- crates/effects/src/lib.rs | 3 +- crates/effects/src/revolve.rs | 136 +++++- crates/effects/src/revolve/tests_graphics.rs | 393 +++++++++++++++++ crates/effects/src/solids.rs | 32 +- crates/effects/src/solids/graphics.rs | 397 +++++++++++++++++- crates/effects/src/solids/tests_graphics.rs | 38 +- crates/engine/src/cmd/effectcmd/graphics.rs | 6 +- .../src/cmd/effectcmd/graphics_tests.rs | 27 +- crates/three-d/src/lib.rs | 315 +++++++++++++- crates/three-d/src/tests.rs | 184 ++++++++ crates/three-d/src/tests/profile_limits.rs | 29 ++ crates/three-d/src/visibility.rs | 1 + .../ui-egui/src/dialogs/three_d_materials.rs | 13 +- crates/ui-egui/src/i18n/ca.tsv | 4 +- crates/ui-egui/src/i18n/cs.tsv | 4 +- crates/ui-egui/src/i18n/de.tsv | 4 +- crates/ui-egui/src/i18n/el.tsv | 4 +- crates/ui-egui/src/i18n/es.tsv | 5 +- crates/ui-egui/src/i18n/fi.tsv | 4 +- crates/ui-egui/src/i18n/fr.tsv | 4 +- crates/ui-egui/src/i18n/hi.tsv | 4 +- crates/ui-egui/src/i18n/hu.tsv | 4 +- crates/ui-egui/src/i18n/it.tsv | 4 +- crates/ui-egui/src/i18n/ja.tsv | 5 +- crates/ui-egui/src/i18n/ka.tsv | 4 +- crates/ui-egui/src/i18n/ko.tsv | 4 +- crates/ui-egui/src/i18n/pl.tsv | 4 +- crates/ui-egui/src/i18n/pt-br.tsv | 4 +- crates/ui-egui/src/i18n/ru.tsv | 4 +- crates/ui-egui/src/i18n/sv.tsv | 4 +- crates/ui-egui/src/i18n/tr.tsv | 4 +- crates/ui-egui/src/i18n/uk.tsv | 4 +- crates/ui-egui/src/i18n/vi.tsv | 4 +- crates/ui-egui/src/i18n/zh-hans.tsv | 5 +- crates/ui-egui/src/i18n/zh-hant.tsv | 5 +- crates/ui-egui/src/panels/tests_three_d.rs | 27 +- docs/effects-parity.md | 2 +- docs/mcp.md | 10 +- docs/target-app-parity.md | 1 + docs/three-d.md | 48 ++- 41 files changed, 1662 insertions(+), 96 deletions(-) create mode 100644 crates/effects/src/revolve/tests_graphics.rs diff --git a/crates/effects/src/catalog.rs b/crates/effects/src/catalog.rs index 52232cd54e..424beebe17 100644 --- a/crates/effects/src/catalog.rs +++ b/crates/effects/src/catalog.rs @@ -182,8 +182,8 @@ pub fn effect_catalog() -> Vec { REVOLVE, "Revolve…", &["Effect", "3D and Materials"], - "{angle: degrees (0..360, 360), offset: pt (0..100000, 0), edge: left|right, rotationX: degrees (0), rotationY: degrees (0), rotationZ: degrees (0), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), segments: integer (8..128, 64), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a hard-edged shadow, black at 50% times the art's opacity), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), cap: bool (true, close circular ends of open profiles; partial-sweep cut sides stay open), expandVisibleOnly: bool (true, trim covered opaque solid surfaces only on Expand Appearance)}. Shaded surfaces use smooth vector gradients automatically; intersecting profiles use approximate painter visibility.", - json!({"angle":360.0,"offset":0.0,"edge":"left","rotationX":0.0,"rotationY":0.0,"rotationZ":0.0,"perspectiveAngle":0.0,"segments":64,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"cap":true,"expandVisibleOnly":true}), + "{angle: degrees (0..360, 360), offset: pt (0..100000, 0), edge: left|right, rotationX: degrees (0), rotationY: degrees (0), rotationZ: degrees (0), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), segments: integer (8..128, 64), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a hard-edged shadow, black at 50% times the art's opacity), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), cap: bool (true, close circular ends of open profiles; partial-sweep cut sides stay open), expandVisibleOnly: bool (true, trim covered opaque solid surfaces only on Expand Appearance; surfaces with graphics keep every face), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the swept side, see threeD.mapGraphic: symbol: name of a document symbol, face: front (the side), x: pt (0; the offset of the graphic's center from the middle of the side, around the axis: the angle times the profile's distance from the axis at that point), y: pt (0; along the profile, toward its lower end), scale: % (1..10000, 100), rotation: degrees (-360..360, 0; counterclockwise); wrapped around the side at its own size, so it reaches farther around where the profile comes nearer the axis, shaded with it and drawn only where the side's outside faces the viewer; a full turn cuts it at the back; nothing on the caps)}. Shaded surfaces use smooth vector gradients automatically; intersecting profiles use approximate painter visibility.", + json!({"angle":360.0,"offset":0.0,"edge":"left","rotationX":0.0,"rotationY":0.0,"rotationZ":0.0,"perspectiveAngle":0.0,"segments":64,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"cap":true,"expandVisibleOnly":true,"graphics":[]}), ), g( EXTRUDE, diff --git a/crates/effects/src/lib.rs b/crates/effects/src/lib.rs index fa06d00922..ac61746266 100644 --- a/crates/effects/src/lib.rs +++ b/crates/effects/src/lib.rs @@ -95,7 +95,8 @@ pub use solids::{ validate_three_d, validate_three_d_at, validate_three_d_at_in, validate_three_d_in, validate_three_d_params, view_options, with_graphic, }; pub use solids::{ - GRAPHIC_MAX_OFFSET, GRAPHIC_SCALE_RANGE, appearance_graphic_symbols, graphic_frame_at, graphics_reshaped_after, rename_appearance_graphic_symbol, + GRAPHIC_MAX_OFFSET, GRAPHIC_SCALE_RANGE, GRAPHICS_NOT_TAKEN, appearance_graphic_symbols, graphic_frame_at, graphics_reshaped_after, + rename_appearance_graphic_symbol, }; pub use stylize::{ScribbleSetting, scribble_setting_id, scribble_settings}; pub use svg_filter::SVG_FILTER; diff --git a/crates/effects/src/revolve.rs b/crates/effects/src/revolve.rs index e9d64864d0..95c643697c 100644 --- a/crates/effects/src/revolve.rs +++ b/crates/effects/src/revolve.rs @@ -96,13 +96,18 @@ pub fn revolve_options(p: &Value) -> Revolve { smooth_shading: true, cap_ends: flag(p, "cap", true), curve_samples: None, + map_surface: false, } } /// The options Revolve (`id` [`REVOLVE`]) or Revolve (Classic) ([`CLASSIC_REVOLVE`]) with -/// parameters `p` sweeps its surface with. +/// parameters `p` sweeps its surface with. A Revolve with graphics lays out its side for them. fn options_of(id: &str, p: &Value) -> Revolve { - if id == CLASSIC_REVOLVE { classic::options(p) } else { revolve_options(p) } + if id == CLASSIC_REVOLVE { + classic::options(p) + } else { + Revolve { map_surface: id == REVOLVE && !crate::solids::mapped_graphics(p).is_empty(), ..revolve_options(p) } + } } /// The options effect `fx`, a Revolve or a Revolve (Classic), sweeps its surface with. @@ -140,6 +145,16 @@ pub(crate) fn validate_in(doc: Option<&Document>, n: &Node, id: &str, p: &Value) let options = shared_options(&shapes, options_of(id, p))?; let mut copies = 0; shapes.iter().try_for_each(|s| check_surface(&s.path, b, options, surface_item(&s.items), &mut copies))?; + match graphics_member(&shapes, b, options).and_then(|k| shapes.get(k)) { + Some(s) => check_graphics(doc, id, &s.path, b, options, p)?, + // With no member to carry them, the graphics' art must still fit its limits. + None => { + if let Some(doc) = doc.filter(|_| id == REVOLVE && !crate::solids::mapped_graphics(p).is_empty()) { + crate::solids::graphics::validate_symbols(doc, p)?; + crate::solids::graphics::validate_surface_symbols(doc, p)?; + } + } + } let casting = shapes.iter().filter(|s| surface_item(&s.items).is_some_and(|i| paint_of(i).1 * s.opacity > 0.0)); return check_shadow(p, casting.map(|s| &s.path), b, options); } @@ -151,9 +166,38 @@ pub(crate) fn validate_in(doc: Option<&Document>, n: &Node, id: &str, p: &Value) let b = path.bounds().ok_or("Revolve requires a shape with at least two anchors")?; let paints = solid_paints(n); check_surface(&path, b, options_of(id, p), surface_item(&paints), &mut 0)?; + check_graphics(doc, id, &path, b, options_of(id, p), p)?; check_shadow(p, [&path], b, options_of(id, p)) } +/// An error when the graphics in Revolve (`id`) parameters `p`, with the symbols of `doc`, are past +/// their limits on the surface of `path` about the axis of `b`: their art, or the parts they draw +/// on its faces ([`crate::solids::graphics::surface_parts`]). Without `doc` nothing is drawn, and +/// nothing is checked. +fn check_graphics(doc: Option<&Document>, id: &str, path: &PathData, b: Rect, options: Revolve, p: &Value) -> Result<(), String> { + let graphics = crate::solids::mapped_graphics(p); + let Some(doc) = doc.filter(|_| id == REVOLVE && !graphics.is_empty()) else { return Ok(()) }; + crate::solids::graphics::validate_symbols(doc, p)?; + crate::solids::graphics::validate_surface_symbols(doc, p)?; + let faces = vectorcraft_three_d::revolve(path, b, options)?; + match crate::solids::graphics::surface_parts(Some(doc), NodeId(0), &graphics, &faces, &|_, c| Paint::solid(c)) { + Some(_) => Ok(()), + None => Err("The graphics are too complex for this surface: simplify the symbols' art or reduce Segments".into()), + } +} + +/// The member of a group whose side takes the group's graphics: the first with the longest +/// profile among those with a fill or stroke. +fn graphics_member(shapes: &[Profile], b: Rect, options: Revolve) -> Option { + shapes + .iter() + .enumerate() + .filter(|(_, s)| surface_item(&s.items).is_some()) + .filter_map(|(k, s)| vectorcraft_three_d::revolve_surface_size(&s.path, b, options).map(|(_, h)| (k, h))) + .fold(None, |best: Option<(usize, f64)>, (k, h)| if best.is_some_and(|(_, top)| top >= h) { best } else { Some((k, h)) }) + .map(|(k, _)| k) +} + /// With the shadow of Revolve parameters `p` on, an error when the surfaces of `paths` it is cast /// from, about the axis of `b`, are past the limits together. fn check_shadow<'a>(p: &Value, paths: impl IntoIterator, b: Rect, options: Revolve) -> Result<(), String> { @@ -168,16 +212,17 @@ fn check_shadow<'a>(p: &Value, paths: impl IntoIterator, b: /// appearance item `target` of `n` ([`validate_item_of`]). #[cfg(test)] pub(crate) fn validate_item_revolve(n: &Node, p: &Value, target: usize, index: usize) -> Result<(), String> { - validate_item_of(n, REVOLVE, p, target, index) + validate_item_of(None, n, REVOLVE, p, target, index) } /// [`validate_revolve`] for a Revolve or Revolve (Classic), `id`, with parameters `p` at index /// `index` of the effects of appearance item `target` of `n`. The surfaces of every fill and stroke /// that carries one, `target`'s included, share one budget of paint copies, as in [`art`]. A visible -/// object-level Revolve draws in place of those surfaces. -pub(crate) fn validate_item_of(n: &Node, id: &str, p: &Value, target: usize, index: usize) -> Result<(), String> { +/// object-level Revolve draws in place of those surfaces. With `doc`, `target`'s graphics must fit +/// its surface ([`check_graphics`]). +pub(crate) fn validate_item_of(doc: Option<&Document>, n: &Node, id: &str, p: &Value, target: usize, index: usize) -> Result<(), String> { if is_container(n) || visible(&n.appearance.effects) || target >= n.appearance.items.len() { - return validate_in(None, n, id, p); + return validate_in(doc, n, id, p); } validate_params_of(id, p)?; const EMPTY: &str = "Revolve requires a shape with at least two anchors"; @@ -200,6 +245,9 @@ pub(crate) fn validate_item_of(n: &Node, id: &str, p: &Value, target: usize, ind let path = geometry(&path, at.and_then(|at| effects.get(..at)).unwrap_or(effects), &ctx.item(item)); let b = path.bounds().ok_or(EMPTY)?; check_surface(&path, b, options, crate::paints(item).then_some(item), &mut copies)?; + if i == target { + check_graphics(doc, kind, &path, b, options, ¶ms)?; + } check_shadow(¶ms, [&path], b, options)?; } Ok(()) @@ -234,7 +282,7 @@ fn shared_options(shapes: &[Profile], options: Revolve) -> Result Option<&AppearanceItem> { +pub(crate) fn surface_item(items: &[AppearanceItem]) -> Option<&AppearanceItem> { items.iter().rev().find(|i| matches!(i, AppearanceItem::Fill(_))).or_else(|| items.last()) } @@ -255,6 +303,7 @@ pub(crate) fn validate_revolve_params(p: &Value) -> Result<(), String> { /// only its own parameters, each in its range. pub(crate) fn validate_params_of(id: &str, p: &Value) -> Result<(), String> { validate_revolve_params(p)?; + crate::solids::graphics::validate(id, p)?; if id == CLASSIC_REVOLVE { classic::validate(p)?; } @@ -304,9 +353,12 @@ fn group_shadow(id: NodeId, fx: &Effect, shapes: &[Profile], b: Rect, options: R /// One object's surface of revolution about the axis of `b`, and each face's depth. `copies` counts /// the bytes of the paint copies of every surface of the object. Revolve (Classic) draws every face -/// with its classic surface, as Extrude & Bevel (Classic) does. +/// with its classic surface, as Extrude & Bevel (Classic) does. Revolve's graphics, with the +/// symbols of `doc`, are drawn on the faces of the side ([`crate::solids::graphics::surface_parts`]): +/// a face with a part of a graphic is a group of the face and that part. #[allow(clippy::too_many_arguments)] fn surface( + doc: Option<&Document>, n: &Node, path: &PathData, b: Rect, @@ -336,10 +388,18 @@ fn surface( if *copies > MAX_PAINT_COPIES { return None; } + let graphics = crate::solids::mapped_graphics(&merged_params(&fx.id, &fx.params)); + let shade = |face: &vectorcraft_three_d::Face, c: Color| graphic_paint(face, c, colored); + // Graphics past the limits are left out, and the surface draws without them. + let mut parts = + if graphics.is_empty() { vec![] } else { crate::solids::graphics::surface_parts(doc, n.id, &graphics, &faces, &shade).unwrap_or_default() }; + let drawn = parts.iter().any(|p| !p.is_empty()); // Visibility is an expansion option, never a change to live geometry or export baking. // Keep all faces for paints whose coverage we cannot prove opaque. A bounded visibility - // failure also retains the complete surface rather than losing any of the user's art. + // failure also retains the complete surface rather than losing any of the user's art. With + // graphics drawn, every face stays, each with its part of the graphics. let visible = (expand + && !drawn && flag(&fx.params, "expandVisibleOnly", true) && paint.color().is_some() && opacity == 1.0 @@ -414,7 +474,16 @@ fn surface( .collect(); Arc::new(Node::path(n.id, face.path, Appearance { items, ..Default::default() })) }) - .collect(); + .collect::>(); + let children = if drawn { + children + .into_iter() + .zip(parts.iter_mut().map(std::mem::take).chain(std::iter::repeat_with(Vec::new))) + .map(|(face, part)| if part.is_empty() { face } else { Arc::new(Node::group(n.id, std::iter::once(face).chain(part).collect())) }) + .collect() + } else { + children + }; let mut group = Node::group(n.id, children); group.opacity = opacity; group.blend = blend; @@ -422,11 +491,33 @@ fn surface( } /// A surface of one object about the bounds of `path`, built with options derived from `fx`. -/// `copies` is the count [`surface`] adds to. -fn object_surface(n: &Node, path: &PathData, fx: &Effect, item: &AppearanceItem, expand: bool, copies: &mut usize) -> Option { +/// `copies` is the count [`surface`] adds to; its graphics take the symbols of `doc`. +fn object_surface( + doc: Option<&Document>, + n: &Node, + path: &PathData, + fx: &Effect, + item: &AppearanceItem, + expand: bool, + copies: &mut usize, +) -> Option { let b = path.bounds()?; let (paint, opacity, blend) = paint_of(item); - surface(n, path, b, fx_options(fx), fx, paint, opacity, blend, expand, copies).map(|(_, art)| art) + surface(doc, n, path, b, fx_options(fx), fx, paint, opacity, blend, expand, copies).map(|(_, art)| art) +} + +/// The paint of a graphic's solid color `c` on `face`, shaded as the face shades a solid fill of +/// that color: across the face with its smooth shading, under colored lights (`colored`) with +/// their color. +fn graphic_paint(face: &vectorcraft_three_d::Face, c: Color, colored: bool) -> Paint { + if colored { + return face + .light_gradient + .map_or_else(|| Paint::solid(crate::lighting::shade(c, face.illumination)), |g| crate::lighting::smooth_paint(g, c)); + } + let [r, g, b] = c.to_rgb(); + let color = |s: f64| Color::rgb(r * s as f32, g * s as f32, b * s as f32); + face.gradient.map_or_else(|| Paint::solid(color(face.brightness)), |g| shading_paint(g, color, |_| 1.0)) } fn shading_paint(g: vectorcraft_three_d::ShadeGradient, color: impl Fn(f64) -> Color, opacity: impl Fn(f64) -> f32) -> Paint { @@ -592,7 +683,7 @@ fn art(doc: Option<&Document>, n: &Node, expand: bool) -> Option { } let n = &*resolve_for(doc, n, "Revolve", false).ok()?; if is_container(n) { - return group_art(n, expand); + return group_art(doc, n, expand); } let (path, rule) = profile(n)?; let ctx = GeomContext::of(n); @@ -606,7 +697,7 @@ fn art(doc: Option<&Document>, n: &Node, expand: bool) -> Option { let paints = solid_paints(n); let item = surface_item(&paints)?; let expand = expand && !n.appearance.effects.iter().skip(index + 1).any(|e| e.visible && is_geometry(&e.id)); - let surface = object_surface(n, &path, fx, item, expand, &mut copies)?; + let surface = object_surface(doc, n, &path, fx, item, expand, &mut copies)?; if let Some(b) = path.bounds() && let Some(shadow) = shadow_of(n.id, fx, &path, item, b, fx_options(fx)).ok()? { @@ -632,7 +723,7 @@ fn art(doc: Option<&Document>, n: &Node, expand: bool) -> Option { let fx = item.effects().get(index)?; let p = geometry(&path, item.effects().get(..index)?, &ctx.item(original)); let expand = expand && !item.effects().iter().skip(index + 1).any(|e| e.visible && is_geometry(&e.id)); - let mut art = object_surface(n, &p, fx, item, expand, &mut copies)?; + let mut art = object_surface(doc, n, &p, fx, item, expand, &mut copies)?; art.appearance.effects = item.effects().iter().skip(index + 1).filter(|e| !is_revolve(&e.id)).cloned().collect(); if let Some(b) = p.bounds() && let Some(mut shadow) = shadow_of(n.id, fx, &p, item, b, fx_options(fx)).ok()? @@ -774,7 +865,7 @@ pub(crate) fn overlaps(a: Rect, b: Rect) -> bool { /// [`art`] of group or layer `n`: every member swept about one axis on the bounds of all of them, /// each in its own paint. Every member's faces are drawn in one back-to-front order. `None` when /// the effect is only on the group's own fills or strokes or when its members can't be revolved. -fn group_art(n: &Node, expand: bool) -> Option { +fn group_art(doc: Option<&Document>, n: &Node, expand: bool) -> Option { let index = n.appearance.effects.iter().position(|e| e.visible && is_revolve(&e.id))?; let fx = n.appearance.effects.get(index)?; let mut shapes = members(n, "").ok()?; @@ -785,14 +876,17 @@ fn group_art(n: &Node, expand: bool) -> Option { let mut copies = 0; let mut surfaces = vec![]; let mut opaque = true; - for s in &shapes { + // The graphics go once, on the side of the member with the longest profile. + let longest = graphics_member(&shapes, b, options); + for (k, s) in shapes.iter().enumerate() { let Some(item) = surface_item(&s.items) else { continue }; // The opacity and blending of the member and the groups it is in apply through its scopes. let (paint, opacity, blend) = paint_of(item); opaque &= opacity >= 1.0 && blend == Default::default() && s.scopes.is_empty(); // A member with transparency of its own keeps every face, as a transparent object does. let expand = expand && s.scopes.is_empty(); - let (depths, art) = surface(n, &s.path, b, options, fx, paint, opacity, blend, expand, &mut copies)?; + let doc = doc.filter(|_| longest == Some(k)); + let (depths, art) = surface(doc, n, &s.path, b, options, fx, paint, opacity, blend, expand, &mut copies)?; surfaces.push((depths, art, s.scopes.as_slice())); } if surfaces.is_empty() { @@ -1517,3 +1611,7 @@ mod tests { assert_eq!(expand_revolve_art(&sample), revolve_art(&sample)); } } + +#[cfg(test)] +#[path = "revolve/tests_graphics.rs"] +mod tests_graphics; diff --git a/crates/effects/src/revolve/tests_graphics.rs b/crates/effects/src/revolve/tests_graphics.rs new file mode 100644 index 0000000000..2261ab4ca7 --- /dev/null +++ b/crates/effects/src/revolve/tests_graphics.rs @@ -0,0 +1,393 @@ +use serde_json::json; +use vectorcraft_doc::Symbol; +use vectorcraft_doc::color::Color; +use vectorcraft_geom::{BezPath, shapes}; + +use super::*; +use crate::solids::three_d_params_as; + +fn bar(r: Rect, color: Color) -> Node { + Node::path(NodeId(0), shapes::rectangle(r), Appearance::basic(Paint::solid(color), Paint::None, 0.0)) +} + +/// A document with symbols "Red" and "Blue" (10 × 20 bars) and "Wide" (a red 300 × 10 bar). +fn document() -> Document { + let mut d = Document::new(1000.0, 1000.0); + for (name, r, color) in [ + ("Red", Rect::new(0.0, 0.0, 10.0, 20.0), Color::rgb(1.0, 0.0, 0.0)), + ("Blue", Rect::new(0.0, 0.0, 10.0, 20.0), Color::rgb(0.0, 0.0, 1.0)), + ("Wide", Rect::new(0.0, 0.0, 300.0, 10.0), Color::rgb(1.0, 0.0, 0.0)), + ("Flat", Rect::new(0.0, 0.0, 10.0, 2.0), Color::rgb(1.0, 0.0, 0.0)), + ] { + d.symbols.push(Symbol { dynamic: false, name: name.into(), art: Arc::new(bar(r, color)) }); + } + d +} + +/// A gray open profile through `points` (its first and last on the axis at x 0), revolved with +/// `params` over a view straight on without shading. +fn revolved(points: &[(f64, f64)], params: Value) -> Node { + let mut b = BezPath::new(); + b.move_to(points[0]); + points[1..].iter().for_each(|p| b.line_to(*p)); + let mut p = json!({"rotationX": 0.0, "rotationY": 0.0, "rotationZ": 0.0, "shade": false}); + p.as_object_mut().unwrap().extend(params.as_object().unwrap().clone()); + let mut n = Node::path(NodeId(7), PathData::from_bezpath(&b), Appearance::basic(Paint::solid(Color::rgb(0.5, 0.5, 0.5)), Paint::None, 0.0)); + n.appearance.effects.push(crate::new_effect(REVOLVE, &p).unwrap()); + n +} + +/// A cylinder of radius 50 about x 0, from y 0 to 200. +const CYLINDER: [(f64, f64); 4] = [(0.0, 0.0), (50.0, 0.0), (50.0, 200.0), (0.0, 200.0)]; + +/// A profile that narrows from 50 to 20 from the axis at y 100 and widens again. +const NECK: [(f64, f64); 5] = [(0.0, 0.0), (50.0, 0.0), (20.0, 100.0), (50.0, 200.0), (0.0, 200.0)]; + +/// The red channel of each color `paint` draws when it is a shade of pure red or pure blue (`blue`): +/// a solid color or the stops of a gradient. `None` for any other paint. +fn shade_of(paint: &Paint, blue: bool) -> Option> { + let hue = |c: &Color| { + let [r, g, b] = c.to_rgb(); + let (on, off) = if blue { (b, r) } else { (r, b) }; + (on > 0.02 && off < 0.01 && g < 0.01).then_some(on) + }; + match paint { + Paint::Solid { .. } => Some(vec![hue(&paint.color()?)?]), + Paint::Gradient(g) => g.gradient.stops.iter().map(|s| hue(&s.color)).collect(), + _ => None, + } +} + +/// The paths in `art` filled in a shade of red (or blue), with their shades. +fn parts(art: &Node, blue: bool) -> Vec<(PathData, Vec)> { + let mut out = vec![]; + art.walk(&mut |n| { + let Some(path) = n.path_data() else { return }; + let fill = n.appearance.items.iter().find_map(|i| match i { + AppearanceItem::Fill(f) => shade_of(&f.paint, blue), + AppearanceItem::Stroke(_) => None, + }); + if let Some(shades) = fill { + out.push((path.clone(), shades)); + } + }); + out +} + +fn reach(parts: &[(PathData, Vec)]) -> Rect { + parts.iter().filter_map(|(p, _)| p.bounds()).reduce(|a, b| a.union(b)).unwrap() +} + +fn near(a: f64, b: f64, tolerance: f64) -> bool { + (a - b).abs() <= tolerance +} + +#[test] +fn a_graphic_wraps_around_the_side_and_narrows_toward_the_silhouette() { + let d = document(); + let n = revolved(&CYLINDER, json!({"graphics": [{"symbol": "Red"}, {"symbol": "Blue", "x": 60.0}]})); + let art = revolve_art_in(Some(&d), &n).unwrap(); + // At the middle of the side, facing the viewer, the bar keeps its size: 10 wide at the axis's + // line, from 10 above the middle of the profile to 10 below. + let front = reach(&parts(&art, false)); + let half = 50.0 * (5.0f64 / 50.0).sin(); + assert!(near(front.x0, -half, 0.05) && near(front.x1, half, 0.05), "{front:?}"); + assert!(near(front.y0, 90.0, 1e-6) && near(front.y1, 110.0, 1e-6), "{front:?}"); + // 60 to its right the side has turned 1.1 to 1.3 radians away: the same bar draws less than + // half as wide, at the sine of those angles. + let turned = reach(&parts(&art, true)); + assert!(near(turned.x0, 50.0 * 1.1f64.sin(), 0.15) && near(turned.x1, 50.0 * 1.3f64.sin(), 0.15), "{turned:?}"); + assert!(turned.width() < front.width() / 2.0); +} + +#[test] +fn the_part_past_the_silhouette_and_on_the_back_is_not_drawn() { + let d = document(); + // A bar wider than the half of the side seen from the front reaches the silhouette and no + // further. + let n = revolved(&CYLINDER, json!({"graphics": [{"symbol": "Wide"}]})); + let wide = reach(&parts(&revolve_art_in(Some(&d), &n).unwrap(), false)); + assert!(wide.x0 > -50.0 - 1e-6 && wide.x1 < 50.0 + 1e-6, "{wide:?}"); + assert!(wide.x0 < -49.5 && wide.x1 > 49.5, "{wide:?}"); + // On the back, half a turn around the axis, nothing is drawn. + let n = revolved(&CYLINDER, json!({"graphics": [{"symbol": "Red", "x": 150.0}]})); + assert!(parts(&revolve_art_in(Some(&d), &n).unwrap(), false).is_empty()); + // Turned half a turn, the back faces the viewer. + let n = revolved(&CYLINDER, json!({"rotationY": 180.0, "graphics": [{"symbol": "Red", "x": 150.0}]})); + assert!(!parts(&revolve_art_in(Some(&d), &n).unwrap(), false).is_empty()); +} + +#[test] +fn a_graphic_follows_the_profile_and_keeps_its_size_where_it_comes_nearer_the_axis() { + let d = document(); + // A 10 wide bar keeps its length around the axis at every distance from it: at the neck, 20 + // from the axis, it spans 0.5 radians; half way up the slanted side (52.2 along it, 35 from + // the axis, at y 50), 2/7 of a radian. Straight on, both draw nearly 10 wide. + let slant = (30.0f64 * 30.0 + 100.0 * 100.0).sqrt(); + let n = revolved(&NECK, json!({"graphics": [{"symbol": "Flat"}, {"symbol": "Flat", "y": -slant / 2.0}]})); + let art = revolve_art_in(Some(&d), &n).unwrap(); + let all = parts(&art, false); + let neck: Vec<_> = all.iter().filter(|(p, _)| p.bounds().unwrap().center().y > 75.0).cloned().collect(); + let up: Vec<_> = all.iter().filter(|(p, _)| p.bounds().unwrap().center().y <= 75.0).cloned().collect(); + let (neck, up) = (reach(&neck), reach(&up)); + // Each bar is 2 tall, so its ends are up to 0.3 farther from the axis than its middle. + assert!(near(neck.width(), 2.0 * 20.0 * 0.25f64.sin(), 0.15), "{neck:?}"); + assert!(near(neck.center().y, 100.0, 0.05), "{neck:?}"); + assert!(near(up.width(), 2.0 * 35.0 * (5.0f64 / 35.0).sin(), 0.15), "{up:?}"); + assert!(near(up.center().y, 50.0, 0.05), "{up:?}"); + // At the neck a bar 25 to the right lies 1 to 1.5 radians around, near the silhouette; one 40 + // to the right lies 1.75 to 2.25 radians around, past the silhouette, and is not drawn. + let n = revolved(&NECK, json!({"graphics": [{"symbol": "Flat", "x": 25.0}]})); + let side = reach(&parts(&revolve_art_in(Some(&d), &n).unwrap(), false)); + assert!(near(side.x0, 20.0 * 1.0f64.sin(), 0.3) && near(side.x1, 20.0 * 1.5f64.sin(), 0.3), "{side:?}"); + let n = revolved(&NECK, json!({"graphics": [{"symbol": "Flat", "x": 40.0}]})); + assert!(parts(&revolve_art_in(Some(&d), &n).unwrap(), false).is_empty()); +} + +#[test] +fn with_the_axis_on_the_right_a_graphic_starts_on_the_front() { + let d = document(); + // The cylinder of radius 50 about x 0, swept from its right edge. + let profile = [(0.0, 0.0), (-50.0, 0.0), (-50.0, 200.0), (0.0, 200.0)]; + let n = revolved(&profile, json!({"edge": "right", "graphics": [{"symbol": "Red"}]})); + let front = reach(&parts(&revolve_art_in(Some(&d), &n).unwrap(), false)); + let half = 50.0 * (5.0f64 / 50.0).sin(); + assert!(near(front.x0, -half, 0.05) && near(front.x1, half, 0.05), "{front:?}"); + assert!(near(front.y0, 90.0, 1e-6) && near(front.y1, 110.0, 1e-6), "{front:?}"); + // x increases to the viewer's right here too. + let n = revolved(&profile, json!({"edge": "right", "graphics": [{"symbol": "Red", "x": 25.0}]})); + let right = reach(&parts(&revolve_art_in(Some(&d), &n).unwrap(), false)); + assert!(near(right.center().x, 50.0 * 0.5f64.sin(), 0.3), "{right:?}"); +} + +#[test] +fn a_graphic_is_shaded_with_the_surface() { + let d = document(); + // The light is on the left: the bar left of the middle is lighter than the one on its right, + // and neither keeps its unlit red. + let n = revolved(&CYLINDER, json!({"shade": true, "graphics": [{"symbol": "Red", "x": -30.0}, {"symbol": "Red", "x": 30.0}]})); + let all = parts(&revolve_art_in(Some(&d), &n).unwrap(), false); + let mean = |left: bool| { + let shades: Vec = + all.iter().filter(|(p, _)| (p.bounds().unwrap().center().x < 0.0) == left).flat_map(|(_, s)| s.iter().copied()).collect(); + shades.iter().sum::() / shades.len() as f32 + }; + assert!(mean(true) > mean(false) + 0.05, "{} {}", mean(true), mean(false)); + assert!(all.iter().all(|(_, s)| s.iter().all(|r| *r < 0.999))); +} + +#[test] +fn overlapping_graphics_keep_their_order_on_every_face() { + let d = document(); + // The wide red bar, listed second, reaches across the narrow blue one, listed first. Shaded, + // each face is one triangle. + let n = revolved(&CYLINDER, json!({"shade": true, "graphics": [{"symbol": "Blue", "x": 30.0}, {"symbol": "Wide"}]})); + let art = revolve_art_in(Some(&d), &n).unwrap(); + let mut both = 0; + art.walk(&mut |g| { + // A face with parts of graphics: the face's path, then the parts' paths. + let NodeKind::Group { children, clip: false } = &g.kind else { return }; + if !children.iter().all(|c| matches!(c.kind, NodeKind::Path { .. })) { + return; + } + let colors: Vec = children + .iter() + .filter_map(|c| { + let blue = !parts(c, true).is_empty(); + (blue || !parts(c, false).is_empty()).then_some(blue) + }) + .collect(); + if colors.contains(&true) && colors.contains(&false) { + both += 1; + assert!(colors.iter().position(|b| !b) > colors.iter().position(|b| *b), "{colors:?}"); + } + }); + assert!(both > 0); +} + +#[test] +fn a_graphic_past_the_end_reaches_the_curved_rim_and_no_further() { + let d = document(); + // A tube 50 from the axis with a cap at each end, in 10 segments, tilted to show its top: the + // bottom rim is an arc on the page whose lowest point, in front, lies between two corners of + // the faces. The wide bar runs 5 past the bottom of the profile. + for shade in [true, false] { + let mut b = BezPath::new(); + b.move_to((0.0, 0.0)); + b.line_to((0.0, 200.0)); + let p = json!({"offset": 50.0, "segments": 10, "rotationX": -30.0, "rotationY": 0.0, "rotationZ": 0.0, "shade": shade, "graphics": [{"symbol": "Wide", "y": 100.0}]}); + let mut n = Node::path(NodeId(7), PathData::from_bezpath(&b), Appearance::basic(Paint::solid(Color::rgb(0.5, 0.5, 0.5)), Paint::None, 0.0)); + n.appearance.effects.push(crate::new_effect(REVOLVE, &p).unwrap()); + let art = revolve_art_in(Some(&d), &n).unwrap(); + let mut lowest = f64::NEG_INFINITY; + art.walk(&mut |c| { + if let Some(b) = c.path_data().and_then(PathData::bounds) { + lowest = lowest.max(b.y1); + } + }); + let bar = reach(&parts(&art, false)); + assert!(near(bar.y1, lowest, 0.05), "shade {shade}: {bar:?} {lowest}"); + // A thin bar wholly past the end, 0.35 to 0.85 below it in front, lies between the faces' + // straight lower edge and the rim's arc there: it is drawn, inside the rim. + let mut thin = n.clone(); + let p = json!({"offset": 50.0, "segments": 10, "rotationX": -30.0, "rotationY": 0.0, "rotationZ": 0.0, "shade": shade, "graphics": [{"symbol": "Flat", "y": 100.6, "scale": 25.0}]}); + thin.appearance.effects = vec![crate::new_effect(REVOLVE, &p).unwrap()]; + let past = parts(&revolve_art_in(Some(&d), &thin).unwrap(), false); + assert!(!past.is_empty(), "shade {shade}"); + assert!(reach(&past).y1 <= lowest + 1e-6, "shade {shade}: {:?} {lowest}", reach(&past)); + } +} + +#[test] +fn under_several_lights_a_graphic_takes_each_faces_own_lit_art() { + let d = document(); + let lights = json!([{"color": "#ff8080", "rotation": 120.0}, {"color": "#8080ff", "rotation": -30.0}]); + let clips = |n: &Node| { + let mut count = 0; + revolve_art_in(Some(&d), n).unwrap().walk(&mut |c| count += usize::from(matches!(c.kind, NodeKind::Group { clip: true, .. }))); + count + }; + let plain = revolved(&CYLINDER, json!({"shade": true, "lights": lights})); + let mapped = revolved(&CYLINDER, json!({"shade": true, "lights": lights, "graphics": [{"symbol": "Red"}]})); + // Each part of the bar is the face's lit art clipped to the part: one clip more for the + // part, one for the face's own art inside it. + assert!(clips(&mapped) > clips(&plain), "{} {}", clips(&mapped), clips(&plain)); + // A lit face draws its paint under the face's light: a layer of the light's three channels, + // multiplied over the paint. Every part of the bar takes such a layer of its own, so the bar + // is shaded with each face's colored light; a bar drawn in flat red would add none. + let lit = |n: &Node| { + let mut count = 0; + revolve_art_in(Some(&d), n).unwrap().walk(&mut |c| count += usize::from(c.blend == vectorcraft_doc::color::BlendMode::Multiply)); + count + }; + assert!(lit(&mapped) > lit(&plain), "{} {}", lit(&mapped), lit(&plain)); +} + +#[test] +fn graphics_past_the_point_limit_are_refused() { + let mut d = document(); + let dots: Vec> = (0..2000) + .map(|i| { + let c = Point::new(f64::from(i % 50) * 12.0, f64::from(i / 50) * 12.0); + Arc::new(Node::path( + NodeId(0), + shapes::ellipse(Rect::new(c.x, c.y, c.x + 10.0, c.y + 10.0)), + Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0), + )) + }) + .collect(); + d.symbols.push(Symbol { dynamic: false, name: "Dots".into(), art: Arc::new(Node::group(NodeId(0), dots)) }); + let n = revolved(&CYLINDER, json!({})); + let p = |scale: f64| json!({"graphics": [{"symbol": "Dots", "scale": scale}]}); + assert!(validate_revolve_in(Some(&d), &n, &p(100.0)).is_ok()); + // At 100 times the size each dot is cut into hundreds of straight pieces. + let e = validate_revolve_in(Some(&d), &n, &p(10_000.0)).unwrap_err(); + assert!(e.contains("too complex"), "{e}"); +} + +#[test] +fn graphics_cut_into_too_many_parts_are_refused_on_the_object_and_on_a_fill() { + let mut d = document(); + // 4,000 thin bars across the side: few points each, but each is cut at every face it crosses. + let bars: Vec> = + (0..4000).map(|i| Arc::new(bar(Rect::new(0.0, f64::from(i) * 0.05, 300.0, f64::from(i) * 0.05 + 0.02), Color::BLACK))).collect(); + d.symbols.push(Symbol { dynamic: false, name: "Bars".into(), art: Arc::new(Node::group(NodeId(0), bars)) }); + let p = json!({"segments": 128, "graphics": [{"symbol": "Bars"}]}); + let n = revolved(&CYLINDER, json!({})); + let e = validate_revolve_in(Some(&d), &n, &p).unwrap_err(); + assert!(e.contains("too complex for this surface"), "{e}"); + assert!(validate_revolve_in(Some(&d), &n, &json!({"graphics": [{"symbol": "Red"}]})).is_ok()); + // The same on a Revolve on the object's fill. + let mut filled = n.clone(); + let fx = filled.appearance.effects.remove(0); + if let Some(AppearanceItem::Fill(f)) = filled.appearance.items.first_mut() { + f.effects.push(fx); + } + let e = crate::solids::validate_three_d_at_in(Some(&d), &filled, REVOLVE, &p, (Some(0), 0)).unwrap_err(); + assert!(e.contains("too complex for this surface"), "{e}"); +} + +#[test] +fn without_the_document_nothing_is_drawn_and_expand_keeps_the_graphics() { + let d = document(); + let n = revolved(&CYLINDER, json!({"graphics": [{"symbol": "Red"}]})); + assert!(parts(&revolve_art(&n).unwrap(), false).is_empty()); + let shown = parts(&revolve_art_in(Some(&d), &n).unwrap(), false); + let expanded = parts(&expand_revolve_art_in(Some(&d), &n).unwrap(), false); + assert!(!shown.is_empty()); + assert_eq!(shown, expanded); + // In a group the graphics go once, on the side of the member with the longest profile. + let mut member = n.clone(); + member.appearance.effects.clear(); + let mut short = member.clone(); + if let NodeKind::Path { path, .. } = &mut short.kind { + *path = PathData::from_bezpath(&{ + let mut b = BezPath::new(); + b.move_to((0.0, 80.0)); + b.line_to((30.0, 80.0)); + b.line_to((30.0, 120.0)); + b.line_to((0.0, 120.0)); + b + }); + } + let mut group = Node::group(NodeId(9), vec![Arc::new(short), Arc::new(member)]); + group.appearance.effects = n.appearance.effects.clone(); + assert_eq!(parts(&revolve_art_in(Some(&d), &group).unwrap(), false).len(), shown.len()); +} + +#[test] +fn revolve_takes_graphics_on_its_side_only() { + let front = json!({"graphics": [{"symbol": "Red"}]}); + let back = json!({"graphics": [{"symbol": "Red", "face": "back"}]}); + assert!(crate::solids::graphics::validate(REVOLVE, &front).is_ok()); + assert!(crate::solids::graphics::validate(REVOLVE, &back).unwrap_err().contains("side")); + assert!(crate::solids::graphics::validate(CLASSIC_REVOLVE, &front).is_err()); + let n = revolved(&CYLINDER, json!({})); + assert!(validate_revolve(&n, &back).is_err()); + // Changing the type keeps the front's graphics on Revolve's side and drops the back's. + let both = json!({"graphics": [{"symbol": "Red"}, {"symbol": "Blue", "face": "back"}]}); + let kept = three_d_params_as(crate::EXTRUDE, &both, REVOLVE); + assert_eq!(kept["graphics"].as_array().map(Vec::len), Some(1)); + assert_eq!(kept["graphics"][0]["symbol"], "Red"); + assert_eq!(three_d_params_as(REVOLVE, &front, crate::INFLATE).get("graphics"), None); +} + +#[test] +fn revolve_classic_draws_no_graphics_its_parameters_carry() { + let d = document(); + let mut n = revolved(&CYLINDER, json!({"graphics": [{"symbol": "Red"}]})); + assert!(!parts(&revolve_art_in(Some(&d), &n).unwrap(), false).is_empty()); + // A file can hold graphics on Revolve (Classic), which commands refuse: Revolve (Classic) + // draws its classic surface, without them. + if let Some(fx) = n.appearance.effects.first_mut() { + fx.id = CLASSIC_REVOLVE.into(); + } + assert!(parts(&revolve_art_in(Some(&d), &n).unwrap(), false).is_empty()); +} + +#[test] +fn a_group_with_no_member_to_carry_graphics_still_checks_their_art() { + let mut d = document(); + let dots: Vec> = (0..2000) + .map(|i| { + let c = Point::new(f64::from(i % 50) * 12.0, f64::from(i / 50) * 12.0); + Arc::new(Node::path( + NodeId(0), + shapes::ellipse(Rect::new(c.x, c.y, c.x + 10.0, c.y + 10.0)), + Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0), + )) + }) + .collect(); + d.symbols.push(Symbol { dynamic: false, name: "Dots".into(), art: Arc::new(Node::group(NodeId(0), dots)) }); + let n = revolved(&CYLINDER, json!({})); + let mut member = n.clone(); + member.appearance.effects.clear(); + member.appearance.items.clear(); + let mut group = Node::group(NodeId(9), vec![Arc::new(member)]); + group.appearance.effects = n.appearance.effects.clone(); + // No member has a fill or stroke, so none carries the graphics, but art past the limits is + // refused as it is on a group whose member carries them. + let e = validate_in(Some(&d), &group, REVOLVE, &json!({"graphics": [{"symbol": "Dots", "scale": 10_000.0}]})).unwrap_err(); + assert!(e.contains("too complex"), "{e}"); + assert!(validate_in(Some(&d), &group, REVOLVE, &json!({"graphics": [{"symbol": "Red"}]})).is_ok()); +} diff --git a/crates/effects/src/solids.rs b/crates/effects/src/solids.rs index 52739983a5..ef4ab373ab 100644 --- a/crates/effects/src/solids.rs +++ b/crates/effects/src/solids.rs @@ -20,13 +20,14 @@ pub use classic::{CLASSIC_EXTRUDE, CLASSIC_ROTATE, ROTATE_SURFACES, SHADING_COLO mod source; pub(crate) use source::{resolve, resolve_for}; -mod graphics; +pub(crate) mod graphics; pub use graphics::{ GRAPHICS, GraphicFrame, MAX_GRAPHICS, MappedGraphic, graphic_symbols, mapped_graphics, missing_symbol, names_graphic_symbol, rename_graphic_symbol, rename_graphic_symbol_in, takes_graphics, with_graphic, }; pub use graphics::{ - MAX_OFFSET as GRAPHIC_MAX_OFFSET, SCALE_RANGE as GRAPHIC_SCALE_RANGE, appearance_graphic_symbols, rename_appearance_graphic_symbol, + MAX_OFFSET as GRAPHIC_MAX_OFFSET, NOT_TAKEN as GRAPHICS_NOT_TAKEN, SCALE_RANGE as GRAPHIC_SCALE_RANGE, appearance_graphic_symbols, + rename_appearance_graphic_symbol, }; pub(crate) mod shadow; @@ -79,8 +80,9 @@ pub fn three_d_params_as(from: &str, params: &Value, to: &str) -> Value { } } } - // A plane has only a front, so graphics on the back cap are dropped. - if to == ROTATE + // A plane has only a front, and Revolve's graphics go on its side, named the front, so graphics + // on the back cap are dropped. + if (to == ROTATE || to == crate::REVOLVE) && let Some(Value::Array(list)) = out.get_mut(GRAPHICS) { list.retain(|g| g.get("face").and_then(Value::as_str) != Some(PlanarFace::Back.id())); @@ -504,7 +506,7 @@ pub fn validate_three_d_at_in(doc: Option<&Document>, n: &Node, id: &str, p: &Va (Some(_), _) if is_container(n) || source::resolves(n) => { Err("A 3D effect on a group or layer goes on the group itself, not on its fill or stroke".into()) } - (Some(item), index) if crate::revolve::is_revolve(id) => crate::revolve::validate_item_of(n, id, p, item, index), + (Some(item), index) if crate::revolve::is_revolve(id) => crate::revolve::validate_item_of(doc, n, id, p, item, index), (None, _) if crate::revolve::is_revolve(id) => crate::revolve::validate_in(doc, n, id, p), (item, index) => validate_solid_for(doc, n, id, p, (item, Some(index))), } @@ -1311,9 +1313,10 @@ pub fn graphic_frame(doc: Option<&Document>, n: &Node, item: Option) -> O } /// [`graphic_frame`] of the 3D effect at `index` in that list, which must be a visible Extrude & -/// Bevel or Rotate. +/// Bevel, Rotate or Revolve. Revolve's frame is its unrolled side seen from the front, centered on +/// the origin, with no face maps: it sizes a new graphic and places no handles. pub fn graphic_frame_at(doc: Option<&Document>, n: &Node, item: Option, index: usize) -> Option { - frame_of(doc, n, item, &|fx: &[Effect]| fx.get(index).filter(|e| e.visible && SOLIDS.contains(&e.id.as_str())).map(|e| (index, e))) + frame_of(doc, n, item, &|fx: &[Effect]| fx.get(index).filter(|e| e.visible && is_three_d(&e.id)).map(|e| (index, e))) } /// Does a visible geometry effect come after the 3D effect at `index` in the effects of `n` (on the @@ -1357,6 +1360,21 @@ fn frame_of(doc: Option<&Document>, n: &Node, item: Option, pick: &Pick<' } let p = crate::merged_params(&fx.id, &fx.params); let b = union_bounds(&shapes)?; + if fx.id == crate::REVOLVE { + // Revolve's graphics lie on its unrolled side (in a group, the side of the member with the + // longest profile): the frame is the part of it seen from the front, with no planar face + // to place a handle on. + let options = crate::revolve::revolve_options(&p); + let (w, h) = shapes + .iter() + .filter(|s| crate::revolve::surface_item(&s.items).is_some()) + .filter_map(|s| vectorcraft_three_d::revolve_surface_size(&s.path, b, options)) + .fold((0.0f64, 0.0f64), |best, size| if size.1 > best.1 { size } else { best }); + if w <= 0.0 || h <= 0.0 { + return None; + } + return Some(graphics::GraphicFrame::new(Rect::new(-w / 2.0, -h / 2.0, w / 2.0, h / 2.0), None, None)); + } let view = view_options(&p); if fx.id == ROTATE { let plane = vectorcraft_three_d::plane_face_map(b, view); diff --git a/crates/effects/src/solids/graphics.rs b/crates/effects/src/solids/graphics.rs index 6c5d8686a7..4957e20c56 100644 --- a/crates/effects/src/solids/graphics.rs +++ b/crates/effects/src/solids/graphics.rs @@ -8,6 +8,11 @@ //! seen from the front of that face), its size as a share of the symbol's own, and its turn //! (degrees, counterclockwise). On the back cap, x runs to the right as the back is seen from //! behind, so the graphic reads the right way round there. +//! +//! On Revolve the graphics lie on the swept side surface, unrolled flat +//! ([`vectorcraft_three_d::SurfaceCell`]): x and y are the offset of the graphic's center from the +//! middle of that surface, x around the axis and y along the profile, and each face of the side +//! draws the part of the graphics that falls on it ([`surface_parts`]). use std::sync::Arc; @@ -15,7 +20,7 @@ use serde_json::{Map, Value, json}; use vectorcraft_doc::color::{BlendMode, Paint}; use vectorcraft_doc::{Appearance, AppearanceItem, Document, FillLayer, Node, NodeId, NodeKind, Symbol}; use vectorcraft_geom::kurbo::{CubicBez, ParamCurve, PathEl, Shape}; -use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, Point, Rect, SubPath}; +use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, Point, Rect, SubPath, Vec2}; use vectorcraft_three_d::{FaceMap, Facet, PlanarFace}; /// The effect parameter that holds the graphics. @@ -41,6 +46,29 @@ const MAX_NESTING: usize = 8; /// places: as deep as an object may be drawn. const MAX_LEVELS: usize = 4 * vectorcraft_doc::MAX_DEPTH; +/// The error for graphics on a 3D effect that takes none. +pub const NOT_TAKEN: &str = "Graphics map onto the Plane, Extrude and Revolve object types"; + +/// The buckets around the unrolled side surface that the pieces of Revolve's graphics are sorted +/// into, so each face looks only at the pieces near it. +const SURFACE_BUCKETS: usize = 256; + +/// How closely the curves of a graphic on Revolve's side follow their shape when they are cut into +/// straight pieces, in points of the unrolled surface. +const SURFACE_TOLERANCE: f64 = 0.05; + +/// How far from the middle of Revolve's unrolled side a curve of a graphic may reach, in points: +/// as far as a Revolve profile's coordinates may. +const SURFACE_REACH: f64 = 1e8; + +/// The most points the parts of Revolve's graphics draw on its faces together, a graphic's area cut +/// at every face it crosses. Past it no graphic is drawn on that surface. +const MAX_SURFACE_POINTS: usize = 2_000_000; + +/// The width of the stroke of the same paint around each opaque part of a graphic on Revolve's +/// side, which covers the seams between the parts on neighboring faces. +const SURFACE_SEAM: f64 = 0.3; + /// The size range of a graphic, as a percentage of its symbol's own size. pub const SCALE_RANGE: (f64, f64) = (1.0, 10_000.0); @@ -116,10 +144,10 @@ impl MappedGraphic { } } -/// The 3D effects that take graphics: Extrude & Bevel (its caps) and Rotate (the plane), the two -/// object types of the 3D and Materials panel with planar faces. +/// The 3D effects that take graphics: Extrude & Bevel (its caps), Rotate (the plane) and Revolve +/// (its swept side). pub fn takes_graphics(id: &str) -> bool { - id == super::EXTRUDE || id == super::ROTATE + id == super::EXTRUDE || id == super::ROTATE || id == crate::REVOLVE } /// The graphics in parameters `p`, leaving out entries that are not valid (a file may hold @@ -131,8 +159,9 @@ pub fn mapped_graphics(p: &Value) -> Vec { } } -/// Are the graphics in parameters `p` of 3D effect `id` valid? Only Extrude & Bevel and Rotate take -/// graphics, and a plane has only a front. +/// Are the graphics in parameters `p` of 3D effect `id` valid? Only Extrude & Bevel, Rotate and +/// Revolve take graphics; a plane has only a front, and Revolve's graphics go on its side, named +/// the front. pub fn validate(id: &str, p: &Value) -> Result<(), String> { let list = match p.get(GRAPHICS) { None => return Ok(()), @@ -143,7 +172,7 @@ pub fn validate(id: &str, p: &Value) -> Result<(), String> { return Ok(()); } if !takes_graphics(id) { - return Err("Graphics map onto planar faces: use the Extrude or Plane object type".into()); + return Err(NOT_TAKEN.into()); } if list.len() > MAX_GRAPHICS { return Err(format!("`{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics")); @@ -153,6 +182,9 @@ pub fn validate(id: &str, p: &Value) -> Result<(), String> { if id == super::ROTATE && g.face == PlanarFace::Back { return Err("A plane has one face: map its graphics onto the front".into()); } + if id == crate::REVOLVE && g.face == PlanarFace::Back { + return Err("Revolve maps graphics onto its side: map them onto the front".into()); + } } Ok(()) } @@ -483,6 +515,357 @@ pub(super) fn face_art( Some(Node::new(id, NodeKind::Group { children: vec![Arc::new(clip), Arc::new(Node::group(id, children))], clip: true })) } +/// One area of a graphic placed on Revolve's unrolled side surface, cut into straight pieces. +struct Unrolled { + polygons: Vec>, + bounds: Rect, + rule: FillRule, + paint: Paint, + opacity: f32, + blend: BlendMode, + /// Where the graphic's art goes on the surface: its gradients and patterns are placed with it. + place: Affine, +} + +/// The areas of `graphics` (those of the front: Revolve's side) placed on the unrolled side +/// surface, cut into straight pieces. A graphic whose symbol `doc` does not have, or whose art is +/// past the limits of [`pieces_of`], is left out. `None` when the pieces take more than +/// [`MAX_ELEMENTS`] points together. +fn unrolled(doc: &Document, graphics: &[MappedGraphic]) -> Option> { + let mut pieces = vec![]; + let mut points = 0usize; + for g in graphics.iter().filter(|g| g.face == PlanarFace::Front) { + let Some(symbol) = doc.symbols.iter().find(|s| s.name == g.symbol) else { continue }; + let Ok(art) = pieces_of(doc, symbol) else { continue }; + let Some(bounds) = art.iter().filter_map(|p| p.path.bounds()).reduce(|a, b| a.union(b)) else { continue }; + let place = g.placement(bounds, Point::ZERO); + for piece in art { + let placed = place * piece.path.to_bezpath(); + let mut polygons = straight_pieces(&placed, &mut points)?; + polygons.retain(|p| p.len() >= 3 && p.iter().all(|q| q.is_finite())); + let Some(bounds) = polygons.iter().flatten().map(|p| Rect::from_points(*p, *p)).reduce(|a, b| a.union(b)) else { continue }; + pieces.push(Unrolled { polygons, bounds, rule: piece.rule, paint: piece.paint, opacity: piece.opacity, blend: piece.blend, place }); + } + } + Some(pieces) +} + +/// The contours of `path` cut into straight pieces within [`SURFACE_TOLERANCE`], adding the points +/// made to `points`. Each curve is cut on its own and the count is checked before the next one, so +/// the work stops at the first curve past [`MAX_ELEMENTS`] points: `None` then, and for a path with +/// a coordinate farther than [`SURFACE_REACH`] from the origin, which bounds the pieces of one +/// curve. +fn straight_pieces(path: &BezPath, points: &mut usize) -> Option>> { + let near = |p: &Point| p.x.abs() <= SURFACE_REACH && p.y.abs() <= SURFACE_REACH; + let mut polygons: Vec> = vec![]; + let mut current: Vec = vec![]; + let (mut start, mut last) = (Point::ZERO, Point::ZERO); + for el in path.elements() { + if *points > MAX_ELEMENTS { + return None; + } + match *el { + PathEl::MoveTo(p) => { + polygons.push(std::mem::take(&mut current)); + current.push(p); + *points += 1; + (start, last) = (p, p); + } + PathEl::LineTo(p) => { + current.push(p); + *points += 1; + last = p; + } + PathEl::ClosePath => { + polygons.push(std::mem::take(&mut current)); + last = start; + } + PathEl::QuadTo(a, p) | PathEl::CurveTo(_, a, p) => { + let first = if let PathEl::CurveTo(b, ..) = *el { b } else { a }; + if ![last, first, a, p].iter().all(near) { + return None; + } + vectorcraft_geom::kurbo::flatten([PathEl::MoveTo(last), *el], SURFACE_TOLERANCE, |cut| { + if let PathEl::LineTo(q) = cut { + current.push(q); + *points += 1; + } + }); + last = p; + } + } + } + polygons.push(current); + (*points <= MAX_ELEMENTS).then_some(polygons) +} + +/// Do the graphics in Revolve parameters `p` fit the limits with the symbols of `doc`? Their art, +/// cut into straight pieces on the side surface, may take up to [`MAX_ELEMENTS`] points together. +pub(crate) fn validate_surface_symbols(doc: &Document, p: &Value) -> Result<(), String> { + let list = mapped_graphics(p); + if list.is_empty() || unrolled(doc, &list).is_some() { + return Ok(()); + } + Err("The graphics are too complex: simplify the symbols' art".into()) +} + +/// The parts of `graphics` that fall on each of `faces`, a revolved surface's faces in drawing +/// order, for an object with id `id`: for each face, the nodes to draw right after it. Only faces +/// of the swept side that show their outside to the viewer carry a part, so a graphic narrows +/// toward the silhouette, is hidden past it and is covered by the nearer faces drawn after it. +/// `shade` gives the paint of a solid color on a face, as the surface under it is shaded; the +/// colors of gradients and patterns are multiplied by the face's light. A graphic whose symbol +/// `doc` does not have, or that is past the limits of its art, draws nothing. `None` past +/// [`MAX_ELEMENTS`] points together before they are cut at the faces, or [`MAX_SURFACE_POINTS`] +/// after: commands refuse such graphics, and a loaded file draws the surface without them. +pub(crate) fn surface_parts( + doc: Option<&Document>, + id: NodeId, + graphics: &[MappedGraphic], + faces: &[vectorcraft_three_d::Face], + shade: &dyn Fn(&vectorcraft_three_d::Face, vectorcraft_doc::color::Color) -> Paint, +) -> Option>>> { + let mut out: Vec>> = vec![vec![]; faces.len()]; + let Some(doc) = doc else { return Some(out) }; + let pieces = unrolled(doc, graphics)?; + let Some(all) = pieces.iter().map(|p| p.bounds).reduce(|a, b| a.union(b)) else { return Some(out) }; + // Each piece listed in the buckets of the surface's x its bounds reach across. + let width = (all.width() / SURFACE_BUCKETS as f64).max(1e-9); + let bucket = |x: f64| (((x - all.x0) / width).floor().max(0.0) as usize).min(SURFACE_BUCKETS - 1); + let mut buckets: Vec> = vec![vec![]; SURFACE_BUCKETS]; + for (k, p) in pieces.iter().enumerate() { + for b in buckets.get_mut(bucket(p.bounds.x0)..=bucket(p.bounds.x1)).into_iter().flatten() { + b.push(k); + } + } + let mut seen = vec![usize::MAX; pieces.len()]; + let mut drawn = 0usize; + let mut triangle_id = 0usize; + for (face, parts) in faces.iter().zip(out.iter_mut()) { + let Some(cell) = face.surface.as_ref().filter(|c| c.outward && !face.cap) else { continue }; + if cell.uv.len() != cell.page.len() || !(3..=4).contains(&cell.uv.len()) { + continue; + } + let triangles: &[[usize; 3]] = if cell.uv.len() == 3 { &[[0, 1, 2]] } else { &[[0, 1, 2], [0, 2, 3]] }; + for corners in triangles { + triangle_id += 1; + let pick = |of: &[Point]| corners.iter().map(|k| of.get(*k).copied()).collect::>>(); + let (Some(uv), Some(page)) = (pick(&cell.uv), pick(&cell.page)) else { continue }; + let (Some(map), Some(window)) = (triangle_map(&uv, &page), counterclockwise(&uv)) else { continue }; + // A face along an end cap's ring has that edge curved on the page: its parts are cut + // from a larger triangle and then to the face's own outline, so they reach the curve + // where the graphic runs past the end of the profile. A four-cornered face is cut into + // two triangles along its diagonal from corner 0 to corner 2: each takes the part of + // the outline on its own side of it. + let window = if face.outline.is_some() { grown(window, 3.0) } else { window }; + // The pieces are looked up over the whole of the window they are cut to. + let Some(reach) = window.iter().map(|p| Rect::from_points(*p, *p)).reduce(|a, b| a.union(b)) else { continue }; + if reach.x1 < all.x0 || reach.x0 > all.x1 || reach.y1 < all.y0 || reach.y0 > all.y1 { + continue; + } + // The pieces near the triangle, each once, in the graphics' drawing order. + let mut near = vec![]; + for b in buckets.get(bucket(reach.x0)..=bucket(reach.x1)).into_iter().flatten() { + for &k in b { + let Some(slot) = seen.get_mut(k) else { continue }; + if *slot != triangle_id { + *slot = triangle_id; + near.push(k); + } + } + } + near.retain(|k| { + pieces + .get(*k) + .is_some_and(|p| p.bounds.x1 >= reach.x0 && p.bounds.x0 <= reach.x1 && p.bounds.y1 >= reach.y0 && p.bounds.y0 <= reach.y1) + }); + if near.is_empty() { + continue; + } + near.sort_unstable(); + let own = corners.iter().find(|k| **k != 0 && **k != 2).and_then(|k| cell.page.get(*k)).filter(|_| triangles.len() == 2); + let rim = face.outline.as_ref().map(|outline| match (own, cell.page.first(), cell.page.get(2)) { + (Some(&toward), Some(&a), Some(&b)) => { + let side = side_of(a, b, toward); + vectorcraft_pathops::boolean(outline, FillRule::NonZero, &side, FillRule::NonZero, vectorcraft_pathops::BoolOp::Intersect) + } + _ => outline.clone(), + }); + let rim = rim.as_ref(); + for k in near { + let Some(piece) = pieces.get(k) else { continue }; + let mut path = BezPath::new(); + for polygon in &piece.polygons { + let cut = clip_to(polygon, &window); + let Some((first, rest)) = cut.split_first() else { continue }; + path.move_to(map * *first); + rest.iter().for_each(|q| path.line_to(map * *q)); + path.close_path(); + drawn = drawn.saturating_add(cut.len()); + } + if drawn > MAX_SURFACE_POINTS { + return None; + } + if path.elements().is_empty() { + continue; + } + let (path, rule) = match rim { + Some(outline) => { + let cut = vectorcraft_pathops::boolean( + &PathData::from_bezpath(&path), + piece.rule, + outline, + FillRule::NonZero, + vectorcraft_pathops::BoolOp::Intersect, + ); + (cut.to_bezpath(), FillRule::NonZero) + } + None => (path, piece.rule), + }; + if path.elements().is_empty() { + continue; + } + parts.push(Arc::new(surface_piece(id, piece, (path, rule), map, face, shade))); + } + } + } + Some(out) +} + +/// The node of the part `path` (on the page, filled under `rule`) of `piece`, which `map` takes +/// from the unrolled surface onto `face`. +fn surface_piece( + id: NodeId, + piece: &Unrolled, + (path, rule): (BezPath, FillRule), + map: Affine, + face: &vectorcraft_three_d::Face, + shade: &dyn Fn(&vectorcraft_three_d::Face, vectorcraft_doc::color::Color) -> Paint, +) -> Node { + let gradient_map = map * piece.place; + // Under several lights a face's light varies across it in each channel: a solid color draws + // as the face's own lit art in that color, clipped to the part. + if let (Some(c), Some(light)) = (piece.paint.color().filter(|_| matches!(piece.paint, Paint::Solid { .. })), face.rgb_gradient) { + let lit = crate::lighting::rgb_gradient_art(id, &face.path(), &Paint::solid(c), light); + let mut clip = Node::path(id, PathData::from_bezpath(&path), Appearance::default()); + if let NodeKind::Path { rule: r, .. } = &mut clip.kind { + *r = rule; + } + let mut group = Node::new(id, NodeKind::Group { children: vec![Arc::new(clip), Arc::new(lit)], clip: true }); + group.opacity = piece.opacity; + group.blend = piece.blend; + return group; + } + let mut paint = piece.paint.clone(); + if let Paint::Pattern { xf, .. } = &mut paint { + *xf = gradient_map * *xf; + } + let solid = paint.color().filter(|_| matches!(paint, Paint::Solid { .. })); + let mut fill = FillLayer::new(paint); + fill.opacity = piece.opacity; + fill.blend = piece.blend; + let mut appearance = Appearance { items: vec![AppearanceItem::Fill(fill)], ..Default::default() }; + appearance.transform_gradients(gradient_map); + for item in appearance.items.iter_mut() { + if let AppearanceItem::Fill(f) = item { + match solid { + Some(c) => f.paint = shade(face, c), + None => { + vectorcraft_doc::recolor::map_paint(&mut f.paint, &|c| crate::lighting::shade(c, face.illumination)); + } + } + } + } + // Parts on neighboring faces meet edge to edge: an opaque part takes a narrow stroke of its + // paint over the seam, as the faces do. A transparent one would show the overlap. + if piece.opacity >= 1.0 + && piece.blend == BlendMode::Normal + && let Some(AppearanceItem::Fill(f)) = appearance.items.first() + { + let mut seam = vectorcraft_doc::StrokeLayer::new(f.paint.clone(), SURFACE_SEAM); + seam.join = vectorcraft_doc::LineJoin::Round; + appearance.items.push(AppearanceItem::Stroke(seam)); + } + let mut node = Node::path(id, PathData::from_bezpath(&path), appearance); + if let NodeKind::Path { rule: r, .. } = &mut node.kind { + *r = rule; + } + node +} + +/// A region far larger than the face on the side of the line through `a` and `b` that `toward` is +/// on: a rectangle with one edge along the line, reaching a thousand times the line's length past +/// its ends and away from it. +fn side_of(a: Point, b: Point, toward: Point) -> PathData { + let along = b - a; + let mut across = Vec2::new(-along.y, along.x); + if across.dot(toward - a) < 0.0 { + across = -across; + } + let (far, wide) = (across * 1000.0, along * 1000.0); + let mut out = BezPath::new(); + out.move_to(a - wide); + out.line_to(b + wide); + out.line_to(b + wide + far); + out.line_to(a - wide + far); + out.close_path(); + PathData::from_bezpath(&out) +} + +/// Triangle `t` scaled by `factor` about its centroid, wound as it was. +fn grown(t: [Point; 3], factor: f64) -> [Point; 3] { + let c = Point::new((t[0].x + t[1].x + t[2].x) / 3.0, (t[0].y + t[1].y + t[2].y) / 3.0); + t.map(|p| c + (p - c) * factor) +} + +/// The affine map that takes the corners `from` of a triangle onto `to`. `None` for a triangle +/// with no area or a map that is not finite. +fn triangle_map(from: &[Point], to: &[Point]) -> Option { + let ([u0, u1, u2], [p0, p1, p2]) = (<[Point; 3]>::try_from(from).ok()?, <[Point; 3]>::try_from(to).ok()?); + let (a, b) = (u1 - u0, u2 - u0); + let det = a.x * b.y - b.x * a.y; + if det.abs() <= 1e-12 * (a.hypot2() + b.hypot2()).max(1e-300) { + return None; + } + let (c, d) = (p1 - p0, p2 - p0); + let m = [(c.x * b.y - d.x * a.y) / det, (c.y * b.y - d.y * a.y) / det, (d.x * a.x - c.x * b.x) / det, (d.y * a.x - c.y * b.x) / det]; + let xf = Affine::new([m[0], m[1], m[2], m[3], p0.x - m[0] * u0.x - m[2] * u0.y, p0.y - m[1] * u0.x - m[3] * u0.y]); + xf.as_coeffs().iter().all(|v| v.is_finite()).then_some(xf) +} + +/// Triangle `t` wound counterclockwise (y up), as [`clip_to`] reads its window. `None` without +/// three corners. +fn counterclockwise(t: &[Point]) -> Option<[Point; 3]> { + let [a, b, c] = <[Point; 3]>::try_from(t).ok()?; + Some(if (b - a).cross(c - a) < 0.0 { [a, c, b] } else { [a, b, c] }) +} + +/// The part of `polygon` inside the convex `window` (one step of Sutherland and Hodgman's clip for +/// each of its edges). A polygon that is not convex keeps its area, with edges along the window's +/// sides where it leaves and comes back. +fn clip_to(polygon: &[Point], window: &[Point; 3]) -> Vec { + let mut out = polygon.to_vec(); + for k in 0..3 { + let (a, b) = (window[k], window[(k + 1) % 3]); + let side = |p: Point| (b - a).cross(p - a); + let input = std::mem::take(&mut out); + for (i, &p) in input.iter().enumerate() { + let q = input[(i + 1) % input.len()]; + let (sp, sq) = (side(p), side(q)); + if sp >= 0.0 { + out.push(p); + } + if (sp >= 0.0) != (sq >= 0.0) { + out.push(p.lerp(q, sp / (sp - sq))); + } + } + if out.len() < 3 { + return vec![]; + } + } + out +} + /// The bounds of the art symbol `name` of `doc` draws as a graphic, in the symbol's coordinates. pub(super) fn art_bounds(doc: &Document, name: &str) -> Option { let symbol = doc.symbols.iter().find(|s| s.name == name)?; diff --git a/crates/effects/src/solids/tests_graphics.rs b/crates/effects/src/solids/tests_graphics.rs index aa73535fc5..f336dca4b2 100644 --- a/crates/effects/src/solids/tests_graphics.rs +++ b/crates/effects/src/solids/tests_graphics.rs @@ -505,7 +505,10 @@ fn graphics_are_checked() { } assert!(check(ROTATE, json!([{"symbol": "Mark", "face": "back"}])).is_err()); assert!(check(INFLATE, json!([{"symbol": "Mark"}])).is_err()); - assert!(validate_three_d_params(crate::REVOLVE, &json!({"graphics": [{"symbol": "Mark"}]})).is_err()); + // Revolve takes graphics on its side, named the front; Revolve (Classic) takes none. + assert!(validate_three_d_params(crate::REVOLVE, &json!({"graphics": [{"symbol": "Mark"}]})).is_ok()); + assert!(validate_three_d_params(crate::REVOLVE, &json!({"graphics": [{"symbol": "Mark", "face": "back"}]})).is_err()); + assert!(validate_three_d_params(crate::CLASSIC_REVOLVE, &json!({"graphics": [{"symbol": "Mark"}]})).is_err()); // A loaded file's invalid entries are left out when drawn. assert_eq!(mapped_graphics(&json!({"graphics": [{"symbol": "Mark"}, {"face": "back"}, 3]})).len(), 1); } @@ -692,3 +695,36 @@ fn a_symbol_instance_in_a_graphic_draws_as_the_canvas_shows_it() { let area: f64 = pieces.iter().map(|p| p.path.to_bezpath().area().abs()).sum(); assert!((area - 30_000.0).abs() < 1e-3, "{area}"); } + +#[test] +fn curves_are_cut_one_at_a_time_and_the_work_stops_at_the_limit() { + let ellipse = shapes::ellipse(Rect::new(0.0, 0.0, 10.0, 6.0)).to_bezpath(); + // Cut curve by curve, a path gives the points it gives cut whole. + for scale in [1.0, 100.0, 10_000.0] { + let placed = Affine::scale(scale) * ellipse.clone(); + let mut whole = vec![]; + vectorcraft_geom::kurbo::flatten(placed.iter(), SURFACE_TOLERANCE, |el| { + if let PathEl::MoveTo(p) | PathEl::LineTo(p) = el { + whole.push(p); + } + }); + let mut points = 0; + let cut: Vec = straight_pieces(&placed, &mut points).unwrap().into_iter().flatten().collect(); + assert_eq!(points, cut.len()); + assert_eq!(cut.len(), whole.len(), "{scale}"); + assert!(cut.iter().zip(&whole).all(|(a, b)| a.distance(*b) < 1e-9), "{scale}"); + } + // Past the limit no further curve is cut: of 1,000 ellipses that each take more than 3,000 + // points, the count stops within one curve of the limit. + let mut many = BezPath::new(); + (0..1000).for_each(|_| many.extend(Affine::scale(10_000.0) * ellipse.clone())); + let mut points = 0; + assert!(straight_pieces(&many, &mut points).is_none()); + assert!(points > MAX_ELEMENTS && points < MAX_ELEMENTS + 2000, "{points}"); + // A curve that reaches farther than any surface, or to no finite point, is not cut at all. + for scale in [1e12, f64::INFINITY] { + let mut points = 0; + assert!(straight_pieces(&(Affine::scale(scale) * ellipse.clone()), &mut points).is_none()); + assert!(points <= 1, "{scale}: {points}"); + } +} diff --git a/crates/engine/src/cmd/effectcmd/graphics.rs b/crates/engine/src/cmd/effectcmd/graphics.rs index 3365a1b764..3f95ae0518 100644 --- a/crates/engine/src/cmd/effectcmd/graphics.rs +++ b/crates/engine/src/cmd/effectcmd/graphics.rs @@ -1,5 +1,5 @@ //! Window › 3D and Materials › Materials › Graphics: art kept as a document symbol (Add as Single -//! Graphic) and mapped onto the planar faces of 3D objects (Extrude & Bevel's caps, a plane). The +//! Graphic) and mapped onto 3D objects (Extrude & Bevel's caps, a plane, Revolve's side). The //! graphics an object shows are the `graphics` parameter of its 3D effect, which `effect.setParams` //! also edits. @@ -28,7 +28,7 @@ pub(super) fn specs() -> Vec { "Map Graphic", [], None, - "{symbol: name of a document symbol, face?: front|back (front; Plane has only a front; the back reads left to right as seen from behind), x?: pt, y?: pt (0, 0: the offset of the graphic's center from the center of the object's bounds, in the face's own plane), scale?: % (1..10000; default 100, or less so the graphic fits inside the object), rotation?: degrees (-360..360, 0; counterclockwise), index?: int (the 3D effect's position; default: each object's first 3D effect, its own before its fills' and strokes'), item?: appearance item index|null (refused without index; as effect.setParams), ids?|id?} add a graphic to the 3D effect of each selected object, drawn on that face turned, foreshortened and shaded with it and clipped to it; every object's 3D effect must be Extrude & Bevel (on a solid cap) or Rotate (the Plane type); one undo step → {ids, graphic}", + "{symbol: name of a document symbol, face?: front|back (front; Plane has only a front; the back reads left to right as seen from behind; on Revolve the front is its swept side, which is the only face), x?: pt, y?: pt (0, 0: the offset of the graphic's center from the center of the object's bounds, in the face's own plane; on Revolve from the middle of the side unrolled flat, x around the axis and y along the profile), scale?: % (1..10000; default 100, or less so the graphic fits inside the object, on Revolve inside the half of the side seen from the front), rotation?: degrees (-360..360, 0; counterclockwise), index?: int (the 3D effect's position; default: each object's first 3D effect, its own before its fills' and strokes'), item?: appearance item index|null (refused without index; as effect.setParams), ids?|id?} add a graphic to the 3D effect of each selected object, drawn on that face turned, foreshortened and shaded with it and clipped to it (on Revolve wrapped around the side, and drawn only where its outside faces the viewer); every object's 3D effect must be Extrude & Bevel (on a solid cap), Rotate (the Plane type) or Revolve; one undo step → {ids, graphic}", has_doc, map_graphic ), @@ -111,7 +111,7 @@ fn map_graphic(s: &mut Session, p: &Value) -> Result { return Err(bad(C, format!("object {} needs a 3D effect at index {index}", id.0))); }; if !effects::takes_graphics(&effect.id) { - return Err(bad(C, format!("object {}: Graphics map onto planar faces: use the Extrude or Plane object type", id.0))); + return Err(bad(C, format!("object {}: {}", id.0, effects::GRAPHICS_NOT_TAKEN))); } // A hollow Extrude & Bevel keeps the graphics it has, to show when Cap is turned on again, // but has no cap to show a new one on. diff --git a/crates/engine/src/cmd/effectcmd/graphics_tests.rs b/crates/engine/src/cmd/effectcmd/graphics_tests.rs index 125ba82514..a9d3a754ce 100644 --- a/crates/engine/src/cmd/effectcmd/graphics_tests.rs +++ b/crates/engine/src/cmd/effectcmd/graphics_tests.rs @@ -68,12 +68,37 @@ fn a_large_graphic_starts_inside_its_object() { assert!((scale - 100.0 * 100.0 / 401.0).abs() < 1e-9, "{scale}"); } +#[test] +fn map_graphic_puts_a_graphic_on_the_side_of_a_revolve() { + let (mut s, id) = setup("threeD.revolve"); + let plain = vectorcraft_render::effects::revolve_art_in(Some(&s.doc().unwrap().doc), s.doc().unwrap().doc.node(id).unwrap()); + let history = undo_len(&s); + s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "ids": [id.0]})).unwrap(); + assert_eq!(graphics(&s, id), json!([{"symbol": "Mark", "face": "front", "x": 0.0, "y": 0.0, "scale": 100.0, "rotation": 0.0}])); + assert_eq!(undo_len(&s), history + 1); + let d = &s.doc().unwrap().doc; + assert_ne!(vectorcraft_render::effects::revolve_art_in(Some(d), d.node(id).unwrap()), plain, "the graphic is drawn"); + // A large graphic starts inside the half of the side seen from the front: 100π around the + // axis (the square's far edge is 100 from it) and 300 along the profile (its edge on the axis + // sweeps nothing). + let big = s.execute("path.create", &json!({"d":"M0 0L400 0L400 200L0 200Z"})).unwrap()["id"].clone(); + s.execute("threeD.addGraphic", &json!({"name": "Big", "ids": [big]})).unwrap(); + s.execute("threeD.mapGraphic", &json!({"symbol": "Big", "ids": [id.0]})).unwrap(); + let scale = graphics(&s, id)[1]["scale"].as_f64().unwrap(); + assert!((scale - 100.0 * 100.0 * std::f64::consts::PI / 401.0).abs() < 1e-6, "{scale}"); + // The side is its only face. + let history = undo_len(&s); + let e = s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "face": "back", "ids": [id.0]})).unwrap_err().to_string(); + assert!(e.contains("side"), "{e}"); + assert_eq!(undo_len(&s), history); +} + #[test] fn map_graphic_refuses_what_cannot_take_it_and_changes_nothing() { let (mut s, id) = setup("threeD.inflate"); let history = undo_len(&s); let e = s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "ids": [id.0]})).unwrap_err().to_string(); - assert!(e.contains("Extrude or Plane"), "{e}"); + assert!(e.contains("Plane, Extrude and Revolve"), "{e}"); let (mut s, id) = setup("threeD.rotate"); for (p, says) in [ (json!({"symbol": "Gone"}), "no symbol named"), diff --git a/crates/three-d/src/lib.rs b/crates/three-d/src/lib.rs index 7b778498e6..0007f22049 100644 --- a/crates/three-d/src/lib.rs +++ b/crates/three-d/src/lib.rs @@ -23,7 +23,8 @@ pub use mesh::{Mesh, extrude_mesh, inflate_meshes, plane_mesh, revolve_mesh}; mod shadow; pub use shadow::{MAX_SHADOW_FACES, Shadow, ShadowCaster, ShadowPlane, ShadowPosition, TOO_COMPLEX_SHADOW}; -use vectorcraft_geom::{BezPath, FillRule, ParamCurve, PathData, Point, Rect, Shape, Vec2, kurbo::ParamCurveDeriv}; +use vectorcraft_geom::kurbo::{ParamCurveArclen, ParamCurveDeriv}; +use vectorcraft_geom::{BezPath, FillRule, ParamCurve, PathData, Point, Rect, Shape, Vec2}; /// Resource limits shared by desktop, CLI and browser evaluation. const MAX_PROFILE_POINTS: usize = 16_384; @@ -104,6 +105,10 @@ pub struct Revolve { /// Samples for each curved profile segment, from [`revolve_curve_samples`] for the surfaces of /// one object. `None` plans them from the profile alone. pub curve_samples: Option, + /// Graphics are mapped onto the side: its faces carry a [`SurfaceCell`], and a closed profile + /// that does not touch the axis takes an anchor where its side is cut. Off by default, which + /// leaves the faces as they are without graphics. + pub map_surface: bool, } /// The default light's Rotation and Height: the light of the earlier default direction (45° to the @@ -133,6 +138,7 @@ impl Default for Revolve { smooth_shading: true, cap_ends: true, curve_samples: None, + map_surface: false, } } } @@ -362,6 +368,235 @@ pub struct Face { pub cap: bool, /// Bounded radial strips for a body face joining two curved endpoint rings. pub visibility_pieces: Option>>, + /// For a face of the swept side (not an end cap): where its corners lie on the side surface, + /// for a graphic mapped onto it. + pub surface: Option, +} + +/// Where a face of Revolve's swept side lies on the side surface, unrolled flat: x runs around the +/// axis and y along the profile, in points. x is the angle from the middle of the surface times the +/// point's own distance from the axis, so a graphic keeps its size at every distance and wraps +/// farther around the axis where the profile comes closer to it. y is the length along the profile +/// from its middle, increasing toward the profile's lower end; on a closed contour that does not +/// touch the axis the middle is where its outer side crosses the middle height of its bounds. The +/// middle of the surface around the axis is the side that faces the viewer before the rotation +/// ([`surface_middle`]). Only the faces of the longest contour of a compound profile carry a cell. +#[derive(Clone, Debug, PartialEq)] +pub struct SurfaceCell { + /// The corners of the face on the page: its `points` before an edge along an end cap's ring + /// is curved. + pub page: Vec, + /// The surface point of each of `page`, in the same order. + pub uv: Vec, + /// The face shows the outside of the surface (the side away from the axis, or out of the + /// region a closed profile encloses) to the viewer. + pub outward: bool, +} + +/// The size of Revolve's side surface unrolled ([`SurfaceCell`]), which is the side of the +/// profile's longest contour: its width around the axis at that contour's largest distance from it +/// over the part of the sweep a viewer can see from the front ([`surface_span`]: half a turn at +/// most), and the contour's length. `None` when the profile has no length or lies on the axis. +pub fn revolve_surface_size(path: &PathData, bounds: Rect, options: Revolve) -> Option<(f64, f64)> { + let o = options.sanitized(); + let axis = revolve_projection(bounds, o).origin.x; + let sp = path.subpaths.get(longest_contour(path, axis)?)?; + let length = swept_length(sp, axis); + let segments = if sp.closed { sp.anchors.len() } else { sp.anchors.len().saturating_sub(1) }; + let radius = (0..segments).map(|i| sp.segment(i).bounding_box()).fold(0.0f64, |r, b| r.max((b.x0 - axis).abs()).max((b.x1 - axis).abs())); + let width = surface_span(o.angle.to_radians(), o.edge) * radius; + (width.is_finite() && length.is_finite() && width > 0.0 && length > 0.0).then_some((width, length)) +} + +/// The length of contour `sp` that sweeps a surface about `axis`: every segment but those that lie +/// wholly on the axis. +fn swept_length(sp: &vectorcraft_geom::SubPath, axis: f64) -> f64 { + let segments = if sp.closed { sp.anchors.len() } else { sp.anchors.len().saturating_sub(1) }; + (0..segments) + .map(|i| { + // A segment sweeps nothing only when the whole of it lies on the axis: its control + // points as well as its ends. + let c = sp.segment(i); + let on_axis = [c.p0, c.p1, c.p2, c.p3].iter().all(|p| (p.x - axis).abs() <= 1e-9); + if on_axis { 0.0 } else { ParamCurveArclen::arclen(&c, 1e-3) } + }) + .sum() +} + +/// The contour of `path` with the longest [`swept_length`] about `axis` (the first of equal ones), +/// which carries Revolve's graphics. `None` when no contour sweeps a surface. +fn longest_contour(path: &PathData, axis: f64) -> Option { + path.subpaths + .iter() + .map(|sp| swept_length(sp, axis)) + .enumerate() + .filter(|(_, l)| l.is_finite() && *l > 0.0) + .fold(None, |best: Option<(usize, f64)>, (k, l)| if best.is_some_and(|(_, top)| top >= l) { best } else { Some((k, l)) }) + .map(|(k, _)| k) +} + +/// The angle of a Revolve sweep of `sweep` radians, about an axis on the profile's `edge`, at the +/// middle of its side surface ([`SurfaceCell`]). Before the rotation the viewer looks straight at +/// the angle 90° with the axis on the left and 270° with it on the right, and sees the half turn +/// around it. The middle is the middle of the part of the sweep in that half turn, or half the +/// sweep when no part is in it. +fn surface_middle(sweep: f64, edge: Edge) -> f64 { + use std::f64::consts::{FRAC_PI_2, PI}; + match edge { + Edge::Left => FRAC_PI_2.min(sweep / 2.0), + Edge::Right if sweep > PI => (3.0 * FRAC_PI_2).min((PI + sweep) / 2.0), + Edge::Right => sweep / 2.0, + } +} + +/// The angle of a Revolve sweep of `sweep` radians about an axis on `edge` that a viewer sees from +/// the front before the rotation, about [`surface_middle`]: the part of the sweep in the half turn +/// facing the viewer, or the whole sweep when no part is in it. +fn surface_span(sweep: f64, edge: Edge) -> f64 { + use std::f64::consts::PI; + match edge { + Edge::Right if sweep > PI => (sweep - PI).min(PI), + _ => sweep.min(PI), + } +} + +/// The surface y ([`SurfaceCell`]) of each end of each piece of a contour's profile `profile` +/// about `axis`: the length along the profile from its middle, counted from just after the +/// pieces that lie on the axis (which sweep no surface and add no length) on a closed contour. +fn along_profile(profile: &[Point], axis: f64, closed: bool) -> Vec<[f64; 2]> { + let n = profile.len().saturating_sub(1); + if n == 0 { + return vec![]; + } + let on_axis = |k: usize| match (profile.get(k), profile.get(k + 1)) { + (Some(a), Some(b)) => (a.x - axis).abs() <= 1e-9 && (b.x - axis).abs() <= 1e-9, + _ => true, + }; + if closed + && !(0..n).any(&on_axis) + && let Some(out) = around_ring(profile, axis, n) + { + return out; + } + let start = if closed { (0..n).find(|&k| on_axis((k + n - 1) % n) && !on_axis(k)).unwrap_or(0) } else { 0 }; + let mut out = vec![[0.0; 2]; n]; + let mut length = 0.0; + for step in 0..n { + let k = (start + step) % n; + let piece = if on_axis(k) { 0.0 } else { profile.get(k).zip(profile.get(k + 1)).map_or(0.0, |(a, b)| a.distance(*b)) }; + if let Some(slot) = out.get_mut(k) { + *slot = [length, length + piece]; + } + length += piece; + } + // y increases toward the profile's lower end on the page: the end of an open contour, or the + // point half way along a closed one. + let middle = length / 2.0; + let first = profile.get(start).map_or(0.0, |p| p.y); + let end = if closed { + (0..n) + .map(|step| (start + step) % n) + .find_map(|k| { + let [a, b] = *out.get(k)?; + let (p, q) = (profile.get(k)?, profile.get(k + 1)?); + (b >= middle).then(|| p.y + (q.y - p.y) * if b > a { (middle - a) / (b - a) } else { 0.0 }) + }) + .unwrap_or(first) + } else { + profile.last().map_or(first, |p| p.y) + }; + let sign = if end >= first { 1.0 } else { -1.0 }; + out.into_iter().map(|[a, b]| [(a - middle) * sign, (b - middle) * sign]).collect() +} + +/// [`along_profile`] of a closed contour `profile` of `n` pieces with none on `axis`: y is 0 where +/// the contour's outer side (its crossing farthest from the axis) crosses the middle height of its +/// bounds and increases from there in the direction that runs down the page. The contour is cut at +/// its anchor nearest half way around from there, on its far side. `None` when the contour has no +/// height or no length. +fn around_ring(profile: &[Point], axis: f64, n: usize) -> Option> { + let RingFrame { ends, length, at, sign } = ring_frame(profile, axis, n)?; + // The cut is at the anchor nearest half way around from the crossing, so no piece runs across + // it: the pieces run on from there, once around. [`ring_cut`] puts an anchor there. + let opposite = at + length / 2.0; + let round = |d: f64| { + let d = d.rem_euclid(length); + d.min(length - d) + }; + let cut = ends + .iter() + .map(|[a, _]| *a) + .fold(None, |best: Option, a| if best.is_some_and(|b| round(b - opposite) <= round(a - opposite)) { best } else { Some(a) })?; + let first = (cut - at).rem_euclid(length) - length; + Some( + ends.into_iter() + .map(|[a, b]| { + let s = first + (a - cut).rem_euclid(length); + [s * sign, (s + (b - a)) * sign] + }) + .collect(), + ) +} + +/// Where a closed contour `profile` with no piece on `axis` is cut for [`around_ring`]: the piece +/// that the point half way around from its outer crossing lies inside, and how far along it, when +/// that point is not an anchor already. `None` otherwise, or for a contour that [`around_ring`] +/// does not measure. +fn ring_cut(profile: &[Point], axis: f64) -> Option<(usize, f64)> { + let n = profile.len().saturating_sub(1); + let on_axis = |k: usize| match (profile.get(k), profile.get(k + 1)) { + (Some(a), Some(b)) => (a.x - axis).abs() <= 1e-9 && (b.x - axis).abs() <= 1e-9, + _ => true, + }; + if n == 0 || (0..n).any(on_axis) { + return None; + } + let RingFrame { ends, length, at, .. } = ring_frame(profile, axis, n)?; + let opposite = (at + length / 2.0).rem_euclid(length); + ends.iter().enumerate().find_map(|(k, [a, b])| { + let t = if b > a { (opposite - a) / (b - a) } else { return None }; + (t > 1e-9 && t < 1.0 - 1e-9).then_some((k, t)) + }) +} + +/// The pieces of a closed contour, measured for [`around_ring`]. +struct RingFrame { + /// Each piece's length along the contour from its first anchor, at each end. + ends: Vec<[f64; 2]>, + /// The contour's length. + length: f64, + /// The length along the contour of its crossing farthest from the axis at the middle height + /// of its bounds. + at: f64, + /// 1 when the contour runs down the page there, -1 when it runs up. + sign: f64, +} + +/// [`RingFrame`] of closed contour `profile` of `n` pieces about `axis`. `None` when the contour +/// has no height or no length. +fn ring_frame(profile: &[Point], axis: f64, n: usize) -> Option { + let (top, bottom) = profile.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(t, b), p| (t.min(p.y), b.max(p.y))); + let mid = (top + bottom) / 2.0; + let mut ends = Vec::with_capacity(n); + let mut length = 0.0; + // The crossing farthest from the axis: its distance from it, its length along the contour + // and the direction down the page there. + let mut crossing: Option<(f64, f64, f64)> = None; + for k in 0..n { + let (p, q) = (profile.get(k)?, profile.get(k + 1)?); + let piece = p.distance(*q); + if (p.y - mid) * (q.y - mid) <= 0.0 && p.y != q.y { + let t = (mid - p.y) / (q.y - p.y); + let distance = (p.x + (q.x - p.x) * t - axis).abs(); + if crossing.is_none_or(|(far, ..)| distance > far) { + crossing = Some((distance, length + piece * t, if q.y > p.y { 1.0 } else { -1.0 })); + } + } + ends.push([length, length + piece]); + length += piece; + } + let (_, at, sign) = crossing?; + (length.is_finite() && length > 0.0).then_some(RingFrame { ends, length, at, sign }) } impl Face { @@ -471,6 +706,7 @@ fn project_face(vertices: &[V3], normals: Option<&[V3]>, o: Revolve, origin: Poi outline: None, cap: false, visibility_pieces: None, + surface: None, })) } @@ -703,6 +939,13 @@ fn revolve_projection(bounds: Rect, o: Revolve) -> shadow::Projection { shadow::Projection { view: o, origin: Point::new(axis, center_y), eye } } +/// The most faces one Revolve surface with sanitized options `o` holds. With graphics mapped, a +/// closed contour may take one more edge where its side is cut ([`ring_cut`]): the surface may +/// hold that edge's faces past [`MAX_REVOLVE_FACES`], which the profile was planned within. +fn revolve_face_limit(o: Revolve) -> usize { + MAX_REVOLVE_FACES + if o.map_surface { o.steps().saturating_mul(2) } else { 0 } +} + /// [`revolve`], or with `mesh` the surface's faces before projection, kept there instead of drawn, /// each turned out of the region `rule` fills. fn revolve_faces( @@ -720,10 +963,11 @@ fn revolve_faces( // For a mesh, each piece of a closed contour's edge is cut where it crosses another contour, so // each part's normal turns toward a hole only where it walls one. let mut search = if mesh.is_some() { Some(HoleSearch::new(path, rule)?) } else { None }; + let face_limit = revolve_face_limit(o); // A face kept for a mesh: its normal follows from its corners. let keep = |mesh: &mut Vec, face: Vec, normal: V3| { mesh.push((vec![face], normal)); - if mesh.len() > MAX_REVOLVE_FACES { Err(TOO_COMPLEX_SURFACE.to_string()) } else { Ok(()) } + if mesh.len() > face_limit { Err(TOO_COMPLEX_SURFACE.to_string()) } else { Ok(()) } }; if ![bounds.x0, bounds.y0, bounds.x1, bounds.y1].iter().all(|v| v.is_finite() && v.abs() <= 1e8) { return Err("Revolve requires finite profile coordinates within 100 million points".into()); @@ -734,6 +978,24 @@ fn revolve_faces( let smooth = o.shade && o.smooth_shading; let [lx, ly, lz] = o.light_direction(); let light = V3(lx, ly, lz); + // The side surface's angle at each end of step `j` ([`SurfaceCell`]): from the middle of the + // surface, increasing to the viewer's right. The middle is the middle of the part of the sweep + // that faces the viewer before the rotation, and at most the angle that faces the viewer + // straight on: 90° with the axis on the profile's left, 270° with it on the right. A sweep + // with no part facing the viewer has its middle at half the sweep. A full turn is cut at the + // back, half a turn from the middle each way. + let middle = surface_middle(sweep, o.edge); + let full = o.angle >= 360.0; + let surface_angle = |j: usize| { + let (from, to) = (sweep * j as f64 / steps as f64, sweep * (j + 1) as f64 / steps as f64); + let mut start = middle - from; + if full { + start = (start + std::f64::consts::PI).rem_euclid(std::f64::consts::TAU) - std::f64::consts::PI; + } + [start, start - (to - from)] + }; + // Only the longest contour of a compound profile carries the graphics. + let surface_contour = o.map_surface.then(|| longest_contour(path, axis)).flatten(); let mut faces = Vec::new(); let vertex = |p: Point, step: usize| { let (s, c) = (sweep * step as f64 / steps as f64).sin_cos(); @@ -748,7 +1010,7 @@ fn revolve_faces( if let Some(face) = face { faces.push(face); mesh_cost += cost; - if mesh_cost > MAX_REVOLVE_FACES { + if mesh_cost > face_limit { return Err(TOO_COMPLEX_SURFACE.into()); } } @@ -833,9 +1095,26 @@ fn revolve_faces( let area: f64 = ring.iter().zip(ring.iter().cycle().skip(1)).take(ring.len()).map(|(p, q)| p.0 * q.1 - q.0 * p.1).sum(); if area < 0.0 { -1.0 } else { 1.0 } }; + // A closed contour that does not touch the axis has its side cut opposite the middle of its + // outer side; an anchor goes there, so no face runs across the cut. That one anchor is not + // counted against the limit on the profile's points. + if sp.closed + && surface_contour == Some(contour) + && let Some((k, t)) = ring_cut(&profile, axis) + && let (Some(a), Some(b), Some([ta, tb]), Some(hole)) = + (profile.get(k), profile.get(k + 1), tangents.get(k).copied(), hole_edges.get(k).copied()) + { + let point = *a + (*b - *a) * t; + let middle = ta + (tb - ta) * t; + profile.insert(k + 1, point); + tangents.splice(k..=k, [[ta, middle], [middle, tb]]); + hole_edges.insert(k + 1, hole); + } + let along = along_profile(&profile, axis, sp.closed); for (i, ((pair, [ta, tb]), hole)) in profile.windows(2).zip(tangents).zip(hole_edges).enumerate() { let [a, b] = pair else { continue }; let turn = if hole { -turn } else { turn }; + let [va, vb] = along.get(i).copied().unwrap_or_default(); if ![a.x, a.y, b.x, b.y].iter().all(|v| v.is_finite() && v.abs() <= 1e8) { return Err("Revolve profile contains invalid coordinates".into()); } @@ -851,20 +1130,42 @@ fn revolve_faces( } let first = (i == 0).then(|| rings.first().and_then(Option::as_ref).and_then(|r| r.arcs.get(j))).flatten(); let last = (i + 2 == profile.len()).then(|| rings.last().and_then(Option::as_ref).and_then(|r| r.arcs.get(j))).flatten(); - let projected = |vertices: &[V3], normals: Option<&[V3]>, edges: &[(usize, &caps::RingArc, bool)]| { + // Where the corners lie on the unrolled side surface, and whether the face shows + // its outside: the edge's outward normal swept to the middle of the step. + // x is the angle times the corner's own distance from the axis. + let [t0, t1] = surface_angle(j); + let (ra, rb) = ((a.x - axis).abs(), (b.x - axis).abs()); + let corners = [Point::new(t0 * ra, va), Point::new(t0 * rb, vb), Point::new(t1 * rb, vb), Point::new(t1 * ra, va)]; + let on_surface = surface_contour == Some(contour); + let outward = { + let (dr, dy) = ((b.x - a.x) * turn, (b.y - a.y) * turn); + let (s, c) = (sweep * (j as f64 + 0.5) / steps as f64).sin_cos(); + let n = o.rotate(V3(dy * c, -dr, dy * s)); + let middle = [v0, v1, v2, v3].iter().fold(V3::default(), |m, v| V3(m.0 + v.0 / 4.0, m.1 + v.1 / 4.0, m.2 + v.2 / 4.0)); + let toward = eye.map_or(V3(0.0, 0.0, 1.0), |e| V3(-middle.0, -middle.1, e - middle.2)); + n.dot(toward) > 0.0 + }; + let projected = |vertices: &[V3], normals: Option<&[V3]>, edges: &[(usize, &caps::RingArc, bool)], uv: &[usize]| { let mut face = project_face(vertices, normals, o, Point::new(axis, center_y), eye, light)?; if let Some(face) = &mut face { + let page = face.points.clone(); caps::curve_edges(face, edges); + if on_surface { + let uv = uv.iter().filter_map(|k| corners.get(*k).copied()).collect(); + face.surface = Some(SurfaceCell { page, uv, outward }); + } } Ok::<_, String>(face) }; if smooth { let [n0, n1, n2, n3] = [normal(ta, j), normal(tb, j), normal(tb, j + 1), normal(ta, j + 1)]; - emit(projected(&[v0, v1, v2], Some(&[n0, n1, n2]), &last.map(|arc| (1, arc, false)).into_iter().collect::>())?, 1)?; - emit(projected(&[v0, v2, v3], Some(&[n0, n2, n3]), &first.map(|arc| (2, arc, true)).into_iter().collect::>())?, 1)?; + let last: Vec<_> = last.map(|arc| (1, arc, false)).into_iter().collect(); + let first: Vec<_> = first.map(|arc| (2, arc, true)).into_iter().collect(); + emit(projected(&[v0, v1, v2], Some(&[n0, n1, n2]), &last, &[0, 1, 2])?, 1)?; + emit(projected(&[v0, v2, v3], Some(&[n0, n2, n3]), &first, &[0, 2, 3])?, 1)?; } else { let edges: Vec<_> = last.map(|arc| (1, arc, false)).into_iter().chain(first.map(|arc| (3, arc, true))).collect(); - emit(projected(&[v0, v1, v2, v3], None, &edges)?, 1)?; + emit(projected(&[v0, v1, v2, v3], None, &edges, &[0, 1, 2, 3])?, 1)?; } } } diff --git a/crates/three-d/src/tests.rs b/crates/three-d/src/tests.rs index 1b0ffa3ffc..fe42769ebb 100644 --- a/crates/three-d/src/tests.rs +++ b/crates/three-d/src/tests.rs @@ -184,6 +184,190 @@ fn perspective_runs_0_to_160_degrees_with_the_eye_outside_the_object() { assert_eq!(wide, revolve(&p, b, Revolve { rotation_x: -30.0, perspective: 400.0, ..Default::default() }).unwrap()); } #[test] +fn side_faces_lie_on_the_unrolled_surface_and_caps_do_not() { + let (p, b) = cylinder(); + // Without graphics no face carries a place on the surface. + let plain = revolve(&p, b, Revolve { rotation_x: 0.0, rotation_y: 0.0, ..Default::default() }).unwrap(); + assert!(plain.iter().all(|f| f.surface.is_none())); + let faces = revolve(&p, b, Revolve { map_surface: true, rotation_x: 0.0, rotation_y: 0.0, ..Default::default() }).unwrap(); + assert_eq!(faces.len(), plain.len()); + assert!(faces.iter().filter(|f| f.cap).all(|f| f.surface.is_none())); + let side: Vec<_> = faces.iter().filter(|f| !f.cap).collect(); + assert!(!side.is_empty() && side.iter().all(|f| f.surface.as_ref().is_some_and(|c| c.uv.len() == c.page.len() && c.uv.len() == 3))); + for f in &side { + let cell = f.surface.as_ref().unwrap(); + // Straight on, x around the axis is the angle from the front times the radius 40: a corner + // at page x lies at 40 asin(x / 40) on the front half; y runs 40 each way from the middle, + // downward. + for (q, uv) in cell.page.iter().zip(&cell.uv) { + assert!((uv.y - (q.y - 50.0)).abs() < 1e-9, "{q:?} {uv:?}"); + if cell.outward { + assert!((uv.x - 40.0 * (q.x / 40.0).clamp(-1.0, 1.0).asin()).abs() < 1e-6, "{q:?} {uv:?}"); + } + } + // The outside faces the viewer on the front half only. + let mean = cell.uv.iter().map(|p| p.x).sum::() / cell.uv.len() as f64; + assert_eq!(cell.outward, mean.abs() < 40.0 * std::f64::consts::FRAC_PI_2, "{mean}"); + } + // A quarter sweep's middle is the middle of the sweep, 45° around the axis. + let quarter = revolve(&p, b, Revolve { map_surface: true, angle: 90.0, rotation_x: 0.0, rotation_y: 0.0, ..Default::default() }).unwrap(); + let xs: Vec = quarter.iter().filter_map(|f| f.surface.as_ref()).flat_map(|c| c.uv.iter().map(|p| p.x)).collect(); + let (lo, hi) = xs.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), x| (lo.min(*x), hi.max(*x))); + let reach = 40.0 * std::f64::consts::FRAC_PI_4; + assert!((lo + reach).abs() < 1e-9 && (hi - reach).abs() < 1e-9, "{lo} {hi}"); + let (w, h) = revolve_surface_size(&p, b, Revolve::default()).unwrap(); + assert!((w - 40.0 * std::f64::consts::PI).abs() < 1e-9 && (h - 80.0).abs() < 1e-3, "{w} {h}"); + assert_eq!(revolve_surface_size(&p, Rect::new(40.0, 10.0, 40.0, 90.0), Revolve::default()), None); + // A curve that starts and ends on the axis but bows away from it sweeps a side with a length. + let mut bow = BezPath::new(); + bow.move_to((0.0, 0.0)); + bow.curve_to((40.0, 0.0), (40.0, 80.0), (0.0, 80.0)); + let (w, h) = revolve_surface_size(&PathData::from_bezpath(&bow), Rect::new(0.0, 0.0, 30.0, 80.0), Revolve::default()).unwrap(); + assert!((w - 30.0 * std::f64::consts::PI).abs() < 1e-9 && h > 80.0, "{w} {h}"); +} +#[test] +fn the_side_keeps_its_length_around_the_axis_at_every_distance_from_it() { + // A step: 40 from the axis, 20 between y 40 and 60, then 40 again. + let mut bp = BezPath::new(); + bp.move_to((40.0, 10.0)); + for p in [(40.0, 40.0), (20.0, 40.0), (20.0, 60.0), (40.0, 60.0), (40.0, 90.0)] { + bp.line_to(p); + } + let (p, b) = (PathData::from_bezpath(&bp), Rect::new(0.0, 10.0, 40.0, 90.0)); + let faces = revolve(&p, b, Revolve { map_surface: true, rotation_x: 0.0, rotation_y: 0.0, ..Default::default() }).unwrap(); + let (mut narrow, mut wide) = (0.0f64, 0.0f64); + for cell in faces.iter().filter_map(|f| f.surface.as_ref()).filter(|c| c.outward) { + // The faces of the narrow part run from y 40 to 60; those of the wide parts reach past + // them; the steps between lie at y 40 or 60 only. + let at = |y: f64| cell.page.iter().any(|q| (q.y - y).abs() < 1e-9); + let radius = if at(40.0) && at(60.0) { + Some(20.0) + } else if cell.page.iter().any(|q| q.y < 40.0 - 1e-9 || q.y > 60.0 + 1e-9) { + Some(40.0) + } else { + None + }; + for (q, uv) in cell.page.iter().zip(&cell.uv) { + // Straight on, a corner at page x that is r from the axis lies r asin(x / r) around it. + let fits = |r: f64| (uv.x - r * (q.x / r).clamp(-1.0, 1.0).asin()).abs() < 1e-6; + match radius { + Some(r) => { + assert!(fits(r), "{r}: {q:?} {uv:?}"); + let reach = if r < 30.0 { &mut narrow } else { &mut wide }; + *reach = reach.max(uv.x.abs()); + } + None => assert!(fits(20.0) || fits(40.0), "{q:?} {uv:?}"), + } + } + } + // The half seen from the front reaches a quarter turn each way: 10π at 20 from the axis, 20π + // at 40. + let quarter = std::f64::consts::FRAC_PI_2; + assert!((narrow - 20.0 * quarter).abs() < 1.0 && (wide - 40.0 * quarter).abs() < 2.0, "{narrow} {wide}"); +} +#[test] +fn with_the_axis_on_the_right_the_middle_of_the_side_faces_the_viewer() { + let mut bp = BezPath::new(); + bp.move_to((0.0, 10.0)); + bp.line_to((0.0, 90.0)); + let (p, b) = (PathData::from_bezpath(&bp), Rect::new(0.0, 10.0, 40.0, 90.0)); + let q = 40.0 * std::f64::consts::FRAC_PI_4; + // The side's reach around the axis either way of its middle: for 270° the middle is 225°, in + // the middle of the part from 180° to 270° that faces the viewer; a quarter turn faces away, + // and its middle is half the sweep. + for (angle, lo_expected, hi_expected) in [(270.0, -q, 5.0 * q), (90.0, -q, q)] { + let o = Revolve { map_surface: true, edge: Edge::Right, angle, rotation_x: 0.0, rotation_y: 0.0, ..Default::default() }; + let xs: Vec = revolve(&p, b, o).unwrap().iter().filter_map(|f| f.surface.as_ref()).flat_map(|c| c.uv.iter().map(|p| p.x)).collect(); + let (lo, hi) = xs.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), x| (lo.min(*x), hi.max(*x))); + assert!((lo - lo_expected).abs() < 1e-6 && (hi - hi_expected).abs() < 1e-6, "{angle}: {lo} {hi}"); + } + // A new graphic fits the part of the sweep that faces the viewer: 90° of a 270° sweep, 20° of + // a 200° one, all of a quarter turn that faces away. + for (angle, seen) in [(270.0f64, 90.0f64), (200.0, 20.0), (90.0, 90.0), (360.0, 180.0)] { + let (w, _) = revolve_surface_size(&p, b, Revolve { edge: Edge::Right, angle, ..Default::default() }).unwrap(); + assert!((w - 40.0 * seen.to_radians()).abs() < 1e-9, "{angle}: {w}"); + } + // A full turn: straight on, the axis is at x 40, a corner at page x lies 40 asin((x - 40) / 40) + // around it, and the front half shows its outside. + let faces = revolve(&p, b, Revolve { map_surface: true, edge: Edge::Right, rotation_x: 0.0, rotation_y: 0.0, ..Default::default() }).unwrap(); + let cells: Vec<_> = faces.iter().filter_map(|f| f.surface.as_ref()).collect(); + assert!(cells.iter().any(|c| c.outward)); + for cell in &cells { + let mean = cell.uv.iter().map(|p| p.x).sum::() / cell.uv.len() as f64; + assert_eq!(cell.outward, mean.abs() < 40.0 * std::f64::consts::FRAC_PI_2, "{mean}"); + if cell.outward { + for (q, uv) in cell.page.iter().zip(&cell.uv) { + assert!((uv.x - 40.0 * ((q.x - 40.0) / 40.0).clamp(-1.0, 1.0).asin()).abs() < 1e-6, "{q:?} {uv:?}"); + } + } + } +} +#[test] +fn only_the_longest_contour_of_a_compound_profile_carries_the_side_surface() { + let mut bp = BezPath::new(); + bp.move_to((40.0, 10.0)); + bp.line_to((40.0, 90.0)); + bp.move_to((20.0, 30.0)); + bp.line_to((20.0, 50.0)); + let (p, b) = (PathData::from_bezpath(&bp), Rect::new(0.0, 10.0, 40.0, 90.0)); + let faces = revolve(&p, b, Revolve { map_surface: true, rotation_x: 0.0, rotation_y: 0.0, ..Default::default() }).unwrap(); + let short = |f: &Face| f.points.iter().all(|q| q.y > 29.0 && q.y < 51.0); + assert!(faces.iter().any(|f| !f.cap && short(f)) && faces.iter().any(|f| !f.cap && !short(f))); + for f in faces.iter().filter(|f| !f.cap) { + assert_eq!(f.surface.is_some(), !short(f), "{:?}", f.points); + } + // The side's size is that contour's: with the longest contour 10 from the axis and a shorter + // one 40 from it, the width is half a turn at 10 and the length the longest contour's 80. + let mut bp = BezPath::new(); + bp.move_to((10.0, 10.0)); + bp.line_to((10.0, 90.0)); + bp.move_to((40.0, 30.0)); + bp.line_to((40.0, 50.0)); + let (w, h) = revolve_surface_size(&PathData::from_bezpath(&bp), b, Revolve::default()).unwrap(); + assert!((w - 10.0 * std::f64::consts::PI).abs() < 1e-9 && (h - 80.0).abs() < 1e-3, "{w} {h}"); +} +/// The square ring of [`a_ring_profile_is_measured_from_its_outer_side_at_mid_height`] with an +/// anchor in the middle of its inner side. +fn split_square() -> [Point; 6] { + [(20.0, 30.0), (40.0, 30.0), (40.0, 50.0), (20.0, 50.0), (20.0, 40.0), (20.0, 30.0)].map(|(x, y)| Point::new(x, y)) +} +#[test] +fn a_ring_profile_is_measured_from_its_outer_side_at_mid_height() { + // A square from 20 to 40 from the axis, starting at its top inner corner and running to the + // right first (down the outer side). + let ring = [(20.0, 30.0), (40.0, 30.0), (40.0, 50.0), (20.0, 50.0), (20.0, 30.0)].map(|(x, y)| Point::new(x, y)); + assert_eq!(along_profile(&ring, 0.0, true), vec![[-30.0, -10.0], [-10.0, 10.0], [10.0, 30.0], [30.0, 50.0]]); + // Wound the other way the outer side still runs down the page as y increases. The cut is at + // an inner corner, so each piece's y runs one way across it. + let back = [(20.0, 30.0), (20.0, 50.0), (40.0, 50.0), (40.0, 30.0), (20.0, 30.0)].map(|(x, y)| Point::new(x, y)); + assert_eq!(along_profile(&back, 0.0, true), vec![[50.0, 30.0], [30.0, 10.0], [10.0, -10.0], [-10.0, -30.0]]); + // The cut falls half way along a long inner side: Revolve puts an anchor there first, and y + // then runs half the contour's length each way. + let tall = [(20.0, 0.0), (40.0, 0.0), (40.0, 100.0), (20.0, 100.0), (20.0, 0.0)].map(|(x, y)| Point::new(x, y)); + assert_eq!(ring_cut(&tall, 0.0), Some((3, 0.5))); + assert_eq!(ring_cut(&ring, 0.0), Some((3, 0.5))); + assert_eq!(ring_cut(&split_square(), 0.0), None); + assert_eq!(along_profile(&split_square(), 0.0, true), vec![[-30.0, -10.0], [-10.0, 10.0], [10.0, 30.0], [30.0, 40.0], [-40.0, -30.0]]); + let split = [(20.0, 0.0), (40.0, 0.0), (40.0, 100.0), (20.0, 100.0), (20.0, 50.0), (20.0, 0.0)].map(|(x, y)| Point::new(x, y)); + assert_eq!(along_profile(&split, 0.0, true), vec![[-70.0, -50.0], [-50.0, 50.0], [50.0, 70.0], [70.0, 120.0], [-120.0, -70.0]]); + let mut bp = BezPath::new(); + bp.move_to((20.0, 0.0)); + for p in [(40.0, 0.0), (40.0, 100.0), (20.0, 100.0)] { + bp.line_to(p); + } + bp.close_path(); + let (path, bounds, o) = + (PathData::from_bezpath(&bp), Rect::new(20.0, 0.0, 40.0, 100.0), Revolve { map_surface: true, offset: 20.0, ..Default::default() }); + let faces = revolve(&path, bounds, o).unwrap(); + // Without graphics the profile takes no anchor at the cut: its inner side stays one edge. + let plain = revolve(&path, bounds, Revolve { map_surface: false, ..o }).unwrap(); + assert!(plain.len() < faces.len() && plain.iter().all(|f| f.surface.is_none()), "{} {}", plain.len(), faces.len()); + let ys: Vec = faces.iter().filter_map(|f| f.surface.as_ref()).flat_map(|c| c.uv.iter().map(|p| p.y)).collect(); + assert!(!ys.is_empty() && ys.iter().all(|y| y.abs() <= 120.0 + 1e-9), "{ys:?}"); + let (w, h) = revolve_surface_size(&path, bounds, o).unwrap(); + assert!((h - 240.0).abs() < 1e-6 && (w - 40.0 * std::f64::consts::PI).abs() < 1e-9, "{w} {h}"); +} +#[test] fn malformed_and_degenerate_inputs_are_bounded() { let (p, b) = cylinder(); let f = revolve(&p, b, Revolve { segments: usize::MAX, angle: f64::NAN, offset: f64::INFINITY, ..Default::default() }).unwrap(); diff --git a/crates/three-d/src/tests/profile_limits.rs b/crates/three-d/src/tests/profile_limits.rs index 148cf4fccc..e785c959d8 100644 --- a/crates/three-d/src/tests/profile_limits.rs +++ b/crates/three-d/src/tests/profile_limits.rs @@ -103,6 +103,35 @@ fn the_profiles_of_one_object_share_one_budget() { assert_eq!(revolve_curve_samples([&both], o), Err(refused)); } +#[test] +fn with_graphics_a_ring_at_the_face_limit_still_takes_the_edge_its_cut_adds() { + // A closed many-sided ring, 50 clear of the axis, with the middle of an edge at the middle of + // its outer side and, with an even number of edges, at the middle of its inner side. + let ring = |edges: usize| { + let anchors = (0..edges) + .map(|i| { + let (s, c) = ((i as f64 + 0.5) * std::f64::consts::TAU / edges as f64).sin_cos(); + Anchor::corner(Point::new(300.0 + 100.0 * c, 100.0 * s)) + }) + .collect(); + PathData::new(vec![SubPath::new(anchors, true)]) + }; + // Tilted, so the flat edges at the top and bottom draw faces too. + let plain = Revolve { offset: 50.0, rotation_x: -20.0, ..Revolve::default() }; + let mapped = Revolve { map_surface: true, ..plain }; + // 1,280 edges of 128 faces each are the most that fit, with graphics or without. + for o in [plain, mapped] { + assert_eq!(revolve_curve_samples([&ring(1280)], o), Ok(CURVE_SAMPLES)); + assert!(revolve_curve_samples([&ring(1281)], o).unwrap_err().contains("reduce Segments")); + } + let faces = revolved(&ring(1280), plain).unwrap(); + assert_eq!(faces.len(), MAX_REVOLVE_FACES); + assert!(faces.iter().all(|f| f.surface.is_none())); + // With graphics the side is cut in the middle of the inner edge, which makes one edge more: + // its faces are taken past the limit. + assert_eq!(revolved(&ring(1280), mapped).unwrap().len(), MAX_REVOLVE_FACES + 128); +} + #[test] fn deeply_nested_contours_stop_the_search_for_holes() { // Concentric triangles: each tests every contour outside it. diff --git a/crates/three-d/src/visibility.rs b/crates/three-d/src/visibility.rs index db8f5b0df7..424242828b 100644 --- a/crates/three-d/src/visibility.rs +++ b/crates/three-d/src/visibility.rs @@ -302,6 +302,7 @@ mod tests { outline: None, cap: false, visibility_pieces: None, + surface: None, } } diff --git a/crates/ui-egui/src/dialogs/three_d_materials.rs b/crates/ui-egui/src/dialogs/three_d_materials.rs index 180572aeaa..3091a00cac 100644 --- a/crates/ui-egui/src/dialogs/three_d_materials.rs +++ b/crates/ui-egui/src/dialogs/three_d_materials.rs @@ -1,13 +1,13 @@ //! The 3D and Materials panel's Materials tab: the document's Graphics (its symbols) as thumbnails, -//! Add as Single Graphic, and the graphics mapped onto the selected 3D object's planar faces with -//! their face, position, size and turn. Picking a thumbnail maps that graphic onto the selected -//! objects (`threeD.mapGraphic`); art dropped on the thumbnails becomes a graphic +//! Add as Single Graphic, and the graphics mapped onto the selected 3D object (its planar faces, or +//! Revolve's side) with their face, position, size and turn. Picking a thumbnail maps that graphic +//! onto the selected objects (`threeD.mapGraphic`); art dropped on the thumbnails becomes a graphic //! (`threeD.addGraphic`). Editing a mapped graphic changes the effect's `graphics` parameter, which //! the panel sends as it sends every other setting. use egui::{Sense, Stroke, StrokeKind, vec2}; use serde_json::{Value, json}; -use vectorcraft_effects::{GRAPHICS, MappedGraphic, PlanarFace, ROTATE}; +use vectorcraft_effects::{GRAPHICS, MappedGraphic, PlanarFace, REVOLVE, ROTATE}; use super::revolve::{heading, label, number}; use crate::VectorcraftApp; @@ -96,7 +96,7 @@ pub(crate) fn controls(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) } ui.add_space(10.0); if !takes { - dim_label(ui, tl!("Graphics map onto planar faces: pick the Plane or Extrude object type.")); + dim_label(ui, tl!("Graphics map onto the Plane, Extrude and Revolve object types.")); return; } let raw = d.fields.get(GRAPHICS).cloned().unwrap_or(Value::Null); @@ -121,7 +121,8 @@ pub(crate) fn controls(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) ui.add_space(6.0); let Some(g) = list.get(index).cloned() else { return }; let mut edited = g.clone(); - if effect != ROTATE { + // A plane has one face, and Revolve's graphics go on its side. + if effect != ROTATE && effect != REVOLVE { ui.horizontal(|ui| { ui.spacing_mut().item_spacing.x = 6.0; label(ui, tl!("Face")); diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 02ae0f4a09..50f1a28b38 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -6092,7 +6092,9 @@ digits Malayalam Malaiàlam @msg `{GRAPHICS}` face must be front or back face de `{GRAPHICS}` ha de ser front o back @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} {key} de `{GRAPHICS}` ha de ser un nombre de {lo} a {hi} @msg `{GRAPHICS}` must be an array `{GRAPHICS}` ha de ser una matriu -@msg Graphics map onto planar faces: use the Extrude or Plane object type Els gràfics s’apliquen a cares planes: fes servir el tipus d’objecte Extrusió o Pla +@msg Graphics map onto the Plane, Extrude and Revolve object types Els gràfics s’apliquen als tipus d’objecte Pla, Extrusió i Revolució +@msg Revolve maps graphics onto its side: map them onto the front Revoluciona aplica els gràfics al seu lateral: aplica’ls a la cara davantera +@msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments Els gràfics són massa complexos per a aquesta superfície: simplifica la il·lustració dels símbols o redueix Segments @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` admet com a màxim {MAX_GRAPHICS} gràfics @msg A plane has one face: map its graphics onto the front Un pla té una sola cara: aplica’n els gràfics a la cara davantera @msg The graphics are too complex: simplify the symbols' art Els gràfics són massa complexos: simplifica la il·lustració dels símbols diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 7e3794e8a1..1e27e4a0f4 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -5935,7 +5935,9 @@ mark-style Japanese Japonské @msg `{GRAPHICS}` face must be front or back face v `{GRAPHICS}` musí být front nebo back @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} {key} v `{GRAPHICS}` musí být číslo od {lo} do {hi} @msg `{GRAPHICS}` must be an array `{GRAPHICS}` musí být pole -@msg Graphics map onto planar faces: use the Extrude or Plane object type Grafika se mapuje na rovinné stěny: použijte typ objektu Vysunutí nebo Rovina +@msg Graphics map onto the Plane, Extrude and Revolve object types Grafika se mapuje na typy objektu Rovina, Vysunutí a Rotační těleso +@msg Revolve maps graphics onto its side: map them onto the front Rotační těleso mapuje grafiku na svůj bok: umístěte ji na přední stranu +@msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments Grafika je pro tento povrch příliš složitá: zjednodušte kresbu symbolů nebo snižte Segmenty @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` přijímá nejvýše {MAX_GRAPHICS} grafik @msg A plane has one face: map its graphics onto the front Rovina má jednu stranu: umístěte její grafiku na přední stranu @msg The graphics are too complex: simplify the symbols' art Grafika je příliš složitá: zjednodušte kresbu symbolů diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 4174537f87..a49d4c103e 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -5510,7 +5510,9 @@ lighting Light Licht @msg `{GRAPHICS}` face must be front or back face in `{GRAPHICS}` muss front oder back sein @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} {key} in `{GRAPHICS}` muss eine Zahl von {lo} bis {hi} sein @msg `{GRAPHICS}` must be an array `{GRAPHICS}` muss ein Array sein -@msg Graphics map onto planar faces: use the Extrude or Plane object type Grafiken werden auf ebene Seiten abgebildet: Verwenden Sie den Objekttyp Extrudieren oder Ebene +@msg Graphics map onto the Plane, Extrude and Revolve object types Grafiken werden auf die Objekttypen Ebene, Extrudieren und Kreiseln abgebildet +@msg Revolve maps graphics onto its side: map them onto the front Kreiseln bildet Grafiken auf seiner Mantelfläche ab: Bilden Sie sie auf der Vorderseite ab +@msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments Die Grafiken sind für diese Oberfläche zu komplex: Vereinfachen Sie das Bildmaterial der Symbole oder verringern Sie Segmente @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` nimmt höchstens {MAX_GRAPHICS} Grafiken auf @msg A plane has one face: map its graphics onto the front Eine Ebene hat nur eine Seite: Bilden Sie ihre Grafiken auf der Vorderseite ab @msg The graphics are too complex: simplify the symbols' art Die Grafiken sind zu komplex: Vereinfachen Sie das Bildmaterial der Symbole diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index bde2fbee78..4df9c95d60 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -5294,7 +5294,9 @@ digits Malayalam Μαλαγιάλαμ @msg `{GRAPHICS}` face must be front or back το face του `{GRAPHICS}` πρέπει να είναι front ή back @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} το {key} του `{GRAPHICS}` πρέπει να είναι αριθμός από {lo} έως {hi} @msg `{GRAPHICS}` must be an array το `{GRAPHICS}` πρέπει να είναι πίνακας -@msg Graphics map onto planar faces: use the Extrude or Plane object type Τα γραφικά αντιστοιχίζονται σε επίπεδες όψεις: χρησιμοποιήστε τον τύπο αντικειμένου Εξώθηση ή Επίπεδο +@msg Graphics map onto the Plane, Extrude and Revolve object types Τα γραφικά αντιστοιχίζονται στους τύπους αντικειμένου Επίπεδο, Εξώθηση και Περιστροφή γύρω από άξονα +@msg Revolve maps graphics onto its side: map them onto the front Η Περιστροφή γύρω από άξονα αντιστοιχίζει τα γραφικά στην πλευρική της επιφάνεια: αντιστοιχίστε τα στην μπροστινή όψη +@msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments Τα γραφικά είναι πολύ σύνθετα για αυτή την επιφάνεια: απλοποιήστε το σχέδιο των συμβόλων ή μειώστε τα Τμήματα @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics το `{GRAPHICS}` δέχεται το πολύ {MAX_GRAPHICS} γραφικά @msg A plane has one face: map its graphics onto the front Ένα επίπεδο έχει μία όψη: αντιστοιχίστε τα γραφικά του στην μπροστινή όψη @msg The graphics are too complex: simplify the symbols' art Τα γραφικά είναι πολύ σύνθετα: απλοποιήστε το σχέδιο των συμβόλων diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index ff28d9dfc5..66f62d725c 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -5876,7 +5876,10 @@ mark-style Japanese Japonesas @msg `{GRAPHICS}` face must be front or back face de `{GRAPHICS}` debe ser front o back @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} {key} de `{GRAPHICS}` debe ser un número de {lo} a {hi} @msg `{GRAPHICS}` must be an array `{GRAPHICS}` debe ser una matriz -@msg Graphics map onto planar faces: use the Extrude or Plane object type Los gráficos se asignan a caras planas: use el tipo de objeto Extrusión o Plano +@msg Graphics map onto the Plane, Extrude and Revolve object types Los gráficos se asignan a los tipos de objeto Plano, Extrusión y Revolución + Graphics map onto the Plane, Extrude and Revolve object types. Los gráficos se asignan a los tipos de objeto Plano, Extrusión y Revolución. +@msg Revolve maps graphics onto its side: map them onto the front Revolución asigna los gráficos a su lateral: asígnelos a la cara frontal +@msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments Los gráficos son demasiado complejos para esta superficie: simplifique la ilustración de los símbolos o reduzca Segmentos @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` admite como máximo {MAX_GRAPHICS} gráficos @msg A plane has one face: map its graphics onto the front Un plano tiene una sola cara: asigne sus gráficos a la cara frontal @msg The graphics are too complex: simplify the symbols' art Los gráficos son demasiado complejos: simplifique la ilustración de los símbolos diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index bb74188ed8..bdba446072 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -5817,7 +5817,9 @@ mark-style Japanese Japanilainen @msg `{GRAPHICS}` face must be front or back `{GRAPHICS}`-kohteen face-arvon on oltava front tai back @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} `{GRAPHICS}`-kohteen {key}-arvon on oltava luku, joka on vähintään {lo} ja enintään {hi} @msg `{GRAPHICS}` must be an array `{GRAPHICS}` on oltava taulukko -@msg Graphics map onto planar faces: use the Extrude or Plane object type Grafiikat sijoitetaan tasaisille pinnoille: käytä objektityyppiä Pursota tai Taso +@msg Graphics map onto the Plane, Extrude and Revolve object types Grafiikat sijoitetaan objektityypeille Taso, Pursota ja Pyöräytä +@msg Revolve maps graphics onto its side: map them onto the front Pyöräytä sijoittaa grafiikat kylkeensä: sijoita ne etupuolelle +@msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments Grafiikat ovat liian monimutkaisia tälle pinnalle: yksinkertaista symbolien kuvitusta tai pienennä Segmentit-arvoa @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` hyväksyy enintään {MAX_GRAPHICS} grafiikkaa @msg A plane has one face: map its graphics onto the front Tasolla on yksi puoli: sijoita sen grafiikat etupuolelle @msg The graphics are too complex: simplify the symbols' art Grafiikat ovat liian monimutkaisia: yksinkertaista symbolien kuvitusta diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 09c9c35b0d..1405e26ba3 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -5505,7 +5505,9 @@ lighting Light Lumière @msg `{GRAPHICS}` face must be front or back face de `{GRAPHICS}` doit valoir front ou back @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} {key} de `{GRAPHICS}` doit être un nombre de {lo} à {hi} @msg `{GRAPHICS}` must be an array `{GRAPHICS}` doit être un tableau -@msg Graphics map onto planar faces: use the Extrude or Plane object type Les graphiques s'appliquent sur des faces planes : utilisez le type d'objet Extrusion ou Plan +@msg Graphics map onto the Plane, Extrude and Revolve object types Les graphiques s'appliquent aux types d'objet Plan, Extrusion et Révolution +@msg Revolve maps graphics onto its side: map them onto the front Révolution applique les graphiques sur sa face latérale : appliquez-les sur la face avant +@msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments Les graphiques sont trop complexes pour cette surface : simplifiez l'illustration des symboles ou réduisez Segments @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` accepte au plus {MAX_GRAPHICS} graphiques @msg A plane has one face: map its graphics onto the front Un plan n'a qu'une face : appliquez ses graphiques sur la face avant @msg The graphics are too complex: simplify the symbols' art Les graphiques sont trop complexes : simplifiez l'illustration des symboles diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 9aa4bd7b99..07e4927a48 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -7918,7 +7918,9 @@ antiAlias Sharp शार्प @msg `{GRAPHICS}` face must be front or back `{GRAPHICS}` का face, front या back होना चाहिए @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} `{GRAPHICS}` का {key}, {lo} से {hi} तक की संख्या होना चाहिए @msg `{GRAPHICS}` must be an array `{GRAPHICS}` एक ऐरे होना चाहिए -@msg Graphics map onto planar faces: use the Extrude or Plane object type ग्राफ़िक्स समतल फ़ेस पर लगते हैं: एक्सट्रूड या समतल ऑब्जेक्ट प्रकार का उपयोग करें +@msg Graphics map onto the Plane, Extrude and Revolve object types ग्राफ़िक्स समतल, एक्सट्रूड और रिवॉल्व ऑब्जेक्ट प्रकारों पर लगते हैं +@msg Revolve maps graphics onto its side: map them onto the front रिवॉल्व ग्राफ़िक्स को अपनी बगल वाली सतह पर लगाता है: उन्हें सामने वाले फ़ेस पर लगाएँ +@msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments ग्राफ़िक्स इस सतह के लिए बहुत जटिल हैं: सिंबल्स के आर्ट को सरल बनाएँ या सेगमेंट कम करें @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` अधिकतम {MAX_GRAPHICS} ग्राफ़िक्स लेता है @msg A plane has one face: map its graphics onto the front समतल का एक ही फ़ेस होता है: उसके ग्राफ़िक्स को सामने वाले फ़ेस पर लगाएँ @msg The graphics are too complex: simplify the symbols' art ग्राफ़िक्स बहुत जटिल हैं: सिंबल्स के आर्ट को सरल बनाएँ diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index af6f586880..70e9721f24 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -5918,7 +5918,9 @@ imageTrace Outline Körvonal @msg `{GRAPHICS}` face must be front or back a `{GRAPHICS}` face értéke front vagy back lehet @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} a `{GRAPHICS}` {key} értéke {lo} és {hi} közötti szám lehet @msg `{GRAPHICS}` must be an array a `{GRAPHICS}` értéke tömb kell legyen -@msg Graphics map onto planar faces: use the Extrude or Plane object type A grafikák sík lapokra kerülnek: használja a Kihúzás vagy a Sík objektumtípust +@msg Graphics map onto the Plane, Extrude and Revolve object types A grafikák a Sík, a Kihúzás és a Forgatás tengely körül objektumtípusra kerülnek +@msg Revolve maps graphics onto its side: map them onto the front A Forgatás tengely körül a grafikákat a palástjára helyezi: az elülső oldalra helyezze őket +@msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments A grafikák túl összetettek ehhez a felülethez: egyszerűsítse a szimbólumok rajzát, vagy csökkentse a Szakaszok értékét @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics a `{GRAPHICS}` legfeljebb {MAX_GRAPHICS} grafikát fogad @msg A plane has one face: map its graphics onto the front A síknak egy oldala van: a grafikáit az elülső oldalra helyezze @msg The graphics are too complex: simplify the symbols' art A grafikák túl összetettek: egyszerűsítse a szimbólumok rajzát diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index ce0bc58ce5..c9da0ceb38 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -5552,7 +5552,9 @@ lighting Light Luce @msg `{GRAPHICS}` face must be front or back face di `{GRAPHICS}` deve essere front o back @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} {key} di `{GRAPHICS}` deve essere un numero da {lo} a {hi} @msg `{GRAPHICS}` must be an array `{GRAPHICS}` deve essere un array -@msg Graphics map onto planar faces: use the Extrude or Plane object type Le grafiche si applicano a facce piane: usate il tipo di oggetto Estrusione o Piano +@msg Graphics map onto the Plane, Extrude and Revolve object types Le grafiche si applicano ai tipi di oggetto Piano, Estrusione e Rivoluzione +@msg Revolve maps graphics onto its side: map them onto the front Rivoluzione applica le grafiche sul suo lato: applicatele sulla faccia anteriore +@msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments Le grafiche sono troppo complesse per questa superficie: semplificate il disegno dei simboli o riducete Segmenti @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` accetta al massimo {MAX_GRAPHICS} grafiche @msg A plane has one face: map its graphics onto the front Un piano ha una sola faccia: applicate le sue grafiche sulla faccia anteriore @msg The graphics are too complex: simplify the symbols' art Le grafiche sono troppo complesse: semplificate il disegno dei simboli diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 1ecce4618a..6d1939ad4b 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5594,7 +5594,10 @@ lighting Light ライト @msg `{GRAPHICS}` face must be front or back `{GRAPHICS}` の face には front または back を指定してください @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} `{GRAPHICS}` の {key} は {lo} から {hi} までの数値にしてください @msg `{GRAPHICS}` must be an array `{GRAPHICS}` は配列にしてください -@msg Graphics map onto planar faces: use the Extrude or Plane object type グラフィックは平らな面にマッピングされます。オブジェクトの種類に押し出しまたは平面を使用してください +@msg Graphics map onto the Plane, Extrude and Revolve object types グラフィックはオブジェクトの種類が平面、押し出し、回転体のときにマッピングされます + Graphics map onto the Plane, Extrude and Revolve object types. グラフィックはオブジェクトの種類が平面、押し出し、回転体のときにマッピングされます。 +@msg Revolve maps graphics onto its side: map them onto the front 回転体はグラフィックを側面にマッピングします。前面にマッピングしてください +@msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments グラフィックがこのサーフェスには複雑すぎます。シンボルのアートを単純化するか、分割数を減らしてください @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` に指定できるグラフィックは {MAX_GRAPHICS} 個までです @msg A plane has one face: map its graphics onto the front 平面には面が 1 つしかありません。グラフィックは前面にマッピングしてください @msg The graphics are too complex: simplify the symbols' art グラフィックが複雑すぎます。シンボルのアートを単純化してください diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 3d6425c373..67a1d72ee8 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -5223,7 +5223,9 @@ font-technology Variable ცვლადი @msg `{GRAPHICS}` face must be front or back `{GRAPHICS}`-ის face უნდა იყოს front ან back @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} `{GRAPHICS}`-ის {key} უნდა იყოს რიცხვი {lo}-დან {hi}-მდე @msg `{GRAPHICS}` must be an array `{GRAPHICS}` უნდა იყოს მასივი -@msg Graphics map onto planar faces: use the Extrude or Plane object type გრაფიკა ბრტყელ წახნაგებზე თავსდება: გამოიყენეთ ობიექტის ტიპი „ამოწევა“ ან „სიბრტყე“ +@msg Graphics map onto the Plane, Extrude and Revolve object types გრაფიკა თავსდება ობიექტის ტიპებზე „სიბრტყე“, „ამოწევა“ და „ბრუნვა“ +@msg Revolve maps graphics onto its side: map them onto the front ბრუნვა გრაფიკას თავის გვერდით ზედაპირზე ათავსებს: განათავსეთ ისინი წინა მხარეზე +@msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments გრაფიკა ზედმეტად რთულია ამ ზედაპირისთვის: გაამარტივეთ სიმბოლოების ნახატი ან შეამცირეთ სეგმენტები @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` იღებს მაქსიმუმ {MAX_GRAPHICS} გრაფიკას @msg A plane has one face: map its graphics onto the front სიბრტყეს ერთი მხარე აქვს: მისი გრაფიკა წინა მხარეზე განათავსეთ @msg The graphics are too complex: simplify the symbols' art გრაფიკა ზედმეტად რთულია: გაამარტივეთ სიმბოლოების ნახატი diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index fb87488d64..f6d7767b89 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5513,7 +5513,9 @@ lighting Light 광원 @msg `{GRAPHICS}` face must be front or back `{GRAPHICS}`의 face는 front 또는 back이어야 합니다 @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} `{GRAPHICS}`의 {key}은(는) {lo}에서 {hi} 사이의 숫자여야 합니다 @msg `{GRAPHICS}` must be an array `{GRAPHICS}`은(는) 배열이어야 합니다 -@msg Graphics map onto planar faces: use the Extrude or Plane object type 그래픽은 평평한 면에 매핑됩니다. 돌출 또는 평면 개체 유형을 사용하십시오 +@msg Graphics map onto the Plane, Extrude and Revolve object types 그래픽은 평면, 돌출, 회전체 개체 유형에 매핑됩니다 +@msg Revolve maps graphics onto its side: map them onto the front 회전체는 그래픽을 옆면에 매핑합니다. 앞면에 매핑하십시오 +@msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments 그래픽이 이 표면에 비해 너무 복잡합니다. 심볼의 아트를 단순화하거나 세그먼트를 줄이십시오 @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}`에는 그래픽을 최대 {MAX_GRAPHICS}개까지 넣을 수 있습니다 @msg A plane has one face: map its graphics onto the front 평면에는 면이 하나뿐입니다. 그래픽을 앞면에 매핑하십시오 @msg The graphics are too complex: simplify the symbols' art 그래픽이 너무 복잡합니다. 심볼의 아트를 단순화하십시오 diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 0729e35c79..6af3616ff3 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -5765,7 +5765,9 @@ mark-style Japanese Japońskie @msg `{GRAPHICS}` face must be front or back face w `{GRAPHICS}` musi mieć wartość front lub back @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} {key} w `{GRAPHICS}` musi być liczbą od {lo} do {hi} @msg `{GRAPHICS}` must be an array `{GRAPHICS}` musi być tablicą -@msg Graphics map onto planar faces: use the Extrude or Plane object type Grafiki są nakładane na płaskie ściany: użyj typu obiektu Wyciągnięcie lub Płaszczyzna +@msg Graphics map onto the Plane, Extrude and Revolve object types Grafiki są nakładane na obiekty typu Płaszczyzna, Wyciągnięcie i Obrót +@msg Revolve maps graphics onto its side: map them onto the front Obrót nakłada grafiki na swoją powierzchnię boczną: umieść je na przedniej stronie +@msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments Grafiki są zbyt złożone dla tej powierzchni: uprość rysunki symboli lub zmniejsz Segmenty @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` przyjmuje najwyżej {MAX_GRAPHICS} grafik @msg A plane has one face: map its graphics onto the front Płaszczyzna ma jedną stronę: umieść jej grafiki na przedniej stronie @msg The graphics are too complex: simplify the symbols' art Grafiki są zbyt złożone: uprość rysunki symboli diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 36f778dbd5..39c516b2fe 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -5884,7 +5884,9 @@ mark-style Japanese Japonesas @msg `{GRAPHICS}` face must be front or back face de `{GRAPHICS}` deve ser front ou back @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} {key} de `{GRAPHICS}` deve ser um número de {lo} a {hi} @msg `{GRAPHICS}` must be an array `{GRAPHICS}` deve ser uma matriz -@msg Graphics map onto planar faces: use the Extrude or Plane object type Os gráficos são mapeados em faces planas: use o tipo de objeto Extrusão ou Plano +@msg Graphics map onto the Plane, Extrude and Revolve object types Os gráficos são mapeados nos tipos de objeto Plano, Extrusão e Revolver +@msg Revolve maps graphics onto its side: map them onto the front Revolver mapeia os gráficos na sua lateral: mapeie-os na face frontal +@msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments Os gráficos são complexos demais para esta superfície: simplifique a arte dos símbolos ou reduza Segmentos @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` aceita no máximo {MAX_GRAPHICS} gráficos @msg A plane has one face: map its graphics onto the front Um plano tem uma única face: mapeie seus gráficos na face frontal @msg The graphics are too complex: simplify the symbols' art Os gráficos são complexos demais: simplifique a arte dos símbolos diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 442a9612d4..b7679093dc 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -5538,7 +5538,9 @@ lighting Light Свет @msg `{GRAPHICS}` face must be front or back face в `{GRAPHICS}` должен быть front или back @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} {key} в `{GRAPHICS}` должен быть числом от {lo} до {hi} @msg `{GRAPHICS}` must be an array `{GRAPHICS}` должен быть массивом -@msg Graphics map onto planar faces: use the Extrude or Plane object type Графика наносится на плоские грани: используйте тип объекта «Выдавливание» или «Плоскость» +@msg Graphics map onto the Plane, Extrude and Revolve object types Графика наносится на объекты типов «Плоскость», «Выдавливание» и «Вращение» +@msg Revolve maps graphics onto its side: map them onto the front «Вращение» наносит графику на свою боковую поверхность: размещайте её на передней стороне +@msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments Графика слишком сложна для этой поверхности: упростите иллюстрации символов или уменьшите «Сегменты» @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` принимает не более {MAX_GRAPHICS} графических элементов @msg A plane has one face: map its graphics onto the front У плоскости одна сторона: размещайте её графику на передней стороне @msg The graphics are too complex: simplify the symbols' art Графика слишком сложна: упростите иллюстрации символов diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 8a8f8453b6..7ded937024 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -5406,7 +5406,9 @@ lighting Light Ljus @msg `{GRAPHICS}` face must be front or back face i `{GRAPHICS}` måste vara front eller back @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} {key} i `{GRAPHICS}` måste vara ett tal från {lo} till {hi} @msg `{GRAPHICS}` must be an array `{GRAPHICS}` måste vara en matris -@msg Graphics map onto planar faces: use the Extrude or Plane object type Grafik placeras på plana sidor: använd objekttypen Extrudera eller Plan +@msg Graphics map onto the Plane, Extrude and Revolve object types Grafik placeras på objekttyperna Plan, Extrudera och Rotera runt axel +@msg Revolve maps graphics onto its side: map them onto the front Rotera runt axel placerar grafik på sin mantelyta: placera den på framsidan +@msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments Grafiken är för komplex för den här ytan: förenkla symbolernas teckning eller minska Segment @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` tar högst {MAX_GRAPHICS} grafiker @msg A plane has one face: map its graphics onto the front Ett plan har en sida: placera dess grafik på framsidan @msg The graphics are too complex: simplify the symbols' art Grafiken är för komplex: förenkla symbolernas teckning diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index ef8773c31b..f5363720bf 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -5201,7 +5201,9 @@ lighting Light Işık @msg `{GRAPHICS}` face must be front or back `{GRAPHICS}` face değeri front veya back olmalıdır @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} `{GRAPHICS}` {key} değeri {lo} ile {hi} arasında bir sayı olmalıdır @msg `{GRAPHICS}` must be an array `{GRAPHICS}` bir dizi olmalıdır -@msg Graphics map onto planar faces: use the Extrude or Plane object type Grafikler düz yüzlere eşlenir: Ekstrüzyon veya Düzlem nesne türünü kullan +@msg Graphics map onto the Plane, Extrude and Revolve object types Grafikler Düzlem, Ekstrüzyon ve Döndür nesne türlerine eşlenir +@msg Revolve maps graphics onto its side: map them onto the front Döndür grafikleri yan yüzeyine eşler: onları ön yüze eşle +@msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments Grafikler bu yüzey için çok karmaşık: sembollerin resmini basitleştir veya Segmentler değerini azalt @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` en fazla {MAX_GRAPHICS} grafik alır @msg A plane has one face: map its graphics onto the front Bir düzlemin tek yüzü vardır: grafiklerini ön yüze eşle @msg The graphics are too complex: simplify the symbols' art Grafikler çok karmaşık: sembollerin resmini basitleştir diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 0bccbd8cb6..79546c4a7b 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -5532,7 +5532,9 @@ lighting Light Світло @msg `{GRAPHICS}` face must be front or back face у `{GRAPHICS}` має бути front або back @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} {key} у `{GRAPHICS}` має бути числом від {lo} до {hi} @msg `{GRAPHICS}` must be an array `{GRAPHICS}` має бути масивом -@msg Graphics map onto planar faces: use the Extrude or Plane object type Графіка наноситься на плоскі грані: використайте тип об’єкта «Видавлювання» або «Площина» +@msg Graphics map onto the Plane, Extrude and Revolve object types Графіка наноситься на об’єкти типів «Площина», «Видавлювання» та «Обертання» +@msg Revolve maps graphics onto its side: map them onto the front «Обертання» наносить графіку на свою бічну поверхню: розміщуйте її на передній стороні +@msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments Графіка надто складна для цієї поверхні: спростіть ілюстрації символів або зменште «Сегменти» @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` приймає не більше {MAX_GRAPHICS} графічних елементів @msg A plane has one face: map its graphics onto the front Площина має одну сторону: розміщуйте її графіку на передній стороні @msg The graphics are too complex: simplify the symbols' art Графіка надто складна: спростіть ілюстрації символів diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 4f084029db..3cf7f4326f 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5319,7 +5319,9 @@ theme Appearance Giao diện @msg `{GRAPHICS}` face must be front or back face của `{GRAPHICS}` phải là front hoặc back @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} {key} của `{GRAPHICS}` phải là số từ {lo} đến {hi} @msg `{GRAPHICS}` must be an array `{GRAPHICS}` phải là một mảng -@msg Graphics map onto planar faces: use the Extrude or Plane object type Đồ họa được đặt lên các mặt phẳng: hãy dùng loại đối tượng Kéo dài hoặc Mặt phẳng +@msg Graphics map onto the Plane, Extrude and Revolve object types Đồ họa được đặt lên các loại đối tượng Mặt phẳng, Kéo dài và Xoay tròn +@msg Revolve maps graphics onto its side: map them onto the front Xoay tròn đặt đồ họa lên mặt bên của nó: hãy đặt chúng lên mặt trước +@msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments Đồ họa quá phức tạp cho bề mặt này: hãy đơn giản hóa hình vẽ của các ký hiệu hoặc giảm Đoạn @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` nhận tối đa {MAX_GRAPHICS} đồ họa @msg A plane has one face: map its graphics onto the front Mặt phẳng chỉ có một mặt: hãy đặt đồ họa của nó lên mặt trước @msg The graphics are too complex: simplify the symbols' art Đồ họa quá phức tạp: hãy đơn giản hóa hình vẽ của các ký hiệu diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index b04e65a65b..350cffaa58 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -5808,7 +5808,10 @@ lighting Light 光源 @msg `{GRAPHICS}` face must be front or back `{GRAPHICS}` 的 face 必须是 front 或 back @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} `{GRAPHICS}` 的 {key} 必须是 {lo} 到 {hi} 之间的数字 @msg `{GRAPHICS}` must be an array `{GRAPHICS}` 必须是数组 -@msg Graphics map onto planar faces: use the Extrude or Plane object type 图形映射到平坦的面上:请使用突出或平面对象类型 +@msg Graphics map onto the Plane, Extrude and Revolve object types 图形映射到平面、突出和回转对象类型上 + Graphics map onto the Plane, Extrude and Revolve object types. 图形映射到平面、突出和回转对象类型上。 +@msg Revolve maps graphics onto its side: map them onto the front 回转将图形映射到其侧面:请将图形映射到正面 +@msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments 图形对此表面过于复杂:请简化符号的图稿或减少分段数 @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` 最多接受 {MAX_GRAPHICS} 个图形 @msg A plane has one face: map its graphics onto the front 平面只有一个面:请将其图形映射到正面 @msg The graphics are too complex: simplify the symbols' art 图形过于复杂:请简化符号的图稿 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index be62fde8a7..680beaea63 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -5640,7 +5640,10 @@ lighting Light 光源 @msg `{GRAPHICS}` face must be front or back `{GRAPHICS}` 的 face 必須是 front 或 back @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} `{GRAPHICS}` 的 {key} 必須是介於 {lo} 到 {hi} 之間的數字 @msg `{GRAPHICS}` must be an array `{GRAPHICS}` 必須是陣列 -@msg Graphics map onto planar faces: use the Extrude or Plane object type 圖形會對應到平坦的面:請使用「突出」或「平面」物件類型 +@msg Graphics map onto the Plane, Extrude and Revolve object types 圖形會對應到「平面」、「突出」與「迴轉」物件類型 + Graphics map onto the Plane, Extrude and Revolve object types. 圖形會對應到「平面」、「突出」與「迴轉」物件類型。 +@msg Revolve maps graphics onto its side: map them onto the front 迴轉會將圖形對應到其側面:請將圖形對應到正面 +@msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments 圖形對此表面過於複雜:請簡化符號的圖稿或減少分段數 @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` 最多接受 {MAX_GRAPHICS} 個圖形 @msg A plane has one face: map its graphics onto the front 平面只有一個面:請將其圖形對應到正面 @msg The graphics are too complex: simplify the symbols' art 圖形過於複雜:請簡化符號的圖稿 diff --git a/crates/ui-egui/src/panels/tests_three_d.rs b/crates/ui-egui/src/panels/tests_three_d.rs index 08f0819b3a..72ce8004b5 100644 --- a/crates/ui-egui/src/panels/tests_three_d.rs +++ b/crates/ui-egui/src/panels/tests_three_d.rs @@ -438,12 +438,35 @@ fn the_materials_tab_lists_the_graphics_and_maps_one_in_one_undo_step() { let nodes = controls(&mut app, &ctx); named(&nodes, "Remove Graphic"); named(&nodes, "Scale"); - // Inflate has no planar faces to map onto. + // Inflate takes no graphics. set_type(&mut app, "inflate").unwrap(); let mut out = ctx.run_ui(egui::RawInput::default(), |ui| show(&mut app, ui)); out.textures_delta.clear(); let text = crate::tests_labels::shapes_text(&out); - assert!(text.contains("Graphics map onto planar faces"), "{text}"); + assert!(text.contains("Graphics map onto the Plane, Extrude and Revolve object types"), "{text}"); +} + +#[test] +fn on_revolve_the_materials_tab_maps_onto_the_side_without_a_face_choice() { + let (mut app, ctx) = materials_app(); + ctx.enable_accesskit(); + super::run_action(&mut app, &ctx, crate::dialogs::three_d_materials::Action::Map("Graphic".into())); + let drawn = |app: &mut VectorcraftApp| { + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| show(app, ui)); + out.textures_delta.clear(); + crate::tests_labels::shapes_text(&out) + }; + assert!(drawn(&mut app).contains("Face")); + // Revolve keeps the graphic on its side and lists it without Face; a pick maps another. + set_type(&mut app, "revolve").unwrap(); + assert_eq!(graphics(&app).as_array().map(Vec::len), Some(1)); + let history = undo_len(&app); + super::run_action(&mut app, &ctx, crate::dialogs::three_d_materials::Action::Map("Graphic".into())); + assert_eq!(graphics(&app).as_array().map(Vec::len), Some(2)); + assert_eq!(undo_len(&app), history + 1); + named(&controls(&mut app, &ctx), "Scale"); + let text = drawn(&mut app); + assert!(text.contains("Mapped graphics") && !text.contains("Face"), "{text}"); } #[test] diff --git a/docs/effects-parity.md b/docs/effects-parity.md index 0eb68c7e25..96b07d508f 100644 --- a/docs/effects-parity.md +++ b/docs/effects-parity.md @@ -180,7 +180,7 @@ VectorCraft choices; an original approximation, never compared with another appl |---|---| | Revolve | initial: live, editable profile, rotation and light gizmos, default-on Cap with continuous curved rims, smooth vector shading and round seam joins, SVG/PDF output, Expand Appearance ([revolve.md](revolve.md), #846) | | Extrude & Bevel, Inflate, Rotate | initial: live, depth, twist, taper, solid or hollow caps, five original bevel shapes, Inflate volume, both sides, twist, taper and cap, Rotate of every fill and stroke, groups and layers turned about one shared axis (#4506), contours that cross, touch or overlap merged first ([three-d.md](three-d.md)), Position presets, rotation and light gizmos, SVG/PDF output, Expand Appearance ([three-d.md](three-d.md)) | -| Materials panel, lighting, ray-traced render | Window › 3D and Materials panel with the object types (Plane, Extrude, Revolve, Inflate) and the Object, Rotation and Lighting settings of the applied effect, and Quick Actions › Expand as Wireframes ([three-d.md](three-d.md#3d-and-materials-panel)); one to ten directional lights with per-light Color (opaque RGB, white by default), Intensity, Rotation, Height, Softness and neutral Ambient Light, Revolve and colored Inflate use smooth vector shading; Extrude & Bevel and Rotate retain planar shading; original Standard, Diffuse, Top Left and Right lighting rigs; hard-edged shadows behind or below the object from the first light ([three-d.md](three-d.md#shadows)); the Materials tab's Graphics, document symbols mapped onto Extrude & Bevel's caps and onto a plane, moved with an artboard handle ([three-d.md](three-d.md#graphics)); no base materials, graphics on curved surfaces, soft shadows or ray tracing | +| Materials panel, lighting, ray-traced render | Window › 3D and Materials panel with the object types (Plane, Extrude, Revolve, Inflate) and the Object, Rotation and Lighting settings of the applied effect, and Quick Actions › Expand as Wireframes ([three-d.md](three-d.md#3d-and-materials-panel)); one to ten directional lights with per-light Color (opaque RGB, white by default), Intensity, Rotation, Height, Softness and neutral Ambient Light, Revolve and colored Inflate use smooth vector shading; Extrude & Bevel and Rotate retain planar shading; original Standard, Diffuse, Top Left and Right lighting rigs; hard-edged shadows behind or below the object from the first light ([three-d.md](three-d.md#shadows)); the Materials tab's Graphics, document symbols mapped onto Extrude & Bevel's caps and onto a plane, moved with an artboard handle, and wrapped around Revolve's side ([three-d.md](three-d.md#graphics)); no base materials, graphics on Inflate or on Extrude & Bevel's walls and bevels, soft shadows or ray tracing | | 3D (Classic): Extrude & Bevel, Revolve, Rotate | Extrude & Bevel (Classic) initial: live, Extrude Depth, Cap, five original bevel shapes with Height and Bevel Extent In or Out, Position presets and rotation gizmo, Perspective, Wireframe, No Shading, Diffuse and Plastic surfaces with one to ten lights, Light Intensity, Ambient Light, Highlight Intensity and Size, Blend Steps, Black, Custom or no Shading Color, Draw Hidden Faces ([create 3D objects](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/create-3d-objects.html)); Revolve (Classic) initial: live, Angle, Cap, Offset from the left or right edge, Position presets and rotation gizmo, Perspective, the same four surfaces, lights, highlight, Blend Steps and Shading Color, groups and layers revolved about one shared axis (same page); Rotate (Classic) initial: live, every fill and stroke turned as one plane, Position presets and rotation gizmo, Perspective, No Shading and Diffuse surfaces with lights, Ambient Light, Blend Steps and Shading Color ([rotate objects in 3D](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/rotate-objects-in-3d.html)); Map Art: none | | Turntable (30.0 beta) | none | | Export 3D objects (OBJ, USDA, glTF) | initial: Asset Export's Export 3D Object collects an object with Extrude & Bevel, Revolve, Inflate or Rotate as a 3D asset, and Export writes its solids as a USDA (the default), USDZ, glTF or OBJ mesh with a material in each solid's paint color (`assets.add3D`, `assets.set3DFormat`, `assets.export3D`); no textures, map art or shading ([3D export help](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/export-3d-vector-artwork.html)) | diff --git a/docs/mcp.md b/docs/mcp.md index 274db05a34..606a29c2a6 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3528,12 +3528,16 @@ effect of each selected object, in one undo step: `face` is `front` (default) or offset in points of the graphic's center from the center of the object's bounds in the face's plane, `scale` is a percentage of the symbol's size (1..10000; omitted, 100 or less so the graphic fits inside the object) and `rotation` is in degrees counterclockwise (-360..360). Without `index` each object's first 3D effect takes it, and `item` is refused. -Every object's 3D effect must be Extrude & Bevel with Cap on (front only at a depth of 0) or Rotate (the Plane type, -front only), and `symbol` must name a document symbol; otherwise the command is refused and nothing changes. It returns `{ids, graphic}`. +Every object's 3D effect must be Extrude & Bevel with Cap on (front only at a depth of 0), Rotate (the Plane type, +front only) or Revolve (front only: its swept side), and `symbol` must name a document symbol; otherwise the command is refused and nothing changes. It returns `{ids, graphic}`. +On Revolve, `x` and `y` are measured on the side unrolled flat from its middle, and a graphic that does not fit +starts scaled to fit the half of the side seen from the front ([three-d.md](three-d.md#graphics)). -The graphics are the `graphics` parameter of `threeD.extrude` and `threeD.rotate`, which `effect.setParams` also +The graphics are the `graphics` parameter of `threeD.extrude`, `threeD.rotate` and `threeD.revolve`, which `effect.setParams` also edits: an array of up to 64 `{symbol, face, x, y, scale, rotation}` objects, drawn on the face turned, foreshortened and shaded with it and clipped to it ([Map artworks on 3D object](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/map-artwork-on-3d-objects.html)). +Revolve takes graphics on its swept side and shades them with the object's light ([the archived reference, page 185](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=185)); +how a graphic wraps around the side is VectorCraft's own rule. A graphic naming a symbol the document does not have is refused, unless the effect already holds a graphic of it. The drawing rules are VectorCraft's own; see [three-d.md](three-d.md#graphics). diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f04ee3c910..750ab68f85 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1183,6 +1183,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Extrude & Bevel (both kinds) and Rotate keep the art's curves in the faces they draw, export and expand: caps and the edges of walls and bevels where they meet a cap are cubics with smooth anchors where the art's are, fitted within 0.001 pt in perspective and within the sampling tolerance on a bevel's inset. An edge of a twisted wall that is cut into pieces, a piece of curve that does not fit after 8 halvings, and the curves past 1,048,576 for one solid stay straight (VectorCraft's own values; [three-d.md](three-d.md#what-differs-from-the-public-documentation)). Tests `solid::tests::a_cap_keeps_the_curves_of_the_art`, `a_cap_in_perspective_fits_the_projected_curves`, `a_beveled_cap_and_its_walls_share_their_curves`, `twisted_beveled_tiny_and_degenerate_caps_keep_their_curves`. - Export 3D Object (Asset Export's menu): an object with Extrude & Bevel, Revolve, Inflate or Rotate becomes a 3D asset whose Format is USDA (the default), USDZ, glTF or OBJ, and Export writes each of its solids as a mesh with a material in its paint's color (`assets.add3D`, `assets.set3DFormat`, `assets.export3D`; [export 3D vector artwork](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/export-3d-vector-artwork.html)). - Initial live Revolve (#605, #846): a portable geometry and shading crate (`three-d`), editable path and compound profiles, compact options with artboard rotation and light gizmos, SVG/PDF vector output and Expand Appearance that can trim covered faces. Open ends have continuous caps by default, shading is smooth with one to ten colored lights, and intersecting surfaces' visibility is approximate ([revolve.md](revolve.md)). + - Revolve takes graphics on its swept side, shaded with the object's light ([the archived reference, page 185](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=185)). By VectorCraft's own rule a graphic wraps around the axis at its own size at every distance from it, narrows toward the silhouette, follows the profile along its length and is hidden where the side faces away (`threeD.mapGraphic`; `revolve::tests_graphics`, `tests::side_faces_lie_on_the_unrolled_surface_and_caps_do_not`, `map_graphic_puts_a_graphic_on_the_side_of_a_revolve`). - Revolve takes type, as its glyph outlines, and groups or layers, whose members sweep about one axis as [the help page](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/create-3d-objects.html) describes; a surface can have up to 16,384 profile points, and curves take fewer samples when a surface would pass 163,840 faces (#3617). - Live effects with previewing dialogs: Distort & Transform, Path, Convert to Shape, 15 Warp styles, Round Corners, Scribble, Effect → Pathfinder (all 10 operations, live on groups; several loose objects are grouped first, in one undo step), Color Adjustments (Brightness/Contrast, Curves, Levels, Hue/Saturation, Shift to Color, Temperature/Tint, on vectors, live type and embedded images), and raster drop shadow, glows and feather. SVG and PDF export keep live effects (geometry baked; SVG raster effects as filters). Zig Zag spaces its ridges evenly along each segment, so lines and curves get a regular wave in Corner and Smooth (#1558). Warp › Arc (the effect and Envelope › Make with Warp) bends in the object's real proportions: a circular arc with concentric edges and no fold-over at 100%, so Arc on art that isn't square draws differently from before (#1581, fixes #1578). `effect.apply` and `effect.setParams` give an error for a misspelt or wrongly typed effect parameter instead of running the effect with its default (#1623, #1592). Roughen with Smooth keeps turn-backs smooth instead of making cusps that draw as spikes (#1646, #1643). Scribble draws one zig-zag per region, with no lines across holes and notches; convex shapes are unchanged (#1651, #1648). On the canvas, in Expand Appearance and in exports, Effect → Pathfinder uses the glyph outlines of type in the group, and results painted like the type keep its opacity and blend mode. - Cmd/Ctrl+4 (`pathfinder.repeat`) repeats the last successful Pathfinder panel operation, direct `object.pathfinder.*` command or `command.batch` step (including Actions playback) on the current selection; the panel menu names it. `action.batch`, Trap, compound-shape edits and live effects do not set history. Public references: [Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html), [Pathfinder panel overview](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/pathfinder-panel-overview.html). diff --git a/docs/three-d.md b/docs/three-d.md index c701585b88..1d43351960 100644 --- a/docs/three-d.md +++ b/docs/three-d.md @@ -308,8 +308,9 @@ Our reading: The public [Map artworks on 3D object](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/map-artwork-on-3d-objects.html) page describes graphics: art kept with the document and placed on single surfaces of a 3D object, and the [3D and Materials panel options](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/3d-materials-panel-options.html) -page lists Graphics and Add Materials and Graphics on the Materials tab. VectorCraft maps graphics onto planar faces: -Extrude & Bevel's front and back caps, and the plane of the Plane type (Rotate). +page lists Graphics and Add Materials and Graphics on the Materials tab. VectorCraft maps graphics onto +Extrude & Bevel's front and back caps, the plane of the Plane type (Rotate), and the swept side of Revolve, which the +public page's example of a label on a bottle describes. - The panel's **Materials** tab shows the document's graphics as thumbnails. A graphic is a document symbol, as the public page allows existing symbols to be used. **Add as Single Graphic** keeps the selected art as a new @@ -337,6 +338,24 @@ These rules are VectorCraft's own: the viewer is not drawn. - On the back cap, X runs to the right as the back is seen from behind, so the graphic reads the right way round there. +- On Revolve a graphic lies on the swept side, which has one face (Front), unrolled flat. X runs around the axis: + the angle from the middle of the side times the profile's distance from the axis at that point, so a graphic + keeps its size at every distance and wraps farther around the axis where the profile comes nearer to it. Y runs + along the profile, toward its lower end, measured from the middle of its length; a profile's edges on the axis + sweep nothing and add no length. On a closed profile that does not touch the axis, Y is measured from where its + outer side crosses the middle of its height, and the graphic is cut on its inner side. The middle of the side + is the middle of the part of the sweep that faces the viewer before the object is turned, which is the part at + 90° with the axis on the left and at 270° with it on the right (the middle of the sweep when no part faces the + viewer). On a compound profile the graphics go on its longest contour. Each face + of the side draws the part of the graphic that falls on it, shaded as the face is shaded, so the graphic narrows + toward the silhouette and is not drawn where the side's outside faces away or past the ends of the sweep; nearer + faces drawn after it cover it. A full turn cuts the graphic at the back, and the end caps take no graphic; a part + that runs past the end of the profile reaches the curved rim of the cap and stops there. On a group or layer the + graphics go once, on the side of the member with the longest profile. Curves + are cut into straight pieces within 0.05 pt before they are mapped, and an opaque part takes a 0.3 pt stroke of + its paint over the seams between faces. A graphic larger than the half of the side seen from the front starts + scaled to fit it. The panel shows no handle for a Revolve's graphics; X and Y move them. Expand Appearance keeps + every face of a surface with graphics. - The symbol's fills and strokes are drawn as filled areas, a stroke as its outline, and their gradients and patterns are placed with the graphic. Images, hidden objects, guides and clipping paths in the symbol are left out, and clipping groups draw their art unclipped. Instances @@ -345,12 +364,13 @@ These rules are VectorCraft's own: - Without perspective, the graphic maps exactly. With perspective, straight lines stay straight and each curve is cut into 8 cubic pieces before it is mapped. The part of a graphic at or behind the eye is left out. - An object takes up to 64 graphics. One graphic draws up to 4,096 fills and strokes, and the graphics of one 3D - effect draw up to 400,000 path elements together. Commands refuse a graphic past either limit. A loaded file + effect draw up to 400,000 path elements together (on Revolve, 400,000 points after the curves are cut, and up to + 2,000,000 once they are cut at the faces). Commands refuse a graphic past either limit. A loaded file draws the object without a graphic past the first limit, and without all of its graphics past the second. - A hollow Extrude & Bevel has no caps, so its graphics are not drawn until Cap is turned on again, and - `threeD.mapGraphic` refuses to map a new one onto it. Changing the type to Revolve or Inflate - drops the graphics, and changing between Extrude and Plane keeps them, except that Plane drops the graphics - on the back cap. + `threeD.mapGraphic` refuses to map a new one onto it. Changing the type to Inflate drops the graphics, and + changing between Extrude, Plane and Revolve keeps them, except that Plane and Revolve drop the graphics on the + back cap; on Revolve the front's graphics go on its side. - `effect.apply` and `effect.setParams` refuse a graphic that names a symbol the document does not have, unless the effect already holds a graphic of that symbol. A graphic whose symbol is deleted is no longer drawn. Renaming a symbol renames it in the graphics that use it, in the layers, in the art of symbols, patterns, graph designs, brushes and opacity masks, and in graphic @@ -364,9 +384,9 @@ These rules are VectorCraft's own: uses: `rotationX`, `rotationY`, `rotationZ`, `perspectiveAngle` (degrees), `shade`, `lightColor` (`#rrggbb`, default `#ffffff`), `lightIntensity` (%), `lightRotation`, `lightHeight` (degrees), `lightSoftness` (%), `ambient` (%, to 200), `lightBehind`. Lengths are points and scale with the object (Scale Strokes & Effects). Commands validate the shape and the parameters before the document changes. All four also take `lights`: null (the default, use the earlier single-light fields), or an array of one to ten objects. Each object takes `color` (opaque `#rrggbb`, white), `intensity` (0..100%, 80), `rotation` (-180..180 degrees, 125.26), `height` (0..90 degrees, 30), `softness` (0..100%, 0), and `behind` (boolean, false). Omitted settings use those defaults. An explicit list replaces the earlier single light; `ambient` and `shade` remain shared. Set `lights` to null to return to the single-light fields. Invalid lists, counts, keys and values are rejected before editing; malformed loaded lists fall back to the earlier light safely. All four take `shadow` (boolean, false), `shadowPosition` (`behind` or `below`), `shadowDistance` (0..100%, 0) and `shadowBounds` (10..400%, 100) ([Shadows](#shadows)); values out of range are rejected before editing. -`threeD.extrude` and `threeD.rotate` take `graphics` ([Graphics](#graphics)): an array of up to 64 objects, each -with `symbol` (the name of a document symbol), `face` (`front` or `back`, default `front`; `threeD.rotate` takes -`front` only), `x` and `y` (points, default 0), `scale` (1..10000%, default 100) and `rotation` (-360..360 degrees, +`threeD.extrude`, `threeD.rotate` and `threeD.revolve` take `graphics` ([Graphics](#graphics)): an array of up to 64 objects, each +with `symbol` (the name of a document symbol), `face` (`front` or `back`, default `front`; `threeD.rotate` and +`threeD.revolve` take `front` only), `x` and `y` (points, default 0), `scale` (1..10000%, default 100) and `rotation` (-360..360 degrees, default 0). Other keys, values out of range and graphics on the other 3D effects are rejected before editing. ## What differs from the public documentation @@ -376,11 +396,11 @@ and [Create 3D objects](https://helpx.adobe.com/illustrator/desktop/special-effe pages, and the archived Extrude & Bevel option list (depth 0–2,000, cap on/off, bevel height, bevel extent in or out, perspective). No Adobe software, assets, presets or bevel shapes were used. -- **Materials** (base and Adobe Substance), graphics on curved surfaces (Revolve, Inflate and Extrude & Bevel's - walls and bevels), soft shadows, shadows of lights after the first, and **ray-traced rendering** are not built: - shading uses directional lights, in the paint of the fill or stroke the solid is built for - ([Fills and strokes](#fills-and-strokes)), and the shadow is hard-edged ([Shadows](#shadows)). Graphics map - onto planar faces only ([Graphics](#graphics)). +- **Materials** (base and Adobe Substance), graphics on Inflate and on Extrude & Bevel's walls and bevels, soft + shadows, shadows of lights after the first, and **ray-traced rendering** are not built: shading uses directional + lights, in the paint of the fill or stroke the solid is built for ([Fills and strokes](#fills-and-strokes)), and + the shadow is hard-edged ([Shadows](#shadows)). Graphics map onto planar faces and Revolve's side only + ([Graphics](#graphics)). - The bevel shapes and their names are our own; custom bevel paths are not supported. - Visibility is a painter's algorithm: faces of a closed solid turned away are left out, and the rest are drawn back to front, with a flat cap or flat back turned toward the viewer drawn after all of them. Concave solids From 3ca5a75d87a459919e18f3be79c5c8e2a37222cb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 05:06:03 -0800 Subject: [PATCH 06/25] Scripts: namespace scopes and edits count against the heap limit The namespace list that inScopeNamespaces(), namespace(), namespaceDeclarations(), the XPath namespace axis, XPath prefixes and XPath name() collect from a node and its ancestors was built in Rust buffers the heap limit did not see, so a node with many namespaces in scope let a script grow past its limit. The scope now holds the bytes of its list and prefix table until it is dropped, and namespaceDeclarations() also holds its ancestor table and the declarations it returns. The queried node stays rooted while the scope is built, and each declaration is read in place instead of copying every node's namespace list. Other copies in the same files are held against the limit too: - addNamespace(), setNamespace(), setName() and removeNamespace() read an element's attributes one at a time instead of copying the list, and removeNamespace() holds its walk stack. - child(index), comments(), text(), elements(), processingInstructions() and normalize() on an XMLList hold the copy of its items, and replace() holds the copy of the children it matched. - XPath name() holds the units of a prefixed name it builds. - The XML, XMLList, Namespace and QName constructors, isXMLName(), attribute(), namespace(), propertyIsEnumerable(), setName(), setLocalName(), addNamespace(), removeNamespace() and setNamespace() reserve the bytes of the flat copy of a long (rope) string argument before they make it, and attribute() reserves the copy of a name without its leading @. - QName.prototype.toString() reserves its result before it builds it. --- crates/js/src/xml_builtins.rs | 271 +++++++++++++++++++++++----------- crates/js/src/xml_tests.rs | 140 +++++++++++++++++- crates/js/src/xpath.rs | 50 ++++--- docs/target-app-parity.md | 1 + 4 files changed, 352 insertions(+), 110 deletions(-) diff --git a/crates/js/src/xml_builtins.rs b/crates/js/src/xml_builtins.rs index 9cd797f48a..d3a5245793 100644 --- a/crates/js/src/xml_builtins.rs +++ b/crates/js/src/xml_builtins.rs @@ -8,8 +8,8 @@ use crate::builtins::{arg, constructor, data, method, native}; use crate::heap::{ Class, ENUMERABLE, Key, NativeFn, NativeKind, OBJECT_BYTES, ObjId, Object, PROP_BYTES, Prop, WRITABLE, XmlKind, XmlName, XmlNs, key, string_bytes, }; -use crate::interp::{Abrupt, Interp, JsResult}; -use crate::string_builtins::{new_array, set_element}; +use crate::interp::{Abrupt, HeldBytes, Interp, JsResult}; +use crate::string_builtins::{flat_charged, new_array, push_held, reserve_units, set_element}; use crate::value::{Str, Value}; use crate::xml::{ Access, Content, NameRef, RESERVED_NS_BINDING, STAR, Xv, canonical_index, is_ncname, is_script_xml_name, ns_binding_allowed, xml_name_writable, @@ -184,6 +184,13 @@ fn as_qname(interp: &Interp, v: &Value) -> Option<(XmlName, bool)> { } } +/// The code units of `v` as a string. A rope is flattened only after the bytes of its copy are +/// reserved. +fn str_arg(interp: &mut Interp, v: &Value) -> JsResult { + let s = interp.to_str(v)?; + flat_charged(interp, &s) +} + /// The namespace `new Namespace(...)` makes from its arguments (ECMA-357 section 13.2.2). fn build_namespace(interp: &mut Interp, args: &[Value]) -> JsResult { match args { @@ -197,7 +204,7 @@ fn build_namespace(interp: &mut Interp, args: &[Value]) -> JsResult { { return Ok(XmlNs { prefix: name.prefix, uri: u }); } - let u = interp.to_str(uri)?.flat(); + let u = str_arg(interp, uri)?; let prefix = if u.is_empty() { Some(empty()) } else { None }; Ok(XmlNs { prefix, uri: u }) } @@ -205,7 +212,7 @@ fn build_namespace(interp: &mut Interp, args: &[Value]) -> JsResult { let qname_uri = as_qname(interp, uri).and_then(|(n, _)| n.uri); let u = match qname_uri { Some(u) => u, - None => interp.to_str(uri)?.flat(), + None => str_arg(interp, uri)?, }; if u.is_empty() { if matches!(prefix_value, Value::Undefined) || interp.to_str(prefix_value)?.len() == 0 { @@ -216,7 +223,7 @@ fn build_namespace(interp: &mut Interp, args: &[Value]) -> JsResult { if matches!(prefix_value, Value::Undefined) { return Ok(XmlNs { prefix: None, uri: u }); } - let p = interp.to_str(prefix_value)?.flat(); + let p = str_arg(interp, prefix_value)?; Ok(XmlNs { prefix: is_ncname(&p).then_some(p), uri: u }) } } @@ -256,7 +263,7 @@ fn build_qname(interp: &mut Interp, args: &[Value]) -> JsResult<(XmlName, bool)> } else if matches!(name_value, Value::Undefined) { empty() } else { - interp.to_str(&name_value)?.flat() + str_arg(interp, &name_value)? }; let (uri, prefix) = match namespace { Some(Value::Undefined) | None => { @@ -290,7 +297,16 @@ fn qname_to_string(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> Js let Some((name, attribute)) = as_qname(interp, &this) else { return Err(interp.type_error("QName.prototype.toString needs a QName")); }; - let mut units: Vec = Vec::new(); + let uri_len = match &name.uri { + None => 3, + Some(u) if !u.is_empty() => u.len().saturating_add(2), + _ => 0, + }; + let len = usize::from(attribute).saturating_add(uri_len).saturating_add(name.local.len()); + let bytes = string_bytes(len); + interp.reserve_heap(bytes)?; + interp.heap.bytes = interp.heap.bytes.saturating_add(bytes); + let mut units: Vec = Vec::with_capacity(len); if attribute { units.push(0x40); } @@ -303,9 +319,6 @@ fn qname_to_string(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> Js _ => {} } units.extend_from_slice(&name.local); - let bytes = string_bytes(units.len()); - interp.reserve_heap(bytes)?; - interp.heap.bytes = interp.heap.bytes.saturating_add(bytes); Ok(Value::String(Str::from_units(units))) } @@ -324,7 +337,7 @@ fn to_xml(interp: &mut Interp, v: &Value) -> JsResult { Err(interp.type_error("an XMLList converts to XML only when it has one item")) } Xv::Other => { - let text = if v.is_nullish() { empty() } else { interp.to_str(v)?.flat() }; + let text = if v.is_nullish() { empty() } else { str_arg(interp, v)? }; interp.xml_from_text(&text) } } @@ -355,7 +368,7 @@ fn xml_list_ctor(interp: &mut Interp, _: Value, args: &[Value], construct: bool) Xv::Node(n) => i.list_push(out, n)?, _ if v.is_nullish() => {} _ => { - let text = i.to_str(&v)?.flat(); + let text = str_arg(i, &v)?; for node in i.xml_parse(&text)? { i.list_push(out, node)?; } @@ -366,7 +379,7 @@ fn xml_list_ctor(interp: &mut Interp, _: Value, args: &[Value], construct: bool) } fn is_xml_name(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { - let s = interp.to_str(&arg(args, 0))?.flat(); + let s = str_arg(interp, &arg(args, 0))?; Ok(Value::Bool(is_script_xml_name(&s))) } @@ -440,10 +453,16 @@ fn this_id(interp: &mut Interp, this: &Value) -> JsResult { } } -fn nodes_of(interp: &mut Interp, this: &Value) -> JsResult> { +/// The nodes of `this`: the node itself, or a copy of the items of an XMLList, whose bytes `held` +/// holds against the heap limit first. +fn nodes_of(interp: &mut Interp, held: &mut HeldBytes, this: &Value) -> JsResult> { match interp.classify(this) { Xv::Node(n) => Ok(vec![n]), - Xv::List(l) => Ok(interp.xml_list(l)?.items.clone()), + Xv::List(l) => interp.rooted(std::slice::from_ref(this), |interp| { + let count = interp.xml_list(l)?.items.len(); + held.add(interp, count.saturating_mul(size_of::()))?; + Ok(interp.xml_list(l)?.items.clone()) + }), Xv::Other => Err(not_xml_method(interp)), } } @@ -464,8 +483,14 @@ fn attribute_name(interp: &mut Interp, v: &Value) -> JsResult { if matches!(v, Value::Undefined | Value::Null | Value::Bool(_) | Value::Number(_)) { return Err(interp.type_error("the value is not an XML attribute name")); } - let local = interp.to_str(v)?.flat(); - let local = local.strip_prefix(&[0x40u16]).map_or_else(|| local.clone(), Rc::from); + let local = str_arg(interp, v)?; + let local = match local.strip_prefix(&[0x40u16]) { + Some(rest) => { + reserve_units(interp, rest.len())?; + Rc::from(rest) + } + None => local, + }; let uri = if *local == *STAR { None } else { Some(empty()) }; Ok(NameRef { uri, local, attribute: true }) } @@ -510,7 +535,8 @@ fn child(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult< match interp.xml_access(&p)? { Access::Name(n) => Ok(Value::Object(interp.xml_select(id, &n)?)), Access::Index(i) => { - let nodes = nodes_of(interp, &this)?; + let mut held = HeldBytes::new(interp); + let nodes = nodes_of(interp, &mut held, &this)?; interp.rooted(std::slice::from_ref(&this), |it| { let out = it.new_xml_list(Some(id), None)?; it.xml_keep(out); @@ -535,7 +561,8 @@ fn select_children( keep: impl Fn(&Interp, ObjId) -> JsResult, ) -> JsResult { let id = this_id(interp, this)?; - let nodes = nodes_of(interp, this)?; + let mut held = HeldBytes::new(interp); + let nodes = nodes_of(interp, &mut held, this)?; interp.rooted(std::slice::from_ref(this), |it| { let out = it.new_xml_list(Some(id), target_name)?; it.xml_keep(out); @@ -666,34 +693,64 @@ fn has_simple_content(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> } } -/// The namespaces in scope at `x`, nearest declarations first, one for each prefix. Takes one unit -/// of fuel for each node it climbs through and for each declaration it reads. -pub(crate) fn scope_of(interp: &mut Interp, x: Option) -> JsResult> { - let mut out: Vec = Vec::new(); - let mut seen: HashSet> = HashSet::new(); - let mut cur = x; - while let Some(y) = cur { - interp.use_fuel()?; - let (list, parent) = { - let node = interp.xml_node(y)?; - (node.ns.clone(), node.parent) - }; - for ns in list { - interp.use_fuel()?; - if seen.insert(ns.prefix.clone()) { - out.push(ns); - } - } - cur = parent; - } - Ok(out) +/// The namespaces in scope at a node, nearest declarations first, one for each prefix. The bytes of +/// the list and of the table of prefixes that built it stay held against the heap limit until the +/// scope is dropped. +pub(crate) struct Scope { + pub(crate) list: Vec, + _held: HeldBytes, } -fn namespaces_array(interp: &mut Interp, list: Vec) -> JsResult { +/// Holds the bytes of a full hash table of `len` entries of `entry` bytes each, and returns how +/// many more entries to reserve room for. Each new entry is counted four times with a control +/// byte, which covers the empty slots the table keeps and the old table while it is rehashed. +fn grow_table(interp: &mut Interp, held: &mut HeldBytes, len: usize, entry: usize) -> JsResult { + let more = len.max(4); + held.add(interp, more.saturating_mul(4).saturating_mul(entry.saturating_add(1)).saturating_add(16))?; + Ok(more) +} + +/// The namespace `y` declares at index `i`. +fn declared_at(interp: &mut Interp, y: ObjId, i: usize) -> JsResult> { + Ok(interp.xml_node(y)?.ns.get(i).cloned()) +} + +/// The namespaces in scope at `x`, nearest declarations first, one for each prefix. Takes one unit +/// of fuel for each node it climbs through and for each declaration it reads. +pub(crate) fn scope_of(interp: &mut Interp, x: Option) -> JsResult { + let root: Vec = x.map(Value::Object).into_iter().collect(); + interp.rooted(&root, |interp| { + let mut held = HeldBytes::new(interp); + let mut out: Vec = Vec::new(); + let mut seen: HashSet> = HashSet::new(); + let mut cur = x; + while let Some(y) = cur { + interp.use_fuel()?; + let mut i = 0; + while let Some(ns) = declared_at(interp, y, i)? { + interp.use_fuel()?; + i += 1; + if seen.contains(&ns.prefix) { + continue; + } + if seen.len() == seen.capacity() { + let more = grow_table(interp, &mut held, seen.len(), size_of::>())?; + seen.reserve(more); + } + seen.insert(ns.prefix.clone()); + push_held(interp, &mut held, &mut out, ns)?; + } + cur = interp.xml_node(y)?.parent; + } + Ok(Scope { list: out, _held: held }) + }) +} + +fn namespaces_array(interp: &mut Interp, list: &[XmlNs]) -> JsResult { interp.rooted(&[], |i| { let a = new_array(i); - for (at, ns) in list.into_iter().enumerate() { - let v = new_namespace(i, ns)?; + for (at, ns) in list.iter().enumerate() { + let v = new_namespace(i, ns.clone())?; set_element(i, a, at, v)?; } Ok(Value::Object(a)) @@ -702,28 +759,46 @@ fn namespaces_array(interp: &mut Interp, list: Vec) -> JsResult { fn in_scope_namespaces(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { let x = this_node(interp, &this)?; - let list = scope_of(interp, Some(x))?; - namespaces_array(interp, list) + let scope = scope_of(interp, Some(x))?; + namespaces_array(interp, &scope.list) } fn namespace_declarations(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { let x = this_node(interp, &this)?; if interp.xml_kind(x)? != XmlKind::Element { - return namespaces_array(interp, Vec::new()); + return namespaces_array(interp, &[]); } - let parent = interp.xml_node(x)?.parent; - let ancestors: HashMap, Key> = scope_of(interp, parent)?.into_iter().map(|a| (a.prefix, a.uri)).collect(); - let declared: Vec = interp.xml_node(x)?.ns.iter().filter(|ns| ancestors.get(&ns.prefix) != Some(&ns.uri)).cloned().collect(); - namespaces_array(interp, declared) + interp.rooted(&[Value::Object(x)], |interp| { + let parent = interp.xml_node(x)?.parent; + let scope = scope_of(interp, parent)?; + let mut held = HeldBytes::new(interp); + let mut ancestors: HashMap, Key> = HashMap::new(); + for a in &scope.list { + if ancestors.len() == ancestors.capacity() { + let more = grow_table(interp, &mut held, ancestors.len(), size_of::<(Option, Key)>())?; + ancestors.reserve(more); + } + ancestors.insert(a.prefix.clone(), a.uri.clone()); + } + let mut declared: Vec = Vec::new(); + let mut i = 0; + while let Some(ns) = declared_at(interp, x, i)? { + i += 1; + if ancestors.get(&ns.prefix) != Some(&ns.uri) { + push_held(interp, &mut held, &mut declared, ns)?; + } + } + namespaces_array(interp, &declared) + }) } fn namespace(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { let x = this_node(interp, &this)?; let scope = scope_of(interp, Some(x))?; if let Some(p) = args.first() { - let p = interp.to_str(p)?.flat(); - return match scope.into_iter().find(|ns| ns.prefix.as_deref() == Some(&*p)) { - Some(ns) => new_namespace(interp, ns), + let p = str_arg(interp, p)?; + return match scope.list.iter().find(|ns| ns.prefix.as_deref() == Some(&*p)) { + Some(ns) => new_namespace(interp, ns.clone()), None => Ok(Value::Undefined), }; } @@ -734,9 +809,10 @@ fn namespace(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsRes let Some(name) = node.name.clone() else { return Ok(Value::Null) }; let uri = name.uri.clone().unwrap_or_else(empty); let found = scope + .list .iter() .find(|ns| ns.uri == uri && ns.prefix == name.prefix) - .or_else(|| scope.iter().find(|ns| ns.uri == uri)) + .or_else(|| scope.list.iter().find(|ns| ns.uri == uri)) .cloned() .unwrap_or(XmlNs { prefix: name.prefix, uri }); new_namespace(interp, found) @@ -777,7 +853,8 @@ fn node_kind(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult } fn normalize(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { - for node in nodes_of(interp, &this)? { + let mut held = HeldBytes::new(interp); + for node in nodes_of(interp, &mut held, &this)? { if interp.xml_kind(node)? == XmlKind::Element { interp.node_normalize(node)?; } @@ -806,7 +883,7 @@ fn parent(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult JsResult { let p = arg(args, 0); - let s = interp.to_str(&p)?.flat(); + let s = str_arg(interp, &p)?; match interp.classify(&this) { Xv::Node(_) => Ok(Value::Bool(canonical_index(&s) == Some(0))), Xv::List(l) => Ok(Value::Bool(canonical_index(&s).is_some_and(|i| (i as usize) < interp.list_len(l).unwrap_or(0)))), @@ -814,6 +891,11 @@ fn property_is_enumerable(interp: &mut Interp, this: Value, args: &[Value], _: b } } +/// The attribute `x` holds at index `i`. +fn attr_at(interp: &mut Interp, x: ObjId, i: usize) -> JsResult> { + Ok(interp.xml_node(x)?.attrs.get(i).copied()) +} + /// [[AddInScopeNamespace]] (ECMA-357 section 9.1.1.13). fn add_in_scope(interp: &mut Interp, x: ObjId, ns: XmlNs) -> JsResult<()> { if interp.xml_kind(x)? != XmlKind::Element { @@ -823,16 +905,14 @@ fn add_in_scope(interp: &mut Interp, x: ObjId, ns: XmlNs) -> JsResult<()> { if !ns_binding_allowed(&prefix, &ns.uri) { return Err(interp.type_error(RESERVED_NS_BINDING)); } - let node = interp.xml_node(x)?; - if prefix.is_empty() && node.name.as_ref().and_then(|n| n.uri.as_ref()).is_some_and(|u| u.is_empty()) { + if prefix.is_empty() && interp.xml_node(x)?.name.as_ref().and_then(|n| n.uri.as_ref()).is_some_and(|u| u.is_empty()) { return Ok(()); } - if !node.ns.iter().any(|m| m.prefix.as_ref() == Some(&prefix)) { + if !interp.xml_node(x)?.ns.iter().any(|m| m.prefix.as_ref() == Some(&prefix)) { let bytes = crate::heap::XML_NS_BYTES; interp.reserve_heap(bytes)?; interp.heap.bytes = interp.heap.bytes.saturating_add(bytes); } - let attrs = interp.xml_node(x)?.attrs.clone(); let node = interp.xml_node_mut(x)?; node.ns.retain(|m| m.prefix.as_ref() != Some(&prefix)); node.ns.push(ns); @@ -841,8 +921,10 @@ fn add_in_scope(interp: &mut Interp, x: ObjId, ns: XmlNs) -> JsResult<()> { { name.prefix = None; } - for a in attrs { + let mut i = 0; + while let Some(a) = attr_at(interp, x, i)? { interp.use_fuel()?; + i += 1; if let Some(name) = &mut interp.xml_node_mut(a)?.name && name.prefix.as_ref() == Some(&prefix) { @@ -915,25 +997,31 @@ fn insert_child_before(interp: &mut Interp, this: Value, args: &[Value], _: bool insert_relative(interp, this, args, false) } -/// One element of a `removeNamespace` walk; true when the walk goes on to its children. -fn remove_ns_from(interp: &mut Interp, x: ObjId, ns: &XmlNs) -> JsResult { - let node = interp.xml_node(x)?; - let attrs = node.attrs.clone(); - if node.name.as_ref().and_then(|n| n.uri.as_ref()) == Some(&ns.uri) { - return Ok(false); +/// Whether the name of element `x` or of one of its attributes is in `ns`, which keeps `ns` on `x` +/// and its descendants in a `removeNamespace` walk. +fn ns_in_use(interp: &mut Interp, x: ObjId, ns: &XmlNs) -> JsResult { + if interp.xml_node(x)?.name.as_ref().and_then(|n| n.uri.as_ref()) == Some(&ns.uri) { + return Ok(true); } - for a in attrs { + let mut i = 0; + while let Some(a) = attr_at(interp, x, i)? { interp.use_fuel()?; + i += 1; if interp.xml_node(a)?.name.as_ref().and_then(|n| n.uri.as_ref()) == Some(&ns.uri) { - return Ok(false); + return Ok(true); } } + Ok(false) +} + +/// Removes `ns` from the declarations of element `x`. +fn remove_ns_from(interp: &mut Interp, x: ObjId, ns: &XmlNs) -> JsResult<()> { let list = &mut interp.xml_node_mut(x)?.ns; match &ns.prefix { None => list.retain(|m| m.uri != ns.uri), Some(p) => list.retain(|m| !(m.uri == ns.uri && m.prefix.as_ref() == Some(p))), } - Ok(true) + Ok(()) } fn remove_namespace(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { @@ -942,23 +1030,31 @@ fn remove_namespace(interp: &mut Interp, this: Value, args: &[Value], _: bool) - return Ok(this); } let ns = build_namespace(interp, std::slice::from_ref(&arg(args, 0)))?; - if !remove_ns_from(interp, x, &ns)? { - return Ok(this); - } - let mut stack = vec![(x, 0usize)]; - while let Some(&(node, next)) = stack.last() { - interp.use_fuel()?; - let Some(c) = interp.xml_node(node)?.children.get(next).copied() else { - stack.pop(); - continue; - }; - if let Some(frame) = stack.last_mut() { - frame.1 += 1; + interp.rooted(&[Value::Object(x)], |interp| { + if ns_in_use(interp, x, &ns)? { + return Ok(()); } - if interp.xml_kind(c)? == XmlKind::Element && remove_ns_from(interp, c, &ns)? { - stack.push((c, 0)); + let mut held = HeldBytes::new(interp); + let mut stack = Vec::new(); + push_held(interp, &mut held, &mut stack, (x, 0usize))?; + remove_ns_from(interp, x, &ns)?; + while let Some(&(node, next)) = stack.last() { + interp.use_fuel()?; + let Some(c) = interp.xml_node(node)?.children.get(next).copied() else { + stack.pop(); + continue; + }; + if let Some(frame) = stack.last_mut() { + frame.1 += 1; + } + if interp.xml_kind(c)? != XmlKind::Element || ns_in_use(interp, c, &ns)? { + continue; + } + push_held(interp, &mut held, &mut stack, (c, 0))?; + remove_ns_from(interp, c, &ns)?; } - } + Ok(()) + })?; Ok(this) } @@ -989,6 +1085,9 @@ fn replace(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResul }; let matched = i.xml_select(x, &NameRef { attribute: false, ..n })?; i.xml_keep(matched); + let mut held = HeldBytes::new(i); + let count = i.xml_list(matched)?.items.len(); + held.add(i, count.saturating_mul(size_of::()))?; let items = i.xml_list(matched)?.items.clone(); if items.is_empty() { return Ok(()); @@ -1020,7 +1119,7 @@ fn set_local_name(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> let v = arg(args, 0); let local = match as_qname(interp, &v) { Some((n, _)) => n.local, - None => interp.to_str(&v)?.flat(), + None => str_arg(interp, &v)?, }; checked_local(interp, &local)?; if kind == XmlKind::Attribute diff --git a/crates/js/src/xml_tests.rs b/crates/js/src/xml_tests.rs index f9f66c8c26..0951d4f350 100644 --- a/crates/js/src/xml_tests.rs +++ b/crates/js/src/xml_tests.rs @@ -351,6 +351,10 @@ fn the_xml_methods_behave_as_specified() { "var x = ; x.b[0].inScopeNamespaces().length === 1 && x.namespaceDeclarations()[0].prefix === 'p' && x.b[0].namespaceDeclarations().length === 0", ); truth("var x = ; x.namespace('p').uri === 'u' && x.namespace('q') === undefined && x.namespace().uri === ''"); + truth( + "var x = ; var c = x.b.c[0]; var s = c.inScopeNamespaces(); var d = x.b[0].namespaceDeclarations(); \ + s.length === 2 && c.namespace('p').uri === 'w' && c.namespace('q').uri === 'v' && c.namespace('z') === undefined && d.length === 1 && d[0].prefix === 'p' && d[0].uri === 'w'", + ); truth("var x = ; x.addNamespace(new Namespace('p', 'u')); x.namespace('p').uri === 'u'"); truth("var x = ; x.removeNamespace(new Namespace('p', 'u')); x.namespace('p') === undefined"); truth("var x = ; x.removeNamespace(new Namespace('p', 'u')); x.namespace('p').uri === 'u'"); @@ -1243,7 +1247,12 @@ fn comparing_xml_values_is_charged_to_the_heap() { /// Runs `setup` with no limit, then `action` in the same realm, and returns how `action` ended. fn after_setup(setup: &str, action: &str) -> Result { - let mut r = realm(); + after_setup_with(e4x(), setup, action) +} + +/// [`after_setup`] in a realm with `options`. +fn after_setup_with(options: Options, setup: &str, action: &str) -> Result { + let mut r = Realm::with_options(options, Limits::default()); let interp = r.interp(); let global = interp.global; assert!(crate::builtins::method(interp, global, "squeeze", squeeze, 1).is_ok()); @@ -1267,6 +1276,135 @@ fn namespace_declarations_and_qname_strings_are_charged_to_the_heap() { assert_eq!(after_setup(long, action), heap); } +#[test] +fn namespace_scopes_are_charged_to_the_heap() { + let heap = Err(RunErrorKind::Limit(LimitKind::Heap)); + let setup = "var x = ; for (var i = 0; i < 2000; i++) x.addNamespace(new Namespace('p' + i, 'u' + i)); \ + var b = x.b[0]; b.c[0].setNamespace(new Namespace('u7'));"; + for (action, ample) in [ + ("b.namespace('p1999').uri", JsValue::String("u1999".into())), + ("b.namespaceDeclarations().length", JsValue::Number(0.0)), + ("b.inScopeNamespaces().length", JsValue::Number(2000.0)), + ("x.xpath('b[namespace::p1999]').length()", JsValue::Number(1.0)), + ("b.xpath('p5:c').length()", JsValue::Number(0.0)), + ("b.xpath(\"*[name() = 'p7:c']\").length()", JsValue::Number(1.0)), + ] { + assert_eq!(after_setup(setup, &format!("squeeze(16384); {action}")), heap, "{action}"); + assert_eq!(after_setup(setup, action), Ok(ample.clone()), "{action}"); + // The scope reads the same bindings after the script has left garbage to collect. + let churn = format!("squeeze(2000000); for (var i = 0; i < 3000; i++) [i]; {action}"); + assert_eq!(after_setup(setup, &churn), Ok(ample), "{action}"); + } +} + +#[test] +fn namespace_edits_read_attributes_in_place_and_charge_their_walk() { + let heap = Err(RunErrorKind::Limit(LimitKind::Heap)); + let wide = "var s = ''); \ + var n = new Namespace('q', 'v'); var m = new Namespace('s', 'w');"; + let deep = "var s = ''; for (var i = 0; i < 2000; i++) s += ''; for (var i = 0; i < 2000; i++) s += ''; \ + var x = new XML(s + ''); var n = new Namespace('q', 'v');"; + let removed = "x.removeNamespace(n); x.namespace('q') === undefined"; + // An element's attributes are read where they are, so 4,000 of them need no room; the walk of a + // deep tree is held against the limit. + for (tree, setup, action, ample, squeezed) in [ + ("wide", wide, "x.addNamespace(m); x.namespace('s').uri", JsValue::String("w".into()), false), + ("wide", wide, removed, JsValue::Bool(true), false), + ("deep", deep, removed, JsValue::Bool(true), true), + ] { + let options = Options { max_depth: 1_000_000, ..e4x() }; + let want = if squeezed { heap.clone() } else { Ok(ample.clone()) }; + assert_eq!(after_setup_with(options.clone(), setup, &format!("squeeze(4096); {action}")), want, "{tree}: {action}"); + assert_eq!(after_setup_with(options, setup, action), Ok(ample), "{tree}: {action}"); + } +} + +#[test] +fn xml_list_methods_charge_their_copies_to_the_heap() { + let heap = Err(RunErrorKind::Limit(LimitKind::Heap)); + let setup = "var x = ; for (var i = 0; i < 4000; i++) x.appendChild(); var l = x.a;"; + for (action, ample) in [ + ("l.child(0).length()", JsValue::Number(0.0)), + ("l.comments().length()", JsValue::Number(0.0)), + ("l.normalize().length()", JsValue::Number(4000.0)), + ] { + assert_eq!(after_setup(setup, &format!("squeeze(4096); {action}")), heap, "{action}"); + assert_eq!(after_setup(setup, action), Ok(ample), "{action}"); + } +} + +/// The least spare heap, found by bisection, at which `action` ends without the heap limit after +/// `setup`. +fn least_spare(setup: &str, action: &str) -> usize { + let (mut lo, mut hi) = (0usize, 1usize << 22); + assert!(after_setup(setup, &format!("squeeze({hi}); {action}")).is_ok(), "{action}"); + while lo < hi { + let mid = lo + (hi - lo) / 2; + match after_setup(setup, &format!("squeeze({mid}); {action}")) { + Ok(_) => hi = mid, + Err(RunErrorKind::Limit(LimitKind::Heap)) => lo = mid + 1, + Err(e) => panic!("{action}: {e:?}"), + } + } + lo +} + +#[test] +fn replace_charges_its_copy_of_the_matches_to_the_heap() { + let setup = "var x = ; for (var i = 0; i < 4000; i++) x.appendChild();"; + let action = "x.replace('a', 'z'); x.children().length()"; + let select = least_spare(setup, "x.a.length()"); + let replace = least_spare(setup, action); + assert!(replace >= select + 4000 * 4, "select {select}, replace {replace}"); + assert_eq!(after_setup(setup, action), Ok(JsValue::Number(1.0))); +} + +#[test] +fn xpath_qualified_names_are_charged_to_the_heap() { + let setup = "var s = 'a'; for (var i = 0; i < 14; i++) s += s; var x = ; var c = x.c[0]; \ + c.setLocalName(s); c.setNamespace(new Namespace('u'));"; + let action = "x.xpath('*[string-length(name()) = 16386]').length()"; + assert_eq!(after_setup(setup, &format!("squeeze(16384); {action}")), Err(RunErrorKind::Limit(LimitKind::Heap))); + assert_eq!(after_setup(setup, action), Ok(JsValue::Number(1.0))); +} + +#[test] +fn xml_methods_charge_the_strings_they_flatten() { + let heap = Err(RunErrorKind::Limit(LimitKind::Heap)); + // `s` and `t` are ropes of 32,768 and 49,152 units; `f` is a flat string that starts with `@`. + let setup = "var s = 'a'; for (var i = 0; i < 15; i++) s += s; var t = 'a b'; for (var i = 0; i < 14; i++) t += t; \ + var f = '@' + s; isXMLName(f); var x = ; var c = x.c[0];"; + let mut wrong = Vec::new(); + for (action, ample) in [ + ("x.addNamespace(s); 1", JsValue::Number(1.0)), + ("new Namespace(t, 'u').prefix", JsValue::Undefined), + ("c.setName(s); 1", JsValue::Number(1.0)), + ("isXMLName(s)", JsValue::Bool(true)), + ("x.attribute(s).length()", JsValue::Number(0.0)), + ("x.attribute(f).length()", JsValue::Number(0.0)), + ("x.namespace(s) === undefined", JsValue::Bool(true)), + ("x.propertyIsEnumerable(s)", JsValue::Bool(false)), + ("c.setLocalName(s); 1", JsValue::Number(1.0)), + ] { + let squeezed = after_setup(setup, &format!("squeeze(16384); {action}")); + if squeezed != heap { + wrong.push(format!("{action} with 16384 spare: {squeezed:?}")); + } + assert_eq!(after_setup(setup, action), Ok(ample), "{action}"); + } + // Parsing a rope needs room for its flat copy on top of what parsing the same flat text needs. + let text = "var k = 'x'; for (var i = 0; i < 15; i++) k += k; var s = ''; \ + var g = ''; isXMLName(g);"; + for ctor in ["XML", "XMLList"] { + let rope = least_spare(text, &format!("new {ctor}(s); 1")); + let flat = least_spare(text, &format!("new {ctor}(g); 1")); + if rope < flat + 32768 { + wrong.push(format!("new {ctor} needs {rope} spare for a rope and {flat} for flat text")); + } + } + assert!(wrong.is_empty(), "{wrong:#?}"); +} + #[test] fn an_interrupt_stops_serialization() { let mut r = realm(); diff --git a/crates/js/src/xpath.rs b/crates/js/src/xpath.rs index 30707e4de0..6ff84f1508 100644 --- a/crates/js/src/xpath.rs +++ b/crates/js/src/xpath.rs @@ -1472,13 +1472,14 @@ impl<'p> Ev<'p> { let xml = key("xml"); let mut at = 0u32; let mut has_xml = false; - for ns in scope_of(interp, Some(*x))? { - let Some(prefix) = ns.prefix else { continue }; + let scope = scope_of(interp, Some(*x))?; + for ns in &scope.list { + let Some(prefix) = ns.prefix.clone() else { continue }; if prefix.is_empty() && ns.uri.is_empty() { continue; } has_xml |= prefix == xml; - self.add(interp, out, axis, test, XNode::Ns { owner: *x, at, prefix, uri: ns.uri })?; + self.add(interp, out, axis, test, XNode::Ns { owner: *x, at, prefix, uri: ns.uri.clone() })?; at += 1; } if !has_xml { @@ -1867,7 +1868,7 @@ impl<'p> Ev<'p> { prefix } } - Some(XNode::Node(x)) => node_name(interp, f, x)?, + Some(XNode::Node(x)) => return node_name(interp, f, x), }; Ok(Text::plain(interp, units)) } @@ -2179,7 +2180,7 @@ impl<'p> Ev<'p> { let uri = if units_are(p, "xml") { key(XML_URI) } else { - match scope.iter().find(|ns| ns.prefix.as_ref() == Some(p)) { + match scope.list.iter().find(|ns| ns.prefix.as_ref() == Some(p)) { Some(ns) if !ns.uri.is_empty() => ns.uri.clone(), _ => { let shown = String::from_utf16_lossy(p); @@ -2213,24 +2214,26 @@ impl<'p> Ev<'p> { } } -fn node_name(interp: &mut Interp, f: Func, x: ObjId) -> JsResult { +fn node_name(interp: &mut Interp, f: Func, x: ObjId) -> JsResult { let node = interp.xml_node(x)?; let (kind, parent) = (node.kind, node.parent); - let Some(name) = node.name.clone() else { return Ok(empty()) }; - match (f, kind) { - (_, XmlKind::Text | XmlKind::Comment) => Ok(empty()), - (Func::NamespaceUri, XmlKind::Pi) => Ok(empty()), - (Func::NamespaceUri, _) => Ok(Rc::from(name_uri(&name))), - (Func::LocalName, _) | (_, XmlKind::Pi) => Ok(name.local), - _ => qualified_name(interp, x, parent, &name, kind == XmlKind::Attribute), - } + let Some(name) = node.name.clone() else { return Ok(Text::plain(interp, empty())) }; + let units = match (f, kind) { + (_, XmlKind::Text | XmlKind::Comment) => empty(), + (Func::NamespaceUri, XmlKind::Pi) => empty(), + (Func::NamespaceUri, _) => Rc::from(name_uri(&name)), + (Func::LocalName, _) | (_, XmlKind::Pi) => name.local, + _ => return qualified_name(interp, x, parent, &name, kind == XmlKind::Attribute), + }; + Ok(Text::plain(interp, units)) } -/// An element's or attribute's name as a QName, with a prefix declared for its namespace. -fn qualified_name(interp: &mut Interp, x: ObjId, parent: Option, name: &XmlName, attribute: bool) -> JsResult { +/// An element's or attribute's name as a QName, with a prefix declared for its namespace. The units +/// of a prefixed name are held against the heap limit while the text lives. +fn qualified_name(interp: &mut Interp, x: ObjId, parent: Option, name: &XmlName, attribute: bool) -> JsResult { let uri = name_uri(name); if uri.is_empty() { - return Ok(name.local.clone()); + return Ok(Text::plain(interp, name.local.clone())); } let prefix = if units_are(uri, XML_URI) { key("xml") @@ -2240,17 +2243,18 @@ fn qualified_name(interp: &mut Interp, x: ObjId, parent: Option, name: &X _ => { let scope = scope_of(interp, if attribute { parent } else { Some(x) })?; let usable = |ns: &XmlNs| *ns.uri == *uri && ns.prefix.as_ref().is_some_and(|p| !(attribute && p.is_empty())); - scope.into_iter().find(usable).and_then(|ns| ns.prefix).unwrap_or_else(empty) + scope.list.iter().find(|ns| usable(ns)).and_then(|ns| ns.prefix.clone()).unwrap_or_else(empty) } } }; if prefix.is_empty() { - return Ok(name.local.clone()); + return Ok(Text::plain(interp, name.local.clone())); } - let mut units = prefix.to_vec(); - units.push(COLON); - units.extend_from_slice(&name.local); - Ok(Rc::from(units)) + let mut buf = TextBuf::new(interp); + buf.push(interp, &prefix)?; + buf.push(interp, &[COLON])?; + buf.push(interp, &name.local)?; + Ok(buf.finish()) } /// The first index where `needle` occurs in `hay`. Every position tried takes fuel. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f04ee3c910..5d9c387e03 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -811,6 +811,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - `vectorcraft-js` has `String`, `Number`, `RegExp` and `Date` as ECMAScript 5.1 defines them (sections 15.5, 15.7, 15.9 and 15.10, https://262.ecma-international.org/5.1/), with Annex B's `substr`, `getYear`, `setYear` and `toGMTString`. `toFixed`, `toExponential` and `toPrecision` format a number from its exact decimal value, and `toString(radix)` writes any base from 2 to 36. Regular expressions (flags `g`, `i` and `m`) run on a backtracking matcher whose choice points and capture state count against the heap limit and which takes fuel for every step, so a catastrophic pattern stops at the fuel limit and 50,000 nested groups give a `SyntaxError` at the default depth limit. A string method that would build a string past the heap limit stops before it allocates. `Date` reads the clock and time zone the host sets (`Realm::set_clock`, `Realm::set_time_zone`; local time is UTC by default). `cargo xtask test262` runs the suite's `built-ins` tests for the four (https://github.com/tc39/test262): of the runs of the ES5 tests that need only the built-ins present, 1,379 of 1,411 pass for `String`, 298 of 298 for `Number`, 954 of 988 for `RegExp` and 8 of 8 for `Date`. The others expect later editions' rules (built-in functions whose `length` can be deleted, flags given with a RegExp object, a negative `lastIndex`, `RegExp.prototype` as a plain object, and `RegExp.prototype`'s `global`, `ignoreCase` and `multiline` properties that can be deleted). Tests: `crates/js/src/text_tests.rs`, `crates/js/tests/test262.rs`. - With `Options::e4x` set, an E4X name standing alone (`@a`, `@ns::a`, `@[expr]`, `ns::a`, `*`) inside `with` or a filter predicate can be assigned, with `=` or a compound operator, incremented, decremented, deleted and used as a `for` or `for each` variable, as well as read. Each of these uses the nearest XML or XMLList value in scope that holds the name and evaluates the name once. When no XML value in scope holds the name, the read or write throws a `ReferenceError` before the right-hand side runs and creates no child or attribute, as ECMA-357 section 11.1 (https://ecma-international.org/publications-and-standards/standards/ecma-357/) specifies, so a filter such as `list.(@id == '1')` throws when an item has no `@id` and no outer XML value holds one. Tests: `crates/js/src/xml_tests.rs`. - `vectorcraft-js` runs ECMAScript for XML (ECMA-357, 2nd edition, https://ecma-international.org/publications-and-standards/standards/ecma-357/) when `Options::e4x` is set, which it is not by default: XML and XMLList literals with embedded `{}` expressions, the `..`, `.@`, `.*`, `.()` and `::` selectors, assignment and `delete` on selected nodes, `for each`, `default xml namespace`, and the `XML`, `XMLList`, `Namespace` and `QName` objects with their methods and settings. `xml.xpath(expression[, variables])` evaluates an XPath 1.0 expression (https://www.w3.org/TR/1999/REC-xpath-19991116/) with all 13 axes and the 27 core functions, and returns the selected nodes as an XMLList in document order without repeats. Each property of `variables` binds the variable of its name, an XMLList runs the expression on each of its elements in turn, and a prefix in a name test resolves through the context element's in-scope namespaces. An expression that breaks the grammar gives a `SyntaxError`; an unknown function, a wrong argument count, an unbound prefix or variable, and a result that is not a node-set or that holds the root or a namespace node give a `TypeError`. `id()` selects nothing, and evaluation uses no native stack, takes fuel and counts against the heap limit. `` in an XML string gives a `SyntaxError`. An XML declaration at the start of an XML string, after optional white space, is checked against XML 1.0's grammar (https://www.w3.org/TR/xml/#NT-XMLDecl): a version of `1.` and digits, then an optional encoding name and an optional standalone `yes` or `no`, in that order; any other declaration, or one with a character XML does not allow, gives a `SyntaxError`. The parser takes fuel for the length of every name, white space run and declaration it scans, and for the text it searched when a quote, CDATA section, comment or processing instruction is not closed. Parsing, serializing, comparing and copying trees use no native stack, and each takes fuel and counts against the heap limit. Inserting a node into itself or its descendants throws a `TypeError` before the tree changes, a literal or XML string nested past `Options::max_depth` gives a `SyntaxError`, and a tree built past that depth stops at the heap limit. Tests: `crates/js/src/xml_tests.rs`. + - Scripts: `inScopeNamespaces()`, `namespace()`, `namespaceDeclarations()`, the XPath `namespace` axis, prefixes in an XPath expression and the qualified names `name()` gives count the namespaces they collect from a node and its ancestors against the heap limit, so a node with many namespaces in scope stops the script at the heap limit instead of growing past it. `addNamespace()`, `setNamespace()`, `setName()` and `removeNamespace()` read an element's attributes in place instead of copying them, and `removeNamespace()` counts its walk of the tree; `child()` by index, `comments()`, `text()`, `elements()`, `processingInstructions()` and `normalize()` on an XMLList count their copy of its items; `replace()` counts its copy of the children it matched; and `name()` counts the prefixed name it builds. The `XML`, `XMLList`, `Namespace` and `QName` constructors, `isXMLName()`, `attribute()`, `namespace()`, `propertyIsEnumerable()`, `setName()`, `setLocalName()`, `addNamespace()`, `removeNamespace()` and `setNamespace()` count the copy they make when they flatten a long string argument, and `QName.prototype.toString()` counts its result before it builds it. Tests: `crates/js/src/xml_tests.rs`. - **UI:** Illustrator 2026 layout restyled to measured values: - Medium Dark theme, categorized and Advanced toolbars (a tool group's flyout opens on a right press, a long press or a press on its corner triangle), 35 pt document tabs, 33 pt panel tabs. - Hint bar, contextual task bar, 19 dock panels with ≡ menus. From fb41d79f28ae9cd22852f371f4079b2c4ae8053b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 06:07:27 -0800 Subject: [PATCH 07/25] Layers: ruler guide rows have their own eye and lock, and go to the trash The eye and lock on a guide's row in the Layers panel hide or lock that guide alone, in one undo step, and a drag down either column takes guide rows along with the other rows it passes. A hidden guide is not drawn and does not snap, and its row is dimmed; a locked guide is drawn and snaps but can't be selected, moved or deleted. Both can be changed while the guide's layer is hidden or locked, and the guide shows or can be edited only when its layer allows it as well. The state is kept through save and reopen. - layer.setProps takes ruler guide node ids; every other command still refuses them. - guide.list rows carry the guide's node id and its own hidden and locked state. - Alt-click and Ctrl/Cmd+Alt-click on a guide row's eye or lock act on the other layers, as on any row in that layer. - Object > Lock > Selection and Object > Hide > Selection lock or hide the selected ruler guides with the selected art, in one undo step, outside isolation mode. Unlock All and Show All, document scope, also unlock or show guides locked or hidden on their own and select them as guides. - Guide rows dropped on the Layers panel's trash delete their guides (guide.remove {indexes}). A click on a guide row clears the highlighted rows, so Delete deletes the guide; with no row highlighted the trash deletes the selected guides. - guide.remove and guide.setLayer refuse index together with indexes and an indexes value that is not a list, and count a repeated index once. guide.select, guide.remove and guide.setLayer refuse an indexes list of more than 10,000 entries; guide.setLayer cut such a list short before. - Moving, deleting or moving to another layer a guide that is hidden or locked on its own fails with "the guide is hidden or locked"; a guide on a hidden or locked layer still fails with "the guide is on a hidden or locked layer". Docs: docs/mcp.md, docs/target-app-parity.md, docs/ui-parity.md. --- crates/engine/src/cmd.rs | 33 +++- crates/engine/src/cmd/docmenu.rs | 73 ++++++--- crates/engine/src/cmd/layer.rs | 18 ++- crates/engine/src/cmd/object/arrange.rs | 37 +++-- crates/engine/src/cmd/object/commands.rs | 14 +- crates/engine/src/command_sets.rs | 5 + crates/engine/src/session.rs | 2 +- crates/engine/src/session/execute.rs | 9 +- crates/engine/src/tests/menucmds.rs | 140 ++++++++++++++++- crates/engine/src/tests/save.rs | 26 ++++ crates/engine/tests/it/ruler_guide_nodes.rs | 6 +- crates/ui-egui/src/panels/layers.rs | 20 ++- crates/ui-egui/src/panels/layers/controls.rs | 24 ++- crates/ui-egui/src/panels/layers/model.rs | 20 ++- crates/ui-egui/src/panels/layers/rows.rs | 36 ++++- crates/ui-egui/src/panels/layers/tests.rs | 152 +++++++++++++++++++ docs/mcp.md | 27 +++- docs/target-app-parity.md | 2 +- docs/ui-parity.md | 2 +- 19 files changed, 553 insertions(+), 93 deletions(-) diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 80ed19d145..1257039bf0 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -245,6 +245,12 @@ pub fn has_selected_member(s: &Session) -> std::result::Result<(), String> { let Some(root) = ordinary_isolation(st) else { return has_selection(s) }; if st.selection.objects.iter().any(|id| inside_isolation(&st.doc, root, *id)) { Ok(()) } else { Err("nothing selected".into()) } } +/// [`has_selected_member`], or a ruler guide is selected outside isolation mode: Object › Lock › +/// Selection and Object › Hide › Selection. +pub fn has_selected_member_or_guide(s: &Session) -> std::result::Result<(), String> { + let st = s.active().ok_or("no document open")?; + if ordinary_isolation(st).is_none() && !st.selection.guides.is_empty() { Ok(()) } else { has_selected_member(s) } +} /// Whether `id` lies inside the isolated object `root` (the root itself does not). pub(crate) fn inside_isolation(d: &vectorcraft_doc::Document, root: vectorcraft_doc::NodeId, id: vectorcraft_doc::NodeId) -> bool { id != root && d.ancestry(id).is_some_and(|a| a.contains(&root)) @@ -506,8 +512,13 @@ fn id_entry(value: &Value, key: &str, index: usize, cmd: &str) -> Result /// them), each checked ([`checked_id`]): a malformed one, or one naming no object, is an error, /// never the selection. `None` when it gives neither (or gives them as `null`). pub(crate) fn given_objects(s: &Session, p: &Value, command: &str) -> Result>> { + given_nodes(s, p, command, false) +} +/// The nodes `p` gives `command`, as [`given_objects`] reads them; ruler guide nodes are taken +/// too when `guides`, else refused. +pub(crate) fn given_nodes(s: &Session, p: &Value, command: &str, guides: bool) -> Result>> { if p.get("ids").is_some_and(|v| !v.is_null()) { - return checked_ids_param(s, p, "ids", command).map(Some); + return checked_nodes_param(s, p, "ids", command, guides).map(Some); } match p.get("id").filter(|v| !v.is_null()) { None => Ok(None), @@ -515,7 +526,7 @@ pub(crate) fn given_objects(s: &Session, p: &Value, command: &str) -> Result { Err(bad(command, format!("`id` is the step reference {r:?}, which only `run` and `command_batch` resolve"))) } - Some(v) => Ok(Some(vec![checked_id(s, v, command)?])), + Some(v) => Ok(Some(vec![checked_node(s, v, command, guides)?])), } } /// The objects `p` gives `command`, as [`given_objects`] reads them, checked only for their form: @@ -541,9 +552,18 @@ pub(crate) fn index(v: u64) -> usize { } /// Validate all explicit targets before a command changes the document or selection. pub(crate) fn checked_ids_param(s: &Session, p: &Value, key: &str, command: &str) -> Result> { + checked_nodes_param(s, p, key, command, false) +} +/// The `key` list as [`checked_ids_param`] checks it; ruler guide nodes are taken too when +/// `guides`, else refused. +pub(crate) fn checked_nodes_param(s: &Session, p: &Value, key: &str, command: &str, guides: bool) -> Result> { let values = p.get(key).and_then(Value::as_array).ok_or_else(|| bad(command, format!("{key} must be an array of non-negative integer object ids")))?; - values.iter().enumerate().map(|(index, value)| id_entry(value, key, index, command).and_then(|_| checked_id(s, value, command))).collect() + values + .iter() + .enumerate() + .map(|(index, value)| id_entry(value, key, index, command).and_then(|_| checked_node(s, value, command, guides))) + .collect() } /// The objects a command acts on: `ids` when given (every one checked, and those inside another @@ -557,11 +577,16 @@ pub(crate) fn checked_ids_or_selection(s: &Session, p: &Value, command: &str) -> } pub(crate) fn checked_id(s: &Session, value: &Value, command: &str) -> Result { + checked_node(s, value, command, false) +} +/// `value` as the id of a node of the active document; a ruler guide's is taken only when +/// `guides`. +pub(crate) fn checked_node(s: &Session, value: &Value, command: &str, guides: bool) -> Result { let id = value.as_u64().map(NodeId).ok_or_else(|| bad(command, format!("invalid object id {value}: expected a non-negative integer")))?; match s.doc()?.doc.node(id) { None => Err(bad(command, format!("no such object id {value}"))), // The guide commands take ruler guides by index. - Some(n) if n.is_ruler_guide() => Err(bad(command, format!("id {value} is a ruler guide, not an object"))), + Some(n) if n.is_ruler_guide() && !guides => Err(bad(command, format!("id {value} is a ruler guide, not an object"))), Some(_) => Ok(id), } } diff --git a/crates/engine/src/cmd/docmenu.rs b/crates/engine/src/cmd/docmenu.rs index ae3fc521f0..ae48ba02e6 100644 --- a/crates/engine/src/cmd/docmenu.rs +++ b/crates/engine/src/cmd/docmenu.rs @@ -210,7 +210,7 @@ pub fn specs() -> Vec { "Guides", [], None, - "{} → [{index, vertical, pos, selected, artboard?: index (an artboard guide's), layer?: id (the layer it is on), shown, editable (its layer shown and unlocked)}…] the ruler guides", + "{} → [{index, id (its node, which `layer.setProps` hides or locks on its own), vertical, pos, selected, artboard?: index (an artboard guide's), layer?: id (the layer it is on), hidden, locked (its own visibility and lock), shown, editable (it and its layer shown and unlocked)}…] the ruler guides", has_doc, guide_list ), @@ -219,7 +219,7 @@ pub fn specs() -> Vec { "Select Guides", [], None, - "{indexes: [index…], toggle?: bool} select ruler guides on their own (deselecting the art); toggle adds or removes them instead, keeping the selected art (a Shift-click on a guide) → {selected: [index…]}", + "{indexes: [index…] (at most 10,000), toggle?: bool} select ruler guides on their own (deselecting the art); toggle adds or removes them instead, keeping the selected art (a Shift-click on a guide) → {selected: [index…]}", guides_unlocked, guide_select ), @@ -228,7 +228,7 @@ pub fn specs() -> Vec { "Remove Guide", [], None, - "{index?} delete ruler guide `index`, else the selected ones (as Delete / edit.clear does) → {count}", + "{index?, indexes?: [index…] (at most 10,000)} delete ruler guide `index` (or guides `indexes`, as dragging their rows onto the Layers panel's trash does), else the selected ones (as Delete / edit.clear does), in one undo step; give `index` or `indexes`, not both, and an index given twice counts once; a hidden or locked guide, or one on a hidden or locked layer, is an error → {count}", guides_unlocked, guide_remove ), @@ -246,7 +246,7 @@ pub fn specs() -> Vec { "Move Guide to Layer", [], None, - "{index?, indexes?: [index…], layer: id} put ruler guide `index` (or guides `indexes`), else the selected guides, on layer `layer` (a layer or sublayer), as dragging their rows onto that layer's row in the Layers panel does → {count}", + "{index?, indexes?: [index…] (at most 10,000), layer: id} put ruler guide `index` (or guides `indexes`), else the selected guides, on layer `layer` (a layer or sublayer), as dragging their rows onto that layer's row in the Layers panel does; give `index` or `indexes`, not both, and an index given twice counts once → {count}", guides_unlocked, guide_set_layer ), @@ -805,12 +805,17 @@ fn guide_list(s: &mut Session, _: &Value) -> Result { let row = |(i, g): (usize, &Guide)| { let selected = g.id.is_some_and(|id| st.selection.guides.contains(&id)); let mut r = json!({ "index": i, "vertical": g.vertical, "pos": g.pos, "selected": selected }); + if let Some(id) = g.id { + r["id"] = json!(id.0); + } if let Some(ab) = st.doc.artboards.iter().position(|a| Some(a.id) == g.artboard) { r["artboard"] = json!(ab); } if let Some(l) = g.layer { r["layer"] = json!(l.0); } + r["hidden"] = json!(g.hidden); + r["locked"] = json!(g.locked); r["shown"] = json!(st.doc.guide_shown(g)); r["editable"] = json!(st.doc.guide_editable(g)); r @@ -824,27 +829,44 @@ fn guide_index_in(ids: &[NodeId], v: Option<&Value>, cmd: &str) -> Result(v: &'a Value, cmd: &str) -> Result<&'a Vec> { + let list = v.as_array().ok_or_else(|| bad(cmd, "indexes must be an array of guide indexes"))?; + if list.len() > MAX_GUIDE_INDEXES { + return Err(bad(cmd, format!("indexes may hold at most {MAX_GUIDE_INDEXES} entries"))); + } + Ok(list) +} + /// The id of ruler guide `index` of the active document (`index` validated). fn guide_index(s: &Session, v: Option<&Value>, cmd: &str) -> Result { guide_index_in(&guide_ids(&s.doc()?.doc), v, cmd) } -/// Is ruler guide `id` one that can be moved or deleted: not on a hidden or locked layer? +/// Is ruler guide `id` one that can be moved or deleted: not hidden or locked itself, nor on a +/// hidden or locked layer? fn check_editable_guide(s: &Session, id: NodeId) -> Result { let d = &s.doc()?.doc; - if !d.ruler_guide(id).is_some_and(|g| d.guide_editable(&g)) { + let guide = d.ruler_guide(id); + if guide.as_ref().is_some_and(|g| g.hidden || g.locked) { + return Err(EngineError::Other("the guide is hidden or locked".into())); + } + if !guide.is_some_and(|g| d.guide_editable(&g)) { return Err(EngineError::Other("the guide is on a hidden or locked layer".into())); } Ok(id) } -/// [`guide_index`] of a guide that can be moved or deleted: not on a hidden or locked layer. +/// [`guide_index`] of a guide that can be moved or deleted ([`check_editable_guide`]). fn editable_guide_index(s: &Session, v: Option<&Value>, cmd: &str) -> Result { check_editable_guide(s, guide_index(s, v, cmd)?) } fn guide_select(s: &mut Session, p: &Value) -> Result { - let list = p.get("indexes").and_then(Value::as_array).ok_or_else(|| bad("guide.select", "missing indexes"))?; + let list = guide_index_list(p.get("indexes").ok_or_else(|| bad("guide.select", "missing indexes"))?, "guide.select")?; let ids = guide_ids(&s.doc()?.doc); let picked = list.iter().map(|v| guide_index_in(&ids, Some(v), "guide.select")).collect::>>()?; if switch_or(p, "toggle", false, "guide.select")? { @@ -861,18 +883,30 @@ fn guide_select(s: &mut Session, p: &Value) -> Result { Ok(json!({ "selected": guide_indexes(&st.doc, &st.selection.guides) })) } -/// Delete ruler guide `index`, else the selected guides, in one undo step → {count}. +/// Delete ruler guide `index` (or guides `indexes`), else the selected guides, in one undo step +/// → {count}. pub(crate) fn guide_remove(s: &mut Session, p: &Value) -> Result { - let gone: Vec = match p.get("index") { - Some(v) => vec![editable_guide_index(s, Some(v), "guide.remove")?], - None => s.doc()?.selection.guides.clone(), + const C: &str = "guide.remove"; + let mut gone: Vec = match (p.get("index"), p.get("indexes")) { + (Some(_), Some(_)) => return Err(bad(C, "give index or indexes, not both")), + (Some(v), None) => vec![editable_guide_index(s, Some(v), C)?], + (None, Some(list)) => { + let list = guide_index_list(list, C)?; + let ids = guide_ids(&s.doc()?.doc); + // A set, so an index given twice deletes its guide once and the ids held never outnumber the guides. + let set = list.iter().map(|v| check_editable_guide(s, guide_index_in(&ids, Some(v), C)?)).collect::>>()?; + set.into_iter().collect() + } + (None, None) => s.doc()?.selection.guides.clone(), }; + gone.sort_unstable(); + gone.dedup(); if gone.is_empty() { - return Err(bad("guide.remove", "no guide selected")); + return Err(bad(C, "no guide selected")); } let label = if gone.len() == 1 { "Delete Guide" } else { "Delete Guides" }; s.edit(label, |d, sel| { - d.retain_guides(sel, |g| !g.id.is_some_and(|id| gone.contains(&id))); + d.retain_guides(sel, |g| !g.id.is_some_and(|id| gone.binary_search(&id).is_ok())); Ok(()) })?; Ok(json!({ "count": gone.len() })) @@ -888,14 +922,19 @@ fn guide_set_layer(s: &mut Session, p: &Value) -> Result { if super::layer::locked_within(d, layer) { return Err(EngineError::Other("the layer or group is locked".into())); } - let moving: Vec = match (p.get("index"), p.get("indexes").and_then(Value::as_array)) { - (Some(v), _) => vec![editable_guide_index(s, Some(v), C)?], + let mut moving: Vec = match (p.get("index"), p.get("indexes")) { + (Some(_), Some(_)) => return Err(bad(C, "give index or indexes, not both")), + (Some(v), None) => vec![editable_guide_index(s, Some(v), C)?], (None, Some(list)) => { + let list = guide_index_list(list, C)?; let ids = guide_ids(&s.doc()?.doc); - list.iter().take(10_000).map(|v| check_editable_guide(s, guide_index_in(&ids, Some(v), C)?)).collect::>>()? + list.iter().map(|v| check_editable_guide(s, guide_index_in(&ids, Some(v), C)?)).collect::>>()? } (None, None) => s.doc()?.selection.guides.clone(), }; + // An index given twice moves (and counts) its guide once; the others keep their order. + let mut seen = HashSet::new(); + moving.retain(|id| seen.insert(*id)); if moving.is_empty() { return Err(bad(C, "no guide selected (or give an index)")); } diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index f816ec7688..f589ea62da 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -14,8 +14,8 @@ use vectorcraft_doc::{Artboard, ArtboardSide, Document, LAYER_COLORS, LayerColor use vectorcraft_geom::{Affine, Rect}; use super::{ - CommandSpec, Result, Session, bad, bool_or, check_numbers, check_switches, checked_id, checked_ids_param, cmd, color_value, f64_or, has_doc, - has_selection, ids_param, index, object_param, ok, str_param, switch_or, + CommandSpec, Result, Session, bad, bool_or, check_numbers, check_switches, checked_id, checked_ids_param, checked_node, checked_nodes_param, cmd, + color_value, f64_or, has_doc, has_selection, ids_param, index, object_param, ok, str_param, switch_or, }; use crate::EngineError; @@ -83,7 +83,7 @@ pub fn specs() -> Vec { "Layer Options…", ["Window", "Layers"], None, - "{ids?|id? (default: the highlighted rows, else the current layer), name? (with prefs.identifyObjectsBy xmlId: a valid XML ID, stored as the object name), visible?, locked?, template?, printable?, preview?, dimImages?: 0..100|false, color?: index 0..26|\"#rrggbb\"|preset name (a hex color with an alpha part, #rrggbbaa or #rgba, is an error)} Layer Options; rows that are not layers take name, visible and locked. Template on also locks the layer and dims its images to 50% (unless given); off unlocks it and stops dimming. One undo step", + "{ids?|id? (default: the highlighted rows, else the current layer), name? (with prefs.identifyObjectsBy xmlId: a valid XML ID, stored as the object name), visible?, locked?, template?, printable?, preview?, dimImages?: 0..100|false, color?: index 0..26|\"#rrggbb\"|preset name (a hex color with an alpha part, #rrggbbaa or #rgba, is an error)} Layer Options; rows that are not layers take name, visible and locked, and `ids` may name ruler guides (their `guide.list` id), which hide or lock on their own. Template on also locks the layer and dims its images to 50% (unless given); off unlocks it and stops dimming. One undo step", has_doc, set_props ), @@ -210,11 +210,16 @@ pub fn specs() -> Vec { /// The rows a panel command acts on: `ids` or `id`, else the highlighted rows, else the current /// layer (capped at [`MAX_ROWS`]). pub(crate) fn rows_param(s: &Session, p: &Value, command: &str) -> Result> { + rows_or_guides_param(s, p, command, false) +} + +/// The rows [`rows_param`] reads; given ruler guide ids are taken too when `guides`, else refused. +fn rows_or_guides_param(s: &Session, p: &Value, command: &str, guides: bool) -> Result> { // Presence is explicit intent: validate every target before fallback, truncation or edits. let mut ids = if p.get("ids").is_some() { - checked_ids_param(s, p, "ids", command)? + checked_nodes_param(s, p, "ids", command, guides)? } else if let Some(id) = p.get("id") { - vec![checked_id(s, id, command)?] + vec![checked_node(s, id, command, guides)?] } else { let st = s.doc()?; let rows = st.highlighted_rows(); @@ -637,7 +642,8 @@ fn set_props(s: &mut Session, p: &Value) -> Result { const C: &str = "layer.setProps"; let xml_id = s.prefs.identify_objects_by == "xmlId"; check_options(C, p, xml_id)?; - let ids = rows_param(s, p, C)?; + // A ruler guide's row takes visible and locked: its own eye and lock. + let ids = rows_or_guides_param(s, p, C, true)?; if ids.is_empty() { return Err(bad(C, "no rows")); } diff --git a/crates/engine/src/cmd/object/arrange.rs b/crates/engine/src/cmd/object/arrange.rs index ff5b950d03..e460712376 100644 --- a/crates/engine/src/cmd/object/arrange.rs +++ b/crates/engine/src/cmd/object/arrange.rs @@ -169,28 +169,47 @@ pub(super) fn lock(s: &mut Session, _: &Value) -> Result { ok() } -/// The selected objects ([`selected_roots`]) that Lock › Selection and Hide › Selection change: in -/// isolation mode, only those inside the isolated object, where a path of the isolated compound -/// path is an object of its own. +/// The selected objects ([`selected_roots`]) and ruler guides that Lock › Selection and Hide › +/// Selection change: in isolation mode, only the objects inside the isolated object, where a path +/// of the isolated compound path is an object of its own. A guide counts while it can be edited +/// (it and its layer shown and unlocked, and Lock Guides off). fn selected_lock_hide_roots(s: &Session) -> Result> { - match crate::cmd::ordinary_isolation(s.doc()?) { + let st = s.doc()?; + match crate::cmd::ordinary_isolation(st) { Some(root) => crate::cmd::edit::selected_roots_inside(s, root, false), - None => selected_roots(s), + None => { + let mut ids = selected_roots(s)?; + if !s.guides_locked() { + let d = &st.doc; + ids.extend(st.selection.guides.iter().copied().filter(|id| d.ruler_guide(*id).is_some_and(|g| d.guide_editable(&g)))); + } + Ok(ids) + } } } +/// The objects and ruler guides in `d` that `f` picks (layers never). fn collect_flag(d: &Document, f: impl Fn(&Node) -> bool) -> Vec { let mut v = vec![]; d.walk(|n| { - if !n.is_layer() && !n.is_ruler_guide() && f(n) { + if !n.is_layer() && f(n) { v.push(n.id) } }); v } +/// Select what Unlock All or Show All changed (`ids`): the objects, and the ruler guides among +/// them as guides (a guide that still can't be edited is then dropped from the selection). +fn select_changed(d: &Document, sel: &mut vectorcraft_doc::Selection, ids: &[NodeId]) { + let guides: std::collections::HashSet = d.ruler_guides().into_iter().filter_map(|g| g.id).collect(); + let (on_guides, objects): (Vec, Vec) = ids.iter().copied().partition(|id| guides.contains(id)); + sel.set(objects); + sel.guides = on_guides; +} + /// The objects that `f` picks for `object.unlockAll` and `object.showAll` (`cmd`): in the whole -/// document, inside the isolated object in isolation mode, or with `scope: "group"` inside the +/// document (its ruler guides included), inside the isolated object in isolation mode, or with `scope: "group"` inside the /// groups that hold the selected objects (in isolation mode, only the objects of those groups /// that are inside the isolated object). A selected group is the group that holds its own /// members, and the objects of a group inside another such group are taken once. With @@ -253,7 +272,7 @@ pub(super) fn unlock_all(s: &mut Session, p: &Value) -> Result { n.locked = false; } } - sel.set(ids.iter().copied()); + select_changed(d, sel, &ids); Ok(()) })?; Ok(json!({ "count": ids.len() })) @@ -292,7 +311,7 @@ pub(super) fn show_all(s: &mut Session, p: &Value) -> Result { n.visible = true; } } - sel.set(ids.iter().copied()); + select_changed(d, sel, &ids); Ok(()) })?; Ok(json!({ "count": ids.len() })) diff --git a/crates/engine/src/cmd/object/commands.rs b/crates/engine/src/cmd/object/commands.rs index 5c66ec8442..21d6530e53 100644 --- a/crates/engine/src/cmd/object/commands.rs +++ b/crates/engine/src/cmd/object/commands.rs @@ -7,7 +7,7 @@ use super::props::set_props; use super::shape::{expand_shape, set_live_shape}; use super::transform::{move_cmd, nudge, reflect, rotate, scale, shear, transform, transform_again}; use super::{CommandSpec, cmd, has_doc, has_multi, has_selection, has_selection_or_guides}; -use crate::cmd::has_selected_member; +use crate::cmd::has_selected_member_or_guide; pub fn specs() -> Vec { vec![ @@ -151,8 +151,8 @@ pub fn specs() -> Vec { "Selection", ["Object", "Lock"], Some("Cmd+2"), - "{ids?: [id…] (selected first; default: the selection; in isolation mode, only those inside the isolated object)}", - has_selected_member, + "{ids?: [id…] (selected first; default: the selection, selected ruler guides included; in isolation mode, only the objects inside the isolated object)}", + has_selected_member_or_guide, lock ), cmd!( @@ -160,7 +160,7 @@ pub fn specs() -> Vec { "Unlock All", ["Object"], Some("Cmd+Alt+2"), - "{scope?: \"document\"|\"group\" (default document, which in isolation mode is the isolated object; group: only the objects inside the groups that hold the selected objects, a selected group holding its own; the in-window menu item chosen with Shift+Alt)} unlock the locked objects and select them → {count}", + "{scope?: \"document\"|\"group\" (default document, which in isolation mode is the isolated object; group: only the objects inside the groups that hold the selected objects, a selected group holding its own; the in-window menu item chosen with Shift+Alt)} unlock the locked objects and select them; document scope outside isolation mode also unlocks ruler guides locked on their own → {count}", has_doc, unlock_all ), @@ -169,8 +169,8 @@ pub fn specs() -> Vec { "Selection", ["Object", "Hide"], Some("Cmd+3"), - "{ids?: [id…] (selected first; default: the selection; in isolation mode, only those inside the isolated object)}", - has_selected_member, + "{ids?: [id…] (selected first; default: the selection, selected ruler guides included; in isolation mode, only the objects inside the isolated object)}", + has_selected_member_or_guide, hide ), cmd!( @@ -178,7 +178,7 @@ pub fn specs() -> Vec { "Show All", ["Object"], Some("Cmd+Alt+3"), - "{scope?: \"document\"|\"group\" (default document, which in isolation mode is the isolated object; group: only the objects inside the groups that hold the selected objects, a selected group holding its own; the in-window menu item chosen with Shift+Alt)} show the hidden objects and select them → {count}", + "{scope?: \"document\"|\"group\" (default document, which in isolation mode is the isolated object; group: only the objects inside the groups that hold the selected objects, a selected group holding its own; the in-window menu item chosen with Shift+Alt)} show the hidden objects and select them; document scope outside isolation mode also shows ruler guides hidden on their own → {count}", has_doc, show_all ), diff --git a/crates/engine/src/command_sets.rs b/crates/engine/src/command_sets.rs index a17fbaf3f8..2425d437ad 100644 --- a/crates/engine/src/command_sets.rs +++ b/crates/engine/src/command_sets.rs @@ -162,6 +162,11 @@ pub(crate) const SELECTS_GIVEN_IDS: &[&str] = &[ "object.ungroup", ]; +/// Commands whose `ids` (or `id`) may name ruler guide nodes as well as objects: the Layers panel's +/// eye and lock on a guide's row, and a drag down either column that passes guide rows. Every other +/// command given a ruler guide's id refuses it (the guide commands take guides by index). +pub(crate) const TAKES_GUIDE_IDS: &[&str] = &["layer.setProps"]; + /// The non-empty `ids` given to a command whose params description names `ids` as a key (the /// key callers outside the app may pass it, [`cmd::params::takes_key`]), or its `id` as `ids` of /// one when no `ids` are given and the description takes `id` so diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 2c59c5630a..d6af60fee1 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -1,4 +1,4 @@ -use super::command_sets::{JOURNALED_READS, SELECTS_GIVEN_IDS, given_ids, strip_replay_only, waits_for_tool_edit}; +use super::command_sets::{JOURNALED_READS, SELECTS_GIVEN_IDS, TAKES_GUIDE_IDS, given_ids, strip_replay_only, waits_for_tool_edit}; use super::doc_state::DocState; use super::error::{EngineError, Result}; use super::history::NamedStep; diff --git a/crates/engine/src/session/execute.rs b/crates/engine/src/session/execute.rs index 23079fe901..203420d9d2 100644 --- a/crates/engine/src/session/execute.rs +++ b/crates/engine/src/session/execute.rs @@ -1,6 +1,6 @@ use super::{ - CommandSpec, EngineError, JOURNALED_READS, NodeId, Result, SELECTS_GIVEN_IDS, Selection, Session, Value, cmd, find_command, given_ids, guard, - strip_replay_only, waits_for_tool_edit, + CommandSpec, EngineError, JOURNALED_READS, NodeId, Result, SELECTS_GIVEN_IDS, Selection, Session, TAKES_GUIDE_IDS, Value, cmd, find_command, + given_ids, guard, strip_replay_only, waits_for_tool_edit, }; impl Session { @@ -87,7 +87,7 @@ impl Session { if id == "effect.refreshDeferred" { cmd::given_object_ids(params, id)?; } else { - cmd::given_objects(self, params, id)?; + cmd::given_nodes(self, params, id, TAKES_GUIDE_IDS.contains(&id))?; } } if SELECTS_GIVEN_IDS.contains(&id) { @@ -106,7 +106,8 @@ impl Session { // whichever tool is chosen. let given = given_ids(spec.params, params); // The guide commands take ruler guides by index; an object command given one's id is refused. - if let (Some(ids), Some(st)) = (&given, self.active()) + if !TAKES_GUIDE_IDS.contains(&id) + && let (Some(ids), Some(st)) = (&given, self.active()) && let Some(guide) = ids.iter().find(|i| st.doc.node(**i).is_some_and(|n| n.is_ruler_guide())) { let value = guide.0; diff --git a/crates/engine/src/tests/menucmds.rs b/crates/engine/src/tests/menucmds.rs index 44a0ddde1b..abb0bf31eb 100644 --- a/crates/engine/src/tests/menucmds.rs +++ b/crates/engine/src/tests/menucmds.rs @@ -4040,9 +4040,11 @@ fn ruler_guides_select_move_and_delete() { assert!(selected(&s).is_empty()); assert_eq!(s.execute("guide.select", &json!({"indexes": [1], "toggle": true})).unwrap()["selected"], json!([0, 1])); let layer = s.doc().unwrap().current_layer().unwrap().0; + let id = s.doc().unwrap().doc.ruler_guides()[1].id.unwrap().0; assert_eq!( s.execute("guide.list", &json!({})).unwrap()[1], - json!({"index": 1, "vertical": false, "pos": 50.0, "selected": true, "layer": layer, "shown": true, "editable": true}) + json!({"index": 1, "id": id, "vertical": false, "pos": 50.0, "selected": true, "layer": layer, + "hidden": false, "locked": false, "shown": true, "editable": true}) ); assert!(s.execute("guide.select", &json!({"indexes": [7]})).is_err()); // A move takes each selected guide along its own axis, in one undo step. @@ -4323,11 +4325,14 @@ fn artboard_guides_go_with_their_artboard() { s.execute("guide.add", &json!({"vertical": false, "pos": 100})).unwrap(); let list = |s: &mut Session| s.execute("guide.list", &json!({})).unwrap(); let layer = s.doc().unwrap().current_layer().unwrap().0; + let ids: Vec = s.doc().unwrap().doc.ruler_guides().iter().map(|g| g.id.unwrap().0).collect(); assert_eq!( list(&mut s), json!([ - {"index": 0, "vertical": true, "pos": 1000.0, "selected": false, "artboard": 1, "layer": layer, "shown": true, "editable": true}, - {"index": 1, "vertical": false, "pos": 100.0, "selected": false, "layer": layer, "shown": true, "editable": true}, + {"index": 0, "id": ids[0], "vertical": true, "pos": 1000.0, "selected": false, "artboard": 1, "layer": layer, + "hidden": false, "locked": false, "shown": true, "editable": true}, + {"index": 1, "id": ids[1], "vertical": false, "pos": 100.0, "selected": false, "layer": layer, + "hidden": false, "locked": false, "shown": true, "editable": true}, ]) ); let spans = |s: &Session| { @@ -4368,7 +4373,8 @@ fn artboard_guides_go_with_their_artboard() { assert_eq!((guides(&s).len(), selected_guides(&s)), (3, vec![0, 1])); assert_eq!( list(&mut s)[0], - json!({"index": 0, "vertical": false, "pos": 100.0, "selected": true, "layer": layer, "shown": true, "editable": true}) + json!({"index": 0, "id": ids[1], "vertical": false, "pos": 100.0, "selected": true, "layer": layer, + "hidden": false, "locked": false, "shown": true, "editable": true}) ); assert_eq!(undo_len(&s), n + 1); s.execute("edit.undo", &json!({})).unwrap(); @@ -4412,9 +4418,11 @@ fn guides_dragged_out_of_a_ruler_snap_and_take_the_artboard_tool_s_artboard() { s.ruler_guide(false, &ev(PointerKind::Drag, 1000.0, 50.0), true, v).unwrap(); s.ruler_guide(false, &ev(PointerKind::Up, 1000.0, 50.0), true, v).unwrap(); let layer = s.doc().unwrap().current_layer().unwrap().0; + let id = s.doc().unwrap().doc.ruler_guides()[1].id.unwrap().0; assert_eq!( s.execute("guide.list", &json!({})).unwrap()[1], - json!({"index": 1, "vertical": false, "pos": 50.0, "selected": false, "artboard": 1, "layer": layer, "shown": true, "editable": true}) + json!({"index": 1, "id": id, "vertical": false, "pos": 50.0, "selected": false, "artboard": 1, "layer": layer, + "hidden": false, "locked": false, "shown": true, "editable": true}) ); } @@ -4569,6 +4577,12 @@ fn ruler_guides_live_on_layers() { assert!(s.doc().unwrap().doc.ruler_guides().iter().all(|g| g.layer == Some(first))); s.execute("guide.setLayer", &json!({"indexes": [1], "layer": second.0})).unwrap(); assert!(s.execute("guide.setLayer", &json!({"indexes": [7], "layer": first.0})).is_err()); + // `indexes` that is not a list, or given with `index`, is an error; an index given twice counts once. + assert!(s.execute("guide.setLayer", &json!({"indexes": 0, "layer": first.0})).is_err()); + assert!(s.execute("guide.setLayer", &json!({"index": 0, "indexes": [1], "layer": first.0})).is_err()); + assert!(s.doc().unwrap().doc.ruler_guides().iter().map(|g| g.layer).eq([Some(first), Some(second)])); + assert_eq!(s.execute("guide.setLayer", &json!({"indexes": [1, 1], "layer": first.0})).unwrap()["count"], 1); + s.execute("guide.setLayer", &json!({"indexes": [1], "layer": second.0})).unwrap(); // Deleting a layer deletes its guides; undo brings them back. s.execute("layer.delete", &json!({"ids": [second.0]})).unwrap(); assert_eq!(guides(&s), [(true, 200.0)]); @@ -4606,6 +4620,122 @@ fn guides_on_hidden_or_locked_layers_are_left_alone() { assert_eq!(guides(&s).len(), 3); } +/// A guide hidden or locked on its own can't be moved, deleted or moved to another layer, and the +/// error names the guide, not its layer; a guide on a hidden or locked layer names the layer. +#[test] +fn a_guide_hidden_or_locked_on_its_own_is_named_in_the_error() { + let mut s = session(); + let first = s.doc().unwrap().current_layer().unwrap(); + for pos in [100.0, 200.0] { + s.execute("guide.add", &json!({"vertical": true, "pos": pos})).unwrap(); + } + let second = id_of(&s.execute("layer.new", &json!({})).unwrap()); + let ids: Vec = s.doc().unwrap().doc.ruler_guides().iter().map(|g| g.id.unwrap().0).collect(); + s.execute("layer.setProps", &json!({"ids": [ids[0]], "locked": true})).unwrap(); + s.execute("layer.setProps", &json!({"ids": [ids[1]], "visible": false})).unwrap(); + let own = "the guide is hidden or locked"; + for i in [0, 1] { + assert_eq!(s.execute("guide.move", &json!({"index": i, "pos": 50})).unwrap_err().to_string(), own, "{i}"); + assert_eq!(s.execute("guide.remove", &json!({"index": i})).unwrap_err().to_string(), own, "{i}"); + assert_eq!(s.execute("guide.remove", &json!({"indexes": [i]})).unwrap_err().to_string(), own, "{i}"); + let p = json!({"index": i, "layer": second.0}); + assert_eq!(s.execute("guide.setLayer", &p).unwrap_err().to_string(), own, "{i}"); + } + // Shown and unlocked, but on a locked layer: the error names the layer. + s.execute("layer.setProps", &json!({"ids": [ids[0]], "locked": false})).unwrap(); + s.execute("layer.setProps", &json!({"ids": [first.0], "locked": true})).unwrap(); + let e = s.execute("guide.move", &json!({"index": 0, "pos": 50})).unwrap_err().to_string(); + assert_eq!(e, "the guide is on a hidden or locked layer"); +} + +/// Object › Lock › Selection and Hide › Selection lock and hide a selected ruler guide on its own, +/// with the selected art, in one undo step; Unlock All and Show All unlock and show it again and +/// select it as a guide. While Lock Guides is on nothing selects it, and in isolation mode Lock +/// leaves it alone. +#[test] +fn lock_hide_unlock_and_show_all_reach_ruler_guides() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + for pos in [100.0, 200.0] { + s.execute("guide.add", &json!({"vertical": true, "pos": pos})).unwrap(); + } + let flags = |s: &Session| s.doc().unwrap().doc.ruler_guides().iter().map(|g| (g.hidden, g.locked)).collect::>(); + let undo = |s: &Session| s.doc().unwrap().history.undo.len(); + let clear = (false, false); + // A guide selected on its own: Lock locks it alone and deselects it. + s.execute("guide.select", &json!({"indexes": [0]})).unwrap(); + let n = undo(&s); + s.execute("object.lock", &json!({})).unwrap(); + assert_eq!((flags(&s), undo(&s)), (vec![(false, true), clear], n + 1)); + assert!(selected_guides(&s).is_empty()); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!((flags(&s), selected_guides(&s)), (vec![clear, clear], vec![0])); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(flags(&s)[0], (false, true)); + // A guide and art selected together: Hide hides both, in one step. + sel(&mut s, &[a]); + s.execute("guide.select", &json!({"indexes": [1], "toggle": true})).unwrap(); + let n = undo(&s); + s.execute("object.hide", &json!({})).unwrap(); + assert_eq!((flags(&s), undo(&s)), (vec![(false, true), (true, false)], n + 1)); + assert!(!s.doc().unwrap().doc.node(a).unwrap().visible); + // Unlock All and Show All reach the guides and select them as guides. + assert_eq!(s.execute("object.unlockAll", &json!({})).unwrap()["count"], 1); + assert_eq!((flags(&s)[0], selected_guides(&s), selected(&s)), (clear, vec![0], vec![])); + assert_eq!(s.execute("object.showAll", &json!({})).unwrap()["count"], 2); + assert_eq!((flags(&s), selected_guides(&s), selected(&s)), (vec![clear, clear], vec![1], vec![a])); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(flags(&s)[1], (true, false), "Show All is one undo step"); + s.execute("edit.redo", &json!({})).unwrap(); + // With Lock Guides on, Unlock All unlocks a guide but leaves it unselected. + s.execute("guide.select", &json!({"indexes": [0]})).unwrap(); + s.execute("object.lock", &json!({})).unwrap(); + s.execute("view.guides.lock", &json!({"locked": true})).unwrap(); + s.execute("object.unlockAll", &json!({})).unwrap(); + assert_eq!((flags(&s)[0], selected_guides(&s)), (clear, vec![])); + s.execute("view.guides.lock", &json!({"locked": false})).unwrap(); + // In isolation mode Lock takes only the objects inside the isolated group. + let b = rect(&mut s, 20.0, 0.0, 10.0, 10.0); + sel(&mut s, &[a, b]); + let g = id_of(&s.execute("object.group", &json!({})).unwrap()); + s.execute("object.isolate", &json!({"id": g.0})).unwrap(); + sel(&mut s, &[a]); + let _ = s.execute("guide.select", &json!({"indexes": [0], "toggle": true})); + s.execute("object.lock", &json!({})).unwrap(); + assert!(s.doc().unwrap().doc.node(a).unwrap().locked); + assert_eq!(flags(&s)[0], clear); +} + +/// `guide.remove` with `indexes` deletes those guides in one undo step, an index given twice +/// once; a locked guide among them, or an unknown index, deletes nothing. +#[test] +fn guide_remove_takes_several_indexes() { + let mut s = session(); + for pos in [100.0, 200.0, 300.0] { + s.execute("guide.add", &json!({"vertical": true, "pos": pos})).unwrap(); + } + let id = s.doc().unwrap().doc.ruler_guides()[2].id.unwrap(); + s.execute("layer.setProps", &json!({"ids": [id.0], "locked": true})).unwrap(); + assert!(s.execute("guide.remove", &json!({"indexes": [0, 2]})).is_err()); + assert!(s.execute("guide.remove", &json!({"indexes": [0, 7]})).is_err()); + assert!(s.execute("guide.remove", &json!({"indexes": 0})).is_err()); + assert!(s.execute("guide.remove", &json!({"index": 0, "indexes": [1]})).is_err()); + // A list longer than 10,000 entries is refused by every guide command that takes one. + let long = json!(vec![0; 10_001]); + assert!(s.execute("guide.remove", &json!({"indexes": long})).is_err()); + assert!(s.execute("guide.select", &json!({"indexes": long})).is_err()); + let layer = s.doc().unwrap().doc.layers[0].id; + assert!(s.execute("guide.setLayer", &json!({"indexes": long, "layer": layer.0})).is_err()); + assert_eq!(s.execute("guide.select", &json!({"indexes": vec![0; 10_000]})).unwrap()["selected"], json!([0])); + s.execute("select.none", &json!({})).unwrap(); + assert_eq!(guides(&s).len(), 3); + let n = s.doc().unwrap().history.undo.len(); + assert_eq!(s.execute("guide.remove", &json!({"indexes": [1, 0, 1]})).unwrap()["count"], 2); + assert_eq!((guides(&s), s.doc().unwrap().history.undo.len()), (vec![(true, 300.0)], n + 1)); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(guides(&s).len(), 3); +} + /// Guides follow their layers through Duplicate, Merge Selected and Flatten Artwork, in one undo /// step each. #[test] diff --git a/crates/engine/src/tests/save.rs b/crates/engine/src/tests/save.rs index 5edd0d7fbd..99febca6b2 100644 --- a/crates/engine/src/tests/save.rs +++ b/crates/engine/src/tests/save.rs @@ -789,3 +789,29 @@ fn units_and_ruler_guides_survive_save_and_reopen() { } let _ = std::fs::remove_dir_all(d); } + +/// A ruler guide hidden or locked on its own (the Layers panel's eye and lock on its row, +/// `layer.setProps` on its node) stays so through Save, Close and Open, and the other guide stays +/// visible and unlocked. +#[test] +fn a_guide_hidden_or_locked_on_its_own_survives_save_and_reopen() { + let d = dir("guide-flags"); + for ext in ["vectorcraft", "pdf", "ai", "eps"] { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap(); + for pos in [10, 20, 30] { + s.execute("guide.add", &json!({"vertical": true, "pos": pos})).unwrap(); + } + rect(&mut s); + let ids: Vec = s.doc().unwrap().doc.ruler_guides().iter().map(|g| g.id.unwrap().0).collect(); + s.execute("layer.setProps", &json!({"ids": [ids[1]], "visible": false})).unwrap(); + s.execute("layer.setProps", &json!({"ids": [ids[2]], "locked": true})).unwrap(); + let p = path(&d, &format!("a.{ext}")); + s.execute("document.save", &json!({"path": p})).unwrap(); + s.execute("file.close", &json!({})).unwrap(); + s.execute("document.open", &json!({"path": p})).unwrap(); + let flags: Vec<_> = s.doc().unwrap().doc.ruler_guides().iter().map(|g| (g.pos, g.hidden, g.locked)).collect(); + assert_eq!(flags, [(10.0, false, false), (20.0, true, false), (30.0, false, true)], "{ext}"); + } + let _ = std::fs::remove_dir_all(d); +} diff --git a/crates/engine/tests/it/ruler_guide_nodes.rs b/crates/engine/tests/it/ruler_guide_nodes.rs index 950da2f065..1a88377585 100644 --- a/crates/engine/tests/it/ruler_guide_nodes.rs +++ b/crates/engine/tests/it/ruler_guide_nodes.rs @@ -103,10 +103,12 @@ fn ruler_guides_are_not_art_to_select_paint_or_inspect() { let layer_row = s.execute("document.inspect", &json!({"ids": [layer.0]})).unwrap(); let listed = layer_row.to_string(); assert!(guides.iter().all(|g| !listed.contains(&format!("\"id\":{}", g.0))), "{listed}"); - // Unlock All does not reach a locked guide. + // Unlock All unlocks a guide locked on its own and selects it as a guide, not as art. Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(guides[0]).unwrap().locked = true; s.execute("object.unlockAll", &json!({})).unwrap(); - assert!(s.doc().unwrap().doc.node(guides[0]).unwrap().locked); + let st = s.doc().unwrap(); + assert!(!st.doc.node(guides[0]).unwrap().locked); + assert_eq!((st.selection.guides.clone(), st.selection.objects.clone()), (vec![guides[0]], vec![])); } #[test] diff --git a/crates/ui-egui/src/panels/layers.rs b/crates/ui-egui/src/panels/layers.rs index 0ac14d243d..22c59218e2 100644 --- a/crates/ui-egui/src/panels/layers.rs +++ b/crates/ui-egui/src/panels/layers.rs @@ -11,13 +11,17 @@ //! - The selection column selects a row's art (`layer.selectAll`, Shift adds or removes); a row //! whose art is selected shows a square in its layer's colour, and dragging that square onto //! another row moves the selected art there (Alt copies it). -//! - The eye and lock columns toggle a row (`layer.setProps`); dragging down a column sets every -//! row it passes to the same state, in one undo step. Ctrl/Cmd-click an eye switches the layer -//! between Preview and Outline. Alt-click an eye hides the other layers (`layer.hideOthers`), or -//! shows every layer when they are hidden (`layer.showAll`); Alt-click a lock does the same with -//! `layer.lockOthers` and `layer.unlockAll`. Ctrl/Cmd+Alt-click an eye switches the other layers -//! to Outline and the row's layer to Preview (`layer.outlineOthers`), or switches every layer to -//! Preview when the others are in Outline (`layer.previewAll`). +//! - The eye and lock columns toggle a row (`layer.setProps`), a ruler guide's row included; +//! dragging down a column sets every row it passes to the same state, in one undo step. +//! Ctrl/Cmd-click a layer's eye switches it between Preview and Outline. Alt-click an eye hides +//! the other layers (`layer.hideOthers`), or shows every layer when they are hidden +//! (`layer.showAll`); Alt-click a lock does the same with `layer.lockOthers` and +//! `layer.unlockAll`. Ctrl/Cmd+Alt-click an eye switches the other layers to Outline and the +//! row's layer to Preview (`layer.outlineOthers`), or switches every layer to Preview when the +//! others are in Outline (`layer.previewAll`). +//! - A ruler guide's row selects the guide (`guide.select`) and leaves no row highlighted, so +//! Delete then deletes the guide; dragged onto another layer's row the guide goes there +//! (`guide.setLayer`), and onto the trash it is deleted (`guide.remove`). //! - Dragging rows moves them above, below or into a layer or group (`layer.move`, a drop line or //! a box shows where); Alt copies them. A dimmed copy of the row follows the pointer. Layers //! dropped in the empty space under the last row go below the bottom layer. Dropped on the trash @@ -134,7 +138,7 @@ enum LayersDrag { /// The selected-art square: the selected objects go to the row it is dropped on. Art, /// Ruler guide rows (indexes into the document's guides): they go to the layer of the row - /// they are dropped on. + /// they are dropped on, or are deleted when dropped on the trash. Guides(Vec), } diff --git a/crates/ui-egui/src/panels/layers/controls.rs b/crates/ui-egui/src/panels/layers/controls.rs index a9ee00462b..381d0a65b1 100644 --- a/crates/ui-egui/src/panels/layers/controls.rs +++ b/crates/ui-egui/src/panels/layers/controls.rs @@ -63,7 +63,8 @@ pub(super) fn bottom_bar(app: &mut VectorcraftApp, ui: &mut Ui, view: &View, doc { actions.push(("appearance.clear".into(), json!({"ids": [id.0]}))); } else if trash.clicked() { - if view.rows.is_empty() && app.session.active().is_some_and(|d| !d.selection.is_empty()) { + // With no row highlighted, the selected art and ruler guides go. + if view.rows.is_empty() && app.session.active().is_some_and(|d| d.selection.has_objects_or_guides()) { actions.push(("edit.clear".into(), json!({}))); } else { actions.push(("ui.layerDelete".into(), json!({}))); @@ -82,15 +83,22 @@ pub(super) fn bottom_bar(app: &mut VectorcraftApp, ui: &mut Ui, view: &View, doc } } // Rows dropped on the trash are deleted, on New Layer duplicated, as in Illustrator. Both are - // outlined while rows (or, on the trash, a target circle) hang over them. + // outlined while rows (or, on the trash, a target circle) hang over them. Guide rows dropped on + // the trash delete their guides (`guide.remove`); New Layer does not take them. for (button, cmd) in [(&trash, "ui.layerDelete"), (&new_layer, "layer.duplicate")] { - if let Some(d) = button.dnd_release_payload::() - && let LayersDrag::Rows(ids) = &*d - { - actions.push((cmd.into(), json!({"ids": ids.iter().map(|i| i.0).collect::>()}))); + let deletes = cmd == "ui.layerDelete"; + if let Some(d) = button.dnd_release_payload::() { + match &*d { + LayersDrag::Rows(ids) => actions.push((cmd.into(), json!({"ids": ids.iter().map(|i| i.0).collect::>()}))), + LayersDrag::Guides(guides) if deletes => actions.push(("guide.remove".into(), json!({"indexes": guides}))), + _ => {} + } } - let over = button.dnd_hover_payload::().is_some_and(|d| matches!(*d, LayersDrag::Rows(_))) - || (cmd == "ui.layerDelete" && button.dnd_hover_payload::().is_some_and(|d| matches!(*d, PanelDrag::Appearance(_)))); + let over = button.dnd_hover_payload::().is_some_and(|d| match *d { + LayersDrag::Rows(_) => true, + LayersDrag::Guides(_) => deletes, + LayersDrag::Art => false, + }) || (deletes && button.dnd_hover_payload::().is_some_and(|d| matches!(*d, PanelDrag::Appearance(_)))); if over { widgets::drop_target_outline(&child, button.rect); } diff --git a/crates/ui-egui/src/panels/layers/model.rs b/crates/ui-egui/src/panels/layers/model.rs index c24863ffbc..428149d776 100644 --- a/crates/ui-egui/src/panels/layers/model.rs +++ b/crates/ui-egui/src/panels/layers/model.rs @@ -62,7 +62,8 @@ pub(super) struct Row { pub(super) colour: Color32, /// Drawn dimmed: hidden itself or in a hidden layer or group, or a template layer. pub(super) dim: bool, - /// A ruler guide on the layer `node` (its index in the document's guides): the guide's row. + /// A ruler guide on the layer `node` (its index in the document's guides): the guide's row, + /// dimmed when the guide or its layer is hidden. pub(super) guide: Option, /// The spine of blend `node`: its row, below the blend's key objects (#4820). pub(super) spine: bool, @@ -263,10 +264,15 @@ pub(super) fn push_rows( let searching = !query.is_empty(); let narrowing = searching || filter.is_on(); // A layer's ruler guides are rows in it, above its art, the highest `guide.list` index first - // (not while searching, nor while the filter leaves them out). - let guides: Vec = if n.is_layer() && !opts.layers_only && !searching && filter.keeps_guides() { - let mut found: Vec = - n.children().into_iter().flatten().filter(|c| c.is_ruler_guide()).filter_map(|c| all_guides.binary_search(&c.id).ok()).collect(); + // (not while searching, nor while the filter leaves them out), each with whether it is visible. + let guides: Vec<(usize, bool)> = if n.is_layer() && !opts.layers_only && !searching && filter.keeps_guides() { + let mut found: Vec<(usize, bool)> = n + .children() + .into_iter() + .flatten() + .filter(|c| c.is_ruler_guide()) + .filter_map(|c| all_guides.binary_search(&c.id).ok().map(|i| (i, c.visible))) + .collect(); found.sort_unstable(); found } else { @@ -277,7 +283,7 @@ pub(super) fn push_rows( let at = out.len(); out.push(Row { node: n.clone(), depth, clip_path, opens, open, colour, dim: !shown || n.is_template(), guide: None, spine: false }); if open { - for i in guides.into_iter().rev() { + for (i, visible) in guides.into_iter().rev() { out.push(Row { node: n.clone(), depth: depth + 1, @@ -285,7 +291,7 @@ pub(super) fn push_rows( opens: false, open: false, colour, - dim: !shown, + dim: !shown || !visible, guide: Some(i), spine: false, }); diff --git a/crates/ui-egui/src/panels/layers/rows.rs b/crates/ui-egui/src/panels/layers/rows.rs index 4e5b7eb218..9f80d93791 100644 --- a/crates/ui-egui/src/panels/layers/rows.rs +++ b/crates/ui-egui/src/panels/layers/rows.rs @@ -116,9 +116,14 @@ fn takes(n: &Node, drag: &LayersDrag, doc: &Document) -> bool { } } -/// The row of ruler guide `i` on the layer of `item`: a guide mark and its name, the selection -/// square when it is selected. A click selects the guide; Shift or Cmd adds it to (or takes it -/// from) the selected guides. A guide on a hidden or locked layer can't be selected or dragged. +/// The row of ruler guide `i` on the layer of `item`: the guide's own eye and lock, a guide mark +/// and its name, the selection square when it is selected. The eye and lock hide and lock this +/// guide alone (`layer.setProps` on its node, one undo step), and take part in a drag down either +/// column, as other rows do; they work while its layer is hidden or locked, and the guide shows or +/// can be edited only when its layer allows it too. A click elsewhere selects the guide and leaves +/// no row highlighted; Shift or Cmd adds it to (or takes it from) the selected guides. Dragged onto +/// another layer's row the guide goes to that layer, and onto the trash it is deleted. A hidden or +/// locked guide, or one on a hidden or locked layer, can't be selected or dragged. fn guide_row(ui: &mut Ui, view: &View, item: &Row, i: usize, out: &mut Out) { let (t, h) = (&view.t, view.h); let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), h), Sense::click_and_drag()); @@ -129,6 +134,9 @@ fn guide_row(ui: &mut Ui, view: &View, item: &Row, i: usize, out: &mut Out) { ui.painter().rect_filled(r, 0.0, t.hover.gamma_multiply(0.6)); } ui.painter().line_segment([r.left_bottom(), r.right_bottom()], Stroke::new(1.0, t.input_border)); + if let Some(node) = g.id.and_then(|id| view.doc.node(id)) { + eye_and_lock(ui, view, node, r, out); + } let mut x = r.left() + 2.0 * COLUMN + 2.0; colour_bar(ui, &item.node, r, x, item.colour); x += 6.0 + item.depth as f32 * INDENT + 16.0; @@ -149,11 +157,17 @@ fn guide_row(ui: &mut Ui, view: &View, item: &Row, i: usize, out: &mut Out) { } if editable && resp.clicked() { let m = ui.input(|i| i.modifiers); + // The highlighted rows are let go, so Delete then deletes the selected guide (Edit › Clear) + // rather than those rows. + if !view.rows.is_empty() { + out.actions.push(("layer.highlight".into(), json!({"ids": [], "mode": "set"}))); + out.rows_after_click = Some(vec![]); + } out.actions.push(("guide.select".into(), json!({"indexes": [i], "toggle": m.shift || m.command}))); } // Dragged: the selected guides when this is one of them, else this one, to another layer's row. - // Only the primary button drags a guide row. - if editable && resp.drag_started_by(egui::PointerButton::Primary) { + // Only the primary button drags a guide row, and not while a drag down a column passes it. + if editable && resp.drag_started_by(egui::PointerButton::Primary) && view.column.is_none() { let guides = if selected { view.guides.clone() } else { vec![i] }; egui::DragAndDrop::set_payload(ui.ctx(), LayersDrag::Guides(guides)); } @@ -426,8 +440,8 @@ fn others_action(doc: &Document, n: &Node, eye: bool) -> (String, Value) { (false, true) => "layer.lockOthers", (false, false) => "layer.unlockAll", }; - // Show All and Unlock All take no rows. - let params = if cmd.ends_with("Others") { json!({ "ids": [n.id.0] }) } else { json!({}) }; + // Show All and Unlock All take no rows; a ruler guide's row names its layer. + let params = if cmd.ends_with("Others") { json!({ "ids": [layer_row(n, own).0] }) } else { json!({}) }; (cmd.into(), params) } @@ -437,13 +451,19 @@ fn others_action(doc: &Document, n: &Node, eye: bool) -> (String, Value) { fn outline_others_action(doc: &Document, n: &Node) -> (String, Value) { let own = doc.layer_of(n.id); if doc.layers.iter().any(|l| Some(l.id) != own && !matches!(l.kind, NodeKind::Layer { preview: false, .. })) { - ("layer.outlineOthers".into(), json!({ "ids": [n.id.0] })) + ("layer.outlineOthers".into(), json!({ "ids": [layer_row(n, own).0] })) } else { // Preview All takes no rows. ("layer.previewAll".into(), json!({})) } } +/// The row the layer commands of an Alt-click on row `n`'s eye or lock name: `n` itself, or for a +/// ruler guide's row the layer `own` that holds the guide (the layer commands refuse a guide). +fn layer_row(n: &Node, own: Option) -> NodeId { + if n.is_ruler_guide() { own.unwrap_or(n.id) } else { n.id } +} + /// The eye and lock columns of row `n` at `r`. fn eye_and_lock(ui: &mut Ui, view: &View, n: &Node, r: egui::Rect, out: &mut Out) { let t = &view.t; diff --git a/crates/ui-egui/src/panels/layers/tests.rs b/crates/ui-egui/src/panels/layers/tests.rs index 2143bd1ee3..939324ff2c 100644 --- a/crates/ui-egui/src/panels/layers/tests.rs +++ b/crates/ui-egui/src/panels/layers/tests.rs @@ -835,6 +835,158 @@ fn guide_rows_select_and_move_their_guides() { assert_eq!(app.session.active().unwrap().doc.ruler_guides()[0].layer, Some(second)); } +/// A guide row's eye and lock hide and lock that guide alone, each click one undo step: a hidden +/// guide neither shows nor stays selected and its row dims, a locked one shows but can't be +/// selected. They work while the guide's layer is hidden, and a drag down the eye column passes +/// the guide row like any other. +#[test] +fn guide_rows_have_their_own_eye_and_lock() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let run = |app: &mut VectorcraftApp, id: &str, p: serde_json::Value| app.session.execute(id, &p).unwrap(); + run(&mut app, "file.new", json!({"width": 200, "height": 200})); + let rect = NodeId(run(&mut app, "shape.rectangle", json!({"x": 0, "y": 0, "width": 20, "height": 20}))["id"].as_u64().unwrap()); + run(&mut app, "guide.add", json!({"vertical": true, "pos": 50})); + run(&mut app, "select.none", json!({})); + expand(&mut app, &json!({})).unwrap(); + let ctx = egui::Context::default(); + // Rows top down: Layer 1, its guide (no target circle), the rectangle. + let (circles, _) = frame(&mut app, &ctx, vec![], false); + assert_eq!(circles.len(), 2); + let y = (circles[0].y + circles[1].y) / 2.0; + let (name, eye, lock) = (egui::pos2(150.0, y), egui::pos2(12.0, y), egui::pos2(37.0, y)); + let st = app.session.active().unwrap(); + let (layer, guide) = (st.doc.layers[0].id, st.doc.ruler_guides()[0].id.unwrap()); + let node = |app: &VectorcraftApp, id: NodeId| app.session.active().unwrap().doc.node(id).unwrap().clone(); + let undo = |app: &VectorcraftApp| app.session.active().unwrap().history.undo.len(); + let selected = |app: &VectorcraftApp| app.session.active().unwrap().selection.guides.clone(); + let shown_and_editable = |app: &VectorcraftApp| { + let d = &app.session.active().unwrap().doc; + let g = d.ruler_guide(guide).unwrap(); + (d.guide_shown(&g), d.guide_editable(&g)) + }; + let dimmed = |app: &VectorcraftApp| { + let st = app.session.active().unwrap(); + list_rows(&st.doc, &st.layers_open, &PanelOptions::default(), "", &Filter::default()).iter().find(|r| r.guide.is_some()).unwrap().dim + }; + click_with(&mut app, &ctx, name, egui::Modifiers::NONE); + assert_eq!(selected(&app), [guide]); + // The eye hides the guide alone, in one step, and deselects it. + let before = undo(&app); + click_with(&mut app, &ctx, eye, egui::Modifiers::NONE); + assert!(!node(&app, guide).visible && node(&app, layer).visible && node(&app, rect).visible); + assert_eq!((undo(&app), shown_and_editable(&app), dimmed(&app)), (before + 1, (false, false), true)); + assert!(selected(&app).is_empty(), "a hidden guide can't stay selected"); + click_with(&mut app, &ctx, name, egui::Modifiers::NONE); + assert!(selected(&app).is_empty(), "its row doesn't select a hidden guide"); + click_with(&mut app, &ctx, eye, egui::Modifiers::NONE); + assert_eq!((node(&app, guide).visible, shown_and_editable(&app), dimmed(&app)), (true, (true, true), false)); + // The lock locks it alone: it still shows, and its row no longer selects it. + click_with(&mut app, &ctx, lock, egui::Modifiers::NONE); + assert!(node(&app, guide).locked && !node(&app, layer).locked); + assert_eq!((undo(&app), shown_and_editable(&app), dimmed(&app)), (before + 3, (true, false), false)); + click_with(&mut app, &ctx, name, egui::Modifiers::NONE); + assert!(selected(&app).is_empty(), "its row doesn't select a locked guide"); + run(&mut app, "edit.undo", json!({})); + assert!(!node(&app, guide).locked); + run(&mut app, "edit.redo", json!({})); + assert!(node(&app, guide).locked); + click_with(&mut app, &ctx, lock, egui::Modifiers::NONE); + assert_eq!(shown_and_editable(&app), (true, true)); + // With its layer hidden, the guide's own eye still changes the guide, which shows again with + // the layer only when its own eye is on. + run(&mut app, "layer.setProps", json!({"ids": [layer.0], "visible": false})); + click_with(&mut app, &ctx, eye, egui::Modifiers::NONE); + assert!(!node(&app, guide).visible); + run(&mut app, "layer.setProps", json!({"ids": [layer.0], "visible": true})); + assert_eq!(shown_and_editable(&app), (false, false)); + click_with(&mut app, &ctx, eye, egui::Modifiers::NONE); + assert_eq!(shown_and_editable(&app), (true, true)); + // A drag down the eye column from the guide row to the rectangle hides both, in one step. + let before = undo(&app); + let below = egui::pos2(12.0, circles[1].y); + let steps = [ + vec![egui::Event::PointerMoved(eye)], + vec![button(eye, true)], + vec![egui::Event::PointerMoved(eye + vec2(0.0, 6.0))], + vec![egui::Event::PointerMoved(below)], + vec![button(below, false)], + vec![], + ]; + for e in steps { + frame(&mut app, &ctx, e, false); + } + assert!(!node(&app, guide).visible && !node(&app, rect).visible && node(&app, layer).visible); + assert_eq!(undo(&app), before + 1, "one undo step"); + assert!(!app.session.in_interaction()); + run(&mut app, "edit.undo", json!({})); + assert!(node(&app, guide).visible && node(&app, rect).visible); + // Alt-click on the guide's eye or lock acts on the other layers, as on any row in its layer. + run(&mut app, "layer.new", json!({})); + let other = app.session.active().unwrap().doc.layers.iter().map(|l| l.id).find(|l| *l != layer).unwrap(); + let (circles, _) = frame(&mut app, &ctx, vec![], false); + assert_eq!(circles.len(), 3, "the new layer, Layer 1 and the rectangle"); + let y = (circles[1].y + circles[2].y) / 2.0; + click_with(&mut app, &ctx, egui::pos2(12.0, y), egui::Modifiers::ALT); + assert!(!node(&app, other).visible && node(&app, layer).visible && node(&app, guide).visible); + click_with(&mut app, &ctx, egui::pos2(37.0, y), egui::Modifiers::ALT); + assert!(node(&app, other).locked && !node(&app, layer).locked && !node(&app, guide).locked); +} + +/// A guide row dropped on the trash deletes its guide, in one undo step; with no row highlighted +/// the trash deletes the guide its row selected; and a click on a guide row lets go of the +/// highlighted rows, so Delete goes to Edit › Clear, which deletes the guide and not the layer. +#[test] +fn guide_rows_are_deleted_with_the_trash_and_delete() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let run = |app: &mut VectorcraftApp, id: &str, p: serde_json::Value| app.session.execute(id, &p).unwrap(); + run(&mut app, "file.new", json!({"width": 200, "height": 200})); + let rect = NodeId(run(&mut app, "shape.rectangle", json!({"x": 0, "y": 0, "width": 20, "height": 20}))["id"].as_u64().unwrap()); + for pos in [50, 80] { + run(&mut app, "guide.add", json!({"vertical": true, "pos": pos})); + } + run(&mut app, "select.none", json!({})); + expand(&mut app, &json!({})).unwrap(); + let ctx = egui::Context::default(); + // Rows top down: Layer 1, the 80 pt guide, the 50 pt guide, the rectangle. + let (circles, _) = frame(&mut app, &ctx, vec![], false); + assert_eq!(circles.len(), 2); + let h = (circles[1].y - circles[0].y) / 3.0; + let (row_80, row_50) = (egui::pos2(150.0, circles[0].y + h), egui::pos2(150.0, circles[0].y + 2.0 * h)); + let positions = |app: &VectorcraftApp| app.session.active().unwrap().doc.ruler_guides().iter().map(|g| g.pos).collect::>(); + let undo = |app: &VectorcraftApp| app.session.active().unwrap().history.undo.len(); + let kept = |app: &VectorcraftApp| { + let d = &app.session.active().unwrap().doc; + d.layers.len() == 1 && d.node(rect).is_some() + }; + let trash = trash_pos(&mut app, &ctx); + let before = undo(&app); + drag(&mut app, &ctx, row_80, trash, false); + assert_eq!((positions(&app), undo(&app)), (vec![50.0], before + 1)); + assert!(kept(&app)); + run(&mut app, "edit.undo", json!({})); + assert_eq!(positions(&app).len(), 2); + // The trash, with the guide selected through its row and no row highlighted. + click_with(&mut app, &ctx, row_50, egui::Modifiers::NONE); + assert!(app.session.active().unwrap().highlighted_rows().is_empty()); + click_with(&mut app, &ctx, trash, egui::Modifiers::NONE); + assert_eq!(positions(&app), [80.0]); + assert!(kept(&app) && app.ui.dialog.is_none()); + run(&mut app, "edit.undo", json!({})); + // Layer 1 highlighted, then the guide's row clicked: the panel lets Delete go. + let layer = app.session.active().unwrap().doc.layers[0].id; + click_with(&mut app, &ctx, egui::pos2(150.0, circles[0].y), egui::Modifiers::NONE); + assert_eq!(app.session.active().unwrap().highlighted_rows(), [layer]); + click_with(&mut app, &ctx, row_80, egui::Modifiers::NONE); + assert!(app.session.active().unwrap().highlighted_rows().is_empty()); + let del = egui::Event::Key { key: egui::Key::Delete, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }; + frame(&mut app, &ctx, vec![del], false); + assert!(kept(&app) && app.ui.dialog.is_none() && !crate::panels::rows_take_delete(&ctx)); + assert_eq!(positions(&app).len(), 2); + app.run("edit.clear", json!({})).unwrap(); + assert_eq!(positions(&app), [50.0]); + assert!(kept(&app)); +} + /// The selection squares drawn: (big ones on rows whose object is selected, small ones on rows /// holding selected art). fn squares(app: &mut VectorcraftApp, ctx: &egui::Context) -> (usize, usize) { diff --git a/docs/mcp.md b/docs/mcp.md index 274db05a34..f492bb73f4 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2473,8 +2473,8 @@ them again with the key object. When the call changes nothing, it records no und Other `object.setProps` calls leave the selection unchanged. `object.unlockAll` and `object.showAll` unlock or show every locked or hidden object in the document and select -them → `{count}`. In isolation mode they take only the objects inside the isolated object. With `scope: "group"` they -take only the objects inside the groups that hold the selected objects: +them → `{count}`. Ruler guides locked or hidden on their own are counted, and are selected as guides. In isolation +mode they take only the objects inside the isolated object. With `scope: "group"` they take only the objects inside the groups that hold the selected objects: for each selected object, the group nearest above it, or the object itself when it is a group. The objects of a group inside another such group are counted once. With no selected object in a group, the call returns the error "nothing selected is in a group" and changes nothing. `scope: "document"` is the default, and any other value is @@ -2721,12 +2721,22 @@ vertical guide, the y of a horizontal one, in points) → `{index}`. With `artbo artboard guide: it runs across that artboard only, moves with it (`artboard.move`, a pure move in `artboard.setProps`, `artboard.rearrange`), scales with it (`artboard.setProps {scaleArt}`), is copied with it (`artboard.duplicate`, `artboard.move {copy}`) and is deleted with it (`artboard.delete`); without, a canvas guide runs across the whole canvas. `guide.list` → -`[{index, vertical, pos, selected, artboard?}…]` (`artboard` only for artboard guides). +`[{index, id, vertical, pos, selected, artboard?, layer?, hidden, locked, shown, editable}…]` (`artboard` only for +artboard guides; `id` is the guide's node and `layer` the layer it is on; `hidden` and `locked` are its own state, +`shown` and `editable` also take its layer into account). `layer.setProps {ids: [id…], visible?, locked?}` hides or +locks guides on their own, as the eye and lock on a guide's row in the Layers panel do; a hidden guide is not drawn +and does not snap, and a locked one is drawn and snaps but can't be selected, moved or deleted. `guide.select {indexes: [index…], toggle?}` selects guides on their own (the art is deselected; `toggle` adds or removes them) → `{selected}`. `guide.move {index, pos}` puts one guide somewhere, `guide.move {dx?, dy?, copy?}` moves the selected ones (vertical guides by `dx`, horizontal ones by `dy`; `copy` leaves them and selects the -moved copies), and `guide.remove {index?}` deletes one guide or the selected ones → `{count}`; each is one undo -step. With guides selected, `edit.clear` (Delete) deletes them and `object.nudge` (the arrow keys) nudges them. +moved copies), and `guide.remove {index?, indexes?}` deletes one guide, the guides `indexes` (not with `index`; an +index given twice counts once; a hidden or locked guide among them is an error and nothing is deleted) or the +selected ones → `{count}`; each is one undo step. An `indexes` list of `guide.select`, `guide.remove` or +`guide.setLayer` holds at most 10,000 entries; a longer one is an error. With guides selected, `edit.clear` (Delete) deletes them and `object.nudge` (the +arrow keys) nudges them. Object › Lock › Selection (`object.lock`) and Object › Hide › Selection (`object.hide`) lock +or hide the selected guides on their own, with the selected art, in one undo step, except in isolation mode. +`object.unlockAll` and `object.showAll` with the default scope, outside isolation mode, also unlock or show the +guides locked or hidden on their own and select them as guides. View › Guides › Lock Guides (`view.guides.lock`) deselects them and the paths made into guides, in every open document, and refuses these commands until unlocked. While it is on, a command that selects art, such as `edit.undo`, `edit.redo`, `object.exitIsolation`, `object.unlockAll`, `object.showAll` or `edit.paste`, leaves the guides out. @@ -4298,6 +4308,13 @@ and `layerRows`, the rows highlighted in the panel. draws and is clicked in outline, Ctrl/Cmd-click its eye), `dimImages` (0–100, or false) and `color` (an index 0–26, `#rrggbb` or a preset name; a hex color with an alpha part, `#rrggbbaa` or `#rgba`, is an error, and so it is in `layer.new` and `layer.newSublayer`). Several rows change in one undo step (a drag down the eye or lock column). + A ruler guide's row has its own eye and lock: `ids` may name ruler guides (their `id` in `guide.list`), which take + `visible` and `locked`. They can be changed while the guide's layer is hidden or locked, and the guide shows + or can be edited only when its layer allows it as well. Alt-click on a guide row's eye or lock acts on the other + layers, as on any row in that layer. A click on a guide row selects the guide (`guide.select`) and clears the + highlighted rows (`layer.highlight {ids: [], mode: "set"}`), so Delete then runs `edit.clear` on the guide; with no + row highlighted, the trash button runs `edit.clear` on the selected guides and art, and guide rows dropped on the + trash are deleted (`guide.remove {indexes}`). - **Dragging rows**: `layer.move {ids, target, place?: above|below|inside, copy?}` moves rows beside a row or into a layer or group (on top of its contents), keeping their stacking order; `copy` (Alt-drag) moves copies. Layers go only in layers or at the top level and objects in layers and groups (an object placed beside a top-level layer goes diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f04ee3c910..b06b8be192 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1101,7 +1101,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur The Blob Brush Tool Options' tip preview is the Angle slider for screen readers, with the Angle in degrees as its value: a click or a drag in it points the Angle at the pointer and gives it the keyboard focus, Tab reaches it after the Roundness field, and the arrow keys step the Angle by 1° (10° with Shift, Home and End to −180° and 180°). The Blob Brush Tool Options also have Fidelity, which the reference app's [Blob Brush options](https://web.archive.org/web/20261012042029/https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/blob-brush-options-and-best-practices.html) list as setting how far the pointer moves before the path gets a new anchor point. The range and default are VectorCraft's own values: the Pencil's logarithmic slider from Accurate (0.01 pt) to Smooth (20 pt) and its field (up to 100 pt), 1.5 pt by default and kept with the tool's options. The brush follows the stroke fitted at the Fidelity, as a Pencil stroke is fitted: a low value follows the drag closely, jitter included, and a higher one gives smoother curves (`path.blob` `fidelity`). A Blob Brush stroke merges with the topmost path of its fill color and no stroke that it touches, and with the other such paths it touches in the same group or layer that are next to that path in stacking order with no other kind of object between them; matching paths in other groups or layers are left alone, as the Blob Brush tool guidelines in [Paint with fills and strokes](https://web.archive.org/web/20241219085603/https://helpx.adobe.com/illustrator/using/painting-fills-strokes.html) describe (`path.blob`). -- **Ruler guides as layer objects:** a guide goes on the current layer, shows, hides, locks and is deleted with it, is listed in the Layers panel (its row selects it) and moves to another layer (`guide.setLayer`, or its row dragged onto that layer's rows); guides on a hidden or locked layer can't be selected, moved or deleted, Duplicate copies a layer's guides and Merge Selected and Flatten Artwork keep them on the merged layer; guides from files saved before guides had layers go on the top visible, unlocked layer when the document opens. Not done: guides stacked among the art of their layer (they are listed above it), a guide row's own eye and lock. Lock Guides also locks the objects made into guides: they can't be selected, moved or deleted (#1543); they are drawn in the guide colour and style of Preferences, and a dragged selection snaps to ruler guides with Smart Guides on (#1583, fixes #1534). Preferences › Guides & Grid › Lock Guides by Default locks guides when the app starts; it is off by default, and new guides can still be dragged out of a ruler while guides are locked. The Transform panel shows a selected ruler guide's X or Y, and typing a value moves it (#1659, part of #1597). This is not established by the documentation we could find: the public help pages on guides, rulers and the Transform, Control and Properties panels (read again on 2026-10-14) describe selecting and dragging unlocked guides and the panels' X and Y for a selection, not a guide's position in a panel, and the one public statement of it is a user's [community answer](https://community.adobe.com/questions-652/adding-a-new-custom-guide-785586), which is not documentation. It is kept as a convenience pending the owner's decision, with no parity claim and nothing counted towards a score. +- **Ruler guides as layer objects:** a guide goes on the current layer, shows, hides, locks and is deleted with it, is listed in the Layers panel (its row selects it) and moves to another layer (`guide.setLayer`, or its row dragged onto that layer's rows); guides on a hidden or locked layer can't be selected, moved or deleted, Duplicate copies a layer's guides and Merge Selected and Flatten Artwork keep them on the merged layer; guides from files saved before guides had layers go on the top visible, unlocked layer when the document opens. A guide's row has its own eye and lock, which hide or lock that guide alone in one undo step and take part in a drag down either column ([help page](https://helpx.adobe.com/in_hi/tutorial-builder/user-guide/illustrator-tutorial-builder/-ai--examples-of-common-coach-marks.html) lists a Guide among the Layers panel's items); a hidden guide is not drawn and does not snap, a locked one is drawn and snaps but can't be selected, moved or deleted, and its own state is kept through save and reopen and while its layer is hidden or locked (`layer.setProps` on its `guide.list` id). Object › Lock › Selection and Object › Hide › Selection lock or hide a selected guide with the selected art, and Unlock All and Show All unlock or show such guides and select them ([help page](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf) for Lock and Hide Selection). A guide row dropped on the panel's trash deletes its guide, the trash deletes a guide its row selected, and after a click on a guide row Delete deletes the guide rather than the rows highlighted before ([help page](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/align-graphic-objects-with-guides.html) for deleting a selected guide). Not done: guides stacked among the art of their layer (they are listed above it). Lock Guides also locks the objects made into guides: they can't be selected, moved or deleted (#1543); they are drawn in the guide colour and style of Preferences, and a dragged selection snaps to ruler guides with Smart Guides on (#1583, fixes #1534). Preferences › Guides & Grid › Lock Guides by Default locks guides when the app starts; it is off by default, and new guides can still be dragged out of a ruler while guides are locked. The Transform panel shows a selected ruler guide's X or Y, and typing a value moves it (#1659, part of #1597). This is not established by the documentation we could find: the public help pages on guides, rulers and the Transform, Control and Properties panels (read again on 2026-10-14) describe selecting and dragging unlocked guides and the panels' X and Y for a selection, not a guide's position in a panel, and the one public statement of it is a user's [community answer](https://community.adobe.com/questions-652/adding-a-new-custom-guide-785586), which is not documentation. It is kept as a convenience pending the owner's decision, with no parity claim and nothing counted towards a score. - **Releasing ruler guides:** View › Guides › Release Guides turns the selected ruler guides into paths with no fill or stroke. An artboard guide becomes a line across its artboard, and a canvas guide becomes a line across the artboards (`view.guides.release {index?, ids?}`). A Cmd/Ctrl+Shift double-click with the Selection, Direct Selection or Group Selection tool releases the ruler guide or guide path under the pointer. - **Layers panel:** every layer, sublayer, group and object is a clickable row at any depth: a click highlights it and makes its layer current (new art goes there), Shift-click a range, Ctrl/Cmd-click toggles. Sublayers are no longer treated as objects: clicks, marquees, Select All and the Select menu take the art inside them, and each sublayer selects in its own colour. Selection squares on rows with selected art (click selects a row's art, Shift adds or removes; dragging the square moves the selection to another row, Alt copies), the eye and lock on every row with drag-down-the-column (one undo step), Ctrl/Cmd-click an eye for per-layer Outline, Alt-click an eye or lock to hide or lock the other layers (again: show or unlock them all), triangles with Alt to open or close everything inside, drag and drop rows above, below or into layers and groups with a drop line (Alt copies) and a dimmed copy of the row under the pointer (layers dropped in the empty space under the last row go below the bottom layer, #2260; dropped on the trash rows are deleted, on New Layer duplicated, as in Illustrator), inline rename, Delete key on highlighted rows. Buttons and the full panel menu: New Layer/Sublayer (Alt: options, Ctrl: on top), Duplicate, Delete, Options for Selection, clipping mask, isolation, Locate Object, Merge Selected, Flatten Artwork, Collect in New Layer, Release to Layers (Sequence and Build), Reverse Order, Template, Hide/Outline/Lock Others and Show/Preview/Unlock All, Paste Remembers Layers, Panel Options (row size, thumbnails per kind, Show Layers Only). Layer Options: name, colour (presets, each with a chip of its colour, or custom), Template, Lock, Show, Print, Preview (outline drawing and clicking) and Dim Images to %. Every operation is a command (`layer.move`, `layer.highlight`, `layer.merge`…) with validation against cycles and invalid nesting. A document opens with only its top-level layers open; the rows left open are saved in the native file (nothing is written for the default) and reopen that way. Only the rows scrolled into view are laid out, from a row list made once per change: a layer of 5,000 groups of 10 paths, all open, draws the panel in 0.4 ms a frame instead of about 29 s (#638). With Paste Remembers Layers on, art copied from a sublayer pastes back into that sublayer, as [the help page](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=223) describes art going back to the layer it was copied from: in the same document while the sublayer is still there, two sublayers of the same name in different layers kept apart; in another document by the names of the sublayer and the layers around it. These rules are VectorCraft's own: a missing sublayer is made inside its layer (a missing layer on top, with the sublayer inside it), in the paste's one undo step; of layers with the same names, the topmost chain that matches the most names wins, a shown and unlocked one first; a matched layer that is hidden or locked, or inside one that is, refuses the paste, and nothing is pasted. diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 5391e3dc5b..26997e4a1e 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -249,7 +249,7 @@ tools, never checked side by side) isn't captured row by row. | A double-click on a ruler adds a guide at the pointer: a vertical one on the top ruler, a horizontal one on the left ruler (swapped in a view turned 90°, where the rulers read the other document axis; the nearer axis in between), exactly where the pointer is (no snapping), shown even with guides hidden, one undo step (`guide.add`); both clicks of the pair must be on that ruler, and the first adds nothing. The [public page on rulers](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/use-rulers.html) doesn't describe this gesture, so it follows the request in #5239 | done | #5239; an artboard guide with the Artboard tool, as a drag from a ruler makes one; `canvas/tests.rs` `double_clicking_a_ruler_adds_a_guide_at_that_position`, `a_canvas_click_then_a_ruler_click_adds_no_guide`, `a_ruler_double_click_follows_a_rotated_view` | | Escape cancels an existing ruler-guide press, move or copy | done | Selection and Direct/Group Selection; app-input regressions cover preselected guides, document/interaction-start selection, Undo/Redo and saved state, later on-canvas motion/release and temporary borrowing from idle Pen. All eight checks and the Direct Selection Escape control passed in current full CI. [Validation evidence](target-app-parity.md#evidence-what-ships-today-by-area) | | Ruler origin: corner drag with preview, snapped as a drawn point is (Smart Guides, Snap to Point and the ruler guides, pixels, the grid), double-click reset to the active artboard, relative X/Y fields, native save/reopen | done | #1212; `document.setRulerOrigin`, `document.resetRulerOrigin`; geometry and command coordinates stay absolute | -| Ruler guides as Layers rows: shown, hidden, locked and deleted with their layer; rows dragged to another layer | done | `guide.setLayer`; guides from older files go on a layer | +| Ruler guides as Layers rows: shown, hidden, locked and deleted with their layer; rows dragged to another layer; each row's own eye and lock; a row dropped on the trash deletes its guide | done | `guide.setLayer`; guides from older files go on a layer; `layer.setProps` on a guide's id hides or locks it alone; Object › Lock/Hide › Selection, Unlock All and Show All reach guides; `guide.remove {indexes}` | | Objects made into guides: drawn in the guide colour and style of Preferences; Lock Guides locks them too (no select, move or delete); a dragged selection snaps to ruler guides with Smart Guides on, by the nearest point of the path when pressed on its stroke or beside its edge, so the path lands exactly on the guide | done | #1534 (#1543, #1583); #3701 | | A selected ruler guide's X or Y in the Transform panel; typing a value moves it | not scored | #1659 (part of #1597); several guides move together; not in Properties or the Control bar. Not established by the documentation we could find: the help pages on guides, rulers and the Transform, Control and Properties panels (read again on 2026-10-14) don't describe it, and the one public statement is a user's [community answer](https://community.adobe.com/questions-652/adding-a-new-custom-guide-785586), which is not documentation. Kept as a convenience pending the owner's decision; no parity claim | | Alt swaps a ruler guide's orientation while dragging | missing | Alt-drag copies the selected guides ([Use rulers](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/use-rulers.html)); `guide.move` `{copy: true}` | From fc70b08f71da281fbdfa9502e2d29555bdd60a42 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 06:16:58 -0800 Subject: [PATCH 08/25] Blend: a blend without a spine shows the Appearance widget A blend made with Create Spine set to Never now shows the Appearance widget with the Selection and Blend tools, so its color Shift can be dragged on the canvas as on a blend with a spine. The Easing widget stays hidden, since easing needs a spine. The widget sits 16 px above the halfway point, by length, of the straight lines between the key centers that the steps are laid out along, and a drag follows those lines' direction there. The lines are not drawn. `blend_layout_line` exposes that line; `blend_spine` still returns `None` for such a blend. --- crates/doc/src/blend.rs | 30 +++++++++++ crates/doc/src/live.rs | 2 +- crates/engine/src/tests/blendopts.rs | 41 ++++++++++++++ crates/tools/src/blendwidget.rs | 78 +++++++++++++++++++++++---- crates/ui-egui/src/canvas/overlays.rs | 4 +- docs/gaps.md | 2 +- docs/mcp.md | 5 +- docs/target-app-parity.md | 4 +- docs/ui-parity.md | 2 +- 9 files changed, 150 insertions(+), 18 deletions(-) diff --git a/crates/doc/src/blend.rs b/crates/doc/src/blend.rs index d9e179286f..ac06205d7a 100644 --- a/crates/doc/src/blend.rs +++ b/crates/doc/src/blend.rs @@ -1369,6 +1369,14 @@ pub fn blend_spine(keys: &[Arc], spec: &BlendSpec) -> Option<(PathData, Op layout_spine(keys, spec) } +/// The line the steps of a blend of `keys` are placed along: [`blend_spine`]'s path for a blend +/// with a spine, and the straight lines between the key centers, in key order, for a blend made +/// without one ([`BlendSpec::no_spine`]). For a blend without a spine the line places the steps +/// only; it is not a spine and is not drawn as one. `None` with fewer than two keys. +pub fn blend_layout_line(keys: &[Arc], spec: &BlendSpec) -> Option { + layout_spine(keys, spec).map(|(path, _)| path) +} + /// The spine `spec` stores, unless the blend was made without one. fn stored_spine(spec: &BlendSpec) -> Option<&PathData> { spec.spine.as_ref().filter(|_| !spec.no_spine) @@ -1840,6 +1848,28 @@ mod tests { assert_eq!(moved.subpaths[0].anchors[2].p, Point::new(305.0, 5.0)); } + #[test] + fn a_blend_without_a_spine_has_a_layout_line_through_its_key_centers() { + let at = + |x: f64, y: f64| Arc::new(Node::path(NodeId(1), shapes::rectangle(Rect::new(x - 5.0, y - 5.0, x + 5.0, y + 5.0)), Appearance::default())); + let line_of = |path: &PathData| path.subpaths.iter().flat_map(|s| s.anchors.iter().map(|a| a.p)).collect::>(); + // A stored spine is ignored once the blend is made without one. + let stored = PathData::single(SubPath::polyline(&[Point::new(0.0, 50.0), Point::new(300.0, 50.0)], false)); + let spec = BlendSpec { no_spine: true, spine: Some(stored), ..Default::default() }; + for keys in [vec![at(10.0, 20.0), at(110.0, 20.0)], vec![at(10.0, 20.0), at(110.0, 20.0), at(110.0, 220.0), at(-40.0, 0.0)]] { + assert!(blend_spine(&keys, &spec).is_none(), "still no spine"); + let line = blend_layout_line(&keys, &spec).unwrap(); + assert_eq!(line.subpaths.len(), 1); + assert!(!line.subpaths[0].closed); + let centers: Vec = keys.iter().map(|k| center_of(k)).collect(); + assert_eq!(line_of(&line), centers, "in key order"); + } + // With a spine, the layout line is the spine. + let keys = vec![key(0.0), key(100.0), key(300.0)]; + assert_eq!(blend_layout_line(&keys, &BlendSpec::default()), blend_spine(&keys, &BlendSpec::default()).map(|(p, _)| p)); + assert!(blend_layout_line(&keys[..1], &spec).is_none(), "one key"); + } + #[test] fn steps_follow_a_bent_spine() { let keys = vec![key(0.0), key(100.0)]; diff --git a/crates/doc/src/live.rs b/crates/doc/src/live.rs index 39fe8cbc43..b1d94c1c8b 100644 --- a/crates/doc/src/live.rs +++ b/crates/doc/src/live.rs @@ -39,7 +39,7 @@ fn fifty() -> f64 { // ===================================================================================== pub use crate::blend::{ - Spine, blend_expand, blend_spine, blend_step_count, lerp_appearance, lerp_color, lerp_node, lerp_paint, lerp_path, pin_spine, + Spine, blend_expand, blend_layout_line, blend_spine, blend_step_count, lerp_appearance, lerp_color, lerp_node, lerp_paint, lerp_path, pin_spine, steps_knockout_shows, }; diff --git a/crates/engine/src/tests/blendopts.rs b/crates/engine/src/tests/blendopts.rs index 93f531d1e8..05fbf1a72e 100644 --- a/crates/engine/src/tests/blendopts.rs +++ b/crates/engine/src/tests/blendopts.rs @@ -542,6 +542,47 @@ fn dragging_a_blend_widget_is_one_undo_step_and_a_click_or_escape_none() { assert_eq!(spec(&s, g).1.color_shift, 0.0); } +/// A blend made without a spine has the Appearance widget alone: a drag of it with the Selection +/// tool or the Blend tool changes the color shift in one undo step, and there is no Easing widget +/// to drag. +#[test] +fn dragging_the_appearance_widget_of_a_blend_without_a_spine_is_one_undo_step() { + let mut s = session(); + let (a, b) = (rect(&mut s, 0.0, 0.0, 40.0), rect(&mut s, 200.0, 0.0, 40.0)); + sel(&mut s, &[a, b]); + let g = id_of(&s.execute("object.blend.make", &json!({"steps": 3, "createSpine": "never", "orientation": "path"})).unwrap()); + assert!(spec(&s, g).1.no_spine); + let v = ViewInfo::default(); + let depth = |s: &Session| s.doc().unwrap().history.undo.len(); + let ptr = |s: &mut Session, kind: PointerKind, x: f64, y: f64| { + s.pointer(&PointerEvent::new(kind, x, y), ViewInfo::default()).unwrap(); + }; + for (n, tool) in [(1.0, "selection"), (2.0, "blend")] { + s.select_tool(tool, v).unwrap(); + sel(&mut s, &[g]); + let d0 = depth(&s); + // The Appearance widget sits 16 px above the halfway point (120, 20) of the line between + // the key centers. + ptr(&mut s, PointerKind::Down, 120.0, 4.0); + ptr(&mut s, PointerKind::Drag, 135.0, 4.0); + ptr(&mut s, PointerKind::Up, 135.0, 4.0); + let sp = spec(&s, g).1; + assert_eq!((sp.color_shift, sp.ease.ramp, depth(&s)), (15.0 * n, 0.0, d0 + 1), "{tool}"); + assert_eq!(s.doc().unwrap().selection.objects, vec![g], "{tool}: the blend stays selected"); + } + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(spec(&s, g).1.color_shift, 15.0, "each drag is its own undo step"); + // 16 px below there is no widget: a drag there leaves the easing and the color shift alone. + s.select_tool("selection", v).unwrap(); + sel(&mut s, &[g]); + let before = spec(&s, g).1; + ptr(&mut s, PointerKind::Down, 120.0, 36.0); + ptr(&mut s, PointerKind::Drag, 150.0, 36.0); + ptr(&mut s, PointerKind::Up, 150.0, 36.0); + let after = spec(&s, g).1; + assert_eq!((after.ease, after.color_shift), (before.ease, before.color_shift), "no Easing widget"); +} + #[test] fn native_blend_easing_values_clamp_and_non_finite_become_default() { for (bad, ramp, shift) in [ diff --git a/crates/tools/src/blendwidget.rs b/crates/tools/src/blendwidget.rs index af1194d78b..e09df663bb 100644 --- a/crates/tools/src/blendwidget.rs +++ b/crates/tools/src/blendwidget.rs @@ -5,8 +5,11 @@ //! the canvas draws from the halfway point to the widget grows with it. The upper one sets the //! blend's color shift (`colorShift`, -100 to 100) and the lower one its easing strength (`ramp`, //! 0 to 100). The lower one shows only when the steps follow a spine (a replaced or edited spine, -//! or Align to Path), where easing moves them; a blend made without a spine shows neither. A drag along the spine's direction at the press -//! changes the value by one per screen pixel, starting from the value at the press, and the arrow +//! or Align to Path), where easing moves them. A blend made without a spine shows the upper one +//! alone, placed in the same way against the straight lines between its key centers that its steps +//! are laid out along ([`blend_layout_line`]); the canvas does not draw those lines. A drag along +//! the spine's direction at the press changes the value by one per screen pixel, starting from the +//! value at the press, and the arrow //! keys during the drag change it by one (Shift: by ten); Escape or a switch to another tool //! cancels the drag and puts the value back. Each drag previews //! `object.blend.setEasing` and is one undo step, or none when the value ends where it started; a @@ -14,7 +17,7 @@ //! from the same geometry. use serde_json::json; -use vectorcraft_doc::live::{Spine, blend_spine}; +use vectorcraft_doc::live::{Spine, blend_layout_line}; use vectorcraft_doc::{Document, Node, NodeId, NodeKind, Selection}; use vectorcraft_geom::{Point, Rect, Vec2}; @@ -69,7 +72,8 @@ impl BlendControl { pub struct BlendWidget { pub id: NodeId, pub control: BlendControl, - /// The spine's halfway point, in the document. + /// The spine's halfway point, in the document (for a blend without a spine, the halfway point of + /// the line its steps are laid out along). pub on: Point, /// The widget's center in the document: [`OFFSET_PX`] from `on`, or further out where other /// artwork crowds that spot. @@ -84,9 +88,10 @@ impl BlendWidget { /// The widgets of the selection at `zoom` (screen px per document point), with `up` the /// document direction of the screen's up: the Appearance widget, then the Easing widget. Empty /// unless the selection is one whole blend, visible and unlocked, with two or more keys and a - /// spine of some length, and no anchors are selected. Each widget sits at the first spot out - /// from the spine, in [`OFFSET_PX`] steps, that the boxes of fewer than three other visible - /// objects hold, at most nine steps out; where every spot is crowded it stays at the first. + /// spine (or, without one, a step layout line) of some length, and no anchors are selected. + /// Each widget sits at the first spot out from the spine, in [`OFFSET_PX`] steps, that the + /// boxes of fewer than three other visible objects hold, at most nine steps out; where every + /// spot is crowded it stays at the first. pub fn of(doc: &Document, selection: &Selection, zoom: f64, up: Vec2) -> Vec { let up_len = up.hypot(); let usable = |v: f64| v.is_finite() && v > 0.0; @@ -98,7 +103,7 @@ impl BlendWidget { if children.len() < 2 || !doc.is_editable(*id) { return vec![]; } - let Some(spine) = blend_spine(children, spec).and_then(|(path, _)| Spine::new(&path)) else { return vec![] }; + let Some(spine) = blend_layout_line(children, spec).and_then(|path| Spine::new(&path)) else { return vec![] }; if !usable(spine.length()) { return vec![]; } @@ -430,9 +435,60 @@ mod tests { // One key. let (d, _, s) = blend_doc(&[(100.0, 200.0)], eased()); assert!(BlendWidget::of(&d, &s, 1.0, UP).is_empty(), "one key"); - // A blend made without a spine (Create Spine › Never), Align to Path included. - let (d, _, s) = blend_doc(&[(100.0, 200.0), (300.0, 200.0)], BlendSpec { no_spine: true, ..eased() }); - assert!(BlendWidget::of(&d, &s, 1.0, UP).is_empty(), "no spine"); + // Without a spine: locked or hidden, or keys on one spot. + let (d, id, s) = blend_doc(&[(100.0, 200.0), (300.0, 200.0)], BlendSpec { no_spine: true, ..eased() }); + for hide in [false, true] { + let mut d = d.clone(); + let n = d.node_mut(id).unwrap(); + (n.visible, n.locked) = (!hide, !hide); + assert!(BlendWidget::of(&d, &s, 1.0, UP).is_empty(), "no spine, hidden: {hide}"); + } + let (d, _, s) = blend_doc(&[(100.0, 200.0), (100.0, 200.0)], BlendSpec { no_spine: true, ..eased() }); + assert!(BlendWidget::of(&d, &s, 1.0, UP).is_empty(), "no spine, no length"); + } + + /// A blend made without a spine (Create Spine › Never), Align to Path included, shows the + /// Appearance widget alone, at the halfway point by length of the straight lines between its + /// key centers. + #[test] + fn a_blend_without_a_spine_shows_the_appearance_widget_alone() { + let no_spine = || BlendSpec { no_spine: true, ..eased() }; + let (d, id, s) = blend_doc(&[(100.0, 200.0), (300.0, 200.0)], no_spine()); + let w = BlendWidget::of(&d, &s, 1.0, UP); + assert_eq!(w.iter().map(|w| w.control).collect::>(), [BlendControl::Appearance], "{w:?}"); + assert!(w[0].id == id && near(w[0].on, Point::new(200.0, 200.0)) && near(w[0].at, Point::new(200.0, 184.0)), "{w:?}"); + assert_eq!(w[0].value, -20.0); + // Halfway along by length, not the middle key: (0, 0), (100, 0), (100, 300) is 400 long. + let (d, _, s) = blend_doc(&[(0.0, 0.0), (100.0, 0.0), (100.0, 300.0)], no_spine()); + let w = BlendWidget::of(&d, &s, 1.0, UP); + assert!(w.len() == 1 && near(w[0].on, Point::new(100.0, 100.0)), "{w:?}"); + // There the line runs down, so a drag down adds. + assert!(near(Point::new(w[0].along.x, w[0].along.y), Point::new(0.0, 1.0)), "{w:?}"); + // Two keys on one spot and a third away: the line still has length. + let (d, _, s) = blend_doc(&[(100.0, 200.0), (100.0, 200.0), (300.0, 200.0)], no_spine()); + let w = BlendWidget::of(&d, &s, 1.0, UP); + assert!(w.len() == 1 && near(w[0].on, Point::new(200.0, 200.0)), "{w:?}"); + } + + /// With the Selection or the Blend tool, a drag of a spineless blend's Appearance widget + /// previews the color shift alone, in one undo step. + #[test] + fn dragging_the_appearance_widget_of_a_blend_without_a_spine() { + let (d, id, s) = blend_doc(&[(100.0, 200.0), (300.0, 200.0)], BlendSpec { no_spine: true, ..eased() }); + let p = paint(); + let c = cx(&d, &s, &p); + let at = Point::new(200.0, 184.0); + assert!(over_widget(&c, at) && !over_widget(&c, Point::new(200.0, 216.0)), "no Easing widget below"); + let tools: [Box; 2] = [Box::new(SelectionTool::default()), Box::new(crate::meshblend::BlendTool::default())]; + for mut t in tools { + assert!(t.pointer(&c, &ev(PointerKind::Down, at)).is_empty()); + let a = t.pointer(&c, &ev(PointerKind::Drag, at + Vec2::new(30.0, 0.0))); + assert_eq!( + a, + vec![Action::Begin(LABEL.into()), Action::Preview("object.blend.setEasing".into(), json!({"id": id.0, "colorShift": 10.0}))] + ); + assert_eq!(t.pointer(&c, &ev(PointerKind::Up, at + Vec2::new(30.0, 0.0))), vec![Action::Commit]); + } } /// A drag of the Easing widget along the spine changes the ramp by one per pixel from its diff --git a/crates/ui-egui/src/canvas/overlays.rs b/crates/ui-egui/src/canvas/overlays.rs index 7eb31f7d01..aefd9253e9 100644 --- a/crates/ui-egui/src/canvas/overlays.rs +++ b/crates/ui-egui/src/canvas/overlays.rs @@ -252,7 +252,9 @@ pub(super) fn selection_overlay(app: &mut VectorcraftApp, p: &egui::Painter, xf: /// The Appearance and Easing widgets of one selected blend (Selection and Blend tools), each joined /// by a line to the spine's halfway point: the Appearance widget hollow above it, the Easing widget -/// filled below it. Drawn with the edges hidden too, as they are controls. +/// filled below it. For a blend without a spine the line goes to the halfway point of the straight +/// lines between its key centers, which are not drawn. Drawn with the edges hidden too, as they are +/// controls. pub(super) fn blend_widgets_overlay(app: &VectorcraftApp, p: &egui::Painter, xf: &Xf) { use vectorcraft_tools::blendwidget::{BlendControl, BlendWidget, RADIUS_PX}; if !matches!(app.session.tool_id(), "selection" | "blend") { diff --git a/docs/gaps.md b/docs/gaps.md index d34956d4e0..4c492fb5b3 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -541,7 +541,7 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi Ease Out In), Ramp 0–100% and independent color Shift; easing is disabled without a spine. The original polynomial distributions approximate the public description. With the Selection or Blend tool, on-canvas widgets on a blend with a spine set the color Shift and, when the steps follow - that spine, the Ramp; a blend made without a spine shows neither widget. The Blend panel shows the + that spine, the Ramp; a blend made without a spine shows the color Shift widget alone. The Blend panel shows the values they set. [Public source](https://helpx.adobe.com/illustrator/desktop/manage-colors/apply-transparency-and-blending/blend-panel-overview.html). - **Done:** gradient Dither (30.0): the Gradient panel's Dither box (`paint.editGradient` `dither`, also in `paint.setFill`'s diff --git a/docs/mcp.md b/docs/mcp.md index 274db05a34..14d6838506 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -9769,8 +9769,9 @@ the Selection and Blend tools show the same values as widgets 16 px above and below the spine's halfway point (where the boxes of three or more other visible objects hold that spot, a widget moves out in 16 px steps, up to 144 px, joined to the halfway point by a line): the upper one sets `colorShift` and the lower one, shown only when the steps follow the spine as `ramp` needs, sets `ramp`, by one per screen pixel dragged along the spine and by one per arrow key -during the drag (ten with Shift). Each drag is one undo step, and `press_key` Escape or a switch to another tool -during it puts the value back: +during the drag (ten with Shift). A blend made without a spine shows the upper widget alone, placed against the +straight lines between its key centers that its steps are laid out along, which are not drawn. Each drag is one undo +step, and `press_key` Escape or a switch to another tool during it puts the value back: ```json {"name":"run_command","arguments":{"command":"object.blend.setEasing","params":{"id":40,"ramp":35}}} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f04ee3c910..223dbc591a 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1780,7 +1780,9 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Blend, mesh and envelope points by number:** `object.blend.spine.moveAnchor`, `reshapeSegment` and `removeAnchor`, `object.mesh.setPointColor`, `movePoint` and `deletePoint`, and `object.envelope.setMeshPoint` refuse an `anchor`, `segment` or `index` that is not a whole number, and `object.envelope.setMeshPoint` refuses a negative `index`. Specified Steps (`object.blend.make`, `object.blend.options`) and the rows and columns of `object.mesh.create`, `object.envelope.makeWithMesh` and `resetWithMesh` must be whole numbers too. -- **Blend widgets on the canvas:** with one blend selected that has a spine, the Selection and Blend tools show two widgets 16 px above and below the spine's halfway point (further out, joined to that point by a line, where the boxes of three or more other objects crowd the spot), as the [Blend panel help page](https://helpx.adobe.com/illustrator/desktop/manage-colors/apply-transparency-and-blending/blend-panel-overview.html) describes an upper widget for Appearance and a lower one for Easing. The upper one sets Shift and the lower one Ramp, keeping the Type, and the lower one shows only when the steps follow that spine; a blend made without a spine shows neither. A drag along the spine changes the value by one per screen pixel from its value at the press, the arrow keys during the drag by one (Shift: ten), and Escape or a tool switch cancels it. A drag is one undo step, or none when the value ends where it started. The placement, the drag and the keys are VectorCraft's own rules. `object.blend.setEasing` sets the same values for agents. Evidence: `blendwidget::tests`, `tests::blendopts::{set_easing_edits_one_blend_and_refuses_what_it_cannot_set, dragging_a_blend_widget_is_one_undo_step_and_a_click_or_escape_none}`, `shortcuts::tests::shift_arrows_step_a_pressed_blend_widget_by_ten`. +- **Blend widgets on the canvas:** with one blend selected that has a spine, the Selection and Blend tools show two widgets 16 px above and below the spine's halfway point (further out, joined to that point by a line, where the boxes of three or more other objects crowd the spot), as the [Blend panel help page](https://helpx.adobe.com/illustrator/desktop/manage-colors/apply-transparency-and-blending/blend-panel-overview.html) describes an upper widget for Appearance and a lower one for Easing. The upper one sets Shift and the lower one Ramp, keeping the Type, and the lower one shows only when the steps follow that spine. A drag along the spine changes the value by one per screen pixel from its value at the press, the arrow keys during the drag by one (Shift: ten), and Escape or a tool switch cancels it. A drag is one undo step, or none when the value ends where it started. The placement, the drag and the keys are VectorCraft's own rules. `object.blend.setEasing` sets the same values for agents. Evidence: `blendwidget::tests`, `tests::blendopts::{set_easing_edits_one_blend_and_refuses_what_it_cannot_set, dragging_a_blend_widget_is_one_undo_step_and_a_click_or_escape_none}`, `shortcuts::tests::shift_arrows_step_a_pressed_blend_widget_by_ten`. + +- **Blend widgets without a spine:** a blend made with Create Spine set to Never shows the Appearance widget alone with the Selection and Blend tools, and its drag sets Shift as on a blend with a spine; there is no Easing widget, as the [Blend panel help page](https://helpx.adobe.com/illustrator/desktop/manage-colors/apply-transparency-and-blending/blend-panel-overview.html) makes Easing available only on a blend with a spine. The widget sits 16 px above the halfway point, by length, of the straight lines between the key centers that the steps are laid out along, and a drag follows those lines' direction there; the lines are not drawn. Showing the widget without a spine and its placement are VectorCraft's own rules. Evidence: `blendwidget::tests::{a_blend_without_a_spine_shows_the_appearance_widget_alone, dragging_the_appearance_widget_of_a_blend_without_a_spine}`, `tests::blendopts::dragging_the_appearance_widget_of_a_blend_without_a_spine_is_one_undo_step`, `blend::tests::a_blend_without_a_spine_has_a_layout_line_through_its_key_centers`. - **Blend, mesh and envelope numbers given as text:** `object.blend.make` and `object.blend.options` (`steps`, `distance`, `value`), `object.envelope.makeWithWarp`, `resetWithWarp` and `options` (`bend`, `h`, `v`, `horizontalDistortion`, `verticalDistortion`), `object.envelope.makeWithMesh` and `resetWithMesh` (`rows`, `cols`, `columns`), `object.envelope.options` (`fidelity`), `object.mesh.create` (`rows`, `cols`, `columns`, `highlight`) and `object.mesh.setPointColor` (`opacity`) refuse a value other than a number or null, such as `"8"`, and change nothing. `object.mesh.create` refuses an `at` that is not `[x, y]`. diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 5391e3dc5b..2850f60ca4 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -436,7 +436,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Canvas context menu | done | Layers rows, panels and type have none (gap) | | SVG Interactivity panel: JavaScript for each object's events and the document's linked JavaScript files, written to SVG and read back as text | done | `svgInteractivity.*`, `ui.javascriptFilesDialog` | | Retype, Comments, Version History panels | missing | the last two are cloud features (out of scope) | -| Blend panel (30.7) | partial | Window › Blend provides Type (Ease In, Ease Out, Ease In Out, Ease Out In), Ramp 0–100% and independent color Shift, alongside the existing blend controls. Easing is disabled without a spine. Original polynomial distributions approximate the publicly documented behavior; on-canvas easing handles remain missing. [Public source](https://helpx.adobe.com/illustrator/desktop/manage-colors/apply-transparency-and-blending/blend-panel-overview.html) | +| Blend panel (30.7) | partial | Window › Blend provides Type (Ease In, Ease Out, Ease In Out, Ease Out In), Ramp 0–100% and independent color Shift, alongside the existing blend controls. Easing is disabled without a spine. Original polynomial distributions approximate the publicly documented behavior. On-canvas Appearance and Easing widgets set Shift and Ramp; a blend without a spine shows the Appearance widget alone. [Public source](https://helpx.adobe.com/illustrator/desktop/manage-colors/apply-transparency-and-blending/blend-panel-overview.html) | | Gradient panel: Dither (30.0) | done | Dither box under the stops (`paint.editGradient` `dither`); dimmed behind the Stroke proxy, fills only; `panels::gradient` test | | Gradient panel: Method, Classic or Perceptual (30.0) | done | Method menu under the Stroke buttons for linear and radial gradients (`paint.editGradient` `method`); [public source](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-gradients/control-perceptual-interpolation-in-gradients.html); `panels::gradient` test | | Gradient panel: Presets (30.0) | done | Presets menu by library (theme) plus Saved: applies a preset to the gradient behind the active proxy, keeping its placement, one undo step; panel menu Save Gradient Preset…, Delete Gradient Preset, Hide/Show Presets (`gradient.presets.*`); `panels::gradient` tests | From 4091f110b1ca6d12d6639dfba2348e8c2173c94a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 06:19:54 -0800 Subject: [PATCH 09/25] Scripts: $.line and $.stack give the line of the file the code is in $.line and $.stack counted lines in the run's expanded source. In code that comes after an #include they gave lines that match no file, and this included code in a file $.evalFile ran and code a named engine kept from an earlier run. Both now map each frame through the run's source maps, as uncaught errors already were. $.stack writes each frame as name@file:line, outermost first, with the run's name as the file of a script given as source. Code that eval or Function compiled keeps the line of the source they compiled, in [eval]; code whose place a named engine no longer keeps is at line 0 of [unknown]. The 64-frame limit, [global] and [anonymous] are unchanged. Docs: docs/mcp.md, docs/target-app-parity.md. --- crates/engine/src/script/mod.rs | 35 ++++++++++++++++++ crates/engine/src/tests/script_dollar.rs | 4 +-- crates/engine/src/tests/script_engines.rs | 38 ++++++++++++++++++++ crates/engine/src/tests/script_include.rs | 43 +++++++++++++++++++++++ crates/js/src/builtins/extensions.rs | 25 ++++++++++--- crates/js/src/extension_tests.rs | 26 ++++++++++++++ crates/js/src/interp.rs | 3 ++ crates/js/src/lib.rs | 2 +- crates/js/src/realm.rs | 11 ++++++ docs/mcp.md | 2 +- docs/target-app-parity.md | 1 + 11 files changed, 182 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 53f6e18f75..e82ab1e275 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -822,6 +822,34 @@ impl Host { } } + /// The file and line that line `line` of the source with tag `tag` came from, as `$.line` and + /// `$.stack` give them: the run's script, a file it included or a file `$.evalFile` gave, in + /// this run or in an earlier run of its named engine, with the run's name standing for a script + /// given as text. Code that `eval` or `Function` compiled has no map and keeps its own line, + /// named `[eval]`; code whose map is gone, such as one the named engine let go to stay within + /// [`KEPT_MAP_BYTES`], is at line 0 of `[unknown]`. + fn source_place(&self, tag: u32, line: u32) -> (String, u32) { + if tag == vectorcraft_js::UNKNOWN_SOURCE { + return ("[eval]".to_string(), line); + } + let named = |map: &include::SourceMap, script: Option<&Arc>| { + let (index, file, line, _) = map.locate(line, 1); + match script { + Some(name) if index == 0 && file.is_empty() => (name.to_string(), line), + _ => (file.to_string(), line), + } + }; + let script = self.script_tag.get(); + let placed = match tag.checked_sub(script).filter(|_| script != vectorcraft_js::UNKNOWN_SOURCE) { + Some(0) => self.script_map.try_borrow().ok().map(|m| named(&m, Some(&self.report_name))), + Some(n) => self.eval_maps.try_borrow().ok().and_then(|maps| maps.get(n as usize - 1).map(|m| named(m, None))), + None => { + self.kept_maps.as_ref().and_then(|k| k.try_borrow().ok()).and_then(|k| k.get(tag).map(|kept| named(&kept.map, kept.script.as_ref()))) + } + }; + placed.unwrap_or_else(|| ("[unknown]".to_string(), 0)) + } + /// Adds a line to the run's console and, during a slice, to the session's. fn line(&self, entry: console::Entry, cut: bool) { let line = console::ConsoleLine { run: self.run, name: self.name.clone(), entry }; @@ -1858,6 +1886,13 @@ impl Session { Ok(expanded) => { *host.script_map.borrow_mut() = expanded.map; realm.set_strict_writes(expanded.strict == Some(true)); + if fresh { + let l = link.clone(); + realm.set_source_locator(Rc::new(move |tag, line| match current(&l) { + Ok(h) => h.source_place(tag, line), + Err(_) => ("[unknown]".to_string(), 0), + })); + } (if fresh { realm.add_script_extensions() } else { Ok(()) }) .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(()) }) diff --git a/crates/engine/src/tests/script_dollar.rs b/crates/engine/src/tests/script_dollar.rs index 57ff9b15cd..849d5b9080 100644 --- a/crates/engine/src/tests/script_dollar.rs +++ b/crates/engine/src/tests/script_dollar.rs @@ -63,7 +63,7 @@ fn each_member_has_its_value() { ("$.memCache", json!(0)), ("$.os", json!(os)), ("$.screens.length", json!(0)), - ("$.stack", json!("[global]:1\n")), + ("$.stack", json!("[global]@t.js:1\n")), ("$.strict", json!(false)), ("$.version", json!(version)), ("typeof $.getenv + typeof $.setenv + typeof $.sleep", json!("functionfunctionfunction")), @@ -165,7 +165,7 @@ fn getenv_reads_only_its_names_and_setenv_changes_only_the_run() { fn error_line_and_stack_follow_the_running_code() { let mut s = Session::new(); let source = "try { null.x; } catch (e) {}\nfunction where() {\n return [$.line, $.stack, $.error instanceof TypeError];\n}\nvc.log(where());"; - assert_eq!(logged(&mut s, source)[0], json!([3, "[global]:5\nwhere:3\n", true])); + assert_eq!(logged(&mut s, source)[0], json!([3, "[global]@t.js:5\nwhere@t.js:3\n", true])); assert_eq!(value(&mut s, "$.error"), json!(null), "each run starts without one"); } diff --git a/crates/engine/src/tests/script_engines.rs b/crates/engine/src/tests/script_engines.rs index 7e768c5875..5edec3b1c9 100644 --- a/crates/engine/src/tests/script_engines.rs +++ b/crates/engine/src/tests/script_engines.rs @@ -230,6 +230,44 @@ fn an_engine_keeps_the_newest_places_within_its_budget() { assert_eq!((d_place.0, d_place.1, d_place.2), (None, 0, 0), "a map larger than the budget is not kept"); } +/// `$.line` and `$.stack` in code an earlier run of a named engine compiled give the line of that +/// run's file: its script, or a file it included; a script given as text is named by that run's +/// name. Code `eval` and `Function` compiled keeps its own line, in `[eval]`, and code whose place +/// the engine did not keep is at line 0 of `[unknown]`. +#[test] +fn the_line_and_the_stack_of_code_an_earlier_run_kept_are_at_that_runs_files() { + use super::script_include::short_stack; + let base: PathBuf = std::env::temp_dir().join(format!("vc-script-engines-line-stack-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + std::fs::create_dir_all(&base).unwrap(); + std::fs::write(base.join("inc.jsxinc"), "\n\nfunction fromInclude() {\n return [$.line, $.stack];\n}").unwrap(); + let def = base.join("def.jsx"); + std::fs::write(&def, "#targetengine e\nvar pad = 1;\n#include \"inc.jsxinc\"\nfunction fromMain() {\n return fromInclude();\n}").unwrap(); + let mut s = Session::new(); + s.execute("script.run", &json!({"path": def.to_string_lossy()})).unwrap(); + run(&mut s, "#targetengine e\n\nfunction fromText() {\n return $.stack;\n}").unwrap(); + let call = |s: &mut Session, code: &str| { + let r = s.execute("script.run", &json!({"source": format!("#targetengine e\n\n{code}"), "name": "caller.js"})); + r.unwrap_or_else(|e| panic!("{code}: {e}"))["log"][0].clone() + }; + let r = call(&mut s, "vc.log(fromMain());"); + assert_eq!(r[0], 4, "{r}"); + assert_eq!(short_stack(&r[1]), "[global]@caller.js:3\nfromMain@def.jsx:5\nfromInclude@inc.jsxinc:4\n"); + assert_eq!(short_stack(&call(&mut s, "vc.log(fromText());")), "[global]@caller.js:3\nfromText@t.js:4\n"); + assert_eq!(call(&mut s, "vc.log(eval('\\n\\n$.line'));"), 3); + assert_eq!(call(&mut s, "vc.log(eval('\\n$.stack'));"), "[global]@caller.js:3\n[global]@[eval]:2\n"); + let r = call(&mut s, "vc.log(new Function('\\nreturn $.stack;')());"); + assert_eq!(r, "[global]@caller.js:3\n[anonymous]@[eval]:4\n", "the line of the function source `Function` compiles"); + // A map larger than the budget is not kept. + TEST_KEPT_MAP_BYTES.with(|b| b.set(Some(1))); + let lost = run(&mut s, "#targetengine e\n\n\nfunction lost() {\n return [$.line, $.stack];\n}"); + let r = lost.map(|_| call(&mut s, "vc.log(lost());")); + TEST_KEPT_MAP_BYTES.with(|b| b.set(None)); + let r = r.unwrap(); + assert_eq!(r, json!([0, "[global]@caller.js:3\nlost@[unknown]:0\n"])); + let _ = std::fs::remove_dir_all(base); +} + /// A run of a named engine whose script does not compile defines no code, so it keeps no place /// and pushes out none of the places kept before. An included file without a preprocessor line is /// first parsed with the script it joins, so its syntax error ends the run as it starts. diff --git a/crates/engine/src/tests/script_include.rs b/crates/engine/src/tests/script_include.rs index e5acc536cc..1d487e44bf 100644 --- a/crates/engine/src/tests/script_include.rs +++ b/crates/engine/src/tests/script_include.rs @@ -454,6 +454,49 @@ fn script_included_error_has_local_file_and_line() { let _ = std::fs::remove_dir_all(base); } +/// `$.stack`'s text with each frame's file cut to its name: `function@name:line` a line. +pub(crate) fn short_stack(stack: &Value) -> String { + let stack = stack.as_str().unwrap_or_else(|| panic!("a stack: {stack}")); + stack + .lines() + .map(|frame| match (frame.split_once('@'), frame.rsplit_once(':')) { + (Some((name, _)), Some((place, line))) => { + let file = place.split_once('@').map_or(place, |(_, f)| f).rsplit(['/', '\\']).next().unwrap_or_default(); + format!("{name}@{file}:{line}\n") + } + _ => format!("{frame}\n"), + }) + .collect() +} + +/// `$.line` and `$.stack` give the line of the file the running code is in: the script, a file it +/// included (and a file that one included) or a file `$.evalFile` gave and the files it included, +/// whatever lines come before it in the run's expanded source. +#[test] +fn script_line_and_stack_are_at_the_line_of_each_file() { + let base = folder("line-stack"); + write( + &base.join("main/lib.jsxinc"), + "\nfunction libWhere() {\n return [$.line, $.stack];\n}\nvar libLine = $.line;\n#include \"deep.jsxinc\"\n", + ); + write(&base.join("main/deep.jsxinc"), "\n\nvar deepLine = $.line;\nfunction deepStack() {\n return $.stack;\n}"); + write(&base.join("main/sub/ev.jsx"), "#include \"inc.jsxinc\"\nfunction evWhere() {\n return incWhere();\n}\nevWhere();"); + write(&base.join("main/sub/inc.jsxinc"), "\n\nfunction incWhere() {\n return [$.line, $.stack];\n}"); + let text = "var a = 1;\nvar b = 2;\n#include \"lib.jsxinc\"\nvar mainLine = $.line;\nvc.log([libLine, deepLine, mainLine]);\n\ + vc.log(libWhere());\nvc.log(deepStack());\nvc.log($.evalFile('sub/ev.jsx'));"; + let log = run(&base, text).unwrap()["log"].clone(); + assert_eq!(log[0], json!([5, 3, 4]), "{log}"); + assert_eq!(log[1][0], 3, "{log}"); + assert_eq!(short_stack(&log[1][1]), "[global]@main.jsx:6\nlibWhere@lib.jsxinc:3\n"); + assert_eq!(short_stack(&log[2]), "[global]@main.jsx:7\ndeepStack@deep.jsxinc:5\n"); + assert_eq!(log[3][0], 4, "{log}"); + assert_eq!(short_stack(&log[3][1]), "[global]@main.jsx:8\n[global]@ev.jsx:5\nevWhere@ev.jsx:3\nincWhere@inc.jsxinc:4\n"); + // The file a frame names is the one `$.fileName` gives while that file runs. + let log = run(&base, "vc.log($.stack.slice(9, -3) === $.fileName);").unwrap()["log"].clone(); + assert_eq!(log, json!([true])); + let _ = std::fs::remove_dir_all(base); +} + /// Pumps the run in the app until it ends or waits at a dialog (`None`). fn pump(s: &mut Session) -> Option> { for _ in 0..10_000 { diff --git a/crates/js/src/builtins/extensions.rs b/crates/js/src/builtins/extensions.rs index 4ef9b82105..94ee226d57 100644 --- a/crates/js/src/builtins/extensions.rs +++ b/crates/js/src/builtins/extensions.rs @@ -388,18 +388,33 @@ fn last_error(interp: &mut Interp, _: Value, _: &[Value], _: bool) -> JsResult JsResult { - let line = interp.script_frames().last().map_or(0, |(code, pc, _)| code.line_column(pc.saturating_sub(1)).0); + let line = interp.script_frames().last().map_or(0, |(code, pc, _)| place(interp.locator.as_ref(), code, pc).1); Ok(Value::Number(f64::from(line))) } +/// Where the instruction before `pc` in `code` came from: the file the realm's locator names +/// (`None` without one) and the line there, or the line in the compiled source without a locator. +fn place(locator: Option<&crate::realm::SourceLocator>, code: &Code, pc: usize) -> (Option, u32) { + let line = code.line_column(pc.saturating_sub(1)).0; + match locator { + Some(locate) => { + let (file, line) = locate(code.source.tag, line); + (Some(file), line) + } + None => (None, line), + } +} + /// The most frames `$.stack` lists, and the most characters of a function's name it shows. const STACK_FRAMES: usize = 64; const STACK_NAME_UNITS: usize = 64; -/// The script's frames, outermost first, one a line: the function's name and the line it is at. +/// The script's frames, outermost first, one a line: the function's name and the line it is at, +/// as `name:line`, or as `name@file:line` with the file the realm's locator names. fn stack(interp: &mut Interp, _: Value, _: &[Value], _: bool) -> JsResult { let frames: Vec<(Rc, usize, bool)> = interp.script_frames().map(|(c, pc, f)| (c.clone(), pc, f)).collect(); let skip = frames.len().saturating_sub(STACK_FRAMES); + let locator = interp.locator.clone(); let mut text = String::new(); if skip > 0 { text.push_str("…\n"); @@ -407,8 +422,10 @@ fn stack(interp: &mut Interp, _: Value, _: &[Value], _: bool) -> JsResult for (code, pc, function) in frames.iter().skip(skip) { interp.use_fuel()?; let name = if *function { function_name(code) } else { "[global]".to_string() }; - let line = code.line_column(pc.saturating_sub(1)).0; - text.push_str(&format!("{name}:{line}\n")); + match place(locator.as_ref(), code, *pc) { + (Some(file), line) => text.push_str(&format!("{name}@{file}:{line}\n")), + (None, line) => text.push_str(&format!("{name}:{line}\n")), + } } let mut out = Builder::new(); out.push_str(interp, &text)?; diff --git a/crates/js/src/extension_tests.rs b/crates/js/src/extension_tests.rs index 8336643e4d..4807856bf5 100644 --- a/crates/js/src/extension_tests.rs +++ b/crates/js/src/extension_tests.rs @@ -219,6 +219,32 @@ fn script_items_read_the_global_object_the_last_error_the_line_and_the_stack() { assert!(thrown(&mut r, "'use strict'; h.line = 1").starts_with("TypeError"), "the items cannot be assigned"); } +#[test] +fn the_line_and_the_stack_give_the_place_the_source_locator_maps_each_frame_to() { + let mut r = realm(); + let items = [("line", ScriptItem::Line), ("stack", ScriptItem::Stack)].into_iter().map(|(n, i)| (n.to_string(), HostItem::Script(i))).collect(); + r.define_host_object("h", items).unwrap(); + let asked: Rc>> = Rc::default(); + let seen = asked.clone(); + r.set_source_locator(Rc::new(move |tag, line| { + seen.borrow_mut().push((tag, line)); + let file = if tag == UNKNOWN_SOURCE { "[eval]".to_string() } else { format!("f{tag}") }; + (file, line + 100) + })); + let source = "function inner() {\n return h.stack;\n}\n\ninner()"; + let stack = text(&mut r, source); + let tag = r.script_tag(); + assert_eq!(stack, format!("[global]@f{tag}:105\ninner@f{tag}:102\n")); + assert_eq!(*asked.borrow(), [(tag, 5), (tag, 2)], "each frame's tag and its line in the compiled source"); + assert_eq!(r.run("\n\n h.line").unwrap(), JsValue::Number(103.0)); + let tag = r.script_tag(); + let stack = text(&mut r, "\neval('\\n\\nh.stack')"); + assert_eq!(stack, format!("[global]@f{}:102\n[global]@[eval]:103\n", tag + 1), "code eval compiles has no tag of its own"); + let deep = "function d(n) { return n ? d(n - 1) : h.stack; } var s = d(100).split('\\n'); s.length + ',' + s[0] + ',' + s[1]"; + let tag = r.script_tag() + 1; + assert_eq!(text(&mut r, deep), format!("66,…,d@f{tag}:101"), "the frames past 64 are still left out"); +} + #[test] fn a_host_property_reads_its_getter_and_gives_assignments_to_its_setter() { let mut r = Realm::new(); diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index 22a365b615..edc5282fe5 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -232,6 +232,8 @@ pub(crate) struct Interp { pub(crate) evaluated: u32, /// The tag of the source the last run's error was raised in. pub(crate) error_tag: u32, + /// Where `$.line` and `$.stack` find the file and line of a compiled line. + pub(crate) locator: Option, /// The mark of the host error ([`crate::HostError::Marked`]) whose exception or limit is /// propagating. pub(crate) thrown_mark: Option, @@ -469,6 +471,7 @@ impl Interp { source_tag: crate::realm::UNKNOWN_SOURCE, evaluated: 0, error_tag: crate::realm::UNKNOWN_SOURCE, + locator: None, thrown_mark: None, finally_marks: Vec::new(), finally_sites: Vec::new(), diff --git a/crates/js/src/lib.rs b/crates/js/src/lib.rs index cad290f1af..1c121a212b 100644 --- a/crates/js/src/lib.rs +++ b/crates/js/src/lib.rs @@ -83,7 +83,7 @@ pub use error::{SyntaxError, TOO_DEEP, TOO_LONG}; pub use host::{Arg, Data, DataLimits, HostError, HostFunction, HostItem, ScriptItem}; 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, UNKNOWN_SOURCE}; +pub use realm::{Interrupt, JsValue, LimitKind, Limits, MAX_UNBROKEN_FUEL, Progress, Realm, RunError, RunErrorKind, SourceLocator, UNKNOWN_SOURCE}; pub use token::{Directive, DirectiveName, Keyword, Punct, Span, Token, TokenKind}; /// How a script is read. diff --git a/crates/js/src/realm.rs b/crates/js/src/realm.rs index 077f3b19b6..4146ae891b 100644 --- a/crates/js/src/realm.rs +++ b/crates/js/src/realm.rs @@ -63,6 +63,10 @@ pub enum LimitKind { /// evaluator's: code that `eval` or `Function` compiled, or an error with no place. pub const UNKNOWN_SOURCE: u32 = u32::MAX; +/// The file and line that line `line` of the source with tag `tag` ([`Realm::error_tag`]) came +/// from, as `$.line` and `$.stack` give them ([`Realm::set_source_locator`]). +pub type SourceLocator = std::rc::Rc (String, u32)>; + /// The source tag after `tag`. Once the tags are used up, every later source gets /// [`UNKNOWN_SOURCE`], so no two sources share a tag. pub(crate) fn next_tag(tag: u32) -> u32 { @@ -395,6 +399,13 @@ impl Realm { self.interp.interrupt = interrupt.0.clone(); } + /// Has `$.line` give the line `locate` maps the running line to, and `$.stack` give each + /// frame's line that way, after the file `locate` names: `function@file:line`. Without a + /// locator they give the line of the compiled source, and `$.stack` names no file. + pub fn set_source_locator(&mut self, locate: SourceLocator) { + self.interp.locator = Some(locate); + } + /// Which source the last error's `line` and `column` are in: 0 for the script last given to /// [`Realm::run`] or [`Realm::start`], `n` for the `n`th source a /// [`crate::HostItem::Evaluator`] gave since then, and [`UNKNOWN_SOURCE`] otherwise, which diff --git a/docs/mcp.md b/docs/mcp.md index 274db05a34..7bb5ecd66a 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2018,7 +2018,7 @@ VectorCraft's own, and `vc.api.has("dollar")` is true where they are available: | `global` | the global object | | `hiresTimer` | the microseconds since the run last read it, or since the run started; `0` on the web | | `level`, `memCache` | `0`; setting `memCache` throws | -| `line`, `stack` | the line of the code that reads it; the running code, outermost first, one a line as `name:line` (`[global]` for the script's own code, `[anonymous]` for a function without a name), at most 64 lines | +| `line`, `stack` | the line of the code that reads it, counted in the file that code is in (the script, a file it included or a file `$.evalFile` ran, in this run or an earlier run of its named engine); the running code, outermost first, one a line as `name@file:line` (`[global]` for the script's own code, `[anonymous]` for a function without a name; the file as `$.fileName` gives it, or the run's name for a script given as `source`), at most 64 lines. Code that `eval` or `Function` compiled keeps the line of the source they compiled, in the file `[eval]`; code whose place a named engine no longer keeps is at line `0` of `[unknown]` | | `locale` | the interface's language as a locale such as `de` or `pt_BR` (`en` when the interface follows the system); a script can set `ll` or `ll_RR`, and `null` or `""` sets the interface's again | | `localize` | `false`; while `true`, `String(object)` of a localization object gives its text for `$.locale` | | `os` | `Windows`, `macOS`, `Linux`, `FreeBSD`, `Unix` or `Web`, without a version | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f04ee3c910..e460b24a13 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -783,6 +783,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: a run reads its preprocessor lines before any of it runs: `#include` and `//@include` put another file in place of the line, looked for beside the including file, in the `#includepath` folders and in `JSINCLUDE`; `#script` names the run; `#target` and `#strict off` are taken, `#strict on` turns on strict write checks (below), `#targetengine` names the engine (below), and `#engine` is refused. `$.evalFile` runs a file with the same globals and returns its last value, and `$.fileName` and `$.includePath` give the file being run and the include folders. A script run from a file reads these files only in its folder and below, without `..` names or links that lead out, and an error in one is reported at its own file, line and column ([preprocessor directives](https://extendscript.docsforadobe.dev/extendscript-tools-features/preprocessor-directives/), [the `$` object](https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/); `crates/engine/src/tests/script_include.rs`). - Scripts: `#targetengine name` (and `//@targetengine name`) runs the script in a named engine that lasts for the session, and a later script that names it sees the globals and functions earlier ones left ([preprocessor directives](https://extendscript.docsforadobe.dev/extendscript-tools-features/preprocessor-directives/)); `$.engineName` gives the name ([the `$` object](https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/)). VectorCraft's own rules: a script without the line and `#targetengine main` get a new engine each run, the line comes once in the script itself before its code, a session keeps 8 named engines with 64 MiB of heap each, an error or a stop keeps the globals the run set while the documents go back, kept host functions act for the run that calls them, `script.engines` lists the engines and `script.engine.drop` drops one, and the web build has none. `crates/engine/src/tests/script_engines.rs`. - Scripts: a runtime error is shown at the line that was running ([the help page](https://extendscript.docsforadobe.dev/extendscript-toolkit/debugging-in-the-toolkit/)). VectorCraft's own rules: an error in code an earlier run of a named engine compiled, such as a function it defined, is reported at that code's file, line and column (the earlier run's script, a file it included or a file its `$.evalFile` ran), while the report and its console line keep the calling run's name; a script given as text is named by its run's name, and each engine keeps these places for 8 MiB of source maps, the oldest going first. An error in code whose place is gone, or in code that `eval` or `Function` compiled, is reported without a line and column, and the code still runs. `crates/engine/src/tests/script_engines.rs`. + - Scripts: `$.line` is the line of the running script, counting from 1, and `$.stack` is the current stack trace ([the help page](https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/)). VectorCraft's own rules: both count lines in the file the code is in (the script, a file it included, a file `$.evalFile` ran, or the file of an earlier run of the named engine), and `$.stack` writes each frame as `name@file:line`, outermost first; code that `eval` or `Function` compiled keeps its own line in `[eval]`, and code whose place the engine no longer keeps is at line 0 of `[unknown]`. `crates/engine/src/tests/script_include.rs`, `crates/engine/src/tests/script_engines.rs`, `crates/js/src/extension_tests.rs`. - Scripts: `File` and `Folder` ([File object](https://extendscript.docsforadobe.dev/file-system-access/file-object/), [Folder object](https://extendscript.docsforadobe.dev/file-system-access/folder-object/)) name files and folders by platform or URI path, with `name`, `fsName`, `absoluteURI`, `relativeURI`, `parent`, `Folder.current` and `encode`/`decode`, and read them: `exists`, `length`, the dates, `getFiles` with a mask or a function, and `open('r')` with `read`, `readln`, `readch`, `seek`, `tell` and `close`, decoding by byte order mark, `encoding`, UTF-8 or CP1252. VectorCraft's own rules: a script reads only in its own folder and below (and inside the automation read roots when they are set); any other path and a network or device path are refused before anything is looked up, and a link that leads out is refused as well (`false` or `null`, with `error` set); a file is read whole up to 8 MiB and a run reads up to 32 MiB; writing, the file dialogs and `execute` are not available yet. `crates/engine/src/tests/script_io.rs`. - Scripts: `#strict on` (and `//@strict on`) runs the script with the checks the [`$` object](https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/) help page gives for `$.strict`: an assignment to a read-only property throws a `TypeError`, and so does a new property on an object that takes none. VectorCraft's own rules: a getter-only property counts as read-only, the objects that take no new properties are the non-extensible ones (`Object.preventExtensions`, `seal`, `freeze`, and the frozen `vc` and `$` objects), the last `#strict` line of the script and its includes sets the whole run, a file `$.evalFile` runs keeps its own line's checks for its code, and the rest of ES5 strict mode stays with `'use strict'`. Without the line, runs are unchanged. `crates/engine/src/tests/script_include.rs` (`strict_on_*`, `strict_mode_in_eval_file_is_scoped`), `crates/js/src/interp_tests.rs` (`strict_writes_are_separate_from_es5_strict`). - Scripts folder: File › Scripts lists the `.js` and `.jsx` files of the `Scripts` folder next to the preferences, each named after its file without the extension, with each subfolder as a submenu, above Check Script… and Other Script… (https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/install-and-run-scripts.html). VectorCraft's own rules: the folder is read again when the window becomes active and when the File menu opens (in the macOS menu bar, when any of its menus opens, and the new listing shows the next time the menu opens), links are not followed, and one read stops at 2,048 entries, 512 scripts, 128 subfolders, 4 levels or 250 ms. `script.listInstalled` returns the listing. `crates/engine/src/tests/script_folder.rs`, `crates/ui-egui/src/tests/scripts_menu.rs`. From 46f5532f23f320be54a67c2e490da2642c998df3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 06:59:18 -0800 Subject: [PATCH 10/25] Actions: script runs and tool edits name a recording limit as they end While an action records, a script run, a tool's drag or a panel's or dialog's commit could journal steps past the 10,000-step or 8 MiB limit of an action set file without any check: the limit showed only when Stop Playing/Recording left the steps out, and a finished script then showed "Ran ". The recording is now checked whenever the journal changed: after every engine command the app runs (a synchronous script.run and a batch included), when a script run ends, after a tool's result, and on the next frame for edits committed directly. The edit and the journal stay, the status bar names the limit at once, later recorded commands are refused as before, and Stop keeps only the steps that fit. A journal rewrite is checked again. --- crates/ui-egui/src/app.rs | 2 + crates/ui-egui/src/app/commands.rs | 13 +- crates/ui-egui/src/canvas/drag.rs | 5 +- crates/ui-egui/src/panels/actions.rs | 266 +++++++++++++++++++++++++-- crates/ui-egui/src/script_runs.rs | 7 +- crates/ui-egui/src/state.rs | 5 + docs/mcp.md | 4 +- docs/target-app-parity.md | 2 +- 8 files changed, 273 insertions(+), 31 deletions(-) diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 67e67ac444..997da6a711 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -344,6 +344,8 @@ impl VectorcraftApp { screen_color::poll(self, ctx); self.poll_finished_work(); crate::script_runs::poll(self); + // A panel's, a dialog's or the text input's commit journaled in the frame before. + crate::panels::actions::after_journaled_edit(self); crate::scripts_menu::poll(self, ctx); if self.session.script_running() && !self.session.script_waiting() && self.session.script_dialog().is_none() { // A script in `$.sleep` goes on when its time is up; until then the app can idle. diff --git a/crates/ui-egui/src/app/commands.rs b/crates/ui-egui/src/app/commands.rs index 1d2493385e..50c7b1be30 100644 --- a/crates/ui-egui/src/app/commands.rs +++ b/crates/ui-egui/src/app/commands.rs @@ -224,13 +224,10 @@ impl VectorcraftApp { } // While an action records, a command that the recording would keep as a step runs only // when the step fits in the action. - let recorded = match panels::actions::before_recorded_command(self, id, ¶ms) { - Ok(recorded) => recorded, - Err(e) => { - self.ui.status = e.clone(); - return Err(e); - } - }; + if let Err(e) = panels::actions::before_recorded_command(self, id, ¶ms) { + self.ui.status = e.clone(); + return Err(e); + } // A command that changes the edited text is an application edit (undo, a panel or menu // edit, a control request). Capture the bounded committed context around it so `Other` // dominates the frame even if an IME receipt follows. Selection/view commands that leave @@ -240,7 +237,7 @@ impl VectorcraftApp { let ime_before = crate::ime::stamp(&mut self.session, ime_view); let cursor_settings = (self.session.caps_lock, self.session.prefs.use_precise_cursors); let r = self.session.execute(id, ¶ms).map_err(|e| e.to_string()); - let r = panels::actions::after_recorded_command(self, recorded, r); + let r = panels::actions::after_recorded_command(self, r); if r.is_ok() && cursor_settings != (self.session.caps_lock, self.session.prefs.use_precise_cursors) { self.canvas.hover_cursor = None; } diff --git a/crates/ui-egui/src/canvas/drag.rs b/crates/ui-egui/src/canvas/drag.rs index 1a385d5642..414746310f 100644 --- a/crates/ui-egui/src/canvas/drag.rs +++ b/crates/ui-egui/src/canvas/drag.rs @@ -399,7 +399,9 @@ fn pressed_with(app: &mut VectorcraftApp, index: Option, pos: Point, tool } } -/// Act on what a tool event asked the UI for (dialogs, tool switches), or show its error. +/// Act on what a tool event asked the UI for (dialogs, tool switches), or show its error. When an +/// edit the tool committed or ran no longer fits in the action being recorded, the edit stays and +/// the status bar names the limit ([`crate::panels::actions::after_journaled_edit`]). pub fn apply_requests(app: &mut VectorcraftApp, r: vectorcraft_engine::Result>) { match r { Ok(reqs) => { @@ -420,6 +422,7 @@ pub fn apply_requests(app: &mut VectorcraftApp, r: vectorcraft_engine::Result app.status(e.to_string()), } diff --git a/crates/ui-egui/src/panels/actions.rs b/crates/ui-egui/src/panels/actions.rs index 8196ad27c2..b65c15c5af 100644 --- a/crates/ui-egui/src/panels/actions.rs +++ b/crates/ui-egui/src/panels/actions.rs @@ -1201,36 +1201,56 @@ fn recorded_steps_fit(app: &mut VectorcraftApp) -> Result<(), String> { } /// Before the engine command `id` runs with `params`: Err when the recording in progress would keep -/// it as a step that does not fit in its action ([`recording_room`]); else whether the recording -/// would keep it, for [`after_recorded_command`]. A command is kept as a step when it is journaled, -/// a batch (`command.batch`, which journals itself) too, and Find Objects when it selects what it -/// finds. Undo and Redo are steps too, and are refused when they do not fit. -pub(crate) fn before_recorded_command(app: &mut VectorcraftApp, id: &str, params: &Value) -> Result { +/// it as a step that does not fit in its action ([`recording_room`]). A command is kept as a step +/// when it is journaled, a batch (`command.batch`, which journals itself) too, and Find Objects +/// when it selects what it finds. Undo and Redo are steps too, and are refused when they do not +/// fit. +pub(crate) fn before_recorded_command(app: &mut VectorcraftApp, id: &str, params: &Value) -> Result<(), String> { let journaled = vectorcraft_engine::find_command(id).is_some_and(|c| c.journal) || id == "command.batch" || (id == "document.find" && params.get("select").and_then(Value::as_bool) == Some(true)); if app.ui.recording.is_none() || !journaled || app.session.active().is_some_and(|d| d.interaction.is_some()) { - return Ok(false); + return Ok(()); } - recording_room(app, id, params)?; - Ok(true) + recording_room(app, id, params) } -/// After a command that the recording keeps as a step (`recorded`, [`before_recorded_command`]) has -/// run with result `r`: when the values the command added to its step as it ran make the steps no -/// longer fit ([`recorded_steps_fit`]), the command's edit and its result stay, the status bar -/// names the limit, no later recorded command runs, and Stop Playing/Recording leaves the step out -/// ([`steps_that_fit`]) → the command's result. -pub(crate) fn after_recorded_command(app: &mut VectorcraftApp, recorded: bool, r: Result) -> Result { - if recorded - && r.is_ok() - && let Err(e) = recorded_steps_fit(app) - { - app.status(e); +/// After an engine command has run with result `r`: when the steps it journaled, the values a +/// command added to its step as it ran or the commands a script ran (`script.run`), make the steps +/// no longer fit ([`after_journaled_edit`]), the command's edit and its result stay, the status bar +/// names the limit, no later recorded command runs, and Stop Playing/Recording leaves the steps +/// out ([`steps_that_fit`]) → the command's result. +pub(crate) fn after_recorded_command(app: &mut VectorcraftApp, r: Result) -> Result { + if r.is_ok() { + after_journaled_edit(app); } r } +/// After an edit that journals without [`before_recorded_command`]'s check (a script run's +/// commands, a tool's or a panel's edit, a dialog's commit): when the journal changed since the +/// last check and the steps that the recording in progress keeps no longer fit in its action +/// ([`recorded_steps_fit`]), the edit and the journal stay, the status bar names the limit, no +/// later recorded command runs, and Stop Playing/Recording keeps the steps that fit +/// ([`steps_that_fit`]) → whether the status bar names a limit. +pub(crate) fn after_journaled_edit(app: &mut VectorcraftApp) -> bool { + if app.ui.recording.is_none() { + return false; + } + let journal = (app.session.journal.rewrites(), app.session.journal.len()); + if app.ui.recording_checked == Some(journal) { + return false; + } + app.ui.recording_checked = Some(journal); + match recorded_steps_fit(app) { + Ok(()) => false, + Err(e) => { + app.status(e); + true + } + } +} + /// What Stop Playing/Recording adds to a set ([`recorded_into`]). struct Recorded { /// The set's action that the recording records into; None for the new action that the @@ -1400,6 +1420,7 @@ fn start_recording(app: &mut VectorcraftApp, set: usize, name: String, into: Opt app.ui.recording_into = into; app.ui.recording_base = None; app.ui.recording_tail = None; + app.ui.recording_checked = Some((app.session.journal.rewrites(), start)); } /// How many of `steps`, from the first, Stop Playing/Recording can give the recording's action so @@ -1446,6 +1467,7 @@ fn stop_recording(app: &mut VectorcraftApp) { let Some((set, name, _)) = app.ui.recording.take() else { return }; app.ui.recording_base = None; app.ui.recording_tail = None; + app.ui.recording_checked = None; app.session.journal.hold(None); match app.ui.recording_into.take() { Some(id) => { @@ -5003,6 +5025,212 @@ mod tests { assert!(files::read_set(&files::write_set(&app.ui.action_sets[0]), "Test").is_ok()); } + /// A script that moves the selection twice. + const TWO_MOVES: &str = "vc.run('object.move', {dx: 1, dy: 0}); vc.run('object.move', {dx: 1, dy: 0});"; + + /// Runs `source` to its end: in one call (`frames` false, a run with nobody to ask), or a frame + /// at a time, as the app does. + fn run_script(app: &mut VectorcraftApp, source: &str, frames: bool) { + app.session.script_frames = frames; + app.run("script.run", json!({"source": source, "name": "t.js"})).unwrap(); + for _ in 0..10_000 { + if !app.session.script_running() { + return; + } + crate::script_runs::poll(app); + } + panic!("the script did not end"); + } + + /// Begin Recording with `filler` steps already recorded. + fn recording_with(app: &mut VectorcraftApp, filler: usize) { + app.run(START_RECORDING, json!({})).unwrap(); + for _ in 0..filler { + app.session.journal.push(("object.group".to_string(), json!({}))); + } + } + + /// A script whose commands take a recording past 10,000 steps keeps its edit and the whole + /// journal, the status bar names the limit as the run ends, the next recorded command does not + /// run, and Stop Playing/Recording keeps the 10,000 steps that fit. One that fills the action + /// exactly names no limit. + #[test] + fn script_run_checks_recording_step_limit_on_completion() { + let steps = "the action already has 10,000 steps"; + for frames in [false, true] { + let (mut app, x) = app_with_three_moves(); + recording_with(&mut app, files::MAX_ACTION_STEPS - 1); + app.ui.status.clear(); + run_script(&mut app, TWO_MOVES, frames); + assert_eq!(x(&app), 2.0, "frames {frames}: the script's edit stays"); + let start = recording_start(&app).unwrap(); + assert_eq!(app.session.journal.len() - start, files::MAX_ACTION_STEPS + 1, "frames {frames}: the journal keeps every step"); + assert_eq!(app.ui.status, steps, "frames {frames}: the status bar names the limit now"); + assert!(app.ui.recording.is_some(), "the recording goes on"); + assert_eq!(app.run("object.move", json!({"dx": 1, "dy": 0})).unwrap_err(), steps, "no later command runs"); + assert_eq!(x(&app), 2.0); + app.run(STOP_RECORDING, json!({})).unwrap(); + let recorded = app.ui.action_sets[0].actions.last().unwrap(); + assert_eq!(recorded.steps.len(), files::MAX_ACTION_STEPS); + assert_eq!(recorded.steps.last().map(|(c, _)| c.as_str()), Some("object.move"), "the first move fits"); + let saved = files::write_set(&app.ui.action_sets[0]); + assert_eq!(files::read_set(&saved, "Test").unwrap().actions[1].steps.len(), files::MAX_ACTION_STEPS, "and loads again"); + + let (mut app, _) = app_with_three_moves(); + recording_with(&mut app, files::MAX_ACTION_STEPS - 2); + app.ui.status.clear(); + run_script(&mut app, TWO_MOVES, frames); + let ran = if frames { "Ran t.js" } else { "" }; + assert_eq!(app.ui.status, ran, "frames {frames}: 10,000 steps fit"); + } + } + + /// A script whose commands give the recording's set a file larger than 8 MiB keeps its edit, + /// the status bar names the limit as the run ends, and Stop Playing/Recording keeps the steps + /// that fit in a set that Load Actions… reads. One that fills the file exactly names no limit. + #[test] + fn script_run_checks_recording_byte_limit_on_completion() { + let size = "the action set would be larger than 8 MiB"; + for frames in [false, true] { + for spare in [0, 1] { + let (mut app, x) = app_with_three_moves(); + // The two steps as an action keeps them. + let before = app.session.journal.len(); + run_script(&mut app, TWO_MOVES, false); + let both: usize = app.session.journal_for_action(before).iter().map(|(c, p)| files::step_bytes(c, p)).sum(); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(x(&app), 0.0); + let pad = |n: usize| ("object.move".to_string(), json!({"dx": 1, "dy": 0, "pad": "x".repeat(n)})); + app.ui.action_sets[0].actions[0].steps = vec![pad(0)]; + let room = files::MAX_SET_FILE - files::write_set(&app.ui.action_sets[0]).len(); + // Room for both moves, or for one move and all but a byte of the other. + app.ui.action_sets[0].actions[0].steps = vec![pad(room - both + 1 - spare)]; + let into = app.ui.action_sets[0].actions[0].id; + app.run(START_RECORDING, json!({})).unwrap(); + app.ui.recording_into = Some(into); + app.ui.status.clear(); + run_script(&mut app, TWO_MOVES, frames); + assert_eq!(x(&app), 2.0, "frames {frames}: the script's edit stays"); + let what = format!("frames {frames}, spare {spare}"); + if spare == 1 { + assert_eq!(app.ui.status, if frames { "Ran t.js" } else { "" }, "{what}: the file is exactly 8 MiB"); + continue; + } + assert_eq!(app.ui.status, size, "{what}: the status bar names the limit now"); + assert_eq!(app.session.journal.since(recording_start(&app).unwrap()).len(), 2, "the journal keeps both moves"); + assert_eq!(app.run("object.move", json!({"dx": 1, "dy": 0})).unwrap_err(), size, "no later command runs"); + app.run(STOP_RECORDING, json!({})).unwrap(); + assert_eq!(app.ui.action_sets[0].actions[0].steps.len(), 2, "{what}: the first move fits"); + let saved = files::write_set(&app.ui.action_sets[0]); + assert!(saved.len() <= files::MAX_SET_FILE); + assert!(files::read_set(&saved, "Test").is_ok()); + } + } + } + + /// Presses, drags and releases the active tool from `from` to `to`, as the canvas hands its + /// results on ([`crate::canvas::apply_requests`]). + fn tool_drag(app: &mut VectorcraftApp, from: (f64, f64), to: (f64, f64)) { + use vectorcraft_tools::{PointerEvent, PointerKind}; + let view = app.view_info(); + for (kind, (x, y)) in [(PointerKind::Down, from), (PointerKind::Drag, to), (PointerKind::Up, to)] { + let r = app.session.pointer(&PointerEvent::new(kind, x, y), view); + crate::canvas::apply_requests(app, r); + } + } + + /// A drag with the Selection tool (a committed preview) or the Rectangle tool (a command the + /// tool runs) that takes a recording past 10,000 steps keeps its edit and the journal, the + /// status bar names the limit as the tool ends, and Stop Playing/Recording keeps the 10,000 + /// steps that fit. One that fills the action exactly names no limit. + #[test] + fn tool_commit_checks_recording_step_limit() { + let steps = "the action already has 10,000 steps"; + for tool in ["selection", "rectangle"] { + for filler in [files::MAX_ACTION_STEPS, files::MAX_ACTION_STEPS - 1] { + let (mut app, _) = app_with_three_moves(); + app.select_tool(tool); + recording_with(&mut app, filler); + app.ui.status.clear(); + let (journal, art) = (app.session.journal.len(), app.session.active().unwrap().doc.art_bounds()); + tool_drag(&mut app, (20.0, 20.0), (60.0, 50.0)); + assert_eq!(app.session.journal.len(), journal + 1, "{tool}: the tool journals one step"); + assert_ne!(app.session.active().unwrap().doc.art_bounds(), art, "{tool}: the edit stays"); + if filler < files::MAX_ACTION_STEPS { + assert_eq!(app.ui.status, "", "{tool}: 10,000 steps fit"); + continue; + } + assert_eq!(app.ui.status, steps, "{tool}: the status bar names the limit now"); + assert!(app.ui.recording.is_some(), "the recording goes on"); + app.run(STOP_RECORDING, json!({})).unwrap(); + assert_eq!(app.ui.action_sets[0].actions.last().unwrap().steps.len(), files::MAX_ACTION_STEPS); + } + } + } + + /// A tool's edit whose step gives the recording's set a file larger than 8 MiB keeps its edit, + /// the status bar names the limit as the tool ends, and Stop Playing/Recording leaves the step + /// out of a set that Load Actions… reads. + #[test] + fn tool_commit_checks_recording_byte_limit() { + let size = "the action set would be larger than 8 MiB"; + for tool in ["selection", "rectangle"] { + let (mut app, _) = app_with_three_moves(); + app.select_tool(tool); + app.run(START_RECORDING, json!({})).unwrap(); + let pad = |n: usize| ("object.move".to_string(), json!({"dx": 1, "dy": 0, "pad": "x".repeat(n)})); + app.ui.action_sets[0].actions[0].steps = vec![pad(0)]; + let room = files::MAX_SET_FILE - files::write_set(&app.ui.action_sets[0]).len(); + app.ui.action_sets[0].actions[0].steps = vec![pad(room)]; + app.ui.recording_into = Some(app.ui.action_sets[0].actions[0].id); + app.ui.status.clear(); + let art = app.session.active().unwrap().doc.art_bounds(); + tool_drag(&mut app, (20.0, 20.0), (60.0, 50.0)); + assert_ne!(app.session.active().unwrap().doc.art_bounds(), art, "{tool}: the edit stays"); + assert_eq!(app.ui.status, size, "{tool}: the status bar names the limit now"); + assert_eq!(app.session.journal.since(recording_start(&app).unwrap()).len(), 1, "{tool}: the journal keeps the step"); + app.run(STOP_RECORDING, json!({})).unwrap(); + assert_eq!(app.ui.action_sets[0].actions[0].steps.len(), 1, "{tool}: the step is left out"); + assert!(files::read_set(&files::write_set(&app.ui.action_sets[0]), "Test").is_ok()); + } + } + + /// A step that reaches the journal outside a command, as a panel's or a dialog's commit does, is + /// checked on the app's next frame. A journal rewrite that makes a checked step larger is + /// checked again, and a frame with no new step does not name the limit again. + #[test] + fn a_journal_rewrite_or_a_direct_commit_is_checked_on_the_next_frame() { + let size = "the action set would be larger than 8 MiB"; + let (mut app, _) = app_with_three_moves(); + let small = ("object.move".to_string(), json!({"dx": 1, "dy": 0})); + let pad = |n: usize| ("object.move".to_string(), json!({"dx": 1, "dy": 0, "pad": "x".repeat(n)})); + app.ui.action_sets[0].actions[0].steps = vec![pad(0)]; + let room = files::MAX_SET_FILE - files::write_set(&app.ui.action_sets[0]).len(); + app.ui.action_sets[0].actions[0].steps = vec![pad(room - files::step_bytes(&small.0, &small.1))]; + let into = app.ui.action_sets[0].actions[0].id; + app.run(START_RECORDING, json!({})).unwrap(); + app.ui.recording_into = Some(into); + let ctx = egui::Context::default(); + let frame = |app: &mut VectorcraftApp| { + app.begin_host_iteration(); + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| app.tick(ui.ctx())); + out.textures_delta.clear(); + }; + app.session.journal.push(small); + app.ui.status.clear(); + frame(&mut app); + assert_eq!(app.ui.status, "", "a step that fills the file exactly"); + let start = recording_start(&app).unwrap(); + app.session.journal.replace(start, pad(1)); + frame(&mut app); + assert_eq!(app.ui.status, size, "the rewritten step no longer fits"); + app.ui.status.clear(); + frame(&mut app); + assert_eq!(app.ui.status, "", "named once"); + app.run(STOP_RECORDING, json!({})).unwrap(); + assert_eq!(app.ui.action_sets[0].actions[0].steps.len(), 1, "the step is left out"); + } + /// When the action New Action made for the recording in progress is deleted, Stop /// Playing/Recording keeps none of its steps, so no limit stops a recorded command, even with /// the set's file at 8 MiB. diff --git a/crates/ui-egui/src/script_runs.rs b/crates/ui-egui/src/script_runs.rs index 02c2229741..ddba7618d1 100644 --- a/crates/ui-egui/src/script_runs.rs +++ b/crates/ui-egui/src/script_runs.rs @@ -34,7 +34,12 @@ pub fn poll(app: &mut VectorcraftApp) { } script_run::settle_close(app); match result { - Ok(_) => app.status(format!("Ran {name}")), + // The commands it ran are journaled now: a recording they no longer fit in names its limit. + Ok(_) => { + if !crate::panels::actions::after_journaled_edit(app) { + app.status(format!("Ran {name}")); + } + } Err(e) => failed(app, e.to_string()), } app.sync_views(); diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index f84b8f53b0..e8051bb8bf 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -632,6 +632,10 @@ pub struct UiState { /// ([`vectorcraft_engine::Journal::rewrites`]). #[serde(skip)] pub recording_tail: Option<(u64, usize, usize, usize)>, + /// The journal as the recording in progress last checked it against the limits of an action + /// set file: (its rewrites, its length) ([`crate::panels::actions::after_journaled_edit`]). + #[serde(skip)] + pub recording_checked: Option<(u64, usize)>, /// How actions play (Actions panel menu › Playback Options…), kept with the UI preferences. #[serde(default, deserialize_with = "crate::panels::actions::deserialize_playback")] pub action_playback: crate::panels::actions::PlaybackOptions, @@ -1152,6 +1156,7 @@ impl Default for UiState { recording_into: None, recording_base: None, recording_tail: None, + recording_checked: None, action_playback: Default::default(), action_playing: None, shortcut_overrides: Default::default(), diff --git a/docs/mcp.md b/docs/mcp.md index 274db05a34..eccc5185d8 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3063,7 +3063,9 @@ already walks Image Trace. Short agent entry points: action set would be larger than 8 MiB`): it does not run, and the recording goes on. A batch (`command.batch`) is such a command too. A command whose step grows past a limit only as it runs, from values it adds to its step, keeps its edit and result; the status bar names the limit, later recorded commands do not run, and - `ui.action.stop` leaves its step out. A stop that playback reaches + `ui.action.stop` leaves its step out. So does a `script.run` whose commands, or a tool's or panel's edit whose + step, takes the recording past a limit: the status bar names the limit when the run or the edit ends, and + `ui.action.stop` keeps the steps that fit. A stop that playback reaches then is not recorded, and the status bar shows the reason. `ui.action.stop` leaves out any recorded steps still past either limit and shows which one in the status bar. - Actions: `ui.action.options {set, action, name?, key?, cmd?, shift?, color?}` changes the action at diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f04ee3c910..5e2a79bbe1 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -744,7 +744,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Actions panel (record/playback, persisted), generic parameter dialogs for every "…" command. - Actions panel: the current set is kept with the UI preferences, so after a restart a recording goes into the set that was current, not into the first set. With no set current, Begin Recording records into the first set and makes it current. - Actions panel: expand an action to show its recorded steps, then clear a step's checkmark to keep it in the action but skip it during playback. The action and set checkmarks include or exclude all their steps; a mixed checkmark includes all. Alt/Option-clicking a step checkmark keeps that step as it was and applies the opposite inclusion state to the other steps in its action. This follows the public [Exclude commands from an action](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/exclude-commands-from-actions.html) guide; the scope of the mixed-state and Alt-click behavior is VectorCraft's design. The exclusion survives UI restart, action duplication, and `.vcactions` save/load. Existing version 1 action set files load with every step included. - - Actions panel: an action keeps to the limits that Load Actions… reads while it records and while its steps are excluded: at most 10,000 steps in an action and 8 MiB in its set's file, which are VectorCraft's own rules. Commands add steps to a recording until it stops ([the help page](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/record-actions.html)); a command whose step would pass a limit does not run, its document stays as it was, and the recording goes on. A command whose step passes a limit only as it runs, from values it adds to its step, keeps its edit; the status bar names the limit, later recorded commands do not run, and Stop Playing/Recording leaves its step out. A stop that playback reaches is not recorded then, and the status bar shows the reason. Clearing a checkmark keeps the step in the action and skips it in playback ([the help page](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/exclude-commands-from-actions.html)); an exclusion that would make the set's file larger than 8 MiB changes no checkmark, and one that makes the file smaller always works. Stop Playing/Recording leaves out any recorded steps still past a limit and names the limit in the status bar. Begin Recording, Duplicate, New Action, renaming an action, Action Options…, Set Options…, New Set… and Load Actions… (`.aia` sets included) also refuse a change that would give a set more than 1,000 actions or a file larger than 8 MiB, and change nothing then. Tests `panels::actions::tests::{recorded_commands_keep_an_action_at_10_000_steps, recorded_commands_keep_an_action_set_file_within_8_mib, a_recorded_command_whose_noted_values_do_not_fit_is_left_out, a_stop_reached_while_recording_a_full_action_is_left_out, stop_leaves_out_recorded_steps_past_the_limits, excluding_steps_keeps_an_action_set_file_within_8_mib, a_recorded_batch_that_edits_another_document_is_left_out_when_it_grows, a_set_renamed_while_it_records_is_measured_again, steps_recorded_after_an_exclusion_past_the_last_step_are_included, duplicate_keeps_action_set_files_within_their_limits, new_action_keeps_an_action_set_file_within_its_limits, renaming_keeps_an_action_set_file_within_8_mib, load_actions_refuses_a_set_that_would_save_larger_than_8_mib}`. + - Actions panel: an action keeps to the limits that Load Actions… reads while it records and while its steps are excluded: at most 10,000 steps in an action and 8 MiB in its set's file, which are VectorCraft's own rules. Commands add steps to a recording until it stops ([the help page](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/record-actions.html)); a command whose step would pass a limit does not run, its document stays as it was, and the recording goes on. A command whose step passes a limit only as it runs, from values it adds to its step, keeps its edit; the status bar names the limit, later recorded commands do not run, and Stop Playing/Recording leaves its step out. The same holds when a script run, a tool's drag or a panel's or dialog's edit takes the recording past a limit: the edit and the journal stay, the status bar names the limit as soon as the edit ends (instead of the script's "Ran" message), and Stop Playing/Recording keeps only the steps that fit. A stop that playback reaches is not recorded then, and the status bar shows the reason. Clearing a checkmark keeps the step in the action and skips it in playback ([the help page](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/exclude-commands-from-actions.html)); an exclusion that would make the set's file larger than 8 MiB changes no checkmark, and one that makes the file smaller always works. Stop Playing/Recording leaves out any recorded steps still past a limit and names the limit in the status bar. Begin Recording, Duplicate, New Action, renaming an action, Action Options…, Set Options…, New Set… and Load Actions… (`.aia` sets included) also refuse a change that would give a set more than 1,000 actions or a file larger than 8 MiB, and change nothing then. Tests `panels::actions::tests::{recorded_commands_keep_an_action_at_10_000_steps, recorded_commands_keep_an_action_set_file_within_8_mib, a_recorded_command_whose_noted_values_do_not_fit_is_left_out, script_run_checks_recording_step_limit_on_completion, script_run_checks_recording_byte_limit_on_completion, tool_commit_checks_recording_step_limit, tool_commit_checks_recording_byte_limit, a_journal_rewrite_or_a_direct_commit_is_checked_on_the_next_frame, a_stop_reached_while_recording_a_full_action_is_left_out, stop_leaves_out_recorded_steps_past_the_limits, excluding_steps_keeps_an_action_set_file_within_8_mib, a_recorded_batch_that_edits_another_document_is_left_out_when_it_grows, a_set_renamed_while_it_records_is_measured_again, steps_recorded_after_an_exclusion_past_the_last_step_are_included, duplicate_keeps_action_set_files_within_their_limits, new_action_keeps_an_action_set_file_within_its_limits, renaming_keeps_an_action_set_file_within_8_mib, load_actions_refuses_a_set_that_would_save_larger_than_8_mib}`. - Actions panel: the panel menu's Playback Options… sets how actions play: Accelerated (the default) plays every step at once, Step by Step plays one step at a time with the canvas drawn after each, and Pause For waits the given number of seconds between steps ([Specify playback speed](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/specify-playback-speed.html); `ui.action.playbackOptions`). VectorCraft's own rules, which the page does not cover: the pause is a whole number of seconds from 1 to 60, the setting is kept with the UI preferences, a paced playback ends at Stop Playing/Recording or when a step comes due while another document is active, each step of a paced playback is its own undo step, and Batch… plays at full speed. - Actions panel: the panel menu's Insert Stop… opens Record Stop, with a Message box and Allow Continue, and adds a stop to the recording in progress, after the selected command, or at the end of the selected action ([Insert stops in actions](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/insert-stops-in-actions.html); `ui.action.insertStop`). A playing action waits at the stop and shows the message so the user can do a manual task, and Play Current Selection plays the rest ([Illustrator CS5 help](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=459); `ui.action.continue`). With Allow Continue, the message box also has Continue. VectorCraft's own rules, which the pages do not cover: an empty message still waits, Stop Playing/Recording ends the playback and keeps the steps already played, the rest plays on the document active then, a stop waits at every playback speed, at Accelerated the steps between two stops are one undo step, Batch… refuses an action with an included stop, and Delete Selection on a selected step deletes that step, a stop or a command, without asking (`ui.action.deleteStep`). - Actions panel: the panel menu's Insert Menu Item… adds a menu command to the recording in progress, after the selected step, or at the end of the selected action, without running it, and playback runs it as the menu does ([Insert non-recordable tasks into actions](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/insert-non-recordable-tasks-into-actions.html); `ui.action.insertMenuItem`). The dialog's Find box picks the one item that matches the words typed, and a click on a listed item picks it. VectorCraft's own rules, which the page does not cover: items that open a dialog, the Object › Align items, Image Trace's Make and Make and Expand, Pattern's Make and Edit Pattern, and the File, Window and Help menu items are not listed, and an action holds at most 10,000 steps and its set file at most 8 MiB, for stops too. From a0e0f09d79fac9e60865f1e23f283132067abbdc Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 06:42:26 -0800 Subject: [PATCH 11/25] 3D and Materials: bound Revolve graphics' work and paint copies, and close the gap at the back - Each contour of a graphic is cut only at the faces its own bounds reach, and the points cut at the faces count toward a limit of 64,000,000. - The paint copies of a graphic's parts count toward a budget of their own, one copy for a part's fill and one for its seam stroke when it takes one. - A part filled with a pattern, or whose gradient has a transparent stop or point, takes no seam stroke. - Under several lights an opaque solid part also covers its seams, with its lit art clipped to a band of the seam stroke's width. - A line of a graphic that reaches farther than any surface is refused, as a curve already was. - A full turn places each segment by its own middle, so the cut at the back falls on the segment edge nearest half a turn from the middle. - A group's members are measured for graphics only when it has some. - docs/three-d.md: Revolve shows no Face control, and the new limits. --- crates/effects/src/revolve.rs | 86 ++++++--- crates/effects/src/revolve/tests_graphics.rs | 183 +++++++++++++++++++ crates/effects/src/solids/graphics.rs | 90 +++++++-- crates/effects/src/solids/tests_graphics.rs | 36 ++++ crates/three-d/src/lib.rs | 7 +- docs/three-d.md | 13 +- 6 files changed, 366 insertions(+), 49 deletions(-) diff --git a/crates/effects/src/revolve.rs b/crates/effects/src/revolve.rs index 95c643697c..18b6d57a68 100644 --- a/crates/effects/src/revolve.rs +++ b/crates/effects/src/revolve.rs @@ -29,6 +29,15 @@ pub fn is_revolve(id: &str) -> bool { /// thousands of faces took gigabytes; past this the source path is drawn. const MAX_PAINT_COPIES: usize = 256 << 20; +/// The bytes of an object's paint copies so far: those of its surfaces' faces, and those of the parts +/// of its graphics, each within [`MAX_PAINT_COPIES`] of its own. Graphics past their budget are left +/// out without taking room the surfaces need. +#[derive(Default)] +struct Copies { + surfaces: usize, + graphics: usize, +} + /// The most face and box tests a group's transparent members' faces take together to rejoin their /// members' last runs; past them each starts a run of its own. pub(crate) const MAX_OVERLAP_TESTS: usize = 1 << 22; @@ -145,11 +154,12 @@ pub(crate) fn validate_in(doc: Option<&Document>, n: &Node, id: &str, p: &Value) let options = shared_options(&shapes, options_of(id, p))?; let mut copies = 0; shapes.iter().try_for_each(|s| check_surface(&s.path, b, options, surface_item(&s.items), &mut copies))?; - match graphics_member(&shapes, b, options).and_then(|k| shapes.get(k)) { - Some(s) => check_graphics(doc, id, &s.path, b, options, p)?, - // With no member to carry them, the graphics' art must still fit its limits. - None => { - if let Some(doc) = doc.filter(|_| id == REVOLVE && !crate::solids::mapped_graphics(p).is_empty()) { + // Without graphics, or without the document they draw from, no member is measured for them. + if let Some(doc) = doc.filter(|_| id == REVOLVE && !crate::solids::mapped_graphics(p).is_empty()) { + match graphics_member(&shapes, b, options).and_then(|k| shapes.get(k)) { + Some(s) => check_graphics(Some(doc), id, &s.path, b, options, p, &mut 0)?, + // With no member to carry them, the graphics' art must still fit its limits. + None => { crate::solids::graphics::validate_symbols(doc, p)?; crate::solids::graphics::validate_surface_symbols(doc, p)?; } @@ -166,22 +176,28 @@ pub(crate) fn validate_in(doc: Option<&Document>, n: &Node, id: &str, p: &Value) let b = path.bounds().ok_or("Revolve requires a shape with at least two anchors")?; let paints = solid_paints(n); check_surface(&path, b, options_of(id, p), surface_item(&paints), &mut 0)?; - check_graphics(doc, id, &path, b, options_of(id, p), p)?; + check_graphics(doc, id, &path, b, options_of(id, p), p, &mut 0)?; check_shadow(p, [&path], b, options_of(id, p)) } /// An error when the graphics in Revolve (`id`) parameters `p`, with the symbols of `doc`, are past /// their limits on the surface of `path` about the axis of `b`: their art, or the parts they draw -/// on its faces ([`crate::solids::graphics::surface_parts`]). Without `doc` nothing is drawn, and -/// nothing is checked. -fn check_graphics(doc: Option<&Document>, id: &str, path: &PathData, b: Rect, options: Revolve, p: &Value) -> Result<(), String> { +/// on its faces ([`crate::solids::graphics::surface_parts`]), whose paint copies count after +/// `copies`, the bytes of the copies of the object's graphics so far ([`Copies`]). The parts' +/// copies are added to `copies` when they fit, as drawing adds them. Without `doc` nothing is +/// drawn, and nothing is checked. +fn check_graphics(doc: Option<&Document>, id: &str, path: &PathData, b: Rect, options: Revolve, p: &Value, copies: &mut usize) -> Result<(), String> { let graphics = crate::solids::mapped_graphics(p); let Some(doc) = doc.filter(|_| id == REVOLVE && !graphics.is_empty()) else { return Ok(()) }; crate::solids::graphics::validate_symbols(doc, p)?; crate::solids::graphics::validate_surface_symbols(doc, p)?; let faces = vectorcraft_three_d::revolve(path, b, options)?; - match crate::solids::graphics::surface_parts(Some(doc), NodeId(0), &graphics, &faces, &|_, c| Paint::solid(c)) { - Some(_) => Ok(()), + let mut used = *copies; + match crate::solids::graphics::surface_parts(Some(doc), NodeId(0), &graphics, &faces, &|_, c| Paint::solid(c), &mut used) { + Some(_) => { + *copies = used; + Ok(()) + } None => Err("The graphics are too complex for this surface: simplify the symbols' art or reduce Segments".into()), } } @@ -232,7 +248,7 @@ pub(crate) fn validate_item_of(doc: Option<&Document>, n: &Node, id: &str, p: &V } let ctx = GeomContext::of(n); let path = geometry(&path, &n.appearance.effects, &ctx); - let mut copies = 0; + let (mut copies, mut graphic_copies) = (0, 0); for (i, item) in n.appearance.items.iter().enumerate() { let effects = item.effects(); let at = if i == target { Some(index) } else { effects.iter().position(|e| e.visible && is_revolve(&e.id)) }; @@ -245,8 +261,11 @@ pub(crate) fn validate_item_of(doc: Option<&Document>, n: &Node, id: &str, p: &V let path = geometry(&path, at.and_then(|at| effects.get(..at)).unwrap_or(effects), &ctx.item(item)); let b = path.bounds().ok_or(EMPTY)?; check_surface(&path, b, options, crate::paints(item).then_some(item), &mut copies)?; + // The graphics of every item add their paints' copies to the graphics' budget, as they + // are drawn; only the edited item's graphics are refused here. + let graphics = check_graphics(doc, kind, &path, b, options, ¶ms, &mut graphic_copies); if i == target { - check_graphics(doc, kind, &path, b, options, ¶ms)?; + graphics?; } check_shadow(¶ms, [&path], b, options)?; } @@ -352,7 +371,7 @@ fn group_shadow(id: NodeId, fx: &Effect, shapes: &[Profile], b: Rect, options: R } /// One object's surface of revolution about the axis of `b`, and each face's depth. `copies` counts -/// the bytes of the paint copies of every surface of the object. Revolve (Classic) draws every face +/// the bytes of the paint copies of every surface and graphic of the object. Revolve (Classic) draws every face /// with its classic surface, as Extrude & Bevel (Classic) does. Revolve's graphics, with the /// symbols of `doc`, are drawn on the faces of the side ([`crate::solids::graphics::surface_parts`]): /// a face with a part of a graphic is a group of the face and that part. @@ -368,14 +387,14 @@ fn surface( opacity: f32, blend: vectorcraft_doc::color::BlendMode, expand: bool, - copies: &mut usize, + copies: &mut Copies, ) -> Option<(Vec, Node)> { // A loaded file or a profile edited past the limits keeps drawing its source path instead // of crashing the frame. Commands validate the same evaluator and report its errors. if fx.id == CLASSIC_REVOLVE { let facets = vectorcraft_three_d::revolve_facets(path, b, options).ok()?; - *copies = copies.saturating_add(paint_copies(facets.len(), &paint)); - if *copies > MAX_PAINT_COPIES { + copies.surfaces = copies.surfaces.saturating_add(paint_copies(facets.len(), &paint)); + if copies.surfaces > MAX_PAINT_COPIES { return None; } let depths = facets.iter().map(|f| f.depth).collect(); @@ -384,15 +403,26 @@ fn surface( } let colored = options.light_color != [1.0; 3] || options.lights.is_some(); let faces = vectorcraft_three_d::revolve(path, b, options).ok()?; - *copies = copies.saturating_add(paint_copies(faces.len(), &paint)); - if *copies > MAX_PAINT_COPIES { + copies.surfaces = copies.surfaces.saturating_add(paint_copies(faces.len(), &paint)); + if copies.surfaces > MAX_PAINT_COPIES { return None; } let graphics = crate::solids::mapped_graphics(&merged_params(&fx.id, &fx.params)); let shade = |face: &vectorcraft_three_d::Face, c: Color| graphic_paint(face, c, colored); - // Graphics past the limits are left out, and the surface draws without them. - let mut parts = - if graphics.is_empty() { vec![] } else { crate::solids::graphics::surface_parts(doc, n.id, &graphics, &faces, &shade).unwrap_or_default() }; + // Graphics past the limits are left out, and the surface draws without them and their paints' + // copies. + let mut used = copies.graphics; + let mut parts = if graphics.is_empty() { + vec![] + } else { + match crate::solids::graphics::surface_parts(doc, n.id, &graphics, &faces, &shade, &mut used) { + Some(parts) => { + copies.graphics = used; + parts + } + None => vec![], + } + }; let drawn = parts.iter().any(|p| !p.is_empty()); // Visibility is an expansion option, never a change to live geometry or export baking. // Keep all faces for paints whose coverage we cannot prove opaque. A bounded visibility @@ -499,7 +529,7 @@ fn object_surface( fx: &Effect, item: &AppearanceItem, expand: bool, - copies: &mut usize, + copies: &mut Copies, ) -> Option { let b = path.bounds()?; let (paint, opacity, blend) = paint_of(item); @@ -688,7 +718,7 @@ fn art(doc: Option<&Document>, n: &Node, expand: bool) -> Option { let (path, rule) = profile(n)?; let ctx = GeomContext::of(n); let mut children = vec![]; - let mut copies = 0; + let mut copies = Copies::default(); let mut remaining = n.appearance.effects.clone(); if let Some(index) = n.appearance.effects.iter().position(|e| e.visible && is_revolve(&e.id)) { let fx = n.appearance.effects.get(index)?; @@ -873,11 +903,13 @@ fn group_art(doc: Option<&Document>, n: &Node, expand: bool) -> Option { let b = union_bounds(&shapes)?; let options = shared_options(&shapes, fx_options(fx)).ok()?; let expand = expand && !n.appearance.effects.iter().skip(index + 1).any(|e| e.visible && is_geometry(&e.id)); - let mut copies = 0; + let mut copies = Copies::default(); let mut surfaces = vec![]; let mut opaque = true; - // The graphics go once, on the side of the member with the longest profile. - let longest = graphics_member(&shapes, b, options); + // The graphics go once, on the side of the member with the longest profile. Without graphics + // no member is measured for them. + let mapped = fx.id == REVOLVE && !crate::solids::mapped_graphics(&merged_params(&fx.id, &fx.params)).is_empty(); + let longest = if mapped { graphics_member(&shapes, b, options) } else { None }; for (k, s) in shapes.iter().enumerate() { let Some(item) = surface_item(&s.items) else { continue }; // The opacity and blending of the member and the groups it is in apply through its scopes. diff --git a/crates/effects/src/revolve/tests_graphics.rs b/crates/effects/src/revolve/tests_graphics.rs index 2261ab4ca7..5d9500628b 100644 --- a/crates/effects/src/revolve/tests_graphics.rs +++ b/crates/effects/src/revolve/tests_graphics.rs @@ -261,6 +261,22 @@ fn under_several_lights_a_graphic_takes_each_faces_own_lit_art() { count }; assert!(lit(&mapped) > lit(&plain), "{} {}", lit(&mapped), lit(&plain)); + // An opaque part also draws its lit art clipped to the band of its seam stroke; a translucent + // part, whose overlap would show, does not. + let mut d = d.clone(); + let mut clear = bar(Rect::new(0.0, 0.0, 10.0, 20.0), Color::rgb(1.0, 0.0, 0.0)); + if let Some(AppearanceItem::Fill(f)) = clear.appearance.items.first_mut() { + f.opacity = 0.5; + } + d.symbols.push(Symbol { dynamic: false, name: "Clear".into(), art: Arc::new(clear) }); + let clips = |n: &Node| { + let mut count = 0; + revolve_art_in(Some(&d), n).unwrap().walk(&mut |c| count += usize::from(matches!(c.kind, NodeKind::Group { clip: true, .. }))); + count + }; + let translucent = revolved(&CYLINDER, json!({"shade": true, "lights": lights, "graphics": [{"symbol": "Clear"}]})); + let (base, opaque, translucent) = (clips(&plain), clips(&mapped), clips(&translucent)); + assert!(translucent > base && opaque - base == 2 * (translucent - base), "{base} {opaque} {translucent}"); } #[test] @@ -391,3 +407,170 @@ fn a_group_with_no_member_to_carry_graphics_still_checks_their_art() { assert!(e.contains("too complex"), "{e}"); assert!(validate_in(Some(&d), &group, REVOLVE, &json!({"graphics": [{"symbol": "Red"}]})).is_ok()); } + +#[test] +fn a_full_turn_draws_a_graphic_on_either_side_of_the_cut_at_the_back() { + let mut d = document(); + d.symbols.push(Symbol { dynamic: false, name: "Thin".into(), art: Arc::new(bar(Rect::new(0.0, 0.0, 2.0, 20.0), Color::rgb(1.0, 0.0, 0.0))) }); + // Half a turn around a radius of 50 is about 157 to each side of the middle: turned to face + // the viewer, a graphic just inside either end is drawn. + for x in [155.0, -155.0] { + let n = revolved(&CYLINDER, json!({"rotationY": 180.0, "graphics": [{"symbol": "Thin", "x": x}]})); + assert!(!parts(&revolve_art_in(Some(&d), &n).unwrap(), false).is_empty(), "x {x}"); + } +} + +/// A gray cylinder of radius 50 whose side is 200 edges along the profile, from y 0 to 200. +fn ribbed() -> Vec<(f64, f64)> { + let mut points = vec![(0.0, 0.0)]; + points.extend((0..=200).map(|k| (50.0, f64::from(k)))); + points.push((0.0, 200.0)); + points +} + +/// A symbol `name` of one red path whose contours are `contours`, each a polygon through its +/// points. +fn contours_symbol(name: &str, contours: &[Vec]) -> Symbol { + let mut b = BezPath::new(); + for contour in contours { + b.move_to(contour[0]); + contour[1..].iter().for_each(|p| b.line_to(*p)); + b.close_path(); + } + let art = Node::path(NodeId(0), PathData::from_bezpath(&b), Appearance::basic(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0)); + Symbol { dynamic: false, name: name.into(), art: Arc::new(art) } +} + +#[test] +fn contours_away_from_a_face_are_not_cut_at_it() { + // 2,000 small squares in two clusters on the back, at opposite corners of the side: the path's + // bounds reach across every face, but no square reaches a face that is drawn. + let squares: Vec> = (0..2000) + .map(|i| { + let (x, y) = if i < 1000 { (0.0, 0.0) } else { (290.0, 190.0) }; + let (x, y) = (x + f64::from(i % 10) * 0.1, y + f64::from(i % 1000 / 10) * 0.1); + vec![Point::new(x, y), Point::new(x + 0.05, y), Point::new(x + 0.05, y + 0.05), Point::new(x, y + 0.05)] + }) + .collect(); + let mut d = document(); + d.symbols.push(contours_symbol("Clusters", &squares)); + let n = revolved(&ribbed(), json!({})); + let p = json!({"graphics": [{"symbol": "Clusters"}]}); + assert_eq!(validate_revolve_in(Some(&d), &n, &p), Ok(())); +} + +#[test] +fn a_contour_that_reaches_every_face_and_draws_on_none_is_refused() { + // One contour of 10,000 points: a thin frame around the whole side, past its ends and on the + // back, so it is cut at every face and keeps nothing. + let edge = |from: Point, to: Point| (0..2500).map(move |k| from.lerp(to, f64::from(k) / 2500.0)); + let (outer, inner) = ([(0.0, 0.0), (400.0, 0.0), (400.0, 400.0), (0.0, 400.0)], [(1.0, 1.0), (1.0, 399.0), (399.0, 399.0), (399.0, 1.0)]); + let ring = |corners: [(f64, f64); 4]| (0..4).flat_map(move |k| edge(corners[k].into(), corners[(k + 1) % 4].into())).collect::>(); + let mut frame = ring(outer); + frame.extend(ring(inner)); + let mut d = document(); + d.symbols.push(contours_symbol("Frame", &[frame])); + let n = revolved(&ribbed(), json!({})); + let e = validate_revolve_in(Some(&d), &n, &json!({"graphics": [{"symbol": "Frame"}]})).unwrap_err(); + assert!(e.contains("too complex for this surface"), "{e}"); + assert!(parts(&revolve_art_in(Some(&d), &n).unwrap(), false).is_empty()); +} + +/// A red linear gradient of `stops` stops, each with `opacity`. +fn ramp(stops: usize, opacity: f32) -> Paint { + use vectorcraft_doc::color::{Gradient, GradientKind, GradientPaint, GradientStop}; + let stops = (0..stops) + .map(|i| { + let mut stop = GradientStop::new(i as f32 / stops as f32, Color::rgb(1.0, 0.0, 0.0)); + stop.opacity = opacity; + stop + }) + .collect(); + Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, stops)))) +} + +#[test] +fn the_copies_of_a_graphics_paint_have_a_budget_of_their_own() { + let mut d = document(); + for (name, opacity) in [("Ramp", 1.0), ("Clear ramp", 0.5)] { + let art = + Node::path(NodeId(0), shapes::rectangle(Rect::new(0.0, 0.0, 300.0, 10.0)), Appearance::basic(ramp(4096, opacity), Paint::None, 0.0)); + d.symbols.push(Symbol { dynamic: false, name: name.into(), art: Arc::new(art) }); + } + let p = json!({"graphics": [{"symbol": "Ramp"}]}); + let n = revolved(&CYLINDER, json!({})); + let NodeKind::Path { path, .. } = &n.kind else { panic!("a path") }; + let faces = vectorcraft_three_d::revolve(path, path.bounds().unwrap(), options_of(REVOLVE, &p)).unwrap(); + let parts_of = |symbol: &str, copies: &mut usize| { + let graphics = crate::solids::mapped_graphics(&json!({"graphics": [{"symbol": symbol}]})); + crate::solids::graphics::surface_parts(Some(&d), NodeId(0), &graphics, &faces, &|_, c| Paint::solid(c), copies).map(|p| p.concat().len()) + }; + // Each opaque part copies the paint into its fill and its seam stroke; a part with + // transparent stops takes no seam stroke and copies it once. + let (opaque, clear) = (paint_bytes(&ramp(4096, 1.0)), paint_bytes(&ramp(4096, 0.5))); + let mut used = 0; + let count = parts_of("Ramp", &mut used).unwrap(); + assert!(count >= 2, "the graphic draws on several faces"); + assert_eq!(used, 2 * count * opaque); + let mut used = 0; + assert_eq!(parts_of("Clear ramp", &mut used), Some(count)); + assert_eq!(used, count * clear); + // Past the budget the graphic is refused. + assert_eq!(parts_of("Ramp", &mut (MAX_PAINT_COPIES - opaque)), None); + // A surface whose own gradient takes nearly the whole budget for surfaces still takes the + // graphic, on the object, on one fill of two and on a member of a group. + let stop = paint_bytes(&ramp(2, 1.0)) - paint_bytes(&ramp(1, 1.0)); + let base = paint_bytes(&ramp(1, 1.0)) - stop; + let gray = Paint::solid(Color::rgb(0.5, 0.5, 0.5)); + let full = ramp(((MAX_PAINT_COPIES - paint_copies(faces.len(), &gray)) / (faces.len() * 4) - base) / stop, 1.0); + assert!(MAX_PAINT_COPIES - paint_copies(faces.len(), &gray) - paint_copies(faces.len(), &full) < opaque); + let mut object = n.clone(); + if let Some(AppearanceItem::Fill(f)) = object.appearance.items.first_mut() { + f.paint = ramp(((MAX_PAINT_COPIES - opaque) / (faces.len() * 4) - base) / stop, 1.0); + } + assert_eq!(validate_revolve_in(Some(&d), &object, &p), Ok(())); + let fill = |paint: Paint, params: Value| { + let mut fill = FillLayer::new(paint); + fill.effects.push(crate::new_effect(REVOLVE, ¶ms).unwrap()); + AppearanceItem::Fill(fill) + }; + let mut two = n.clone(); + two.appearance = Appearance { items: vec![fill(gray.clone(), p.clone()), fill(full.clone(), json!({}))], ..Default::default() }.into(); + assert_eq!(crate::solids::validate_three_d_at_in(Some(&d), &two, REVOLVE, &json!({}), (Some(1), 0)), Ok(())); + let mut member = n.clone(); + member.appearance.effects.clear(); + let mut second = member.clone(); + if let Some(AppearanceItem::Fill(f)) = second.appearance.items.first_mut() { + f.paint = full; + } + let mut group = Node::group(NodeId(9), vec![Arc::new(member), Arc::new(second)]); + group.appearance.effects = n.appearance.effects.clone(); + assert_eq!(validate_in(Some(&d), &group, REVOLVE, &p), Ok(())); +} + +/// Whether each part of `art` filled with a gradient has a stroke over its seams. +fn gradient_seams(art: &Node) -> Vec { + let mut out = vec![]; + art.walk(&mut |n| { + let items = &n.appearance.items; + let red = |p: &Paint| matches!(p, Paint::Gradient(_)) && shade_of(p, false).is_some(); + if n.path_data().is_some() && matches!(items.first(), Some(AppearanceItem::Fill(f)) if red(&f.paint)) { + out.push(items.iter().any(|i| matches!(i, AppearanceItem::Stroke(_)))); + } + }); + out +} + +#[test] +fn a_gradient_with_transparent_stops_takes_no_stroke_over_its_seams() { + let mut d = document(); + for (name, opacity) in [("Opaque", 1.0), ("Clear", 0.5)] { + let art = Node::path(NodeId(0), shapes::rectangle(Rect::new(0.0, 0.0, 60.0, 10.0)), Appearance::basic(ramp(2, opacity), Paint::None, 0.0)); + d.symbols.push(Symbol { dynamic: false, name: name.into(), art: Arc::new(art) }); + } + let seams = |symbol: &str| gradient_seams(&revolve_art_in(Some(&d), &revolved(&CYLINDER, json!({"graphics": [{"symbol": symbol}]}))).unwrap()); + let opaque = seams("Opaque"); + assert!(!opaque.is_empty() && opaque.iter().all(|s| *s), "{opaque:?}"); + let clear = seams("Clear"); + assert!(!clear.is_empty() && clear.iter().all(|s| !*s), "{clear:?}"); +} diff --git a/crates/effects/src/solids/graphics.rs b/crates/effects/src/solids/graphics.rs index 4957e20c56..7c0087e15b 100644 --- a/crates/effects/src/solids/graphics.rs +++ b/crates/effects/src/solids/graphics.rs @@ -65,6 +65,10 @@ const SURFACE_REACH: f64 = 1e8; /// at every face it crosses. Past it no graphic is drawn on that surface. const MAX_SURFACE_POINTS: usize = 2_000_000; +/// The most points of Revolve's graphics cut at its faces together, counted before each cut whether +/// or not it keeps any of them. Past it no graphic is drawn on that surface. +const MAX_SURFACE_CUTS: usize = 32 * MAX_SURFACE_POINTS; + /// The width of the stroke of the same paint around each opaque part of a graphic on Revolve's /// side, which covers the seams between the parts on neighboring faces. const SURFACE_SEAM: f64 = 0.3; @@ -518,6 +522,8 @@ pub(super) fn face_art( /// One area of a graphic placed on Revolve's unrolled side surface, cut into straight pieces. struct Unrolled { polygons: Vec>, + /// The bounds of each of `polygons`. + boxes: Vec, bounds: Rect, rule: FillRule, paint: Paint, @@ -543,8 +549,19 @@ fn unrolled(doc: &Document, graphics: &[MappedGraphic]) -> Option> let placed = place * piece.path.to_bezpath(); let mut polygons = straight_pieces(&placed, &mut points)?; polygons.retain(|p| p.len() >= 3 && p.iter().all(|q| q.is_finite())); - let Some(bounds) = polygons.iter().flatten().map(|p| Rect::from_points(*p, *p)).reduce(|a, b| a.union(b)) else { continue }; - pieces.push(Unrolled { polygons, bounds, rule: piece.rule, paint: piece.paint, opacity: piece.opacity, blend: piece.blend, place }); + let boxes: Vec = + polygons.iter().filter_map(|polygon| polygon.iter().map(|p| Rect::from_points(*p, *p)).reduce(|a, b| a.union(b))).collect(); + let Some(bounds) = boxes.iter().copied().reduce(|a, b| a.union(b)) else { continue }; + pieces.push(Unrolled { + polygons, + boxes, + bounds, + rule: piece.rule, + paint: piece.paint, + opacity: piece.opacity, + blend: piece.blend, + place, + }); } } Some(pieces) @@ -553,8 +570,8 @@ fn unrolled(doc: &Document, graphics: &[MappedGraphic]) -> Option> /// The contours of `path` cut into straight pieces within [`SURFACE_TOLERANCE`], adding the points /// made to `points`. Each curve is cut on its own and the count is checked before the next one, so /// the work stops at the first curve past [`MAX_ELEMENTS`] points: `None` then, and for a path with -/// a coordinate farther than [`SURFACE_REACH`] from the origin, which bounds the pieces of one -/// curve. +/// a coordinate of a line or a curve farther than [`SURFACE_REACH`] from the origin, which bounds +/// the pieces of one curve and the arithmetic of the cuts at the faces. fn straight_pieces(path: &BezPath, points: &mut usize) -> Option>> { let near = |p: &Point| p.x.abs() <= SURFACE_REACH && p.y.abs() <= SURFACE_REACH; let mut polygons: Vec> = vec![]; @@ -565,6 +582,7 @@ fn straight_pieces(path: &BezPath, points: &mut usize) -> Option> return None; } match *el { + PathEl::MoveTo(p) | PathEl::LineTo(p) if !near(&p) => return None, PathEl::MoveTo(p) => { polygons.push(std::mem::take(&mut current)); current.push(p); @@ -616,14 +634,17 @@ pub(crate) fn validate_surface_symbols(doc: &Document, p: &Value) -> Result<(), /// `shade` gives the paint of a solid color on a face, as the surface under it is shaded; the /// colors of gradients and patterns are multiplied by the face's light. A graphic whose symbol /// `doc` does not have, or that is past the limits of its art, draws nothing. `None` past -/// [`MAX_ELEMENTS`] points together before they are cut at the faces, or [`MAX_SURFACE_POINTS`] -/// after: commands refuse such graphics, and a loaded file draws the surface without them. +/// [`MAX_ELEMENTS`] points together before they are cut at the faces, [`MAX_SURFACE_POINTS`] +/// after, [`MAX_SURFACE_CUTS`] points cut, or when the copies of their paints in the parts take +/// `copies`, the bytes of the copies of the object's graphics so far, past Revolve's budget for +/// them: commands refuse such graphics, and a loaded file draws the surface without them. pub(crate) fn surface_parts( doc: Option<&Document>, id: NodeId, graphics: &[MappedGraphic], faces: &[vectorcraft_three_d::Face], shade: &dyn Fn(&vectorcraft_three_d::Face, vectorcraft_doc::color::Color) -> Paint, + copies: &mut usize, ) -> Option>>> { let mut out: Vec>> = vec![vec![]; faces.len()]; let Some(doc) = doc else { return Some(out) }; @@ -640,6 +661,7 @@ pub(crate) fn surface_parts( } let mut seen = vec![usize::MAX; pieces.len()]; let mut drawn = 0usize; + let mut cut_points = 0usize; let mut triangle_id = 0usize; for (face, parts) in faces.iter().zip(out.iter_mut()) { let Some(cell) = face.surface.as_ref().filter(|c| c.outward && !face.cap) else { continue }; @@ -695,7 +717,15 @@ pub(crate) fn surface_parts( for k in near { let Some(piece) = pieces.get(k) else { continue }; let mut path = BezPath::new(); - for polygon in &piece.polygons { + // Each contour is cut only where its own bounds reach the triangle. + for (polygon, b) in piece.polygons.iter().zip(&piece.boxes) { + if b.x1 < reach.x0 || b.x0 > reach.x1 || b.y1 < reach.y0 || b.y0 > reach.y1 { + continue; + } + cut_points = cut_points.saturating_add(polygon.len()); + if cut_points > MAX_SURFACE_CUTS { + return None; + } let cut = clip_to(polygon, &window); let Some((first, rest)) = cut.split_first() else { continue }; path.move_to(map * *first); @@ -725,6 +755,11 @@ pub(crate) fn surface_parts( if path.elements().is_empty() { continue; } + // Each part copies its paint into its fill, and into the stroke over its seams when + // it takes one. + if !crate::revolve::paint_copies_add(copies, 1 + usize::from(takes_seam(piece)), &piece.paint) { + return None; + } parts.push(Arc::new(surface_piece(id, piece, (path, rule), map, face, shade))); } } @@ -744,14 +779,24 @@ fn surface_piece( ) -> Node { let gradient_map = map * piece.place; // Under several lights a face's light varies across it in each channel: a solid color draws - // as the face's own lit art in that color, clipped to the part. + // as the face's own lit art in that color, clipped to the part. An opaque part also draws that + // art clipped to a band of the seam stroke's width around its edges, as the other parts take + // a stroke over their seams. if let (Some(c), Some(light)) = (piece.paint.color().filter(|_| matches!(piece.paint, Paint::Solid { .. })), face.rgb_gradient) { - let lit = crate::lighting::rgb_gradient_art(id, &face.path(), &Paint::solid(c), light); - let mut clip = Node::path(id, PathData::from_bezpath(&path), Appearance::default()); - if let NodeKind::Path { rule: r, .. } = &mut clip.kind { - *r = rule; + let lit = Arc::new(crate::lighting::rgb_gradient_art(id, &face.path(), &Paint::solid(c), light)); + let clipped = |area: &BezPath, rule: FillRule| { + let mut clip = Node::path(id, PathData::from_bezpath(area), Appearance::default()); + if let NodeKind::Path { rule: r, .. } = &mut clip.kind { + *r = rule; + } + Node::new(id, NodeKind::Group { children: vec![Arc::new(clip), lit.clone()], clip: true }) + }; + let mut group = clipped(&path, rule); + if takes_seam(piece) { + let style = vectorcraft_geom::kurbo::Stroke::new(SURFACE_SEAM).with_join(vectorcraft_geom::kurbo::Join::Round); + let band = vectorcraft_geom::kurbo::stroke(path.iter(), &style, &vectorcraft_geom::kurbo::StrokeOpts::default(), SURFACE_TOLERANCE); + group = Node::group(id, vec![Arc::new(group), Arc::new(clipped(&band, FillRule::NonZero))]); } - let mut group = Node::new(id, NodeKind::Group { children: vec![Arc::new(clip), Arc::new(lit)], clip: true }); group.opacity = piece.opacity; group.blend = piece.blend; return group; @@ -777,9 +822,8 @@ fn surface_piece( } } // Parts on neighboring faces meet edge to edge: an opaque part takes a narrow stroke of its - // paint over the seam, as the faces do. A transparent one would show the overlap. - if piece.opacity >= 1.0 - && piece.blend == BlendMode::Normal + // paint over the seam, as the faces do. + if takes_seam(piece) && let Some(AppearanceItem::Fill(f)) = appearance.items.first() { let mut seam = vectorcraft_doc::StrokeLayer::new(f.paint.clone(), SURFACE_SEAM); @@ -793,6 +837,20 @@ fn surface_piece( node } +/// Does each part of `piece` take a stroke of its paint over its seams? Only an opaque part does: +/// the overlap of a transparent one, of one whose gradient has a stop or a freeform point that is +/// not fully opaque, or of a pattern, whose tile may hold transparent art, would show. +fn takes_seam(piece: &Unrolled) -> bool { + let clear = match &piece.paint { + Paint::Gradient(g) => { + g.gradient.stops.iter().any(|s| s.opacity < 1.0) || g.freeform.as_ref().is_some_and(|f| f.points.iter().any(|p| p.opacity < 1.0)) + } + Paint::Pattern { .. } => true, + _ => false, + }; + piece.opacity >= 1.0 && piece.blend == BlendMode::Normal && !clear +} + /// A region far larger than the face on the side of the line through `a` and `b` that `toward` is /// on: a rectangle with one edge along the line, reaching a thousand times the line's length past /// its ends and away from it. diff --git a/crates/effects/src/solids/tests_graphics.rs b/crates/effects/src/solids/tests_graphics.rs index f336dca4b2..b4ded98e8f 100644 --- a/crates/effects/src/solids/tests_graphics.rs +++ b/crates/effects/src/solids/tests_graphics.rs @@ -728,3 +728,39 @@ fn curves_are_cut_one_at_a_time_and_the_work_stops_at_the_limit() { assert!(points <= 1, "{scale}: {points}"); } } + +#[test] +fn a_line_that_reaches_farther_than_any_surface_is_not_cut() { + let triangle = |far: f64| { + let mut b = BezPath::new(); + b.move_to((0.0, 0.0)); + b.line_to((far, 0.0)); + b.line_to((0.0, 1.0)); + b.close_path(); + b + }; + assert!(straight_pieces(&triangle(1e7), &mut 0).is_some()); + for far in [1e12, 1e300] { + assert!(straight_pieces(&triangle(far), &mut 0).is_none(), "{far}"); + assert!(straight_pieces(&(Affine::translate((far, 0.0)) * triangle(1.0)), &mut 0).is_none(), "{far}"); + } +} + +#[test] +fn only_an_opaque_part_on_revolve_takes_a_seam_stroke() { + let piece = |paint: Paint, opacity: f32, blend: BlendMode| Unrolled { + polygons: vec![], + boxes: vec![], + bounds: Rect::ZERO, + rule: FillRule::NonZero, + paint, + opacity, + blend, + place: Affine::IDENTITY, + }; + assert!(takes_seam(&piece(Paint::solid(red()), 1.0, BlendMode::Normal))); + assert!(!takes_seam(&piece(Paint::solid(red()), 0.5, BlendMode::Normal))); + assert!(!takes_seam(&piece(Paint::solid(red()), 1.0, BlendMode::Multiply))); + // A pattern's tile may hold transparent art, which the overlap would show. + assert!(!takes_seam(&piece(Paint::Pattern { pattern: "Dots".into(), xf: Affine::IDENTITY }, 1.0, BlendMode::Normal))); +} diff --git a/crates/three-d/src/lib.rs b/crates/three-d/src/lib.rs index 0007f22049..48065d62c6 100644 --- a/crates/three-d/src/lib.rs +++ b/crates/three-d/src/lib.rs @@ -983,14 +983,17 @@ fn revolve_faces( // that faces the viewer before the rotation, and at most the angle that faces the viewer // straight on: 90° with the axis on the profile's left, 270° with it on the right. A sweep // with no part facing the viewer has its middle at half the sweep. A full turn is cut at the - // back, half a turn from the middle each way. + // back, at the edge between two steps nearest half a turn from the middle: each step is placed + // by its own middle, within half a turn of the surface's middle, so the steps meet edge to + // edge on either side of the cut. let middle = surface_middle(sweep, o.edge); let full = o.angle >= 360.0; let surface_angle = |j: usize| { let (from, to) = (sweep * j as f64 / steps as f64, sweep * (j + 1) as f64 / steps as f64); + let half = (to - from) / 2.0; let mut start = middle - from; if full { - start = (start + std::f64::consts::PI).rem_euclid(std::f64::consts::TAU) - std::f64::consts::PI; + start = (start - half + std::f64::consts::PI).rem_euclid(std::f64::consts::TAU) - std::f64::consts::PI + half; } [start, start - (to - from)] }; diff --git a/docs/three-d.md b/docs/three-d.md index 1d43351960..e85986b816 100644 --- a/docs/three-d.md +++ b/docs/three-d.md @@ -319,7 +319,8 @@ public page's example of a label on a bottle describes. - Clicking a thumbnail maps that graphic onto the front of the 3D effect of each selected object (`threeD.mapGraphic`), in one undo step. A graphic larger than the object starts scaled down to fit inside it. - Below the thumbnails the tab lists the graphics mapped onto the first selected object. The selected one shows - its Face (Front or Back; Plane has only a front), X and Y (the offset of its center from the center of the + its Face (Front or Back; Plane and Revolve show no Face, as a plane has only a front and Revolve's graphics go + on its side), X and Y (the offset of its center from the center of the object's bounds, in the face's plane), Scale (a percentage of the symbol's size) and Rotation (counterclockwise), and **Remove Graphic** takes it off. Each change is one undo step. - While the tab is open, a blue handle sits on the center of each mapped graphic whose face is turned toward the @@ -349,11 +350,13 @@ These rules are VectorCraft's own: viewer). On a compound profile the graphics go on its longest contour. Each face of the side draws the part of the graphic that falls on it, shaded as the face is shaded, so the graphic narrows toward the silhouette and is not drawn where the side's outside faces away or past the ends of the sweep; nearer - faces drawn after it cover it. A full turn cuts the graphic at the back, and the end caps take no graphic; a part + faces drawn after it cover it. A full turn cuts the graphic at the back, on the edge between two segments nearest + half a turn from the middle, and the end caps take no graphic; a part that runs past the end of the profile reaches the curved rim of the cap and stops there. On a group or layer the graphics go once, on the side of the member with the longest profile. Curves are cut into straight pieces within 0.05 pt before they are mapped, and an opaque part takes a 0.3 pt stroke of - its paint over the seams between faces. A graphic larger than the half of the side seen from the front starts + its paint over the seams between faces; a part filled with a pattern, or whose gradient has a transparent stop + or point, takes none. A graphic larger than the half of the side seen from the front starts scaled to fit it. The panel shows no handle for a Revolve's graphics; X and Y move them. Expand Appearance keeps every face of a surface with graphics. - The symbol's fills and strokes are drawn as filled areas, a stroke as its outline, and their gradients and @@ -365,7 +368,9 @@ These rules are VectorCraft's own: cut into 8 cubic pieces before it is mapped. The part of a graphic at or behind the eye is left out. - An object takes up to 64 graphics. One graphic draws up to 4,096 fills and strokes, and the graphics of one 3D effect draw up to 400,000 path elements together (on Revolve, 400,000 points after the curves are cut, and up to - 2,000,000 once they are cut at the faces). Commands refuse a graphic past either limit. A loaded file + 2,000,000 once they are cut at the faces, with up to 64,000,000 points cut together, and the copies of their + paints in the parts take up to 256 MiB per object, apart from those of the surfaces). Commands refuse a graphic + past either limit. A loaded file draws the object without a graphic past the first limit, and without all of its graphics past the second. - A hollow Extrude & Bevel has no caps, so its graphics are not drawn until Cap is turned on again, and `threeD.mapGraphic` refuses to map a new one onto it. Changing the type to Inflate drops the graphics, and From d7740ff587cb5b96cce3fdd89690aad5b2199c0f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 07:19:15 -0800 Subject: [PATCH 12/25] Images: an image stored again keeps its ICC profile and 16-bit samples Open and Place store some images again instead of keeping their bytes: a photo turned by its orientation, a TIFF the image decoder reads, and a CMYK TIFF with one plane per ink. Those images lost the ICC profile their file embeds, and 16-bit samples were cut to 8 bits. - raster_image keeps gray and RGB samples at 8 or 16 bits in the stored PNG, with the gray or RGB profile in its iCCP chunk. A profile of another color space, such as the CMYK profile of a CMYK image read as RGB, is left out. A TIFF's profile is read with the tiff decoder, which reads it whatever the image's size. - stored_cmyk_tiff and turned_cmyk write CMYK8 or CMYK16 as the file has it, with the CMYK profile as TIFF tag 34675 (UNDEFINED). A CMYK JPEG's profile is put together from all its APP2 segments. - The docs/target-app-parity.md line on EXIF orientation says 8 or 16 bits, and a line after it describes the kept profile. --- crates/doc/src/cmyk.rs | 226 +++++++++++++++++++++----- crates/engine/src/cmd/fileio/load.rs | 42 ++++- crates/engine/src/cmd/fileio/tests.rs | 210 ++++++++++++++++++++++++ docs/target-app-parity.md | 3 +- 4 files changed, 436 insertions(+), 45 deletions(-) diff --git a/crates/doc/src/cmyk.rs b/crates/doc/src/cmyk.rs index ea2c44215e..272fffeec9 100644 --- a/crates/doc/src/cmyk.rs +++ b/crates/doc/src/cmyk.rs @@ -151,24 +151,180 @@ fn planar(d: &mut tiff::decoder::Decoder>) -> bool { /// that many samples, which includes images whose planes together need more than the decoder's /// limit (256 MB of samples). pub(crate) fn read_samples(d: &mut tiff::decoder::Decoder>, n: usize, per: usize) -> Option> { + Some(match read_samples_at_depth(d, n, per)? { + Samples::Eight(v) => v, + Samples::Sixteen(v) => v.iter().map(|s| (s >> 8) as u8).collect(), + }) +} + +/// Samples of an image, pixel by pixel, at the depth its file stores them. +#[derive(Clone, Debug, PartialEq)] +enum Samples { + Eight(Vec), + Sixteen(Vec), +} + +impl Samples { + fn as_slice(&self) -> SampleSlice<'_> { + match self { + Self::Eight(v) => SampleSlice::Eight(v), + Self::Sixteen(v) => SampleSlice::Sixteen(v), + } + } +} + +/// [`Samples`], borrowed. +#[derive(Clone, Copy, Debug)] +enum SampleSlice<'a> { + Eight(&'a [u8]), + Sixteen(&'a [u16]), +} + +/// [`read_samples`], keeping 16-bit samples at 16 bits. +fn read_samples_at_depth(d: &mut tiff::decoder::Decoder>, n: usize, per: usize) -> Option { let mut buf = tiff::decoder::DecodingResult::U8(Vec::new()); let layout = d.read_image_to_buffer(&mut buf).ok()?; - let data = match buf { - tiff::decoder::DecodingResult::U8(v) => v, - tiff::decoder::DecodingResult::U16(v) => v.iter().map(|s| (s >> 8) as u8).collect(), - _ => return None, - }; + match buf { + tiff::decoder::DecodingResult::U8(v) => chunky(v, layout.planes, n, per).map(Samples::Eight), + tiff::decoder::DecodingResult::U16(v) => chunky(v, layout.planes, n, per).map(Samples::Sixteen), + _ => None, + } +} + +/// `data`, the samples of `n` pixels, `per` to a pixel, stored in `planes` planes, as the samples +/// pixel by pixel; `None` when it doesn't hold that many samples or a plane per sample. +fn chunky(data: Vec, planes: usize, n: usize, per: usize) -> Option> { if Some(data.len()) != n.checked_mul(per) { return None; } - if layout.planes <= 1 { + if planes <= 1 { return Some(data); } - if layout.planes != per { + if planes != per { return None; } - let planes: Vec<&[u8]> = data.chunks_exact(n).collect(); - Some((0..n).flat_map(|i| planes.iter().map(move |p| p.get(i).copied().unwrap_or(0))).collect()) + let planes: Vec<&[T]> = data.chunks_exact(n).collect(); + Some((0..n).flat_map(|i| planes.iter().filter_map(move |p| p.get(i).copied())).collect()) +} + +/// The color space an ICC profile's header names (bytes 16 to 19, such as `RGB `, `GRAY` or +/// `CMYK`); `None` when `icc` is shorter than a header. +pub fn icc_color_space(icc: &[u8]) -> Option<[u8; 4]> { + if icc.len() < 128 { + return None; + } + icc.get(16..20)?.try_into().ok() +} + +/// The ICC profile of TIFF tag 34675 (ICCProfile) of the image `d` reads; `None` without one. +fn tiff_icc(d: &mut tiff::decoder::Decoder>) -> Option> { + d.get_tag_u8_vec(tiff::tags::Tag::IccProfile).ok().filter(|icc| !icc.is_empty()) +} + +/// The ICC profile of TIFF `bytes`' first image (tag 34675), read with the `tiff` decoder's own +/// limits, whatever the size of the image; `None` for other images and TIFFs without one. +pub fn tiff_icc_profile(bytes: &[u8]) -> Option> { + let (_, mut d) = tiff(bytes)?; + tiff_icc(&mut d) +} + +/// The ICC profile of a JPEG, put together from all its numbered `ICC_PROFILE` APP2 segments; +/// `None` without one. +fn jpeg_icc(bytes: &[u8]) -> Option> { + let mut d = zune_jpeg::JpegDecoder::new_with_options(ZCursor::new(bytes), DecoderOptions::default()); + d.decode_headers().ok()?; + d.icc_profile().filter(|icc| !icc.is_empty()) +} + +/// `icc` when it is a profile of CMYK colors, which the samples of a CMYK image are in. +fn cmyk_icc(icc: Option>) -> Option> { + icc.filter(|icc| icc_color_space(icc) == Some(*b"CMYK")) +} + +/// The CMYK samples of a CMYK image at the depth its file stores them, and its ICC profile. +struct CmykSource { + width: u32, + height: u32, + samples: Samples, + icc: Option>, +} + +/// The samples of CMYK TIFF `bytes` (8 or 16 bits), their inks together or one plane per ink, with +/// the TIFF's CMYK ICC profile; `None` for other images and ones larger than [`MAX_CMYK_PIXELS`]. +fn tiff_source(bytes: &[u8]) -> Option { + let (kind, mut d) = tiff(bytes)?; + if !matches!(kind, tiff::ColorType::CMYK(8 | 16)) { + return None; + } + let (width, height) = d.dimensions().ok()?; + let n = usize::try_from(pixels(width, height)?).ok()?; + let icc = cmyk_icc(tiff_icc(&mut d)); + let samples = read_samples_at_depth(&mut d, n, 4)?; + Some(CmykSource { width, height, samples, icc }) +} + +/// The ink amounts of a four-component JPEG, 8 bits each, with its CMYK ICC profile. +fn jpeg_source(bytes: &[u8]) -> Option { + let Inks { width, height, data } = jpeg_inks(bytes)?; + Some(CmykSource { width, height, samples: Samples::Eight(data), icc: cmyk_icc(jpeg_icc(bytes)) }) +} + +/// A Deflate-compressed CMYK TIFF of `width` × `height` pixels of `samples` (inks together, 8 or 16 +/// bits as they are given), declaring the resolution `ppi` when both of its values are finite and +/// above 0, and carrying `icc` as tag 34675 (ICCProfile, of type UNDEFINED); `None` when it can't be +/// written. +fn write_cmyk_tiff(width: u32, height: u32, samples: SampleSlice<'_>, ppi: Option<(f64, f64)>, icc: Option<&[u8]>) -> Option> { + use tiff::encoder::colortype::{CMYK8, CMYK16, ColorType}; + use tiff::encoder::{Compression, ImageEncoder, Rational, TiffEncoder, TiffKind, compression::DeflateLevel}; + use tiff::tags::{ResolutionUnit, Tag}; + fn tags( + img: &mut ImageEncoder<'_, W, C, K>, + ppi: Option<(f64, f64)>, + icc: Option<&[u8]>, + ) -> Option<()> { + if let Some((x, y)) = ppi.filter(|(x, y)| [x, y].iter().all(|v| v.is_finite() && **v > 0.0)) { + // Ten-thousandths of a pixel per inch. + let r = |v: f64| Rational { n: (v * 10_000.0).round() as u32, d: 10_000 }; + img.encoder().write_tag(Tag::XResolution, r(x)).ok()?; + img.encoder().write_tag(Tag::YResolution, r(y)).ok()?; + img.encoder().write_tag(Tag::ResolutionUnit, ResolutionUnit::Inch).ok()?; + } + if let Some(icc) = icc { + img.encoder().write_tag(Tag::IccProfile, Undefined(icc)).ok()?; + } + Some(()) + } + let mut out = Cursor::new(Vec::new()); + let mut enc = TiffEncoder::new(&mut out).ok()?.with_compression(Compression::Deflate(DeflateLevel::Balanced)); + match samples { + SampleSlice::Eight(data) => { + let mut img = enc.new_image::(width, height).ok()?; + tags(&mut img, ppi, icc)?; + img.write_data(data).ok()?; + } + SampleSlice::Sixteen(data) => { + let mut img = enc.new_image::(width, height).ok()?; + tags(&mut img, ppi, icc)?; + img.write_data(data).ok()?; + } + } + Some(out.into_inner()) +} + +/// Bytes written as a TIFF field of type UNDEFINED, the type of an embedded ICC profile. +struct Undefined<'a>(&'a [u8]); + +impl tiff::encoder::TiffValue for Undefined<'_> { + const BYTE_LEN: u8 = 1; + const FIELD_TYPE: tiff::tags::Type = tiff::tags::Type::UNDEFINED; + + fn count(&self) -> usize { + self.0.len() + } + + fn data(&self) -> std::borrow::Cow<'_, [u8]> { + std::borrow::Cow::Borrowed(self.0) + } } impl ImageBlob { @@ -180,20 +336,8 @@ impl ImageBlob { /// [`ImageBlob::cmyk_tiff`], declaring the resolution `ppi` (horizontal, vertical pixels per /// inch) when it is given and both are finite and above 0. pub fn cmyk_tiff_at(inks: &Inks, ppi: Option<(f64, f64)>) -> Option { - use tiff::encoder::{Compression, Rational, TiffEncoder, colortype::CMYK8, compression::DeflateLevel}; - use tiff::tags::{ResolutionUnit, Tag}; - let mut out = Cursor::new(Vec::new()); - let mut enc = TiffEncoder::new(&mut out).ok()?.with_compression(Compression::Deflate(DeflateLevel::Balanced)); - let mut img = enc.new_image::(inks.width, inks.height).ok()?; - if let Some((x, y)) = ppi.filter(|(x, y)| [x, y].iter().all(|v| v.is_finite() && **v > 0.0)) { - // Ten-thousandths of a pixel per inch. - let r = |v: f64| Rational { n: (v * 10_000.0).round() as u32, d: 10_000 }; - img.encoder().write_tag(Tag::XResolution, r(x)).ok()?; - img.encoder().write_tag(Tag::YResolution, r(y)).ok()?; - img.encoder().write_tag(Tag::ResolutionUnit, ResolutionUnit::Inch).ok()?; - } - img.write_data(&inks.data).ok()?; - Some(Self::new("image/tiff", out.into_inner())) + let tiff = write_cmyk_tiff(inks.width, inks.height, SampleSlice::Eight(&inks.data), ppi, None)?; + Some(Self::new("image/tiff", tiff)) } /// Does the image hold CMYK samples (a four-component JPEG or a CMYK TIFF)? Reads only its @@ -318,30 +462,38 @@ fn tiff_inks(bytes: &[u8]) -> Option { /// CMYK TIFF `bytes` that no orientation turns ([`turned_cmyk`] stores the others) as Open and /// Place store them: as they are, or, when they store one plane per ink, which the image decoder -/// doesn't read, their ink amounts written again by [`ImageBlob::cmyk_tiff_at`] with the resolution -/// `ppi`. `None` for other images and for CMYK TIFFs whose inks [`ImageBlob::cmyk`] doesn't read. +/// doesn't read, their inks together in a CMYK TIFF with the resolution `ppi`, at the 8 or 16 bits +/// the file has, carrying the file's CMYK ICC profile. `None` for other images and for CMYK TIFFs +/// whose inks [`ImageBlob::cmyk`] doesn't read. pub fn stored_cmyk_tiff(bytes: &[u8], ppi: Option<(f64, f64)>) -> Option> { - let inks = tiff_inks(bytes)?; + let source = tiff_source(bytes)?; let (_, mut d) = tiff(bytes)?; if !planar(&mut d) { return Some(bytes.to_vec()); } - ImageBlob::cmyk_tiff_at(&inks, ppi).map(|b| Arc::unwrap_or_clone(b.bytes)) + write_cmyk_tiff(source.width, source.height, source.samples.as_slice(), ppi, source.icc.as_deref()) } /// CMYK JPEG or TIFF `bytes` that `orientation` turns or flips, as Open and Place store them: their -/// ink amounts ([`ImageBlob::cmyk`], 8 bits each) turned and written again by -/// [`ImageBlob::cmyk_tiff_at`] with the resolution `ppi` of the turned pixels, with the turned -/// width and height. `None` for other images and for CMYK images whose inks [`ImageBlob::cmyk`] -/// doesn't read. +/// inks turned and written again as a CMYK TIFF with the resolution `ppi` of the turned pixels, +/// with the turned width and height. A TIFF keeps its 8 or 16 bits, a JPEG has 8, and both keep +/// their CMYK ICC profile (a JPEG's put together from all its APP2 segments). `None` for other +/// images and for CMYK images whose inks [`ImageBlob::cmyk`] doesn't read. pub fn turned_cmyk(bytes: &[u8], orientation: image::metadata::Orientation, ppi: Option<(f64, f64)>) -> Option<(Vec, (u32, u32))> { - let inks = if bytes.starts_with(&[0xFF, 0xD8]) { jpeg_inks(bytes) } else { tiff_inks(bytes) }?; - // Four 8-bit inks to a pixel, turned as four 8-bit channels are. - let mut px = image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(inks.width, inks.height, inks.data)?); + let CmykSource { width, height, samples, icc } = if bytes.starts_with(&[0xFF, 0xD8]) { jpeg_source(bytes) } else { tiff_source(bytes) }?; + // Four inks to a pixel, turned as four channels of the same depth are. + let mut px = match samples { + Samples::Eight(v) => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(width, height, v)?), + Samples::Sixteen(v) => image::DynamicImage::ImageRgba16(image::ImageBuffer::from_raw(width, height, v)?), + }; px.apply_orientation(orientation); - let inks = Inks::new(px.width(), px.height(), px.into_bytes())?; - let tiff = ImageBlob::cmyk_tiff_at(&inks, ppi)?; - Some((Arc::unwrap_or_clone(tiff.bytes), (inks.width, inks.height))) + let size = (px.width(), px.height()); + let samples = match px { + image::DynamicImage::ImageRgba16(v) => Samples::Sixteen(v.into_raw()), + other => Samples::Eight(other.into_rgba8().into_raw()), + }; + let tiff = write_cmyk_tiff(size.0, size.1, samples.as_slice(), ppi, icc.as_deref())?; + Some((tiff, size)) } /// A TIFF whose pixels have samples after their colour, which the image decoder doesn't read at diff --git a/crates/engine/src/cmd/fileio/load.rs b/crates/engine/src/cmd/fileio/load.rs index e9f6ecf3d4..ba27e70d14 100644 --- a/crates/engine/src/cmd/fileio/load.rs +++ b/crates/engine/src/cmd/fileio/load.rs @@ -870,7 +870,10 @@ pub(crate) fn size_note(bytes: &[u8]) -> Option { /// read with [`jxlread`] and stored as PNG, with the ICC profile their colors are left in. /// A PNG, JPEG, GIF, WebP or TIFF whose orientation ([`exif_orientation`]) turns or flips it is /// stored as it is shown, with its resolution's axes swapped when it turns a quarter; a CMYK JPEG -/// or TIFF keeps its inks, 8 bits each, as a CMYK TIFF ([`vectorcraft_doc::cmyk::turned_cmyk`]). +/// or TIFF keeps its inks, at the 8 or 16 bits the file has, and its CMYK ICC profile as a CMYK +/// TIFF ([`vectorcraft_doc::cmyk::turned_cmyk`]). An image the decoder reads and that is stored as +/// PNG keeps its gray or RGB samples at 8 or 16 bits, and the gray or RGB ICC profile they are in; +/// other samples become 8-bit RGBA. pub fn raster_image(bytes: &[u8]) -> Result { let ppi = super::ppi::resolution(bytes); if let Some((w, h)) = vectorcraft_doc::cmyk::oversized_tiff(bytes) { @@ -933,28 +936,52 @@ pub fn raster_image(bytes: &[u8]) -> Result { let cms = vectorcraft_color::cms::active(); vectorcraft_doc::cmyk::extra_samples_tiff_rgba(bytes, |c| cms.cmyk_to_srgb(c, false)) }; + // The ICC profile of the samples the image decoder reads; the other readers give sRGB pixels. + let mut icc = None; let mut img = match (f.id == "tiff").then(extra_samples).flatten() { Some(img) => image::DynamicImage::ImageRgba8(img), None => match (f.id == "tiff").then(|| vectorcraft_doc::cmyk::group3_tiff_rgba(bytes)).flatten() { Some(read) => image::DynamicImage::ImageRgba8(read.map_err(err)?), None => { use image::ImageDecoder as _; - let decoder = reader.into_decoder().map_err(err)?; + let mut decoder = reader.into_decoder().map_err(err)?; // The allowance counts the decoded samples and the RGBA pixels they become (#1717). let (w, h) = decoder.dimensions(); if decoder.total_bytes() > MAX_RASTER_ALLOC || u64::from(w) * u64::from(h) * 4 > MAX_RASTER_ALLOC { return Err(err(format!("an image of {w} × {h} pixels is too large to draw"))); } + // A profile the decoder can't read leaves the image without one. The image decoder + // reads a TIFF's tags within the size of its pixels, so a small TIFF's profile is + // read by the TIFF decoder itself. + icc = match f.id { + "tiff" => vectorcraft_doc::cmyk::tiff_icc_profile(bytes), + _ => decoder.icc_profile().ok().flatten(), + }; image::DynamicImage::from_decoder(decoder).map_err(err)? } }, }; img.apply_orientation(orientation.unwrap_or(image::metadata::Orientation::NoTransforms)); - let mut img = img.into_rgba8(); if f.id == "tga" { + let mut img = img.into_rgba8(); super::tgaread::fix_alpha(bytes, &mut img); + return as_png(img, None, shown_ppi); } - as_png(img, None, shown_ppi) + use image::DynamicImage as D; + let img = match img { + D::ImageLuma8(_) | D::ImageLumaA8(_) | D::ImageRgb8(_) | D::ImageRgba8(_) => img, + D::ImageLuma16(_) | D::ImageLumaA16(_) | D::ImageRgb16(_) | D::ImageRgba16(_) => img, + other => D::ImageRgba8(other.into_rgba8()), + }; + let icc = icc.filter(|icc| png_takes_icc(&img, icc)); + as_png(img, icc, shown_ppi) +} + +/// Can a PNG of `img`'s samples carry ICC profile `icc`? Its color space must be the samples': +/// `GRAY` for gray samples, `RGB ` for RGB ones. +fn png_takes_icc(img: &image::DynamicImage, icc: &[u8]) -> bool { + let want = if img.color().has_color() { *b"RGB " } else { *b"GRAY" }; + vectorcraft_doc::cmyk::icc_color_space(icc) == Some(want) } /// The EXIF orientation of encoded image `bytes` when it turns or flips the pixels; `None` when @@ -970,10 +997,11 @@ pub(crate) fn exif_orientation(bytes: &[u8]) -> Option>, ppi: Option<(f64, f64)>) -> Result { +/// colors are in. `img` has samples a PNG holds: 8 or 16 bits of gray or RGB, with or without alpha. +pub(super) fn as_png(img: impl Into, icc: Option>, ppi: Option<(f64, f64)>) -> Result { use image::ImageEncoder as _; - let size = img.dimensions(); + let img: image::DynamicImage = img.into(); + let size = (img.width(), img.height()); let mut png = Vec::new(); let mut encoder = image::codecs::png::PngEncoder::new(&mut png); if let Some(icc) = icc { diff --git a/crates/engine/src/cmd/fileio/tests.rs b/crates/engine/src/cmd/fileio/tests.rs index 18bb4853b1..71c1bd06e5 100644 --- a/crates/engine/src/cmd/fileio/tests.rs +++ b/crates/engine/src/cmd/fileio/tests.rs @@ -1171,6 +1171,216 @@ fn png_webp_and_rgb_tiff_turned_a_quarter_swap_their_resolution() { } } +/// A made-up ICC profile of `len` bytes (at least a header's 128) whose header names the color +/// space `space`; the bytes after the header differ from place to place. +fn icc_profile(space: &[u8; 4], len: usize) -> Vec { + let mut icc: Vec = (0..len).map(|i| (i % 251) as u8).collect(); + icc[..4].copy_from_slice(&u32::try_from(len).unwrap().to_be_bytes()); + icc[12..16].copy_from_slice(b"mntr"); + icc[16..20].copy_from_slice(space); + icc[36..40].copy_from_slice(b"acsp"); + icc +} + +/// `tiff` (little-endian) with an ICCProfile tag (34675, of type UNDEFINED) holding `icc`: its first +/// directory copied to the end of the file with the tag added in order, as [`tiff_oriented`] adds +/// its tag. +fn tiff_with_icc(tiff: &[u8], icc: &[u8]) -> Vec { + let at = usize::try_from(u32::from_le_bytes(tiff[4..8].try_into().unwrap())).unwrap(); + let n = usize::from(u16::from_le_bytes([tiff[at], tiff[at + 1]])); + let mut entries: Vec> = tiff[at + 2..at + 2 + 12 * n].chunks(12).map(<[u8]>::to_vec).collect(); + let mut out = tiff.to_vec(); + if out.len() % 2 == 1 { + out.push(0); + } + let data = u32::try_from(out.len()).unwrap(); + out.extend(icc); + if out.len() % 2 == 1 { + out.push(0); + } + let i = entries.iter().position(|e| u16::from_le_bytes([e[0], e[1]]) > 34675).unwrap_or(n); + let count = u32::try_from(icc.len()).unwrap(); + entries.insert(i, [&34675u16.to_le_bytes()[..], &7u16.to_le_bytes(), &count.to_le_bytes(), &data.to_le_bytes()].concat()); + let ifd = u32::try_from(out.len()).unwrap(); + out[4..8].copy_from_slice(&ifd.to_le_bytes()); + out.extend(u16::try_from(n + 1).unwrap().to_le_bytes()); + out.extend(entries.concat()); + out.extend([0; 4]); + out +} + +/// The ICC profile and pixels of a stored image, read by the image decoder for its format. +fn stored_pixels(what: &str, img: &RasterImage) -> (Option>, image::ExtendedColorType, image::DynamicImage) { + use image::ImageDecoder as _; + let bytes = Cursor::new(img.blob.bytes.as_slice()); + let mut d: Box = match img.blob.mime.as_str() { + "image/png" => Box::new(image::codecs::png::PngDecoder::new(bytes).unwrap()), + "image/tiff" => Box::new(image::codecs::tiff::TiffDecoder::new(bytes).unwrap()), + other => panic!("{what}: stored as {other}"), + }; + let icc = d.icc_profile().unwrap(); + let color = d.original_color_type(); + (icc, color, image::DynamicImage::from_decoder(d).unwrap()) +} + +/// An image turned by its orientation and stored as PNG keeps the gray or RGB ICC profile its file +/// carries, and its 16-bit samples at 16 bits, from a PNG, a JPEG, a WebP and a TIFF; a TIFF the +/// image decoder reads, stored as PNG without a turn, keeps them too. A profile of another color +/// space than the samples' is left out. +#[test] +fn images_stored_as_png_keep_their_icc_profile_and_16_bit_samples() { + use image::{DynamicImage, ImageEncoder as _}; + let (rgb_icc, gray_icc, cmyk_icc) = (icc_profile(b"RGB ", 600), icc_profile(b"GRAY", 300), icc_profile(b"CMYK", 400)); + // 3 × 2, every sample's low byte different. + let rgb16 = image::ImageBuffer::from_fn(3, 2, |x, y| { + let v = u16::try_from(x * 0x1111 + y * 0x2345).unwrap(); + image::Rgb([0x1000 + v, 0x8001 + v, 0xF0F3 - v]) + }); + let rgb16 = DynamicImage::ImageRgb16(rgb16); + let gray16 = DynamicImage::ImageLuma16(image::ImageBuffer::from_fn(3, 2, |x, y| image::Luma([u16::try_from(x * 0x3001 + y * 0x0107).unwrap()]))); + let rgb8 = DynamicImage::ImageRgb8(image::RgbImage::from_fn(3, 2, |x, y| image::Rgb([u8::try_from(x * 70 + y * 9).unwrap(), 200, 13]))); + let png = |img: &DynamicImage, icc: &[u8], orientation: u16| { + let mut out = Vec::new(); + let mut enc = image::codecs::png::PngEncoder::new(&mut out); + enc.set_icc_profile(icc.to_vec()).unwrap(); + enc.set_exif_metadata(exif_block(orientation, (150, 150))).unwrap(); + img.write_with_encoder(enc).unwrap(); + out + }; + let webp = { + let mut out = Vec::new(); + let mut enc = image::codecs::webp::WebPEncoder::new_lossless(&mut out); + enc.set_icc_profile(rgb_icc.clone()).unwrap(); + enc.set_exif_metadata(exif_block(6, (150, 150))).unwrap(); + rgb8.write_with_encoder(enc).unwrap(); + out + }; + let tiff = |orientation: Option| { + let mut out = Vec::new(); + let mut enc = image::codecs::tiff::TiffEncoder::new(Cursor::new(&mut out)); + enc.set_icc_profile(rgb_icc.clone()).unwrap(); + rgb16.write_with_encoder(enc).unwrap(); + match orientation { + Some(o) => tiff_oriented(&out, o, false, None), + None => out, + } + }; + // (what, file, the ICC profile to keep, the pixels as they show, 16 bits) + type Case<'a> = (&'a str, Vec, Option<&'a [u8]>, DynamicImage, bool); + let cases: Vec = vec![ + ("16-bit RGB PNG, orientation 6", png(&rgb16, &rgb_icc, 6), Some(&rgb_icc), rgb16.rotate90(), true), + ("16-bit gray PNG, orientation 8", png(&gray16, &gray_icc, 8), Some(&gray_icc), gray16.rotate270(), true), + ("8-bit RGB PNG, orientation 3", png(&rgb8, &rgb_icc, 3), Some(&rgb_icc), rgb8.rotate180(), false), + ("RGB PNG with a CMYK profile, orientation 6", png(&rgb8, &cmyk_icc, 6), None, rgb8.rotate90(), false), + ("WebP, orientation 6", webp, Some(&rgb_icc), rgb8.rotate90(), false), + ("16-bit RGB TIFF, not turned", tiff(None), Some(&rgb_icc), rgb16.clone(), true), + ("16-bit RGB TIFF, orientation 6", tiff(Some(6)), Some(&rgb_icc), rgb16.rotate90(), true), + ]; + for (what, file, icc, want, wide) in cases { + let img = raster_image(&file).unwrap_or_else(|e| panic!("{what}: {e}")); + assert_eq!((img.width, img.height, img.blob.mime.as_str()), (want.width(), want.height(), "image/png"), "{what}"); + let (kept, color, px) = stored_pixels(what, &img); + assert_eq!(kept.as_deref(), icc, "{what}: the ICC profile"); + assert_eq!(color.bits_per_pixel() / u16::from(color.channel_count()), if wide { 16 } else { 8 }, "{what}: the sample depth"); + if wide { + assert_eq!(px.to_rgb16(), want.to_rgb16(), "{what}: the samples"); + } else { + assert_eq!(px.to_rgb8(), want.to_rgb8(), "{what}: the samples"); + } + } + // A JPEG's samples change in encoding; its profile is kept. + let mut jpg = Vec::new(); + let mut enc = image::codecs::jpeg::JpegEncoder::new_with_quality(&mut jpg, 95); + enc.set_icc_profile(rgb_icc.clone()).unwrap(); + rgb8.write_with_encoder(enc).unwrap(); + let exif = [b"Exif\0\0".as_slice(), &exif_block(6, (150, 150))].concat(); + let mut turned = jpg[..2].to_vec(); + turned.extend([0xff, 0xe1]); + turned.extend(u16::try_from(exif.len() + 2).unwrap().to_be_bytes()); + turned.extend(&exif); + turned.extend(&jpg[2..]); + let img = raster_image(&turned).unwrap(); + assert_eq!((img.width, img.height, img.blob.mime.as_str()), (2, 3, "image/png"), "JPEG"); + assert_eq!(stored_pixels("JPEG", &img).0, Some(rgb_icc.clone()), "JPEG: the ICC profile"); + // Not turned, a PNG keeps its own bytes. + let plain = png(&rgb16, &rgb_icc, 1); + assert_eq!(raster_image(&plain).unwrap().blob.bytes.as_slice(), plain.as_slice(), "a PNG as taken keeps its bytes"); +} + +/// A CMYK TIFF stored again, because it stores one plane per ink or because its orientation turns +/// it, keeps its ICC profile as tag 34675 and its 8 or 16 bits a sample, exactly; one that stores +/// its inks together and isn't turned keeps its own bytes. +#[test] +fn cmyk_tiffs_written_again_keep_their_icc_profile_and_depth() { + use image::DynamicImage; + let icc = icc_profile(b"CMYK", 900); + // 3 × 2, no black, every sample's low byte different. + let ink = |c: usize, p: usize| -> u16 { u16::try_from(0x0101 * (c * 5 + p + 1) + 0x10 * p + c).unwrap() }; + for bits in [8u16, 16] { + let sample = |c: usize, p: usize| match (c, bits) { + (3, _) => 0, + (_, 16) => ink(c, p), + _ => ink(c, p) & 0xFF, + }; + let channels: Vec> = (0..4).map(|c| (0..6).map(|p| sample(c, p)).collect()).collect(); + // The image decoder shows a CMYK pixel without black as 1 - C, 1 - M, 1 - Y, exactly. + let full = if bits == 16 { 0xFFFF } else { 0xFF }; + let shown: Vec = (0..6).flat_map(|p| (0..3).map(|c| full - channels[c][p]).collect::>()).collect(); + let shown = if bits == 16 { + DynamicImage::ImageRgb16(image::ImageBuffer::from_raw(3, 2, shown).unwrap()) + } else { + DynamicImage::ImageRgb8(image::RgbImage::from_raw(3, 2, shown.iter().map(|v| u8::try_from(*v).unwrap()).collect()).unwrap()) + }; + for planar in [false, true] { + let file = tiff_with_icc(&hand_tiff(5, bits, &[], planar, &channels), &icc); + for (orientation, want) in [(None, shown.clone()), (Some(6), shown.rotate90()), (Some(3), shown.rotate180())] { + let what = format!("{bits} bits, planar {planar}, orientation {orientation:?}"); + let file = orientation.map_or_else(|| file.clone(), |o| tiff_oriented(&file, o, false, Some(150))); + let img = raster_image(&file).unwrap_or_else(|e| panic!("{what}: {e}")); + if orientation.is_none() && !planar { + assert_eq!(img.blob.bytes.as_slice(), file.as_slice(), "{what}: kept as it is"); + } + let (kept, color, px) = stored_pixels(&what, &img); + assert_eq!(kept.as_deref(), Some(icc.as_slice()), "{what}: the ICC profile"); + let depth = if bits == 16 { image::ExtendedColorType::Cmyk16 } else { image::ExtendedColorType::Cmyk8 }; + assert_eq!(color, depth, "{what}: the sample depth"); + assert_eq!(px, want, "{what}: the samples"); + } + } + } +} + +/// A CMYK JPEG turned by its orientation and stored as a CMYK TIFF keeps its whole ICC profile, +/// put together from the two APP2 segments a profile larger than one segment is split into. +#[test] +fn a_turned_cmyk_jpeg_keeps_its_icc_profile_from_every_segment() { + use vectorcraft_render::encode::jpeg::{self, ColorModel, JpegOptions}; + let icc = icc_profile(b"CMYK", 70_000); + let inks: Vec = (0..16u32 * 8).flat_map(|i| [u8::try_from(i).unwrap(), 0, 0, 40]).collect(); + let o = JpegOptions { color_model: ColorModel::Cmyk, embed_icc: false, ..Default::default() }; + let jpg = jpeg::encode(&inks, 16, 8, 100, None, &o).unwrap(); + let exif = [b"Exif\0\0".as_slice(), &exif_block(6, (300, 300))].concat(); + let mut file = jpg[..2].to_vec(); + file.extend([0xff, 0xe1]); + file.extend(u16::try_from(exif.len() + 2).unwrap().to_be_bytes()); + file.extend(&exif); + let chunks: Vec<&[u8]> = icc.chunks(65_519).collect(); + assert_eq!(chunks.len(), 2, "the profile takes two segments"); + for (i, chunk) in chunks.iter().enumerate() { + file.extend([0xff, 0xe2]); + file.extend(u16::try_from(chunk.len() + 16).unwrap().to_be_bytes()); + file.extend(b"ICC_PROFILE\0"); + file.extend([u8::try_from(i + 1).unwrap(), 2]); + file.extend(*chunk); + } + file.extend(&jpg[2..]); + let img = raster_image(&file).unwrap(); + assert_eq!((img.width, img.height, img.blob.mime.as_str()), (8, 16, "image/tiff")); + let (kept, color, _) = stored_pixels("CMYK JPEG", &img); + assert_eq!(color, image::ExtendedColorType::Cmyk8); + assert!(kept.as_deref() == Some(icc.as_slice()), "the whole ICC profile: {:?} bytes", kept.map(|k| k.len())); +} + /// With `importer` named, a file up to the importer's limit is read whole and a larger one is an /// error, whatever its content. #[test] diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f04ee3c910..a5036cd320 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1639,7 +1639,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - On the desktop, File › Place reads and decodes files off the UI thread, one at a time, and places each once it is read, with "Placing" in the status bar and the busy spinner until then: the Place dialog's OK, a file dropped on the canvas, a click or drag of the place cursor, and the OK of the PDF, DXF and text import options. The files and thumbnails the place cursor is loaded with are read the same way, and the Place dialog's lines about its files are read on a thread of their own. Files are placed in the order they were started; a file is not placed while a dialog is open or a drag is under way, and a file whose document was closed meanwhile is not placed. `file.place` and `file.place.queue` over MCP and scripts reply as before. - On the desktop, Paste from a menu or shortcut captures another app's bitmap or reads a copied image file on the UI thread, then decodes the image on the file-reading worker. The status bar shows "Pasting" until the image is pasted. Windows device-independent bitmaps and Linux clipboard images are encoded as PNG on that worker. A Copy or Cut made while the image is read keeps its internal clipboard. `edit.paste*` over MCP and scripts reads the bitmap at once. - The pixels of a PNG, JPEG, GIF or WebP file that Place decodes to check them are kept in the image store the renderers share, so the canvas's first frame with the placed image draws them without decoding the file again on the UI thread: File › Place, a file dropped on the canvas, a click or drag of the place cursor, `file.place`, and Paste of such an image. A CMYK JPEG is still decoded when it is first drawn (`crates/ui-egui/src/placing.rs`, `crates/render/src/tests.rs`). - - A photo whose EXIF orientation turns or flips it (a camera held upright or upside down) is placed and opened upright, as it was taken; the image is stored as it is seen (#4284). A quarter turn swaps the resolution's axes, so the image keeps its physical size. TIFFs read without the image decoder (grayscale with extra channels, CCITT Group 3, CMYK with one plane per ink) follow their Orientation tag too, and a turned CMYK JPEG or TIFF keeps its inks, 8 bits each, as a CMYK TIFF. + - A photo whose EXIF orientation turns or flips it (a camera held upright or upside down) is placed and opened upright, as it was taken; the image is stored as it is seen (#4284). A quarter turn swaps the resolution's axes, so the image keeps its physical size. TIFFs read without the image decoder (grayscale with extra channels, CCITT Group 3, CMYK with one plane per ink) follow their Orientation tag too, and a turned CMYK JPEG or TIFF keeps its inks, at the 8 or 16 bits the file has, as a CMYK TIFF. + - An image that Open and Place store again keeps the ICC profile its file embeds and its 16-bit samples. A turned PNG, JPEG, WebP or TIFF stored as PNG, and a TIFF the image decoder reads, keep their gray or RGB samples at 8 or 16 bits with their gray or RGB profile in the PNG's `iCCP` chunk ([PNG specification, iCCP](https://www.w3.org/TR/png-3/#11iCCP)). A CMYK TIFF stored with one plane per ink and a turned CMYK JPEG or TIFF keep their CMYK profile as TIFF tag 34675, a JPEG's put together from all its APP2 segments ([ICC image-format guide](https://github.com/InternationalColorConsortium/iccDEV/blob/master/iccdev-mcp/docs/icc-format-guide.md)). A profile whose color space differs from the stored samples' is left out. The profile is kept in the stored image; how CMYK inks are drawn and exported to PDF does not change (`crates/engine/src/cmd/fileio/tests.rs`). - File › Place and a file dropped on the canvas refuse a PNG, JPEG, GIF or WebP file whose pixels can't be read, such as one cut short by a download or a sync still running, and the status bar shows "Couldn't place : the image's pixels can't be read". Paste and Relink refuse such an image too, and Update Links, or Open when it reads the file again, counts it as missing. A JPEG cut short still places when its pixels can be decoded (`file.place`, `crates/engine/src/tests_place.rs`). - On the desktop, Copy and Cut make the system clipboard's formats (text, SVG, PDF, PNG) from a copy of the clipboard on the thread that writes background saves and exports, and write them when they are ready; while that thread has a save, an export, a print or a recovery copy to finish, they are made and written at once. Until they are written, Paste in VectorCraft takes the internal clipboard, and while a text field or the Type tool has the keyboard the app waits for them. Another Copy or Cut, or a copy of text in VectorCraft, drops them. - On the desktop with Enable Background Export on (Preferences › File Handling), File › Package… collects the linked files and fonts and writes the package from the document as it was at OK on the thread that writes background saves and exports, with "Packaging" in the status bar and the busy spinner until it is written; a save of unsaved changes that Package starts is written first. `file.package` over MCP and scripts replies as before. From b6aaea6c9790aacd3a01e7242693803502ea9ae7 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 07:11:57 -0800 Subject: [PATCH 13/25] Graphs: Appearance commands and graphic styles given a series group edit its marks A graph draws its series groups again with no rows of their own, so a fill, stroke, opacity or graphic style that a command put on a series group was lost the next time the graph's data, type or size changed, and the graph stored nothing. paint.setFill and paint.setStroke already pass a series group's id on to the paths directly inside it. - appearance.addFill, addStroke, setItem, removeItem, duplicateItem and moveItem, graphicStyle.apply and transparency.set with a fill or stroke item now edit the paths directly in a series group given by id or picked with Group Selection, and the graph stores what they change. A series group with no such path, or with a fill or stroke row of its own, is still edited itself, and appearance.moveItem from "contents" still moves the group's own Contents row. - appearance.clear, appearance.reduceToBasic, appearance.showAllHidden and graphicStyle.breakLink edit the group as well as its paths. - graphicStyle.apply without add and appearance.transfer onto a series group clear the group's own opacity, blend mode, isolation, knockout, effects and style link, and graphicStyle.apply with add unlinks the group. A transfer source that is one of the group's paths keeps its look, and a source that is the group's only path is an error. - graphicStyle.redefine passes the style to the paths of a linked series group, other than the source and the linked paths whose look was edited, and clears and unlinks the group. - graphicStyle.new, graphicStyle.redefine and appearance.transfer read a series group that holds no row, effect, opacity, blend mode, isolation, knockout or style link of its own through the topmost path directly in it, and a move clears each of those paths. A series group that holds one of them is read itself, as before. - The Graphic Styles panel reads the style link of such a selected series group from that path. Docs: docs/mcp.md, docs/target-app-parity.md. Not yet: the Appearance panel and appearance.setActiveItem still read the selected group's own rows, and the effect commands and the paint, stroke and gradient commands with an item still edit the group itself. Follows #5501. --- crates/engine/src/cmd/appearance.rs | 191 +++++++++++--- crates/engine/src/cmd/graph.rs | 3 +- crates/engine/src/cmd/graph/series.rs | 39 ++- crates/engine/src/cmd/graph/tests.rs | 358 ++++++++++++++++++++++++++ crates/engine/src/cmd/paint.rs | 6 +- crates/engine/src/cmd/style.rs | 44 +++- docs/mcp.md | 28 +- docs/target-app-parity.md | 2 +- 8 files changed, 612 insertions(+), 59 deletions(-) diff --git a/crates/engine/src/cmd/appearance.rs b/crates/engine/src/cmd/appearance.rs index fb86fa7852..f342f8bb21 100644 --- a/crates/engine/src/cmd/appearance.rs +++ b/crates/engine/src/cmd/appearance.rs @@ -19,7 +19,10 @@ //! shape that a Convert to Shape or Outline Object effect on them gives them, below or above the //! image as its Contents row says; new ones go right below that row. -use std::{collections::HashMap, sync::Arc}; +use std::{ + collections::{HashMap, HashSet}, + sync::Arc, +}; use serde_json::{Value, json}; use vectorcraft_color::{BlendMode, Paint}; @@ -45,7 +48,7 @@ pub fn specs() -> Vec { "Add New Fill", ["Window", "Appearance"], Some("Cmd+/"), - "{ids?|id?, target?: \"object\"|\"contents\"} add a fill on top of each selected object's own stack, on an image right below its Contents row, with its top fill's paint (type without one: its characters' fill; else the default fill). With a fill row active (appearance.setActiveItem), no `ids`, no `id` and no `target: \"contents\"`, the new fill takes that row's paint, goes right above it, and becomes the active row; appearance.duplicateItem copies a whole row. 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 (exceptions: docs/mcp.md)", + "{ids?|id?, target?: \"object\"|\"contents\"} add a fill on top of each selected object's own stack, on an image right below its Contents row, with its top fill's paint (type without one: its characters' fill; else the default fill). With a fill row active (appearance.setActiveItem), no `ids`, no `id` and no `target: \"contents\"`, the new fill takes that row's paint, goes right above it, and becomes the active row; appearance.duplicateItem copies a whole row. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md)", has_doc, |s, p| add_item(s, p, true) ), @@ -54,7 +57,7 @@ pub fn specs() -> Vec { "Add New Stroke", ["Window", "Appearance"], Some("Cmd+Alt+/"), - "{ids?|id?, target?} add a stroke on top of each selected object's own stack, on an image right below its Contents row, with its top stroke's paint (else the default stroke) and that stroke's weight when it has paint, at least 1 pt. 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 (exceptions: docs/mcp.md)", + "{ids?|id?, target?} add a stroke on top of each selected object's own stack, on an image right below its Contents row, with its top stroke's paint (else the default stroke) and that stroke's weight when it has paint, at least 1 pt. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md)", has_doc, |s, p| add_item(s, p, false) ), @@ -63,7 +66,7 @@ pub fn specs() -> Vec { "Clear Appearance", ["Window", "Appearance"], None, - "{ids?|id?, target?} leave each object one empty fill and stroke (None; a group none of its own) and reset its opacity and blend mode. 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 the object's opacity and blend mode (exceptions: docs/mcp.md)", + "{ids?|id?, target?} leave each object one empty fill and stroke (None; a group none of its own) and reset its opacity and blend mode. On a path directly in a graph series (a series group's id stands for those paths and the group), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions: docs/mcp.md)", has_doc, clear_appearance ), @@ -72,7 +75,7 @@ pub fn specs() -> Vec { "Reduce to Basic Appearance", ["Window", "Appearance"], None, - "{ids?|id?, target?} keep only one visible fill and stroke (without ids: the Appearance panel's active row in place of the topmost one of its kind; else the topmost), without their own opacity, blend mode or effects (a group keeps no rows it lacked), and drop the object's effects. 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 (exceptions: docs/mcp.md)", + "{ids?|id?, target?} keep only one visible fill and stroke (without ids: the Appearance panel's active row in place of the topmost one of its kind; else the topmost), without their own opacity, blend mode or effects (a group keeps no rows it lacked), and drop the object's effects. On a path directly in a graph series (a series group's id stands for those paths and the group), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md)", has_doc, reduce_basic ), @@ -81,7 +84,7 @@ pub fn specs() -> Vec { "Appearance Item", [], None, - "{index: paint-order item index, ids?|id? (default: the selection), target?: \"object\"|\"contents\", opacity?: 0..100, blend?: name, visible?: bool, weight?: pt (strokes), color?|none?|swatch?|gradient? (as paint.setFill), tint?: 0..100, keepModel?: bool (both as paint.setFill), 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)} edit one fill/stroke of each target object's own appearance stack. 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 (exceptions: docs/mcp.md)", + "{index: paint-order item index, ids?|id? (default: the selection), target?: \"object\"|\"contents\", opacity?: 0..100, blend?: name, visible?: bool, weight?: pt (strokes), color?|none?|swatch?|gradient? (as paint.setFill), tint?: 0..100, keepModel?: bool (both as paint.setFill), 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)} edit one fill/stroke of each target object's own appearance stack. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md)", has_doc, set_item ), @@ -90,7 +93,7 @@ pub fn specs() -> Vec { "Remove Item", [], None, - "{index | indices: [..] (paint-order item indices), ids?|id?, target?, 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)} remove those fills/strokes from each target object's own stack. 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 (exceptions: docs/mcp.md)", + "{index | indices: [..] (paint-order item indices), ids?|id?, target?, 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)} remove those fills/strokes from each target object's own stack. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md)", has_doc, remove_item ), @@ -108,7 +111,7 @@ pub fn specs() -> Vec { "Duplicate Item", ["Window", "Appearance"], None, - "{index | indices: [..] (paint-order item indices), to?: paint-order index of the copy (with several, of the lowest copy: they land together in their order; default: each right above its item; not with aligned rows of a mixed selection), contents?: count (with `to`: how many items paint below the Contents (Characters) row afterwards; default: it stays between the same items), ids?|id?, target?, 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)} copy fills/strokes with their effects, as Alt-dragging rows places them. 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 (exceptions: docs/mcp.md)", + "{index | indices: [..] (paint-order item indices), to?: paint-order index of the copy (with several, of the lowest copy: they land together in their order; default: each right above its item; not with aligned rows of a mixed selection), contents?: count (with `to`: how many items paint below the Contents (Characters) row afterwards; default: it stays between the same items), ids?|id?, target?, 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)} copy fills/strokes with their effects, as Alt-dragging rows places them. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md)", has_doc, duplicate_item ), @@ -117,7 +120,7 @@ pub fn specs() -> Vec { "Reorder Appearance Item", [], None, - "{from: paint-order item index | \"contents\", indices?: [..] (several items instead of from: they move as one block in their order, the lowest landing at `to`; a block landing next to the Contents row keeps its lowest item's side), to, contents?: count, ids?|id?, target?, aligned?: bool (refused when the targets' appearances differ)} move fill/stroke `from` to paint-order index `to`; on a group, layer or type the Contents (Characters) row stays between the same items (a moved item landing next to it keeps its side) unless `contents` says how many items paint below it afterwards. from \"contents\": move that row so `to` items paint below the members (characters) and the rest above. 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 (exceptions: docs/mcp.md) → {index: where the item landed | contents: the row's slot}", + "{from: paint-order item index | \"contents\", indices?: [..] (several items instead of from: they move as one block in their order, the lowest landing at `to`; a block landing next to the Contents row keeps its lowest item's side), to, contents?: count, ids?|id?, target?, aligned?: bool (refused when the targets' appearances differ)} move fill/stroke `from` to paint-order index `to`; on a group, layer or type the Contents (Characters) row stays between the same items (a moved item landing next to it keeps its side) unless `contents` says how many items paint below it afterwards. from \"contents\": move that row so `to` items paint below the members (characters) and the rest above. On a path directly in a graph series (a series group's id stands for those paths, except with from \"contents\", which moves the group's own row), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md) → {index: where the item landed | contents: the row's slot}", has_doc, move_item ), @@ -144,7 +147,7 @@ pub fn specs() -> Vec { "Show All Hidden Attributes", ["Window", "Appearance"], None, - "{ids?|id?, target?} make every hidden fill, stroke and effect (the object's and each item's) of each selected object visible again; errors when nothing is hidden. 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 (exceptions: docs/mcp.md) → {ids}", + "{ids?|id?, target?} make every hidden fill, stroke and effect (the object's and each item's) of each selected object visible again; errors when nothing is hidden. On a path directly in a graph series (a series group's id stands for those paths and the group), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md) → {ids}", has_doc, show_all_hidden ), @@ -162,7 +165,7 @@ pub fn specs() -> Vec { "Move Appearance", [], None, - "{source: id, target: id, copy?: bool} give `target` (a layer, group or object) the appearance (fills, strokes, effects) and transparency (opacity, blend mode, isolation, knockout) of `source`, as dragging a target circle onto another in the Layers panel does; the source is left with a cleared appearance (as appearance.clear) unless `copy` (Alt-drag). Opacity masks stay; placed gradients keep their place relative to each object's bounds. 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 the object's opacity and blend mode (exceptions: docs/mcp.md) → {source, target}", + "{source: id, target: id, copy?: bool} give `target` (a layer, group or object) the appearance (fills, strokes, effects) and transparency (opacity, blend mode, isolation, knockout) of `source`, as dragging a target circle onto another in the Layers panel does; the source is left with a cleared appearance (as appearance.clear) unless `copy` (Alt-drag). Opacity masks stay; placed gradients keep their place relative to each object's bounds. On a path directly in a graph series (a series group's id stands for those paths; as `source`, when the group has no effect, opacity, blend mode, isolation, knockout or style link of its own, the topmost one is read and a move clears them all; as `target` each takes the appearance and the group is cleared, a `source` among them keeps its look, and a `source` that is the group's only path is an error), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions: docs/mcp.md) → {source, target}", has_doc, transfer ), @@ -416,9 +419,87 @@ pub(crate) fn appearance_targets(s: &Session, p: &Value) -> Result> if targets_contents(p)? { leaf_targets(s, &roots) } else { Ok(roots) } } -/// [`appearance_targets`] of `cmd`, which needs at least one. -fn require_targets(s: &Session, p: &Value, cmd: &str) -> Result> { +/// `ids` with each graph series group that has no fill or stroke row of its own replaced by the paths directly inside +/// it ([`super::graph::series_group_marks`]). A series group with rows, as a document saved earlier can hold, stays: +/// the Appearance panel lists those rows and edits them by index. +pub(crate) fn rowless_series_marks(d: &Document, ids: &[NodeId]) -> Vec { + super::graph::series_group_marks_where(d, ids, |group| group.appearance.items.is_empty()) +} + +/// Whether series group `group` holds nothing of its own, as the graph draws it: no fill or stroke row, no effect, the +/// default opacity, blend mode, isolation and knockout, and no graphic style link. +fn holds_no_look(group: &Node) -> bool { + let ap = &group.appearance; + ap.items.is_empty() + && ap.effects.is_empty() + && group.opacity == 1.0 + && group.blend == BlendMode::Normal + && !group.isolate + && group.knockout == Default::default() + && !group.knockout_shape + && group.extras().graphic_style.is_none() +} + +/// The objects whose appearance a command reads for `id`: a graph series group that holds nothing of its own +/// ([`holds_no_look`]) gives the paths directly inside it, backmost first. A series group with an effect, an opacity or +/// another attribute of its own is read itself, with that attribute. +fn look_holders(d: &Document, id: NodeId) -> Vec { + super::graph::series_group_marks_where(d, &[id], holds_no_look) +} + +/// The object whose appearance a command reads for `n`: a graph series group that holds nothing of its own stands for +/// the topmost path directly inside it ([`look_holders`]). +pub(crate) fn look_holder<'a>(d: &'a Document, n: &'a Node) -> &'a Node { + look_holders(d, n.id).last().and_then(|id| d.node(*id)).unwrap_or(n) +} + +/// Objects whose fill and stroke rows a command edits: the [`appearance_targets`], with a graph series group standing +/// for the paths directly inside it ([`rowless_series_marks`]), so the graph can store the edit. +pub(crate) fn row_targets(s: &Session, p: &Value) -> Result> { let ids = appearance_targets(s, p)?; + Ok(rowless_series_marks(&s.doc()?.doc, &ids)) +} + +/// Objects whose whole appearance a command edits: the [`row_targets`], then each graph series group they stand for, +/// which can hold effects and a graphic style link of its own. +pub(crate) fn whole_targets(s: &Session, p: &Value) -> Result> { + let own = appearance_targets(s, p)?; + let mut ids = rowless_series_marks(&s.doc()?.doc, &own); + let groups = stood_for(&own, &ids); + ids.extend(groups); + Ok(ids) +} + +/// The series groups among `own` that `ids` ([`rowless_series_marks`] of `own`) replaced with their paths. +pub(crate) fn stood_for(own: &[NodeId], ids: &[NodeId]) -> Vec { + let kept: HashSet = ids.iter().copied().collect(); + own.iter().copied().filter(|id| !kept.contains(id)).collect() +} + +/// Clear Appearance on each series group a command gave a whole new appearance through its paths, so the group's own +/// opacity, blend mode, isolation, knockout, effects and style link do not stay on top of it. +pub(crate) fn clear_stood_for(d: &mut Document, groups: &[NodeId]) { + for id in groups { + if let Some(n) = d.node_mut(*id) { + clear(n); + (n.isolate, n.knockout, n.knockout_shape) = (false, Default::default(), false); + n.extras_mut().graphic_style = None; + } + } +} + +/// [`whole_targets`] of `cmd`, which needs at least one. +fn require_whole_targets(s: &Session, p: &Value, cmd: &str) -> Result> { + let ids = whole_targets(s, p)?; + if ids.is_empty() { + return Err(bad(cmd, "select objects or give ids")); + } + Ok(ids) +} + +/// [`row_targets`] of `cmd`, which needs at least one. +fn require_targets(s: &Session, p: &Value, cmd: &str) -> Result> { + let ids = row_targets(s, p)?; if ids.is_empty() { return Err(bad(cmd, "select objects or give ids")); } @@ -616,7 +697,7 @@ fn add_item(s: &mut Session, p: &Value, fill: bool) -> Result { } fn clear_appearance(s: &mut Session, p: &Value) -> Result { - let ids = require_targets(s, p, "appearance.clear")?; + let ids = require_whole_targets(s, p, "appearance.clear")?; // When every object is cleared already, the document and its undo history stay as they are. let before = s.doc()?.doc.clone(); super::overprint::edit_counted(s, "Clear Appearance", |d| { @@ -732,35 +813,64 @@ fn transfer(s: &mut Session, p: &Value) -> Result { return Err(bad(C, "`source` and `target` are the same object")); } let copy = switch_or(p, "copy", false, C)?; + // A graph series group stands for the paths directly inside it: as the source, the topmost of them is read and a + // move clears them all; as the target, each of them other than a source takes the appearance. + let sources = look_holders(&s.doc()?.doc, source); + let read = sources.last().copied().unwrap_or(source); + let from: Vec = sources.iter().copied().chain(stood_for(&[source], &sources)).collect(); + let marks = rowless_series_marks(&s.doc()?.doc, &[target]); + let stands = !marks.contains(&target); + let within: HashSet = from.iter().copied().collect(); + let mut targets: Vec = marks.iter().copied().filter(|id| !within.contains(id)).collect(); + if targets.is_empty() { + if stands { + return Err(bad(C, "`source` is the only path in series group `target`")); + } + targets.push(target); + } + // A source that is one of the target group's paths keeps its look: the group stands for it too. + let part: HashSet = if stands { marks.into_iter().collect() } else { HashSet::new() }; + let from: Vec = stood_for(&from, &targets); + let cleared: Vec = if copy { vec![] } else { from.iter().copied().filter(|id| !part.contains(id)).collect() }; + // The group its paths stand for loses its own opacity, blend mode and effects, which would stay on top of them. + let group: Vec = if stands { vec![target] } else { vec![] }; // When both objects come out as they were, the document and its undo history stay as they are. let before = s.doc()?.doc.clone(); super::overprint::edit_counted(s, if copy { "Copy Appearance" } else { "Move Appearance" }, |d| { - let src = d.node(source).cloned().ok_or(EngineError::NoNode(source))?; - let to = d.node_mut(target).ok_or(EngineError::NoNode(target))?; - let mut ap = src.appearance.clone(); - if let (Some(f), Some(t)) = (src.geometric_bounds(), to.geometric_bounds()) { - ap.rebase_gradients(f, t); + d.node(source).ok_or(EngineError::NoNode(source))?; + let src = d.node(read).cloned().ok_or(EngineError::NoNode(read))?; + for id in &targets { + let to = d.node_mut(*id).ok_or(EngineError::NoNode(*id))?; + let mut ap = src.appearance.clone(); + if let (Some(f), Some(t)) = (src.geometric_bounds(), to.geometric_bounds()) { + ap.rebase_gradients(f, t); + } + // Only groups, layers, type and images have a Contents (Characters) row to keep a slot for. + if to.contents_label().is_none() { + ap.contents_index = None; + } + to.appearance = ap; + (to.opacity, to.blend, to.isolate, to.knockout, to.knockout_shape) = + (src.opacity, src.blend, src.isolate, src.knockout, src.knockout_shape); + super::object::snap_if_aligned(to); } - // Only groups, layers, type and images have a Contents (Characters) row to keep a slot for. - if to.contents_label().is_none() { - ap.contents_index = None; + clear_stood_for(d, &group); + for id in &cleared { + if let Some(n) = d.node_mut(*id) { + clear(n); + (n.isolate, n.knockout, n.knockout_shape) = (false, Default::default(), false); + super::object::snap_if_aligned(n); + } } - to.appearance = ap; - (to.opacity, to.blend, to.isolate, to.knockout, to.knockout_shape) = (src.opacity, src.blend, src.isolate, src.knockout, src.knockout_shape); - super::object::snap_if_aligned(to); - if !copy && let Some(n) = d.node_mut(source) { - clear(n); - (n.isolate, n.knockout, n.knockout_shape) = (false, Default::default(), false); - super::object::snap_if_aligned(n); - } - let changed = if copy { vec![target] } else { vec![source, target] }; + let changed: Vec = cleared.iter().chain(&targets).copied().collect(); let kept = super::graph::capture_series_opacity(d, &both_kinds(&changed)); - // The target last: on marks of one series, its paint is the one the series keeps. + // The targets last: on marks of one series, their paint is the one the series keeps. let mut rows = top_paint_changed(&before, d, &changed); - rows.extend(painted_rows(d, both_kinds(&[target]))); + rows.extend(painted_rows(d, both_kinds(&targets))); let painted = super::graph::capture_series_top_paints(d, &rows); let object = super::graph::capture_series_object_opacity(d, &changed); - Ok(count_changed(d, &before, &[source, target]) + usize::from(kept || painted || object)) + let all: Vec = from.iter().chain(&targets).chain(&group).copied().collect(); + Ok(count_changed(d, &before, &all) + usize::from(kept || painted || object)) })?; s.active_appearance_item = None; Ok(json!({ "source": source.0, "target": target.0 })) @@ -772,7 +882,7 @@ fn is_group(n: &Node) -> bool { } fn reduce_basic(s: &mut Session, p: &Value) -> Result { - let ids = require_targets(s, p, "appearance.reduceToBasic")?; + let ids = require_whole_targets(s, p, "appearance.reduceToBasic")?; // When every object comes out as it was, the document and its undo history stay as they are. let before = s.doc()?.doc.clone(); // The Appearance panel's active row (a row of the first selected object's stack, and in each @@ -828,7 +938,7 @@ fn set_item(s: &mut Session, p: &Value) -> Result { check_numbers(p, &["weight", "opacity"], "appearance.setItem")?; check_switches(p, &["visible"], "appearance.setItem")?; let paint = paint_from(s, p)?; - let ids = appearance_targets(s, p)?; + let ids = row_targets(s, p)?; if ids.is_empty() { return Err(bad("appearance.setItem", "select objects or give ids")); } @@ -1039,7 +1149,7 @@ fn duplicate_item(s: &mut Session, p: &Value) -> Result { /// `appearance.showAllHidden`: shows every hidden fill, stroke and effect of the selected objects. fn show_all_hidden(s: &mut Session, p: &Value) -> Result { - let roots = require_targets(s, p, "appearance.showAllHidden")?; + let roots = require_whole_targets(s, p, "appearance.showAllHidden")?; let before = s.doc()?.doc.clone(); let ids = s.edit("Show All Hidden Attributes", |d, _| { let shown: Vec = roots @@ -1069,11 +1179,16 @@ fn show_all_hidden(s: &mut Session, p: &Value) -> Result { fn move_item(s: &mut Session, p: &Value) -> Result { const C: &str = "appearance.moveItem"; let to = index_param(p, "to", C)?; - let ids = require_targets(s, p, C)?; let aligned = aligned(p, C)?; if p.get("from").and_then(Value::as_str) == Some("contents") { + // A graph series group's own Contents row, not its paths, which have none. + let ids = appearance_targets(s, p)?; + if ids.is_empty() { + return Err(bad(C, "select objects or give ids")); + } return move_contents(s, &ids, to); } + let ids = require_targets(s, p, C)?; // Where an aligned row would go in each of several different stacks isn't one place. if aligned && appearances_differ(&s.doc()?.doc, &ids) { return Err(bad(C, "rows of objects whose appearances differ can't be reordered together")); diff --git a/crates/engine/src/cmd/graph.rs b/crates/engine/src/cmd/graph.rs index 2c42494160..c45bbf5a67 100644 --- a/crates/engine/src/cmd/graph.rs +++ b/crates/engine/src/cmd/graph.rs @@ -46,7 +46,8 @@ use generate::generate; use series::default_series_color; pub(crate) use series::{ capture_label_anti_alias, capture_label_paragraphs, capture_label_styles, capture_series_object_opacity, capture_series_opacity, - capture_series_paints, capture_series_top_paints, paint_targets, series_object_opacity_differs, shown_paint, + capture_series_paints, capture_series_top_paints, paint_targets, series_group_marks, series_group_marks_where, series_object_opacity_differs, + shown_paint, }; #[cfg(test)] diff --git a/crates/engine/src/cmd/graph/series.rs b/crates/engine/src/cmd/graph/series.rs index 229a4d4b42..99a7ec084b 100644 --- a/crates/engine/src/cmd/graph/series.rs +++ b/crates/engine/src/cmd/graph/series.rs @@ -79,6 +79,11 @@ struct SeriesRef { index: usize, } +/// How many series groups `spec`'s graph has: a group whose index is past it (the index comes from the file) is not one. +fn series_count(spec: &GraphSpec) -> usize { + spec.rows.iter().map(Vec::len).max().unwrap_or(0).clamp(1, vectorcraft_doc::MAX_GRAPH_SERIES) +} + /// Every node in a graph's series groups (the groups too), found in one pass over the document. /// Axes, the legend and groups whose index is past the graph's series (the index comes from the /// file) are left out. @@ -86,7 +91,7 @@ fn series_members(doc: &Document) -> HashMap { let mut out = HashMap::new(); doc.walk(|n| { let Some(spec) = n.extras().graph.as_deref() else { return }; - let count = spec.rows.iter().map(Vec::len).max().unwrap_or(0).clamp(1, vectorcraft_doc::MAX_GRAPH_SERIES); + let count = series_count(spec); for group in n.children().into_iter().flatten() { let Some(index) = group.extras().series_index.and_then(|i| usize::try_from(i).ok()).filter(|i| *i < count) else { continue }; let r = SeriesRef { graph: n.id, group: group.id, index }; @@ -124,6 +129,38 @@ pub(crate) fn paint_targets(doc: &Document, ids: &[NodeId]) -> Vec { out } +/// `ids` with each graph series group replaced by the paths directly inside it, as [`paint_targets`] reads a series +/// group: the graph draws its series groups again with no rows of their own. A series group with no such path, other +/// ids and the art of a graph design pass through, and the order of `ids` is kept. +pub(crate) fn series_group_marks(doc: &Document, ids: &[NodeId]) -> Vec { + series_group_marks_where(doc, ids, |_| true) +} + +/// [`series_group_marks`] for the series groups `stands` accepts; the others pass through. +pub(crate) fn series_group_marks_where(doc: &Document, ids: &[NodeId], stands: impl Fn(&Node) -> bool) -> Vec { + // A series group is a child of a graph with one of the graph's series indexes ([`series_members`]). Each id is + // looked up through its parent, with no pass over the document: the panels call this while they draw. + let is_series_group = |n: &Node| { + let Some(index) = n.extras().series_index.and_then(|i| usize::try_from(i).ok()) else { return false }; + let graph = doc.parent_of(n.id).and_then(|parent| doc.node(parent)).and_then(|parent| parent.extras().graph.as_deref()); + graph.is_some_and(|spec| index < series_count(spec)) + }; + let mut seen = std::collections::HashSet::new(); + let mut out = Vec::new(); + for id in ids { + match doc.node(*id) { + Some(group) if is_series_group(group) && stands(group) => { + let marks: Vec = + group.children().into_iter().flatten().filter(|m| matches!(m.kind, NodeKind::Path { .. })).map(|m| m.id).collect(); + if marks.is_empty() { out.push(*id) } else { out.extend(marks) } + } + _ => out.push(*id), + } + } + out.retain(|id| seen.insert(*id)); + out +} + /// Copy the paint just applied to generated series art into that series' fill or stroke. Called /// inside the same document edit, so the visible paint and future regeneration undo together. /// Gradients, patterns and swatch links are kept as [`Paint`], not reduced to a solid colour. diff --git a/crates/engine/src/cmd/graph/tests.rs b/crates/engine/src/cmd/graph/tests.rs index aef1918a6d..dacb7d4eb0 100644 --- a/crates/engine/src/cmd/graph/tests.rs +++ b/crates/engine/src/cmd/graph/tests.rs @@ -1686,6 +1686,364 @@ fn redefining_a_graphic_style_from_a_series_mark_keeps_the_paint_another_mark_st assert_eq!(spec(&s, id).series_paints, was); } +/// Series 0's group, and whether it is as the graph draws it: the group has no rows of its own and each path directly +/// inside it has rows. +fn series_0_group(s: &Session, id: NodeId) -> (NodeId, bool) { + let n = s.doc().unwrap().doc.node(id).unwrap().clone(); + let g = series(&n, 0); + let drawn = g.appearance.items.is_empty() && g.children().unwrap().iter().all(|m| !m.appearance.items.is_empty()); + (g.id, drawn) +} + +/// `appearance.setItem` given a series group's id edits the paths directly inside it, so the graph stores the color and +/// opacity and every mark has them after the graph is drawn again. The group keeps no rows of its own. +#[test] +fn an_appearance_item_set_on_a_series_group_edits_its_marks() { + let (mut s, id, _, marks) = column_marks(); + let (group, drawn) = series_0_group(&s, id); + assert!(drawn); + let was = spec(&s, id).series_paints; + let row = top_row(&s, marks[0], true); + s.execute("appearance.setItem", &json!({"ids": [group.0], "index": row, "color": "#0000ff", "opacity": 40})).unwrap(); + assert!(series_0_group(&s, id).1, "the group has no rows of its own"); + let blue = s.doc().unwrap().doc.node(marks[0]).unwrap().appearance.fill_paint(); + let kept = spec(&s, id).series_paints[0].clone(); + assert_eq!((kept.fill.clone(), kept.fill_opacity), (Some(blue.clone()), Some(0.4))); + let (stroke, weight) = { + let m = s.doc().unwrap().doc.node(marks[0]).unwrap().clone(); + (m.appearance.stroke_paint(), m.appearance.stroke_width()) + }; + series_0_is(&mut s, id, (&blue, 0.4, &stroke, weight), &was); +} + +/// The other Appearance commands given a series group's id, picked with Group Selection or given in `ids`, edit the +/// paths directly inside it, and the graph stores what they change: Add New Fill, Clear Appearance, Move Appearance onto +/// the group, and an opacity set on a row with `transparency.set`. +#[test] +fn appearance_commands_given_a_series_group_edit_its_marks() { + let (mut s, id, marks) = stored_red_stroke(); + let (group, _) = series_0_group(&s, id); + s.execute("select.set", &json!({"ids": [group.0]})).unwrap(); + s.execute("appearance.addFill", &json!({})).unwrap(); + assert!(series_0_group(&s, id).1, "Add New Fill on the selected group"); + let rows = s.doc().unwrap().doc.node(marks[0]).unwrap().appearance.items.iter().filter(|it| it.is_fill()).count(); + assert_eq!(rows, 2, "each mark has a new fill row"); + s.execute("edit.undo", &json!({})).unwrap(); + + let row = top_row(&s, marks[0], true); + s.execute("transparency.set", &json!({"ids": [group.0], "item": row, "opacity": 30})).unwrap(); + assert!(series_0_group(&s, id).1); + assert_eq!(spec(&s, id).series_paints[0].fill_opacity, Some(0.3)); + s.execute("edit.undo", &json!({})).unwrap(); + + s.execute("appearance.clear", &json!({"ids": [group.0]})).unwrap(); + assert_eq!(spec(&s, id).series_paints[0].fill, Some(Paint::None)); + s.execute("edit.undo", &json!({})).unwrap(); + + let (rect, blue) = blue_style(&mut s, "Blue", false); + let was = spec(&s, id).series_paints; + s.execute("object.setProps", &json!({"ids": [group.0], "opacity": 50})).unwrap(); + s.execute("appearance.transfer", &json!({"source": rect.0, "target": group.0, "copy": true})).unwrap(); + assert!(series_0_group(&s, id).1); + assert_eq!(s.doc().unwrap().doc.node(group).unwrap().opacity, 1.0, "the appearance replaces the group's own opacity"); + let kept = spec(&s, id).series_paints[0].clone(); + assert_eq!((kept.fill.clone(), kept.fill_opacity, kept.stroke), (Some(blue.clone()), Some(0.5), Some(Paint::None))); + series_0_is(&mut s, id, (&blue, 0.5, &Paint::None, 0.0), &was); +} + +/// Moving the Contents row of a series group as the graph draws it, with no rows of its own, moves the group's own +/// row: the paths inside it have none. +#[test] +fn moving_a_series_groups_contents_row_moves_its_own_row() { + let (mut s, id, _, _) = column_marks(); + let (group, drawn) = series_0_group(&s, id); + assert!(drawn); + let out = s.execute("appearance.moveItem", &json!({"ids": [group.0], "from": "contents", "to": 0})).unwrap(); + assert_eq!(out["contents"], json!(0)); +} + +/// Add New Stroke, Duplicate Item, Reorder Appearance Item and Remove Item given a series group's id edit the rows of +/// the paths directly inside it, and the group keeps no rows of its own. +#[test] +fn row_commands_given_a_series_group_edit_its_marks_rows() { + let (mut s, id, _, marks) = column_marks(); + let (group, _) = series_0_group(&s, id); + let count = |s: &Session, fill: bool| -> Vec { + let d = &s.doc().unwrap().doc; + marks.iter().map(|m| d.node(*m).unwrap().appearance.items.iter().filter(|it| it.is_fill() == fill).count()).collect() + }; + let (fills, strokes) = (count(&s, true), count(&s, false)); + s.execute("appearance.addStroke", &json!({"ids": [group.0]})).unwrap(); + assert_eq!(count(&s, false), strokes.iter().map(|n| n + 1).collect::>(), "each mark has a new stroke row"); + let fill = top_row(&s, marks[0], true); + s.execute("appearance.duplicateItem", &json!({"ids": [group.0], "index": fill})).unwrap(); + assert_eq!(count(&s, true), fills.iter().map(|n| n + 1).collect::>(), "each mark has a copy of its fill row"); + let rows = s.doc().unwrap().doc.node(marks[0]).unwrap().appearance.items.len(); + let out = s.execute("appearance.moveItem", &json!({"ids": [group.0], "from": 0, "to": rows - 1})).unwrap(); + assert_eq!(out["index"], json!(rows - 1)); + s.execute("appearance.removeItem", &json!({"ids": [group.0], "index": top_row(&s, marks[0], true)})).unwrap(); + assert_eq!(count(&s, true), fills); + assert!(series_0_group(&s, id).1, "the group has no rows of its own"); +} + +/// Reduce to Basic Appearance given a series group's id reduces the paths directly inside it and drops an effect the +/// group holds. +#[test] +fn reducing_a_series_group_reduces_its_marks_and_drops_its_own_effect() { + let (mut s, id, _, marks) = column_marks(); + let (group, _) = series_0_group(&s, id); + s.execute("appearance.addFill", &json!({"ids": [group.0]})).unwrap(); + s.execute("effect.apply", &json!({"ids": [group.0], "effect": "distort.twist"})).unwrap(); + s.execute("appearance.reduceToBasic", &json!({"ids": [group.0]})).unwrap(); + let d = &s.doc().unwrap().doc; + assert!(d.node(group).unwrap().appearance.effects.is_empty(), "the group's effect is dropped"); + assert!(marks.iter().all(|m| d.node(*m).unwrap().appearance.items.iter().filter(|it| it.is_fill()).count() == 1)); + assert!(series_0_group(&s, id).1); +} + +/// A graphic style added on top (Alt-click) given a series group's id adds its rows to the paths directly inside the +/// group and unlinks a group that held a style link. +#[test] +fn a_graphic_style_added_to_a_series_group_adds_rows_to_its_marks_and_unlinks_the_group() { + let (mut s, id, _, marks) = column_marks(); + let (group, _) = series_0_group(&s, id); + blue_style(&mut s, "Blue", false); + let style = s.doc().unwrap().doc.graphic_style("Blue").unwrap().id; + s.edit("Link", |d, _| { + d.node_mut(group).unwrap().extras_mut().graphic_style = Some(style); + Ok(()) + }) + .unwrap(); + let fills = |s: &Session, m: NodeId| s.doc().unwrap().doc.node(m).unwrap().appearance.items.iter().filter(|it| it.is_fill()).count(); + let was = fills(&s, marks[0]); + s.execute("graphicStyle.apply", &json!({"name": "Blue", "ids": [group.0], "add": true})).unwrap(); + assert!(marks.iter().all(|m| fills(&s, *m) == was + 1), "each mark has the style's fill on top"); + assert!(series_0_group(&s, id).1, "the group takes no rows of the style"); + assert_eq!(s.doc().unwrap().doc.node(group).unwrap().extras().graphic_style, None, "the group is unlinked"); +} + +/// Move Appearance from one of a series group's paths onto the group gives the other paths its look and leaves that +/// path as it was. When the path is the only one directly in the group, the command is refused and the group takes no +/// rows. +#[test] +fn moving_an_appearance_from_a_mark_onto_its_own_series_group_keeps_the_mark() { + let (mut s, id, _, marks) = column_marks(); + let (group, _) = series_0_group(&s, id); + s.execute("appearance.setItem", &json!({"ids": [marks[0].0], "index": top_row(&s, marks[0], true), "color": "#00ff00"})).unwrap(); + let green = s.doc().unwrap().doc.node(marks[0]).unwrap().appearance.fill_paint(); + s.execute("appearance.transfer", &json!({"source": marks[0].0, "target": group.0})).unwrap(); + let d = &s.doc().unwrap().doc; + assert!(marks.iter().all(|m| d.node(*m).unwrap().appearance.fill_paint() == green), "every mark, the source too, is green"); + assert_eq!(spec(&s, id).series_paints[0].fill, Some(green)); + + s.edit("One path", |d, _| { + d.children_mut(Some(group)).unwrap().truncate(1); + Ok(()) + }) + .unwrap(); + let only = s.doc().unwrap().doc.node(group).unwrap().children().unwrap()[0].id; + let err = s.execute("appearance.transfer", &json!({"source": only.0, "target": group.0})).unwrap_err(); + assert!(err.to_string().contains("only path"), "{err}"); + assert!(series_0_group(&s, id).1, "the group has no rows of its own"); +} + +/// A series group that holds an opacity and an effect of its own is read itself as a source, as any group is: a new +/// graphic style and Move Appearance take the group's opacity and effect, and the group, not a path, is linked. +#[test] +fn a_series_group_with_a_look_of_its_own_is_read_itself_as_a_source() { + let (mut s, id, _, marks) = column_marks(); + let (group, _) = series_0_group(&s, id); + s.execute("transparency.set", &json!({"ids": [group.0], "opacity": 50, "item": null})).unwrap(); + s.execute("effect.apply", &json!({"ids": [group.0], "effect": "distort.twist"})).unwrap(); + s.execute("graphicStyle.new", &json!({"id": group.0, "name": "Series"})).unwrap(); + let d = &s.doc().unwrap().doc; + let style = d.graphic_style("Series").unwrap(); + assert_eq!((style.opacity, style.appearance.effects.len()), (0.5, 1)); + assert_eq!(d.node(group).unwrap().extras().graphic_style, Some(style.id)); + assert!(marks.iter().all(|m| d.node(*m).unwrap().extras().graphic_style.is_none())); + + let rect = NodeId(s.execute("shape.rectangle", &json!({"x": 600, "y": 600, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap()); + s.execute("appearance.transfer", &json!({"source": group.0, "target": rect.0, "copy": true})).unwrap(); + let r = s.doc().unwrap().doc.node(rect).unwrap().clone(); + assert_eq!((r.opacity, r.appearance.effects.len()), (0.5, 1)); +} + +/// Clear Appearance and Show All Hidden Attributes given a series group's id also reach an effect the group holds, and +/// Break Link to Graphic Style unlinks the paths a style applied to the group linked. +#[test] +fn whole_appearance_commands_given_a_series_group_edit_the_group_and_its_marks() { + let (mut s, id, marks) = stored_red_stroke(); + let (group, _) = series_0_group(&s, id); + let effects = |s: &Session| s.doc().unwrap().doc.node(group).unwrap().appearance.effects.clone(); + s.execute("effect.apply", &json!({"ids": [group.0], "effect": "distort.twist"})).unwrap(); + s.execute("effect.setParams", &json!({"ids": [group.0], "index": 0, "visible": false, "item": null})).unwrap(); + assert!(!effects(&s)[0].visible); + let shown = s.execute("appearance.showAllHidden", &json!({"ids": [group.0]})).unwrap(); + assert_eq!(shown["ids"], json!([group.0])); + assert!(effects(&s)[0].visible); + s.execute("appearance.clear", &json!({"ids": [group.0]})).unwrap(); + assert!(effects(&s).is_empty(), "the group's effect is cleared with its marks' rows"); + assert_eq!(spec(&s, id).series_paints[0].fill, Some(Paint::None)); + s.execute("edit.undo", &json!({})).unwrap(); + + blue_style(&mut s, "Blue", false); + s.execute("select.set", &json!({"ids": [group.0]})).unwrap(); + s.execute("graphicStyle.apply", &json!({"name": "Blue"})).unwrap(); + assert_eq!(s.selection_graphic_style().map(|(g, linked)| (g.name.clone(), linked)), Some(("Blue".into(), true))); + s.execute("graphicStyle.breakLink", &json!({})).unwrap(); + let d = &s.doc().unwrap().doc; + assert!(marks.iter().all(|m| d.node(*m).unwrap().extras().graphic_style.is_none()), "each mark is unlinked"); + assert!(s.selection_graphic_style().is_none()); +} + +/// Redefine Graphic Style on a selected series group whose paths a style links takes the look of the topmost of them. +#[test] +fn redefining_a_graphic_style_from_a_selected_series_group_reads_its_topmost_mark() { + let (mut s, id, marks) = stored_red_stroke(); + let (group, _) = series_0_group(&s, id); + blue_style(&mut s, "Blue", false); + s.execute("select.set", &json!({"ids": [group.0]})).unwrap(); + s.execute("graphicStyle.apply", &json!({"name": "Blue"})).unwrap(); + let top = *marks.last().unwrap(); + s.execute("appearance.setItem", &json!({"ids": [top.0], "index": top_row(&s, top, true), "color": "#00ff00"})).unwrap(); + let green = s.doc().unwrap().doc.node(top).unwrap().appearance.fill_paint(); + s.execute("graphicStyle.redefine", &json!({})).unwrap(); + let d = &s.doc().unwrap().doc; + assert_eq!(d.graphic_style("Blue").unwrap().appearance.fill_paint(), green); + assert!(marks.iter().all(|m| d.node(*m).unwrap().appearance.fill_paint() == green), "the marks still linked follow"); +} + +/// A series group as the graph draws it, read as a source, gives the look of the topmost path directly inside it: New +/// Graphic Style keeps that path's fill and links it, Move Appearance copies it, and a move clears every path of the +/// group. +#[test] +fn a_series_group_read_as_a_source_gives_its_topmost_marks_look() { + let (mut s, id, marks) = stored_red_stroke(); + let (group, _) = series_0_group(&s, id); + let top = *marks.last().unwrap(); + s.execute("appearance.setItem", &json!({"ids": [group.0], "index": top_row(&s, marks[0], true), "color": "#0000ff", "opacity": 30})).unwrap(); + s.execute("appearance.setItem", &json!({"ids": [marks[0].0], "index": top_row(&s, marks[0], true), "color": "#00ff00"})).unwrap(); + let look = s.doc().unwrap().doc.node(top).unwrap().appearance.clone(); + assert_ne!(look.fill_paint(), s.doc().unwrap().doc.node(marks[0]).unwrap().appearance.fill_paint()); + s.execute("graphicStyle.new", &json!({"id": group.0, "name": "Series"})).unwrap(); + let d = &s.doc().unwrap().doc; + assert_eq!(d.graphic_style("Series").unwrap().appearance.fill_paint(), look.fill_paint()); + assert_eq!(d.node(top).unwrap().extras().graphic_style, Some(d.graphic_style("Series").unwrap().id)); + + let rect = NodeId(s.execute("shape.rectangle", &json!({"x": 600, "y": 600, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap()); + s.execute("appearance.transfer", &json!({"source": group.0, "target": rect.0})).unwrap(); + let d = &s.doc().unwrap().doc; + assert_eq!(d.node(rect).unwrap().appearance.fill_paint(), look.fill_paint()); + assert!(marks.iter().all(|m| d.node(*m).unwrap().appearance.fill_paint() == Paint::None), "the move clears each mark"); + assert_eq!(spec(&s, id).series_paints[0].fill, Some(Paint::None)); +} + +/// A series group that has a row of its own, as a document saved earlier can hold, is edited itself: the Appearance +/// panel lists that row and edits it by its index. +#[test] +fn a_series_group_with_a_row_of_its_own_is_edited_itself() { + let (mut s, id, _, marks) = column_marks(); + let (group, _) = series_0_group(&s, id); + s.edit("Row", |d, _| { + let g = d.node_mut(group).unwrap(); + g.appearance = vectorcraft_doc::Appearance::basic(Paint::None, Paint::None, 1.0).into(); + Ok(()) + }) + .unwrap(); + let was = s.doc().unwrap().doc.node(marks[0]).unwrap().appearance.clone(); + s.execute("appearance.setItem", &json!({"ids": [group.0], "index": top_row(&s, group, true), "color": "#0000ff"})).unwrap(); + let d = &s.doc().unwrap().doc; + assert_ne!(d.node(group).unwrap().appearance.fill_paint(), Paint::None); + assert_eq!(d.node(marks[0]).unwrap().appearance, was, "the marks keep their rows"); +} + +/// A graphic style applied to a series group's id styles and links the paths directly inside it, and the graph stores +/// the style's fill and stroke. +#[test] +fn a_graphic_style_applied_to_a_series_group_styles_its_marks() { + let (mut s, id, marks) = stored_red_stroke(); + let (group, _) = series_0_group(&s, id); + let (_, blue) = blue_style(&mut s, "Blue", false); + let was = spec(&s, id).series_paints; + let own = json!({"ids": [group.0], "opacity": 50, "blend": "multiply", "isolate": true, "knockout": "on", "item": null}); + s.execute("transparency.set", &own).unwrap(); + s.execute("effect.apply", &json!({"ids": [group.0], "effect": "distort.twist"})).unwrap(); + let g = s.doc().unwrap().doc.node(group).unwrap().clone(); + assert!(g.isolate && g.knockout != Default::default() && g.blend != vectorcraft_color::BlendMode::Normal); + s.execute("graphicStyle.apply", &json!({"name": "Blue", "ids": [group.0]})).unwrap(); + assert!(series_0_group(&s, id).1, "the group takes no rows of the style"); + let g = s.doc().unwrap().doc.node(group).unwrap().clone(); + assert_eq!((g.opacity, g.isolate), (1.0, false), "the style replaces the group's own opacity and isolation"); + assert_eq!((g.blend, g.knockout), (vectorcraft_color::BlendMode::Normal, Default::default()), "and its blend mode and knockout"); + assert!(g.appearance.effects.is_empty(), "and its effects"); + let style = s.doc().unwrap().doc.graphic_style("Blue").unwrap().id; + let d = &s.doc().unwrap().doc; + assert!(marks.iter().all(|m| d.node(*m).unwrap().extras().graphic_style == Some(style)), "each mark is linked to the style"); + assert_eq!(d.node(group).unwrap().extras().graphic_style, None); + let kept = spec(&s, id).series_paints[0].clone(); + assert_eq!((kept.fill.clone(), kept.fill_opacity, kept.stroke), (Some(blue.clone()), Some(0.5), Some(Paint::None))); + series_0_is(&mut s, id, (&blue, 0.5, &Paint::None, 0.0), &was); +} + +/// Redefine Graphic Style on a series group linked to the style (as a file can hold it) restyles the paths directly +/// inside the group and links them, and the graph stores the new look; the group goes back to no rows of its own. +#[test] +fn redefining_a_graphic_style_restyles_the_marks_of_a_linked_series_group() { + let (mut s, id, marks) = stored_red_stroke(); + let (group, _) = series_0_group(&s, id); + let (rect, _) = blue_style(&mut s, "Blue", false); + let style = s.doc().unwrap().doc.graphic_style("Blue").unwrap().clone(); + s.edit("Link", |d, _| { + let g = d.node_mut(group).unwrap(); + g.appearance = style.appearance.clone().into(); + g.extras_mut().graphic_style = Some(style.id); + Ok(()) + }) + .unwrap(); + s.execute("appearance.setItem", &json!({"ids": [rect.0], "index": top_row(&s, rect, true), "color": "#00ff00", "opacity": 100})).unwrap(); + let green = s.doc().unwrap().doc.node(rect).unwrap().appearance.fill_paint(); + let was = spec(&s, id).series_paints; + s.execute("graphicStyle.redefine", &json!({"name": "Blue", "id": rect.0})).unwrap(); + assert!(series_0_group(&s, id).1, "the group has no rows of its own"); + let d = &s.doc().unwrap().doc; + assert_eq!(d.node(group).unwrap().extras().graphic_style, None); + assert!(marks.iter().all(|m| d.node(*m).unwrap().extras().graphic_style == Some(style.id))); + assert!(marks.iter().all(|m| d.node(*m).unwrap().appearance.fill_paint() == green)); + let kept = spec(&s, id).series_paints[0].clone(); + assert_eq!((kept.fill.clone(), kept.fill_opacity, kept.stroke), (Some(green.clone()), None, Some(Paint::None))); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(spec(&s, id).series_paints, was, "one undo takes back the redefinition and what the graph stored"); + s.execute("edit.redo", &json!({})).unwrap(); + series_0_is(&mut s, id, (&green, 1.0, &Paint::None, 0.0), &was); +} + +/// Redefine Graphic Style on a linked series group leaves a path of the group that is linked to the style but no +/// longer has its look as it is, unlinked, and restyles the group's other paths. +#[test] +fn redefining_a_graphic_style_keeps_an_edited_mark_of_a_linked_series_group() { + let (mut s, id, _, marks) = column_marks(); + let (group, _) = series_0_group(&s, id); + let (rect, _) = blue_style(&mut s, "Blue", false); + let style = s.doc().unwrap().doc.graphic_style("Blue").unwrap().clone(); + s.edit("Link", |d, _| { + let g = d.node_mut(group).unwrap(); + g.appearance = style.appearance.clone().into(); + g.extras_mut().graphic_style = Some(style.id); + d.node_mut(marks[0]).unwrap().extras_mut().graphic_style = Some(style.id); + Ok(()) + }) + .unwrap(); + let edited = s.doc().unwrap().doc.node(marks[0]).unwrap().appearance.clone(); + s.execute("appearance.setItem", &json!({"ids": [rect.0], "index": top_row(&s, rect, true), "color": "#00ff00", "opacity": 100})).unwrap(); + let green = s.doc().unwrap().doc.node(rect).unwrap().appearance.fill_paint(); + s.execute("graphicStyle.redefine", &json!({"name": "Blue", "id": rect.0})).unwrap(); + let d = &s.doc().unwrap().doc; + let first = d.node(marks[0]).unwrap(); + assert_eq!((&first.appearance, first.extras().graphic_style), (&edited, None), "the edited mark keeps its look, unlinked"); + assert!(marks[1..].iter().all(|m| d.node(*m).unwrap().appearance.fill_paint() == green)); + assert!(marks[1..].iter().all(|m| d.node(*m).unwrap().extras().graphic_style == Some(style.id))); +} + /// Default Fill and Stroke on a series mark stores a white fill and a 1 pt black stroke, both opaque, on the graph. #[test] fn default_fill_and_stroke_on_a_series_mark_is_kept() { diff --git a/crates/engine/src/cmd/paint.rs b/crates/engine/src/cmd/paint.rs index eaf1597423..3464df3833 100644 --- a/crates/engine/src/cmd/paint.rs +++ b/crates/engine/src/cmd/paint.rs @@ -6,7 +6,7 @@ use serde_json::{Value, json}; use vectorcraft_color::{BlendMode, Color, GradientPaint, Paint}; use vectorcraft_doc::{Appearance, CharStyle, Document, GraySource, Node, NodeId, NodeKind}; -use super::appearance::{ItemTarget, appearance_targets, edit_items, edit_items_then, item_target}; +use super::appearance::{ItemTarget, edit_items, edit_items_then, item_target, row_targets}; use super::gradient::{item_paint_bounds, place_paint, place_run_paint, run_paint_mut, run_stroke_weight, unplaced}; use super::{ Affine, CommandSpec, Result, Session, always, bad, bool_or, check_numbers, check_switches, cmd, color_value, has_doc, leaf_targets, ok, @@ -73,7 +73,7 @@ pub fn specs() -> Vec { "Transparency", ["Window", "Transparency"], None, - "{ids?|id?, opacity?: 0..100, blend?: name, isolate?, knockout?: \"on\"|\"off\"|\"neutral\"|bool (true = on, false = neutral), knockoutShape?: bool, item?: appearance item index|null, target?: \"object\"|\"contents\", 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)} for `ids`, the selection, or the object whose opacity mask is being edited; opacity and blend go to the targeted fill/stroke item (omitted: the Appearance panel's active item, else the objects; a gradient mesh point last clicked with the Mesh tool or Direct Selection takes the opacity itself). With an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, opacity and blend change that object for this instance only (isolate, knockout, knockoutShape, aligned and target are refused). On a path directly in a graph series, the graph also stores the opacity and blend mode of the object and of the topmost visible fill and stroke (exceptions: docs/mcp.md)", + "{ids?|id?, opacity?: 0..100, blend?: name, isolate?, knockout?: \"on\"|\"off\"|\"neutral\"|bool (true = on, false = neutral), knockoutShape?: bool, item?: appearance item index|null, target?: \"object\"|\"contents\", 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)} for `ids`, the selection, or the object whose opacity mask is being edited; opacity and blend go to the targeted fill/stroke item (omitted: the Appearance panel's active item, else the objects; a gradient mesh point last clicked with the Mesh tool or Direct Selection takes the opacity itself). With an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, opacity and blend change that object for this instance only (isolate, knockout, knockoutShape, aligned and target are refused). On a path directly in a graph series (for a fill or stroke item, a series group's id stands for those paths), the graph also stores the opacity and blend mode of the object and of the topmost visible fill and stroke (exceptions: docs/mcp.md)", has_doc, transparency ), @@ -1062,7 +1062,7 @@ fn transparency(s: &mut Session, p: &Value) -> Result { return s.execute("object.setProps", &Value::Object(q)); }; // Opacity and blend belong to the targeted fill/stroke; isolate/knockout/knockoutShape stay object-level. - let item_ids = if editing_mask { ids } else { appearance_targets(s, p)? }; + let item_ids = if editing_mask { ids } else { row_targets(s, p)? }; if explicit { let d = &s.doc()?.doc; if !item_ids.iter().any(|id| d.node(*id).is_some_and(|n| index < n.appearance.items.len())) { diff --git a/crates/engine/src/cmd/style.rs b/crates/engine/src/cmd/style.rs index bca9ed6ea9..65fe18b282 100644 --- a/crates/engine/src/cmd/style.rs +++ b/crates/engine/src/cmd/style.rs @@ -14,7 +14,7 @@ //! paint shows instead of the character colour under it. use std::borrow::Cow; -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use serde_json::{Value, json}; use vectorcraft_color::Paint; @@ -31,7 +31,7 @@ pub fn specs() -> Vec { "Apply Graphic Style", ["Window", "Graphic Styles"], None, - "{name, add?: bool, ids?|id? (layers too), target?: \"object\"|\"contents\"} give the objects (default: the selection; a group or layer itself, its fills and strokes painting its members and its effects applying to them as one piece; target contents: the objects inside instead) the style's appearance, opacity, blend mode, isolate and knockout, and link them to it (placed gradients land at the same place relative to each object's bounds); add: true (Alt-click) adds its fills, strokes and effects on top of the existing appearance instead and unlinks. 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 (with `add`: of the kinds of row the style shows) and, without `add`, the object's opacity and blend mode (exceptions: docs/mcp.md). With nothing selected (and no ids) the next object drawn takes the style instead (see appearance.newArt) → {newArt: true}", + "{name, add?: bool, ids?|id? (layers too), target?: \"object\"|\"contents\"} give the objects (default: the selection; a group or layer itself, its fills and strokes painting its members and its effects applying to them as one piece; target contents: the objects inside instead) the style's appearance, opacity, blend mode, isolate and knockout, and link them to it (placed gradients land at the same place relative to each object's bounds); add: true (Alt-click) adds its fills, strokes and effects on top of the existing appearance instead and unlinks. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (with `add`: of the kinds of row the style shows) and, without `add`, the object's opacity and blend mode (exceptions: docs/mcp.md). With nothing selected (and no ids) the next object drawn takes the style instead (see appearance.newArt) → {newArt: true}", has_doc, style_apply ), @@ -40,7 +40,7 @@ pub fn specs() -> Vec { "New Graphic Style", ["Window", "Graphic Styles"], None, - "{name?, id?} a style from object `id` or the first selected object: its appearance, opacity, blend mode, isolate and knockout (a group without fills or strokes of its own lends its topmost object's, type its characters'; placed gradients are kept relative to its bounds); links the object. Names are made unique → {name}", + "{name?, id?} a style from object `id` or the first selected object: its appearance, opacity, blend mode, isolate and knockout (a group without fills or strokes of its own lends its topmost object's, type its characters'; a graph series group with no fill, stroke, effect, opacity, blend mode, isolation, knockout or style link of its own stands for the topmost path directly in it; placed gradients are kept relative to its bounds); links the object. Names are made unique → {name}", has_doc, style_new ), @@ -68,7 +68,7 @@ pub fn specs() -> Vec { "Redefine Graphic Style", ["Window", "Appearance"], None, - "{name?, id?} replace the style (default: the one the object was last linked to) with the look of object `id` or the first selected object; the objects still linked to it update, and that object becomes linked. On a linked 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 the object's opacity and blend mode (exceptions: docs/mcp.md) → {name}", + "{name?, id?} replace the style (default: the one the object was last linked to) with the look of object `id` or the first selected object (a graph series group with no fill, stroke, effect, opacity, blend mode, isolation, knockout or style link of its own: the topmost path directly in it); the objects still linked to it update, and that object becomes linked. A linked graph series group passes the style to the paths directly in it, other than the source and paths linked to the style whose look was edited, and is left cleared (as appearance.clear) and unlinked. On a linked 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 the object's opacity and blend mode (exceptions: docs/mcp.md) → {name}", has_doc, style_redefine ), @@ -77,7 +77,7 @@ pub fn specs() -> Vec { "Break Link to Graphic Style", ["Window", "Graphic Styles"], None, - "{ids?|id?, target?: \"object\"|\"contents\"} unlink the objects (default: the selection) from their graphic style; they keep their look", + "{ids?|id?, target?: \"object\"|\"contents\"} unlink the objects (default: the selection) from their graphic style; they keep their look. A graph series group's id stands for the group and the paths directly in it", has_doc, style_break_link ), @@ -307,10 +307,11 @@ fn source<'a>(s: &'a Session, p: &Value, cmd: &str) -> Result<(NodeId, &'a Node) impl Session { /// The graphic style of the first selected object: the one it was last linked to, and whether - /// it is still linked (still has that style's look). + /// it is still linked (still has that style's look). A graph series group that holds nothing of its own stands + /// for the topmost path directly inside it, which a style applied to the group links. pub fn selection_graphic_style(&self) -> Option<(&GraphicStyle, bool)> { let st = self.active()?; - let n = st.doc.node(*st.selection.subjects().first()?)?; + let n = super::appearance::look_holder(&st.doc, st.doc.node(*st.selection.subjects().first()?)?); let g = st.doc.graphic_style_by_id(n.extras().graphic_style?)?; Some((g, in_sync(n, g))) } @@ -331,7 +332,11 @@ fn style_apply(s: &mut Session, p: &Value) -> Result { let i = style_index(&s.doc()?.doc, name)?; let add = bool_or(p, "add", false); let chars = s.prefs.override_char_color; - let ids = super::appearance::appearance_targets(s, p)?; + let own = super::appearance::appearance_targets(s, p)?; + let ids = super::appearance::rowless_series_marks(&s.doc()?.doc, &own); + // The series groups their paths stand for: a style that replaces the appearance clears what they hold themselves, + // and a style added on top unlinks them. + let groups = super::appearance::stood_for(&own, &ids); if ids.is_empty() { if p.get("ids").is_some() || p.get("id").is_some() { return Err(bad("graphicStyle.apply", "no such objects")); @@ -353,6 +358,8 @@ fn style_apply(s: &mut Session, p: &Value) -> Result { n.extras_mut().graphic_style = None; } } + // The series groups their paths stand for are unlinked with them. + set_link(d, &groups, None); // The graph stores the rows of the kinds the style shows, now on top of each stack. let shows = |kind: bool| g.appearance.items.iter().any(|it| it.is_fill() == kind && it.visible()); let kinds = (shows(true), shows(false)); @@ -364,6 +371,7 @@ fn style_apply(s: &mut Session, p: &Value) -> Result { for id in &ids { apply_style(d, *id, &g, &mut shared, chars); } + super::appearance::clear_stood_for(d, &groups); super::appearance::capture_series_writes(&before, d, &ids, (true, true), (true, true), false, true); } Ok(()) @@ -372,8 +380,11 @@ fn style_apply(s: &mut Session, p: &Value) -> Result { } fn style_new(s: &mut Session, p: &Value) -> Result { - let (src, n) = source(s, p, "graphicStyle.new")?; + let (_, n) = source(s, p, "graphicStyle.new")?; let d = &s.doc()?.doc; + // A series group that holds nothing of its own shows the look of its paths: the style is made from the topmost. + let n = super::appearance::look_holder(d, n); + let src = n.id; let name = match str_param(p, "name").map(str::trim).filter(|n| !n.is_empty()) { Some(n) => unique_name(n, |x| d.graphic_style(x).is_some()), None => d.new_graphic_style_name(), @@ -459,6 +470,9 @@ fn style_redefine(s: &mut Session, p: &Value) -> Result { let cmd = "graphicStyle.redefine"; let (src, n) = source(s, p, cmd)?; let d = &s.doc()?.doc; + // A series group that holds nothing of its own is redefined from the topmost of its paths, which a style links. + let n = super::appearance::look_holder(d, n); + let src = if n.id == src { src } else { n.id }; let i = match str_param(p, "name") { Some(name) => style_index(d, name)?, None => n @@ -480,12 +494,18 @@ fn style_redefine(s: &mut Session, p: &Value) -> Result { let linked = objects_where(d, |n| n.extras().graphic_style == Some(id) && n.id != src); let (follow, edited): (Vec, Vec) = linked.into_iter().partition(|nid| d.node(*nid).is_some_and(|n| in_sync(n, &old))); set_link(d, &edited, None); + // A linked graph series group passes the style to the paths directly inside it, so the graph stores it, and + // goes back to the empty appearance the graph draws it with. The source and the edited paths keep their look. + let mut follow_marks = super::graph::series_group_marks(d, &follow); + let edited: HashSet = edited.into_iter().collect(); + follow_marks.retain(|nid| *nid != src && !edited.contains(nid)); + super::appearance::clear_stood_for(d, &super::appearance::stood_for(&follow, &follow_marks)); let g = d.graphic_styles[i].clone(); let mut shared = None; - for nid in &follow { + for nid in &follow_marks { apply_style(d, *nid, &g, &mut shared, chars); } - super::appearance::capture_series_writes(&before, d, &follow, (true, true), (true, true), false, true); + super::appearance::capture_series_writes(&before, d, &follow_marks, (true, true), (true, true), false, true); set_link(d, &[src], Some(id)); Ok(()) })?; @@ -493,7 +513,7 @@ fn style_redefine(s: &mut Session, p: &Value) -> Result { } fn style_break_link(s: &mut Session, p: &Value) -> Result { - let ids = super::appearance::appearance_targets(s, p)?; + let ids = super::appearance::whole_targets(s, p)?; s.edit("Break Link to Graphic Style", |d, _| { set_link(d, &ids, None); Ok(()) diff --git a/docs/mcp.md b/docs/mcp.md index 274db05a34..41c5d84f48 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -758,9 +758,31 @@ designs keep their own paint. A row that had no paint before the command and has none after it does not change the paint the graph stores. `paint.setFill`, `paint.setStroke`, `paint.none` and the commands that apply one paint kind to the other store the topmost row of the kind even when it is hidden, and store a stroke set on a band. `stroke.set`, `paint.editGradient` and the recolor commands do -not store a series' paint. An `appearance.*` command or `graphicStyle.apply` given a series group's id, and -`graphicStyle.redefine` on a series group linked to the style, edit the group's own rows, and the graph does not store -them. +not store a series' paint. + +`appearance.addFill`, `appearance.addStroke`, `appearance.setItem`, `appearance.removeItem`, +`appearance.duplicateItem`, `appearance.moveItem`, `appearance.clear`, `appearance.reduceToBasic`, +`appearance.showAllHidden`, `appearance.transfer` (as its `target`), `graphicStyle.apply`, and `transparency.set` with a +fill or stroke `item`, given a series group's id or the selected series group, edit the paths directly in the group as +if each had been given, and the group keeps no rows of its own. A series group with no path directly in it, for example +one drawn with a column design, and a series group that has a fill or stroke row of its own, as a document saved by an +earlier version can hold, are edited themselves by these commands, and `appearance.moveItem` with `from: "contents"` +moves the group's own Contents row. `appearance.clear`, `appearance.reduceToBasic`, `appearance.showAllHidden` and +`graphicStyle.breakLink` edit the group as well as its paths. `graphicStyle.apply` without `add` and +`appearance.transfer` onto the group clear the group's own effects, opacity, blend mode, isolation, knockout and style +link, and `graphicStyle.apply` with `add` unlinks the group. With `appearance.transfer`, a `source` that is one of the +target group's paths keeps its look on a move, and a `source` that is the group's only path is an error. +`graphicStyle.redefine` gives the style to the paths directly in a series group linked to it, whether or not the group +has rows of its own, links them, and clears and unlinks the group; the source and the paths linked to the style whose +look was edited keep their look. Read as a source, by `graphicStyle.new`, `graphicStyle.redefine` or +`appearance.transfer`, a series group that has no fill, stroke, effect, opacity, blend mode, isolation, knockout or +style link of its own gives the look and the style link of the topmost path directly in it, and a move with +`appearance.transfer` clears each of those paths; a series group that has one of them is read itself. + +The other commands given a series group's id edit the group itself, and the graph does not store what they set on it: +`transparency.set` and `object.setProps` with an opacity or blend mode for the object, the `effect.*` commands and +`appearance.addEffect`, and the paint, stroke and gradient commands with a fill or stroke `item`, which is a row of the +group's own stack. The Appearance panel and `appearance.setActiveItem` read the selected group's own rows. `text.setFormat` without `start` and `end`, on a graph or on its labels, stores the character and paragraph attributes it sets for each kind of label it reaches (value axis numbers, category labels, legend labels), and every label of that diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 086d4cfc0d..ececa3e2f1 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1056,7 +1056,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Blend spine Anchor Point tool (#2544):** on a selected blend, dragging a spine corner makes symmetric Smooth handles; the tool displays and picks existing spine handles when switched to, drags one independently or retracts it on click, and clicking a point with handles retracts both. The spine is edited live without moving its key objects. Windows native canvas checks and screenshots reviewed: symmetric and independent handles, corner/retraction, Shift constraints and perpendicular reshaping, tool switching, key preservation, Undo/Redo, save/reopen, hidden handles and overlapping Path/Blend priority (PR #2643). Behaviour reference: [public path-editing documentation](https://helpx.adobe.com/illustrator/using/adjust-path-segments.html). - **Blend steps of brushed strokes:** the steps interpolate the pen pressure, tilt, bearing and rotation recorded with the Paintbrush, so a Calligraphic, Scatter or Art brush that varies with the pen changes gradually from one key to the next. A key without a recording counts as half pressure, half tilt and 0°, as brushes read it, and angles turn the shorter way round. When the blend starts a key's path at another anchor (an open path run from its end, a closed one turned to another start), the key's recordings, width profile and arrowheads turn with the path. Different brushes still switch halfway (VectorCraft's own rule; strokes blend their options, as [Blended objects overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/apply-transparency-and-blending/blended-objects-overview.html) describes; `crates/doc/src/blend.rs`, `pen_pressure_tilt_and_angles_interpolate_for_brushes`, `stroke_profiles_turn_with_a_key_path_started_elsewhere`). - **Path editing (#494):** the handles shown are the handles that drag: Direct Selection drags those of a path selected as a whole (as the Pen leaves it), the Anchor Point tool and Pen+Alt no longer grab handles that Show handles when multiple anchors are selected hides, a handle shorter than the tolerance leaves its anchor to be picked, and the anchor tools pick within Selection & Anchor Display › Tolerance. A dragged segment keeps a smooth anchor at either end smooth. With Direct Selection, the Pen, the Curvature and the anchor tools, a path selected as a whole shows all its anchors selected, and the Control bar and the Properties panel offer Convert (corner, smooth) for them too; Remove and Cut wait for anchors direct-selected (#504). A handle drag gathers its snap targets once per drag (it took 21 ms per pointer move on a 20,000-path document, now 1 ms; `vectorcraft-cli perf` measures handle and segment drags on a 5,000-anchor path). Join merges the selected anchor points that lie on one another, as after Average, into one anchor (#1582, fixes #1533); Object › Path › Average & Join… (`path.averageJoin`, Cmd+Alt+Shift+J, the "Create corner or smooth join" shortcut of [Default keyboard shortcuts](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)) moves two open path ends to their midpoint and joins them there, a corner or smooth point as its dialog's Points choice asks, in one undo step. - - **Graphs:** Column, Stacked Column, Bar, Stacked Bar, Line, Area, Scatter, Pie and Radar graph tools with Graph Data and Graph Type. A series starts in greyscale; Group Selection's fill and stroke, the paint, weight, opacity and blend mode of a mark's top visible fill or stroke row after an Appearance command, the Eyedropper, a graphic style, Default Fill and Stroke or Swap Fill and Stroke, and a mark's object opacity and blend mode, are kept separately on the graph and reapplied when its data, type or size changes, and through save, open and undo. Graph Type's Override Calculated Values (both `axisMin` and `axisMax`) uses exactly that value-axis range, split into the tick count (5 when automatic). Line graphs take Edge-to-Edge Lines (off by default: the points sit at the centres of their categories; graphs saved before the option keep their edge-to-edge lines), and radar graphs follow Mark Data Points and Connect Data Points. Blank cells (an empty CSV cell or `null`) are values left out, not zeros: columns, bars and stacked segments skip them, lines and scatter lines break around them and the value axis ignores them, while area, pie and radar draw them as 0; a number in straight quotes is a label, and the data window writes it back quoted. Graph types combine: Graph Type on series picked with Group Selection (or `series` indexes) draws them as their own type, with column, stacked column, line and area mixing on the vertical value axis and bar and stacked bar on the horizontal one; stacked columns take one slot of the cluster, lines draw in front of columns and areas behind. The value axis goes on the left, the right or both sides (column, stacked column, line, area and scatter graphs; bar graphs keep theirs along the bottom), and Separate Scales gives the series assigned to the right axis a scale of their own with its own tick values. Each value axis takes tick marks of no, short or full (across the plot) length and a count per division, and a prefix and suffix for its numbers; the category axis takes tick marks too (none by default), at or between its labels. Graph designs: Object › Graph › Design lists the designs with a preview of the selected one, and New Design (the selected art), Rename, Delete Design, Paste Design (a copy back to edit) and Select Unused, and Marker draws the data points and legend swatches of line, scatter and radar series with a design, scaled so its backmost object fills the default marker's square. Graph Data transposes rows and columns and switches a scatter graph's x and y, and a `|` in a category or series label starts a new line. Pie graphs take Legends in Wedges, Position (Even, Ratio sized by area, Stacked on one centre) and Sort (None, All, First). Graph Type takes column and cluster widths up to 1000% (overlapping past 100%) with First Row and First Column in Front (First Row orders each series' categories; across series the series order decides, so series stay one group each for Group Selection), draws filled lines, adds drop shadows behind columns, bars, lines and wedges, and puts the legend in rows across the top. Text formatted with the Character, Paragraph or Appearance controls, on the whole graph or on labels picked with Group Selection, is kept per kind of label (value axis numbers, category labels, legend labels) through the graph being drawn again. Object › Graph › Data opens a worksheet: cells picked with a click and edited above the sheet (Tab moves right, Enter down, the arrows between cells), Import Data from a tab-separated text file, Transpose, Switch x/y, Cell Style (decimals shown, column width), Revert and Apply. `graph.setData` returns and takes the data as CSV with each value written exactly, not rounded to two decimals, so applying the returned CSV changes nothing (#1485). + - **Graphs:** Column, Stacked Column, Bar, Stacked Bar, Line, Area, Scatter, Pie and Radar graph tools with Graph Data and Graph Type. A series starts in greyscale; Group Selection's fill and stroke, the paint, weight, opacity and blend mode of a mark's top visible fill or stroke row after an Appearance command or a graphic style (each given a mark or its series picked with Group Selection), the Eyedropper, Default Fill and Stroke or Swap Fill and Stroke, and a mark's object opacity and blend mode, are kept separately on the graph and reapplied when its data, type or size changes, and through save, open and undo. Graph Type's Override Calculated Values (both `axisMin` and `axisMax`) uses exactly that value-axis range, split into the tick count (5 when automatic). Line graphs take Edge-to-Edge Lines (off by default: the points sit at the centres of their categories; graphs saved before the option keep their edge-to-edge lines), and radar graphs follow Mark Data Points and Connect Data Points. Blank cells (an empty CSV cell or `null`) are values left out, not zeros: columns, bars and stacked segments skip them, lines and scatter lines break around them and the value axis ignores them, while area, pie and radar draw them as 0; a number in straight quotes is a label, and the data window writes it back quoted. Graph types combine: Graph Type on series picked with Group Selection (or `series` indexes) draws them as their own type, with column, stacked column, line and area mixing on the vertical value axis and bar and stacked bar on the horizontal one; stacked columns take one slot of the cluster, lines draw in front of columns and areas behind. The value axis goes on the left, the right or both sides (column, stacked column, line, area and scatter graphs; bar graphs keep theirs along the bottom), and Separate Scales gives the series assigned to the right axis a scale of their own with its own tick values. Each value axis takes tick marks of no, short or full (across the plot) length and a count per division, and a prefix and suffix for its numbers; the category axis takes tick marks too (none by default), at or between its labels. Graph designs: Object › Graph › Design lists the designs with a preview of the selected one, and New Design (the selected art), Rename, Delete Design, Paste Design (a copy back to edit) and Select Unused, and Marker draws the data points and legend swatches of line, scatter and radar series with a design, scaled so its backmost object fills the default marker's square. Graph Data transposes rows and columns and switches a scatter graph's x and y, and a `|` in a category or series label starts a new line. Pie graphs take Legends in Wedges, Position (Even, Ratio sized by area, Stacked on one centre) and Sort (None, All, First). Graph Type takes column and cluster widths up to 1000% (overlapping past 100%) with First Row and First Column in Front (First Row orders each series' categories; across series the series order decides, so series stay one group each for Group Selection), draws filled lines, adds drop shadows behind columns, bars, lines and wedges, and puts the legend in rows across the top. Text formatted with the Character, Paragraph or Appearance controls, on the whole graph or on labels picked with Group Selection, is kept per kind of label (value axis numbers, category labels, legend labels) through the graph being drawn again. Object › Graph › Data opens a worksheet: cells picked with a click and edited above the sheet (Tab moves right, Enter down, the arrows between cells), Import Data from a tab-separated text file, Transpose, Switch x/y, Cell Style (decimals shown, column width), Revert and Apply. `graph.setData` returns and takes the data as CSV with each value written exactly, not rounded to two decimals, so applying the returned CSV changes nothing (#1485). - **Graph column designs:** Object › Graph › Column (`graph.column`) draws the columns, bars or stacked segments and the legend swatch of the series picked with Group Selection with a graph design: Vertically Scaled stretches it to each column's length, Uniformly Scaled scales it both ways and centers it, Repeating stacks a copy for each Each Design Represents value and chops or scales the last one (For Fractions), and Sliding keeps the part above the design's guide line in proportion and stretches the part below. The dialog lists the designs with a preview; the choice is saved with the graph and follows the design's rename and delete. Type in a column design that holds a `%` followed by two digits shows each column's value in place of the `%` and the digits: the first digit is the least number of places before the decimal point (zeros are added in front; 0 gives as many as the value needs), and the second digit sets the places after it, rounded. Unless it is inside a group that clips or has its own opacity or appearance, or inside a blend, compound shape, envelope, repeat or intertwined objects, the type keeps its size and is drawn once per column in a repeating design. The legend swatch leaves it out. - **Other:** Eyedropper, Gradient annotator, Artboard (Alt-drag duplicates an artboard, and its art with Move/Copy Artwork with Artboard on; Copy, Cut and Paste take the artboard with its art, Paste right of the last artboard, Paste in Place where it was, into this or another document, #446; Object › Artboards › Rearrange All Artboards lays them out in a grid by row or by column, in one row or one column, left to right or right to left, from the menu, the Artboards panel or Properties' Rearrange All, #681; Scale Artwork with Artboard, in the Control bar and Properties beside Move Artwork with Artboard, resizes the artboard proportionally with the art fully inside it and its guides, strokes and corners per the Scale preferences, #602), Measure, Type, Hand, Zoom, Rotate View. From 4cd998dce076677dbc2fa3313fbeade789aa60fd Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 07:28:01 -0800 Subject: [PATCH 14/25] Place: a file read apart from the session goes only into its document Session::place_read and Session::place_queue_read placed a file, or loaded the place cursor, in whichever document was active when the read finished. A job prepared in one document could land in another one that was activated meanwhile, or that stayed open after the first was closed. Replace did not stop it when the other document held an equal object under the same id. PlaceJob, QueueJob and QueueRead now keep the uid of the document they were prepared in. Both calls refuse a read whose document is not the active one with "the document it was prepared for is no longer active", before any selection, edit, tool change or journal entry. Switching back to the original document places the file as before. --- crates/engine/src/cmd/place.rs | 48 +++++++++++----- crates/engine/src/tests/place.rs | 89 +++++++++++++++++++++++++++++ crates/ui-egui/src/i18n/bg.tsv | 1 + crates/ui-egui/src/i18n/bs.tsv | 1 + crates/ui-egui/src/i18n/ca.tsv | 1 + crates/ui-egui/src/i18n/cs.tsv | 1 + crates/ui-egui/src/i18n/da.tsv | 1 + crates/ui-egui/src/i18n/de.tsv | 1 + crates/ui-egui/src/i18n/el.tsv | 1 + crates/ui-egui/src/i18n/es.tsv | 1 + crates/ui-egui/src/i18n/fi.tsv | 1 + crates/ui-egui/src/i18n/fr.tsv | 1 + crates/ui-egui/src/i18n/hi.tsv | 1 + crates/ui-egui/src/i18n/hu.tsv | 1 + crates/ui-egui/src/i18n/id.tsv | 1 + crates/ui-egui/src/i18n/it.tsv | 1 + crates/ui-egui/src/i18n/ja.tsv | 1 + crates/ui-egui/src/i18n/ka.tsv | 1 + crates/ui-egui/src/i18n/ko.tsv | 1 + crates/ui-egui/src/i18n/nl.tsv | 1 + crates/ui-egui/src/i18n/pl.tsv | 1 + crates/ui-egui/src/i18n/pt-br.tsv | 1 + crates/ui-egui/src/i18n/ru.tsv | 1 + crates/ui-egui/src/i18n/sv.tsv | 1 + crates/ui-egui/src/i18n/tr.tsv | 1 + crates/ui-egui/src/i18n/uk.tsv | 1 + crates/ui-egui/src/i18n/vi.tsv | 1 + crates/ui-egui/src/i18n/zh-hans.tsv | 1 + crates/ui-egui/src/i18n/zh-hant.tsv | 1 + docs/target-app-parity.md | 1 + 30 files changed, 150 insertions(+), 15 deletions(-) diff --git a/crates/engine/src/cmd/place.rs b/crates/engine/src/cmd/place.rs index 36444878ef..8215e8f0e3 100644 --- a/crates/engine/src/cmd/place.rs +++ b/crates/engine/src/cmd/place.rs @@ -58,6 +58,9 @@ use crate::{EngineError, MAX_COORD}; const PLACE: &str = "file.place"; const QUEUE: &str = "file.place.queue"; +/// The error of a file read apart from the session while another document is active, or after the +/// document it was read for closed ([`Session::place_read`], [`Session::place_queue_read`]). +const NOT_ACTIVE: &str = "the document it was prepared for is no longer active"; /// The most files one `file.place.queue` loads. const MAX_QUEUE: usize = 100; /// The longest thumbnail side `thumbnail` may ask for (px). @@ -503,11 +506,13 @@ fn fit(natural: Rect, r: Rect) -> Affine { Affine::translate(r.center().to_vec2()) * Affine::scale(k) * Affine::translate(-natural.center().to_vec2()) } -/// What `file.place` takes from the session before it reads the file: the params, the object -/// Replace swaps and the artboard under `at`, which a DXF drawing is laid out on -/// ([`Session::prepare_place`]). [`PlaceJob::read`] reads and decodes the file without the session, -/// on any thread. +/// What `file.place` takes from the session before it reads the file: the document it places into, +/// the params, the object Replace swaps and the artboard under `at`, which a DXF drawing is laid +/// out on ([`Session::prepare_place`]). [`PlaceJob::read`] reads and decodes the file without the +/// session, on any thread. pub struct PlaceJob { + /// The document it was prepared in (`DocState::uid`). + doc: u64, params: Value, old: Option, /// The object Replace swaps as it was when Place started. @@ -560,10 +565,14 @@ impl Session { /// Run `file.place` with the params of `read` as a command (checked and journaled as any /// other) that places the file `read` holds instead of reading it again → `file.place`'s - /// reply. The object Replace swaps must still be in the document as it was when Place started; - /// when the selection changed meanwhile, `select.set` selects that object again first, so a - /// replay of the journal replaces the same object. + /// reply. The document Place started in must be the active one, and the object Replace swaps + /// must still be in it as it was when Place started; when the selection changed meanwhile, + /// `select.set` selects that object again first, so a replay of the journal replaces the same + /// object. pub fn place_read(&mut self, read: PlaceRead) -> Result { + if self.doc()?.uid != read.job.doc { + return Err(bad(PLACE, NOT_ACTIVE)); + } let params = read.job.params.clone(); if let Some(old) = read.job.old { let st = self.doc()?; @@ -615,7 +624,7 @@ fn prepare(s: &Session, p: &Value) -> Result { (true, _) => return Err(bad(PLACE, "replace: select the one object to replace")), }; let replaced = old.and_then(|id| st.doc.node(id)).cloned(); - Ok(PlaceJob { params: p.clone(), old, replaced, target: board_at(&st.doc, at) }) + Ok(PlaceJob { doc: st.uid, params: p.clone(), old, replaced, target: board_at(&st.doc, at) }) } /// Place the file `read` holds in the active document. @@ -755,6 +764,8 @@ fn queued_files(p: &Value) -> Result> { /// ([`Session::prepare_place_queue`]). [`QueueJob::read`] reads them without the session, on any /// thread. pub struct QueueJob { + /// The document it was prepared in (`DocState::uid`). + doc: u64, params: Value, files: Vec, } @@ -762,6 +773,8 @@ pub struct QueueJob { /// The files [`QueueJob::read`] read, which [`Session::place_queue_read`] loads the place cursor /// with. pub struct QueueRead { + /// The document the files were read for (`DocState::uid`). + doc: u64, params: Value, entries: Vec, files: Vec, @@ -776,13 +789,13 @@ impl QueueJob { /// Read every file for its size and thumbnail, as `file.place.queue` does, without the session. pub fn read(self) -> Result { - read_queue(self.params, self.files) + read_queue(self.doc, self.params, self.files) } } -/// Read each of `queued`, the files of `file.place.queue` with params `p`, for its size and -/// thumbnail. -fn read_queue(p: Value, queued: Vec) -> Result { +/// Read each of `queued`, the files of `file.place.queue` with params `p` for the document `doc`, +/// for its size and thumbnail. +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 { @@ -823,7 +836,7 @@ fn read_queue(p: Value, queued: Vec) -> Result { } } } - Ok(QueueRead { params: p, entries, files, skipped }) + Ok(QueueRead { doc, params: p, entries, files, skipped }) } impl Session { @@ -834,12 +847,17 @@ impl Session { has_doc(self).map_err(|why| EngineError::Disabled(QUEUE.into(), why))?; check_switches(params, &["link", "template"], QUEUE)?; check_numbers(params, &["thumbnail"], QUEUE)?; - Ok(QueueJob { params: params.clone(), files: queued_files(params)? }) + let files = queued_files(params)?; + Ok(QueueJob { doc: self.doc()?.uid, params: params.clone(), files }) } /// Run `file.place.queue` with the params of `read` as a command that loads the place cursor - /// with the files `read` holds instead of reading them again → `file.place.queue`'s reply. + /// with the files `read` holds instead of reading them again → `file.place.queue`'s reply. The + /// document the files were read for must be the active one. pub fn place_queue_read(&mut self, read: QueueRead) -> Result { + if self.doc()?.uid != read.doc { + return Err(bad(QUEUE, NOT_ACTIVE)); + } let params = read.params.clone(); self.queue_hand_off = Some(read); let r = self.execute(QUEUE, ¶ms); diff --git a/crates/engine/src/tests/place.rs b/crates/engine/src/tests/place.rs index a0a8ededa0..911894c9df 100644 --- a/crates/engine/src/tests/place.rs +++ b/crates/engine/src/tests/place.rs @@ -365,6 +365,95 @@ fn a_file_read_apart_from_the_session_replaces_what_was_selected_when_place_star } } +/// Every open document with its art, selection and undo steps, and the journal, tool and tool +/// options: what a refused hand-off leaves as it was. +type Snapshot = (Vec<(u64, Arc, Vec, usize)>, usize, &'static str, Value); + +fn snapshot(s: &Session) -> Snapshot { + let docs = s.documents().iter().map(|d| (d.uid, d.doc.clone(), d.selection.objects.clone(), d.history.undo.len())).collect(); + (docs, s.journal.len(), s.tool_id(), s.tool_options()) +} + +/// A file read apart from the session is placed only in the document Place started in: with +/// another document active, Replace included when that document holds the same object under the +/// same id, or after the document closed, nothing changes in any document; with the document +/// active again, the file is placed in it. +#[test] +fn a_file_read_apart_from_the_session_is_placed_only_in_the_document_it_was_read_for() { + let blue = file("blue.png", &png(8, 8, [0, 0, 255, 255], None)); + let not_active = "the document it was prepared for is no longer active"; + for replace in [false, true] { + let p = with(blue.clone(), json!({"replace": replace})); + let mut s = session(); + let square = json!({"x": 10, "y": 10, "width": 20, "height": 20}); + let a = s.execute("shape.rectangle", &square).unwrap()["id"].clone(); + let read = s.prepare_place(&p).unwrap().read().unwrap(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let b = s.execute("shape.rectangle", &square).unwrap()["id"].clone(); + assert_eq!(a, b, "the other document holds an object with the same id"); + assert!(node(&s, &b) == s.documents()[0].doc.node(NodeId(a.as_u64().unwrap())).unwrap().clone(), "and the same content"); + let before = snapshot(&s); + let err = s.place_read(read).unwrap_err(); + assert!(err.to_string().contains(not_active), "replace {replace}: {err}"); + assert!(snapshot(&s) == before, "replace {replace}: nothing placed, selected or journaled in either document"); + // Active again, the document Place started in takes the file. + let read = { + s.execute("document.activate", &json!({"index": 0})).unwrap(); + s.prepare_place(&p).unwrap().read().unwrap() + }; + s.execute("document.activate", &json!({"index": 1})).unwrap(); + s.execute("document.activate", &json!({"index": 0})).unwrap(); + let r = s.place_read(read).unwrap(); + assert_eq!(s.active_index(), Some(0)); + assert!(s.doc().unwrap().doc.node(NodeId(r["ids"][0].as_u64().unwrap())).is_some(), "replace {replace}: placed in the first document"); + let others = s.documents()[1].doc.layers.last().unwrap().children().unwrap().len(); + assert_eq!(others, 1, "replace {replace}: the other document keeps its one object"); + } + // The document Place started in closed: refused in the document left open, and with none left. + let mut s = session(); + let read = s.prepare_place(&blue).unwrap().read().unwrap(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + s.execute("file.close", &json!({"index": 0})).unwrap(); + let before = snapshot(&s); + assert!(s.place_read(read).unwrap_err().to_string().contains(not_active)); + assert!(snapshot(&s) == before, "nothing placed in the document left open"); + let read = s.prepare_place(&blue).unwrap().read().unwrap(); + s.execute("file.close", &json!({})).unwrap(); + let journal = s.journal.len(); + assert!(s.place_read(read).is_err() && s.journal.len() == journal, "no document left: refused"); +} + +/// Files read for the place cursor apart from the session load it only in the document they were +/// read for: with another document active, or after that document closed, its tool and queue stay +/// as they were; with the document active again, the cursor is loaded. +#[test] +fn files_read_for_the_place_cursor_apart_from_the_session_load_it_only_in_their_document() { + let p = json!({"files": [file("a.png", &png(40, 20, [9, 9, 9, 255], None))], "link": false}); + let not_active = "the document it was prepared for is no longer active"; + let mut s = session(); + let read = s.prepare_place_queue(&p).unwrap().read().unwrap(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let before = snapshot(&s); + assert!(s.place_queue_read(read).unwrap_err().to_string().contains(not_active)); + assert!(snapshot(&s) == before && s.tool_id() == "selection", "the other document's tool and queue stay"); + let read = { + s.execute("document.activate", &json!({"index": 0})).unwrap(); + s.prepare_place_queue(&p).unwrap().read().unwrap() + }; + s.execute("document.activate", &json!({"index": 1})).unwrap(); + s.execute("document.activate", &json!({"index": 0})).unwrap(); + assert_eq!(s.place_queue_read(read).unwrap()["count"], 1); + assert_eq!(s.tool_id(), "place"); + // The document they were read for closed. + let mut s = session(); + let read = s.prepare_place_queue(&p).unwrap().read().unwrap(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + s.execute("file.close", &json!({"index": 0})).unwrap(); + let before = snapshot(&s); + assert!(s.place_queue_read(read).unwrap_err().to_string().contains(not_active)); + assert!(snapshot(&s) == before, "the document left open keeps its tool"); +} + /// A linked image keeps the preview its file was read with ([`cmd::place::PlaceJob::read`] makes /// it), so placing the read file does not decode the image again; an embedded image has none. #[test] diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 1fb96d9c7d..ba71759b44 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -4493,6 +4493,7 @@ axis Both И двете @msg paths contain invalid coordinates пътищата съдържат невалидни координати @msg paths: give at least one file пътища: посочете поне един файл @msg replace: the object to replace was changed or deleted замяна: обектът за замяна е променен или изтрит +@msg the document it was prepared for is no longer active документът, за който е подготвено, вече не е активен @msg pattern missing липсва мостра @msg patterns nested too deeply are filled with mid-grey мострите, вложени прекалено дълбоко, се запълват със средно сиво @msg percent must be above 0 and at most 6400, not {p} percent трябва да е над 0 и най-много 6400, а не {p} diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index f04e9535e5..a38088e8a7 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -4889,6 +4889,7 @@ imageTrace Outline Obris @msg paths contain invalid coordinates putanje sadrže nevažeće koordinate @msg paths: give at least one file paths: navedite barem jednu datoteku @msg replace: the object to replace was changed or deleted replace: objekat za zamjenu je promijenjen ili izbrisan +@msg the document it was prepared for is no longer active dokument za koji je pripremljeno više nije aktivan @msg pattern missing uzorak nedostaje @msg patterns nested too deeply are filled with mid-grey previše duboko ugniježđeni uzorci ispunjavaju se srednje sivom @msg percent must be above 0 and at most 6400, not {p} percent mora biti iznad 0 i najviše 6400, a ne {p} diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index e6b6f398f2..3989acb76d 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -5945,6 +5945,7 @@ digits Malayalam Malaiàlam @msg Reload the page to go on (changes not saved yet may be lost). Recarrega la pàgina per continuar (els canvis encara no desats es poden perdre). @msg Replace Spine: select a blend and a path Substitueix l’espina: selecciona una fusió i un traçat @msg replace: the object to replace was changed or deleted replace: l’objecte que s’havia de substituir s’ha canviat o suprimit +@msg the document it was prepared for is no longer active el document per al qual es va preparar ja no està actiu @msg Reset {_1} Restableix {_1} @msg resolutions must be between 1 and 2400 ppi les resolucions han de ser entre 1 i 2400 ppi @msgplural Restored {n} recovered document: save it to keep it|Restored {n} recovered documents: save them to keep them S’ha restaurat {n} document recuperat: desa’l per conservar-lo|S’han restaurat {n} documents recuperats: desa’ls per conservar-los diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index a44e3b9979..87a879f3ea 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -5056,6 +5056,7 @@ imageTrace Outline Obrys @msg paths contain invalid coordinates cesty obsahují neplatné souřadnice @msg paths: give at least one file paths: zadejte alespoň jeden soubor @msg replace: the object to replace was changed or deleted replace: objekt k nahrazení byl změněn nebo odstraněn +@msg the document it was prepared for is no longer active dokument, pro který bylo připraveno, už není aktivní @msg pattern missing chybí vzorek @msg patterns nested too deeply are filled with mid-grey příliš hluboko vnořené vzorky se vyplní středně šedou @msg percent must be above 0 and at most 6400, not {p} percent musí být větší než 0 a nejvýše 6400, ne {p} diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index bce3bd12da..a348ad740e 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -4594,6 +4594,7 @@ imageTrace Outline Kontur @msg paths contain invalid coordinates stierne indeholder ugyldige koordinater @msg paths: give at least one file stier: angiv mindst én fil @msg replace: the object to replace was changed or deleted erstat: objektet, der skulle erstattes, er ændret eller slettet +@msg the document it was prepared for is no longer active dokumentet, det blev forberedt til, er ikke længere aktivt @msg pattern missing mønster mangler @msg patterns nested too deeply are filled with mid-grey mønstre, der er indlejret for dybt, udfyldes med mellemgrå @msg percent must be above 0 and at most 6400, not {p} percent skal være over 0 og højst 6400, ikke {p} diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 0d995ddc2e..fa8c59d604 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -4671,6 +4671,7 @@ theme Appearance Erscheinungsbild @msg paths contain invalid coordinates die Pfade enthalten ungültige Koordinaten @msg paths: give at least one file paths: Geben Sie mindestens eine Datei an @msg replace: the object to replace was changed or deleted replace: Das zu ersetzende Objekt wurde geändert oder gelöscht +@msg the document it was prepared for is no longer active das Dokument, für das es vorbereitet wurde, ist nicht mehr aktiv @msg pattern missing das Muster fehlt @msg patterns nested too deeply are filled with mid-grey zu tief verschachtelte Muster werden mit mittlerem Grau gefüllt @msg percent must be above 0 and at most 6400, not {p} percent muss über 0 und höchstens 6400 sein, nicht {p} diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index cb409e9274..158fd5e056 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -4701,6 +4701,7 @@ digits Malayalam Μαλαγιάλαμ @msg paths contain invalid coordinates οι διαδρομές περιέχουν μη έγκυρες συντεταγμένες @msg paths: give at least one file διαδρομές: δώστε τουλάχιστον ένα αρχείο @msg replace: the object to replace was changed or deleted αντικατάσταση: το αντικείμενο προς αντικατάσταση άλλαξε ή διαγράφηκε +@msg the document it was prepared for is no longer active το έγγραφο για το οποίο προετοιμάστηκε δεν είναι πλέον ενεργό @msg pattern missing λείπει το μοτίβο @msg patterns nested too deeply are filled with mid-grey τα πολύ βαθιά ένθετα μοτίβα γεμίζονται με μέτριο γκρι @msg percent must be above 0 and at most 6400, not {p} το percent πρέπει να είναι μεγαλύτερο από 0 και έως 6400, όχι {p} diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index de9512cddb..7f01e36334 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -4748,6 +4748,7 @@ axis Both Ambos @msg paths contain invalid coordinates los trazados contienen coordenadas no válidas @msg paths: give at least one file paths: indica al menos un archivo @msg replace: the object to replace was changed or deleted replace: se modificó o eliminó el objeto que se iba a reemplazar +@msg the document it was prepared for is no longer active el documento para el que se preparó ya no está activo @msg pattern missing falta el motivo @msg patterns nested too deeply are filled with mid-grey los motivos anidados a demasiada profundidad se rellenan de gris medio @msg percent must be above 0 and at most 6400, not {p} percent debe ser mayor que 0 y como máximo 6400, no {p} diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 1c3327fb1e..4ff166aead 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -4962,6 +4962,7 @@ imageTrace Outline Ääriviiva @msg paths contain invalid coordinates polut sisältävät virheellisiä koordinaatteja @msg paths: give at least one file paths: anna vähintään yksi tiedosto @msg replace: the object to replace was changed or deleted replace: korvattavaa objektia on muutettu tai se on poistettu +@msg the document it was prepared for is no longer active asiakirja, jota varten se valmisteltiin, ei ole enää aktiivinen @msg pattern missing kuvio puuttuu @msg patterns nested too deeply are filled with mid-grey liian syvälle sisäkkäiset kuviot täytetään keskiharmaalla @msg percent must be above 0 and at most 6400, not {p} percent-arvon on oltava yli 0 ja enintään 6400, ei {p} diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 3b45c4d386..e3d03e6948 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -4737,6 +4737,7 @@ axis Both Les deux @msg paths contain invalid coordinates les tracés contiennent des coordonnées non valides @msg paths: give at least one file paths : indiquez au moins un fichier @msg replace: the object to replace was changed or deleted replace : l’objet à remplacer a été modifié ou supprimé +@msg the document it was prepared for is no longer active le document pour lequel il a été préparé n’est plus actif @msg pattern missing motif manquant @msg patterns nested too deeply are filled with mid-grey les motifs imbriqués trop profondément sont remplis de gris moyen @msg percent must be above 0 and at most 6400, not {p} percent doit être supérieur à 0 et au plus égal à 6400, pas {p} diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 0c6089e40a..ab66f69414 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -7648,6 +7648,7 @@ antiAlias Sharp शार्प @msg Replace Spine: select a blend and a path Spine: एक मिश्रण और एक पाथ चुनें @msg replace: select the one object to replace प्रतिस्थापित करने के लिए एक ऑब्जेक्ट सिलेक्ट करें @msg replace: the object to replace was changed or deleted प्रतिस्थापित करने के लिए ऑब्जेक्ट को बदल दिया गया था या हटा दिया गया +@msg the document it was prepared for is no longer active जिस डॉक्यूमेंट के लिए इसे तैयार किया गया था, वह अब सक्रिय नहीं है @msg Reset {_1} रीसेट करें {_1} @msg resolution must be a number or screen|medium|high resolution: रिज़ॉल्यूशन एक नंबर या स्क्रीन होना चाहिए @msg resolution must be between 1 and 2400 ppi resolution: संकल्प 1 और 2400 ppi के बीच होना चाहिए diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 06122f94ee..85339ad015 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -5457,6 +5457,7 @@ imageTrace Outline Körvonal @msg paths contain invalid coordinates az útvonalakban érvénytelen koordináták vannak @msg paths: give at least one file paths: legalább egy fájlt adj meg @msg replace: the object to replace was changed or deleted replace: a cserélendő objektumot módosították vagy törölték +@msg the document it was prepared for is no longer active az a dokumentum, amelyhez előkészítették, már nem aktív @msg pattern missing hiányzik a mintázat @msg patterns nested too deeply are filled with mid-grey a túl mélyen egymásba ágyazott mintázatok helyén középszürke kitöltés áll @msg PDF settings are not an object a PDF-beállítások nem objektumot alkotnak diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 00d2b09600..be75eee783 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -4594,6 +4594,7 @@ imageTrace Outline Kontur @msg paths contain invalid coordinates jalur berisi koordinat yang tidak valid @msg paths: give at least one file jalur: berikan setidaknya satu berkas @msg replace: the object to replace was changed or deleted ganti: objek yang akan diganti telah diubah atau dihapus +@msg the document it was prepared for is no longer active dokumen yang menjadi tujuan persiapannya tidak lagi aktif @msg pattern missing pola hilang @msg patterns nested too deeply are filled with mid-grey pola yang bersarang terlalu dalam diisi dengan abu-abu tengah @msg percent must be above 0 and at most 6400, not {p} percent harus di atas 0 dan paling banyak 6400, bukan {p} diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 869fe2e4a0..6f177e57a8 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -4799,6 +4799,7 @@ axis Both Entrambi @msg paths contain invalid coordinates i tracciati contengono coordinate non valide @msg paths: give at least one file paths: specifica almeno un file @msg replace: the object to replace was changed or deleted replace: l’oggetto da sostituire è stato modificato o eliminato +@msg the document it was prepared for is no longer active il documento per cui è stato preparato non è più attivo @msg pattern missing motivo mancante @msg patterns nested too deeply are filled with mid-grey i motivi annidati troppo in profondità vengono riempiti di grigio medio @msg percent must be above 0 and at most 6400, not {p} percent deve essere maggiore di 0 e al massimo 6400, non {p} diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index a0ce9c93b9..c1d912809c 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5162,6 +5162,7 @@ swatch Bright Violet ビビッドバイオレット @msg `{file}` isn't a VectorCraft document, a PDF or a PDF-compatible .ai file `{file}` は VectorCraft ドキュメント、PDF、PDF 互換の .ai ファイルのいずれでもありません @msg paths: give at least one file paths: ファイルを 1 つ以上指定してください @msg replace: the object to replace was changed or deleted replace: 置き換えるオブジェクトは変更または削除されています +@msg the document it was prepared for is no longer active 準備したときのドキュメントがもうアクティブではありません @msg Couldn't place {name}: {e} {name} を配置できませんでした: {e} @msg no print service プリントサービスがありません @msg the print job has no data プリントジョブにデータがありません diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index b19ed4009a..72116951a6 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -4423,6 +4423,7 @@ font-technology Variable ცვლადი @msg paths contain invalid coordinates ტრაექტორიებში არასწორი კოორდინატებია @msg paths: give at least one file paths: მიუთითეთ ერთი ფაილი მაინც @msg replace: the object to replace was changed or deleted replace: ჩასანაცვლებელი ობიექტი შეიცვალა ან წაიშალა +@msg the document it was prepared for is no longer active დოკუმენტი, რომლისთვისაც მომზადდა, აღარ არის აქტიური @msg pattern missing პატერნი აკლია @msg patterns nested too deeply are filled with mid-grey ზედმეტად ღრმად ჩადგმული პატერნები საშუალო ნაცრისფრით ივსება @msg percent must be above 0 and at most 6400, not {p} percent უნდა იყოს 0-ზე მეტი და არაუმეტეს 6400-ისა და არა {p} diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 3f518f00c4..99a13c1fee 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5089,6 +5089,7 @@ theme Appearance 외관 @msg `{file}` isn't a VectorCraft document, a PDF or a PDF-compatible .ai file `{file}`은(는) VectorCraft 문서, PDF 또는 PDF 호환 .ai 파일이 아닙니다 @msg paths: give at least one file paths: 파일을 하나 이상 지정하세요 @msg replace: the object to replace was changed or deleted replace: 바꿀 개체가 변경되었거나 삭제되었습니다 +@msg the document it was prepared for is no longer active 준비한 문서가 더 이상 활성 상태가 아닙니다 @msg Couldn't place {name}: {e} {name}을(를) 가져올 수 없습니다: {e} @msg no print service 인쇄 서비스가 없습니다 @msg the print job has no data 인쇄 작업에 데이터가 없습니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 40facfda42..1fff37393a 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -5108,6 +5108,7 @@ imageTrace Outline Contour @msg paths contain invalid coordinates paden bevatten ongeldige coördinaten @msg paths: give at least one file paden: geef minstens één bestand @msg replace: the object to replace was changed or deleted vervangen: het te vervangen object is gewijzigd of verwijderd +@msg the document it was prepared for is no longer active het document waarvoor het is voorbereid, is niet langer actief @msg pattern missing patroon ontbreekt @msg patterns nested too deeply are filled with mid-grey patronen die te diep genest zijn, worden gevuld met middelgrijs @msg percent must be above 0 and at most 6400, not {p} percent moet boven 0 en maximaal 6400 zijn, niet {p} diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 770622cc1e..1f02021252 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -4881,6 +4881,7 @@ imageTrace Outline Kontur @msg paths contain invalid coordinates ścieżki zawierają nieprawidłowe współrzędne @msg paths: give at least one file paths: podaj co najmniej jeden plik @msg replace: the object to replace was changed or deleted replace: obiekt do zastąpienia został zmieniony lub usunięty +@msg the document it was prepared for is no longer active dokument, dla którego to przygotowano, nie jest już aktywny @msg pattern missing brak wzorka @msg patterns nested too deeply are filled with mid-grey zbyt głęboko zagnieżdżone wzorki są wypełniane średnią szarością @msg percent must be above 0 and at most 6400, not {p} percent musi być większy od 0 i nie większy niż 6400, nie {p} diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 77fce38c53..df02ab2e4c 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -4204,6 +4204,7 @@ axis Both Ambos @msg paths contain invalid coordinates os traçados contêm coordenadas inválidas @msg paths: give at least one file paths: informe pelo menos um arquivo @msg replace: the object to replace was changed or deleted replace: o objeto a ser substituído foi alterado ou excluído +@msg the document it was prepared for is no longer active o documento para o qual foi preparado não está mais ativo @msg pattern missing padrão ausente @msg patterns nested too deeply are filled with mid-grey padrões aninhados com profundidade excessiva são preenchidos com cinza médio @msg percent must be above 0 and at most 6400, not {p} percent deve ser maior que 0 e no máximo 6400, não {p} diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index b546e87258..06170b5596 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -4785,6 +4785,7 @@ axis Both Оба @msg paths contain invalid coordinates контуры содержат недопустимые координаты @msg paths: give at least one file paths: укажите как минимум один файл @msg replace: the object to replace was changed or deleted replace: заменяемый объект был изменён или удалён +@msg the document it was prepared for is no longer active документ, для которого это было подготовлено, больше не активен @msg pattern missing узор отсутствует @msg patterns nested too deeply are filled with mid-grey слишком глубоко вложенные узоры заполняются серым @msg percent must be above 0 and at most 6400, not {p} percent должен быть больше 0 и не более 6400, а не {p} diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 9271ac4bac..02de7a123c 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -4649,6 +4649,7 @@ axis Both Båda @msg paths contain invalid coordinates banorna innehåller ogiltiga koordinater @msg paths: give at least one file paths: ange minst en fil @msg replace: the object to replace was changed or deleted replace: objektet som skulle ersättas har ändrats eller tagits bort +@msg the document it was prepared for is no longer active dokumentet som det förbereddes för är inte längre aktivt @msg pattern missing mönster saknas @msg patterns nested too deeply are filled with mid-grey mönster som är kapslade för djupt fylls med mellangrått @msg percent must be above 0 and at most 6400, not {p} percent måste vara över 0 och högst 6400, inte {p} diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 107f30f3ea..31f332dd11 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -4502,6 +4502,7 @@ axis Both Her İkisi @msg paths contain invalid coordinates yollar geçersiz koordinatlar içeriyor @msg paths: give at least one file yollar: en az bir dosya verin @msg replace: the object to replace was changed or deleted değiştir: değiştirilecek nesne değiştirildi veya silindi +@msg the document it was prepared for is no longer active hazırlandığı belge artık etkin değil @msg pattern missing desen eksik @msg patterns nested too deeply are filled with mid-grey çok derin iç içe geçmiş desenler orta gri renkle dolu @msg percent must be above 0 and at most 6400, not {p} percent 0'ın üzerinde ve en fazla 6400 olmalıdır, {p} değil diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 68aabf0253..36371da989 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -4783,6 +4783,7 @@ axis Both Обидві @msg paths contain invalid coordinates контури містять неприпустимі координати @msg paths: give at least one file paths: вкажіть щонайменше один файл @msg replace: the object to replace was changed or deleted replace: об’єкт для заміни було змінено або видалено +@msg the document it was prepared for is no longer active документ, для якого це було підготовлено, більше не активний @msg pattern missing візерунок відсутній @msg patterns nested too deeply are filled with mid-grey надто глибоко вкладені візерунки заповнюються сірим @msg percent must be above 0 and at most 6400, not {p} percent має бути більше 0 і не більше 6400, а не {p} diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 36793e6c56..a2f5126327 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5120,6 +5120,7 @@ theme Appearance Giao diện @msg paths contain invalid coordinates đường dẫn chứa tọa độ không hợp lệ @msg paths: give at least one file đường dẫn: hãy cung cấp ít nhất một tệp @msg replace: the object to replace was changed or deleted thay thế: đối tượng cần thay thế đã bị thay đổi hoặc xóa +@msg the document it was prepared for is no longer active tài liệu được chuẩn bị không còn hoạt động @msg pattern missing thiếu họa tiết @msg patterns nested too deeply are filled with mid-grey họa tiết lồng nhau quá sâu được tô bằng màu xám trung tính @msg PDF settings are not an object Cài đặt PDF không phải là đối tượng diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 27cad80b4a..f38c4c1cd2 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -4850,6 +4850,7 @@ imageTrace Outline 轮廓 @msg `{file}` isn't a VectorCraft document, a PDF or a PDF-compatible .ai file `{file}` 不是 VectorCraft 文档、PDF 或 PDF 兼容的 .ai 文件 @msg paths: give at least one file paths:请至少给出一个文件 @msg replace: the object to replace was changed or deleted replace:要替换的对象已被更改或删除 +@msg the document it was prepared for is no longer active 为其准备的文档已不再处于活动状态 @msg Couldn't place {name}: {e} 无法置入 {name}:{e} @msg no print service 没有打印服务 @msg the print job has no data 打印作业没有数据 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index ab1fd359cd..f0d756cc05 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2615,6 +2615,7 @@ file-filter Templates 範本 @msg `{file}` isn't a VectorCraft document, a PDF or a PDF-compatible .ai file `{file}` 不是 VectorCraft 文件、PDF 或 PDF 相容的 .ai 檔案 @msg paths: give at least one file paths:請提供至少一個檔案 @msg replace: the object to replace was changed or deleted replace:要取代的物件已被變更或刪除 +@msg the document it was prepared for is no longer active 為其準備的文件已不再處於使用中 @msg Couldn't place {name}: {e} 無法置入 {name}:{e} @msg no print service 沒有列印服務 @msg the print job has no data 列印工作沒有資料 diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index d9783b0216..32228c4321 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1639,6 +1639,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - File › Place reads Word 97-2003 `.doc` documents as area type with the same formatting, read from the main text's pieces, the style sheet's paragraph and character styles and direct formatting. Table rows are paragraphs with their cells separated by tabs and fields place as their results; fields without a result, hidden and deleted text, pictures, headers, footers, notes, comments and text boxes are left out, and `warnings` names each kind left out or changed. Encrypted documents, documents last saved with fast save and Word 6.0 and Word 95 documents are refused (`file.place`, `crates/engine/src/tests/textimport.rs`). - Placing a Word 97-2003 `.doc` document works out each style's formatting once and each property run's once, and refuses property pages that are out of order, listed twice or overlap, a style sheet that holds fewer styles than it counts, styles based on each other in a loop, and more than 100,000 runs of character or of paragraph properties, 16 MiB of properties or 100,000 paragraphs, hidden ones included (`file.place`, `crates/engine/src/tests/textimport.rs`). - On the desktop, File › Place reads and decodes files off the UI thread, one at a time, and places each once it is read, with "Placing" in the status bar and the busy spinner until then: the Place dialog's OK, a file dropped on the canvas, a click or drag of the place cursor, and the OK of the PDF, DXF and text import options. The files and thumbnails the place cursor is loaded with are read the same way, and the Place dialog's lines about its files are read on a thread of their own. Files are placed in the order they were started; a file is not placed while a dialog is open or a drag is under way, and a file whose document was closed meanwhile is not placed. `file.place` and `file.place.queue` over MCP and scripts reply as before. + - A file read for `file.place`, or files read for the place cursor, apart from the session (`Session::place_read`, `Session::place_queue_read`) go only into the document they were read for: while another document is active, or once that document is closed, they are refused with "the document it was prepared for is no longer active" and no document, selection, tool or undo step changes (`crates/engine/src/tests/place.rs`). - On the desktop, Paste from a menu or shortcut captures another app's bitmap or reads a copied image file on the UI thread, then decodes the image on the file-reading worker. The status bar shows "Pasting" until the image is pasted. Windows device-independent bitmaps and Linux clipboard images are encoded as PNG on that worker. A Copy or Cut made while the image is read keeps its internal clipboard. `edit.paste*` over MCP and scripts reads the bitmap at once. - The pixels of a PNG, JPEG, GIF or WebP file that Place decodes to check them are kept in the image store the renderers share, so the canvas's first frame with the placed image draws them without decoding the file again on the UI thread: File › Place, a file dropped on the canvas, a click or drag of the place cursor, `file.place`, and Paste of such an image. A CMYK JPEG is still decoded when it is first drawn (`crates/ui-egui/src/placing.rs`, `crates/render/src/tests.rs`). - A photo whose EXIF orientation turns or flips it (a camera held upright or upside down) is placed and opened upright, as it was taken; the image is stored as it is seen (#4284). A quarter turn swaps the resolution's axes, so the image keeps its physical size. TIFFs read without the image decoder (grayscale with extra channels, CCITT Group 3, CMYK with one plane per ink) follow their Orientation tag too, and a turned CMYK JPEG or TIFF keeps its inks, 8 bits each, as a CMYK TIFF. From 9fad6eb9526d054ad2eff33b3bf4fbe36621fb36 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 07:40:39 -0800 Subject: [PATCH 15/25] Objects on Path: Detach takes the chosen object off the path With one Objects on Path group selected and an object chosen with its Select/Move widget, Detach in the Properties panel's Objects on Path Options section takes that object out of the group (`object.objectsOnPath.detach {member?}`). The object goes just above the group in the Layers panel, stays where it is drawn and is selected alone. The other objects move up the path in their order: Auto Space spreads them evenly again, and a Space value and the start are kept. The group and its path stay with one object or none left. Hidden or locked objects and groups are refused, and Detach is one undo step. When the group is itself on another group's path, the object goes above the outer group so it does not join that path. Docs: docs/mcp.md, docs/target-app-parity.md. Detach and its undo name have rows in every catalog, and the new message in the complete-message catalogs. --- crates/engine/src/cmd/objects_on_path.rs | 56 ++++- crates/engine/src/cmd/plugin_call/reviewed.rs | 1 + crates/engine/src/tests/objects_on_path.rs | 194 ++++++++++++++++++ crates/ui-egui/src/i18n/bg.tsv | 2 + crates/ui-egui/src/i18n/bs.tsv | 3 + crates/ui-egui/src/i18n/ca.tsv | 3 + crates/ui-egui/src/i18n/cs.tsv | 3 + crates/ui-egui/src/i18n/da.tsv | 2 + crates/ui-egui/src/i18n/de.tsv | 3 + crates/ui-egui/src/i18n/el.tsv | 3 + crates/ui-egui/src/i18n/es.tsv | 3 + crates/ui-egui/src/i18n/fi.tsv | 3 + crates/ui-egui/src/i18n/fr.tsv | 3 + crates/ui-egui/src/i18n/hi.tsv | 3 + crates/ui-egui/src/i18n/hu.tsv | 3 + crates/ui-egui/src/i18n/id.tsv | 2 + crates/ui-egui/src/i18n/it.tsv | 3 + crates/ui-egui/src/i18n/ja.tsv | 3 + crates/ui-egui/src/i18n/ka.tsv | 3 + crates/ui-egui/src/i18n/ko.tsv | 3 + crates/ui-egui/src/i18n/nl.tsv | 3 + crates/ui-egui/src/i18n/pl.tsv | 3 + crates/ui-egui/src/i18n/pt-br.tsv | 3 + crates/ui-egui/src/i18n/ru.tsv | 3 + crates/ui-egui/src/i18n/sv.tsv | 3 + crates/ui-egui/src/i18n/tests.rs | 17 ++ crates/ui-egui/src/i18n/tr.tsv | 3 + crates/ui-egui/src/i18n/uk.tsv | 3 + crates/ui-egui/src/i18n/vi.tsv | 3 + crates/ui-egui/src/i18n/zh-hans.tsv | 3 + crates/ui-egui/src/i18n/zh-hant.tsv | 3 + crates/ui-egui/src/panels/properties.rs | 22 +- crates/ui-egui/src/panels/properties/tests.rs | 33 +++ docs/mcp.md | 15 ++ docs/target-app-parity.md | 3 +- 35 files changed, 412 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/cmd/objects_on_path.rs b/crates/engine/src/cmd/objects_on_path.rs index 296cef4dc2..7dc8aec1c9 100644 --- a/crates/engine/src/cmd/objects_on_path.rs +++ b/crates/engine/src/cmd/objects_on_path.rs @@ -12,7 +12,8 @@ //! `object.objectsOnPath.selectMember` chooses one object of a selected group (its Select/Move //! widget), and `object.objectsOnPath.moveMember` moves one object to another's place along the //! path, the objects between it and that place each moving one place toward where it was; hidden -//! and locked objects keep their places. +//! and locked objects keep their places. `object.objectsOnPath.detach` takes one object out of its +//! group, just above it, and the others move up the path. //! //! After every edit, [`refresh`] puts the objects of each Objects on Path group that changed back //! on its path: editing the path moves them, an object moved on its own goes back to its place, @@ -21,7 +22,8 @@ //! //! Behavior: (the tool and //! Object › Objects on Path › Attach; the order on the path, the attachment point, the distribution, -//! the objects squared to the path; Pivot and Rotate; path edits realign the objects; Expand). +//! the objects squared to the path; Pivot and Rotate; path edits realign the objects; Detach and +//! the objects that move up the path after it; Expand). use std::collections::{HashMap, HashSet}; use std::sync::Arc; @@ -75,6 +77,15 @@ pub fn specs() -> Vec { has_doc, move_member ), + cmd!( + "object.objectsOnPath.detach", + "Detach Object from Path", + [], + None, + "{member?: id of an object of an Objects on Path group (default: the object chosen with the selected group's Select/Move widget); neither the object nor the group may be hidden or locked} take one object off the path, out of its group and just above the group in the Layers panel, where it stays as drawn and is selected alone. The group's other objects move up the path in their order: with Auto Space they spread evenly again, and a Space value and the start are kept. The group and its path stay, even with one object or none left → {group, member}", + has_doc, + detach + ), cmd!( "object.objectsOnPath.expand", "Expand", @@ -383,6 +394,47 @@ fn move_member(s: &mut Session, p: &Value) -> Result { Ok(json!({ "group": g.0, "member": member.0, "index": index })) } +// ---------- Detach ---------- + +/// The object chosen with the Select/Move widget of the one selected Objects on Path group. +fn chosen_member(s: &Session) -> Option { + let st = s.active()?; + match st.selection.objects[..] { + [_] => st.selection.on_path_member, + _ => None, + } +} + +fn detach(s: &mut Session, p: &Value) -> Result { + const C: &str = "object.objectsOnPath.detach"; + const CHOOSE: &str = "choose the object to detach with its Select/Move widget"; + let (g, member) = if p.get("member").is_none_or(Value::is_null) { + let chosen = chosen_member(s).ok_or_else(|| bad(C, CHOOSE))?; + let found = member_param(s, &json!({ "member": chosen.0 }), "member", C)?; + if s.active().is_none_or(|st| st.selection.objects[..] != [found.0]) { + return Err(bad(C, CHOOSE)); + } + found + } else { + member_param(s, p, "member", C)? + }; + // The object goes just above the group, in the group's parent, and keeps where it is drawn. + // When the group is itself an object on another group's path, the object goes above that + // group instead (and so on outward), so it does not join that path. The refresh after the edit + // removes it from the group's record and moves the others up the path. + s.edit("Detach Object from Path", |d, sel| { + let mut above = g; + while let Some(p) = d.parent_of(above).filter(|p| d.node(*p).is_some_and(is_objects_on_path)) { + above = p; + } + let (parent, index, _) = d.position(above).ok_or(EngineError::NoNode(above))?; + d.move_node(member, parent, index + 1)?; + sel.set([member]); + Ok(()) + })?; + Ok(json!({ "group": g.0, "member": member.0 })) +} + // ---------- Expand ---------- fn expand(s: &mut Session, p: &Value) -> Result { diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index 5958a84b53..6223f8f218 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -314,6 +314,7 @@ pub(super) const ALLOWED: &[&str] = &[ "object.move", "object.nudge", "object.objectsOnPath.attach", + "object.objectsOnPath.detach", "object.objectsOnPath.expand", "object.objectsOnPath.moveMember", "object.objectsOnPath.options", diff --git a/crates/engine/src/tests/objects_on_path.rs b/crates/engine/src/tests/objects_on_path.rs index 4ae8321167..d9e76f85bf 100644 --- a/crates/engine/src/tests/objects_on_path.rs +++ b/crates/engine/src/tests/objects_on_path.rs @@ -681,3 +681,197 @@ fn the_space_saves_and_reopens_and_goes_with_a_copy() { let copy = s.doc().unwrap().selection.objects.to_vec(); assert_eq!(space(&s, copy[0]), (Some(40.0), 25.0)); } + +/// Where `id` is in the tree: its parent and its index there (0 at the bottom). +fn place_of(s: &Session, id: NodeId) -> (Option, usize) { + let (parent, index, _) = s.doc().unwrap().doc.position(id).unwrap(); + (parent, index) +} + +#[test] +fn detach_takes_the_chosen_object_off_the_path_and_the_others_move_up_in_one_undo_step() { + let mut s = session(); + let ([left, middle, right], path) = squares_and_line(&mut s); + let g = attach(&mut s, path, &[left, middle, right], json!({"rotate": 30})); + let (layer, at) = place_of(&s, g); + s.execute("object.objectsOnPath.selectMember", &json!({"member": middle.0})).unwrap(); + let drawn = s.doc().unwrap().doc.node(middle).unwrap().clone(); + let steps = s.doc().unwrap().history.undo.len(); + let v = s.execute("object.objectsOnPath.detach", &json!({})).unwrap(); + assert_eq!(v, json!({"group": g.0, "member": middle.0})); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "one undo step"); + let (on_path, children) = orders(&s, g); + assert_eq!(on_path, [left, right]); + assert!(children.len() == 3 && !children.contains(&middle), "{children:?}"); + assert_eq!(place_of(&s, middle), (layer, at + 1), "just above the group, in its layer"); + assert_eq!(s.doc().unwrap().doc.node(middle), Some(&drawn), "the object keeps its art, place and rotation"); + let sel = &s.doc().unwrap().selection; + assert_eq!((sel.objects.as_slice(), sel.on_path_member), (&[middle][..], None), "the detached object alone is selected"); + // The two left stay on the ends of the path; the path stays. + assert_eq!(center(&s, left), Point::new(50.0, 300.0)); + assert_eq!(center(&s, right), Point::new(350.0, 300.0)); + assert_eq!(s.doc().unwrap().doc.node(g).unwrap().extras().objects_on_path.as_deref().unwrap().path, path); + // The detached object is free: moving it moves it, and the group does not take it back. + s.execute("object.move", &json!({"ids": [middle.0], "dx": 0, "dy": -100})).unwrap(); + assert_eq!(center(&s, middle), Point::new(200.0, 200.0)); + assert_eq!(orders(&s, g).0, [left, right]); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + let (on_path, children) = orders(&s, g); + assert_eq!(on_path, [left, middle, right], "undo puts it back on the path"); + assert!(children.contains(&middle), "{children:?}"); + assert_eq!(center(&s, middle), Point::new(200.0, 300.0)); + assert_eq!(center(&s, right), Point::new(350.0, 300.0)); + let sel = &s.doc().unwrap().selection; + assert_eq!((sel.objects.as_slice(), sel.on_path_member), (&[g][..], Some(middle)), "and the choice back"); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(orders(&s, g).0, [left, right]); + assert_eq!(place_of(&s, middle), (layer, at + 1)); +} + +#[test] +fn after_the_first_object_is_detached_the_second_takes_the_start() { + let mut s = session(); + let ([left, middle, right], path) = squares_and_line(&mut s); + let g = attach(&mut s, path, &[left, middle, right], json!({})); + select(&mut s, &[]); + let v = s.execute("object.objectsOnPath.detach", &json!({"member": left.0})).unwrap(); + assert_eq!(v, json!({"group": g.0, "member": left.0})); + assert_eq!(orders(&s, g).0, [middle, right]); + assert_eq!(center(&s, middle), Point::new(50.0, 300.0), "the second object moves up to the start"); + assert_eq!(center(&s, right), Point::new(350.0, 300.0)); + assert_eq!(center(&s, left), Point::new(50.0, 300.0), "the detached object stays where it was drawn"); + assert_eq!(s.doc().unwrap().selection.objects.to_vec(), [left]); +} + +#[test] +fn detach_on_a_closed_path_spreads_the_others_all_the_way_round_again() { + let mut s = session(); + let ids: Vec = (0..4).map(|i| rect(&mut s, 10.0 + 40.0 * f64::from(i), 0.0, 10.0, 10.0)).collect(); + let ring = rect(&mut s, 100.0, 100.0, 200.0, 200.0); + let g = attach(&mut s, ring, &ids, json!({})); + s.execute("object.objectsOnPath.detach", &json!({"member": ids[1].0})).unwrap(); + assert_eq!(orders(&s, g).0, [ids[0], ids[2], ids[3]]); + let data = s.doc().unwrap().doc.node(ring).unwrap().path_data().unwrap().clone(); + let stops = vectorcraft_doc::objects_on_path::stops(&data, 3, None, 0.0).unwrap(); + for (id, (p, _)) in [ids[0], ids[2], ids[3]].iter().zip(stops) { + let c = center(&s, *id); + assert!((c.x - p.x).abs() < 1e-3 && (c.y - p.y).abs() < 1e-3, "a third of the way round apart: {c:?} {p:?}"); + } +} + +#[test] +fn detach_keeps_a_space_value_and_the_start() { + let mut s = session(); + let (g, [a, b, c], _) = three_on_a_line(&mut s); + s.execute("object.objectsOnPath.options", &json!({"start": 20})).unwrap(); + s.execute("object.objectsOnPath.detach", &json!({"member": a.0})).unwrap(); + assert_eq!(space(&s, g), (Some(100.0), 20.0)); + assert_eq!(center(&s, b), Point::new(70.0, 300.0), "the second object moves up to the first place"); + assert_eq!(center(&s, c), Point::new(170.0, 300.0)); + // A Space value the path is too short for stays, and two objects get more of the path. + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("object.objectsOnPath.options", &json!({"spacing": 200, "start": 0})).unwrap(); + assert_eq!(center(&s, c), Point::new(350.0, 300.0), "three objects drawn 150 pt apart"); + s.execute("object.objectsOnPath.detach", &json!({"member": b.0})).unwrap(); + assert_eq!(space(&s, g), (Some(200.0), 0.0)); + assert_eq!(center(&s, a), Point::new(50.0, 300.0)); + assert_eq!(center(&s, c), Point::new(250.0, 300.0), "two objects 200 pt apart"); +} + +#[test] +fn the_group_and_its_path_stay_with_one_object_or_none_left() { + let mut s = session(); + let ([left, middle, _], path) = squares_and_line(&mut s); + let g = attach(&mut s, path, &[left, middle], json!({"pivot": 7})); + s.execute("object.objectsOnPath.options", &json!({"spacing": 30})).unwrap(); + s.execute("object.objectsOnPath.detach", &json!({"member": left.0})).unwrap(); + assert_eq!(orders(&s, g), (vec![middle], vec![path, middle])); + let b = bounds(&s, middle); + assert!((b.center().x - 50.0).abs() < 1e-6 && (b.y1 - 300.0).abs() < 1e-6, "the one left on the start, by its Pivot: {b:?}"); + s.execute("object.objectsOnPath.detach", &json!({"member": middle.0})).unwrap(); + let n = s.doc().unwrap().doc.node(g).unwrap().clone(); + let rec = n.extras().objects_on_path.as_deref().unwrap(); + assert_eq!((rec.path, rec.members.len(), rec.pivot, rec.spacing), (path, 0, 7, Some(30.0)), "a live group with no objects"); + assert_eq!(orders(&s, g).1, [path]); + // An object moved back in joins the path. + s.execute("layer.move", &json!({"ids": [left.0], "target": g.0, "place": "inside"})).unwrap(); + assert_eq!(orders(&s, g).0, [left]); +} + +#[test] +fn detach_refuses_what_is_not_one_chosen_editable_object_on_a_path() { + let mut s = session(); + let (g, [a, b, c], path) = three_on_a_line(&mut s); + let loose = rect(&mut s, 300.0, 20.0, 10.0, 10.0); + let err = |s: &mut Session, p: Value| s.execute("object.objectsOnPath.detach", &p).unwrap_err().to_string(); + let choose = "choose the object to detach with its Select/Move widget"; + let steps = s.doc().unwrap().history.undo.len(); + select(&mut s, &[g]); + assert!(err(&mut s, json!({})).contains(choose), "the group without a chosen object"); + select(&mut s, &[]); + assert!(err(&mut s, json!({})).contains(choose), "nothing selected"); + assert!(err(&mut s, json!({"member": path.0})).contains("`member` must name an object attached"), "the path"); + assert!(err(&mut s, json!({"member": g.0})).contains("`member` must name"), "the group itself"); + assert!(err(&mut s, json!({"member": loose.0})).contains("`member` must name"), "an object on no path"); + assert!(err(&mut s, json!({"member": 99999})).contains("no such object")); + assert!(err(&mut s, json!({"member": "a"})).contains("invalid object id")); + // Hidden and locked objects stay; a locked group keeps all of its objects. + select(&mut s, &[c]); + s.execute("object.lock", &json!({})).unwrap(); + assert!(err(&mut s, json!({"member": c.0})).contains("`member` names an object that is hidden or locked")); + s.execute("object.unlockAll", &json!({})).unwrap(); + select(&mut s, &[b]); + s.execute("object.hide", &json!({})).unwrap(); + assert!(err(&mut s, json!({"member": b.0})).contains("hidden or locked"), "a hidden object"); + s.execute("object.showAll", &json!({})).unwrap(); + select(&mut s, &[g]); + s.execute("object.lock", &json!({})).unwrap(); + assert!(err(&mut s, json!({"member": a.0})).contains("the Objects on Path group is hidden or locked")); + s.execute("object.unlockAll", &json!({})).unwrap(); + assert_eq!(orders(&s, g).0, [a, b, c], "nothing refused detached anything"); + let undone = s.doc().unwrap().history.undo.len(); + assert_eq!(undone, steps + 6, "only the lock, hide and show steps"); +} + +#[test] +fn an_object_detached_from_a_group_on_another_path_does_not_join_that_path() { + let mut s = session(); + let ([left, middle, right], path) = squares_and_line(&mut s); + let inner = attach(&mut s, path, &[left, middle], json!({})); + let outer_line = line(&mut s, (20.0, 380.0), (380.0, 380.0)); + let outer = attach(&mut s, outer_line, &[inner, right], json!({})); + let outer_members = orders(&s, outer).0; + s.execute("object.objectsOnPath.detach", &json!({"member": left.0})).unwrap(); + assert_eq!(orders(&s, inner).0, [middle]); + assert_eq!(orders(&s, outer).0, outer_members, "the outer path keeps its objects and takes no new one"); + let (layer, at) = place_of(&s, outer); + assert_eq!(place_of(&s, left), (layer, at + 1), "above the outer group"); +} + +#[test] +fn hidden_and_locked_objects_left_on_the_path_move_up_too() { + let mut s = session(); + let ([left, middle, right], path) = squares_and_line(&mut s); + let g = attach(&mut s, path, &[left, middle, right], json!({})); + select(&mut s, &[right]); + s.execute("object.lock", &json!({})).unwrap(); + select(&mut s, &[middle]); + s.execute("object.hide", &json!({})).unwrap(); + s.execute("object.objectsOnPath.detach", &json!({"member": left.0})).unwrap(); + assert_eq!(orders(&s, g).0, [middle, right]); + assert_eq!(center(&s, middle), Point::new(50.0, 300.0), "the hidden object moves up to the start"); + assert_eq!(center(&s, right), Point::new(350.0, 300.0)); +} + +#[test] +fn objects_moved_out_together_in_the_layers_panel_all_leave_the_path() { + let mut s = session(); + let ([left, middle, right], path) = squares_and_line(&mut s); + let g = attach(&mut s, path, &[left, middle, right], json!({})); + s.execute("layer.move", &json!({"ids": [left.0, middle.0], "target": g.0, "place": "above"})).unwrap(); + assert_eq!(orders(&s, g), (vec![right], vec![path, right])); + assert_eq!(center(&s, right), Point::new(50.0, 300.0), "the one left takes the start"); + let (layer, at) = place_of(&s, g); + assert_eq!((place_of(&s, left), place_of(&s, middle)), ((layer, at + 1), (layer, at + 2)), "above the group, in their order"); +} diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 1fb96d9c7d..695a914c02 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -1537,6 +1537,8 @@ font-technology Variable Променливи Objects on Path Tool Инструмент „Обекти по пътя“ Attach Objects on Path Прикрепяне на обекти към пътя Expand Objects on Path Разширяване на обекти по пътя + Detach Откачване + Detach Object from Path Откачване на обект от пътя Release Live Paint Освобождаване на динамично оцветяване Release Repeat Освобождаване на повторение Release Slice Освобождаване на отрязък diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index f04e9535e5..dead3c7366 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -1809,6 +1809,8 @@ digits Malayalam Malajalam Objects on Path Tool Alat objekti na putanji Attach Objects on Path Priloži objekte na putanju Expand Objects on Path Proširi objekte na putanji + Detach Odvoji + Detach Object from Path Odvoji objekat s putanje Release Live Paint Oslobodi živo bojenje Release Repeat Oslobodi ponavljanje Release Slice Oslobodi isječak @@ -4924,6 +4926,7 @@ imageTrace Outline Obris @msg select a repeat odaberite ponavljanje @msg select an Intertwine group odaberite Intertwine grupu @msg select an Objects on Path group odaberite grupu objekata na putanji +@msg choose the object to detach with its Select/Move widget odaberite objekat koji želite odvojiti njegovom ručicom Odaberi/Pomjeri @msg a path inside a compound path, blend, envelope, repeat or Intertwine group can't take objects putanja unutar složene putanje, stapanja, omotnice, ponavljanja ili Intertwine grupe ne može primiti objekte @msg a clipping path can't take objects putanja isijecanja ne može primiti objekte @msg objects inside a blend, envelope, repeat or Intertwine group can't be attached to a path objekti unutar stapanja, omotnice, ponavljanja ili Intertwine grupe ne mogu se priložiti putanji diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index e6b6f398f2..5d0d4ce9bf 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -1542,6 +1542,8 @@ antiAlias Sharp Nítid Expand Live Paint Expandeix la pintura interactiva Expand Object Expandeix l’objecte Expand Objects on Path Expandeix els objectes del traçat + Detach Separa + Detach Object from Path Separa l’objecte del traçat Expand Options Opcions d’expansió Expand Panels Expandeix els panells Expand Repeat Expandeix la repetició @@ -6000,6 +6002,7 @@ digits Malayalam Malaiàlam @msg select an Intertwine group selecciona un grup Intertwine @msg select an object in perspective selecciona un objecte en perspectiva @msg select an Objects on Path group selecciona un grup d’objectes sobre un traçat +@msg choose the object to detach with its Select/Move widget tria l’objecte que vols separar amb el seu control Selecciona/Mou @msg select artwork (or a colour group) to recolor selecciona la il·lustració (o un grup de colors) per recolorejar @msg Recolor completed; {locked} and {hidden} were left unchanged Recoloració completada; sense canvis: {locked} i {hidden} @msg Recolor completed; {objects} were left unchanged Recoloració completada; sense canvis: {objects} diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index a44e3b9979..7356a6179c 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -1840,6 +1840,8 @@ digits Malayalam Malajálamské Objects on Path Tool Nástroj Objekty na cestě Attach Objects on Path Připojit objekty na cestu Expand Objects on Path Rozložit objekty na cestě + Detach Odpojit + Detach Object from Path Odpojit objekt od cesty Release Live Paint Uvolnit živou malbu Release Repeat Uvolnit opakování Release Slice Uvolnit řez @@ -5091,6 +5093,7 @@ imageTrace Outline Obrys @msg select a repeat vyberte opakování @msg select an Intertwine group vyberte skupinu propletení @msg select an Objects on Path group vyberte skupinu objektů na cestě +@msg choose the object to detach with its Select/Move widget vyberte objekt k odpojení jeho ovládacím prvkem Vybrat/Přesunout @msg a path inside a compound path, blend, envelope, repeat or Intertwine group can't take objects cesta uvnitř složené cesty, prolnutí, obálky, opakování nebo skupiny propletení nemůže přijmout objekty @msg a clipping path can't take objects ořezová cesta nemůže přijmout objekty @msg objects inside a blend, envelope, repeat or Intertwine group can't be attached to a path objekty uvnitř prolnutí, obálky, opakování nebo skupiny propletení nelze připojit na cestu diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index bce3bd12da..8b2d8b6683 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -5821,6 +5821,8 @@ swatch Bright Violet Kraftig violet Objects on Path Tool Objekter på kurve-værktøj Attach Objects on Path Tilknyt objekter til kurve Expand Objects on Path Udvid objekter på kurve + Detach Frigør + Detach Object from Path Frigør objekt fra kurve Release Live Paint Frigør live-maling Release Repeat Frigør gentagelse Release Slice Frigør udsnit diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 0d995ddc2e..1148856319 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -1592,6 +1592,8 @@ file-filter Templates Vorlagen Objects on Path Tool Objekte-auf-Pfad-Werkzeug Attach Objects on Path Objekte an Pfad anhängen Expand Objects on Path Objekte auf Pfad umwandeln + Detach Lösen + Detach Object from Path Objekt vom Pfad lösen Release Live Paint „Interaktiv malen“ zurückwandeln Release Repeat Wiederholung zurückwandeln Release Slice Slice zurückwandeln @@ -4706,6 +4708,7 @@ theme Appearance Erscheinungsbild @msg select a repeat wählen Sie eine Wiederholung aus @msg select an Intertwine group wählen Sie eine Verflechtungsgruppe aus @msg select an Objects on Path group wählen Sie eine Gruppe „Objekte auf Pfad“ aus +@msg choose the object to detach with its Select/Move widget wählen Sie das zu lösende Objekt mit seinem Steuerelement „Auswählen/Verschieben“ aus @msg a path inside a compound path, blend, envelope, repeat or Intertwine group can't take objects ein Pfad in einem zusammengesetzten Pfad, einer Angleichung, einer Hülle, einer Wiederholung oder einer Verflechtungsgruppe kann keine Objekte aufnehmen @msg a clipping path can't take objects ein Schnittpfad kann keine Objekte aufnehmen @msg objects inside a blend, envelope, repeat or Intertwine group can't be attached to a path die Objekte in einer Angleichung, einer Hülle, einer Wiederholung oder einer Verflechtungsgruppe können nicht an einen Pfad angehängt werden diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index cb409e9274..a906b40d12 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -1512,6 +1512,8 @@ font-technology Variable Μεταβλητές Objects on Path Tool Αντικείμενα σε διαδρομή (Objects on Path Tool) Attach Objects on Path Προσάρτηση αντικειμένων σε διαδρομή Expand Objects on Path Επέκταση αντικειμένων σε διαδρομή + Detach Αποσύνδεση + Detach Object from Path Αποσύνδεση αντικειμένου από διαδρομή Release Live Paint Αποδέσμευση δυναμικής βαφής Release Repeat Αποδέσμευση επανάληψης Release Slice Αποδέσμευση τομής @@ -6016,6 +6018,7 @@ effect Points Σημεία @msg no bound object reports a value (locked objects and embedded images report none) κανένα συνδεδεμένο αντικείμενο δεν αναφέρει τιμή (τα κλειδωμένα αντικείμενα και οι ενσωματωμένες εικόνες δεν αναφέρουν καμία) @msg select an Intertwine group επιλέξτε μια ομάδα διαπλοκής @msg select an Objects on Path group επιλέξτε μια ομάδα αντικειμένων σε διαδρομή +@msg choose the object to detach with its Select/Move widget επιλέξτε το αντικείμενο προς αποσύνδεση με το στοιχείο ελέγχου Επιλογή/Μετακίνηση @msg a path inside a compound path, blend, envelope, repeat or Intertwine group can't take objects μια διαδρομή μέσα σε σύνθετη διαδρομή, ανάμειξη, περίβλημα, επανάληψη ή ομάδα διαπλοκής δεν μπορεί να δεχτεί αντικείμενα @msg a clipping path can't take objects μια διαδρομή αποκοπής δεν μπορεί να δεχτεί αντικείμενα @msg objects inside a blend, envelope, repeat or Intertwine group can't be attached to a path τα αντικείμενα μέσα σε ανάμειξη, περίβλημα, επανάληψη ή ομάδα διαπλοκής δεν μπορούν να προσαρτηθούν σε διαδρομή diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index de9512cddb..57b9ee9cd7 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -1592,6 +1592,8 @@ font-technology Variable Variables Objects on Path Tool Herramienta Objetos en trazado Attach Objects on Path Adjuntar objetos al trazado Expand Objects on Path Expandir objetos en trazado + Detach Separar + Detach Object from Path Separar objeto del trazado Release Live Paint Soltar pintura interactiva Release Repeat Soltar repetición Release Slice Soltar sector @@ -4783,6 +4785,7 @@ axis Both Ambos @msg select a repeat selecciona una repetición @msg select an Intertwine group selecciona un grupo entrelazado @msg select an Objects on Path group selecciona un grupo de objetos en trazado +@msg choose the object to detach with its Select/Move widget elige el objeto que quieres separar con su control Seleccionar/Mover @msg a path inside a compound path, blend, envelope, repeat or Intertwine group can't take objects un trazado dentro de un trazado compuesto, una fusión, una envolvente, una repetición o un grupo entrelazado no puede recibir objetos @msg a clipping path can't take objects un trazado de recorte no puede recibir objetos @msg objects inside a blend, envelope, repeat or Intertwine group can't be attached to a path los objetos dentro de una fusión, una envolvente, una repetición o un grupo entrelazado no se pueden adjuntar a un trazado diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 1c3327fb1e..e80c061677 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -1813,6 +1813,8 @@ digits Malayalam Malajalam Objects on Path Tool Objektit polulla -työkalu Attach Objects on Path Kiinnitä objektit polulle Expand Objects on Path Laajenna objektit polulla + Detach Irrota + Detach Object from Path Irrota objekti polulta Release Live Paint Vapauta elävä maalaus Release Repeat Vapauta toisto Release Slice Vapauta siivu @@ -6028,6 +6030,7 @@ mark-style Japanese Japanilainen @msg no bound object reports a value (locked objects and embedded images report none) mikään sidottu objekti ei ilmoita arvoa (lukitut objektit ja upotetut kuvat eivät ilmoita arvoa) @msg select an Intertwine group valitse lomitusryhmä @msg select an Objects on Path group valitse Objektit polulla -ryhmä +@msg choose the object to detach with its Select/Move widget valitse irrotettava objekti sen Valitse/Siirrä-säätimellä @msg a path inside a compound path, blend, envelope, repeat or Intertwine group can't take objects yhdistelmäpolun, sulautuksen, vääristyskuoren, toiston tai lomitusryhmän sisällä olevaan polkuun ei voi kiinnittää objekteja @msg a clipping path can't take objects leikkauspolkuun ei voi kiinnittää objekteja @msg objects inside a blend, envelope, repeat or Intertwine group can't be attached to a path sulautuksen, vääristyskuoren, toiston tai lomitusryhmän sisällä olevia objekteja ei voi kiinnittää polulle diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 3b45c4d386..450a696e99 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -1586,6 +1586,8 @@ font-technology Variable Variables Objects on Path Tool Outil Objets sur tracé Attach Objects on Path Attacher des objets au tracé Expand Objects on Path Décomposer les objets sur tracé + Detach Détacher + Detach Object from Path Détacher l’objet du tracé Release Live Paint Annuler la peinture dynamique Release Repeat Annuler la répétition Release Slice Annuler la tranche @@ -4772,6 +4774,7 @@ axis Both Les deux @msg select a repeat sélectionnez une répétition @msg select an Intertwine group sélectionnez un groupe entrelacé @msg select an Objects on Path group sélectionnez un groupe d’objets sur tracé +@msg choose the object to detach with its Select/Move widget choisissez l’objet à détacher avec sa commande Sélectionner/Déplacer @msg a path inside a compound path, blend, envelope, repeat or Intertwine group can't take objects un tracé à l’intérieur d’un tracé transparent, d’un dégradé de formes, d’une enveloppe, d’une répétition ou d’un groupe entrelacé ne peut pas recevoir d’objets @msg a clipping path can't take objects un tracé d’écrêtage ne peut pas recevoir d’objets @msg objects inside a blend, envelope, repeat or Intertwine group can't be attached to a path les objets à l’intérieur d’un dégradé de formes, d’une enveloppe, d’une répétition ou d’un groupe entrelacé ne peuvent pas être attachés à un tracé diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 0c6089e40a..e1c1c0ef7a 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -1706,6 +1706,8 @@ antiAlias Sharp शार्प Expand Live Paint लाइव पेंट एक्सपैंड करें Expand Object ऑब्जेक्ट का विस्तार Expand Objects on Path पाथ पर ऑब्जेक्ट्स एक्सपैंड करें + Detach अलग करें + Detach Object from Path पाथ से ऑब्जेक्ट अलग करें Expand Options ऑप्शन्स एक्सपैंड करें Expand Panels पैनलों का विस्तार Expand Repeat रिपीट एक्सपैंड करें @@ -7731,6 +7733,7 @@ antiAlias Sharp शार्प @msg select an object with a freeform gradient एक फ्रीफॉर्म ग्रेडिएंट के साथ एक ऑब्जेक्ट सिलेक्ट करें @msg select an object with an opacity mask एक opacity मास्क के साथ एक ऑब्जेक्ट सिलेक्ट करें @msg select an Objects on Path group पाथ समूह पर एक ऑब्जेक्ट चुनें +@msg choose the object to detach with its Select/Move widget अलग करने वाले ऑब्जेक्ट को उसके चुनें/ले जाएँ विजेट से चुनें @msg select area type क्षेत्र प्रकार सिलेक्ट करें @msg select area type (text in a frame) क्षेत्र प्रकार (एक फ्रेम में टेक्स्ट) सिलेक्ट करें @msg select area type and closed paths (at least one area type object) क्षेत्र प्रकार और बंद पाथ (कम से कम एक क्षेत्र प्रकार ऑब्जेक्ट) सिलेक्ट करें diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 06122f94ee..db3587cd1f 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -1999,6 +1999,8 @@ file-filter Templates Sablonok Objects on Path Tool Objektumok útvonalon Attach Objects on Path Objektumok csatolása útvonalhoz Expand Objects on Path Objektumok útvonalon kibontása + Detach Leválasztás + Detach Object from Path Objektum leválasztása az útvonalról Release Live Paint Élő festés megszüntetése Release Repeat Ismétlés megszüntetése Release Slice Szelet megszüntetése @@ -5539,6 +5541,7 @@ imageTrace Outline Körvonal @msg select a repeat jelölj ki egy ismétlést @msg select an Intertwine group jelölj ki egy összefonási csoportot @msg select an Objects on Path group jelölj ki egy Objektumok útvonalon csoportot +@msg choose the object to detach with its Select/Move widget válaszd ki a leválasztandó objektumot a Kijelölés/Mozgatás vezérlőjével @msg a path inside a compound path, blend, envelope, repeat or Intertwine group can't take objects összetett útvonalban, összemosásban, burkolóban, ismétlésben vagy összefonási csoportban lévő útvonalhoz nem csatolhatók objektumok @msg a clipping path can't take objects vágóútvonalhoz nem csatolhatók objektumok @msg objects inside a blend, envelope, repeat or Intertwine group can't be attached to a path összemosásban, burkolóban, ismétlésben vagy összefonási csoportban lévő objektumok nem csatolhatók útvonalhoz diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 00d2b09600..ecdb10db4f 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -5821,6 +5821,8 @@ swatch Bright Violet Violet cerah Objects on Path Tool Alat objek pada jalur Attach Objects on Path Tempelkan objek pada jalur Expand Objects on Path Perluas objek pada jalur + Detach Lepaskan + Detach Object from Path Lepaskan objek dari jalur Release Live Paint Lepaskan Live Paint Release Repeat Lepaskan perulangan Release Slice Lepaskan slice diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 869fe2e4a0..3ef40a5c95 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -1623,6 +1623,8 @@ file-filter Templates Modelli Objects on Path Tool Strumento Oggetti su tracciato Attach Objects on Path Aggancia oggetti al tracciato Expand Objects on Path Espandi oggetti su tracciato + Detach Sgancia + Detach Object from Path Sgancia oggetto dal tracciato Release Live Paint Rilascia pittura dinamica Release Repeat Rilascia ripetizione Release Slice Rilascia sezione @@ -4834,6 +4836,7 @@ axis Both Entrambi @msg select a repeat seleziona una ripetizione @msg select an Intertwine group seleziona un gruppo intrecciato @msg select an Objects on Path group seleziona un gruppo di oggetti su tracciato +@msg choose the object to detach with its Select/Move widget scegli l’oggetto da sganciare con il suo controllo Seleziona/Sposta @msg a path inside a compound path, blend, envelope, repeat or Intertwine group can't take objects un tracciato all'interno di un tracciato composto, una fusione, un involucro, una ripetizione o un gruppo intrecciato non può ricevere oggetti @msg a clipping path can't take objects un tracciato di ritaglio non può ricevere oggetti @msg objects inside a blend, envelope, repeat or Intertwine group can't be attached to a path gli oggetti all'interno di una fusione, un involucro, una ripetizione o un gruppo intrecciato non possono essere agganciati a un tracciato diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index a0ce9c93b9..9d88af4809 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -1992,6 +1992,8 @@ antiAlias Sharp シャープ Objects on Path Tool パス上のオブジェクトツール Attach Objects on Path パス上のオブジェクトをアタッチ Expand Objects on Path パス上のオブジェクトを拡張 + Detach 切り離し + Detach Object from Path オブジェクトをパスから切り離し Release Live Paint ライブペイントを解除 Release Repeat リピートを解除 Release Slice スライスを解除 @@ -4556,6 +4558,7 @@ swatch Bright Violet ビビッドバイオレット @msg select a repeat リピートを選択してください @msg select an Intertwine group 織り交ぜグループを選択してください @msg select an Objects on Path group パス上のオブジェクトグループを選択してください +@msg choose the object to detach with its Select/Move widget 切り離すオブジェクトを選択/移動ウィジェットで選んでください @msg a path inside a compound path, blend, envelope, repeat or Intertwine group can't take objects 複合パス、ブレンド、エンベロープ、リピートまたは織り交ぜグループ内のパスにはオブジェクトをアタッチできません @msg a clipping path can't take objects クリッピングパスにはオブジェクトをアタッチできません @msg objects inside a blend, envelope, repeat or Intertwine group can't be attached to a path ブレンド、エンベロープ、リピートまたは織り交ぜグループ内のオブジェクトはパスにアタッチできません diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index b19ed4009a..b57164cce1 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -5715,6 +5715,7 @@ imageTrace Outline კონტური Arrange Intertwine Area გადახლართვის არის დალაგება @msg select an Intertwine group მონიშნეთ გადახლართვის ჯგუფი @msg select an Objects on Path group მონიშნეთ ტრაექტორიაზე ობიექტების ჯგუფი +@msg choose the object to detach with its Select/Move widget მოსახსნელი ობიექტი აირჩიეთ მისი არჩევა/გადატანის ვიჯეტით @msg a path inside a compound path, blend, envelope, repeat or Intertwine group can't take objects შედგენილ ტრაექტორიაში, გადასვლაში, გარსში, გამეორებაში ან გადახლართვის ჯგუფში მყოფ ტრაექტორიაზე ობიექტების მიმაგრება ვერ ხერხდება @msg a clipping path can't take objects მომჭრელ ტრაექტორიაზე ობიექტების მიმაგრება ვერ ხერხდება @msg objects inside a blend, envelope, repeat or Intertwine group can't be attached to a path გადასვლაში, გარსში, გამეორებაში ან გადახლართვის ჯგუფში მყოფი ობიექტების ტრაექტორიაზე მიმაგრება ვერ ხერხდება @@ -5977,6 +5978,8 @@ imageTrace Outline კონტური Objects on Path Tool ტრაექტორიაზე ობიექტების ხელსაწყო Attach Objects on Path ობიექტების ტრაექტორიაზე მიმაგრება Expand Objects on Path ტრაექტორიაზე ობიექტების გაშლა + Detach მოხსნა + Detach Object from Path ობიექტის ტრაექტორიიდან მოხსნა Release Live Paint ცოცხალი შეღებვის მოხსნა Release Repeat გამეორების მოხსნა Release Slice ნაჭრის მოხსნა diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 3f518f00c4..0dec091e81 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -1982,6 +1982,8 @@ antiAlias Sharp 날카롭게 Objects on Path Tool 패스 위 개체 도구 Attach Objects on Path 패스 위 개체 부착 Expand Objects on Path 패스 위 개체 확장 + Detach 분리 + Detach Object from Path 패스에서 개체 분리 Release Live Paint 라이브 페인트 해제 Release Repeat 반복 해제 Release Slice 분할 해제 @@ -4483,6 +4485,7 @@ theme Appearance 외관 @msg select a repeat 반복을 선택하세요 @msg select an Intertwine group 교차 그룹을 선택하세요 @msg select an Objects on Path group 패스 위 개체 그룹을 선택하세요 +@msg choose the object to detach with its Select/Move widget 분리할 개체를 선택/이동 위젯으로 고르세요 @msg a path inside a compound path, blend, envelope, repeat or Intertwine group can't take objects 컴파운드 패스, 블렌드, 엔벨로프, 반복 또는 교차 그룹 안의 패스에는 개체를 부착할 수 없습니다 @msg a clipping path can't take objects 클리핑 패스에는 개체를 부착할 수 없습니다 @msg objects inside a blend, envelope, repeat or Intertwine group can't be attached to a path 블렌드, 엔벨로프, 반복 또는 교차 그룹 안의 개체는 패스에 부착할 수 없습니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 40facfda42..0d330108dc 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -185,6 +185,7 @@ @msg node {_1} is on a locked artboard knooppunt {_1} staat op een vergrendeld tekengebied @msg thumbnail: no page {n} (the file has 1) miniatuur: geen pagina {n} (het bestand heeft er 1) @msg select an Objects on Path group selecteer een groep Objecten op pad +@msg choose the object to detach with its Select/Move widget kies het object dat je wilt loskoppelen met zijn widget Selecteren/verplaatsen @msg a path inside a compound path, blend, envelope, repeat or Intertwine group can't take objects een pad binnen een samengesteld pad, mengsel, omvorming, herhaling of verstrengelingsgroep kan geen objecten opnemen @msg a clipping path can't take objects een knippad kan geen objecten opnemen @msg objects inside a blend, envelope, repeat or Intertwine group can't be attached to a path objecten binnen een mengsel, omvorming, herhaling of verstrengelingsgroep kunnen niet aan een pad worden gekoppeld @@ -6391,6 +6392,8 @@ swatch Bright Violet Felviolet Objects on Path Tool Objecten-op-pad-gereedschap Attach Objects on Path Objecten aan pad koppelen Expand Objects on Path Objecten op pad uitbreiden + Detach Loskoppelen + Detach Object from Path Object van pad loskoppelen Release Live Paint Live Paint vrijgeven Release Repeat Herhaling vrijgeven Release Slice Slice vrijgeven diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 770622cc1e..9955d76ff7 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -1757,6 +1757,8 @@ digits Malayalam Malajalam Objects on Path Tool Narzędzie Obiekty na ścieżce Attach Objects on Path Dołącz obiekty do ścieżki Expand Objects on Path Rozszerz obiekty na ścieżce + Detach Odłącz + Detach Object from Path Odłącz obiekt od ścieżki Release Live Paint Uwolnij aktywne malowanie Release Repeat Uwolnij powtórzenie Release Slice Uwolnij plasterek @@ -4916,6 +4918,7 @@ imageTrace Outline Kontur @msg select a repeat zaznacz powtórzenie @msg select an Intertwine group zaznacz grupę przeplotu @msg select an Objects on Path group zaznacz grupę obiektów na ścieżce +@msg choose the object to detach with its Select/Move widget wybierz obiekt do odłączenia jego uchwytem Zaznacz/Przesuń @msg a path inside a compound path, blend, envelope, repeat or Intertwine group can't take objects do ścieżki wewnątrz ścieżki złożonej, przejścia, koperty, powtórzenia lub grupy przeplotu nie można dołączyć obiektów @msg a clipping path can't take objects do ścieżki przycinającej nie można dołączyć obiektów @msg objects inside a blend, envelope, repeat or Intertwine group can't be attached to a path obiektów wewnątrz przejścia, koperty, powtórzenia lub grupy przeplotu nie można dołączyć do ścieżki diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 77fce38c53..148e676987 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -1410,6 +1410,8 @@ antiAlias Sharp Nítido Objects on Path Tool Ferramenta Objetos no Caminho Attach Objects on Path Anexar Objetos ao Caminho Expand Objects on Path Expandir Objetos no Caminho + Detach Desanexar + Detach Object from Path Desanexar Objeto do Caminho Release Live Paint Liberar Pintura ao Vivo Release Repeat Liberar Repetição Release Slice Liberar Fatia @@ -4239,6 +4241,7 @@ axis Both Ambos @msg select a repeat selecione uma repetição @msg select an Intertwine group selecione um grupo entrelaçado @msg select an Objects on Path group selecione um grupo de objetos no caminho +@msg choose the object to detach with its Select/Move widget escolha o objeto a desanexar com o controle Selecionar/Mover dele @msg a path inside a compound path, blend, envelope, repeat or Intertwine group can't take objects um caminho dentro de um caminho composto, mesclagem, envelope, repetição ou grupo entrelaçado não pode receber objetos @msg a clipping path can't take objects um caminho de recorte não pode receber objetos @msg objects inside a blend, envelope, repeat or Intertwine group can't be attached to a path objetos dentro de uma mesclagem, envelope, repetição ou grupo entrelaçado não podem ser anexados a um caminho diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index b546e87258..0987445196 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -1612,6 +1612,8 @@ file-filter Templates Шаблоны Objects on Path Tool Инструмент «Объекты на контуре» Attach Objects on Path Прикрепить объекты к контуру Expand Objects on Path Разобрать объекты на контуре + Detach Открепить + Detach Object from Path Открепить объект от контура Release Live Paint Освободить быструю заливку Release Repeat Освободить повтор Release Slice Освободить фрагмент @@ -4820,6 +4822,7 @@ axis Both Оба @msg select a repeat выделите повтор @msg select an Intertwine group выделите группу переплетения @msg select an Objects on Path group выделите группу объектов на контуре +@msg choose the object to detach with its Select/Move widget выберите открепляемый объект его элементом «Выбрать/Переместить» @msg a path inside a compound path, blend, envelope, repeat or Intertwine group can't take objects к контуру внутри составного контура, перехода, оболочки, повтора или группы переплетения нельзя прикрепить объекты @msg a clipping path can't take objects к контуру обрезки нельзя прикрепить объекты @msg objects inside a blend, envelope, repeat or Intertwine group can't be attached to a path объекты внутри перехода, оболочки, повтора или группы переплетения нельзя прикрепить к контуру diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 9271ac4bac..9b6017228b 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -1550,6 +1550,8 @@ font-technology Variable Variabla Objects on Path Tool Verktyg för objekt på bana Attach Objects on Path Fäst objekt på bana Expand Objects on Path Expandera objekt på bana + Detach Lossa + Detach Object from Path Lossa objekt från bana Release Live Paint Släpp direktmålning Release Repeat Släpp upprepning Release Slice Släpp skiva @@ -6019,6 +6021,7 @@ theme Appearance Utseende @msg no bound object reports a value (locked objects and embedded images report none) inget bundet objekt rapporterar ett värde (låsta objekt och inbäddade bilder rapporterar inget) @msg select an Intertwine group markera en sammanflätningsgrupp @msg select an Objects on Path group markera en grupp med objekt på bana +@msg choose the object to detach with its Select/Move widget välj objektet som ska lossas med dess Markera/Flytta-reglage @msg a path inside a compound path, blend, envelope, repeat or Intertwine group can't take objects en bana inuti en sammansatt bana, en blandning, ett kuvert, en upprepning eller en sammanflätningsgrupp kan inte ta emot objekt @msg a clipping path can't take objects en klippbana kan inte ta emot objekt @msg objects inside a blend, envelope, repeat or Intertwine group can't be attached to a path objekt inuti en blandning, ett kuvert, en upprepning eller en sammanflätningsgrupp kan inte fästas på en bana diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 605ff0382b..2ee4080c81 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -184,6 +184,23 @@ fn font_height_reference_labels_are_in_complete_catalogs() { } } +/// The Objects on Path Options section's Detach button, its undo step and the message for a +/// Detach with no object chosen. +#[test] +fn objects_on_path_detach_strings_are_in_complete_catalogs() { + for lang in LANGUAGES.iter().filter(|lang| lang.complete_menus) { + for label in ["Detach", "Detach Object from Path"] { + assert!(lang.catalog().plain(label).is_some(), "{} is missing {label}", lang.code); + } + } + let choose = "choose the object to detach with its Select/Move widget"; + assert!(message_literals().contains(choose)); + for code in COMPLETE_MESSAGES { + let lang = Lang::from_code(code).expect("registered"); + assert_ne!(message(lang, choose), choose, "{code}"); + } +} + /// The Window › Brush Libraries menu, built from the built-in library table, names each library. #[test] fn built_in_brush_library_names_are_in_complete_catalogs() { diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 107f30f3ea..b2cc8e18cb 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -5977,6 +5977,7 @@ theme Appearance Görünüm @msg nothing in data set {name} was applied: no object is bound to a variable it has a value for {name} veri kümesinden hiçbir şey uygulanmadı: değer içerdiği bir değişkene bağlı hiçbir nesne yok @msg no bound object reports a value (locked objects and embedded images report none) bağlı hiçbir nesne bir değer bildirmiyor (kilitli nesneler ve gömülü görüntüler değer bildirmez) @msg select an Objects on Path group bir Yol Üzerindeki Nesneler grubu seçin +@msg choose the object to detach with its Select/Move widget ayrılacak nesneyi Seç/Taşı denetimiyle seçin @msg the Simplify slider is not open Basitleştirme kaydırıcısı açık değil @msg the Smooth slider is not open Düzgünleştirme kaydırıcısı açık değil @msg {_1} is an exporter (File › Export › Export As…) {_1} bir dışa aktarma eklentisidir (Dosya › Dışa Aktar › Farklı Dışa Aktar…) @@ -6009,6 +6010,8 @@ theme Appearance Görünüm Chrome Krom Chrome… Krom… Expand Objects on Path Yol Üzerindeki Nesneleri Genişlet + Detach Ayır + Detach Object from Path Nesneyi Yoldan Ayır Graphic Pen Grafik Kalemi Graphic Pen… Grafik Kalemi… Move Anchor Point Bağlantı Noktasını Taşı diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 68aabf0253..7a51c3a074 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -1617,6 +1617,8 @@ file-filter Templates Шаблони Objects on Path Tool Інструмент «Об’єкти на контурі» Attach Objects on Path Прикріпити об’єкти до контуру Expand Objects on Path Розібрати об’єкти на контурі + Detach Відкріпити + Detach Object from Path Відкріпити об’єкт від контуру Release Live Paint Звільнити швидку заливку Release Repeat Звільнити повтор Release Slice Звільнити фрагмент @@ -4818,6 +4820,7 @@ axis Both Обидві @msg select a repeat виділіть повтор @msg select an Intertwine group виділіть групу переплетення @msg select an Objects on Path group виділіть групу об’єктів на контурі +@msg choose the object to detach with its Select/Move widget виберіть об’єкт для відкріплення його елементом «Вибрати/Перемістити» @msg a path inside a compound path, blend, envelope, repeat or Intertwine group can't take objects до контуру всередині складеного контуру, переходу, оболонки, повтору або групи переплетення не можна прикріпити об’єкти @msg a clipping path can't take objects до відсічного контуру не можна прикріпити об’єкти @msg objects inside a blend, envelope, repeat or Intertwine group can't be attached to a path об’єкти всередині переходу, оболонки, повтору або групи переплетення не можна прикріпити до контуру diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 36793e6c56..e79a56d178 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -1847,6 +1847,8 @@ digits Hindi Hindi Objects on Path Tool Công cụ Đối tượng trên đường dẫn Attach Objects on Path Gắn đối tượng lên đường dẫn Expand Objects on Path Mở rộng đối tượng trên đường dẫn + Detach Tách + Detach Object from Path Tách đối tượng khỏi đường dẫn Release Live Paint Giải phóng tô trực tiếp Release Repeat Giải phóng lặp lại Release Slice Giải phóng lát cắt @@ -5202,6 +5204,7 @@ theme Appearance Giao diện @msg select a repeat hãy chọn một đối tượng lặp @msg select an Intertwine group hãy chọn một nhóm đan xen @msg select an Objects on Path group hãy chọn một nhóm đối tượng trên đường dẫn +@msg choose the object to detach with its Select/Move widget hãy chọn đối tượng cần tách bằng tiện ích Chọn/Di chuyển của nó @msg a path inside a compound path, blend, envelope, repeat or Intertwine group can't take objects không thể gắn đối tượng lên một đường dẫn nằm trong đường dẫn phức, đối tượng hòa trộn, Envelope, đối tượng lặp hoặc nhóm đan xen @msg a clipping path can't take objects không thể gắn đối tượng lên đường dẫn cắt @msg objects inside a blend, envelope, repeat or Intertwine group can't be attached to a path không thể gắn các đối tượng nằm trong đối tượng hòa trộn, Envelope, đối tượng lặp hoặc nhóm đan xen lên đường dẫn diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 27cad80b4a..ac09988981 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -1543,6 +1543,8 @@ file-filter Templates 模板 Objects on Path Tool 路径上的对象工具 Attach Objects on Path 附加路径上的对象 Expand Objects on Path 扩展路径上的对象 + Detach 分离 + Detach Object from Path 将对象从路径分离 Release Live Paint 释放实时上色 Release Repeat 释放重复 Release Slice 释放切片 @@ -4259,6 +4261,7 @@ imageTrace Outline 轮廓 @msg select a repeat 请选择一个重复对象 @msg select an Intertwine group 请选择一个交织组 @msg select an Objects on Path group 请选择一个路径上的对象组 +@msg choose the object to detach with its Select/Move widget 请用对象的“选择/移动”控件选择要分离的对象 @msg a path inside a compound path, blend, envelope, repeat or Intertwine group can't take objects 复合路径、混合对象、封套、重复对象或交织组中的路径无法附加对象 @msg a clipping path can't take objects 剪切路径无法附加对象 @msg objects inside a blend, envelope, repeat or Intertwine group can't be attached to a path 混合对象、封套、重复对象或交织组中的对象无法附加到路径 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index ab1fd359cd..7c45de741c 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -1588,6 +1588,8 @@ file-filter Templates 範本 Objects on Path Tool 路徑上的物件工具 Attach Objects on Path 附加路徑上的物件 Expand Objects on Path 展開路徑上的物件 + Detach 分離 + Detach Object from Path 將物件從路徑分離 Release Live Paint 釋放即時上色 Release Repeat 釋放重複 Release Slice 釋放切片 @@ -2021,6 +2023,7 @@ file-filter Templates 範本 @msg select a repeat 請選取重複物件 @msg select an Intertwine group 請選取交織群組 @msg select an Objects on Path group 請選取路徑上的物件群組 +@msg choose the object to detach with its Select/Move widget 請用物件的「選取/移動」控制項選取要分離的物件 @msg a path inside a compound path, blend, envelope, repeat or Intertwine group can't take objects 複合路徑、漸變物件、封套、重複物件或交織群組中的路徑無法附加物件 @msg a clipping path can't take objects 剪裁路徑無法附加物件 @msg objects inside a blend, envelope, repeat or Intertwine group can't be attached to a path 漸變物件、封套、重複物件或交織群組中的物件無法附加到路徑 diff --git a/crates/ui-egui/src/panels/properties.rs b/crates/ui-egui/src/panels/properties.rs index 07b53cc6d8..6195de4b24 100644 --- a/crates/ui-egui/src/panels/properties.rs +++ b/crates/ui-egui/src/panels/properties.rs @@ -389,12 +389,15 @@ fn trace_section(app: &mut VectorcraftApp, ui: &mut Ui, preset: &str, view: vect }); } -/// The Objects on Path groups selected with nothing else: their ids, and the Pivot and Rotate they -/// share (`None` where they differ). +/// The Objects on Path groups selected with nothing else: their ids, the Pivot and Rotate they +/// share (`None` where they differ), and whether Detach can take an object off the path: one group, +/// neither hidden nor locked, with an object chosen with its Select/Move widget that is neither +/// hidden nor locked. struct ObjectsOnPathSelection { ids: Vec, pivot: Option, rotate: Option, + detachable: bool, } /// The selection as Objects on Path groups ([`ObjectsOnPathSelection`]), when every selected @@ -405,7 +408,11 @@ fn selected_objects_on_path(app: &VectorcraftApp) -> Option out = Some(ObjectsOnPathSelection { ids: vec![id.0], pivot: Some(rec.pivot), rotate: Some(rec.rotate) }), + None => { + let chosen = st.selection.on_path_member.filter(|m| st.selection.objects.len() == 1 && rec.members.iter().any(|x| x.id == *m)); + let detachable = chosen.is_some_and(|m| st.doc.is_editable(*id) && st.doc.is_editable(m)); + out = Some(ObjectsOnPathSelection { ids: vec![id.0], pivot: Some(rec.pivot), rotate: Some(rec.rotate), detachable }); + } Some(s) => { s.ids.push(id.0); if s.pivot != Some(rec.pivot) { @@ -425,7 +432,8 @@ fn selected_objects_on_path(app: &VectorcraftApp) -> Option). A change goes to every /// selected group in one undo step (`object.objectsOnPath.options`). Where the groups differ, no -/// Pivot square is chosen and Rotate is blank. +/// Pivot square is chosen and Rotate is blank. Detach takes the object chosen with its Select/Move +/// widget off the path (`object.objectsOnPath.detach`), and is dimmed until one is chosen. fn objects_on_path_section(app: &mut VectorcraftApp, ui: &mut Ui, oop: &ObjectsOnPathSelection) { section_header(ui, tl!("Objects on Path Options")); let fw = super::field_width(ui); @@ -452,6 +460,12 @@ fn objects_on_path_section(app: &mut VectorcraftApp, ui: &mut Ui, oop: &ObjectsO } ui.end_row(); }); + let w = ui.available_width(); + if ui.add_enabled_ui(oop.detachable, |ui| widgets::flat_button(ui, tl!("Detach"), w)).inner.clicked() + && let Err(e) = app.run("object.objectsOnPath.detach", json!({})) + { + app.status(e); + } } /// Whether the selection uses more than one colour (`recolor.colors`), which offers the Recolor diff --git a/crates/ui-egui/src/panels/properties/tests.rs b/crates/ui-egui/src/panels/properties/tests.rs index 5ed020c326..9300619765 100644 --- a/crates/ui-egui/src/panels/properties/tests.rs +++ b/crates/ui-egui/src/panels/properties/tests.rs @@ -1879,6 +1879,39 @@ fn objects_on_path_options_set_pivot_and_rotate_in_one_undo_step() { assert_eq!(undo_depth(&app), depth + 1, "one undo step for both groups"); } +/// The objects of the Objects on Path group `id`, in their order along the path. +fn on_path(app: &VectorcraftApp, id: &Value) -> Vec { + let d = &app.session.active().unwrap().doc; + let rec = d.node(vectorcraft_doc::NodeId(id.as_u64().unwrap())).unwrap().extras().objects_on_path.as_deref().unwrap(); + rec.members.iter().map(|m| m.id.0).collect() +} + +/// The help page's Detach in the Objects on Path Options section takes the object chosen with its +/// Select/Move widget off the path in one undo step and selects it. It is dimmed, and a click does +/// nothing, until one group is selected with an object chosen. +#[test] +fn detach_takes_the_chosen_object_off_the_path() { + let (mut app, ctx) = reference_setup(&[]); + let group = objects_on_path(&mut app, 150.0, 0.0); + let [first, second] = on_path(&app, &group)[..] else { panic!("two objects") }; + assert!(shows(&panel_frame(&mut app, &ctx, vec![], objects_on_path_options), "Detach")); + let depth = undo_depth(&app); + click_named(&mut app, &ctx, objects_on_path_options, "Detach"); + assert_eq!((on_path(&app, &group), undo_depth(&app)), (vec![first, second], depth), "no object chosen: dimmed"); + let other = objects_on_path(&mut app, 250.0, 0.0); + app.run("object.objectsOnPath.selectMember", json!({"member": first})).unwrap(); + app.run("select.add", json!({"ids": [other]})).unwrap(); + click_named(&mut app, &ctx, objects_on_path_options, "Detach"); + assert_eq!(on_path(&app, &group), [first, second], "two groups: dimmed"); + app.run("object.objectsOnPath.selectMember", json!({"member": first})).unwrap(); + let depth = undo_depth(&app); + click_named(&mut app, &ctx, objects_on_path_options, "Detach"); + assert_eq!(on_path(&app, &group), [second]); + assert_eq!(undo_depth(&app), depth + 1, "one undo step"); + let sel = &app.session.active().unwrap().selection; + assert_eq!((sel.objects.iter().map(|i| i.0).collect::>(), sel.on_path_member), (vec![first], None)); +} + /// #3759: with area type selected, the Properties panel's Paragraph section shows Align Top, Align /// Center, Align Bottom and Justify Vertically; a click sets the alignment on every selected frame /// in one undo step. Point type shows none; frames with rows or columns and threaded frames turn diff --git a/docs/mcp.md b/docs/mcp.md index 41e28969f4..51816c1a46 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -9896,11 +9896,26 @@ order along the path changes: Space, the start, Pivot, Rotate and the children's new place along the path counted from 0. `object.objectsOnPath.selectMember {member}` takes the same kind of `member` and returns `{group, member}`. +`object.objectsOnPath.detach {member?}` takes one object off the path: `member`, or without it the object chosen with +the Select/Move widget of the one selected group (otherwise it fails with "choose the object to detach with its +Select/Move widget"). `member` takes the same kind of object as `moveMember`, and neither it nor the group may be +hidden or locked. The object leaves the group and goes just above it in the group's layer or group, staying where it +is drawn, and becomes the selection; when the group is itself an object on another group's path, the object goes just +above that outer group, so it does not join its path. The objects after it move up the path in their order: with Auto Space they spread +evenly again (on an open path the first and last on its ends while two or more are left), and a Space value and the +start are kept, drawn as close as the path has room for. Hidden and locked objects left in the group move up too. The +group, its path and its options stay even with one object or none left, and an object moved back into it joins the +path. It is one undo step, and undo puts the object back on the path with the choice it had. It returns +`{group, member}`. In the desktop app, Detach in the Properties panel's Objects on Path Options section sends it, and +is dimmed until one group is selected with an object chosen. To take several objects off at once, drag their rows out +of the group in the Layers panel (`layer.move`). + ```json {"name":"run_command","arguments":{"command":"tool.setOption","params":{"tool":"objectsOnPath","values":{"pivot":7,"rotate":30}}}} {"name":"run_command","arguments":{"command":"object.objectsOnPath.attach","params":{"path":30,"ids":[12,15,18]}}} {"name":"run_command","arguments":{"command":"object.objectsOnPath.options","params":{"pivot":7,"rotate":15}}} {"name":"run_command","arguments":{"command":"object.objectsOnPath.options","params":{"spacing":24,"start":0}}} +{"name":"run_command","arguments":{"command":"object.objectsOnPath.detach","params":{"member":15}}} {"name":"run_command","arguments":{"command":"object.objectsOnPath.expand","params":{}}} ``` diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index d9783b0216..c145a7fb7b 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1367,10 +1367,11 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Window › Blend opens the Blend panel: Make, the selected blend's Spacing and Orientation (with no blend selected, the options new blends start with), Reverse Front to Back, Reverse Spine, Replace Spine, Expand and Release, each running its Object › Blend command. Make is dimmed until two or more objects are selected. Spacing and Orientation are dimmed until a blend or two or more objects are selected, and the other buttons are dimmed until a blend is selected. The Blend panel's Create Spine menu (Auto, Always, Never; `object.blend.createSpine`) sets whether new blends get a spine, from the Blend tool, Make and `object.blend.make` alike ([Blend panel overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/apply-transparency-and-blending/blend-panel-overview.html)). Auto and Always give every new blend a straight spine, as before; Never makes blends without one, which keep their steps on the straight lines between the keys, have Type and Ramp dimmed, refuse Reverse Spine and spine edits, release without a spine path, and get a spine from Replace Spine. The setting is kept with the preferences and leaves blends already made as they are; Auto as the starting value and keeping the setting across sessions are VectorCraft's own rules. Builds on #5177 by adambelis. Evidence: `tests::blendopts::{create_spine_sets_whether_new_blends_get_a_spine, a_blend_without_a_spine_has_none_to_edit_reverse_ease_or_release, whether_a_blend_has_a_spine_is_saved_and_old_blends_have_one}` and `panels::tests_blend::create_spine_sets_what_new_blends_get_whatever_is_selected`. With the Blend tool, Escape drops the object clicked first and stops the next click adding to the blend just made, so the next click picks a new first object; the document and the selection stay as they are. Regression tests: `escape_drops_the_blend_tools_first_pick` in `meshblend.rs` and `tests/blendopts.rs`. - Objects on Path (#2545): a click with the Objects on Path tool (in Edit Toolbar's Modify section and the Blend tool's flyout; Object › Objects on Path › Attach and the context menu with two or more objects selected choose it) attaches the selected objects to the path clicked, open or closed, in an Objects on Path group with the path at its bottom. The objects go along the path column by column from left to right, spread evenly from its first anchor (the last one sits on the end of an open path), each turned to the path at its attachment point; Pivot and Rotate set where each one attaches and how far it tilts (`object.objectsOnPath.attach`, `object.objectsOnPath.options`), and with Objects on Path groups selected the Properties panel's Objects on Path Options section shows them as a nine-point Pivot grid and a Rotate field with common angles, each change one undo step for every selected group. Editing the path moves the objects, an object moved on its own goes back, objects moved into or out of the group in the Layers panel join or leave the path, and Object › Objects on Path › Expand leaves a plain group. The group saves and reopens live and exports as plain art. With one Objects on Path group selected, the Selection and Objects on Path tools show the Rotate All widget beside its first object: dragging it turns every object about its attachment point by the angle the pointer turns, adding it to the group's Rotate in one undo step, in 15° steps with Shift ([Objects on Path](https://helpx.adobe.com/illustrator/using/objects-on-path.html)). Detach is missing. + Objects on Path (#2545): a click with the Objects on Path tool (in Edit Toolbar's Modify section and the Blend tool's flyout; Object › Objects on Path › Attach and the context menu with two or more objects selected choose it) attaches the selected objects to the path clicked, open or closed, in an Objects on Path group with the path at its bottom. The objects go along the path column by column from left to right, spread evenly from its first anchor (the last one sits on the end of an open path), each turned to the path at its attachment point; Pivot and Rotate set where each one attaches and how far it tilts (`object.objectsOnPath.attach`, `object.objectsOnPath.options`), and with Objects on Path groups selected the Properties panel's Objects on Path Options section shows them as a nine-point Pivot grid and a Rotate field with common angles, each change one undo step for every selected group. Editing the path moves the objects, an object moved on its own goes back, objects moved into or out of the group in the Layers panel join or leave the path, and Object › Objects on Path › Expand leaves a plain group. The group saves and reopens live and exports as plain art. With one Objects on Path group selected, the Selection and Objects on Path tools show the Rotate All widget beside its first object: dragging it turns every object about its attachment point by the angle the pointer turns, adding it to the group's Rotate in one undo step, in 15° steps with Shift ([Objects on Path](https://helpx.adobe.com/illustrator/using/objects-on-path.html)). Detach is in its own entry below. Objects on Path Space widget: with one Objects on Path group of two or more objects selected, the Selection and Objects on Path tools show a square handle beyond its last object; dragging it along the path, round its bends, sets the distance between the objects' attachment points in one undo step, the first object staying where it is, and with Alt (Option on macOS) the objects spread from both ends toward the center; the distance shows next to the pointer during the drag, in the document's units ([Rearrange and edit objects on a path](https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/rearrange-and-edit-objects-on-a-path.html), [Objects on Path](https://helpx.adobe.com/illustrator/using/objects-on-path.html)). The group keeps the distance (`object.objectsOnPath.options {spacing, start}`) through Pivot and Rotate changes, path edits, copies, saving and reopening, and scales it with the group; by default (`"auto"`) the objects are spread evenly as before. Evidence: `objects_on_path::tests::{space_sets_the_distance_between_the_stops, space_on_a_closed_path_wraps_at_the_first_anchor_and_stops_short_of_the_first_object}` in `crates/doc`, `tests::objects_on_path::space_sets_the_distance_between_the_objects_in_one_undo_step` in `crates/engine`, `objects_on_path::tests::dragging_the_space_widget_spaces_the_objects_from_the_first_one` in `crates/tools`. Objects on Path Move All widget: with one Objects on Path group selected whose objects have room to move, the Selection and Objects on Path tools show a diamond below its first object; dragging it along the path, round its bends, moves every object along the path together in one undo step, keeping the distances between them (`object.objectsOnPath.options {start}`). On an open path the widget shows only when the distance from the first object to the last is shorter than the path, so not for objects spread evenly from end to end, and the objects stop at the path's ends; on a closed path they go on round across its first anchor. The first object's distance along the path shows next to the pointer during the drag, in the document's units ([Rearrange and edit objects on a path](https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/rearrange-and-edit-objects-on-a-path.html), [Objects on Path](https://helpx.adobe.com/illustrator/using/objects-on-path.html)). Evidence: `objects_on_path::tests::{dragging_the_move_all_widget_moves_every_object_along_the_path, a_move_all_drag_on_a_closed_path_goes_round_across_the_first_anchor}` in `crates/tools`, `canvas::tests::a_selected_objects_on_path_group_shows_its_move_all_widget_when_it_has_room` in `crates/ui-egui`. Objects on Path Select/Move widget: with one Objects on Path group selected, the Selection and Objects on Path tools show a small ring on each object's attachment point, highlighted under the pointer. A click on one chooses that object and fills its ring blue while the group stays selected (`object.objectsOnPath.selectMember`); a click on the object's art still selects the group. Dragging a ring along the path moves its object to the object's place nearest the pointer, and the objects between move one place toward where it was, in one undo step (`object.objectsOnPath.moveMember`); hidden and locked objects keep their places; only the order along the path changes, not the Layers panel's order or the Space. On an open path the drag stops at the ends, on a closed path it goes on round across the first anchor, and Escape cancels it ([Rearrange and edit objects on a path](https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/rearrange-and-edit-objects-on-a-path.html), [Objects on Path](https://helpx.adobe.com/illustrator/using/objects-on-path.html)). Evidence: `objects_on_path::tests::moving_an_object_shifts_the_ones_between_it_and_its_new_place` in `crates/doc`, `tests::objects_on_path::move_member_takes_the_target_s_place_and_shifts_the_objects_between` in `crates/engine`, `objects_on_path::tests::{dragging_a_select_move_widget_moves_its_object_to_the_nearest_place, a_select_move_drag_goes_round_a_closed_path_across_its_first_anchor}` in `crates/tools`, `canvas::tests::a_selected_objects_on_path_group_shows_a_select_move_widget_per_object` in `crates/ui-egui`. + Objects on Path Detach: with one Objects on Path group selected and an object chosen with its Select/Move widget, Detach in the Properties panel's Objects on Path Options section takes that one object off the path (`object.objectsOnPath.detach`), and the objects after it move up the path in their order: with Auto Space they spread evenly again, the ends of an open path staying occupied while two or more are left, and a Space value is kept ([Objects on Path](https://helpx.adobe.com/illustrator/using/objects-on-path.html), [Rearrange and edit objects on a path](https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/rearrange-and-edit-objects-on-a-path.html)). Detach is dimmed until an object is chosen. VectorCraft's own rules: the object stays where it is drawn, goes just above the group in the Layers panel and is selected alone; the start is kept; the group and its path stay with one object or none left; a hidden or locked object or group is not detached; and Detach is one undo step. Several objects still leave together by dragging their rows out of the group in the Layers panel. Evidence: `tests::objects_on_path::{detach_takes_the_chosen_object_off_the_path_and_the_others_move_up_in_one_undo_step, after_the_first_object_is_detached_the_second_takes_the_start, detach_on_a_closed_path_spreads_the_others_all_the_way_round_again, detach_keeps_a_space_value_and_the_start, the_group_and_its_path_stay_with_one_object_or_none_left, an_object_detached_from_a_group_on_another_path_does_not_join_that_path, detach_refuses_what_is_not_one_chosen_editable_object_on_a_path}` in `crates/engine`, `panels::properties::tests::detach_takes_the_chosen_object_off_the_path` in `crates/ui-egui`. Double-clicking the Objects on Path tool opens Objects on Path Tool Options ([Objects on Path](https://helpx.adobe.com/illustrator/using/objects-on-path.html)): the nine-point Pivot grid and the Rotate field set the attachment point and angle of the objects attached next, and groups already attached keep theirs; Reset puts the center and 0° back. Save keeps the options across tool switches and saves them with the preferences (`tool.setOption {tool: "objectsOnPath"}`). - **Paint and appearance (M3):** - **CSS swatch libraries:** fractional linear and radial gradient stop positions are preserved, so nearby stops such as 12.5% and 12.890625% remain distinct instead of collapsing to 13%. Reference: [CSS Images 3 color stops](https://www.w3.org/TR/css-images-3/#color-stop-syntax). The original synthetic regression is `palette_io::tests::css_preserves_fractional_gradient_stop_positions` in `crates/color/src/palette_io.rs`. Scores and hours are unchanged. From 5f45e3910823cad4c1cc67ca42e64f153a554db5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 07:58:15 -0800 Subject: [PATCH 16/25] Area type: Inset Spacing on a shaped frame is measured from the frame's edge On a shaped frame, Inset Spacing keeps text that far from the frame's edge, measured from the edge itself rather than along the line. Before, the inset was trimmed from each end of a line after the frame's edge was found, so on a sloped edge the text came closer than the inset: a triangle (0,0), (100,0), (0,100) with a 10 pt inset gave the band 40..60 the span 10..30, where a 10 pt clearance gives 10..25.86. Holes keep the same clearance. A rectangular frame keeps its inset from each side as before, a column's inner edges keep it once, and the gap kept beside a wrap object along the line is unchanged. --- crates/text/src/layout/region.rs | 161 ++++++++++++++++++++++++++++++- docs/target-app-parity.md | 1 + 2 files changed, 159 insertions(+), 3 deletions(-) diff --git a/crates/text/src/layout/region.rs b/crates/text/src/layout/region.rs index 9303d4c0fb..6272e54d71 100644 --- a/crates/text/src/layout/region.rs +++ b/crates/text/src/layout/region.rs @@ -73,6 +73,52 @@ fn poly_intervals(polys: &[Vec], y: f64) -> Vec<(f64, f64)> { xs.as_chunks::<2>().0.iter().map(|c| (c[0], c[1])).collect() } +/// The part of the horizontal line at `y` closer than `r` to the segment `a`–`b`: the line's +/// intersection with the segment's two end disks and the band between them, which together make +/// a convex shape, so the result is one interval. +fn near_segment(a: Point, b: Point, y: f64, r: f64) -> Option<(f64, f64)> { + if y <= a.y.min(b.y) - r || y >= a.y.max(b.y) + r { + return None; + } + let (mut lo, mut hi) = (f64::INFINITY, f64::NEG_INFINITY); + for p in [a, b] { + let h = r * r - (y - p.y) * (y - p.y); + if h > 0.0 { + lo = lo.min(p.x - h.sqrt()); + hi = hi.max(p.x + h.sqrt()); + } + } + let d = b - a; + let len = d.hypot(); + if len > 0.0 { + let n = kurbo::Vec2::new(-d.y, d.x) * (r / len); + let band = [a + n, b + n, b - n, a - n]; + for i in 0..4 { + let (p, q) = (band[i], band[(i + 1) % 4]); + if (p.y <= y) != (q.y <= y) { + let x = p.x + (y - p.y) / (q.y - p.y) * (q.x - p.x); + lo = lo.min(x); + hi = hi.max(x); + } + } + } + (hi > lo).then_some((lo, hi)) +} + +/// Inside intervals (even-odd) of the horizontal line at `y` through `polys`, less the points +/// closer than `inset` to any edge of them (holes included), measured from the edge itself. +fn inset_intervals(polys: &[Vec], y: f64, inset: f64) -> Vec<(f64, f64)> { + let iv = poly_intervals(polys, y); + if inset <= 0.0 || iv.is_empty() { + return iv; + } + if !inset.is_finite() { + return vec![]; + } + let near = polys.iter().flat_map(|p| (0..p.len()).filter_map(move |i| near_segment(p[i], p[(i + 1) % p.len()], y, inset))); + subtract_intervals(&iv, &union_intervals(near.collect())) +} + /// Union of sorted-or-not intervals. fn union_intervals(mut v: Vec<(f64, f64)>) -> Vec<(f64, f64)> { v.sort_by(|a, b| a.0.total_cmp(&b.0)); @@ -168,12 +214,22 @@ impl Region { /// Inside intervals (even-odd) of the horizontal line at `y`, minus the wrap objects (or /// inside them, for Invert Wrap). Offsets grow each wrap shape vertically and horizontally. + /// On a shaped frame the intervals keep the inset from the frame's edges, measured from the + /// edge itself. Along the line, the text also keeps the inset beside each wrap object (outside + /// it, or inside it for Invert Wrap); above and below a wrap object only its offset applies. fn intervals(&self, y: f64) -> Vec<(f64, f64)> { - let mut iv = if self.polys.is_empty() || self.rect { vec![(self.cell.x0, self.cell.x1)] } else { poly_intervals(&self.polys, y) }; + let mut iv = + if self.polys.is_empty() || self.rect { vec![(self.cell.x0, self.cell.x1)] } else { inset_intervals(&self.polys, y, self.inset) }; for (polys, off, invert) in self.wraps.iter() { let ys = if *off > 0.0 { vec![y - off, y - off * 0.5, y, y + off * 0.5, y + off] } else { vec![y] }; let w = union_intervals(ys.into_iter().flat_map(|y| poly_intervals(polys, y)).map(|(a, b)| (a - off, b + off)).collect()); - iv = if *invert { intersect_intervals(&iv, &w) } else { subtract_intervals(&iv, &w) }; + iv = if *invert { + let w: Vec<_> = w.into_iter().map(|(a, b)| (a + self.inset, b - self.inset)).filter(|(a, b)| b > a).collect(); + intersect_intervals(&iv, &w) + } else { + let w = union_intervals(w.into_iter().map(|(a, b)| (a - self.inset, b + self.inset)).collect()); + subtract_intervals(&iv, &w) + }; } iv } @@ -186,8 +242,10 @@ impl Region { /// Every horizontal span inside the frame (and the cell) over the band `top..bottom`, left to /// right (text wraps on both sides of an object). pub(super) fn spans(&self, top: f64, bottom: f64) -> Vec<(f64, f64)> { + // The inset from the cell's edges; `intervals` already keeps it from the frame's edges and + // beside the wrap objects. let clip = |(a, b): (f64, f64)| { - let (a, b) = (a.max(self.cell.x0) + self.inset, b.min(self.cell.x1) - self.inset); + let (a, b) = (a.max(self.cell.x0 + self.inset), b.min(self.cell.x1 - self.inset)); (b > a).then_some((a, b)) }; let plain = self.polys.is_empty() || self.rect; @@ -238,3 +296,100 @@ fn the_cells_of_a_frame_share_its_polygons_and_the_wrap_shapes() { assert!(!first.polys.is_empty() && !first.wraps.is_empty()); assert!(cells.iter().all(|c| c.polys.as_ptr() == first.polys.as_ptr() && c.wraps.as_ptr() == first.wraps.as_ptr())); } + +/// A path with one closed subpath through each list of points. +#[cfg(test)] +fn closed(subpaths: &[&[(f64, f64)]]) -> BezPath { + let mut path = BezPath::new(); + for pts in subpaths { + path.move_to(pts[0]); + for &p in &pts[1..] { + path.line_to(p); + } + path.close_path(); + } + path +} + +/// The spans of every cell of `path` over the band `top..bottom`. +#[cfg(test)] +fn cell_spans(path: &BezPath, opts: &LayoutOptions, wrap: &[vectorcraft_doc::WrapShape], top: f64, bottom: f64) -> Vec> { + Region::cells(path, opts, wrap).iter().map(|c| c.spans(top, bottom)).collect() +} + +#[cfg(test)] +fn assert_spans(got: &[(f64, f64)], want: &[(f64, f64)]) { + assert_eq!(got.len(), want.len(), "{got:?} != {want:?}"); + for (g, w) in got.iter().zip(want) { + assert!((g.0 - w.0).abs() < 1e-6 && (g.1 - w.1).abs() < 1e-6, "{got:?} != {want:?}"); + } +} + +/// On a triangle, the inset keeps the line 10 pt from the sloped edge, measured from the edge +/// itself (x + y <= 100 - 10√2 at the band's bottom), not 10 pt along the line. +#[cfg(test)] +#[test] +fn inset_on_a_shaped_frame_is_measured_from_its_sloped_edge() { + let triangle = closed(&[&[(0.0, 0.0), (100.0, 0.0), (0.0, 100.0)]]); + let inset = |inset| cell_spans(&triangle, &LayoutOptions { inset, ..LayoutOptions::default() }, &[], 40.0, 60.0); + assert_spans(&inset(10.0)[0], &[(10.0, 40.0 - 10.0 * std::f64::consts::SQRT_2)]); + assert_spans(&inset(0.0)[0], &[(0.0, 40.0)]); +} + +/// A rectangular frame keeps its inset from each side, and its first line starts the inset below +/// its top. +#[cfg(test)] +#[test] +fn a_rectangular_frame_keeps_its_inset_from_each_side() { + let cells = Region::cells(&Rect::new(0.0, 0.0, 100.0, 100.0).to_path(0.1), &LayoutOptions { inset: 10.0, ..LayoutOptions::default() }, &[]); + assert!(cells[0].rect); + assert_eq!((cells[0].top(), cells[0].bottom()), (10.0, 90.0)); + assert_spans(&cells[0].spans(40.0, 60.0), &[(10.0, 90.0)]); +} + +/// The inset keeps text clear of a hole's sloped edges too. +#[cfg(test)] +#[test] +fn inset_keeps_text_clear_of_a_hole_s_sloped_edges() { + let square = [(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)]; + let diamond = [(50.0, 30.0), (70.0, 50.0), (50.0, 70.0), (30.0, 50.0)]; + let spans = cell_spans(&closed(&[&square, &diamond]), &LayoutOptions { inset: 5.0, ..LayoutOptions::default() }, &[], 40.0, 44.0); + let clear = 5.0 * std::f64::consts::SQRT_2; + assert_spans(&spans[0], &[(5.0, 36.0 - clear), (64.0 + clear, 95.0)]); +} + +/// In a frame of columns, the inset is kept once from a column's inner edge and once from the +/// frame's sloped edge. +#[cfg(test)] +#[test] +fn inset_applies_once_at_a_column_s_edge_and_at_the_frame_s_edge() { + let triangle = closed(&[&[(0.0, 0.0), (100.0, 0.0), (0.0, 100.0)]]); + let spans = cell_spans(&triangle, &LayoutOptions { inset: 10.0, columns: 2, gutter: 0.0, ..LayoutOptions::default() }, &[], 10.0, 20.0); + assert_spans(&spans[0], &[(10.0, 40.0)]); + assert_spans(&spans[1], &[(60.0, 80.0 - 10.0 * std::f64::consts::SQRT_2)]); +} + +/// An inset wider than a shaped frame leaves no room for text, whatever its size. +#[cfg(test)] +#[test] +fn an_inset_wider_than_a_shaped_frame_leaves_no_room() { + let triangle = closed(&[&[(0.0, 0.0), (100.0, 0.0), (0.0, 100.0)]]); + for inset in [40.0, 1e300, f64::INFINITY] { + let cells = Region::cells(&triangle, &LayoutOptions { inset, ..LayoutOptions::default() }, &[]); + assert!(cells[0].spans(40.0, 60.0).is_empty() && cells[0].span(40.0, 60.0).is_none(), "inset {inset}"); + } +} + +/// Along the line, text keeps the inset beside a wrap object, around it and, with Invert Wrap, +/// inside it. +#[cfg(test)] +#[test] +fn text_keeps_the_inset_beside_a_wrap_object_along_the_line() { + let frame = Rect::new(0.0, 0.0, 100.0, 100.0).to_path(0.1); + let shape = PathData::from_bezpath(&Rect::new(40.0, 40.0, 60.0, 60.0).to_path(0.1)); + let opts = LayoutOptions { inset: 5.0, ..LayoutOptions::default() }; + for (invert, want) in [(false, vec![(5.0, 35.0), (65.0, 95.0)]), (true, vec![(45.0, 55.0)])] { + let wrap = vectorcraft_doc::WrapShape { path: shape.clone(), wrap: vectorcraft_doc::TextWrap { offset: 0.0, invert } }; + assert_spans(&cell_spans(&frame, &opts, &[wrap], 45.0, 55.0)[0], &want); + } +} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index d9783b0216..e330a8dcbb 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1239,6 +1239,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Paragraph alignment:** the shared Paragraph/Properties alignment row leaves every button unselected when the paragraphs it acts on differ. Auto resolves per paragraph; choosing an alignment uses the existing command. Headless paragraph_mixed_alignment_* regressions exercise mixed → Center → Undo, caret/uniform states, Unicode range boundaries, Auto/direction, split runs and grouped text. These regressions and full integration CI pass. Original captures confirm mixed → Center → Undo in the existing alignment-button layout. The [public Paragraph panel guide](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/paragraph-panel-overview.html) lists the seven controls, but does not specify mixed-state rendering. Other paragraph fields remain outside this change; scores and hours unchanged. For Auto Size area type in columns, the bisection for the frame's height runs on the lines of the one-column layout, and its result is checked with at most two layouts of the columns. When the text wraps around objects or does not fit the one-column layout, or when the check fails, the columns are laid out at every step of the bisection, as before. Typing at the start of a story of 50,000 characters in 2 columns took 1,670 ms a keystroke and now takes 292 ms (release build, `auto_height_in_columns_typing_timing`). Exports to PDF, EPS, SVG, EMF, WMF and the raster formats warn about the area type and type on a path that they draw without the text that doesn't fit, and give their ids, as Print and Print Preview do. + On a shaped area type frame, Inset Spacing keeps text that far from the frame's edge, holes included, measured from the edge itself rather than along the line; the archived help treats the inset as the space an area type object leaves between its text and the path that bounds it (, ). A rectangular frame keeps its inset from each side as before, and a column's inner edges keep it once. Tests: `layout::region::inset_on_a_shaped_frame_is_measured_from_its_sloped_edge`, `inset_keeps_text_clear_of_a_hole_s_sloped_edges`, `inset_applies_once_at_a_column_s_edge_and_at_the_frame_s_edge`. An edit copies a thread's story only when it changes one of the thread's frames: with a story of 50,000 characters threaded through 8 frames with a style change at every word, moving another object took 7.8 ms and now takes 0.013 ms, and a frame of a drag took 7.2 ms and now takes 0.012 ms (release build, `threaded_story_edit_timing`). A paragraph that continues from one threaded frame into the next has its first-line indent and bullet or number in the frame where it starts; in the next frame its first line starts where its wrapped lines start. In frames that are no longer threaded, copies of a frame and point type converted from one, the first paragraph has its indent and bullet or number again. Type › Convert To Point Type on a frame of threaded text makes point type of the text that frame holds and takes it out of the thread; the story flows through the other frames without that text, so each character is in the document once. From 3e53884b7e4716eb932fd8ee4234160477418b2c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 07:58:36 -0800 Subject: [PATCH 17/25] Artwork Cleanup: remove quadratic work from three path repairs Three repairs in crates/pathops/src/addons/cleanup.rs grew with the square of the input. Each now gives the same results as before, bit for bit. - Collinear anchors: removing an anchor called Vec::remove, so a straight run of n anchors took O(n^2) moves. The repair now tests each anchor once against the nearest kept neighbors, with the same test order, neighbors and stop rule, and moves the kept anchors into place once. - Nearly Coincident Anchors (near_point_groups): every pair of anchors in touching grid cells was compared, so a cluster of A anchors cost O(A^2) checks. Groups now grow one anchor at a time and look only at anchors no group has taken, by exact position, skipping quarter-cell squares that lie out of reach. - Rejoin Path Pieces (rejoin): every pair of ends within the gap was listed and sorted, O(P^2 log P) for P pieces meeting at one place. Each end now finds its first partner in the same order (turn, distance, then end order), searching by direction among the ends still free, and two ends that are each other's first partner meet. Tests compare each repair with a copy of the old algorithm on generated and focused inputs, count the work on dense cases (20,000-anchor runs, 4,000-anchor clusters, 2,000 pieces meeting at one point), and check Health Check, Show and Fix on a 5,001-anchor path. --- crates/engine/src/cmd/addons/cleanup/tests.rs | 27 + crates/pathops/src/addons/cleanup.rs | 556 +++++++++++++++--- crates/pathops/src/addons/cleanup/tests.rs | 417 ++++++++++++- 3 files changed, 917 insertions(+), 83 deletions(-) diff --git a/crates/engine/src/cmd/addons/cleanup/tests.rs b/crates/engine/src/cmd/addons/cleanup/tests.rs index b20eb0d59b..1184687366 100644 --- a/crates/engine/src/cmd/addons/cleanup/tests.rs +++ b/crates/engine/src/cmd/addons/cleanup/tests.rs @@ -341,6 +341,33 @@ fn fix_all_is_one_undo_step() { assert_eq!(s.doc().unwrap().doc.artboards.len(), doc.artboards.len()); } +#[test] +fn a_long_straight_run_loses_its_inner_anchors_in_one_step() { + let mut s = session(); + let n: u32 = 5_000; + let mut pts: Vec<(f64, f64)> = (0..n).map(|i| (10.0 + f64::from(i) * 0.05, 150.0)).collect(); + pts.push((260.0, 190.0)); + let id = line(&mut s, &pts); + let other = rect(&mut s, 300.0, 20.0, 40.0, 40.0); + select(&mut s, &[other]); + let check = s.execute("addon.cleanup.check", &json!({"kinds": ["collinearAnchors"], "scope": "document"})).unwrap(); + assert_eq!(check["total"], n - 2, "{check}"); + assert_eq!(check["findings"][0]["ids"], json!([id.0])); + let shown = s.execute("addon.cleanup.show", &json!({"kind": "collinearAnchors", "scope": "document"})).unwrap(); + assert_eq!(shown["count"], n - 2); + assert_eq!(s.doc().unwrap().selection.objects, [id], "Show selects the path"); + select(&mut s, &[other]); + let (steps, before) = (undo_steps(&s), node(&s, id).unwrap()); + let r = s.execute("addon.cleanup.fix", &json!({"kinds": ["collinearAnchors"], "scope": "document"})).unwrap(); + assert_eq!((r["total"].as_u64(), r["fixed"]["collinearAnchors"].as_u64()), (Some(u64::from(n) - 2), Some(u64::from(n) - 2))); + assert_eq!(undo_steps(&s), steps + 1); + assert_eq!(s.doc().unwrap().selection.objects, [other], "Fix keeps the selection"); + let ends: Vec<(f64, f64)> = node(&s, id).unwrap().path_data().unwrap().subpaths[0].anchors.iter().map(|a| (a.p.x, a.p.y)).collect(); + assert_eq!(ends, [(10.0, 150.0), (10.0 + f64::from(n - 1) * 0.05, 150.0), (260.0, 190.0)]); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(node(&s, id).unwrap(), before); +} + #[test] fn the_scope_is_the_selection_or_the_document() { let mut s = session(); diff --git a/crates/pathops/src/addons/cleanup.rs b/crates/pathops/src/addons/cleanup.rs index edb3489007..75cf45b583 100644 --- a/crates/pathops/src/addons/cleanup.rs +++ b/crates/pathops/src/addons/cleanup.rs @@ -3,7 +3,7 @@ //! nearly closed paths; [`near_point_groups`] finds anchors to snap together, and [`rejoin`] welds //! open pieces whose ends meet back into paths. -use std::collections::HashMap; +use std::collections::{BTreeSet, HashMap}; use kurbo::{Point, Vec2}; use vectorcraft_geom::{Anchor, AnchorKind, EPS, SubPath}; @@ -23,24 +23,64 @@ fn moved(p: Point, a_p: Point, h: Point) -> Point { /// Remove the corner anchors (no handles, straight segments both sides) where a straight run goes /// on in the same direction: the sine of the angle it turns there is at most `tolerance`. Open ends /// stay, and a subpath keeps two anchors (three when closed) → how many went. +/// +/// Each anchor is tested once, first to last, against the nearest anchors still kept on either +/// side. On a closed subpath, an anchor with none kept before it has the last anchor as its +/// previous neighbor, and the last anchor has the first one kept as its next neighbor. The kept +/// anchors move into place once at the end, so the work grows linearly with the number of anchors. pub fn remove_collinear_anchors(sp: &mut SubPath, tolerance: f64) -> usize { - let mut removed = 0; - let mut i = 0; - while i < sp.anchors.len() && sp.anchors.len() > min_anchors(sp) { - let n = sp.anchors.len(); - let inner = sp.closed || (i > 0 && i + 1 < n); - let (Some(prev), Some(cur), Some(next)) = (sp.anchors.get((i + n - 1) % n), sp.anchors.get(i), sp.anchors.get((i + 1) % n)) else { break }; + let n = sp.anchors.len(); + let min = min_anchors(sp); + if n <= min { + return 0; + } + let mut keep = vec![true; n]; + let (mut left, mut first_kept, mut last_kept) = (n, None, None); + #[cfg(test)] + let mut work = 0; + for i in 0..n { + if left <= min { + break; + } + #[cfg(test)] + { + work += 1; + } + // Every anchor after `i` is still there, the last one included. + let p = last_kept.unwrap_or(n - 1); + let q = if i + 1 < n { i + 1 } else { first_kept.unwrap_or(i) }; + let inner = sp.closed || (last_kept.is_some() && i + 1 < n); + let (Some(prev), Some(cur), Some(next)) = (sp.anchors.get(p), sp.anchors.get(i), sp.anchors.get(q)) else { break }; let straight = !prev.has_out() && !cur.has_in() && !cur.has_out() && !next.has_in(); let (a, b) = (cur.p - prev.p, next.p - cur.p); let len = a.hypot() * b.hypot(); if inner && straight && len > EPS && a.dot(b) > 0.0 && a.cross(b).abs() / len <= tolerance { - sp.anchors.remove(i); - removed += 1; + if let Some(k) = keep.get_mut(i) { + *k = false; + } + left -= 1; } else { - i += 1; + first_kept.get_or_insert(i); + last_kept = Some(i); } } - removed + if left < n { + let mut kept = keep.iter(); + sp.anchors.retain(|_| kept.next().copied().unwrap_or(true)); + #[cfg(test)] + { + work += n; + } + } + #[cfg(test)] + COLLINEAR_WORK.with(|w| w.set(work)); + n - left +} + +#[cfg(test)] +thread_local! { + /// Anchors tested plus anchors moved by the last [`remove_collinear_anchors`] on this thread. + static COLLINEAR_WORK: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Merge each anchor lying within `distance` of the one before it (and a closed subpath's last @@ -101,58 +141,203 @@ pub fn close_nearly_closed(sp: &mut SubPath, distance: f64) -> bool { true } +/// The cell of a grid of `size`-wide squares that `p` lies in. +fn grid_cell(p: Point, size: f64) -> (i64, i64) { + ((p.x / size).floor() as i64, (p.y / size).floor() as i64) +} + +/// The cell `(x, y)` and the cells around it, each once. +fn around((x, y): (i64, i64)) -> Vec<(i64, i64)> { + let mut out: Vec<(i64, i64)> = [-1, 0, 1].into_iter().flat_map(|dx| [-1, 0, 1].map(|dy| (x.saturating_add(dx), y.saturating_add(dy)))).collect(); + out.sort_unstable(); + out.dedup(); + out +} + +/// The root of `i`'s set in the union-find forest `parent`. +fn root(parent: &mut [usize], mut i: usize) -> usize { + while let Some(&p) = parent.get(i).filter(|&&p| p != i) { + let up = parent.get(p).copied().unwrap_or(p); + if let Some(slot) = parent.get_mut(i) { + *slot = up; + } + i = p; + } + i +} + /// Groups of `points` to snap together: points within `distance` of one another (and so on, one /// to the next) that aren't all at the same place, skipping the pairs `linked` names (such as /// neighbouring anchors of one path). Each group lists its points in order; snapping them all to /// the first one makes them coincide. Non-finite points and a distance that isn't a positive number /// find nothing. +/// +/// Two points are compared when their cells of a `distance`-wide grid touch. Each group grows from +/// one point at a time, which looks only at points no group has taken yet, so a cluster of points +/// all within `distance` of one another is grouped with work that grows linearly with its size. pub fn near_point_groups(points: &[Point], distance: f64, linked: impl Fn(usize, usize) -> bool) -> Vec> { if !(distance > 0.0 && distance.is_finite()) { return vec![]; } - let cell = |p: Point| ((p.x / distance).floor() as i64, (p.y / distance).floor() as i64); - let mut grid: HashMap<(i64, i64), Vec> = HashMap::new(); - for (i, p) in points.iter().enumerate().filter(|(_, p)| p.is_finite()) { - grid.entry(cell(*p)).or_default().push(i); - } - let mut parent: Vec = (0..points.len()).collect(); - fn root(parent: &mut [usize], mut i: usize) -> usize { - while let Some(&p) = parent.get(i).filter(|&&p| p != i) { - let up = parent.get(p).copied().unwrap_or(p); - if let Some(slot) = parent.get_mut(i) { - *slot = up; - } - i = p; + let mut cells = buckets(points, distance); + let mut near = Near { + distance, + linked, + parent: (0..points.len()).collect(), + taken: points.iter().map(|p| !p.is_finite()).collect(), + queue: vec![], + #[cfg(test)] + work: 0, + }; + for (start, &p) in points.iter().enumerate() { + if near.taken.get(start) != Some(&false) { + continue; } - i - } - for (&(cx, cy), members) in &grid { - for (dx, dy) in [(0, 0), (1, 0), (-1, 1), (0, 1), (1, 1)] { - let Some(others) = grid.get(&(cx.saturating_add(dx), cy.saturating_add(dy))) else { continue }; - for &i in members { - for &j in others.iter().filter(|&&j| (dx, dy) != (0, 0) || j > i) { - let (Some(a), Some(b)) = (points.get(i), points.get(j)) else { continue }; - let d = a.distance(*b); - if d <= distance && d > 0.0 && !linked(i.min(j), i.max(j)) { - let (ri, rj) = (root(&mut parent, i), root(&mut parent, j)); - if let Some(slot) = parent.get_mut(ri.max(rj)) { - *slot = ri.min(rj); - } - } - } - } + if let Some(t) = near.taken.get_mut(start) { + *t = true; + } + let mut at = Some((start, p)); + while let Some((i, p)) = at { + near.reach(&mut cells, i, p); + at = near.queue.pop().and_then(|j| Some((j, *points.get(j)?))); } } + #[cfg(test)] + NEAR_WORK.with(|w| w.set(near.work)); // Only pairs that aren't at the same place were joined, so no group is all at one place. let mut groups: HashMap> = HashMap::new(); for i in 0..points.len() { - groups.entry(root(&mut parent, i)).or_default().push(i); + groups.entry(root(&mut near.parent, i)).or_default().push(i); } let mut out: Vec> = groups.into_values().filter(|g| g.len() > 1).collect(); out.sort_unstable(); out } +#[cfg(test)] +thread_local! { + /// Buckets, places and points looked at by the last [`near_point_groups`] on this thread. + static NEAR_WORK: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// The finite points of one cell of a grid that lie in one square a quarter of a cell wide, with +/// the box around them. +struct Bucket { + lo: Point, + hi: Point, + /// Each place (bit for bit) and the points there that no group has taken yet, though some of + /// them may have been taken since. + places: Vec<(Point, Vec)>, +} + +impl Bucket { + /// Whether [`Point::distance`] puts every point here further than `distance` from `p`: one + /// coordinate alone differs by more. The square of a `distance` of 1e-150 or more does not + /// underflow, so the measured distance is at least that difference. + fn beyond(&self, p: Point, distance: f64) -> bool { + distance >= 1e-150 && [self.lo.x - p.x, p.x - self.hi.x, self.lo.y - p.y, p.y - self.hi.y].into_iter().any(|g| g > distance) + } +} + +/// The finite `points` in buckets, by grid cell. +fn buckets(points: &[Point], distance: f64) -> HashMap<(i64, i64), Vec> { + let quarter = distance / 4.0; + let mut cells: HashMap<(i64, i64), Vec> = HashMap::new(); + // Each bucket by its cell and square, and each place by its cell, bucket and coordinates. + let mut bucket_at: HashMap<[i64; 4], usize> = HashMap::new(); + let mut place_at: HashMap<(usize, [i64; 2], [u64; 2]), usize> = HashMap::new(); + for (i, &p) in points.iter().enumerate().filter(|(_, p)| p.is_finite()) { + let c = grid_cell(p, distance); + let list = cells.entry(c).or_default(); + let square = grid_cell(p, quarter); + let b = *bucket_at.entry([c.0, c.1, square.0, square.1]).or_insert_with(|| { + list.push(Bucket { lo: p, hi: p, places: vec![] }); + list.len() - 1 + }); + let Some(bucket) = list.get_mut(b) else { continue }; + bucket.lo = Point::new(bucket.lo.x.min(p.x), bucket.lo.y.min(p.y)); + bucket.hi = Point::new(bucket.hi.x.max(p.x), bucket.hi.y.max(p.y)); + let at = *place_at.entry((b, [c.0, c.1], [p.x.to_bits(), p.y.to_bits()])).or_insert_with(|| { + bucket.places.push((p, vec![])); + bucket.places.len() - 1 + }); + if let Some((_, here)) = bucket.places.get_mut(at) { + here.push(i); + } + } + cells +} + +/// The grouping behind [`near_point_groups`]. +struct Near { + distance: f64, + linked: F, + /// The union-find forest of the groups. + parent: Vec, + /// Whether each point is in a group being grown or grown already (non-finite ones never are). + taken: Vec, + /// Points taken into the group being grown whose own neighbors are still to be looked at. + queue: Vec, + #[cfg(test)] + work: usize, +} + +impl bool> Near { + /// Take into `i`'s group every point no group has taken yet that lies within the distance of + /// `p`, `i`'s place, in the cells around it, at a different place and not linked to `i`. + fn reach(&mut self, cells: &mut HashMap<(i64, i64), Vec>, i: usize, p: Point) { + for c in around(grid_cell(p, self.distance)) { + let Some(buckets) = cells.get_mut(&c) else { continue }; + buckets.retain_mut(|b| { + #[cfg(test)] + { + self.work += 1; + } + if !b.beyond(p, self.distance) { + b.places.retain_mut(|place| { + self.visit(i, p, place); + !place.1.is_empty() + }); + } + !b.places.is_empty() + }); + } + } + + /// Take into `i`'s group the points at `place` that `i` joins, and drop the ones taken. + fn visit(&mut self, i: usize, p: Point, (at, here): &mut (Point, Vec)) { + #[cfg(test)] + { + self.work += 1; + } + let d = p.distance(*at); + if !(d <= self.distance && d > 0.0) { + return; + } + here.retain(|&j| { + if self.taken.get(j) != Some(&false) { + return false; + } + #[cfg(test)] + { + self.work += 1; + } + if (self.linked)(i.min(j), i.max(j)) { + return true; + } + let (ri, rj) = (root(&mut self.parent, i), root(&mut self.parent, j)); + if let Some(slot) = self.parent.get_mut(ri.max(rj)) { + *slot = ri.min(rj); + } + if let Some(t) = self.taken.get_mut(j) { + *t = true; + } + self.queue.push(j); + false + }); + } +} + /// Open pieces welded into one path by [`rejoin`]: `members` index the pieces in the order they /// run along `path`. #[derive(Clone, Debug, PartialEq)] @@ -179,6 +364,12 @@ fn outward(sp: &SubPath, last: bool) -> Option { /// Each junction keeps the earlier piece's anchor and the later piece's out handle. Pieces that are /// closed, have fewer than two anchors or a non-finite coordinate stay out. → the chains of two or /// more pieces, and the single pieces that closed. +/// +/// Two ends are compared when their cells of a `gap`-wide grid touch, and pairs are taken in order +/// of the turn, then the distance, then the order of the ends. Each end looks for its first +/// partner in that order among the ends still free, searching outward from the reverse of its own +/// direction, and two ends that are each other's first partner meet; these are the pairs that +/// taking every pair in that order gives. pub fn rejoin(pieces: &[SubPath], gap: f64) -> Vec { if !(gap >= 0.0 && gap.is_finite()) { return vec![]; @@ -187,7 +378,7 @@ pub fn rejoin(pieces: &[SubPath], gap: f64) -> Vec { !sp.closed && sp.anchors.len() >= 2 && sp.anchors.iter().all(|a| a.p.is_finite() && a.h_in.is_finite() && a.h_out.is_finite()) }; // Each usable end: where it is and the way out of its piece there. - let ends: Vec<(End, Point, Vec2)> = pieces + let ends: Vec = pieces .iter() .enumerate() .filter(|(_, sp)| usable(sp)) @@ -197,49 +388,254 @@ pub fn rejoin(pieces: &[SubPath], gap: f64) -> Vec { Some(((i, last), a.p, outward(sp, last)?)) }) .collect(); - let points: Vec = ends.iter().map(|e| e.1).collect(); - // Every pair of ends within the gap, by the turn across the junction. - let mut pairs: Vec<(f64, f64, End, End)> = vec![]; - for (a, b) in candidate_pairs(&points, gap.max(1e-9)) { - let (Some(&(ea, pa, oa)), Some(&(eb, pb, ob))) = (ends.get(a), ends.get(b)) else { continue }; - // A piece's own two ends meet only when closing it leaves a shape (three anchors). - if ea.0 == eb.0 && pieces.get(ea.0).is_none_or(|sp| sp.anchors.len() < 3) { - continue; - } - let d = pa.distance(pb); - if d <= gap { - pairs.push((oa.dot(-ob).clamp(-1.0, 1.0).acos(), d, ea, eb)); - } - } - pairs.sort_by(|x, y| x.0.total_cmp(&y.0).then(x.1.total_cmp(&y.1))); - let mut link: HashMap = HashMap::new(); - for (_, _, a, b) in pairs { - if !link.contains_key(&a) && !link.contains_key(&b) { - link.insert(a, b); - link.insert(b, a); - } - } + let link = Weld::new(pieces, &ends, gap).link(); chains(pieces, &link) } -/// Pairs (a < b) of `points` that may lie within `gap`: those in neighbouring grid cells. -fn candidate_pairs(points: &[Point], gap: f64) -> Vec<(usize, usize)> { - let cell = |p: Point| ((p.x / gap).floor() as i64, (p.y / gap).floor() as i64); - let mut grid: HashMap<(i64, i64), Vec> = HashMap::new(); - for (i, p) in points.iter().enumerate() { - grid.entry(cell(*p)).or_default().push(i); - } - let mut out = vec![]; - for (i, p) in points.iter().enumerate() { - let (cx, cy) = cell(*p); - for dx in -1..=1 { - for dy in -1..=1 { - let Some(others) = grid.get(&(cx.saturating_add(dx), cy.saturating_add(dy))) else { continue }; - out.extend(others.iter().filter(|&&j| j > i).map(|&j| (i, j))); +/// An end, where it lies and the unit direction pointing out of its piece there. +type EndAt = (End, Point, Vec2); + +/// Where a pair of ends (`a` < `b` in the list of ends) comes in the order [`rejoin`] takes pairs: +/// the turn across the junction, the distance between the ends, `a`, the place of `b`'s grid cell +/// among the cells around `a`'s, and `b`. +type Order = (f64, f64, usize, usize, usize); + +/// Whether pair `x` comes before pair `y`. +fn earlier(x: &Order, y: &Order) -> bool { + x.0.total_cmp(&y.0).then(x.1.total_cmp(&y.1)).then((x.2, x.3, x.4).cmp(&(y.2, y.3, y.4))).is_lt() +} + +/// The place of cell `to` among the cells around `from`, listed by x step and then y step from -1 +/// to 1 (cells past the end of the grid repeat their neighbor; the first place counts). +fn listed_at(from: (i64, i64), to: (i64, i64)) -> usize { + let mut steps = [-1, 0, 1].into_iter().flat_map(|dx| [-1, 0, 1].map(|dy| (from.0.saturating_add(dx), from.1.saturating_add(dy)))); + steps.position(|c| c == to).unwrap_or(9) +} + +/// `angle` as an integer in the same order. +fn angle_key(angle: f64) -> i64 { + let bits = angle.to_bits() as i64; + bits ^ (((bits >> 63) as u64) >> 1) as i64 +} + +/// The angle between the directions at angles `a` and `b`, from 0 to π. +fn apart(a: f64, b: f64) -> f64 { + let d = (a - b).abs(); + d.min(std::f64::consts::TAU - d) +} + +/// How far past the turn of the best pair found so far [`Weld::first_partner`] still looks. The +/// turn [`rejoin`] measures (the arc cosine of a dot product of unit vectors) is within 1e-7 of +/// the angle between the directions, and the angles the search sorts by are within 1e-14 of it. +const TURN_SLACK: f64 = 1e-6; + +/// Ends in one grid cell at one place with one outward direction (bit for bit): every other end +/// pairs with each of them at the same turn and distance. +struct Class { + at: Point, + angle: f64, + /// The ends here no pair has taken yet. + free: BTreeSet, +} + +/// The pairing behind [`rejoin`]. +struct Weld<'a> { + pieces: &'a [SubPath], + ends: &'a [EndAt], + gap: f64, + /// The width of the grid's cells. + size: f64, + classes: Vec, + /// Each end's class. + class_of: Vec, + /// Each grid cell's classes with free ends, by the angle of their direction. + cells: HashMap<(i64, i64), BTreeSet<(i64, usize)>>, + /// Whether each end is still free. + free: Vec, + /// Whether each end has looked for its first partner. Another end's first partner in a class + /// is one of the class's first three free ends, so the ends after those cannot meet next and + /// look only once they move up. + awake: Vec, + /// Each awake end's first partner, and where that pair comes in the order. + first: Vec>, + /// The ends whose first partner each end is (some may have moved on since). + wanted_by: Vec>, + /// Ends to check for a partner whose first partner they are. + todo: Vec, + #[cfg(test)] + work: std::cell::Cell, +} + +impl<'a> Weld<'a> { + fn new(pieces: &'a [SubPath], ends: &'a [EndAt], gap: f64) -> Self { + let size = gap.max(1e-9); + let (mut classes, mut class_of, mut cells) = (vec![], vec![], HashMap::new()); + let mut class_at: HashMap<((i64, i64), [u64; 4]), usize> = HashMap::new(); + for (i, &(_, p, out)) in ends.iter().enumerate() { + let c = grid_cell(p, size); + let k = *class_at.entry((c, [p.x, p.y, out.x, out.y].map(f64::to_bits))).or_insert_with(|| { + let angle = out.y.atan2(out.x); + cells.entry(c).or_insert_with(BTreeSet::new).insert((angle_key(angle), classes.len())); + classes.push(Class { at: p, angle, free: BTreeSet::new() }); + classes.len() - 1 + }); + if let Some(class) = classes.get_mut(k) { + class.free.insert(i); } + class_of.push(k); + } + let n = ends.len(); + Weld { + pieces, + ends, + gap, + size, + classes, + class_of, + cells, + free: vec![true; n], + awake: vec![false; n], + first: vec![None; n], + wanted_by: vec![vec![]; n], + todo: vec![], + #[cfg(test)] + work: std::cell::Cell::new(0), } } - out + + /// The links between the ends that meet: two free ends that are each other's first partner + /// meet, and the ends that wanted either of them look again, until no such pair is left. + fn link(mut self) -> HashMap { + for k in 0..self.classes.len() { + self.wake(k); + } + let mut link: HashMap = HashMap::new(); + while let Some(v) = self.todo.pop() { + let Some(w) = self.partner(v) else { continue }; + if self.free.get(v) != Some(&true) || self.free.get(w) != Some(&true) || self.partner(w) != Some(v) { + continue; + } + let (Some(&(ev, ..)), Some(&(ew, ..))) = (self.ends.get(v), self.ends.get(w)) else { continue }; + link.insert(ev, ew); + link.insert(ew, ev); + self.take(v); + self.take(w); + for e in [v, w] { + if let Some(&k) = self.class_of.get(e) { + self.wake(k); + } + } + let waiting: Vec = [v, w].iter().flat_map(|&e| self.wanted_by.get_mut(e).map(std::mem::take).unwrap_or_default()).collect(); + for x in waiting { + if self.free.get(x) == Some(&true) && matches!(self.partner(x), Some(p) if p == v || p == w) { + self.look(x); + } + } + } + #[cfg(test)] + REJOIN_WORK.with(|w| w.set(self.work.get())); + link + } + + /// End `v`'s first partner, once it has looked. + fn partner(&self, v: usize) -> Option { + self.first.get(v).and_then(|f| f.as_ref()).map(|f| f.1) + } + + /// Have the first three free ends of class `k` that have not looked for a partner look. + fn wake(&mut self, k: usize) { + let Some(class) = self.classes.get(k) else { return }; + let sleeping: Vec = class.free.iter().take(3).copied().filter(|&e| self.awake.get(e) == Some(&false)).collect(); + for e in sleeping { + if let Some(a) = self.awake.get_mut(e) { + *a = true; + } + self.look(e); + } + } + + /// Find free end `e`'s first partner, and queue `e` to check whether that end wants it too. + fn look(&mut self, e: usize) { + let next = self.first_partner(e); + if let Some(list) = next.as_ref().and_then(|f| self.wanted_by.get_mut(f.1)) { + list.push(e); + } + if let Some(f) = self.first.get_mut(e) { + *f = next; + } + self.todo.push(e); + } + + /// End `e` has met another: it is no longer free. + fn take(&mut self, e: usize) { + if let Some(f) = self.free.get_mut(e) { + *f = false; + } + let Some(&k) = self.class_of.get(e) else { return }; + let Some(class) = self.classes.get_mut(k) else { return }; + class.free.remove(&e); + if class.free.is_empty() + && let Some(&(_, p, _)) = self.ends.get(e) + && let Some(set) = self.cells.get_mut(&grid_cell(p, self.size)) + { + set.remove(&(angle_key(class.angle), k)); + } + } + + /// The free end `v` meets first, and where that pair comes in the order: the classes in the + /// cells around `v`'s are looked at by how far their direction is from the reverse of `v`'s, + /// until that is more than [`TURN_SLACK`] past the best turn found. + fn first_partner(&self, v: usize) -> Option<(Order, usize)> { + let &((piece, _), p, out) = self.ends.get(v)?; + let toward = (-out.y).atan2(-out.x); + let split = (angle_key(toward), 0); + let mut best: Option<(Order, usize)> = None; + for c in around(grid_cell(p, self.size)) { + let Some(set) = self.cells.get(&c) else { continue }; + // Both ways round from `toward`; between them they meet every class once. + let mut up = set.range(split..).chain(set.range(..split)).peekable(); + let mut down = set.range(..split).rev().chain(set.range(split..).rev()).peekable(); + let turn = |e: Option<&&(i64, usize)>| e.and_then(|e| self.classes.get(e.1)).map_or(f64::INFINITY, |k| apart(k.angle, toward)); + for _ in 0..set.len() { + let (tu, td) = (turn(up.peek()), turn(down.peek())); + if best.as_ref().is_some_and(|b| tu.min(td) > b.0.0 + TURN_SLACK) { + break; + } + let Some(&(_, k)) = (if tu <= td { up.next() } else { down.next() }) else { break }; + if let Some(pair) = self.pair_with(v, p, piece, k) + && best.as_ref().is_none_or(|b| earlier(&pair.0, &b.0)) + { + best = Some(pair); + } + } + } + best + } + + /// The first free end of class `k` that free end `v` (at `p`, on `piece`) may meet, and where + /// that pair comes in the order. Within a class the pairs differ only in the ends' order, so + /// the end listed first comes first. + fn pair_with(&self, v: usize, p: Point, piece: usize, k: usize) -> Option<(Order, usize)> { + #[cfg(test)] + self.work.set(self.work.get() + 1); + let class = self.classes.get(k)?; + if p.distance(class.at) > self.gap { + return None; + } + // A piece's own two ends meet only when closing it leaves a shape (three anchors). + let short = self.pieces.get(piece).is_none_or(|sp| sp.anchors.len() < 3); + let u = *class.free.iter().find(|&&u| u != v && !(short && self.ends.get(u).is_some_and(|e| e.0.0 == piece)))?; + let (a, b) = (v.min(u), v.max(u)); + let (&(_, pa, oa), &(_, pb, ob)) = (self.ends.get(a)?, self.ends.get(b)?); + let at = listed_at(grid_cell(pa, self.size), grid_cell(pb, self.size)); + Some(((oa.dot(-ob).clamp(-1.0, 1.0).acos(), pa.distance(pb), a, at, b), u)) + } +} + +#[cfg(test)] +thread_local! { + /// Classes of ends looked at by the last [`rejoin`] on this thread. + static REJOIN_WORK: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Walk the links between piece ends into chains. diff --git a/crates/pathops/src/addons/cleanup/tests.rs b/crates/pathops/src/addons/cleanup/tests.rs index 3e1c58d42b..d262128234 100644 --- a/crates/pathops/src/addons/cleanup/tests.rs +++ b/crates/pathops/src/addons/cleanup/tests.rs @@ -1,7 +1,12 @@ -use kurbo::{Point, Vec2}; -use vectorcraft_geom::{Anchor, AnchorKind, SubPath}; +use std::collections::HashMap; -use super::{close_nearly_closed, merge_duplicate_anchors, near_point_groups, rejoin, remove_collinear_anchors, retract_tiny_handles}; +use kurbo::{Point, Vec2}; +use vectorcraft_geom::{Anchor, AnchorKind, EPS, SubPath}; + +use super::{ + End, Rejoined, chains, close_nearly_closed, merge_duplicate_anchors, near_point_groups, outward, rejoin, remove_collinear_anchors, + retract_tiny_handles, root, +}; fn line(pts: &[(f64, f64)], closed: bool) -> SubPath { SubPath::polyline(&pts.iter().map(|&p| p.into()).collect::>(), closed) @@ -30,6 +35,174 @@ fn collinear_anchors_go_and_corners_stay() { assert_eq!(remove_collinear_anchors(&mut bend, 0.005), 1); } +/// The collinear-anchor removal done one `Vec::remove` at a time, testing the anchor that moves +/// into the gap next: the result [`remove_collinear_anchors`] gives. +fn one_at_a_time(sp: &mut SubPath, tolerance: f64) -> usize { + let min = if sp.closed { 3 } else { 2 }; + let mut removed = 0; + let mut i = 0; + while i < sp.anchors.len() && sp.anchors.len() > min { + let n = sp.anchors.len(); + let inner = sp.closed || (i > 0 && i + 1 < n); + let (prev, cur, next) = (sp.anchors[(i + n - 1) % n], sp.anchors[i], sp.anchors[(i + 1) % n]); + let straight = !prev.has_out() && !cur.has_in() && !cur.has_out() && !next.has_in(); + let (a, b) = (cur.p - prev.p, next.p - cur.p); + let len = a.hypot() * b.hypot(); + if inner && straight && len > EPS && a.dot(b) > 0.0 && a.cross(b).abs() / len <= tolerance { + sp.anchors.remove(i); + removed += 1; + } else { + i += 1; + } + } + removed +} + +/// A subpath's closed flag and every anchor's coordinates bit for bit, with its kind. +fn bits(sp: &SubPath) -> (bool, Vec<([u64; 6], AnchorKind)>) { + let anchors = sp.anchors.iter().map(|a| ([a.p.x, a.p.y, a.h_in.x, a.h_in.y, a.h_out.x, a.h_out.y].map(f64::to_bits), a.kind)); + (sp.closed, anchors.collect()) +} + +/// Check that [`remove_collinear_anchors`] gives `sp` the count and anchors [`one_at_a_time`] does. +fn same_as_one_at_a_time(sp: &SubPath, tolerance: f64) { + let (mut fast, mut slow) = (sp.clone(), sp.clone()); + let got = remove_collinear_anchors(&mut fast, tolerance); + let want = one_at_a_time(&mut slow, tolerance); + assert_eq!(got, want, "count at tolerance {tolerance} for {sp:?}"); + assert_eq!(bits(&fast), bits(&slow), "anchors at tolerance {tolerance} for {sp:?}"); +} + +/// xorshift64: the same numbers on every run. +struct Rng(u64); + +impl Rng { + fn next(&mut self) -> u64 { + self.0 ^= self.0 << 13; + self.0 ^= self.0 >> 7; + self.0 ^= self.0 << 17; + self.0 + } + + fn pick(&mut self, xs: &[T]) -> T { + xs[(self.next() % xs.len() as u64) as usize] + } +} + +/// A subpath of `n` anchors stepping mostly straight along one direction, with repeated points, +/// small and large bends, reversals, short and long handles and non-finite or huge coordinates. +fn generated(r: &mut Rng, n: usize, closed: bool) -> SubPath { + let dir = r.pick(&[Vec2::new(1.0, 0.0), Vec2::new(0.0, -1.0), Vec2::new(0.6, 0.8), Vec2::new(-1.0, 1.0)]); + let side = Vec2::new(-dir.y, dir.x); + let mut at = Point::new(r.pick(&[0.0, 3.0, -7.5]), r.pick(&[0.0, 2.0])); + let anchors = (0..n) + .map(|_| { + at += dir * r.pick(&[1.0, 1.0, 1.0, 2.0, 0.5, 0.0, -1.0]); + let bend = r.pick(&[0.0, 0.0, 0.0, 0.0, 1e-3, 0.004, 0.005, 0.006, 1.0]); + let mut p = at + side * bend; + match r.next() % 40 { + 0 => p.x = f64::NAN, + 1 => p.y = f64::INFINITY, + 2 => p.x = f64::NEG_INFINITY, + 3 => p = Point::new(p.x * 1e300, p.y * 1e300), + 4 => p = Point::new(1e-300, -1e-300), + _ => {} + } + let handle = |r: &mut Rng| p + Vec2::new(r.pick(&[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1e-10, 1.0]), 0.0); + let (h_in, h_out) = (handle(r), handle(r)); + Anchor { p, h_in, h_out, kind: r.pick(&[AnchorKind::Corner, AnchorKind::Corner, AnchorKind::Smooth]) } + }) + .collect(); + SubPath::new(anchors, closed) +} + +const TOLERANCES: [f64; 12] = [-1.0, -0.0, 0.0, 1e-9, 0.001, 0.005, 0.5, 1.0, 2.0, f64::NAN, f64::INFINITY, f64::NEG_INFINITY]; + +#[test] +fn collinear_anchors_go_as_when_removed_one_at_a_time() { + let mut r = Rng(0x9e37_79b9_7f4a_7c15); + for n in (0..40).chain([64, 100, 257]) { + for _ in 0..40 { + for closed in [false, true] { + let sp = generated(&mut r, n, closed); + for tolerance in TOLERANCES { + same_as_one_at_a_time(&sp, tolerance); + } + } + } + } +} + +#[test] +fn collinear_anchors_keep_their_neighbors_order_and_ends() { + let ring = |pts: &[(f64, f64)]| line(pts, true); + let cases = [ + // A closed run whose first anchor goes: the last anchor's next neighbor is then the second. + ring(&[(5.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0), (0.0, 0.0)]), + ring(&[(0.0, 0.0), (1.0, 0.0), (2.0, 0.0), (3.0, 0.0), (4.0, 0.0), (5.0, 0.0), (2.0, 4.0)]), + // Every anchor on one line: the path stops at three (closed) or two (open) anchors. + ring(&[(0.0, 0.0), (1.0, 0.0), (2.0, 0.0), (3.0, 0.0), (4.0, 0.0)]), + line(&[(0.0, 0.0), (1.0, 0.0), (2.0, 0.0), (3.0, 0.0), (4.0, 0.0)], false), + // The last anchor lies between the first one kept and the one before it. + ring(&[(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0), (0.0, 5.0)]), + // Repeated and zero-length points. + line(&[(0.0, 0.0), (0.0, 0.0), (1.0, 0.0), (1.0, 0.0), (2.0, 0.0)], false), + ring(&[(0.0, 0.0), (0.0, 0.0), (0.0, 0.0), (0.0, 0.0)]), + // Products of huge coordinates overflow; tiny ones underflow. + line(&[(0.0, 0.0), (1e200, 1e200), (2e200, 2e200), (f64::MAX, f64::MAX)], false), + line(&[(0.0, 0.0), (1e-200, 0.0), (2e-200, 0.0)], false), + line(&[(0.0, 0.0), (f64::NAN, 0.0), (2.0, 0.0), (f64::INFINITY, 0.0), (5.0, 0.0)], false), + ]; + for sp in &cases { + for tolerance in TOLERANCES { + same_as_one_at_a_time(sp, tolerance); + } + } + let mut first = cases[0].clone(); + assert_eq!(remove_collinear_anchors(&mut first, 0.0), 1); + assert_eq!(points(&first), [(10.0, 0.0), (10.0, 10.0), (0.0, 10.0), (0.0, 0.0)]); + let (mut closed, mut open) = (cases[2].clone(), cases[3].clone()); + assert_eq!((remove_collinear_anchors(&mut closed, 0.0), closed.anchors.len()), (2, 3)); + assert_eq!(remove_collinear_anchors(&mut open, 0.0), 3); + assert_eq!(points(&open), [(0.0, 0.0), (4.0, 0.0)], "open ends stay"); + // A handle on either side of either segment keeps the anchor between them. + for side in 0..4 { + let mut sp = line(&[(0.0, 0.0), (1.0, 0.0), (2.0, 0.0)], false); + let (i, h) = [(0, 1), (1, 0), (1, 1), (2, 0)][side]; + for kind in [AnchorKind::Corner, AnchorKind::Smooth] { + let a = &mut sp.anchors[i]; + a.kind = kind; + *(if h == 0 { &mut a.h_in } else { &mut a.h_out }) = a.p + Vec2::new(0.0, 1.0); + same_as_one_at_a_time(&sp, 0.005); + assert_eq!(remove_collinear_anchors(&mut sp.clone(), 0.005), 0, "handle {h} on anchor {i}"); + } + } +} + +#[test] +fn collinear_anchors_at_the_tolerance_go_and_just_past_it_stay() { + let sp = line(&[(0.0, 0.0), (100.0, 0.1), (200.0, 0.0)], false); + let (a, b) = (sp.anchors[1].p - sp.anchors[0].p, sp.anchors[2].p - sp.anchors[1].p); + let sine = a.cross(b).abs() / (a.hypot() * b.hypot()); + for (tolerance, removed) in [(sine, 1), (sine.next_down(), 0), (sine.next_up(), 1)] { + same_as_one_at_a_time(&sp, tolerance); + assert_eq!(remove_collinear_anchors(&mut sp.clone(), tolerance), removed, "{tolerance}"); + } +} + +#[test] +fn collinear_anchors_go_in_linear_work() { + for (n, closed) in [(10_000, false), (20_000, false), (20_000, true)] { + let pts: Vec = (0..n).map(|i| Point::new(i as f64, 0.0)).collect(); + let mut sp = SubPath::polyline(&pts, closed); + let removed = remove_collinear_anchors(&mut sp, 0.005); + // A closed straight run stops at three anchors; an open one keeps its two ends. + assert_eq!((removed, sp.anchors.len()), if closed { (n - 3, 3) } else { (n - 2, 2) }); + let work = super::COLLINEAR_WORK.with(std::cell::Cell::get); + assert!(work <= 2 * n, "{n} anchors took {work} steps"); + } +} + #[test] fn duplicate_anchors_merge_keeping_the_outer_handles() { let mut sp = SubPath::new( @@ -89,6 +262,244 @@ fn near_points_group_but_linked_and_equal_ones_do_not() { assert!(near_point_groups(&far, 1e-300, |_, _| false).is_empty()); } +/// Nearly Coincident Anchors' grouping comparing every pair of points in touching grid cells: the +/// groups [`near_point_groups`] gives. +fn near_groups_pair_by_pair(points: &[Point], distance: f64, linked: impl Fn(usize, usize) -> bool) -> Vec> { + if !(distance > 0.0 && distance.is_finite()) { + return vec![]; + } + let cell = |p: Point| ((p.x / distance).floor() as i64, (p.y / distance).floor() as i64); + let mut grid: HashMap<(i64, i64), Vec> = HashMap::new(); + for (i, p) in points.iter().enumerate().filter(|(_, p)| p.is_finite()) { + grid.entry(cell(*p)).or_default().push(i); + } + let mut parent: Vec = (0..points.len()).collect(); + for (&(cx, cy), members) in &grid { + for (dx, dy) in [(0, 0), (1, 0), (-1, 1), (0, 1), (1, 1)] { + let Some(others) = grid.get(&(cx.saturating_add(dx), cy.saturating_add(dy))) else { continue }; + for &i in members { + for &j in others.iter().filter(|&&j| (dx, dy) != (0, 0) || j > i) { + let d = points[i].distance(points[j]); + if d <= distance && d > 0.0 && !linked(i.min(j), i.max(j)) { + let (ri, rj) = (root(&mut parent, i), root(&mut parent, j)); + parent[ri.max(rj)] = ri.min(rj); + } + } + } + } + } + let mut groups: HashMap> = HashMap::new(); + for i in 0..points.len() { + groups.entry(root(&mut parent, i)).or_default().push(i); + } + let mut out: Vec> = groups.into_values().filter(|g| g.len() > 1).collect(); + out.sort_unstable(); + out +} + +/// Points around a few spots on a lattice, many at the same place, with signed zeros, huge, tiny +/// and non-finite coordinates. +fn generated_points(r: &mut Rng, n: usize, distance: f64) -> Vec { + let spots: Vec = (0..1 + r.next() % 6).map(|_| Point::new((r.next() % 5) as f64 * distance, (r.next() % 5) as f64 * distance)).collect(); + (0..n) + .map(|_| { + let jitter = |r: &mut Rng| r.pick(&[0.0, 0.0, -0.0, 0.1, 0.3, 0.5, 0.7, 0.99, 1.0, 1.01, 2.0, -0.5, -1.0]) * distance; + let at = r.pick(&spots); + let p = Point::new(at.x + jitter(r), at.y + jitter(r)); + match r.next() % 50 { + 0 => Point::new(f64::NAN, p.y), + 1 => Point::new(p.x, f64::INFINITY), + 2 => Point::new(-0.0, -0.0), + 3 => Point::new(p.x * 1e300, p.y), + 4 => Point::new(1e-300, 1e-300), + _ => p, + } + }) + .collect() +} + +#[test] +fn near_points_group_as_when_every_pair_is_compared() { + let mut r = Rng(0x2545_f491_4f6c_dd1d); + let linked: [fn(usize, usize) -> bool; 5] = + [|_, _| false, |a, b| b == a + 1, |a, b| (a * 31 + b * 17) % 5 == 0, |a, b| (a + b) % 2 == 0, |_, _| true]; + for n in (0..30).chain([64, 150, 300]) { + for _ in 0..12 { + for distance in [0.01, 0.5, 1.0, 3.0, 1e-200, 1e300] { + let pts = generated_points(&mut r, n, distance); + for (k, linked) in linked.iter().enumerate() { + let want = near_groups_pair_by_pair(&pts, distance, linked); + assert_eq!(near_point_groups(&pts, distance, linked), want, "linked {k} at {distance} for {pts:?}"); + } + } + } + } +} + +/// A tight cluster of `n` points around `at`, no two at the same place. +fn cluster(at: Point, radius: f64, n: usize) -> Vec { + (0..n).map(|i| at + Vec2::from_angle(i as f64 * 2.399_963) * (radius * ((i + 1) as f64 / n as f64).sqrt())).collect() +} + +#[test] +fn near_points_in_a_dense_cell_group_in_linear_work() { + let n = 4_000; + let neighbours = |a: usize, b: usize| b == a + 1; + let one_cluster = cluster(Point::new(0.005, 0.005), 0.004, n); + let mut two_clusters = cluster(Point::new(0.001, 0.001), 0.0009, n / 2); + two_clusters.extend(cluster(Point::new(0.019, 0.019), 0.0009, n / 2)); + let same_place = vec![Point::new(0.005, 0.005); n]; + let cases = [(&one_cluster, 1, n), (&two_clusters, 2, n / 2), (&same_place, 0, 0)]; + for (pts, count, size) in cases { + let groups = near_point_groups(pts, 0.01, neighbours); + let work = super::NEAR_WORK.with(std::cell::Cell::get); + assert_eq!(groups, near_groups_pair_by_pair(pts, 0.01, neighbours)); + assert_eq!(groups.len(), count); + assert!(groups.iter().all(|g| g.len() == size), "{:?}", groups.iter().map(Vec::len).collect::>()); + assert!(work <= 4 * n, "{n} points took {work} steps"); + } +} + +/// One pair of ends (`a` < `b` in the list of ends) for [`rejoin_sorting_every_pair`]: the turn, +/// the distance, and the two ends. +type Pair = (f64, f64, End, End); + +/// Rejoin listing every pair of ends in touching grid cells and sorting them by turn and then +/// distance: the joins [`rejoin`] makes. +fn rejoin_sorting_every_pair(pieces: &[SubPath], gap: f64) -> Vec { + if !(gap >= 0.0 && gap.is_finite()) { + return vec![]; + } + let usable = |sp: &&SubPath| { + !sp.closed && sp.anchors.len() >= 2 && sp.anchors.iter().all(|a| a.p.is_finite() && a.h_in.is_finite() && a.h_out.is_finite()) + }; + let ends: Vec<(End, Point, Vec2)> = pieces + .iter() + .enumerate() + .filter(|(_, sp)| usable(sp)) + .flat_map(|(i, sp)| [(i, sp, false), (i, sp, true)]) + .filter_map(|(i, sp, last)| { + let a = if last { sp.anchors.last() } else { sp.anchors.first() }?; + Some(((i, last), a.p, outward(sp, last)?)) + }) + .collect(); + let size = gap.max(1e-9); + let cell = |p: Point| ((p.x / size).floor() as i64, (p.y / size).floor() as i64); + let mut grid: HashMap<(i64, i64), Vec> = HashMap::new(); + for (i, e) in ends.iter().enumerate() { + grid.entry(cell(e.1)).or_default().push(i); + } + let mut pairs: Vec = vec![]; + for (a, &(ea, pa, oa)) in ends.iter().enumerate() { + let (cx, cy) = cell(pa); + for dx in -1..=1 { + for dy in -1..=1 { + let Some(others) = grid.get(&(cx.saturating_add(dx), cy.saturating_add(dy))) else { continue }; + for &b in others.iter().filter(|&&b| b > a) { + let (eb, pb, ob) = ends[b]; + if ea.0 == eb.0 && pieces[ea.0].anchors.len() < 3 { + continue; + } + let d = pa.distance(pb); + if d <= gap { + pairs.push((oa.dot(-ob).clamp(-1.0, 1.0).acos(), d, ea, eb)); + } + } + } + } + } + pairs.sort_by(|x, y| x.0.total_cmp(&y.0).then(x.1.total_cmp(&y.1))); + let mut link: HashMap = HashMap::new(); + for (_, _, a, b) in pairs { + if !link.contains_key(&a) && !link.contains_key(&b) { + link.insert(a, b); + link.insert(b, a); + } + } + chains(pieces, &link) +} + +/// Check that [`rejoin`] joins `pieces` as [`rejoin_sorting_every_pair`] does, bit for bit. +fn same_as_sorting_every_pair(pieces: &[SubPath], gap: f64) { + let (got, want) = (rejoin(pieces, gap), rejoin_sorting_every_pair(pieces, gap)); + let shape = |out: &[Rejoined]| out.iter().map(|j| (j.members.clone(), bits(&j.path))).collect::>(); + assert_eq!(shape(&got), shape(&want), "gap {gap} for {pieces:?}"); +} + +/// Pieces of two to four anchors whose ends sit on or near a few lattice points, often at the +/// same place, some curving, closed or non-finite. +fn generated_pieces(r: &mut Rng, n: usize, gap: f64) -> Vec { + let spot = |r: &mut Rng| { + let near = r.pick(&[0.0, 0.0, 0.0, 0.25, 0.5, 1.0, 1.5]) * gap; + Point::new((r.next() % 3) as f64 + near, (r.next() % 3) as f64 + r.pick(&[0.0, 0.0, near, -near])) + }; + (0..n) + .map(|_| { + let count = 2 + (r.next() % 3) as usize; + let mut pts: Vec = (0..count).map(|_| spot(r)).collect(); + if r.next().is_multiple_of(30) { + pts[0].x = f64::NAN; + } + let mut sp = SubPath::polyline(&pts, r.next().is_multiple_of(15)); + if r.next().is_multiple_of(4) { + let a = &mut sp.anchors[0]; + a.h_out = a.p + r.pick(&[Vec2::new(0.3, 0.1), Vec2::new(0.0, -0.2), Vec2::new(-0.1, -0.1)]); + } + sp + }) + .collect() +} + +#[test] +fn rejoin_joins_as_when_every_pair_is_sorted() { + let mut r = Rng(0xd1b5_4a32_d192_ed03); + for n in (0..25).chain([40, 80, 160]) { + for _ in 0..15 { + for gap in [0.0, 0.05, 0.1, 0.5, 1.0, 3.0] { + same_as_sorting_every_pair(&generated_pieces(&mut r, n, gap), gap); + } + } + } + // Ends meeting from directions that tie: a plus sign, a doubled star and stacked copies. + let plus: Vec = [(1.0, 0.0), (0.0, 1.0), (-1.0, 0.0), (0.0, -1.0)].map(|(x, y)| line(&[(0.0, 0.0), (x, y)], false)).to_vec(); + let mut doubled = plus.clone(); + doubled.extend(plus.iter().map(|sp| { + let mut sp = sp.clone(); + sp.reverse(); + sp + })); + let stacked = vec![line(&[(0.0, 0.0), (1.0, 0.0), (2.0, 1.0)], false); 7]; + for pieces in [&plus, &doubled, &stacked] { + for gap in [0.0, 0.1, 5.0] { + same_as_sorting_every_pair(pieces, gap); + } + } +} + +#[test] +fn rejoin_pairs_coincident_ends_in_near_linear_work() { + let n = 2_000; + let ray = |angle: f64| { + let tip = Vec2::from_angle(angle) * 100.0; + line(&[(0.0, 0.0), (tip.x, tip.y)], false) + }; + let star: Vec = (0..n).map(|i| ray(i as f64 * std::f64::consts::TAU / n as f64)).collect(); + let mut r = Rng(0x9e37_79b9_7f4a_7c15); + let scattered: Vec = (0..n).map(|_| ray((r.next() % 1_000_000) as f64 * 1e-6 * std::f64::consts::TAU)).collect(); + let stacked = vec![line(&[(0.0, 0.0), (10.0, 0.0)], false); n]; + for (name, pieces) in [("star", &star), ("scattered", &scattered), ("stacked", &stacked)] { + let out = rejoin(pieces, 0.1); + let work = super::REJOIN_WORK.with(std::cell::Cell::get); + let want = rejoin_sorting_every_pair(pieces, 0.1); + assert_eq!( + out.iter().map(|j| (j.members.clone(), bits(&j.path))).collect::>(), + want.iter().map(|j| (j.members.clone(), bits(&j.path))).collect::>(), + "{name}" + ); + assert!(work <= 20 * n, "{name}: {n} pieces took {work} steps"); + } +} + #[test] fn rejoin_welds_pieces_within_the_gap() { // Three pieces of one zig-zag, the middle one drawn backwards, plus one too far away. From 302be702d427b6b9874371bbe86e5629c8d42219 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 08:08:06 -0800 Subject: [PATCH 18/25] i18n: Dutch rows for the Revolve graphics messages --- crates/ui-egui/src/i18n/nl.tsv | 3 +++ 1 file changed, 3 insertions(+) diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 40facfda42..2720be519c 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -5884,6 +5884,9 @@ mark-style Japanese Japans @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} {key} in `{GRAPHICS}` moet een getal van {lo} tot {hi} zijn @msg `{GRAPHICS}` must be an array `{GRAPHICS}` moet een array zijn @msg Graphics map onto planar faces: use the Extrude or Plane object type Illustraties worden op platte vlakken geplaatst: gebruik het objecttype Extruderen of Vlak +@msg Graphics map onto the Plane, Extrude and Revolve object types Illustraties worden op de objecttypen Vlak, Extruderen en Draaien geplaatst +@msg Revolve maps graphics onto its side: map them onto the front Draaien plaatst illustraties op de zijkant: plaats ze op de voorkant +@msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments De illustraties zijn te complex voor dit oppervlak: vereenvoudig de illustraties van de symbolen of verlaag Segmenten @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` neemt maximaal {MAX_GRAPHICS} illustraties op @msg A plane has one face: map its graphics onto the front Een vlak heeft één zijde: plaats de illustraties ervan op de voorkant @msg The graphics are too complex: simplify the symbols' art De illustraties zijn te complex: vereenvoudig de illustraties van de symbolen From cd7e20993487990b189a83cf7b274c4968fc7989 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 08:10:42 -0800 Subject: [PATCH 19/25] PDF: pages longer than 200 in are written at full size in points by default PDF export without a PDF/X or PDF/A standard writes pages longer than 200 in at full size in points instead of with a UserUnit scale. longPagesInPoints is now on by default in PdfSettings, the built-in presets and the Save PDF dialog. Turning it off writes such a page with a UserUnit from PDF 1.6 on, as before. PDF/A-2b files keep the UserUnit, and .ai saves keep it unless longPagesInPoints: true is passed. Docs: params text, docs/mcp.md, docs/target-app-parity.md. --- crates/engine/src/cmd/fileio/pdf.rs | 6 +-- crates/engine/src/cmd/fileio/save.rs | 4 ++ crates/engine/src/tests/pdfpresets.rs | 53 ++++++++++-------- crates/pdf/src/settings.rs | 31 +++++++++-- crates/pdf/src/tests/marks.rs | 57 +++++++++++--------- crates/ui-egui/src/dialogs/save_pdf/tests.rs | 4 +- crates/ui-egui/src/dialogs/tests_export.rs | 14 ++++- docs/mcp.md | 8 +-- docs/target-app-parity.md | 2 +- 9 files changed, 117 insertions(+), 62 deletions(-) diff --git a/crates/engine/src/cmd/fileio/pdf.rs b/crates/engine/src/cmd/fileio/pdf.rs index acc22c7876..ec7d43472d 100644 --- a/crates/engine/src/cmd/fileio/pdf.rs +++ b/crates/engine/src/cmd/fileio/pdf.rs @@ -98,8 +98,8 @@ pub(crate) const OPTIONS: &[FormatOption] = &[ FormatOption { name: "longPagesInPoints", ty: "boolean", - default: "false", - description: "a page with a side longer than 14,400 pt (200 in) is written at its size in points, without a UserUnit, at every PDF version, in files without a standard (PDF/A files keep the UserUnit)", + default: "true", + description: "a page with a side longer than 14,400 pt (200 in) is written at its size in points, without a UserUnit, at every PDF version, in files without a standard (PDF/A files keep the UserUnit); false writes it with a UserUnit from PDF 1.6 on", }, FormatOption { name: "createLayers", @@ -128,7 +128,7 @@ pub fn specs() -> Vec { "Export PDF", [], None, - "{path?, preset?: \"VectorCraft Default\" (built-in or saved: pdf.preset.list), artboard? | artboards?: [i…] | range?: \"1-3, 5\" (1-based; default all, one page each), useArtboards?: true (false: one page, the bounds of the visible art, as document.export writes it; artboard, artboards and range are then ignored, Preserve Editing is left out (with a warning when it is on), and a document with no visible art is refused), standard?: none|pdfA2b|pdfX1a (CMYK, grey and spot colours only: colours and images converted to output.destination or the CMYK output intent, untagged; transparency flattened with flattenerPreset; PDF 1.3)|pdfX3 (colours ICC-tagged; transparency flattened; PDF 1.3)|pdfX4 (transparency and layers kept; colours ICC-tagged; PDF 1.6 at most) (PDF/X: a /GTS_PDFX output intent, by default the CMYK profile in effect, embedded; TrimBox, Trapped, GTS_PDFXVersion, title and dates; fonts embedded or outlined), compatibility?: 1.3 (no transparency: it is flattened with flattenerPreset, without the layers the file leaves out; images keep no see-through pixels)|1.4|1.5|1.6|1.7 (default)|2.0 (choosing a standard sets its version: 1.7 for pdfA2b, 1.6 for pdfX4, 1.3 for pdfX1a and pdfX3, which write 1.4 as 1.3 too; pdfA2b refuses 1.3; a page with a side longer than 14,400 pt keeps its size with a UserUnit from 1.6 on: 1.5 is then written as 1.6, with 1.5's encryption, and so is 1.4 in pdfA2b files, with a warning; PDF/X files and other 1.3 and 1.4 files write it in points, and 1.3 and 1.4 (pdfX1a and pdfX3 too) refuse a page past 32,767 pt whose size or art needs a real number past 32,767; a page whose short side is 3 pt or longer but would be under 3 units at that UserUnit gets a smaller one that keeps the short side at 3 units; a warning gives each such page's size), longPagesInPoints?: false (true: such a page is written at its size in points, without a UserUnit, at every version, and 1.5 stays 1.5, in files without a standard (PDF/A files keep the UserUnit); apps that keep to the limit cut it to 200 in), preserveEditing? (on in VectorCraft Default: the native document as an embedded file, which document.open restores; choosing a standard turns it off, a standard refuses it), thumbnails? (each page drawn as a /Thumb image, 106 px on its long side), fastWebView? (a linearised file: the first page shows while the rest downloads; it stays linearised when encrypted), viewAfterSaving? (the app opens the written file), createLayers? (each layer and sublayer but template layers as a PDF layer, an optional content group listed under its layer's: hidden layers off, non-printing ones /PrintState /OFF, locked ones locked; needs 1.5 or later; they reopen as layers; choosing pdfX1a or pdfX3 turns it off; they refuse it), includeNonPrinting? (keep layers whose Print option is off; left out by default unless createLayers), flattenerPreset?: \"\" (High Resolution) | high | medium | low | a saved preset (flattener.presets.list): what PDF 1.3 files flatten transparency with, flattener?: {object.flattenTransparency options over it}, compression?: {color?, gray?: {downsample: none|average|subsample|bicubic, ppi: 300, abovePpi: 450, compression: none|zip|jpeg|jpeg2000|auto, quality: minimum|low|medium|high|maximum}, mono?: {downsample, ppi: 1200, abovePpi: 1800, compression: none|ccittG3|ccittG4|zip|runLength} (black-and-white images), compressText?: true} (images above abovePpi are resampled to ppi; auto keeps JPEGs JPEG, the others lossless; JPEG needs opaque images; none, jpeg2000, CCITT and runLength are written as ZIP with a warning), marks?: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25 (trim marks and targets), offset: 6 (pt from the artboard, at least the bleed)} (printer's marks in [Registration], every plate: trim marks, registration targets mid-side, CMYK/spot/black-tint colour bars on top, page information (title, artboard, date UTC) below), bleed?: {useDocument (the document's bleed, document.setup), top, bottom, left, right} (pt; art in the bleed is kept; a PDF/X file with no bleed on a side where the document's bleed has one comes back with a warning). Each page: TrimBox = artboard, BleedBox = artboard + bleed, MediaBox = that + the marks' room (art clipped to the BleedBox), output?: {conversion: none (default)|destination (every colour into the destination profile's model, CMYK or RGB, also colours of that model in another profile)|preserveNumbers (only colours of the other model and Lab; those in the destination's model keep their numbers) (grey stays grey; images are converted too, printer's marks are not), destination: profile name (edit.colorSettings lists them; default: the document's profile for its colour mode), profiles: none (device colours)|all|destination|taggedSource (documents assigned a profile: edit.assignProfile) (ICC-based colours: CMYK with the destination or document CMYK profile, RGB as sRGB, grey with the sRGB tone curve; PDF/A, pdfX3 and pdfX4 always, whatever profiles says), outputIntent: profile name (embedded as the catalog's /GTS_PDFX output intent; a name that isn't a profile is only named, which pdfX1a and pdfX3 allow only with a registry and pdfX4 refuses; pdfX1a needs a CMYK one), outputCondition, outputConditionId (default: outputIntent), registry, trapped (/Trapped /True; /False when an output intent is written)} (PDF/A files keep their own output intent), advanced?: {fontSubsetPercent: 100 (below 100 is accepted with a warning: fonts are always embedded as subsets), outlineText: false (type as real, selectable and searchable text in embedded subset fonts with a ToUnicode map; fonts whose licence forbids embedding, or allows only whole fonts, stay outlines with a warning; true: every glyph as an outline), overprint: preserve (overprinting fills and strokes set /OP /op true, /OPM 1; white ones knock out with document.setup discardWhiteOverprint)|discard (they knock out)}, security?: {openPassword, permissionsPassword, printing: none|low|high, changes: none|pages|forms|comments|any, copy, screenReader, plaintextMetadata}, acknowledgeLoss?: bool (write over the file the document was read from although reading it left things out), format?: \"pdf\"} → {path, bytes, warnings}; no path → {dataBase64, bytes, warnings}. The options apply over the preset (null keeps its value); options accepted but not applied yet come back as warnings; a standard with a PDF version it doesn't allow and a password with a standard are refused, and so is a PDF/X file that would still break its standard (transparency the flattener left, RGB in pdfX1a, a font not embedded) or a PDF 1.3 file with transparency left. document.export {format: pdf} takes the same options. A key PDF doesn't take, and an unknown key inside one of the option objects, are refused", + "{path?, preset?: \"VectorCraft Default\" (built-in or saved: pdf.preset.list), artboard? | artboards?: [i…] | range?: \"1-3, 5\" (1-based; default all, one page each), useArtboards?: true (false: one page, the bounds of the visible art, as document.export writes it; artboard, artboards and range are then ignored, Preserve Editing is left out (with a warning when it is on), and a document with no visible art is refused), standard?: none|pdfA2b|pdfX1a (CMYK, grey and spot colours only: colours and images converted to output.destination or the CMYK output intent, untagged; transparency flattened with flattenerPreset; PDF 1.3)|pdfX3 (colours ICC-tagged; transparency flattened; PDF 1.3)|pdfX4 (transparency and layers kept; colours ICC-tagged; PDF 1.6 at most) (PDF/X: a /GTS_PDFX output intent, by default the CMYK profile in effect, embedded; TrimBox, Trapped, GTS_PDFXVersion, title and dates; fonts embedded or outlined), compatibility?: 1.3 (no transparency: it is flattened with flattenerPreset, without the layers the file leaves out; images keep no see-through pixels)|1.4|1.5|1.6|1.7 (default)|2.0 (choosing a standard sets its version: 1.7 for pdfA2b, 1.6 for pdfX4, 1.3 for pdfX1a and pdfX3, which write 1.4 as 1.3 too; pdfA2b refuses 1.3; in pdfA2b files, and with longPagesInPoints: false, a page with a side longer than 14,400 pt keeps its size with a UserUnit from 1.6 on: 1.5 is then written as 1.6, with 1.5's encryption, and so is 1.4 in pdfA2b files, with a warning; PDF/X files and other 1.3 and 1.4 files write it in points, and 1.3 and 1.4 (pdfX1a and pdfX3 too) refuse a page past 32,767 pt whose size or art needs a real number past 32,767; a page whose short side is 3 pt or longer but would be under 3 units at that UserUnit gets a smaller one that keeps the short side at 3 units; a warning gives each such page's size), longPagesInPoints?: true (such a page is written at its size in points, without a UserUnit, at every version, and 1.5 stays 1.5, in files without a standard (PDF/A files keep the UserUnit); apps that keep to the limit cut it to 200 in; false: the UserUnit as above), preserveEditing? (on in VectorCraft Default: the native document as an embedded file, which document.open restores; choosing a standard turns it off, a standard refuses it), thumbnails? (each page drawn as a /Thumb image, 106 px on its long side), fastWebView? (a linearised file: the first page shows while the rest downloads; it stays linearised when encrypted), viewAfterSaving? (the app opens the written file), createLayers? (each layer and sublayer but template layers as a PDF layer, an optional content group listed under its layer's: hidden layers off, non-printing ones /PrintState /OFF, locked ones locked; needs 1.5 or later; they reopen as layers; choosing pdfX1a or pdfX3 turns it off; they refuse it), includeNonPrinting? (keep layers whose Print option is off; left out by default unless createLayers), flattenerPreset?: \"\" (High Resolution) | high | medium | low | a saved preset (flattener.presets.list): what PDF 1.3 files flatten transparency with, flattener?: {object.flattenTransparency options over it}, compression?: {color?, gray?: {downsample: none|average|subsample|bicubic, ppi: 300, abovePpi: 450, compression: none|zip|jpeg|jpeg2000|auto, quality: minimum|low|medium|high|maximum}, mono?: {downsample, ppi: 1200, abovePpi: 1800, compression: none|ccittG3|ccittG4|zip|runLength} (black-and-white images), compressText?: true} (images above abovePpi are resampled to ppi; auto keeps JPEGs JPEG, the others lossless; JPEG needs opaque images; none, jpeg2000, CCITT and runLength are written as ZIP with a warning), marks?: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25 (trim marks and targets), offset: 6 (pt from the artboard, at least the bleed)} (printer's marks in [Registration], every plate: trim marks, registration targets mid-side, CMYK/spot/black-tint colour bars on top, page information (title, artboard, date UTC) below), bleed?: {useDocument (the document's bleed, document.setup), top, bottom, left, right} (pt; art in the bleed is kept; a PDF/X file with no bleed on a side where the document's bleed has one comes back with a warning). Each page: TrimBox = artboard, BleedBox = artboard + bleed, MediaBox = that + the marks' room (art clipped to the BleedBox), output?: {conversion: none (default)|destination (every colour into the destination profile's model, CMYK or RGB, also colours of that model in another profile)|preserveNumbers (only colours of the other model and Lab; those in the destination's model keep their numbers) (grey stays grey; images are converted too, printer's marks are not), destination: profile name (edit.colorSettings lists them; default: the document's profile for its colour mode), profiles: none (device colours)|all|destination|taggedSource (documents assigned a profile: edit.assignProfile) (ICC-based colours: CMYK with the destination or document CMYK profile, RGB as sRGB, grey with the sRGB tone curve; PDF/A, pdfX3 and pdfX4 always, whatever profiles says), outputIntent: profile name (embedded as the catalog's /GTS_PDFX output intent; a name that isn't a profile is only named, which pdfX1a and pdfX3 allow only with a registry and pdfX4 refuses; pdfX1a needs a CMYK one), outputCondition, outputConditionId (default: outputIntent), registry, trapped (/Trapped /True; /False when an output intent is written)} (PDF/A files keep their own output intent), advanced?: {fontSubsetPercent: 100 (below 100 is accepted with a warning: fonts are always embedded as subsets), outlineText: false (type as real, selectable and searchable text in embedded subset fonts with a ToUnicode map; fonts whose licence forbids embedding, or allows only whole fonts, stay outlines with a warning; true: every glyph as an outline), overprint: preserve (overprinting fills and strokes set /OP /op true, /OPM 1; white ones knock out with document.setup discardWhiteOverprint)|discard (they knock out)}, security?: {openPassword, permissionsPassword, printing: none|low|high, changes: none|pages|forms|comments|any, copy, screenReader, plaintextMetadata}, acknowledgeLoss?: bool (write over the file the document was read from although reading it left things out), format?: \"pdf\"} → {path, bytes, warnings}; no path → {dataBase64, bytes, warnings}. The options apply over the preset (null keeps its value); options accepted but not applied yet come back as warnings; a standard with a PDF version it doesn't allow and a password with a standard are refused, and so is a PDF/X file that would still break its standard (transparency the flattener left, RGB in pdfX1a, a font not embedded) or a PDF 1.3 file with transparency left. document.export {format: pdf} takes the same options. A key PDF doesn't take, and an unknown key inside one of the option objects, are refused", has_doc, export_pdf ), diff --git a/crates/engine/src/cmd/fileio/save.rs b/crates/engine/src/cmd/fileio/save.rs index e1cbf68bf2..aa0b2e9a58 100644 --- a/crates/engine/src/cmd/fileio/save.rs +++ b/crates/engine/src/cmd/fileio/save.rs @@ -699,6 +699,10 @@ pub(super) fn encode_ai(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Res if o.get("standard").is_none_or(Value::is_null) { o.entry("createLayers").or_insert(json!(true)); } + // A page longer than 14,400 pt keeps its `UserUnit` (PDF export writes it in points). + if o.get("longPagesInPoints").is_none_or(Value::is_null) { + o.insert("longPagesInPoints".into(), json!(false)); + } if let Some(c) = o.get("compress").and_then(Value::as_bool) { let compression = o.entry("compression").or_insert_with(|| json!({})); if let Some(m) = compression.as_object_mut() { diff --git a/crates/engine/src/tests/pdfpresets.rs b/crates/engine/src/tests/pdfpresets.rs index 7de08463f3..ecdf140c0e 100644 --- a/crates/engine/src/tests/pdfpresets.rs +++ b/crates/engine/src/tests/pdfpresets.rs @@ -123,40 +123,49 @@ fn presets_export_and_import_round_trip() { assert!(is_bad_params(Session::new().execute("pdf.preset.export", &json!({}))), "nothing saved to export"); } -/// `longPagesInPoints` is saved with a preset, comes back through a presets file and the -/// preferences, shows in `document.pdfSettings`, and a 10 m page exported with it reopens at 10 m. -/// A value that isn't a boolean is refused. +/// `longPagesInPoints` is on by default: a 10 m page exported without options is written in +/// points and reopens at 10 m. Turned off, it is saved with a preset, comes back through a presets +/// file and the preferences, shows in `document.pdfSettings`, and the page exported with it has a +/// `UserUnit` and reopens at 10 m. A value that isn't a boolean is refused. #[test] fn long_pages_in_points_round_trips_through_presets_and_reopens_at_full_size() { let mut s = Session::new(); s.execute("file.new", &json!({"width": 28_346.456_692_913_386, "height": 2_834.645_669_291_338_5})).unwrap(); - s.execute("pdf.preset.save", &json!({"name": "Banner", "longPagesInPoints": true, "preserveEditing": false})).unwrap(); - assert!(s.prefs.pdf_presets[0].settings.long_pages_in_points); + let reopened = |bytes: &[u8]| { + let mut o = Session::new(); + o.execute("document.open", &json!({"name": "banner.pdf", "dataBase64": vectorcraft_format::base64_encode(bytes)})).unwrap(); + let rect = o.doc().unwrap().doc.artboards[0].rect; + assert!((rect.width() - 28_346.46).abs() < 0.01 && (rect.height() - 2_834.65).abs() < 0.01, "{rect:?}"); + }; + let warned = |v: &Value, end: &str| v["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().ends_with(end)); + // By default the page is written in points. + assert_eq!(s.execute("document.pdfSettings", &json!({})).unwrap()["settings"]["longPagesInPoints"], json!(true)); + let v = s.execute("document.exportPdf", &json!({"preserveEditing": false})).unwrap(); + let bytes = pdf(&v); + assert!(!String::from_utf8_lossy(&bytes).contains("/UserUnit")); + assert!(warned(&v, "written without a UserUnit, in points, and apps that keep to the limit cut the page to 200 in"), "{v}"); + reopened(&bytes); + // Off in a preset. + s.execute("pdf.preset.save", &json!({"name": "Banner", "longPagesInPoints": false, "preserveEditing": false})).unwrap(); + assert!(!s.prefs.pdf_presets[0].settings.long_pages_in_points); let back: crate::Prefs = serde_json::from_value(s.prefs.to_json()).unwrap(); assert_eq!(back.pdf_presets, s.prefs.pdf_presets); let text = s.execute("pdf.preset.export", &json!({"names": ["Banner"]})).unwrap()["data"].as_str().unwrap().to_string(); let mut t = session(); t.execute("pdf.preset.import", &json!({"data": text})).unwrap(); assert_eq!(t.prefs.pdf_presets, s.prefs.pdf_presets); - let v = s.execute("document.pdfSettings", &json!({"longPagesInPoints": true})).unwrap(); - assert_eq!((&v["settings"]["longPagesInPoints"], &v["changed"]), (&json!(true), &json!([{"option": "longPagesInPoints", "value": true}])), "{v}"); - assert_eq!(s.execute("document.pdfSettings", &json!({})).unwrap()["settings"]["longPagesInPoints"], json!(false)); - // The preset writes the page in points; the file reopens at 10 m. - let v = s.execute("document.exportPdf", &json!({"preset": "Banner"})).unwrap(); - let bytes = pdf(&v); - assert!(!String::from_utf8_lossy(&bytes).contains("/UserUnit")); - assert!( - v["warnings"] - .as_array() - .unwrap() - .iter() - .any(|w| w.as_str().unwrap().ends_with("written without a UserUnit, in points, and apps that keep to the limit cut the page to 200 in")), + let v = s.execute("document.pdfSettings", &json!({"longPagesInPoints": false})).unwrap(); + assert_eq!( + (&v["settings"]["longPagesInPoints"], &v["changed"]), + (&json!(false), &json!([{"option": "longPagesInPoints", "value": false}])), "{v}" ); - let mut o = Session::new(); - o.execute("document.open", &json!({"name": "banner.pdf", "dataBase64": vectorcraft_format::base64_encode(&bytes)})).unwrap(); - let rect = o.doc().unwrap().doc.artboards[0].rect; - assert!((rect.width() - 28_346.46).abs() < 0.01 && (rect.height() - 2_834.65).abs() < 0.01, "{rect:?}"); + // The preset writes the page with a `UserUnit`; the file reopens at 10 m. + let v = s.execute("document.exportPdf", &json!({"preset": "Banner"})).unwrap(); + let bytes = pdf(&v); + assert!(String::from_utf8_lossy(&bytes).contains("/UserUnit 1.969")); + assert!(warned(&v, "it is written with a UserUnit of 1.969, so apps that ignore UserUnit show it that many times smaller"), "{v}"); + reopened(&bytes); for bad in [json!("yes"), json!(1)] { assert!(is_bad_params(s.execute("document.exportPdf", &json!({"longPagesInPoints": bad}))), "{bad}"); assert!(is_bad_params(s.execute("pdf.preset.save", &json!({"name": "Bad", "longPagesInPoints": bad}))), "{bad}"); diff --git a/crates/pdf/src/settings.rs b/crates/pdf/src/settings.rs index 710037a7c1..adaaa30c9c 100644 --- a/crates/pdf/src/settings.rs +++ b/crates/pdf/src/settings.rs @@ -217,7 +217,7 @@ choice! { } /// Save PDF settings (the dialog's sections; what a preset stores). -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(default, rename_all = "camelCase")] pub struct PdfSettings { pub standard: Standard, @@ -237,9 +237,9 @@ pub struct PdfSettings { /// `create_layers` is on). pub include_non_printing: bool, /// Write a page with a side longer than 14,400 pt (200 in) at its size in points, without a - /// `UserUnit`, at every PDF version, in files without a standard (off, and in PDF/A files: - /// PDF 1.6 and later files that aren't PDF/X files write it with a `UserUnit`, and PDF 1.5 - /// files are written as PDF 1.6 for it). + /// `UserUnit`, at every PDF version, in files without a standard (on by default; off, and in + /// PDF/A files: PDF 1.6 and later files that aren't PDF/X files write it with a `UserUnit`, + /// and PDF 1.5 files are written as PDF 1.6 for it). pub long_pages_in_points: bool, pub compression: CompressionSettings, pub marks: MarkSettings, @@ -253,6 +253,29 @@ pub struct PdfSettings { pub flattener_preset: String, } +impl Default for PdfSettings { + fn default() -> Self { + Self { + standard: Standard::default(), + compatibility: Compatibility::default(), + preserve_editing: false, + thumbnails: false, + fast_web_view: false, + view_after_saving: false, + create_layers: false, + include_non_printing: false, + long_pages_in_points: true, + compression: CompressionSettings::default(), + marks: MarkSettings::default(), + bleed: BleedSettings::default(), + output: OutputSettings::default(), + advanced: AdvancedSettings::default(), + security: SecuritySettings::default(), + flattener_preset: String::new(), + } + } +} + /// Resampling and compression of one kind of image. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(default, rename_all = "camelCase")] diff --git a/crates/pdf/src/tests/marks.rs b/crates/pdf/src/tests/marks.rs index 655ed43ea4..4693b4c44b 100644 --- a/crates/pdf/src/tests/marks.rs +++ b/crates/pdf/src/tests/marks.rs @@ -105,8 +105,9 @@ fn units_and_media(bytes: &[u8]) -> Vec<(f32, Rect)> { } /// A page with a side longer than ISO 32000-1's 14,400 units is written in larger units (its -/// `UserUnit`), so that its sides are 14,400 units at most, and reads back at its size in points. -/// Pages up to 14,400 pt, files before PDF 1.6 and PDF/X files keep their sizes in points. +/// `UserUnit`), so that its sides are 14,400 units at most, and reads back at its size in points, +/// with `longPagesInPoints` off. Pages up to 14,400 pt, files before PDF 1.6 and PDF/X files keep +/// their sizes in points. #[test] fn a_page_past_14400_pt_is_written_with_a_user_unit_and_reads_back_at_its_size() { let mut d = doc(); @@ -117,7 +118,7 @@ fn a_page_past_14400_pt_is_written_with_a_user_unit_and_reads_back_at_its_size() small.rect = Rect::new(0.0, 12_000.0, 20_000.0, 12_001.0); d.artboards.push(small); let near = |a: Rect, b: Rect| [a.x0 - b.x0, a.y0 - b.y0, a.x1 - b.x1, a.y1 - b.y1].iter().all(|d| d.abs() < 0.01); - let bytes = pdf(&d, json!({})); + let bytes = pdf(&d, json!({"longPagesInPoints": false})); let pages = units_and_media(&bytes); // 20,000 / 14,400 = 1.3889, rounded up to 1.389: the page is 14,398.85 × 7,199.42 units. assert_eq!(pages[0].0, 1.389, "{pages:?}"); @@ -155,6 +156,12 @@ fn report(d: &Document, set: PdfSettings) -> Result { export_with_report(d, &PdfOptions { settings: set, created: Some(1_791_200_000), ..PdfOptions::uncompressed() }) } +/// The default settings with `long_pages_in_points` off: long pages from PDF 1.6 on get a +/// `UserUnit`. +fn user_units() -> PdfSettings { + PdfSettings { long_pages_in_points: false, ..PdfSettings::default() } +} + /// The numbers that follow `key` in the file's bytes (`/MediaBox [0 0 w h]`, `/UserUnit u`), read /// as text, without the PDF reader: none when the file has no `key`. fn raw_numbers(bytes: &[u8], key: &str, count: usize) -> Vec { @@ -178,13 +185,13 @@ fn long_page_warnings(r: &ExportReport) -> Vec<&String> { r.warnings.iter().filter(|w| w.contains("page limit of 14,400 pt")).collect() } -/// A 20 m page at PDF 1.7 (the default) is written with a `UserUnit` of 3.938, reads back at 20 m -/// from the file's bytes, through the PDF reader and through the import, and the export says how -/// it is written. +/// A 20 m page at PDF 1.7 (the default) with `long_pages_in_points` off is written with a +/// `UserUnit` of 3.938, reads back at 20 m from the file's bytes, through the PDF reader and +/// through the import, and the export says how it is written. #[test] fn a_20_m_page_keeps_its_size_with_a_user_unit_and_the_export_says_so() { let d = sized(TWENTY_M, TWENTY_M / 20.0); - let r = report(&d, PdfSettings::default()).unwrap(); + let r = report(&d, user_units()).unwrap(); assert!(r.bytes.starts_with(b"%PDF-1.7")); assert_eq!( long_page_warnings(&r), @@ -209,7 +216,7 @@ fn a_20_m_page_keeps_its_size_with_a_user_unit_and_the_export_says_so() { /// Every built-in preset and every PDF version keeps a 20 m page at its size, or refuses it with /// the reason: PDF 1.3 and 1.4 files (PDF/X-1a and PDF/X-3 among them) have no `UserUnit` and /// hold no real number past 32,767, PDF 1.5 is written as PDF 1.6 to have one, and PDF/X-4 pages -/// at PDF 1.5 or 1.6 stay in points with a warning. +/// at PDF 1.5 or 1.6 stay in points with a warning (with `long_pages_in_points` off). #[test] fn every_preset_and_version_keeps_a_20_m_page_or_says_why_not() { let d = sized(TWENTY_M, TWENTY_M / 20.0); @@ -223,7 +230,7 @@ fn every_preset_and_version_keeps_a_20_m_page_or_says_why_not() { }; for preset in crate::builtin_presets() { let name = preset.name.as_str(); - match report(&d, preset.settings.clone()) { + match report(&d, PdfSettings { long_pages_in_points: false, ..preset.settings.clone() }) { Err(e) if matches!(name, "PDF/X-1a:2001" | "PDF/X-3:2002") => refused(e, name), Err(e) => panic!("{name}: {e}"), Ok(r) if name == "PDF/X-4:2010" => { @@ -241,7 +248,7 @@ fn every_preset_and_version_keeps_a_20_m_page_or_says_why_not() { } } for c in Compatibility::ALL.iter().copied() { - let set = PdfSettings { compatibility: c, ..PdfSettings::default() }; + let set = PdfSettings { compatibility: c, ..user_units() }; match (c, report(&d, set)) { (Compatibility::Pdf13 | Compatibility::Pdf14, Err(e)) => refused(e, c.label()), (Compatibility::Pdf13 | Compatibility::Pdf14, Ok(_)) => panic!("{} is refused", c.label()), @@ -362,7 +369,7 @@ fn the_error_names_the_long_page_whose_art_needs_a_larger_real() { #[test] fn a_page_too_narrow_for_its_user_unit_keeps_3_units_on_its_short_side() { const MM: f64 = 72.0 / 25.4; - for set in [PdfSettings::default(), PdfSettings { standard: Standard::PdfA2b, ..PdfSettings::default() }] { + for set in [user_units(), PdfSettings { standard: Standard::PdfA2b, ..PdfSettings::default() }] { let r = report(&sized(TWENTY_M * 5.0, 4.0 * MM), set).unwrap(); assert_eq!(raw_numbers(&r.bytes, "/UserUnit", 1), [3.779]); let media = raw_numbers(&r.bytes, "/MediaBox", 4); @@ -377,11 +384,11 @@ fn a_page_too_narrow_for_its_user_unit_keeps_3_units_on_its_short_side() { assert!(long_page_warnings(&r).is_empty(), "{:?}", r.warnings); } // A short side of 3 units or more at the long side's unit keeps that unit. - let r = report(&sized(TWENTY_M * 5.0, 60.0), PdfSettings::default()).unwrap(); + let r = report(&sized(TWENTY_M * 5.0, 60.0), user_units()).unwrap(); assert_eq!(raw_numbers(&r.bytes, "/UserUnit", 1), [19.686]); let media = raw_numbers(&r.bytes, "/MediaBox", 4); assert!(media[3] - media[1] >= 3.0, "{media:?}"); - let r = report(&sized(TWENTY_M * 5.0, 2.0), PdfSettings::default()).unwrap(); + let r = report(&sized(TWENTY_M * 5.0, 2.0), user_units()).unwrap(); assert_eq!(raw_numbers(&r.bytes, "/UserUnit", 1), [19.686]); } @@ -389,7 +396,7 @@ fn a_page_too_narrow_for_its_user_unit_keeps_3_units_on_its_short_side() { /// the Save PDF dialog shows it. #[test] fn a_pdf_1_5_file_written_as_1_6_keeps_rc4_encryption() { - let mut set = PdfSettings { compatibility: Compatibility::Pdf15, ..PdfSettings::default() }; + let mut set = PdfSettings { compatibility: Compatibility::Pdf15, ..user_units() }; set.security.open_password = "secret".into(); let has = |bytes: &[u8], s: &[u8]| bytes.windows(s.len()).any(|w| w == s); let r = report(&sized(TWENTY_M, 300.0), set).unwrap(); @@ -408,7 +415,7 @@ fn the_long_page_warning_rounds_the_size_up() { /// point longer gets a `UserUnit` of 1.001 and the warning, and stays in points at PDF 1.4. #[test] fn a_page_of_14400_pt_stays_in_points_and_one_point_more_does_not() { - let at = |side: f64, c: Compatibility| report(&sized(side, 300.0), PdfSettings { compatibility: c, ..PdfSettings::default() }); + let at = |side: f64, c: Compatibility| report(&sized(side, 300.0), PdfSettings { compatibility: c, ..user_units() }); for c in [Compatibility::Pdf14, Compatibility::Pdf15, Compatibility::Pdf17] { let r = at(14_400.0, c).unwrap(); assert!(long_page_warnings(&r).is_empty() && !r.warnings.iter().any(|w| w.contains("UserUnit")), "{}: {:?}", c.label(), r.warnings); @@ -455,13 +462,14 @@ fn a_page_within_14400_pt_is_written_as_before_at_every_version() { /// 10 m in points. const TEN_M: f64 = 10.0 / 0.0254 * 72.0; -/// With `long_pages_in_points`, a 10 m page at PDF 1.7 is written at its size in points, with no -/// `UserUnit`, the warning says so, and the page reads back at 10 m. Without it the page keeps -/// its `UserUnit`. +/// With `long_pages_in_points` (on by default), a 10 m page at PDF 1.7 is written at its size in +/// points, with no `UserUnit`, the warning says so, and the page reads back at 10 m. Without it the +/// page keeps its `UserUnit`. #[test] fn long_pages_in_points_writes_a_10_m_page_in_points() { let d = sized(TEN_M, TEN_M / 10.0); - let r = report(&d, PdfSettings { long_pages_in_points: true, ..PdfSettings::default() }).unwrap(); + assert!(settings(json!({})).long_pages_in_points, "on by default"); + let r = report(&d, PdfSettings::default()).unwrap(); assert!(r.bytes.starts_with(b"%PDF-1.7")); assert_eq!(raw_numbers(&r.bytes, "/UserUnit", 1), Vec::::new()); let media = raw_numbers(&r.bytes, "/MediaBox", 4); @@ -479,13 +487,12 @@ fn long_pages_in_points_writes_a_10_m_page_in_points() { let back = import(&r.bytes).unwrap(); let rect = back.artboards[0].rect; assert!((rect.width() - TEN_M).abs() < 0.01 && (rect.height() - TEN_M / 10.0).abs() < 0.01, "{rect:?}"); - // Off (the default), the page has a `UserUnit` of 28,346.46 / 14,400, rounded up. - let off = report(&d, PdfSettings::default()).unwrap(); + // Off, the page has a `UserUnit` of 28,346.46 / 14,400, rounded up. + let off = report(&d, user_units()).unwrap(); assert_eq!(raw_numbers(&off.bytes, "/UserUnit", 1), [1.969]); assert!( long_page_warnings(&off)[0].ends_with("it is written with a UserUnit of 1.969, so apps that ignore UserUnit show it that many times smaller") ); - assert!(!settings(json!({})).long_pages_in_points, "off by default"); } /// With `long_pages_in_points`, every PDF version writes a 10 m page in points: PDF 1.5 stays @@ -496,7 +503,7 @@ fn long_pages_in_points_keeps_every_version_and_changes_nothing_where_pages_are_ let d = sized(TEN_M, TEN_M / 10.0); let with = |set: &PdfSettings| PdfSettings { long_pages_in_points: true, ..set.clone() }; for c in Compatibility::ALL.iter().copied() { - let set = PdfSettings { compatibility: c, ..PdfSettings::default() }; + let set = PdfSettings { compatibility: c, ..user_units() }; let r = report(&d, with(&set)).unwrap(); assert!(r.bytes.starts_with(format!("%PDF-{}", c.id()).as_bytes()), "{}", c.label()); assert_eq!(raw_numbers(&r.bytes, "/UserUnit", 1), Vec::::new(), "{}", c.label()); @@ -520,7 +527,7 @@ fn pdfa2b_long_page_stays_within_14400_units() { let d = sized(TEN_M, TEN_M / 10.0); for s in Standard::ALL.iter().copied().filter(|s| *s != Standard::None && !s.is_pdfx()) { for c in Compatibility::ALL.iter().copied().filter(|c| s.allows(*c)) { - let off = PdfSettings { standard: s, compatibility: c, ..PdfSettings::default() }; + let off = PdfSettings { standard: s, compatibility: c, ..user_units() }; let on = PdfSettings { long_pages_in_points: true, ..off.clone() }; let (on, off) = (report(&d, on).unwrap(), report(&d, off).unwrap()); assert_eq!(on.bytes, off.bytes, "{} {}", s.label(), c.label()); @@ -540,7 +547,7 @@ fn pdfa2b_long_page_stays_within_14400_units() { fn long_pages_in_points_leaves_a_page_within_14400_pt_as_it_is() { let d = sized(14_400.0, 300.0); for c in Compatibility::ALL.iter().copied() { - let off = PdfSettings { compatibility: c, ..PdfSettings::default() }; + let off = PdfSettings { compatibility: c, ..user_units() }; let on = PdfSettings { long_pages_in_points: true, ..off.clone() }; let (off, on) = (report(&d, off).unwrap(), report(&d, on).unwrap()); assert_eq!(on.bytes, off.bytes, "{}", c.label()); diff --git a/crates/ui-egui/src/dialogs/save_pdf/tests.rs b/crates/ui-egui/src/dialogs/save_pdf/tests.rs index a3a6cc4768..fda9e78cc5 100644 --- a/crates/ui-egui/src/dialogs/save_pdf/tests.rs +++ b/crates/ui-egui/src/dialogs/save_pdf/tests.rs @@ -251,14 +251,14 @@ fn long_page_notes_are_translated() { let mut s = Session::new(); s.execute("file.new", &json!({"width": 56_692.91, "height": 2_834.65})).unwrap(); let mut notes: Vec = vec![]; - for p in [json!({"compatibility": "1.5"}), json!({"preset": "PDF/X-4:2010"})] { + for p in [json!({"compatibility": "1.5", "longPagesInPoints": false}), json!({"preset": "PDF/X-4:2010"})] { let r = s.execute("document.exportPdf", &p).unwrap(); let warnings = r["warnings"].as_array().unwrap().iter().filter_map(|w| w.as_str()); notes.extend(warnings.filter(|w| w.contains("14,400 pt")).map(str::to_string)); } notes.push(s.execute("document.exportPdf", &json!({"preset": "PDF/X-1a:2001"})).unwrap_err().to_string()); s.execute("file.new", &json!({"width": 85_040, "height": 17})).unwrap(); - let r = s.execute("document.exportPdf", &json!({})).unwrap(); + let r = s.execute("document.exportPdf", &json!({"longPagesInPoints": false})).unwrap(); let warnings = r["warnings"].as_array().unwrap().iter().filter_map(|w| w.as_str()); notes.extend(warnings.filter(|w| w.contains("too long and narrow")).map(str::to_string)); assert_eq!(notes.len(), 5, "{notes:?}"); diff --git a/crates/ui-egui/src/dialogs/tests_export.rs b/crates/ui-egui/src/dialogs/tests_export.rs index 117e83277c..ca37940601 100644 --- a/crates/ui-egui/src/dialogs/tests_export.rs +++ b/crates/ui-egui/src/dialogs/tests_export.rs @@ -205,7 +205,8 @@ fn svg_continues_in_svg_options() { /// Without Use Artboards, a PDF continues in Save PDF too, without its artboard choice, and the /// file is one page of the art's bounds. Its options apply: a drawing 10 m long is written at -/// full size in points with "Write pages longer than 200 in at full size in points". +/// full size in points with "Write pages longer than 200 in at full size in points" (on by +/// default), and with a `UserUnit` without it. #[test] fn pdf_art_continues_in_the_save_pdf_dialog() { let (mut app, written) = app(2); @@ -223,13 +224,22 @@ fn pdf_art_continues_in_the_save_pdf_dialog() { app.run("shape.rectangle", json!({"x": 0, "y": 100, "width": 28_346.46, "height": 50})).unwrap(); app.run("file.exportAs", json!({"format": "pdf"})).unwrap(); confirm(&mut app).unwrap(); - set(&mut app, "longPagesInPoints", json!(true)); frame(&mut app); confirm(&mut app).unwrap(); let bytes = written.borrow()[1].1.clone(); assert!(!String::from_utf8_lossy(&bytes).contains("/UserUnit")); let width = vectorcraft_pdf::import(&bytes).unwrap().artboards[0].rect.width(); assert!((28_346.0..28_350.0).contains(&width), "{width}"); + + app.run("file.exportAs", json!({"format": "pdf"})).unwrap(); + confirm(&mut app).unwrap(); + set(&mut app, "longPagesInPoints", json!(false)); + frame(&mut app); + confirm(&mut app).unwrap(); + let bytes = written.borrow()[2].1.clone(); + assert!(String::from_utf8_lossy(&bytes).contains("/UserUnit")); + let width = vectorcraft_pdf::import(&bytes).unwrap().artboards[0].rect.width(); + assert!((28_346.0..28_350.0).contains(&width), "{width}"); } #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 274db05a34..4701eb87c7 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1036,7 +1036,8 @@ and `flattener` options over it (as `object.flattenTransparency` takes them); im transparency and rasterized areas are clipped to their regions. Layers the file leaves out (non-printing ones, unless `includeNonPrinting` or `createLayers` is set) are left out of the flattening. A file that would still have transparency fails the export. PDF/X-1a and PDF/X-3 files are PDF 1.3 files too. -A page with a side longer than 14,400 pt is written with a `UserUnit` (PDF 1.6): its longer side divided by 14,400, +In PDF/A-2b files, `.ai` saves and files written with `longPagesInPoints: false`, a page with a side longer than +14,400 pt is written with a `UserUnit` (PDF 1.6): its longer side divided by 14,400, rounded up to the next thousandth, with the page's sizes and coordinates in those units, so that no side is longer than 14,400 units (ISO 32000-1, Annex C.2). A PDF 1.5 file with such a page is written as PDF 1.6, with a warning, and keeps PDF 1.5's encryption (128-bit RC4). A PDF/A-2b file at PDF 1.4 with such a page is written as PDF 1.6 too, with a @@ -1045,9 +1046,10 @@ unless the page is too narrow for that (below) ([veraPDF rule 6.1.13-11](https://github.com/veraPDF/veraPDF-validation-profiles/wiki/PDFA-Parts-2-and-3-rules#rule-6113-11); PDF/A-2 files may declare PDF 1.0 to 1.7, [rule 6.1.2-1](https://github.com/veraPDF/veraPDF-validation-profiles/wiki/PDFA-Parts-2-and-3-rules#rule-612-1)). PDF/X files and other PDF 1.3 and 1.4 files write such a page in points, and apps -that keep to the limit cut it to 200 in. `longPagesInPoints: true` (off by default; "Write pages longer than 200 in at +that keep to the limit cut it to 200 in. `longPagesInPoints` (on by default; "Write pages longer than 200 in at full size in points" in the Save PDF dialog's General section) writes such a page in points at every PDF version, without -a `UserUnit`, and a PDF 1.5 file stays PDF 1.5; the warning then says the page is written in points. The option applies +a `UserUnit`, and a PDF 1.5 file stays PDF 1.5; the warning then says the page is written in points. Readers that +ignore `UserUnit` show such a page at its full size. The option applies only to files without a standard: PDF/X files write such a page in points anyway, and PDF/A files keep the `UserUnit`, which keeps their page boundaries within PDF/A-2's limit of 14,400 units (ISO 19005-2, 6.1.13), a PDF/A file at PDF 1.4 included (written as PDF 1.6). The dialog disables the diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f04ee3c910..94c63e2e85 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1573,7 +1573,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur In a `.ai` opened from its editing data, an envelope made with a warp, a mesh or a top object opens as a live envelope of its contents, with its warp style, bend and distortions, its mesh points and handles or its top object's outline, its Envelope Options, its Fidelity and whether its contents are being edited. When Distort Appearance is on and the size the file saves for the contents matches their bounds with strokes, the contents map from that stroked box, until an edit in Edit Contents changes how far the strokes reach; VectorCraft's new envelopes map from the geometric box, as do contents with no width or no height, such as a single straight line. An envelope that can't be read, or that VectorCraft draws differently from the file's drawn art, keeps that drawn art, with a note. An envelope of type opens live, its type laid out from the text document as its contents, where VectorCraft's own envelope of that type draws as the drawn art the file saves (compared as for the other envelopes, seen on white and on black, so white type counts, and only where the layers with it are compared with the page and draw as it, the envelope weighed as the art it draws); elsewhere, and where the type's font isn't available, a text or visibility variable binds the type, or the envelope is in a symbol's or a pattern's art, it keeps its drawn art, with its type hidden and a note that says the type isn't editable (#3179; `crates/eps/src/import/ai/tests.rs`, `crates/eps/src/import/tests_native.rs`). A warp of type whose own warp, VectorCraft's, doesn't draw as its drawn art is tried again as a mesh envelope on the grid the file saves for it: its type stays editable and keeps the file's shape, but the warp's settings (style, bend) are lost, as the document has no place for them on a mesh. Type with strokes in an envelope with Distort Appearance on is also tried mapped from its glyphs grown by as far as its strokes paint along a side (half the weight of a centred stroke), without what miter joins add at corners, where the size the file saves for it doesn't already give that box; after those tries (and before a grid moved onto its drawn art), it is also tried mapped from the box of what it paints, where that is another box, as users' files map some such type: its glyph outlines with their fills and strokes baked as the envelope bakes them, so geometry effects on them count (a stroke a Transform effect moves paints where it is moved to), each measured by its visual bounds (exact for miter joins, a tip counting where the miter limit keeps it, and for round joins; an upper bound for bevel joins, miters the limit cuts, width profiles and square-capped dashes), and a contour of zero length, which paints nothing, left out; effects on the type object itself are left out, as VectorCraft applies them after the envelope bends the type. The drawn-art check decides which one opens. An envelope's grid reads its way round from all its rows and columns, so a mesh bent far round reads the way it runs. While an envelope's contents are edited, its mesh is kept in its dictionary, and in some files that mesh lies away from the drawn art by a move, the contents with the drawn art (as if the mesh hadn't followed the envelope when it moved): a mesh or top object saved in Edit Contents whose mesh draws the contents as large as the drawn art but elsewhere is tried again, after every other way, with its mesh moved onto that art, and opens there where it then draws as it. The drawn art of these files strokes type in an envelope along its bent outlines at the stroke's own weight, Distort Appearance on or off, and VectorCraft draws it so (#6644): an envelope of stroked type whose grid squeezes or stretches it opens live where it draws as that art. In a `.ai` opened from its editing data, Convert to Shape on a whole path or type object opens as a live Rectangle, Rounded Rectangle or Ellipse effect with its Absolute or Relative size, its corner radius, its place among the object's effects and whether it is hidden. A relative size in the file is added to each side. A relative Ellipse, or a setting VectorCraft doesn't read, keeps the drawn art (`crates/eps/src/import/ai/style/tests.rs`, `crates/eps/src/import/ai/tests.rs`, `crates/eps/src/import/tests_native.rs`). In a `.ai` opened from its editing data, Bas Relief in an art style takes its Detail, Smoothness and Light direction from the style's settings block, and an object other than type with it opens as itself with the live effect. A settings block that VectorCraft can't read (malformed, another effect's, a value out of range or a key it doesn't know) keeps the object's drawn look (part of #637; [raster effects reference](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-filter-effects/raster-effects-reference.html), [Photoshop File Formats Specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/), [scripting the filter gallery](https://community.adobe.com/questions-712/scripting-support-for-the-filter-gallery-1064646); `crates/eps/src/import/ai/style/tests.rs`, `crates/eps/src/import/ai/tests.rs`). - PDF export and `.ai` saves write a page with a side longer than 14,400 pt with a `UserUnit` (PDF 1.6), its longer side divided by 14,400 and rounded up to the next thousandth, so that no side is longer than 14,400 units (ISO 32000-1, Annex C.2); a PDF 1.5 file with such a page is written as PDF 1.6 with PDF 1.5's encryption, PDF/X files and PDF 1.3 and 1.4 files write it in points (in PDF 1.3 and 1.4, a page past 32,767 pt that needs a real number past 32,767 is refused with an error naming it), a page whose short side is 3 pt or longer but would be under 3 units at that `UserUnit` gets a smaller one that keeps the short side at 3 units, and the export's warnings give each such page's size and how it is written (#6382). The Save PDF dialog's "Write pages longer than 200 in at full size in points" (`longPagesInPoints`, off by default) writes such pages in points without a `UserUnit` at every PDF version, in files without a PDF/X or PDF/A standard. + PDF export and `.ai` saves write a page with a side longer than 14,400 pt with a `UserUnit` (PDF 1.6), its longer side divided by 14,400 and rounded up to the next thousandth, so that no side is longer than 14,400 units (ISO 32000-1, Annex C.2); a PDF 1.5 file with such a page is written as PDF 1.6 with PDF 1.5's encryption, PDF/X files and PDF 1.3 and 1.4 files write it in points (in PDF 1.3 and 1.4, a page past 32,767 pt that needs a real number past 32,767 is refused with an error naming it), a page whose short side is 3 pt or longer but would be under 3 units at that `UserUnit` gets a smaller one that keeps the short side at 3 units, and the export's warnings give each such page's size and how it is written (#6382). The Save PDF dialog's "Write pages longer than 200 in at full size in points" (`longPagesInPoints`, on by default; `.ai` saves leave it off) writes such pages in points without a `UserUnit` at every PDF version, in files without a PDF/X or PDF/A standard, so readers that ignore `UserUnit` show them at full size. Export As PDF with Use Artboards off also opens the Save PDF dialog, without its Artboards section, and writes one page of the visible art's bounds with the dialog's options (`document.exportPdf {useArtboards: false}`; `crates/ui-egui/src/dialogs/tests_export.rs`, `crates/engine/src/cmd/fileio/tests_pdf.rs`). PDF export warns when a PDF/X file has no bleed on a side where the document's bleed has one, and writes the file as asked. A PDF/A-2b export at PDF 1.4 with a page longer than 14,400 pt is written as PDF 1.6 with a `UserUnit` and a warning, whether or not `longPagesInPoints` is on, so its page boundaries stay within PDF/A-2's limit of 14,400 units (ISO 19005-2, 6.1.13) unless the page is too narrow for that (`crates/pdf/src/tests/marks.rs`). From d9ebfa53e6935b90623fe828b3d312b2a3c70a85 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 08:11:26 -0800 Subject: [PATCH 20/25] Docs: the quit's clipboard handle order holds only when the check lets go in time --- docs/target-app-parity.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index dedcd6930a..64ae76d692 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1633,7 +1633,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - `file.print`, `print.preview` and `print.setup` take a print preset by name (`preset`: `[Default]` or a saved preset, in any case): its settings are used instead of the document's, with `settings` over them, `print.setup` saves them with the document, and an unknown name is refused with the list of presets. - Print's Copies per Sheet (`copiesPerSheet`, `gutter`; off by default) prints as many copies of each artboard, with its bleed and marks, as fit the imageable area, across then down, as one grid placed like a single copy; the preview shows them, and an artboard that does not fit prints one copy per sheet with a warning (#1283). - Place and the Links panel, Package (placed `.vectorcraft` documents packaged with their own linked files and fonts, relinked to the copies: #777), File Info, Print with print presets, PostScript output and print tiling, slices and Save for Web, Export for Screens and Asset Export, CSS Properties, PNG/PDF/SVG/text clipboard flavours; files copied in a file manager paste as art (SVG, PDF, EMF/WMF, bitmaps) on every desktop platform, and Linux/Wayland reads the compositor's clipboard (#398); on Linux the Paste menu checks the clipboard off the UI thread, so an X11 owner that never answers can't freeze the window (#510); screenshots and other copied pictures paste as embedded images at the view centre everywhere, the web included (#457). - - On X11, quitting while the Paste menu's background check waits on a clipboard owner that never answers waits up to 27 s for that check to drop its clipboard handle, so the app's own handle is still the last one dropped; the window is hidden before that wait, so an X11 window closes at once (`crates/ui-egui/src/tests/sysclip_probe.rs`, `apps/vectorcraft/src/clipboard.rs`, `apps/vectorcraft/src/tests.rs`). + - On X11, quitting while the Paste menu's background check waits on a clipboard owner that never answers waits up to 27 s for that check to drop its clipboard handle, so the app's own handle is the last one dropped when the check drops its handle within that wait, and the app quits after the wait when it has not; the window is hidden before that wait, so an X11 window closes at once (`crates/ui-egui/src/tests/sysclip_probe.rs`, `apps/vectorcraft/src/clipboard.rs`, `apps/vectorcraft/src/tests.rs`). - File › Place reads RTF files as area type with their formatting: each run's font, size, bold and italic, underline, strikethrough, caps, superscript or subscript, baseline shift and color, and each paragraph's alignment, indents, space before and after and direction. Table cells are separated by tabs; hidden text, pictures, headers, footers and notes are left out (`file.place`, `crates/engine/src/tests/textimport.rs`). - File › Place reads Word `.docx` documents as area type with the same formatting, taken from the document defaults, the paragraph and character styles (their toggle properties reversing each other) and direct formatting, the theme's fonts included. Table rows are paragraphs with their cells separated by tabs; hidden and deleted text, field instructions, pictures, headers, footers and notes are left out (`file.place`, `crates/engine/src/tests/textimport.rs`). - A Word paragraph justified with a low, medium or high kashida length places justified with Insert Kashidas set to Short, Medium or Long (`file.place`, `crates/engine/src/tests/textimport.rs`). From e11c21ce98b10e42e582f659670d839226e04725 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 08:19:07 -0800 Subject: [PATCH 21/25] MCP: an old app's window capture goes through a private temporary folder An app that does not send the image back wrote the window capture to vectorcraft-window-.png directly in the system's temporary folder. On a shared Unix temporary folder another user could put a link at that name, and the app would then overwrite the file it points to. A failed read also left the file behind. The capture now goes to window.png in a new folder made for it inside the temporary folder (owner-only on Unix; a name that is taken is skipped). The folder is removed after the read, also when the app or the read fails. --- crates/mcp/src/tests/conventions.rs | 78 +++++++++++++++++++++++++++++ crates/mcp/src/tools/handlers.rs | 46 ++++++++++++++--- docs/mcp.md | 2 +- docs/target-app-parity.md | 1 + 4 files changed, 120 insertions(+), 7 deletions(-) diff --git a/crates/mcp/src/tests/conventions.rs b/crates/mcp/src/tests/conventions.rs index 0b7352bf4a..3618f9214f 100644 --- a/crates/mcp/src/tests/conventions.rs +++ b/crates/mcp/src/tests/conventions.rs @@ -313,6 +313,84 @@ fn window_captures_take_max_side() { assert!(r["content"][0]["text"].as_str().unwrap().contains("`scale`"), "{r}"); } +/// The path an app from before `ui.screenshot {data}` was sent, with the mode of the folder holding +/// it on unix (`None` elsewhere). +type SeenPaths = std::sync::Arc)>>>; + +/// An app from before `ui.screenshot {data}`: it writes `png` (nothing when `None`) to the `path` +/// it is sent, keeps the path in `seen` and answers `reply`. A capture without a path is answered +/// with its size alone. +struct OldWindow { + png: Option>, + reply: Result, + seen: SeenPaths, +} +impl Backend for OldWindow { + fn call(&mut self, method: &str, p: Value) -> Result { + if method != "ui.screenshot" { + return Err(format!("unexpected {method}")); + } + // Without a path it ignores `data` and sends the size alone. + let Some(path) = p["path"].as_str().map(str::to_owned) else { return Ok(json!({"width": 2, "height": 1})) }; + #[cfg(unix)] + let mode = { + use std::os::unix::fs::PermissionsExt as _; + std::path::Path::new(&path).parent().and_then(|d| std::fs::metadata(d).ok()).map(|m| m.permissions().mode() & 0o777) + }; + #[cfg(not(unix))] + let mode = None; + self.seen.lock().unwrap().push((path.clone(), mode)); + if let Some(png) = &self.png { + std::fs::write(&path, png).map_err(|e| format!("{path}: {e}"))?; + } + self.reply.clone() + } + fn has_ui(&self) -> bool { + true + } + fn describe(&self) -> String { + "old window".into() + } +} + +/// An app without `ui.screenshot {data}` writes the window capture to a file in a new folder of its +/// own inside the system's temporary folder (owner-only on unix), never to a fixed name in the +/// shared folder itself. The folder is removed after the capture is read, and also when the app +/// fails after writing it or the file can't be read. +#[test] +fn an_old_app_captures_the_window_in_a_new_private_folder() { + let temp = std::env::temp_dir(); + let png = b"window capture".to_vec(); + let size = json!({"width": 2, "height": 1}); + let mut folders = Vec::new(); + for (written, reply, ok) in [ + (Some(png.clone()), Ok(size.clone()), true), + (Some(png.clone()), Ok(size.clone()), true), + (Some(png.clone()), Err("the capture failed".to_string()), false), + (None, Ok(size.clone()), false), + ] { + let seen = SeenPaths::default(); + let mut s = Server::new(Box::new(OldWindow { png: written, reply, seen: seen.clone() })); + let r = call(&mut s, "screenshot", json!({"window": true})); + assert_eq!(r["isError"], !ok, "{r}"); + if ok { + assert_eq!(vectorcraft_format::base64_decode(r["content"][0]["data"].as_str().unwrap()).unwrap(), png, "{r}"); + } + let seen = seen.lock().unwrap().clone(); + let [(path, mode)] = seen.as_slice() else { panic!("one capture: {seen:?}") }; + let dir = std::path::Path::new(path).parent().unwrap().to_path_buf(); + assert_eq!(dir.parent(), Some(temp.as_path()), "{path} is in a folder of its own inside {}", temp.display()); + assert!(!dir.exists(), "{} is removed", dir.display()); + if cfg!(unix) { + assert_eq!(*mode, Some(0o700), "{path}"); + } + folders.push(dir); + } + folders.sort(); + folders.dedup(); + assert_eq!(folders.len(), 4, "each capture has a new folder: {folders:?}"); +} + /// Each tool with another name for the same call names it in its description. #[test] fn alias_tools_name_their_pair() { diff --git a/crates/mcp/src/tools/handlers.rs b/crates/mcp/src/tools/handlers.rs index e76b5704ae..39d3f3f8e1 100644 --- a/crates/mcp/src/tools/handlers.rs +++ b/crates/mcp/src/tools/handlers.rs @@ -437,18 +437,52 @@ pub(super) fn screenshot(b: &mut dyn Backend, a: &Args) -> Result) -> Result { - let tmp = std::env::temp_dir().join(format!("vectorcraft-window-{}.png", std::process::id())).to_string_lossy().to_string(); - let r = b.call("ui.screenshot", json!({"path": tmp}))?; - let png = std::fs::read(&tmp).map_err(|e| format!("read {tmp}: {e}"))?; - // Best effort: a temporary file left behind is harmless. - std::fs::remove_file(&tmp).ok(); + let dir = new_capture_folder(&std::env::temp_dir())?; + let tmp = dir.join("window.png").to_string_lossy().to_string(); + let captured = b.call("ui.screenshot", json!({"path": tmp})).and_then(|r| Ok((std::fs::read(&tmp).map_err(|e| format!("read {tmp}: {e}"))?, r))); + // Best effort: a folder that can't be removed holds only this capture, and on unix only its + // owner can open it. + let _ = std::fs::remove_dir_all(&dir); + let (png, r) = captured?; let mut info = json!({"window": true, "width": r.get("width"), "height": r.get("height"), "path": Value::Null}); let png = fit_capture(png, max, &mut info)?; Ok(image_result(&png, info)) } +/// A new folder in `parent` named `vectorcraft-window-` followed by the process id, `-` and a count +/// of the process's captures; on unix only its owner can open it. A name that is already taken, by +/// an earlier process with the same id or by anyone else, is skipped for the next count. +fn new_capture_folder(parent: &std::path::Path) -> Result { + static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + loop { + let dir = parent.join(format!("vectorcraft-window-{}-{}", std::process::id(), NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed))); + match private_folder().create(&dir) { + Ok(()) => return Ok(dir), + Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {} + Err(e) => return Err(format!("{}: {e}", dir.display())), + } + } +} + +/// A builder for folders that only their owner can read, write or open (mode 0o700). +#[cfg(unix)] +fn private_folder() -> std::fs::DirBuilder { + let mut b = std::fs::DirBuilder::new(); + std::os::unix::fs::DirBuilderExt::mode(&mut b, 0o700); + b +} + +/// A builder for folders: a plain one outside unix. +#[cfg(not(unix))] +fn private_folder() -> std::fs::DirBuilder { + std::fs::DirBuilder::new() +} + /// `max_side`: absent, or an integer in 1..4096. pub(super) fn max_side(a: &Args) -> Result, String> { match a.get("max_side") { diff --git a/docs/mcp.md b/docs/mcp.md index 9930b33734..f9700ce616 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -630,7 +630,7 @@ sampler. | `answer_dialog` | `{set?: [{field, value?}], action?}` | Remote only. Sets fields of the app's open dialog in the order given with one `ui.dialog.set {fields, action?}` (a missing `value` is `null`). The app stores all of them or none, then answers that same dialog with `action` in the same request: `confirm` (OK) or `cancel`. Another connection cannot open a dialog between the two steps. When the app refuses the `ui.dialog.set`, for example because no dialog is open, the call is an error and the dialog is not confirmed or canceled. `set` cannot change a `__` field other than the dialog's controls held under a `__` name (such as Save PDF's `__section` or the Preferences `__search`): the `__command` and `__params` of a `confirm` or `command` dialog, and every other `__` field that holds what OK acts on, are refused with "the `` dialog cannot set protected field ``", so OK runs what the dialog was opened for. `action` alone is sent as `ui.dialog.confirm` or `ui.dialog.cancel`. Give `set`, `action` or both; `set` holds at most 256 fields. `inspect_ui` shows the open dialog and its fields as `ui.dialog`. Returns `{dialog, result}`: the dialog after the fields were set (or `null`) and the reply to `confirm` or `cancel` (or `null`). After `invoke_menu` `app.quit`, `file.close` or `file.closeAll` replies `{"pending": "saveChanges"}`, `{action: "confirm"}` saves, `{set: [{field: "discard", value: true}], action: "confirm"}` closes without saving and `{action: "cancel"}` cancels the close or quit. | | `invoke_menu` | `{command, params?}` | Invokes a menu item by command id. UI commands such as `view.*` and `window.*` are in `command_list` with `ui: true`; running them needs the desktop app (`--connect`). | | `open_panel` | `{panel}` | Remote only. `panel` is a panel id (`layers`, `swatches`, `colorGuide`, …, as `window.panel` takes) or its display label (`"Color Guide"`), in any case. | -| `screenshot` | `{path?, scale?, artboard?, window?, max_side?, traceViews?}` | Returns MCP image content (`image/png`, base64) plus a text block. Renders the artboard with the pixels of a PNG `export` with `background: "white"` at the same scale; `traceViews:true` draws Image Trace objects in the view set with `imageTrace.setView`, as in the app's window; `window:true` captures the app window (remote only), as `ui_screenshot` does, and `max_side` (1–4096, window captures only) scales the returned image down as described for `ui_screenshot`. With `path` the backend (the headless session or the app) writes the PNG there too; a window capture written there keeps its full size with `max_side`. | +| `screenshot` | `{path?, scale?, artboard?, window?, max_side?, traceViews?}` | Returns MCP image content (`image/png`, base64) plus a text block. Renders the artboard with the pixels of a PNG `export` with `background: "white"` at the same scale; `traceViews:true` draws Image Trace objects in the view set with `imageTrace.setView`, as in the app's window; `window:true` captures the app window (remote only), as `ui_screenshot` does, and `max_side` (1–4096, window captures only) scales the returned image down as described for `ui_screenshot`. With `path` the backend (the headless session or the app) writes the PNG there too; a window capture written there keeps its full size with `max_side`. An app that does not send the image back writes a window capture without `path` to a file in a new folder inside the system's temporary folder (on Unix only the user can open it); the server reads the file and then removes the folder, also when the capture or the read fails. | | `open_file` | `{path, importer?, params?}` | Opens any readable file as a new active document: `.vectorcraft`/`.drawcraft`, `.vctemplate`, `.svg`/`.svgz`, `.pdf`/`.ai`, `.ait`, `.eps`/`.epsf`, `.ps`, `.dxf`, `.emf`, `.wmf`, PICT (`.pct`/`.pic`/`.pict`, and a version 2 picture of any extension), HP-GL (`.plt`/`.hpgl`/`.hgl`/`.hpg`, and a file of an extension no other format reads that starts with plotter instructions), PNG (`.png`/`.pns`), JPEG, GIF, WebP, TIFF, BMP (`.bmp`/`.dib`/`.rle`), Targa (`.tga`/`.vda`/`.icb`/`.vst`), PCX, Pixar (`.pxr`), JPEG 2000 (`.jpf`/`.jpx`/`.jp2`/`.j2k`/`.j2c`/`.jpc`), HEIC/HEIF (`.heic`/`.heif`), JPEG XL (`.jxl`), PSD (`.psd`/`.pdd`)/PSB (an image opens as a document of its pixel size; a PSD or PSB file with its layers as layers, or as its merged image through `run_command document.open` with `layers: false`; a JPEG XL file as its first frame). Templates (`.vctemplate`, `.ait`) open as a new untitled document. PDF, `.ai` and SVG files saved with Preserve Editing reopen as the document they carry. The reply is `document.open`'s: its `warnings` say what didn't come in as it was (an EPS whose PostScript can't be read opens as its preview, and the warning names the PostScript error, the operator and the procedure). A file of an extension only an installed importer plug-in lists opens with that importer ([Plug-ins](#plug-ins)); `importer: "plugin."` opens the file with the importer it names, which must list the file's extension, also one a built-in format reads (in the app, as File › Open With does), and `params` gives that importer's parameters (their defaults when omitted). `run_command document.formats` lists the formats. | | `save_file` | `{path?, compress?, version?, preview?, precision?, options?}` | Runs `document.save`: the document's own file in its own format (native `.vectorcraft` unless it was opened from or saved as SVG, PDF or a restorable `.ai`; then `warnings` say what that format loses). A path's extension picks the format (`.vectorcraft`, `.vctemplate`, `.pdf`, `.svg`, `.svgz`, `.ai`: a PDF carrying the native document, which reopens editable; `.eps`: by default one file whose bounding box fits the visible art, the first artboard when no art shows; `options.useArtboards: true` makes the chosen artboard the page and, with two or more chosen, the file at the path is the central file of the visible art and each artboard is also written to `_.eps` beside it, listed in the reply's `files`). For a native file, `compress: true` gzips it (default: the `useCompression` preference, Preferences › File Handling › Use Compression), `version` (1 to 4) writes it for an older VectorCraft (1 and 2 are never compressed, and `version: 2` with `compress: true` is an error), `preview: true` embeds a PNG of the first artboard, and `precision` (0 to 9) rounds path anchors and handles to that many decimal places for that save only (colors, transforms and type stay exact). `options` passes the format's save options as `run_command document.formats` lists them. When `compress`, `version`, `preview` or `precision` is given both at the top level and in `options` with different values, the call is an error (`` `compress: true` and `options.compress: false` disagree: give the option once ``) and nothing is written. A key in `options` that no save format takes is an error, and nothing is written (see Parameter keys). The save drops each option the written format doesn't read. The reply's `warnings` then name each such option given (for example `` `compress` was not used: SVG files don't read it `` for an `.svg` path, and `` `options.preview` was not used: … `` for a key in `options`; a `.ai` file reads `compress` but not `version`, `preview` or `precision`). For a `.ai` file, these warnings name the kind of `.ai` written: a legacy .ai (version 7) for `aiVersion: "7"`, a non-PDF-compatible .ai for `pdfCompatible: false`, and a PDF-compatible .ai otherwise, including a save that reuses the options the document was last saved with. `run_command document.save` and the other save commands refuse any option given beside the path and in `options` with different values, and give the same warnings for a top-level `compress`, `version`, `preview` or `precision` and for each key in `options` that the format doesn't read. The headless session and the app receive the same `app.save` params, and the app is also sent `wait: true`: the call returns once the file is written, or with the error (such as a path outside the write root), even with Background Save on. When the save asks first (the question before replacing a file that opened with losses, or on macOS and Linux the file dialog for an untitled document without `path`), the reply is `{pending}` or `"cancelled"` as before, and the save that runs after the answer uses the Background Save preference. Location refusals return `READ_ONLY_LOCATION: ` without a fallback panel for automation; see [Save location errors](#save-location-errors). | | `export` | `{path?, format?, scale?, artboard?, range?, selection?, outlineText?, options?}` | `svg`, `svgz`, `pdf`, `ai` (the PDF-compatible `.ai` that Save writes, which carries the document when every artboard is written in order), `eps`, `dxf`, `emf`, `wmf`, `hpgl` (a `.plt` plot file for plotters and cutters), `png`, `jpg`, `webp`, `gif`, `png8` (an indexed `.png`), `tiff`, `bmp`, `tga`, `psd` (layered), `txt` (the document's text), `vectorcraft` or `template` (a native template). The tool's `format` enum and `document.formats` list them, generated from the engine's format table. When `format` is omitted, it comes from the path's extension. PDF and `.ai` write one page per artboard: all of them, or `artboard` (0-based) / `range` (`"1-3, 5"`, 1-based). SVG and SVGZ write one file per chosen artboard. EPS writes one file of the visible art; with `artboard`, `range`, `options.artboards` or `options: {"useArtboards": true}` it writes one file per chosen artboard, after a central file of the visible art when there are two or more, and `useArtboards: false` keeps the one file. Rasters, DXF, EMF, WMF and HP-GL write one artboard, or one file per chosen artboard with `options: {"useArtboards": true}`. Rasters also take `options: {"rect": [x, y, width, height]}` (page points, y down): that area of the page at the given `ppi`/`scale`, without an artboard and without changing the document; it is refused with `artboard`, `artboards`, `range` or `useArtboards`, with a non-positive or non-finite size, and for non-raster formats. `options` carries more format options (e.g. `{"quality": 80}` for JPEG). `selection: true` exports the selected objects cropped to their bounds (the reply adds their `bounds`, and reports `format` and the encoder's `warnings` as a whole-document export does); `outlineText: true` writes SVG text as paths. Template layers are left out, live effects are kept, and exporting `vectorcraft` never changes the document's path. Without `path` the bytes come back as `dataBase64`. Both backends run the same `document.export` call. | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f9c6855f68..558b6ba57f 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -808,6 +808,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Parameter keys: the engine refuses a key that a command's params description doesn't name before the command runs, in every build and for every caller, including the app's own calls, the commands a command runs and the steps of `command.batch` and `action.batch`. An action recorded by an older version still plays from the Actions panel and the Batch dialog (`Session::replay`). `crates/engine/tests/it/param_keys.rs`. - Effect parameter types: `effect.apply`, `appearance.addEffect` and `effect.setParams` refuse an effect parameter of another type than the effect reads, for keys only the params text names too (the earlier 3D `perspective`, `lightAzimuth` and `lightElevation`, Scribble's `variation`, Outline Stroke's `width`, Gaussian Blur's `linear`), a Crop Marks `style` other than `roman` or `japanese`, and an installed plug-in effect's parameter of another type than its manifest gives it, in a `command.batch` step too, with the document and undo history unchanged; a replayed action still plays. `effect.setParams` checks the parameters against a Warp's new style, and refuses a `visible` that is not true or false, in a replayed action too. `crates/engine/src/tests/params.rs` (`an_effect_parameter_without_a_default_is_held_to_its_type`, `effect_commands_refuse_an_undefaulted_parameter_of_the_wrong_type`), `crates/engine/src/tests/plugins.rs` (`live_effect_plugins_reshape_editable_art_and_expand`), `crates/engine/src/cmd/effectcmd/tests.rs` (`set_params_refuses_a_visible_that_is_not_true_or_false`, `set_params_checks_the_effect_it_leaves`). - MCP server with 33 tools (drawing, text, effects, Pathfinder, transforms, graphs, text wrap, export, screenshots, undo/redo, UI inspect/screenshot aliases, any command), attached to the running app or headless. Headless and remote `command_list` include desktop `UI_COMMANDS` (`ui: true`); a UI-only id still needs `--connect` to run. Eight prompts (poster, icon-set, recolor, trace-and-style, export-set, check-spelling, variables-bind, path-tools). Effect ids are not command ids. Prefer a CLI built from the checkout when a release binary lags (#6460). `vectorcraft://commands/reference` serves the API reference. Tool descriptions and replies agree with the engine: format lists come from its format table, `save_file` says it keeps the document's own format, `inspect_document` reports the paint type's characters show, and selection exports report the encoder's warnings. `--automation-read-root` / `--automation-write-root` (on `vectorcraft-cli mcp` and on `vectorcraft --control`) confine the files commands read and write to chosen folders, links followed, with the flags PhotoCraft takes (#832); each flag may be given more than once, a path inside any of its folders being allowed (#3546, `file_access::tests::several_roots_of_a_kind_each_grant_their_access`, `cli::mcp_automation_roots_take_several_folders`). A long export can be cancelled (`notifications/cancelled` stops it at the next page or group and writes nothing), reports page progress to a client that sent a progress token, and does not make other requests wait: engine-free ones answer at once, the rest are refused as busy after two seconds (#2165, #2171, #2172). + - MCP window captures from an app that does not send the image back go through a file in a new folder inside the system's temporary folder, which only the user can open on Unix, instead of a fixed name in the shared folder; the folder is removed after the read, also when the capture or the read fails (`tests::conventions::an_old_app_captures_the_window_in_a_new_private_folder`). - MCP protocol: five prompts (`prompts/list` / `prompts/get`: poster, icon set, recolour, trace-and-style, export set), `completion/complete` for prompt arguments and template variables read from the live catalogues (formats, effect ids, command ids, trace presets, swatch and object ids), four resource templates (`vectorcraft://object/{id}`, `//command/{id}`, `//effect/{id}`, `//swatch/{name}`) so an agent reads one thing instead of the whole document, and `logging/setLevel` with `notifications/message`. `window.panel` ids are case-insensitive (display labels work too), `vectorcraft://object/{id}` reads through `document.node {summary: true}` (the same reply bytes from one lookup instead of summarizing the whole document: a leaf read on a 2,000-object document drops from ~20 ms to ~0.06 ms), large containers slice with `document.node {depth?, childLimit?}` (truncated levels report `childCount`), `document.inspect` and the `inspect_document` tool slice the same way so a depth-0 read is the layer skeleton (~9.7 KB instead of ~2 MB on a 2,000-object document), `document.find` locates nodes by name/kind/text with ancestor paths, and the CLI sweeps the protocol surface over stdio against the compiled binary. `docs/mcp.md` has a Protocol section covering the capability table and what is deliberately absent (subscriptions, progress, cancellation, sampling, elicitation, Streamable HTTP — all of which need the transport to interleave reads). - Headless CLI (`vectorcraft-cli run`, `convert`, `info`, `bench`, `perf`, `mcp`). A `run` step, like a `command_batch` step over MCP, can use an earlier step's result (`"$1.id"`, #785); `run --commands FILE` (or `-` for standard input) reads the steps from a JSON array or JSON Lines, past the Windows command-line limit (#3147, `apps/vectorcraft-cli/tests/it/cli.rs` `run_reads_*`, `run_refuses_malformed_commands_naming_the_step`). - File › Scripts › Check Script… reads a script written for Illustrator (`.jsx`, `.jsxinc` or a compiled `.jsxbin`) without running any of it and reports what it needs (the document model, files, dialogs, menu commands, features only Illustrator has), what it would do outside the document, the menu commands and document-model members it uses, its directives and included files, and the problems that would stop it loading (`script.check`, which also reads `.js` files); File › Open and drag-and-drop show the report for `.jsx`, `.jsxinc` and `.jsxbin` files. From 940b47234b6a6c64b6be85318af466179e283a44 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 08:22:23 -0800 Subject: [PATCH 22/25] Tests: the vectorcraft-mcp integration tests remove their temp folders automation_roots.rs and protocol_props.rs wrote their files into folders made by vectorcraft_testkit::temp_dir (vectorcraft-testkit-roots--, mcp-junk, mcp-confined), and nothing removed them after the run. A shared tests/common module adds TempFolder, which takes the folder from temp_dir, with its checks against a folder made by another user, and removes it with everything in it when dropped, also when the test panics, as the findfiles tests' Tree guard does (crates/engine/src/cmd/findfiles/tests.rs:49). Each proptest case of a_confined_server_writes_only_inside_its_root now gets a new folder. A new test checks that the folder is removed on drop and after a panic. --- crates/mcp/tests/automation_roots.rs | 35 ++++++++++++++++++++++++---- crates/mcp/tests/common/mod.rs | 28 ++++++++++++++++++++++ crates/mcp/tests/protocol_props.rs | 7 ++++-- 3 files changed, 64 insertions(+), 6 deletions(-) create mode 100644 crates/mcp/tests/common/mod.rs diff --git a/crates/mcp/tests/automation_roots.rs b/crates/mcp/tests/automation_roots.rs index d45ecc7142..74bd95d455 100644 --- a/crates/mcp/tests/automation_roots.rs +++ b/crates/mcp/tests/automation_roots.rs @@ -5,8 +5,11 @@ // 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 std::path::{Path, PathBuf}; +mod common; +use std::path::Path; + +use common::TempFolder; use serde_json::{Value, json}; use vectorcraft_engine::file_access::AutomationRoots; use vectorcraft_mcp::{Headless, Server}; @@ -14,9 +17,10 @@ use vectorcraft_mcp::{Headless, Server}; const SVG: &str = r#""#; /// A folder holding `in` (the read root, with `a.svg`), `out` (the write root), `outside` (with -/// `b.svg`) and `in2`, and a server confined to `in` and `out` (either may be left out). -fn confined(tag: &str, read: bool, write: bool) -> (Server, PathBuf) { - let base = vectorcraft_testkit::temp_dir(&format!("roots-{tag}")); +/// `b.svg`) and `in2`, and a server confined to `in` and `out` (either may be left out). The +/// folder is removed when the returned [`TempFolder`] is dropped. +fn confined(tag: &str, read: bool, write: bool) -> (Server, TempFolder) { + let base = TempFolder::new(&format!("roots-{tag}")); for d in ["in", "out", "outside", "in2"] { std::fs::create_dir_all(base.join(d)).unwrap(); } @@ -55,6 +59,29 @@ fn refused(server: &mut Server, name: &str, args: Value, why: &str) { assert!(error && text.contains(why), "{name} {args} should be refused ({why}): {text}"); } +/// A `TempFolder` is removed with the files and folders in it when dropped, also when the test +/// that holds it panics. +#[test] +fn temp_folders_are_removed_when_dropped() { + let dir = TempFolder::new("roots-drop-check"); + std::fs::create_dir(dir.join("sub")).unwrap(); + std::fs::write(dir.join("sub/a.svg"), SVG).unwrap(); + let path = dir.to_path_buf(); + drop(dir); + assert!(!path.exists(), "{} is removed", path.display()); + + let mut held = None; + let panicked = vectorcraft_testkit::catch_quiet(|| { + let dir = TempFolder::new("roots-panic-check"); + std::fs::write(dir.join("a.svg"), SVG).unwrap(); + held = Some(dir.to_path_buf()); + panic!("the test fails with {} in use", dir.display()); + }); + assert!(panicked.is_err()); + let path = held.unwrap(); + assert!(!path.exists(), "{} is removed after a panic", path.display()); +} + #[test] fn files_open_only_from_inside_the_read_root() { let (mut server, base) = confined("open", true, true); diff --git a/crates/mcp/tests/common/mod.rs b/crates/mcp/tests/common/mod.rs new file mode 100644 index 0000000000..08954ca21e --- /dev/null +++ b/crates/mcp/tests/common/mod.rs @@ -0,0 +1,28 @@ +//! Shared helpers for the MCP integration tests. + +use std::path::{Path, PathBuf}; + +/// A test's own folder, made by [`vectorcraft_testkit::temp_dir`] (with its checks against a +/// folder made by someone else) and removed with everything in it when dropped, also when the +/// test panics. A removal that fails (a file still open) is ignored. Tests that run at the same +/// time use different tags. +pub struct TempFolder(PathBuf); + +impl TempFolder { + pub fn new(tag: &str) -> Self { + Self(vectorcraft_testkit::temp_dir(tag)) + } +} + +impl std::ops::Deref for TempFolder { + type Target = Path; + fn deref(&self) -> &Path { + &self.0 + } +} + +impl Drop for TempFolder { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} diff --git a/crates/mcp/tests/protocol_props.rs b/crates/mcp/tests/protocol_props.rs index f9dc065ff1..b3145a20b9 100644 --- a/crates/mcp/tests/protocol_props.rs +++ b/crates/mcp/tests/protocol_props.rs @@ -4,6 +4,9 @@ // 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)] +mod common; + +use common::TempFolder; use proptest::prelude::*; use serde_json::{Value, json}; use vectorcraft_doc::Document; @@ -98,7 +101,7 @@ fn tool_definitions_are_valid() { #[test] fn every_tool_survives_empty_and_junk_arguments() { - let dir = vectorcraft_testkit::temp_dir("mcp-junk"); + let dir = TempFolder::new("mcp-junk"); let safe = dir.join("junk.vectorcraft").to_string_lossy().to_string(); let mut failures = vec![]; for t in tool_definitions() { @@ -169,7 +172,7 @@ proptest! { tail in junk_tail(), tool in prop::sample::select(vec!["open_file", "save_file", "export", "screenshot"]), ) { - let base = vectorcraft_testkit::temp_dir("mcp-confined"); + let base = TempFolder::new("mcp-confined"); let root = base.join("a/b/c/root"); std::fs::create_dir_all(&root).unwrap(); std::fs::create_dir_all(base.join("outside")).unwrap(); From bc7eddeb5d3f877980ddbcbff5176eff5ba6b4cf Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 08:27:09 -0800 Subject: [PATCH 23/25] Expand: type reports a gradient only when Fill expands one of its outlines object.expand.info reported a gradient (and a fill) to expand for any type whose characters have a gradient fill. Expand outlines type first, and each outline then holds the run's gradient on its own box, so a gradient that repeats or reflects in more than 256 runs across every outline stays a gradient: the dialog enabled options that changed nothing. - The query now measures the paths type.createOutlines makes of the glyphs, ruby glyphs and underline and strikethrough bars, each with its run's paint, and reports a gradient when one of them expands. It lays the text out only when a run has a gradient fill, stops at the first outline that expands, and does not change the document. Type in symbol art, blends and repeats goes through the same check. - docs/mcp.md says when gradient is false; docs/target-app-parity.md gets an evidence line. --- crates/engine/src/cmd/expand.rs | 36 ++++++++++-- crates/engine/src/tests/objexpand.rs | 83 ++++++++++++++++++++++++++++ docs/mcp.md | 4 +- docs/target-app-parity.md | 1 + 4 files changed, 119 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/expand.rs b/crates/engine/src/cmd/expand.rs index 0f55386830..352e520433 100644 --- a/crates/engine/src/cmd/expand.rs +++ b/crates/engine/src/cmd/expand.rs @@ -18,8 +18,8 @@ use vectorcraft_color::{BlendMode, Color, Gradient, GradientKind, GradientPaint, use vectorcraft_doc::appearance::{AppearanceItem, FillLayer}; use vectorcraft_doc::live::GradientMesh; use vectorcraft_doc::pattern::{PatternDef, place_art}; -use vectorcraft_doc::{Appearance, Document, Node, NodeId, NodeKind, Scaling}; -use vectorcraft_geom::{Affine, PathData, Point, Rect, SubPath, Vec2, shapes}; +use vectorcraft_doc::{Appearance, Document, Node, NodeId, NodeKind, Scaling, TextObject}; +use vectorcraft_geom::{Affine, BezPath, PathData, Point, Rect, SubPath, Vec2, shapes}; use super::dimension::EndedLink; use super::edit::selected_roots; @@ -56,7 +56,7 @@ pub fn specs() -> Vec { "Expand Options", [], None, - "{} what each Expand option would change in the selection → {object, fill, stroke, gradient, appearance, symbolArt?: {fill, stroke, gradient}} (true: something to expand; gradient: a gradient fill that Fill expands, which Expand Gradient To applies to; appearance: appearance attributes Expand Appearance expands first, for which Object › Expand… is dimmed in the menus; symbolArt, when the selection holds symbol instances that Object expands: true when only their art holds it, which Fill and Stroke reach only with Object on)", + "{} what each Expand option would change in the selection → {object, fill, stroke, gradient, appearance, symbolArt?: {fill, stroke, gradient}} (true: something to expand; gradient: a gradient fill that Fill expands (in type, on the outline Object makes of a character), which Expand Gradient To applies to; appearance: appearance attributes Expand Appearance expands first, for which Object › Expand… is dimmed in the menus; symbolArt, when the selection holds symbol instances that Object expands: true when only their art holds it, which Fill and Stroke reach only with Object on)", has_selection, |s, _| { let roots = selected_roots(s)?; @@ -197,7 +197,7 @@ impl Expandable { // Once one is found, the next path is not measured. e.gradient = e.gradient || match &c.kind { - NodeKind::Text(t) => t.runs.iter().any(|r| matches!(r.style.fill, Paint::Gradient(_))), + NodeKind::Text(t) => text_gradient_expands(d, t), _ => shape && gradient_expands(d, c), }; e.fill |= e.gradient; @@ -247,6 +247,34 @@ fn gradient_expands(d: &Document, l: &Node) -> bool { any } +/// Whether type `t` has a gradient fill that Fill expands once Object has outlined it: one of the +/// paths `type.createOutlines` makes of its glyphs, ruby glyphs and underline and strikethrough +/// bars, each painted as its run, has one ([`gradient_expands`] on that path's own box). Inline +/// graphics and color glyphs become other art. Leaves the document as it is and stops at the +/// first such path. +fn text_gradient_expands(d: &Document, t: &TextObject) -> bool { + if !t.runs.iter().any(|r| matches!(r.style.fill, Paint::Gradient(_))) { + return false; + } + let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t); + let expands = |run: usize, outline: &BezPath| { + let style = t.runs.get(run).map(|r| &r.style); + if !matches!(style.map_or_else(|| t.first_style().fill, |s| s.fill.clone()), Paint::Gradient(_)) { + return false; + } + let path = PathData::from_bezpath(outline).transformed(t.xf); + if path.is_empty() { + return false; + } + let appearance = style.map_or_else(|| t.first_style().appearance(), |s| s.appearance()); + gradient_expands(d, &Node::path(NodeId(u64::MAX), path, appearance)) + }; + let inline = |gi: usize| lay.inlines.iter().find(|i| i.glyph == gi).is_some_and(|i| t.runs.get(i.run).is_some_and(|r| r.inline.is_some())); + lay.glyphs.iter().enumerate().any(|(gi, g)| !inline(gi) && g.image.is_none() && g.colour.is_none() && expands(g.run, &g.outline)) + || lay.ruby.iter().any(|g| expands(g.run, &g.outline)) + || vectorcraft_text::decorations(&lay, vectorcraft_text::FontDb::global(), t).iter().any(|(run, bar)| expands(*run, bar)) +} + /// [`gradient_expands`] for a path that no live-effect plug-in paints ([`expand_piece_fills`]). fn piece_gradient_expands(d: &Document, l: &Node) -> bool { if !l.appearance.items.iter().filter_map(gradient_fill).any(|(_, g)| g.gradient.is_spread()) { diff --git a/crates/engine/src/tests/objexpand.rs b/crates/engine/src/tests/objexpand.rs index 1c931e0de8..b8c4724853 100644 --- a/crates/engine/src/tests/objexpand.rs +++ b/crates/engine/src/tests/objexpand.rs @@ -629,6 +629,89 @@ fn a_spread_gradient_with_more_runs_than_written_stays_a_gradient() { } } +/// Selected type "Hi" at 48 pt, its characters filled with a gradient that repeats 100 times along +/// a vector `len` pt long. +fn spread_gradient_type(s: &mut Session, len: f64) -> u64 { + let t = run(s, "text.create", json!({"x": 50, "y": 100, "text": "Hi", "size": 48}))["id"].as_u64().unwrap(); + run(s, "select.set", json!({"ids": [t]})); + run( + s, + "paint.setFill", + json!({"gradient": {"kind": "linear", "spread": "repeat", "repeats": 100, "start": [50, 100], "end": [50.0 + len, 100], + "stops": [{"offset": 0, "color": "#ffff00"}, {"offset": 1, "color": "#004080"}]}}), + ); + t +} + +/// How many objects in the document have a gradient fill, and how many are type. +fn gradients_and_type(s: &Session) -> (usize, usize) { + let (mut gradients, mut texts) = (0, 0); + s.doc().unwrap().doc.walk(|n| { + gradients += usize::from(matches!(n.appearance.fill_paint(), Paint::Gradient(_))); + texts += usize::from(matches!(n.kind, NodeKind::Text(_))); + }); + (gradients, texts) +} + +/// Type is outlined before its fills expand, and each glyph's gradient fits that glyph's own box: +/// `object.expand.info` reports a gradient (and a fill) only when a glyph's box needs no more runs +/// than are written, so Expand turns it into art. Both Expand Gradient To options leave the +/// glyphs whose gradient needs more runs with their gradient, and Object still outlines the type. +/// The query leaves the document and its history as they are. +#[test] +fn type_whose_gradient_needs_more_runs_than_written_reports_no_gradient() { + // 0.2 pt runs (100 repeats over 20 pt) across glyphs about 30 pt wide: under the limit. + // 0.02 pt runs (over 2 pt): far over it. + for (len, expands) in [(20.0, true), (2.0, false)] { + let mut s = session(); + spread_gradient_type(&mut s, len); + let before = (s.doc().unwrap().revision, s.doc().unwrap().history.undo.len(), s.doc().unwrap().doc.layers.clone()); + let info = run(&mut s, "object.expand.info", json!({})); + assert_eq!((info["gradient"].clone(), info["fill"].clone(), info["object"].clone()), (json!(expands), json!(expands), json!(true)), "{len}"); + assert!( + before == (s.doc().unwrap().revision, s.doc().unwrap().history.undo.len(), s.doc().unwrap().doc.layers.clone()), + "{len}: the query changed the document" + ); + for to in [json!({}), json!({"gradient": "mesh"})] { + let mut s = session(); + spread_gradient_type(&mut s, len); + run(&mut s, "object.expand", to.clone()); + let (gradients, texts) = gradients_and_type(&s); + assert_eq!(texts, 0, "{len} {to}: outlined"); + assert_eq!(gradients == 0, expands, "{len} {to}: {gradients} gradient fills left"); + } + } +} + +/// One glyph whose box needs more runs than are written does not hide another that Expand turns +/// into art: the 200 pt "H" keeps its gradient, the 48 pt "i" expands, and the query reports it. +#[test] +fn type_reports_a_gradient_when_any_glyph_expands() { + let mut s = session(); + let t = spread_gradient_type(&mut s, 20.0); + run(&mut s, "text.setRangeStyle", json!({"id": t, "start": 0, "end": 1, "size": 200})); + let info = run(&mut s, "object.expand.info", json!({})); + assert_eq!((info["gradient"].clone(), info["fill"].clone()), (json!(true), json!(true))); + run(&mut s, "object.expand", json!({})); + assert_eq!(gradients_and_type(&s), (1, 0), "the large glyph keeps its gradient"); +} + +/// The same rule for type in the art of a symbol instance that Object expands. The symbol's art +/// is the type scaled down (its "i" about 2.5 pt wide), so its glyphs need more runs than are +/// written with 0.002 pt runs (over a 0.2 pt vector). +#[test] +fn type_in_symbol_art_reports_a_gradient_only_when_it_expands() { + for (len, expands) in [(20.0, true), (0.2, false)] { + let mut s = session(); + spread_gradient_type(&mut s, len); + let inst = run(&mut s, "symbol.new", json!({"name": "Hi"}))["id"].as_u64().unwrap(); + run(&mut s, "select.set", json!({"ids": [inst]})); + let info = run(&mut s, "object.expand.info", json!({})); + assert_eq!(info["gradient"], json!(expands), "{len}"); + assert_eq!((info["symbolArt"]["gradient"].clone(), info["symbolArt"]["fill"].clone()), (json!(expands), json!(expands)), "{len}: {info}"); + } +} + #[test] fn the_mesh_option_makes_a_mesh_that_paints_the_gradient() { for gradient in [ diff --git a/docs/mcp.md b/docs/mcp.md index 9930b33734..70ee8d39ef 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -4669,7 +4669,9 @@ and those of the object shape the outline of the clip group, the gradient fits t box, as the canvas paints the fill; the expanded art does not keep them. With `fill: false` gradient and pattern fills stay live. `object.expand.info` answers which options have something to expand in the selection (`{object, fill, stroke, gradient, appearance, symbolArt?}`; `gradient` says whether Fill has a gradient fill, which Expand -Gradient To applies to; `appearance` whether the selection has appearance attributes Expand Appearance expands first, +Gradient To applies to, that it turns into art: it is false when every such fill repeats or reflects in more than 256 +runs across the box it fills, which for type, symbol art included, is the box of each outline Object makes of a character, +ruby character, underline or strikethrough; `appearance` whether the selection has appearance attributes Expand Appearance expands first, for which Object → Expand… is dimmed in the menus; `symbolArt: {fill, stroke, gradient}`, present when the selection holds symbol instances that `object` expands, whether only their art holds it, which Fill and Stroke reach only with `object` on), and `object.mesh.create` on a gradient-filled object colours the diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f9c6855f68..5e9f39dafb 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1756,6 +1756,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Pattern tiles:** the renderer keeps a tile of each pattern for each scale it rasterizes the pattern at, until the tiles fill the tile cache's budget, and then drops the least recently used tiles first. Objects that show one pattern at different scales, such as a pattern scaled to 25% with Transform Pattern Tiles next to the same pattern at 100%, draw from tiles kept between frames. - **Pattern fills in Expand:** Object › Expand with Fill turns a pattern fill into the pattern's tiles in a clip group shaped like the object, with the fill's opacity and blend mode, and the object's other fills and strokes stay above or below it in paint order, in one undo step (`object.expand`). +- **Gradient options for type in Expand:** the Expand dialog enables its gradient options for type, symbol art included, only when the outline of at least one character, ruby character, underline or strikethrough gets a gradient that Fill turns into art. A gradient that repeats or reflects in more than 256 runs across a character's outline, VectorCraft's own limit, stays a gradient after Expand (`object.expand.info`, `crates/engine/src/tests/objexpand.rs`). - **Type with transparency or effects:** type at less than 100% opacity, in a blend mode other than Normal, or with raster effects such as a drop shadow keeps its glyph outlines between frames, as opaque type does, and is laid out again when it is edited or the fonts change. At 2880 × 1800 on 8 threads, a page of 1,000 type objects takes 13 ms a frame instead of 23 ms at 80% opacity, 31 ms instead of 41 ms in Multiply and 16 ms instead of 26 ms with a drop shadow, with the same pixels. From bc9280967a7473c44e777289ad2e728c22f6ca5c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 21:48:10 -0800 Subject: [PATCH 24/25] Image Trace: staircases of longer steps in smooth areas trace as slopes Where a band border in a gradient or a shaded area runs at a slant, its pixels form a staircase whose steps are two or more pixels long. When one piece of outline also runs along a sharp edge in the image, that piece as a whole is not the contour of a smooth area, and the outline kept a corner at every step, so the border was traced as a series of right-angle steps. subpixel::outline now reads a run of three or more edges of 1 to 8 px, each turning one way where it starts and the other where it ends, with no junction on it, as a staircase when the run's own cracks pass subpixel::low_contrast. A run is cut at any step whose own cracks show half of the step between the two colors or more. Its edges are steps, as one-pixel steps already were: no corner where two of them meet, and one point at the middle of each, moved by the mean of its cracks' shifts. The corner where a run meets an edge that is not a step stays, so a straight edge longer than 8 px next to a staircase stays straight. Two one-pixel steps inside a run are read as part of the slope and do not make a notch. Longer steps, staircases along a sharp edge and Black and White traces keep their corners. The runs are the same from either side of the border. On gradient and photo inputs most traces take fewer anchors. Some rows get worse: 6 Colors on gradient and photo leaves a gap of 0.9 px (was 1.2) and an overlap of 1.0 px (was 0.8), High Fidelity Photo with Gradients on a blurred input takes 50 anchors (was 47), and on a synthetic 800 px photo the 95th percentile of High Fidelity Photo's pixel difference rises from 6.33 to 6.67 and 16 Colors leaves 2 staircases of 2 px steps or more where it left none. Docs: docs/target-app-parity.md, docs/image-trace-quality.md. --- crates/trace/src/subpixel.rs | 276 ++++++++++++++++++++++++++++++++++- docs/image-trace-quality.md | 41 ++++++ docs/target-app-parity.md | 1 + 3 files changed, 316 insertions(+), 2 deletions(-) diff --git a/crates/trace/src/subpixel.rs b/crates/trace/src/subpixel.rs index 550fb87d2f..5dba6f8850 100644 --- a/crates/trace/src/subpixel.rs +++ b/crates/trace/src/subpixel.rs @@ -12,6 +12,8 @@ //! An image with hard edges (a GIF, a 1-bit scan) says nothing more than the cracks do: every crack //! moves by the same amount. There the staircase is read the classic way: a one-pixel step between //! two runs is a point of a sloped edge (its middle is on the edge, the corners beside it are not). +//! A staircase of longer steps is read the same way where a smooth area was split into bands (see +//! [`outline`]). use kurbo::Vec2; use vectorcraft_geom::Point; @@ -119,6 +121,10 @@ pub(crate) fn low_contrast(steps: &[[f64; 5]]) -> bool { /// flat (see [`low_contrast`]). const FLAT: f64 = 12.0; +/// The longest step (px) of a staircase read as the slope through it in a smooth area (see +/// [`outline`]). An edge longer than this keeps its corners. +const STAIR_MAX: usize = 8; + /// What `across` says of a crack that is an edge whatever the image does there: a crack on the /// image's border, or one that the image's pixels cannot be read across (see [`low_contrast`]). pub(crate) const EDGE_STEP: [f64; 5] = [1.0, 1.0, f64::NAN, f64::NAN, f64::NAN]; @@ -233,6 +239,50 @@ pub(crate) fn outline( if junctions[edges[i % n].first].is_some() { 0 } else { (a.0 * b.1 - a.1 * b.0).signum() } }; let step: Vec = (0..n).map(|i| edges[i].len == 1 && turn(i) * turn(i + 1) < 0).collect(); + // A staircase of longer steps, where a smooth area was split into bands: a run of three or more + // edges of one to `STAIR_MAX` pixels, each turning one way where it starts and the other where + // it ends, with no junction on it, whose cracks read as the contour of a smooth area (see + // `low_contrast`, applied to the run's own cracks; a run is cut at any step whose own cracks + // show half the step between the colors or more). Its edges are steps: no corner where two of + // them meet, and each gives one point, its middle. Where a run meets an edge that is not a + // step, that corner stays. A sharp edge drawn as a staircase keeps its corners. (The runs are + // the same from either side: they depend only on the edges, their turns and the junctions, + // which every region around a pixel corner shares.) + let stair = { + let candidate: Vec = (0..n) + .map(|i| { + let e = &edges[i]; + (1..=STAIR_MAX).contains(&e.len) && turn(i) * turn(i + 1) < 0 && !(0..=e.len).any(|k| junction((e.first + k) % cracks)) + }) + .collect(); + let own = |i: usize| (0..edges[i].len).filter_map(|j| steps.get(edges[i].first + j).copied()).collect::>(); + // Whether a step's own cracks show under half of the step between the two colors, as a + // contour does (an edge shows nearly all of it): a staircase that runs on from a contour + // into an edge is cut there. (Summed in sorted order: the same from either side.) + let gentle = |i: usize| { + let mut near: Vec = own(i).iter().map(|s| s[0]).filter(|s| !s.is_nan()).collect(); + near.sort_by(f64::total_cmp); + !near.is_empty() && near.iter().sum::() < 0.5 * near.len() as f64 + }; + let mut stair = vec![false; n]; + // A loop turns once round in all, so some edge is not a candidate: runs start after it. + if let Some(s0) = (0..n).find(|&i| !candidate[i]) { + let mut k = 1; + while k < n { + let run: Vec = (k..n).map(|j| (s0 + j) % n).take_while(|&i| candidate[i] && gentle(i)).collect(); + k += run.len().max(1); + if run.len() < 3 { + continue; + } + if low_contrast(&run.iter().flat_map(|&i| own(i)).collect::>()) { + for &i in &run { + stair[i] = true; + } + } + } + } + stair + }; let outward = |d: (i32, i32)| Vec2::new(f64::from(d.1), f64::from(-d.0)); // The pixel at a corner of the shape lies on both of the corner's edges, and what it lacks of // the inside's colour is the doing of both: read as one edge's alone it dents the corner. The @@ -242,7 +292,7 @@ pub(crate) fn outline( let mut shifts = shifts; for i in 0..n { let (b, e) = ((i + n - 1) % n, i); - if step[b] || step[e] || turn(i) == 0 { + if step[b] || step[e] || (stair[b] && stair[e]) || turn(i) == 0 { continue; } let (before, edge) = (&edges[b], &edges[e]); @@ -276,6 +326,9 @@ pub(crate) fn outline( && edges[b].len >= 3 && edges[s1].dir == edges[b].dir && edges[s2].dir == edges[a].dir + // The edges of a staircase of longer steps (see `stair`) make no corner here. + && !stair[a] + && !stair[b] && free(s1) && free(s2) && free(b) @@ -311,7 +364,7 @@ pub(crate) fn outline( if k == 0 && first.is_some() { // The junction itself: the one point every region around it has. pts.push(junctions[crack].unwrap_or(corner)); - } else if along_edge == 0 && !step[i] && !step[(i + n - 1) % n] { + } else if along_edge == 0 && !step[i] && !step[(i + n - 1) % n] && !(stair[i] && stair[(i + n - 1) % n]) { // A true corner: where its two edges, each moved by its own shift, meet. let before = &edges[(i + n - 1) % n]; pts.push(corner + outward(before.dir) * shifts[(crack + cracks - 1) % cracks] + outward(e.dir) * shifts[crack]); @@ -319,6 +372,13 @@ pub(crate) fn outline( if !hard && let Some(sharp) = notch[i] { // A corner whose own pixel went to the other side: the corner, not the two steps. pts.extend(sharp); + } else if stair[i] { + if along_edge == e.len / 2 { + // The middle of the step, moved by its cracks' mean shift (multiples of 1/1024, + // so the same sum from either side). + let shift = (0..e.len).map(|j| shifts[e.first + j]).sum::() / e.len as f64; + pts.push(at(i) + Vec2::new(f64::from(e.dir.0), f64::from(e.dir.1)) * (e.len as f64 / 2.0) + outward(e.dir) * shift); + } } else if step[i] || !hard { pts.push(corner + Vec2::new(f64::from(e.dir.0), f64::from(e.dir.1)) * 0.5 + outward(e.dir) * shifts[crack]); } @@ -494,6 +554,218 @@ mod tests { } } + #[test] + fn a_staircase_of_longer_steps_in_a_smooth_area_becomes_the_slope_through_its_steps() { + // Left and right regions meet along a staircase of steps two pixels across and three down + // (rows 0 to 8), a straight run of ten rows, and the same staircase again (rows 19 to 27). + // The cracks above row 9 read as the contour of a smooth area, the others as an edge, so + // the piece as a whole is no contour. + let (w, h) = (18, 28); + let edge = |y: usize| match y { + 0..9 => 2 + 2 * (y / 3), + 9..19 => 8, + _ => 10 + 2 * ((y - 19) / 3), + }; + let left: Vec = (0..w * h).map(|i| i % w < edge(i / w)).collect(); + let right: Vec = left.iter().map(|b| !b).collect(); + let step = |c: Crack| if c.at(0).unwrap().min(c.at(1).unwrap()) / w < 9 { [0.1, 0.3, 4.0, 4.0, 4.0] } else { [1.0, 1.0, 40.0, 40.0, 0.0] }; + let a = outline(&loop_of(&left, w, h), w, h, &|c| (0.0, 1, step(c)), &grid); + let b = outline(&loop_of(&right, w, h), w, h, &|c| (0.0, 2, step(c)), &grid); + let inner = |pieces: &[Piece]| { + pieces.iter().find(|p| p.pts.iter().any(|q| q.x > 0.0 && q.x < w as f64 && q.y > 0.0 && q.y < h as f64)).unwrap().clone() + }; + let (mut ours, theirs) = (inner(&a), inner(&b)); + assert!(!ours.contour); + ours.pts.reverse(); + assert_eq!(ours, theirs); + let pts = &theirs.pts; + // The upper staircase: the middle of each of its steps, on one line, and none of its corners. + let middles = [(3.0, 3.0), (4.0, 4.5), (5.0, 6.0), (6.0, 7.5), (7.0, 9.0)].map(Point::from); + assert!(middles.iter().all(|m| pts.contains(m)), "{pts:?}"); + assert!([(4.0, 3.0), (4.0, 6.0), (6.0, 6.0), (6.0, 9.0)].map(Point::from).iter().all(|c| !pts.contains(c)), "{pts:?}"); + // The straight run keeps the corners at both its ends, so it stays straight. + assert!([(8.0, 9.0), (8.0, 19.0)].map(Point::from).iter().all(|c| pts.contains(c)), "{pts:?}"); + // The lower one is a sharp edge: it keeps its corners. + assert!([(8.0, 19.0), (10.0, 19.0), (10.0, 22.0), (12.0, 22.0), (12.0, 25.0)].map(Point::from).iter().all(|c| pts.contains(c)), "{pts:?}"); + + // Steps longer than STAIR_MAX keep their corners, in a smooth area too. + let (w, h) = (40, 40); + let left: Vec = (0..w * h).map(|i| i % w < 5 + 10 * (i / w / 10)).collect(); + let pieces = outline(&loop_of(&left, w, h), w, h, &|_| (0.0, 1, [0.1, 0.3, 4.0, 4.0, 4.0]), &grid); + let pts = &inner(&pieces).pts; + assert!([(15.0, 10.0), (15.0, 20.0), (25.0, 20.0), (25.0, 30.0)].map(Point::from).iter().all(|c| pts.contains(c)), "{pts:?}"); + } + + #[test] + fn a_staircase_that_runs_on_from_a_smooth_area_into_an_edge_keeps_the_edges_corners() { + // One staircase of steps two pixels across and three down, from the top of the image to its + // bottom: its cracks above row 18 read as the contour of a smooth area, the others as an + // edge. Read as a whole, the run would pass as a contour. + let (w, h) = (20, 27); + let left: Vec = (0..w * h).map(|i| i % w < 2 + 2 * (i / w / 3)).collect(); + let right: Vec = left.iter().map(|b| !b).collect(); + let step = |c: Crack| if c.at(0).unwrap().min(c.at(1).unwrap()) / w < 18 { [0.1, 0.3, 4.0, 4.0, 4.0] } else { [1.0, 1.0, 40.0, 40.0, 0.0] }; + let a = outline(&loop_of(&left, w, h), w, h, &|c| (0.0, 1, step(c)), &grid); + let b = outline(&loop_of(&right, w, h), w, h, &|c| (0.0, 2, step(c)), &grid); + let inner = |pieces: &[Piece]| { + pieces.iter().find(|p| p.pts.iter().any(|q| q.x > 0.0 && q.x < w as f64 && q.y > 0.0 && q.y < h as f64)).unwrap().clone() + }; + let (mut ours, theirs) = (inner(&a), inner(&b)); + ours.pts.reverse(); + assert_eq!(ours, theirs); + let pts = &theirs.pts; + assert!([(3.0, 3.0), (4.0, 4.5), (9.0, 12.0), (11.0, 15.0), (12.0, 16.5)].map(Point::from).iter().all(|m| pts.contains(m)), "{pts:?}"); + assert!([(4.0, 3.0), (10.0, 15.0)].map(Point::from).iter().all(|c| !pts.contains(c)), "{pts:?}"); + // The corner where the staircase meets the edge's first step stays. + assert!([(14.0, 18.0), (14.0, 21.0), (16.0, 21.0), (16.0, 24.0), (18.0, 24.0)].map(Point::from).iter().all(|c| pts.contains(c)), "{pts:?}"); + } + + #[test] + fn a_staircase_whose_cracks_do_not_read_as_a_contour_keeps_its_corners() { + // Each step's cracks show a tenth of the step near them, but nothing changes within either + // side: two flat colors, not a smooth area. + let (w, h) = (20, 27); + let left: Vec = (0..w * h).map(|i| i % w < 2 + 2 * (i / w / 3)).collect(); + let right: Vec = left.iter().map(|b| !b).collect(); + let flat = [0.1, 0.3, 4.0, 4.0, 0.0]; + let a = outline(&loop_of(&left, w, h), w, h, &|_| (0.0, 1, flat), &grid); + let b = outline(&loop_of(&right, w, h), w, h, &|_| (0.0, 2, flat), &grid); + let inner = |pieces: &[Piece]| { + pieces.iter().find(|p| p.pts.iter().any(|q| q.x > 0.0 && q.x < w as f64 && q.y > 0.0 && q.y < h as f64)).unwrap().clone() + }; + let (mut ours, theirs) = (inner(&a), inner(&b)); + ours.pts.reverse(); + assert_eq!(ours, theirs); + let pts = &theirs.pts; + assert!([(4.0, 3.0), (4.0, 6.0), (6.0, 6.0), (10.0, 15.0)].map(Point::from).iter().all(|c| pts.contains(c)), "{pts:?}"); + assert!([(4.0, 4.5), (9.0, 12.0)].map(Point::from).iter().all(|m| !pts.contains(m)), "{pts:?}"); + } + + #[test] + fn a_staircase_step_moves_by_the_mean_shift_of_its_cracks() { + // The staircase of steps two pixels across and three down, in a smooth area. Down a step, + // its cracks move 0, 1/8 and 1/4 px; across one, 0 and 1/8 px (out of the left region; the + // right region sees them negated). + let (w, h) = (20, 27); + let left: Vec = (0..w * h).map(|i| i % w < 2 + 2 * (i / w / 3)).collect(); + let right: Vec = left.iter().map(|b| !b).collect(); + let shift = |c: Crack| { + let (p, q) = (c.at(0).unwrap(), c.at(1).unwrap()); + let v = if p / w == q / w { 0.125 * (p / w % 3) as f64 } else { 0.125 * (p % w % 2) as f64 }; + if left[p] { v } else { -v } + }; + let gentle = [0.1, 0.3, 4.0, 4.0, 4.0]; + let a = outline(&loop_of(&left, w, h), w, h, &|c| (shift(c), 1, gentle), &grid); + let b = outline(&loop_of(&right, w, h), w, h, &|c| (shift(c), 2, gentle), &grid); + let inner = |pieces: &[Piece]| { + pieces.iter().find(|p| p.pts.iter().any(|q| q.x > 0.0 && q.x < w as f64 && q.y > 0.0 && q.y < h as f64)).unwrap().clone() + }; + let (mut ours, theirs) = (inner(&a), inner(&b)); + assert!(!ours.hard); + ours.pts.reverse(); + assert_eq!(ours, theirs); + let pts = &theirs.pts; + // A step down at x = 4 moves right by 1/8 px; the step across at y = 6 moves up by 1/16 px. + assert!([(4.125, 4.5), (5.0, 5.9375), (6.125, 7.5), (7.0, 8.9375)].map(Point::from).iter().all(|m| pts.contains(m)), "{pts:?}"); + } + + #[test] + fn a_staircase_of_mixed_one_pixel_and_longer_steps_is_one_slope_without_a_notch() { + // Per four rows: three down, one across, one down, three across. Each three-pixel step meets + // the next one with no one-pixel step between them, and the one-pixel steps are a notch + // between two longer ones. All of it is the contour of a smooth area, and the cracks move by + // different amounts. + let (w, h) = (26, 24); + let edge = |y: usize| 2 + 4 * (y / 4) + usize::from(y % 4 == 3); + let left: Vec = (0..w * h).map(|i| i % w < edge(i / w)).collect(); + let right: Vec = left.iter().map(|b| !b).collect(); + let shift = |c: Crack| { + let (p, q) = (c.at(0).unwrap(), c.at(1).unwrap()); + let v = 0.125 * ((p + q) % 3) as f64 - 0.125; + if left[p] { v } else { -v } + }; + let gentle = [0.1, 0.3, 4.0, 4.0, 4.0]; + let a = outline(&loop_of(&left, w, h), w, h, &|c| (shift(c), 1, gentle), &grid); + let b = outline(&loop_of(&right, w, h), w, h, &|c| (shift(c), 2, gentle), &grid); + let inner = |pieces: &[Piece]| { + pieces.iter().find(|p| p.pts.iter().any(|q| q.x > 0.0 && q.x < w as f64 && q.y > 0.0 && q.y < h as f64)).unwrap().clone() + }; + let (mut ours, theirs) = (inner(&a), inner(&b)); + assert!(!ours.hard); + ours.pts.reverse(); + assert_eq!(ours, theirs); + let pts = &theirs.pts; + let near = |x: f64, y: f64, d: f64| pts.iter().any(|p| (p.x - x).hypot(p.y - y) < d); + for k in 1..5 { + let (c, y) = ((2 + 4 * k) as f64, (4 * k) as f64); + // The middle of each step, and no point at the corner where the three-pixel steps + // meet or at the corner the notch would make. + assert!(near(c, y + 1.5, 0.2) && near(c + 2.5, y + 4.0, 0.2), "{k}: {pts:?}"); + assert!(!near(c, y, 0.4) && !near(c, y + 4.0, 0.4), "{k}: {pts:?}"); + } + } + + /// Every point of every piece that `mask` and the region around it get in a smooth area, with + /// `junction_at` and the near share of each crack from `near`. + fn both_sides( + mask: &[bool], + w: usize, + h: usize, + near: &dyn Fn(Crack) -> [f64; 5], + junction_at: &dyn Fn(i32, i32) -> Option, + ) -> [Vec; 2] { + let other: Vec = mask.iter().map(|b| !b).collect(); + [(mask, 1), (&other[..], 2)] + .map(|(m, id)| outline(&loop_of(m, w, h), w, h, &|c| (0.0, id, near(c)), junction_at).into_iter().flat_map(|p| p.pts).collect()) + } + + #[test] + fn a_run_of_two_steps_keeps_its_corners() { + // Ten rows down, two across, three down, ten across: only two edges are short enough to + // be steps. + let (w, h) = (20, 20); + let edge = |y: usize| match y { + 0..10 => 2, + 10..13 => 4, + _ => 14, + }; + let left: Vec = (0..w * h).map(|i| i % w < edge(i / w)).collect(); + for pts in both_sides(&left, w, h, &|_| [0.1, 0.3, 4.0, 4.0, 4.0], &grid) { + assert!([(2.0, 10.0), (4.0, 10.0), (4.0, 13.0), (14.0, 13.0)].map(Point::from).iter().all(|c| pts.contains(c)), "{pts:?}"); + assert!(!pts.contains(&Point::new(4.0, 11.5)), "{pts:?}"); + } + } + + #[test] + fn a_junction_on_a_step_ends_the_staircase_there() { + // The staircase of steps two pixels across and three down, in a smooth area, with a + // junction at (8, 10), on the step down from (8, 9) to (8, 12). + let (w, h) = (20, 27); + let left: Vec = (0..w * h).map(|i| i % w < 2 + 2 * (i / w / 3)).collect(); + let junction_at = |x: i32, y: i32| (x == 8 && y == 10).then(|| Point::new(8.0, 10.0)); + for pts in both_sides(&left, w, h, &|_| [0.1, 0.3, 4.0, 4.0, 4.0], &junction_at) { + // The step keeps the corners at both its ends; the steps on either side of it are slopes. + assert!([(8.0, 9.0), (8.0, 10.0), (8.0, 12.0), (5.0, 6.0), (11.0, 15.0)].map(Point::from).iter().all(|c| pts.contains(c)), "{pts:?}"); + assert!(!pts.contains(&Point::new(8.0, 10.5)) && !pts.contains(&Point::new(6.0, 6.0)), "{pts:?}"); + } + } + + #[test] + fn a_step_whose_cracks_read_as_an_edge_ends_the_staircase_there() { + // The same staircase in a smooth area, but the cracks of the step down from (8, 9) to + // (8, 12) cannot be read across. + let (w, h) = (20, 27); + let left: Vec = (0..w * h).map(|i| i % w < 2 + 2 * (i / w / 3)).collect(); + let near = |c: Crack| { + let (p, q) = (c.at(0).unwrap(), c.at(1).unwrap()); + if p / w == q / w && (9..12).contains(&(p / w)) && (p % w).max(q % w) == 8 { EDGE_STEP } else { [0.1, 0.3, 4.0, 4.0, 4.0] } + }; + for pts in both_sides(&left, w, h, &near, &grid) { + assert!([(8.0, 9.0), (8.0, 12.0), (5.0, 6.0), (11.0, 15.0)].map(Point::from).iter().all(|c| pts.contains(c)), "{pts:?}"); + assert!(!pts.contains(&Point::new(8.0, 10.5)) && !pts.contains(&Point::new(6.0, 6.0)), "{pts:?}"); + } + } + #[test] fn a_shift_that_is_not_a_number_moves_nothing() { let mask = [true, true, false, false, true, true, false, false]; diff --git a/docs/image-trace-quality.md b/docs/image-trace-quality.md index 034e009f17..f949d06071 100644 --- a/docs/image-trace-quality.md +++ b/docs/image-trace-quality.md @@ -156,6 +156,47 @@ under 0.9 px RMS from the gradient's contours, 1.13 px when smoothed as edges, a four corners); `layers::tests` (a ramp, flat colors in palette entries far apart, close flat colors, a thin flat stroke, colors off the line between their entries, and Grayscale's grays, each read from both sides of the crack) and `subpixel::tests` (the rule, and one decision for a whole piece from either side). +## Staircases in smooth areas +Where a band border in a gradient or a shaded area runs at a slant, its pixels form a staircase whose +steps are two or more pixels long. One piece of outline can run along a sharp edge in the image and then +along such a border with no junction between them. That piece as a whole is not a contour (see above), +and the outline kept a corner at every step. `subpixel::outline` now reads a run of three or more edges of +1 to 8 px (`STAIR_MAX`), each turning one way where it starts and the other where it ends, with no +junction on it, as a staircase when the run's own cracks pass `subpixel::low_contrast`. A run is cut at +any step whose own cracks show half of the step between the two colors or more. The 8 px limit and the +one-half cut are VectorCraft's own values. The run's edges are then steps, as one-pixel steps already +were: the outline has no corner where two of them meet, and each gives one point, its middle, moved by the +mean of its cracks' shifts. Where a run meets an edge that is not a step, the corner between them stays, +so a straight edge longer than 8 px next to a staircase stays straight. A straight edge of 8 px or less +between two turns of opposite sign is read as one more step of the run. Inside a run, two one-pixel steps +between longer ones are read as part of the slope and do not make a notch. A staircase of longer steps, +and one whose cracks read as an edge, keep their corners, and Black and White traces do not use the rule. +The runs are the same from either side of the border. +Measured with the harness below, before and after the change: rows of the "flat colour art" inputs do not +change. On gradient and photo inputs, anchors change in 106 rows, 101 of them fewer, by −64% to +6.4%: for +example 390 to 142 (Shades of Gray, linear gradients), 1,860 to 1,537 (High Fidelity Photo, linear +gradients), 6,766 to 6,542 (High Fidelity Photo, gradient and photo) and 47 to 50 (High Fidelity Photo with +Gradients, blurred). On gradient and photo, 6 Colors, 6 Colors with Shapes, with Auto Grouping, without +Gradients and enhanced each leave a gap of 0.9 px (was 1.2) and an overlap of 1.0 px (was 0.8). Edge ΔE +of Shades of Gray on linear gradients goes from 8.36 to 8.40 (8.39 enhanced), and that of 6 Colors with +Gradients on a blurred input from 2.24 to 2.22; other ΔE and edge ΔE values change by 0.01 or less. +Lines % changes by −2 to +3, grouped % by −1 to +4, upright % by +1 in 3 rows (Shades of Gray on a blurred +input), and specks do not change. On synthetic photos of 800 and 4,000 px traced outside this harness, +the corners of rectilinear staircases per 100 px of outline fall from 0.57 to 0.46 and from 1.09 to 0.94 +with High Fidelity Photo. On the 800 px photo, the 95th percentile of the pixel difference with High +Fidelity Photo rises from 6.33 to 6.67, and 16 Colors leaves 2 staircases of steps of 2 px or more where +it left none. The tables below are the previous measurement, not a rerun. +Tests on code-drawn outlines in `subpixel::tests`: +`a_staircase_of_longer_steps_in_a_smooth_area_becomes_the_slope_through_its_steps` (a piece with a +staircase of 2 × 3 px steps in a smooth area, a straight run and the same staircase on a sharp edge: the +first gives its steps' middles and none of its corners, the straight run keeps the corners at its ends, the +second staircase keeps its corners, both regions get the same points, and 10 px steps keep their corners +in a smooth area), `a_staircase_that_runs_on_from_a_smooth_area_into_an_edge_keeps_the_edges_corners`, +`a_staircase_whose_cracks_do_not_read_as_a_contour_keeps_its_corners` (two flat colors), +`a_staircase_step_moves_by_the_mean_shift_of_its_cracks`, +`a_staircase_of_mixed_one_pixel_and_longer_steps_is_one_slope_without_a_notch`, +`a_run_of_two_steps_keeps_its_corners`, `a_junction_on_a_step_ends_the_staircase_there` and +`a_step_whose_cracks_read_as_an_edge_ends_the_staircase_there`. ## A simpler contour walk `contour::trace_mask` follows each region's outline along the pixel cracks with the inside on the right. It used to build a table of outgoing directions for every pixel corner in a raster pass and diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index d9783b0216..a523a01945 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1328,6 +1328,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Image Trace, notches read only their own piece:** the notch rule of `subpixel::outline` reads only the shared piece, so both regions of an edge cut a corner pixel alike and leave no gap; a code-drawn noisy multi-colour coverage test in `crates/trace` (see [quality notes](image-trace-quality.md#notches-read-only-their-own-piece)). - **Image Trace, same shift from either side of an edge:** a crack's sub-pixel shift is averaged from its two sides, so abutting regions on one- and two-pixel slivers get the same points and leave nothing uncovered; code-drawn regressions in `crates/trace` (see [quality notes](image-trace-quality.md#same-sub-pixel-shift-from-either-side-of-an-edge)). - **Image Trace, band borders in smooth areas:** in Color and Grayscale traces, a border between two colors where the image changes gradually is the contour of a smooth area, by VectorCraft's own rule (`subpixel::low_contrast`, distances measured in RGB, 0 to 255 a channel): next to the border the image makes less than half the step between the two colors; it makes more of the step a few pixels further out, or changes by a distance under 12 (about 7 levels in each channel of a gray); the pixels on each side change too; and its whole change next to the border is under twice its change from one color towards the other, or under 24. Grayscale reads each pixel as its gray, for this rule and for every edge's sub-pixel position. Such a border is smoothed over about 4 px instead of 0.5 px (0.9 px for an edge without anti-aliasing), keeps no corners and is fitted to at least 0.5 px, so band borders in photos and gradients follow the image's contours with fewer anchors; without Shapes, both colors beside it share the same curve. Color traces of clean flat-color art and Black and White traces are unchanged, Grayscale traces of colored art place their edges closer to the art's outlines, and noisy flat-color art can take fewer anchors where noise splits a color into bands; see [quality notes](image-trace-quality.md#band-borders-in-smooth-areas). Tests: `tests::the_borders_of_a_gradients_bands_follow_its_contours`, `layers::tests` and `subpixel::tests` in `crates/trace`. Scores and hours unchanged. +- **Image Trace, staircases in smooth areas:** in Color and Grayscale traces, a staircase of three or more steps of 1 to 8 px along a border between two colors, where the image changes gradually by the same rule (`subpixel::low_contrast`, read for the staircase alone, which ends at any step that shows half of the step between the two colors or more; the 8 px limit and the one-half cut are VectorCraft's own values), is traced as the slope through the middles of its steps with no corner at each step, also on an outline that runs on along a sharp edge in the image. The corner where a staircase meets a straight edge longer than 8 px stays. Longer steps, staircases along a sharp edge and Black and White traces keep their corners; 6 Colors on gradient and photo leaves a gap of 0.9 px (was 1.2) and an overlap of 1.0 px (was 0.8), and High Fidelity Photo with Gradients on a blurred input takes 50 anchors (was 47); see [quality notes](image-trace-quality.md#staircases-in-smooth-areas) for these and the other rows that got worse. Tests: eight `subpixel::tests` in `crates/trace`, starting with `a_staircase_of_longer_steps_in_a_smooth_area_becomes_the_slope_through_its_steps`. Scores and hours unchanged. - **Image Trace, cut-out edges:** in Color and Grayscale, a semi-transparent pixel (alpha 128 to 254) on the edge of a cut-out image, beside a pixel that is less than half opaque, traces as a color of the fully opaque pixels within two pixels of it when its own color is that color or a darker shade of it, and of several such colors, as the one the most of those pixels have (art across a transparent gap does not count), so a darkened edge tone no longer traces as a 1 px sliver of an unrelated palette color, while a thin semi-transparent outline of another color keeps its own; code-drawn cut-out, opaque-edge and thin-outline tests in `crates/trace`. - **Image Trace, cut-out edges choose no color:** in Color and Grayscale, the edge pixels that take the color beside them, and the semi-transparent pixels within two pixels of them whose color is also the opaque art's color blended with the background, do not count when the palette or the grays are chosen, so the edge of a cut-out image no longer adds a second shade of a color to Auto Color's palette, takes away an outline's color or takes a gray of its own; beside those pixels, the anti-aliasing between a color and an outline drawn along the edge is no color of Auto Color's own when it lies at least 0.45 of the way from the color to the outline and at least one in 32 of its pixels has both around it (edge pixels that choose no color count when they lie within 2.5 Oklab × 100 of the nearest of those colors): its pixels trace as the outline, so a thin outline stays a ring of few pieces, except beside an outline along the edge with a region of 8 pixels of its own, where each takes the nearer of the two, so a wider outline is not drawn wider; an outline over the edge in the color of other art traces in that color, while an opaque rim drawn along the edge keeps its color, also where other art reaches it; a thin semi-transparent outline of another color still counts, and opaque images trace as before; code-drawn cut-out outline, rim, opaque line and grayscale edge tests in `crates/trace`. - **Image Trace, simpler contour walk:** `contour::trace_mask` works out each turn from the pixels during the walk, with no precomputed direction table and no assertion; identical loops to the previous walk on every 4 × 4 mask (see [quality notes](image-trace-quality.md#a-simpler-contour-walk)). From d1c8ff78def306a8396bf3eddbcf551c78e903a7 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 08:31:25 -0800 Subject: [PATCH 25/25] =?UTF-8?q?Context=20menu:=20Smooth=E2=80=A6=20on=20?= =?UTF-8?q?a=20selected=20path=20opens=20the=20Smooth=20slider?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A right-click on a selection that holds a path (a path, a group of paths, a compound path, or anchors selected with Direct Selection) lists Smooth…, after Join and Average… and the anchor entries when those are listed. It opens the slider that Object › Path › Smooth opens, which previews the result until OK keeps it as one undo step. With nothing, only type or a group of type selected, Smooth… is not listed. Docs: docs/mcp.md, docs/target-app-parity.md. --- crates/mcp/src/ui_catalog.rs | 2 +- crates/ui-egui/src/menus/context.rs | 4 ++ crates/ui-egui/src/menus/ui_commands.rs | 2 +- crates/ui-egui/src/tests/contextmenu.rs | 90 +++++++++++++++++++++++++ docs/mcp.md | 7 +- docs/target-app-parity.md | 1 + 6 files changed, 101 insertions(+), 5 deletions(-) diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 2337e08a23..0e835a8325 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -1236,7 +1236,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.smoothAuto", "Auto-Smooth", "", - "{} the open Smooth slider (Object › Path › Smooth opens it: dialog `smoothSlider` with field `level` 0..100, object.path.smooth's level, opening at the level object.path.smooth {auto: true} picks, previewed on the canvas until ui.dialog.confirm keeps it as one undo step) moves to the level object.path.smooth {auto: true} picks and previews it → {level}; an error when the slider isn't open", + "{} the open Smooth slider (Object › Path › Smooth and the canvas context menu's Smooth… open it: dialog `smoothSlider` with field `level` 0..100, object.path.smooth's level, opening at the level object.path.smooth {auto: true} picks, previewed on the canvas until ui.dialog.confirm keeps it as one undo step) moves to the level object.path.smooth {auto: true} picks and previews it → {level}; an error when the slider isn't open", ), ( "ui.simplifyMoreOptions", diff --git a/crates/ui-egui/src/menus/context.rs b/crates/ui-egui/src/menus/context.rs index abf43a3584..bc11e703e0 100644 --- a/crates/ui-egui/src/menus/context.rs +++ b/crates/ui-egui/src/menus/context.rs @@ -73,6 +73,10 @@ pub fn context_items(app: &VectorcraftApp) -> Vec { if !st.selection.anchors.is_empty() { v.extend([c("Remove Anchor Points", "path.removeAnchors"), c("Cut Path at Selected Anchor Points", "path.cutAtAnchors")]); } + // Object › Path › Smooth…, which opens the Smooth slider (`invoke`). `prune` leaves it out + // unless object.path.smooth can run: the selection holds a path, in a group or a compound + // path too. + v.push(c("Smooth…", "object.path.smooth")); if several { v.push(c("Make Clipping Mask", "object.clippingMask.make")); } diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index bb4481e532..fe980cc9d0 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1237,7 +1237,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.smoothAuto", "Auto-Smooth", "", - "{} the open Smooth slider (Object › Path › Smooth opens it: dialog `smoothSlider` with field `level` 0..100, object.path.smooth's level, opening at the level object.path.smooth {auto: true} picks, previewed on the canvas until ui.dialog.confirm keeps it as one undo step) moves to the level object.path.smooth {auto: true} picks and previews it → {level}; an error when the slider isn't open", + "{} the open Smooth slider (Object › Path › Smooth and the canvas context menu's Smooth… open it: dialog `smoothSlider` with field `level` 0..100, object.path.smooth's level, opening at the level object.path.smooth {auto: true} picks, previewed on the canvas until ui.dialog.confirm keeps it as one undo step) moves to the level object.path.smooth {auto: true} picks and previews it → {level}; an error when the slider isn't open", ), ( "ui.simplifyMoreOptions", diff --git a/crates/ui-egui/src/tests/contextmenu.rs b/crates/ui-egui/src/tests/contextmenu.rs index b443d84586..b73bb08dfa 100644 --- a/crates/ui-egui/src/tests/contextmenu.rs +++ b/crates/ui-egui/src/tests/contextmenu.rs @@ -248,6 +248,96 @@ fn the_menu_follows_the_selection() { assert!(items.windows(2).all(|w| !matches!(w, [Item::Sep, Item::Sep]))); } +/// A closed path of 60 jagged anchors around (150, 150), filled so that a right-click inside it +/// hits it, with nothing selected. +fn jagged(app: &mut VectorcraftApp) -> NodeId { + let anchors: Vec<_> = (0..60) + .map(|i| { + let a = f64::from(i) * std::f64::consts::TAU / 60.0; + let r = 60.0 + f64::from(i % 2) * 4.0; + json!({"x": 150.0 + r * a.cos(), "y": 150.0 + r * a.sin()}) + }) + .collect(); + let id = NodeId(app.run("path.create", json!({"anchors": anchors, "closed": true})).unwrap()["id"].as_u64().unwrap()); + app.run("paint.setFill", json!({"color": "#ff8010"})).unwrap(); + app.run("select.none", json!({})).unwrap(); + id +} + +/// The anchor points of every path in the document. +fn anchor_total(app: &VectorcraftApp) -> usize { + let mut n = 0; + app.session.active().unwrap().doc.walk(|node| { + if let NodeKind::Path { path, .. } = &node.kind { + n += path.anchor_count(); + } + }); + n +} + +/// A right-click on a path lists Object › Path › Smooth… after Join and Average…. Smooth… opens +/// the Smooth slider at Auto-Smooth's level and adds no undo step while it is open; OK keeps the +/// smoothed path as one undo step. +#[test] +fn right_click_on_a_path_opens_the_smooth_slider() { + let mut app = app(); + let id = jagged(&mut app); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + let p = screen(&app, 150.0, 150.0); + let texts = click(&mut app, &ctx, p, PointerButton::Secondary); + assert_eq!(app.session.active().unwrap().selection.objects, [id], "the path right-clicked is selected"); + let y = |label| at(&texts, label).y; + assert!(y("Join") < y("Average…") && y("Average…") < y("Smooth…"), "{texts:?}"); + let (undo, before) = (app.session.active().unwrap().history.undo.len(), anchor_total(&app)); + let after = click(&mut app, &ctx, at(&texts, "Smooth…"), PointerButton::Primary); + assert!(!has(&after, "Arrange"), "choosing Smooth… closes the menu"); + let open = app.ui.dialog.as_ref().map(|d| (d.kind.clone(), d.f64("level", -1.0))); + assert_eq!(open, Some((crate::dialogs::smooth_slider::KIND.to_string(), vectorcraft_engine::SMOOTH_AUTO_LEVEL))); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo, "no undo step while the slider is open"); + crate::dialogs::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none() && !app.session.in_interaction()); + let st = app.session.active().unwrap(); + assert_eq!(st.history.undo.len(), undo + 1, "OK keeps the result as one undo step"); + assert!(anchor_total(&app) < before, "the path was smoothed: {} anchor points from {before}", anchor_total(&app)); +} + +/// Smooth… is listed while the selection holds a path: a path, a group of paths, a compound path, +/// a path with type, and anchors selected with Direct Selection (whose Remove Anchor Points +/// stays). It is left out with nothing, only type or a group of type selected. +#[test] +fn smooth_follows_the_selections_paths() { + let mut app = app(); + let (a, b) = (rect(&mut app, 0.0, 0.0), rect(&mut app, 150.0, 0.0)); + let t = NodeId(app.run("text.create", json!({"x": 10, "y": 250, "text": "Type"})).unwrap()["id"].as_u64().unwrap()); + let smooth = |app: &VectorcraftApp| labels(&menus::context_items(app)).contains(&"Smooth…"); + app.run("select.none", json!({})).unwrap(); + assert!(!smooth(&app), "nothing selected"); + app.run("select.set", json!({"ids": [t.0]})).unwrap(); + assert!(!smooth(&app), "only type selected"); + let u = NodeId(app.run("text.create", json!({"x": 10, "y": 300, "text": "More"})).unwrap()["id"].as_u64().unwrap()); + app.run("select.set", json!({"ids": [t.0, u.0]})).unwrap(); + app.run("object.group", json!({})).unwrap(); + assert!(!smooth(&app), "a group of type only"); + app.run("object.ungroup", json!({})).unwrap(); + app.run("select.set", json!({"ids": [a.0]})).unwrap(); + assert!(smooth(&app), "a path"); + app.run("select.set", json!({"ids": [a.0, t.0]})).unwrap(); + assert!(smooth(&app), "a path and type"); + app.run("select.set", json!({"ids": [a.0, b.0]})).unwrap(); + app.run("object.group", json!({})).unwrap(); + assert!(smooth(&app), "a group of paths"); + app.run("object.ungroup", json!({})).unwrap(); + app.run("select.set", json!({"ids": [a.0, b.0]})).unwrap(); + app.run("object.compoundPath.make", json!({})).unwrap(); + assert!(smooth(&app), "a compound path"); + app.run("object.compoundPath.release", json!({})).unwrap(); + app.select_tool("directSelection"); + app.run("select.anchors", json!({"id": a.0, "anchors": [[0, 1]]})).unwrap(); + assert!(smooth(&app), "an anchor point direct-selected"); + assert!(labels(&menus::context_items(&app)).contains(&"Remove Anchor Points"), "the anchor entries stay"); +} + /// Selected type has Bullets and Numbering › Apply Bullets in the context menu and the Type menu, /// which makes its paragraphs a bulleted list; other art has no such item. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 9930b33734..3b20752472 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -4989,9 +4989,10 @@ round, such as a rectangle, stays as it is. Closed paths stay closed and open pa {"name":"run_command","arguments":{"command":"object.path.smooth","params":{"level":80}}} ``` -In the desktop app, Object › Path › Smooth opens the slider (`ui.menuDialog {command: "object.path.smooth"}`, dialog -`smoothSlider` with field `level`) at the Auto-Smooth level and previews the result until `ui.dialog.confirm`; -`ui.smoothAuto` moves the open slider back to the Auto-Smooth level. +In the desktop app, Object › Path › Smooth and the canvas context menu's Smooth… (listed while the selection holds a +path) open the slider (`ui.menuDialog {command: "object.path.smooth"}`, dialog `smoothSlider` with field `level`) at +the Auto-Smooth level, and the slider previews the result until `ui.dialog.confirm`; `ui.smoothAuto` moves the open +slider back to the Auto-Smooth level. ## Editing a path with the Curvature tool diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f9c6855f68..f716249f2f 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -909,6 +909,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Dry Media library** ([help page](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/about-brushes.html)): Window › Brush Libraries › Dry Media holds four art brushes with textured strokes like dry drawing materials, each 100 pt long: Chalk Grain (about 8 pt high), Graphite Pencil (about 2.3 pt), Wax Crayon (about 5.5 pt) and Charcoal Dust (about 7 pt). The brushes, their names, sizes and art are VectorCraft's own: each is filled vector paths from a fixed seed, at most 80 paths and 500 anchors, stretched along the path with Tints colorization, and the chalk and crayon art has even-odd gaps where the paper shows (`brush.libraries`, `brush.addFromLibrary`; `the_dry_media_library_holds_grainy_art_brushes_with_bounded_art`). - A canvas context menu: right-click selects the object under the pointer and lists what applies to the selection (Undo/Redo, clipboard, group, isolation, join, Remove Anchor Points when anchors are selected, masks, compound paths, guides, Transform, Arrange, Select, Export Selection, and on type Bullets and Numbering and Spelling › Auto Spell Check, checked while it is on), or the view commands on empty canvas. - A right-click over locked objects adds an Unlock submenu to the canvas context menu. The submenu lists up to 20 locked objects under the pointer, topmost first, by the name the Layers panel shows, and choosing one unlocks it (`layer.setProps`). A locked group is listed as one item. Objects on hidden, locked or template layers are not listed. + - The canvas context menu lists Object › Path › Smooth… while the selection holds a path, in a group or a compound path too. It opens the Smooth slider, as the Object menu does (`right_click_on_a_path_opens_the_smooth_slider`, `smooth_follows_the_selections_paths`). - Native macOS save sheets offer a localised Format menu (#866), built from the request's existing format filters. It selects the suggested filename's format and updates the suffix when changed, including legacy `.drawcraft` names. `apps/vectorcraft/src/mac_save_format.rs` has filename regressions; an actual native SVG save, selection of PDF and cancellation without changing the saved document were verified. - Save / Don't Save / Cancel before closing or quitting with unsaved documents (tabs, Close, Close All, Quit, window close). - Four brightness themes, persistent preferences.