diff --git a/.github/workflows/windows-arm64.yml b/.github/workflows/windows-arm64.yml index 7fc9b59251..b121ce45f1 100644 --- a/.github/workflows/windows-arm64.yml +++ b/.github/workflows/windows-arm64.yml @@ -27,8 +27,8 @@ permissions: jobs: windows-arm64: - # Immutable supporting workflow revision until the new install contract lands upstream. - uses: storytold/craft-common-actions/.github/workflows/windows-arm64.yml@8bb4e5ab95443171104ad88113fe1ef9b0e5ce3f + # Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos. + uses: storytold/craft-common-actions/.github/workflows/windows-arm64.yml@main with: app-name: vectorcraft app-dir: VectorCraft diff --git a/AGENTS.md b/AGENTS.md index 61f141079e..1677f01c52 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -86,3 +86,8 @@ When a task lands, update in the same PR: the area row in `docs/target-app-parit GitHub profiles). Never hand-edit `contributors.json`. - Maintainers refresh the stats with `python3 ../../craftrules/scripts/contributors.py .` (it also re-verifies who wrote each `people.toml` entry; `--check` only verifies). + +## CI workflows +- Workflows in `.github/workflows/` call the shared workflows in [`storytold/craft-common-actions`](https://github.com/storytold/craft-common-actions) at `@main`, with their inputs and secrets. No other jobs: if no shared workflow does what's needed, it doesn't go here. +- Don't add or change CI in a feature or fix PR. If the existing workflows can't build or test a change, link an existing craft-common-actions issue or PR, or open a new issue, or a PR only for a small fix that is safe for every app and does not increase CI time. +- Some workflow files here still run their own jobs. Don't add to them. Moving a job into craft-common-actions is its own task, never part of another PR, and the job stays here until a shared workflow runs it. diff --git a/CLAUDE.md b/CLAUDE.md index 0460b61925..2b6ffcc436 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -69,3 +69,8 @@ The progress docs follow craftrules' [`standards/progress-docs.md`](https://gith When a task lands, update in the same PR: the area row in `docs/target-app-parity.md` (score, missing items, hours) and its evidence list, the gap entry in `docs/gaps.md` if it closed or shrank, the checklist it belongs to, the milestone row in `docs/roadmap.md`, and the ROADMAP's tables and progress log when a headline number moves. Update each touched doc's status line and revision history. - Grade by behaviour against the public documentation (`plan/illustrator/` notes), not by whether a menu item exists. Scores are self-assessed, so err low; mark each number measured or estimated. - Keep the README's Status section in step with the ROADMAP headline. + +## CI workflows +- Workflows in `.github/workflows/` call the shared workflows in [`storytold/craft-common-actions`](https://github.com/storytold/craft-common-actions) at `@main`, with their inputs and secrets. No other jobs: if no shared workflow does what's needed, it doesn't go here. +- Don't add or change CI in a feature or fix PR. If the existing workflows can't build or test a change, link an existing craft-common-actions issue or PR, or open a new issue, or a PR only for a small fix that is safe for every app and does not increase CI time. +- Some workflow files here still run their own jobs. Don't add to them. Moving a job into craft-common-actions is its own task, never part of another PR, and the job stays here until a shared workflow runs it. diff --git a/Cargo.lock b/Cargo.lock index 78306baae3..e8aa942dfa 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -217,7 +217,7 @@ dependencies = [ "objc2-foundation 0.3.2", "parking_lot", "percent-encoding", - "windows-sys 0.61.2", + "windows-sys 0.59.0", "wl-clipboard-rs", "x11rb", ] @@ -1017,7 +1017,7 @@ source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13af dependencies = [ "craft-winprint-gdi", "miniz_oxide 0.9.1", - "roxmltree 0.21.1", + "roxmltree 0.21.2", "tempfile", "winprint", "winsafe", @@ -1047,13 +1047,14 @@ dependencies = [ [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0" +source = "git+https://github.com/storytold/craft-libs?rev=1065653e75854e9c17e1ff563acdd344c1b185f0#1065653e75854e9c17e1ff563acdd344c1b185f0" dependencies = [ "chrono", "dunce", "egui", "flate2", "getrandom 0.3.4", + "image", "log", "plist", "semver", @@ -1562,7 +1563,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -3617,7 +3618,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -4139,7 +4140,7 @@ dependencies = [ "once_cell", "socket2", "tracing", - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -4445,9 +4446,9 @@ checksum = "6c20b6793b5c2fa6553b250154b78d6d0db37e72700ae35fad9387a46f487c97" [[package]] name = "roxmltree" -version = "0.21.1" +version = "0.21.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f1964b10c76125c36f8afe190065a4bf9a87bf324842c05701330bba9f1cacbb" +checksum = "9da7f59328b09405b181fee1018925fad50f157afb43c0c0f5c522c256dd5907" dependencies = [ "memchr", ] @@ -4496,7 +4497,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys 0.12.1", - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -4555,7 +4556,7 @@ dependencies = [ "security-framework", "security-framework-sys", "webpki-root-certs", - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -5414,10 +5415,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" dependencies = [ "fastrand", - "getrandom 0.4.3", + "getrandom 0.3.4", "once_cell", "rustix 1.1.5", - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -5992,7 +5993,7 @@ dependencies = [ "kurbo 0.13.1", "log", "pico-args", - "roxmltree 0.21.1", + "roxmltree 0.21.2", "simplecss", "siphasher", "skrifa 0.44.0", @@ -6196,7 +6197,7 @@ dependencies = [ "kurbo 0.13.1", "log", "proptest", - "roxmltree 0.21.1", + "roxmltree 0.21.2", "rustix 1.1.5", "ruzstd", "serde", @@ -6335,7 +6336,7 @@ dependencies = [ "kurbo 0.13.1", "log", "md-5", - "roxmltree 0.21.1", + "roxmltree 0.21.2", "serde", "serde_json", "sha2", @@ -7181,7 +7182,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -7907,9 +7908,9 @@ dependencies = [ [[package]] name = "zip" -version = "9.1.0" +version = "9.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2886b00003a72c4ccee3f42cfc34908d33b2508a74d827dc2a4244706475c704" +checksum = "1156b39d142a34b999c2310a50455e0cb3760bf7efad0122f796d813bee26ccb" dependencies = [ "crc32fast", "flate2", diff --git a/Cargo.toml b/Cargo.toml index c134a3c19d..28cd269e91 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -19,7 +19,8 @@ craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "92d392c # Decides who draws the window frame (desktop vs. app) so the suite shares one native titlebar per # desktop. The `egui` feature adds `craft_window::decorate`. (craft-libs#217.) craft-window = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0", features = ["egui"] } -craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0", features = ["egui"] } +# craft-update with storytold/craft-libs#434: the update prompt shows the app's icon, accent and developer. +craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "1065653e75854e9c17e1ff563acdd344c1b185f0", features = ["egui"] } # internal vectorcraft-geom = { path = "crates/geom" } vectorcraft-color = { path = "crates/color" } diff --git a/ROADMAP.md b/ROADMAP.md index 8231428eeb..8a4d00db95 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -144,6 +144,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap | Date | What landed | |---|---| +| 2026-10-29 | Linux: a clipboard that can't be opened (the Flatpak on GNOME, where arboard has neither data-control nor X11) is retried after 1 s, doubling to a minute, and logged once, where the background Paste check used to reconnect and log a warning every 250 ms (267k warnings in 18 h). Scores and estimates unchanged. | | 2026-10-21 | 3D lighting: four original lighting presets shared by Revolve, Extrude & Bevel, Inflate and Rotate, with command access and manual Custom settings; scores and estimates unchanged. | | 2026-10-21 | Print: the Print dialog's Media list has the Japanese papers — JIS B4 (257 × 364 mm), JIS B5 (182 × 257 mm) and JIS B6 next to the ISO B4/B5 (which keep their ISO 216 dimensions for settings saved before them), はがき 100 × 148 mm, 往復はがき 148 × 200 mm, 封筒 長形3号 120 × 235 mm / 長形4号 90 × 225 mm / 角形2号 240 × 332 mm / 角形3号 216 × 277 mm and 四六判 127 × 188 mm. A paper is named by its JSON id or its dialog label, any case and spacing (`B5 (JIS)` or `b5jis`), and every added size prints as its own PDF page size. Headline numbers unchanged. | | 2026-10-18 | Inch rulers divide the inch in half, not in ten. Zooming in stepped an inch ruler through 0.2, 0.1 and 0.05 of an inch, marks an inch ruler does not carry; below an inch the steps are binary fractions now, 1/2 down to 1/16, with the unlabelled ticks between them binary too (down to 1/128, so the 32nds, 64ths and 128ths appear as the report expects), while the metric units, points, pixels and picas keep their tenths. A label carries the decimals its step needs, so a sixteenth reads 0.0625 rather than the rounded 0.06, with trailing zeros dropped (#2827). Headline numbers unchanged. | @@ -198,6 +199,7 @@ The full pre-standard record of what landed is kept in [docs/roadmap.md](docs/ro | Date | Change | Summary | |---|---|---| +| 2026-10-29 | minor | Progress log row for the Linux clipboard retry backoff; headline numbers unchanged. | | 2026-10-23 | minor | Progress log row for Pathfinder › Trap; Live vector effects hours 6–10 → 4–8; headline numbers unchanged. | | 2026-10-23 | minor | Progress log row for OpenType SVG colour fonts; headline numbers unchanged. | | 2026-10-23 | minor | Progress log row for COLR colour fonts; headline numbers unchanged. | diff --git a/apps/vectorcraft/src/app.rs b/apps/vectorcraft/src/app.rs index 2847004b34..05c756a0c0 100644 --- a/apps/vectorcraft/src/app.rs +++ b/apps/vectorcraft/src/app.rs @@ -1,6 +1,6 @@ #[cfg(all(target_os = "macos", feature = "accessibility", feature = "wgpu"))] use super::gpu; -use super::prefs::save_prefs; +use super::prefs::{save_prefs, save_prefs_soon}; #[cfg(all(windows, not(target_vendor = "win7")))] use super::windows_stylus; use super::{App, VectorcraftApp, file_access, window}; @@ -71,6 +71,9 @@ impl eframe::App for App { // (the system shutting down, the process ended or crashing) used to lose them (#1747). if self.app.take_prefs_changed() { file_access::unconfined(|| save_prefs(&self.app)); + } else { + // The workspace, panels and other UI settings change without the dialog (#4625). + file_access::unconfined(|| save_prefs_soon(&self.app)); } // Not while a file dialog's sheet has the keyboard: its name field's composition would go. #[cfg(target_os = "macos")] diff --git a/apps/vectorcraft/src/clipboard.rs b/apps/vectorcraft/src/clipboard.rs index ef3832f1e2..fcaf3857d6 100644 --- a/apps/vectorcraft/src/clipboard.rs +++ b/apps/vectorcraft/src/clipboard.rs @@ -9,7 +9,8 @@ //! and EPS as vector art (#1499) and its PNG or TIFF as they are, as screenshots copy them (on //! Linux arboard reads no other formats). On Wayland, arboard's data-control //! backend reads the compositor's clipboard (X11 through XWayland only sees what X11 apps -//! copied), falling back to X11 where the compositor lacks the protocol. +//! copied), falling back to X11 where the compositor lacks the protocol. A clipboard that can't +//! be opened is tried again after a wait that grows to a minute, not each time Paste asks. //! - Everywhere: files copied in a file manager paste as the first one that is art (SVG, PDF, EPS, //! a metafile or a bitmap), before the clipboard's other formats (the files' paths as text). @@ -310,6 +311,8 @@ mod win { #[cfg_attr(windows, allow(dead_code))] mod portable { use std::borrow::Cow; + use std::sync::atomic::{AtomicBool, Ordering}; + use std::time::{Duration, Instant}; use super::{BITMAP, Flavour, PNG, SystemClipboard, TEXT, copied_file, decode_png, png_flavour, text_of}; @@ -319,19 +322,113 @@ mod portable { Image(usize, usize), } - #[derive(Default)] + /// Who asks for the clipboard: the background paste check waits out the whole wait after a + /// failure, a Copy or Paste of the user's [`USER_RETRY`] at most. + #[derive(Clone, Copy, PartialEq, Eq, Debug)] + pub(super) enum Asker { + Probe, + User, + } + + /// The wait after the first failure to open the clipboard; it doubles with each failed retry. + const FIRST_WAIT: Duration = Duration::from_secs(1); + /// The longest wait between retries. + const MAX_WAIT: Duration = Duration::from_secs(60); + /// A Copy or Paste of the user's retries at most this often. + const USER_RETRY: Duration = Duration::from_secs(1); + + /// Whether "unavailable" has been logged and not yet answered by "available again": the + /// clipboard and its background check hold a handle each, and their failures are one outage. + static UNAVAILABLE_LOGGED: AtomicBool = AtomicBool::new(false); + + /// A failure to open, and when to try again. + struct Failed { + at: Instant, + wait: Duration, + } + + /// A handle opened on first use and kept, or after a failure opened again only once its wait is + /// over: where the clipboard can't be opened, asking a few times a second must not reconnect each time. + pub(super) struct Reopen { + handle: Option, + failed: Option, + /// The outage flag shared with the other handles ([`UNAVAILABLE_LOGGED`]). + logged: &'static AtomicBool, + } + + impl Reopen { + pub(super) fn new(logged: &'static AtomicBool) -> Self { + Self { handle: None, failed: None, logged } + } + + /// The open handle, opened with `open` when there is none and `asker` may try at `now`. + /// `name` names an opened handle in the log. + pub(super) fn get( + &mut self, + asker: Asker, + now: Instant, + open: impl FnOnce() -> Result, + name: impl Fn(&B) -> &'static str, + ) -> Option<&mut B> { + if self.handle.is_none() { + if let Some(f) = &self.failed { + let wait = match asker { + Asker::Probe => f.wait, + Asker::User => f.wait.min(USER_RETRY), + }; + if now.saturating_duration_since(f.at) < wait { + return None; + } + } + match open() { + Ok(handle) => { + if self.logged.swap(false, Ordering::Relaxed) { + log::info!("the system clipboard is available again, through {}", name(&handle)); + } else { + log::debug!("system clipboard opened through {}", name(&handle)); + } + self.failed = None; + self.handle = Some(handle); + } + Err(why) => { + let wait = match &self.failed { + Some(f) => (f.wait * 2).min(MAX_WAIT), + None => FIRST_WAIT, + }; + if self.logged.swap(true, Ordering::Relaxed) { + log::debug!("the system clipboard is still unavailable ({why}); next try in {wait:?}"); + } else { + log::warn!("the system clipboard is unavailable ({why}): Copy and Paste stay inside VectorCraft"); + } + self.failed = Some(Failed { at: now, wait }); + } + } + } + self.handle.as_mut() + } + + /// The handle if one is open, without trying to open one. + pub(super) fn opened(&mut self) -> Option<&mut B> { + self.handle.as_mut() + } + } + pub struct Clipboard { /// Kept open: on Linux the copied data lives as long as the handle does. - cb: Option, + cb: Reopen, ours: Option, } + impl Default for Clipboard { + fn default() -> Self { + Self { cb: Reopen::new(&UNAVAILABLE_LOGGED), ours: None } + } + } + impl Clipboard { - fn cb(&mut self) -> Result<&mut arboard::Clipboard, String> { - if self.cb.is_none() { - self.cb = Some(arboard::Clipboard::new().map_err(|e| e.to_string())?); - } - self.cb.as_mut().ok_or_else(|| "no system clipboard".to_string()) + fn cb(&mut self, asker: Asker) -> Result<&mut arboard::Clipboard, String> { + let open = || arboard::Clipboard::new().map_err(|e| e.to_string()); + self.cb.get(asker, Instant::now(), open, |_| "arboard").ok_or_else(|| "no system clipboard".to_string()) } } @@ -342,7 +439,7 @@ mod portable { Some(_) => None, None => flavours.iter().find(|f| f.mime == PNG).and_then(|f| decode_png(&f.data)), }; - let cb = self.cb()?; + let cb = self.cb(Asker::User)?; let ours = match (text, image) { (Some(t), _) => { cb.set_text(t.as_str()).map_err(|e| e.to_string())?; @@ -363,7 +460,7 @@ mod portable { } fn holds_ours(&mut self) -> bool { - let Some(cb) = self.cb.as_mut() else { return false }; + let Some(cb) = self.cb.opened() else { return false }; match &self.ours { Some(Ours::Text(t)) => cb.get_text().is_ok_and(|now| now == *t), Some(Ours::Image(w, h)) => cb.get_image().is_ok_and(|now| (now.width, now.height) == (*w, *h)), @@ -372,7 +469,7 @@ mod portable { } fn read(&mut self, mimes: &[&'static str]) -> Option { - let cb = self.cb().ok()?; + let cb = self.cb(Asker::User).ok()?; if let Some(f) = cb.get().file_list().ok().and_then(|paths| copied_file(paths, mimes)) { return Some(f); } @@ -402,7 +499,126 @@ mod portable { if super::mac::has(mimes) { return true; } - mimes.contains(&TEXT) && self.cb().is_ok_and(|cb| cb.get_text().is_ok_and(|t| !t.is_empty())) + mimes.contains(&TEXT) && self.cb(Asker::Probe).is_ok_and(|cb| cb.get_text().is_ok_and(|t| !t.is_empty())) + } + } + + #[cfg(test)] + mod tests { + use std::cell::Cell; + + use super::*; + + /// A clock that starts now and moves only when told. + struct Clock(Cell); + + impl Clock { + fn new() -> Self { + Self(Cell::new(Instant::now())) + } + fn now(&self) -> Instant { + self.0.get() + } + fn advance(&self, by: Duration) { + self.0.set(self.0.get() + by); + } + } + + fn fail() -> Result { + Err("no compositor".into()) + } + + fn name(_: &u8) -> &'static str { + "fake" + } + + #[test] + fn the_paste_check_retries_with_a_growing_wait() { + static LOGGED: AtomicBool = AtomicBool::new(false); + let (clock, attempts) = (Clock::new(), Cell::new(0)); + let mut cb = Reopen::new(&LOGGED); + // Every 250 ms for a minute, as `clipboard_probe` asks. + for _ in 0..240 { + let open = || { + attempts.set(attempts.get() + 1); + fail() + }; + assert!(cb.get(Asker::Probe, clock.now(), open, name).is_none()); + clock.advance(Duration::from_millis(250)); + } + // 0, 1, 3, 7, 15 and 31 s: not one connection a check. + assert_eq!(attempts.get(), 6); + assert!(LOGGED.load(Ordering::Relaxed), "the outage is logged"); + } + + #[test] + fn the_wait_stops_growing_at_a_minute() { + static LOGGED: AtomicBool = AtomicBool::new(false); + let (clock, attempts) = (Clock::new(), Cell::new(0)); + let mut cb = Reopen::new(&LOGGED); + for _ in 0..(20 * 60) { + let open = || { + attempts.set(attempts.get() + 1); + fail() + }; + let _ = cb.get(Asker::Probe, clock.now(), open, name); + clock.advance(Duration::from_secs(1)); + } + // 0, 1, 3, 7, 15, 31, 63 s, then a minute apart until 20 minutes are up. + assert_eq!(attempts.get(), 7 + (20 * 60 - 63 - 1) / 60); + } + + #[test] + fn a_copy_or_paste_retries_at_most_once_a_second() { + static LOGGED: AtomicBool = AtomicBool::new(false); + let (clock, attempts) = (Clock::new(), Cell::new(0)); + let mut cb = Reopen::new(&LOGGED); + let mut ask = |asker| { + let open = || { + attempts.set(attempts.get() + 1); + fail() + }; + let _ = cb.get(asker, clock.now(), open, name); + }; + // Long after the paste check gave up for a minute, a held Ctrl+V for 3 s at 30 a second. + for _ in 0..8 { + ask(Asker::Probe); + clock.advance(Duration::from_secs(70)); + } + let before = attempts.get(); + for _ in 0..90 { + ask(Asker::User); + clock.advance(Duration::from_millis(33)); + } + assert_eq!(attempts.get() - before, 3); + } + + #[test] + fn a_success_is_kept_and_ends_the_outage() { + static LOGGED: AtomicBool = AtomicBool::new(false); + let clock = Clock::new(); + let mut cb = Reopen::new(&LOGGED); + assert!(cb.get(Asker::Probe, clock.now(), fail, name).is_none()); + assert!(LOGGED.load(Ordering::Relaxed)); + clock.advance(FIRST_WAIT); + assert_eq!(cb.get(Asker::Probe, clock.now(), || Ok(7), name).copied(), Some(7)); + assert!(!LOGGED.load(Ordering::Relaxed), "the recovery is logged"); + // Kept: not opened again, even where opening would now fail. + assert_eq!(cb.get(Asker::Probe, clock.now(), fail, name).copied(), Some(7)); + assert_eq!(cb.opened().copied(), Some(7)); + } + + #[test] + fn one_outage_is_logged_once_across_handles() { + static LOGGED: AtomicBool = AtomicBool::new(false); + let clock = Clock::new(); + let (mut ui, mut probe) = (Reopen::new(&LOGGED), Reopen::new(&LOGGED)); + assert!(probe.get(Asker::Probe, clock.now(), fail, name).is_none()); + assert!(LOGGED.load(Ordering::Relaxed)); + // The other handle's failure is the same outage: `swap` reports it already logged. + assert!(ui.get(Asker::User, clock.now(), fail, name).is_none()); + assert!(LOGGED.load(Ordering::Relaxed)); + assert!(probe.opened().is_none() && ui.opened().is_none()); } } } diff --git a/apps/vectorcraft/src/gpu.rs b/apps/vectorcraft/src/gpu.rs index dc6ac19292..431d403463 100644 --- a/apps/vectorcraft/src/gpu.rs +++ b/apps/vectorcraft/src/gpu.rs @@ -140,33 +140,48 @@ pub fn backends(default: Backends, env_set: bool, opengl: bool) -> Backends { } /// Whether a Windows start lists OpenGL's adapters beside Direct3D 12's: only when it leaves an -/// adapter out (an earlier start crashed on it, or a restart failed on it) or DX12 lists none -/// (Windows 7). wgpu's OpenGL backend keeps a hidden window on a thread that pumps no messages, -/// and Windows waits on it when the input language changes, so the whole app hung on a switch to -/// another keyboard layout (#4150, gfx-rs/wgpu#10504), even drawing with DX12. +/// adapter out (an earlier start crashed on it, or a restart failed on it), when +/// `WGPU_ADAPTER_NAME` names one (it may be an OpenGL adapter), or when DX12 lists no hardware +/// adapter (Windows 7, or a GPU without a DX12 driver, which then draws through OpenGL as before +/// rather than on the CPU with WARP). wgpu's OpenGL backend keeps a hidden window on a thread that +/// pumps no messages, and Windows waits on it when the input language changes, so the whole app +/// hung on a switch to another keyboard layout (#4150, gfx-rs/wgpu#10504), even drawing with DX12. pub fn windows_opengl(left_out: &LeftOut) -> bool { - left_out.opengl_only || !left_out.adapters.is_empty() || !skipped().is_empty() || !dx12_lists_adapters() + opengl_needed(left_out, !skipped().is_empty(), std::env::var_os(NAME_ENV).is_some(), dx12_lists_hardware) } -/// Whether Direct3D 12 lists any adapter, WARP's software one included. A driver that crashes here -/// crashes a start while it lists the adapters, which the next start answers with OpenGL alone. +/// [`windows_opengl`], with a restart leaving adapters out (`skipping`) and an adapter named +/// (`named`): `dx12_hardware` is asked only when nothing else decides. +fn opengl_needed(left_out: &LeftOut, skipping: bool, named: bool, dx12_hardware: impl FnOnce() -> bool) -> bool { + left_out.opengl_only || !left_out.adapters.is_empty() || skipping || named || !dx12_hardware() +} + +/// Whether Direct3D 12 lists a hardware adapter; WARP, its software one, doesn't count. A driver +/// that crashes here crashes a start while it lists the adapters, which the next start answers with +/// OpenGL alone. #[cfg(windows)] -fn dx12_lists_adapters() -> bool { +fn dx12_lists_hardware() -> bool { let mut descriptor = wgpu::InstanceDescriptor::new_without_display_handle(); descriptor.backends = Backends::DX12; - // FXC is part of Windows, as for the window's own instance (#1194). - descriptor.backend_options.dx12.shader_compiler = wgpu::Dx12Compiler::Fxc; + // The shader compiler the window's own instance takes (#1194). + descriptor.backend_options.dx12.shader_compiler = wgpu::Dx12Compiler::from_env().unwrap_or(wgpu::Dx12Compiler::Fxc); let instance = wgpu::Instance::new(descriptor); - let found = pollster::block_on(instance.enumerate_adapters(Backends::DX12)).len(); - log::info!("Direct3D 12 lists {found} graphics adapters"); - found > 0 + let kinds: Vec = pollster::block_on(instance.enumerate_adapters(Backends::DX12)).iter().map(|a| a.get_info().device_type).collect(); + log::info!("Direct3D 12 lists these graphics adapters: {kinds:?}"); + any_hardware(&kinds) } #[cfg(not(windows))] -fn dx12_lists_adapters() -> bool { +fn dx12_lists_hardware() -> bool { false } +/// Is one of the adapters of these kinds hardware, not software such as WARP? +#[cfg(any(windows, test))] +fn any_hardware(kinds: &[DeviceType]) -> bool { + kinds.iter().any(|k| *k != DeviceType::Cpu) +} + /// The largest texture side to ask the device for, which bounds the window's surface: the /// adapter's own limit when it is above eframe's `default` (8192 px), so a window larger than /// that keeps its surface (#1459). Never below `default`, which is what was asked for before. diff --git a/apps/vectorcraft/src/gpu/tests.rs b/apps/vectorcraft/src/gpu/tests.rs index e4824ecd9a..3d13b51579 100644 --- a/apps/vectorcraft/src/gpu/tests.rs +++ b/apps/vectorcraft/src/gpu/tests.rs @@ -472,6 +472,31 @@ fn windows_lists_opengl_once_a_start_leaves_an_adapter_out() { assert_eq!(listing.backends(backends(Backends::all(), false, true)), Backends::GL); } +/// OpenGL stays where it drew before #4150's fix: a GPU without a Direct3D 12 driver (DX12 lists +/// WARP alone) and an adapter `WGPU_ADAPTER_NAME` names; a start with a DX12 GPU lists DX12 alone. +#[test] +fn windows_lists_opengl_without_a_dx12_gpu_or_with_an_adapter_named() { + let start = LeftOut::default(); + let asked = std::cell::Cell::new(false); + let hardware = |found: bool| { + asked.set(true); + found + }; + assert!(!opengl_needed(&start, false, false, || hardware(true)), "a DX12 GPU: DX12 alone (#4150)"); + assert!(asked.replace(false)); + assert!(opengl_needed(&start, false, false, || hardware(false)), "WARP alone: the GPU draws through OpenGL, not the CPU"); + assert!(opengl_needed(&start, false, true, || hardware(true)), "a named adapter may be an OpenGL one"); + assert!(opengl_needed(&start, true, false, || hardware(true)), "a restart left an adapter out"); + let listing = LeftOut { opengl_only: true, ..LeftOut::default() }; + asked.set(false); + assert!(opengl_needed(&listing, false, false, || hardware(true))); + assert!(!asked.get(), "DX12 isn't listed once OpenGL must be"); + assert!(any_hardware(&[DeviceType::Cpu, DeviceType::IntegratedGpu])); + assert!(any_hardware(&[DeviceType::VirtualGpu])); + assert!(!any_hardware(&[DeviceType::Cpu]), "WARP"); + assert!(!any_hardware(&[]), "Windows 7"); +} + #[test] fn power_preference_follows_the_environment_then_the_preference() { assert_eq!(power_preference(None, None), AUTOMATIC); diff --git a/apps/vectorcraft/src/main.rs b/apps/vectorcraft/src/main.rs index f02cbda187..e90977726d 100644 --- a/apps/vectorcraft/src/main.rs +++ b/apps/vectorcraft/src/main.rs @@ -128,7 +128,7 @@ Without a window (converting, scripting, the MCP server), use vectorcraft-cli: fn main() -> std::process::ExitCode { // Windows: the update helper is a copy of this program started with `--finish-update`. #[cfg(windows)] - if let Some(result) = craft_update::self_update::finish(&craft_update::suite::VECTORCRAFT, &std::env::args_os().skip(1).collect::>()) { + if let Some(result) = craft_update::self_update::finish(&vectorcraft_ui_egui::UPDATE_APP, &std::env::args_os().skip(1).collect::>()) { std::process::exit(i32::from(result.is_err())); } // Before any thread starts: the pointer must find a cursor theme on Wayland (#2450). diff --git a/apps/vectorcraft/src/prefs.rs b/apps/vectorcraft/src/prefs.rs index 56ea30f21f..728fe9ba8d 100644 --- a/apps/vectorcraft/src/prefs.rs +++ b/apps/vectorcraft/src/prefs.rs @@ -84,24 +84,200 @@ pub(crate) fn load_prefs(app: &mut VectorcraftApp, saved: Option(&b).ok()); + let merged = match (base.as_ref(), on_disk) { + (Some(base), Some(on_disk)) => merge_changes(base, &mine, on_disk), + _ => mine.clone(), + }; + let _ = std::fs::create_dir_all(p.parent().unwrap_or(std::path::Path::new("."))); + let Ok(bytes) = serde_json::to_vec_pretty(&merged) else { return }; + // Preferences are best effort: a failed write keeps the previous file, and the changes are + // tried again on the next save. + if fileio::write_atomic(&p, &bytes).is_ok() { + set_saved_base(Some(mine)); } } +/// How often [`save_prefs_soon`] looks for changes to save. +const SAVE_EVERY: std::time::Duration = std::time::Duration::from_secs(2); + +/// Save the preferences at most every [`SAVE_EVERY`] while the app runs, when something changed: +/// the workspace, panels, toolbars and the other UI settings kept only in the UI state were saved +/// only on quitting, so a session ended any other way (the window closed by the system, the +/// process ended or crashing) started the next one from the settings before it (#4625). +pub(crate) fn save_prefs_soon(app: &VectorcraftApp) { + static LAST: std::sync::Mutex> = std::sync::Mutex::new(None); + let Ok(mut last) = LAST.lock() else { return }; + if last.is_some_and(|t| t.elapsed() < SAVE_EVERY) { + return; + } + *last = Some(std::time::Instant::now()); + drop(last); + save_prefs(app); +} + +/// The preferences as this window last read or saved them (`None`: not read yet). +static SAVED_BASE: std::sync::Mutex> = std::sync::Mutex::new(None); + +fn saved_base() -> Option { + SAVED_BASE.lock().ok().and_then(|b| b.clone()) +} + +fn set_saved_base(value: Option) { + if let Ok(mut b) = SAVED_BASE.lock() { + *b = value; + } +} + +/// Fields of the UI state that a start resets ([`vectorcraft_ui_egui::UiState::sanitized`]): a +/// change to them alone isn't saved, and they are never merged over another window's. +const PASSING: &[&str] = &["status", "dialog", "flyout", "palette_open", "palette_query", "about", "open_panel"]; + +/// Do `a` and `b` hold the same preferences, leaving out what a start resets ([`PASSING`])? +fn same_lasting(a: &serde_json::Value, b: &serde_json::Value) -> bool { + match (a.as_object(), b.as_object()) { + (Some(a), Some(b)) => { + let keys: std::collections::BTreeSet<&String> = a.keys().chain(b.keys()).filter(|k| !PASSING.contains(&k.as_str())).collect(); + keys.into_iter().all(|k| a.get(k) == b.get(k)) + } + _ => a == b, + } +} + +/// `on_disk` with what changed from `base` to `mine` put over it: each top-level field of the UI +/// state, and each engine preference (`engine_prefs`) on its own, so two windows that change +/// different settings keep both. A field both changed takes this window's value (it saves last). +fn merge_changes(base: &serde_json::Value, mine: &serde_json::Value, on_disk: serde_json::Value) -> serde_json::Value { + use serde_json::Value; + let (Some(base), Some(mine), Value::Object(mut out)) = (base.as_object(), mine.as_object(), on_disk) else { + return mine.clone(); + }; + let keys: std::collections::BTreeSet<&String> = base.keys().chain(mine.keys()).collect(); + for key in keys { + if PASSING.contains(&key.as_str()) { + if let Some(v) = mine.get(key) { + out.entry(key.clone()).or_insert_with(|| v.clone()); + } + continue; + } + let (was, now) = (base.get(key), mine.get(key)); + if was == now { + continue; + } + if key == "engine_prefs" + && let (Some(Value::Object(was)), Some(Value::Object(now)), Some(Value::Object(theirs))) = (was, now, out.get_mut(key)) + { + let names: std::collections::BTreeSet<&String> = was.keys().chain(now.keys()).collect(); + for name in names { + match (was.get(name), now.get(name)) { + (a, b) if a == b => {} + (_, Some(v)) => { + theirs.insert(name.clone(), v.clone()); + } + (_, None) => { + theirs.remove(name); + } + } + } + continue; + } + match now { + Some(v) => { + out.insert(key.clone(), v.clone()); + } + None => { + out.remove(key); + } + } + } + Value::Object(out) +} + /// The preferences file's contents: the UI state with the engine preferences. +#[cfg(test)] pub(crate) fn prefs_bytes(app: &VectorcraftApp) -> serde_json::Result> { + serde_json::to_vec_pretty(&prefs_value(app)?) +} + +/// [`prefs_bytes`] as JSON. +fn prefs_value(app: &VectorcraftApp) -> serde_json::Result { let mut ui = app.ui.clone(); ui.engine_prefs = app.session.prefs.to_json(); - serde_json::to_vec_pretty(&ui) + serde_json::to_value(&ui) +} + +#[cfg(test)] +mod tests { + use serde_json::json; + + use super::{merge_changes, same_lasting}; + + /// Two windows open at once (#4625): the one that saves last keeps the other's changes and + /// adds its own, instead of putting back the preferences it started from. + #[test] + fn a_window_saves_only_what_it_changed_over_another_windows_save() { + let base = json!({"workspace": "Essentials", "toolbar": true, "engine_prefs": {"uiAccent": "blue", "uiScaling": 1.0}}); + // The other window switched the workspace and the accent, and saved. + let on_disk = json!({"workspace": "Painting", "toolbar": true, "engine_prefs": {"uiAccent": "violet", "uiScaling": 1.0}}); + // This one changed only the UI scaling. + let mine = json!({"workspace": "Essentials", "toolbar": true, "engine_prefs": {"uiAccent": "blue", "uiScaling": 1.25}}); + let merged = merge_changes(&base, &mine, on_disk); + assert_eq!(merged, json!({"workspace": "Painting", "toolbar": true, "engine_prefs": {"uiAccent": "violet", "uiScaling": 1.25}})); + } + + #[test] + fn a_setting_both_windows_changed_takes_the_last_saved() { + let base = json!({"workspace": "Essentials", "engine_prefs": {"uiAccent": "blue"}}); + let on_disk = json!({"workspace": "Painting", "engine_prefs": {"uiAccent": "violet"}}); + let mine = json!({"workspace": "Typography", "engine_prefs": {"uiAccent": "green"}}); + assert_eq!(merge_changes(&base, &mine, on_disk), json!({"workspace": "Typography", "engine_prefs": {"uiAccent": "green"}})); + } + + #[test] + fn fields_added_or_removed_by_this_window_are_saved() { + let base = json!({"docking": {"root": 1}, "engine_prefs": {"old": 1}}); + let on_disk = json!({"docking": {"root": 1}, "recent_files": ["a.svg"], "engine_prefs": {"old": 1}}); + let mine = json!({"dock_width": 300.0, "engine_prefs": {"new": 2}}); + assert_eq!(merge_changes(&base, &mine, on_disk), json!({"dock_width": 300.0, "recent_files": ["a.svg"], "engine_prefs": {"new": 2}})); + } + + /// The status line and open dialogs reset at start: they don't make a save, and they don't + /// replace another window's. + #[test] + fn what_a_start_resets_is_left_out() { + let base = json!({"status": "", "dialog": null, "workspace": "Essentials"}); + let mine = json!({"status": "Saved", "dialog": {"kind": "preferences"}, "workspace": "Essentials"}); + assert!(same_lasting(&base, &mine)); + let on_disk = json!({"status": "Opened", "dialog": null, "workspace": "Painting"}); + let mine = json!({"status": "Saved", "dialog": {"kind": "preferences"}, "workspace": "Essentials", "toolbar": false}); + let merged = merge_changes(&base, &mine, on_disk); + assert_eq!(merged, json!({"status": "Opened", "dialog": null, "workspace": "Painting", "toolbar": false})); + assert!(!same_lasting(&base, &mine)); + } + + #[test] + fn a_file_that_is_not_an_object_is_replaced() { + let base = json!({"workspace": "Essentials"}); + let mine = json!({"workspace": "Painting"}); + assert_eq!(merge_changes(&base, &mine, json!([1, 2])), mine); + } } diff --git a/contributors/people.toml b/contributors/people.toml index 8578d13f18..4883c236ad 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -17,6 +17,11 @@ # To remove your names, delete your entry (or set fields empty) in a PR. The next # contributors.py run, and the next build, drop them. +[people.el-j] +real_name = "Fabian Althaus" +display_name = "faff (el-j)" +sync_github_name = false + [people.lollinoo] sync_github_name = true @@ -172,3 +177,6 @@ sync_github_name = false [people.krosk93] sync_github_name = true + +[people.ashokram-si] +real_name = "Ashok Ram" diff --git a/crates/affinity/src/model/read.rs b/crates/affinity/src/model/read.rs index daf5d778c6..f94de75b93 100644 --- a/crates/affinity/src/model/read.rs +++ b/crates/affinity/src/model/read.rs @@ -441,8 +441,34 @@ impl<'s, 'a, 'b> Reader<'s, 'a, 'b> { _ => self.warn("layer effects of other kinds (left out)"), } } + for a in s.objs(id, b"AdCh") { + if let Some(effect) = self.attached_recolor(a) { + out.push(effect); + } + } out } + fn attached_recolor(&mut self, a: ObjId) -> Option { + let s = self.s; + if !s.is(a, b"RcRA") { + return None; + } + if s.bool(a, b"Visi") == Some(false) { + return None; + } + let adjp = s.obj(a, b"AdjP")?; + if !s.is(adjp, b"RecP") { + return None; + } + let h = s.f64(adjp, b"RecH").unwrap_or(0.0); + let sat = s.f64(adjp, b"RecS").unwrap_or(1.0); + let l = s.f64(adjp, b"RecL").unwrap_or(0.5); + let (r, g, b) = crate::paint::hsl(h, sat, l); + let color = crate::paint::Color::Rgb { r, g, b, a: 1.0 }; + let opacity = s.f64(a, b"Opac").filter(|v| v.is_finite()).unwrap_or(1.0).clamp(0.0, 1.0); + let blend = self.effect_blend(a); + Some(Effect::ColorOverlay { color, opacity, blend }) + } /// A layer effect's blend mode (`BlnM`); unknown modes are Normal (warned). fn effect_blend(&mut self, e: ObjId) -> Blend { @@ -479,6 +505,8 @@ impl<'s, 'a, 'b> Reader<'s, 'a, 'b> { Some(_) => self.warn("several pixel masks on one layer (only the first is used)"), None => {} } + } else if class == Tag::of(b"RcRA") { + // Handled in `effects` as a colour overlay. } else { self.warn(format!("{} layers attached to other layers (imported without them)", describe(class))); } diff --git a/crates/affinity/src/paint.rs b/crates/affinity/src/paint.rs index 8f9e424aae..1dfdb65759 100644 --- a/crates/affinity/src/paint.rs +++ b/crates/affinity/src/paint.rs @@ -194,7 +194,7 @@ fn color_within(r: &mut Reader, id: ObjId, depth: u32) -> Option { }) } -fn hsl(h: f64, s: f64, l: f64) -> (f64, f64, f64) { +pub(crate) fn hsl(h: f64, s: f64, l: f64) -> (f64, f64, f64) { let c = (1.0 - (2.0 * l - 1.0).abs()) * s; let hp = (h.rem_euclid(1.0)) * 6.0; let x = c * (1.0 - (hp % 2.0 - 1.0).abs()); @@ -355,3 +355,17 @@ pub(crate) fn stroke(r: &mut Reader, pen: ObjId, ldsc: ObjId, local: Affine, beh } Some(Stroke { paint, width, cap, join, miter_limit, align, dash, behind }) } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn hsl_lightness_1_is_white_and_0_is_black() { + assert_eq!(hsl(0.0, 1.0, 1.0), (1.0, 1.0, 1.0)); + assert_eq!(hsl(0.5, 1.0, 1.0), (1.0, 1.0, 1.0)); + assert_eq!(hsl(0.0, 1.0, 0.0), (0.0, 0.0, 0.0)); + let (r, g, b) = hsl(0.0, 1.0, 0.5); + assert!((r - 1.0).abs() < 1e-6 && g.abs() < 1e-6 && b.abs() < 1e-6); + } +} diff --git a/crates/brush/src/tests.rs b/crates/brush/src/tests.rs index 884dd27cf2..28bbcda752 100644 --- a/crates/brush/src/tests.rs +++ b/crates/brush/src/tests.rs @@ -27,10 +27,16 @@ fn near(a: f64, b: f64, tol: f64) -> bool { (a - b).abs() <= tol } +/// Points along every outline under `n`, its anchors among them. Bent art keeps its curves and +/// long lines since #3926, so its anchors alone no longer trace it. fn all_points(n: &Node, out: &mut Vec) { n.walk(&mut |c| { - if let Some(p) = c.path_data() { - out.extend(p.anchors().map(|(_, _, a)| a.p)); + for sp in c.path_data().into_iter().flat_map(|p| &p.subpaths) { + out.extend(sp.anchors.iter().map(|a| a.p)); + for i in 0..sp.segment_count() { + let seg = sp.segment(i); + out.extend((1..32).map(|j| kurbo::ParamCurve::eval(&seg, j as f64 / 32.0))); + } } }); } @@ -185,9 +191,12 @@ fn art_brush_follows_curves() { } } let out = stroke_pieces(&Document::new(1.0, 1.0), &art_brush(rect_art(10.0, 4.0), ArtScale::Stretch), &bp_open, &stroke(1.0)); + // The long edges bend as curves (#3926), where they used to be cut into some 400 chords. The + // path is run along in 0.05 pt chords, which the curves follow, so a few dozen remain. + let (anchors, curved) = anchors_and_curved(&out[0]); + assert!(anchors < 100 && curved > anchors / 2, "long edges bend as curves: {curved} of {anchors} anchors with handles"); let mut pts = vec![]; all_points(&out[0], &mut pts); - assert!(pts.len() > 40, "long edges are subdivided so they bend: {}", pts.len()); for p in pts { let r = p.distance(Point::new(100.0, 100.0)); assert!((r - 100.0).abs() <= 2.0 + 0.3, "point {p:?} is {r} from the centre"); @@ -1226,11 +1235,12 @@ fn a_pattern_tile_keeps_its_curves_on_a_straight_path() { assert!(near(b.height(), 40.0, 1.0), "and still stand the tile's height: {}", b.height()); } -/// The other half of the same behaviour: where the path really does bend, the tile is still -/// subdivided, because an affine cannot reproduce a bend. The fit is checked before it is used, -/// so a bent run falls back to exactly what it did before. +/// The other half of the same behaviour: where the path really does bend, an affine cannot +/// reproduce the bend, so the tile is bent, and it still comes out as curves: cubics fitted to the +/// bent art rather than the chords it used to be flattened into (#3926). Here a 4-anchor circle +/// tile runs round a circle of radius 200, so its outline stays in the band 20 either side of it. #[test] -fn a_pattern_tile_on_a_bent_path_is_still_subdivided() { +fn a_pattern_tile_on_a_bent_path_keeps_its_curves() { let circle = Node::path(NodeId(0), shapes::ellipse(Rect::new(0.0, -20.0, 40.0, 20.0)), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0)); let brush = Brush { @@ -1240,9 +1250,23 @@ fn a_pattern_tile_on_a_bent_path_is_still_subdivided() { // A circle to run along: every tile sits on a curving section. let round = shapes::ellipse(Rect::new(0.0, 0.0, 400.0, 400.0)).to_bezpath(); let out = stroke_pieces(&Document::new(1.0, 1.0), &brush, &round, &stroke(1.0)); - assert!(!out.is_empty()); - let bent = out.iter().filter(|n| anchors_and_curved(n).0 > 8).count(); - assert!(bent > out.len() / 2, "tiles on a bend are still densified: {bent} of {}", out.len()); + assert!(out.len() > 20, "tiles all the way round: {}", out.len()); + let (mut lo, mut hi) = (f64::MAX, f64::MIN); + for n in &out { + let (anchors, curved) = anchors_and_curved(n); + assert!((4..=16).contains(&anchors), "a bent circle tile is a few curves, not a polygon: {anchors} anchors"); + assert!(curved == anchors, "every anchor keeps a handle: {curved} of {anchors}"); + let mut pts = vec![]; + all_points(n, &mut pts); + for q in pts { + let r = q.distance(Point::new(200.0, 200.0)); + (lo, hi) = (lo.min(r), hi.max(r)); + } + } + // The path is a cubic circle (0.06 out at most) run along in chords of 0.05, and the fit holds + // a quarter of the 0.25 flattening tolerance, so the band holds to 0.2. + assert!(lo > 179.8 && hi < 220.2, "the curves stay in the tile's band round the path: {lo:.3}..{hi:.3}"); + assert!(lo < 180.2 && hi > 219.8, "and reach both edges of it: {lo:.3}..{hi:.3}"); } /// The kind of every node in a piece of brushed art, in paint order. diff --git a/crates/brush/src/warp.rs b/crates/brush/src/warp.rs index 95632ad495..99f7e63048 100644 --- a/crates/brush/src/warp.rs +++ b/crates/brush/src/warp.rs @@ -1,13 +1,15 @@ //! Art, scatter and pattern brushes: art bent along the path by arc length. //! //! Art coordinates `(x, y)` map to the path point at arc length `s(x)` offset by -//! `(y - centre) × cross` along the path's left normal. Art outlines are flattened and -//! subdivided first so long straight edges bend with the path instead of cutting chords. +//! `(y - centre) × cross` along the path's left normal. Art outlines come out as cubics fitted +//! to the bent art, so curves stay curves and long straight edges bend with the path (#3926); +//! where that would take more anchors than chords, they are flattened and subdivided instead. use std::sync::Arc; +use kurbo::ParamCurveNearest; use vectorcraft_doc::{Appearance, Node, NodeId, NodeKind, PressureProfile}; -use vectorcraft_geom::{Affine, BezPath, PathData, PathEl, Point, Rect, SubPath, Vec2}; +use vectorcraft_geom::{Affine, BezPath, CubicBez, ParamCurve, PathData, PathEl, Point, Rect, SubPath, Vec2}; use crate::track::{Rng, Track, normal, seed_of, tracks}; use crate::{ArtBrush, ArtScale, CornerSource, Direction, PatternBrush, PatternFit, Scatter, Variation, tolerance}; @@ -34,22 +36,26 @@ const MAX_WALK: usize = 10_000; /// Points on each side of the box an Auto-Sliced pattern brush corner masks its tiles with. const MASK_STEPS: usize = 32; -/// Bend every path under `n` through `f`. Paths are flattened with `flat_tol` (art space) and -/// segments subdivided so none is longer than `max_du` along x. Stroke widths scale by -/// `width_scale`. Text, images and symbol instances can't bend and are dropped. -pub(crate) fn warp_node(n: &Node, f: &dyn Fn(Point) -> Point, flat_tol: f64, max_du: f64, width_scale: f64) -> Option { +/// Bend every path under `n` through `f`. Each art segment comes out as cubics that follow it +/// through the bend to within [`fit_tol`] of `doc_tol`, the flattening tolerance in document +/// space, so the art keeps its curves (#3926). Where that cannot be done in no more anchors than +/// chords would take, the path is flattened with `flat_tol` (art space) and subdivided so no chord +/// is longer than `max_du` along x, as it always was. Stroke widths scale by `width_scale`. +/// Text, images and symbol instances can't bend and are dropped. +pub(crate) fn warp_node(n: &Node, f: &dyn Fn(Point) -> Point, flat_tol: f64, max_du: f64, doc_tol: f64, width_scale: f64) -> Option { let mut out = n.clone(); out.appearance.scale_strokes(width_scale); match &mut out.kind { NodeKind::Path { path, live, .. } => { *live = None; - *path = warp_path(path, f, flat_tol, max_du); + *path = warp_path(path, f, flat_tol, max_du, fit_tol(doc_tol)); if path.is_empty() { return None; } } NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } | NodeKind::Compound { children, .. } => { - let kids: Vec> = children.iter().filter_map(|c| warp_node(c, f, flat_tol, max_du, width_scale)).map(Arc::new).collect(); + let kids: Vec> = + children.iter().filter_map(|c| warp_node(c, f, flat_tol, max_du, doc_tol, width_scale)).map(Arc::new).collect(); if kids.is_empty() { return None; } @@ -60,54 +66,156 @@ pub(crate) fn warp_node(n: &Node, f: &dyn Fn(Point) -> Point, flat_tol: f64, max Some(out) } -fn warp_path(p: &PathData, f: &dyn Fn(Point) -> Point, flat_tol: f64, max_du: f64) -> PathData { - let bp = p.to_bezpath(); +/// Each subpath of `p` through `f`: fitted cubics when they take no more anchors than the chords +/// would, else the chords. Points `f` cannot place (not finite) are left out of the chords. +fn warp_path(p: &PathData, f: &dyn Fn(Point) -> Point, flat_tol: f64, max_du: f64, fit_tol: f64) -> PathData { let mut subs = vec![]; - let mut cur: Vec = vec![]; - let mut els = vec![]; - kurbo::flatten(bp.iter(), flat_tol.max(1e-4), |e| els.push(e)); - let finish = |cur: &mut Vec, closed: bool, subs: &mut Vec| { - let pts = std::mem::take(cur); - if pts.len() < 2 { - return; + for sp in &p.subpaths { + let Some(dense) = densified(sp, flat_tol, max_du) else { continue }; + if let Some(fit) = fitted(sp, f, fit_tol, dense.len()) { + subs.push(fit); + continue; } - let mut dense = vec![pts[0]]; - let n = pts.len(); - let segs = if closed { n } else { n - 1 }; - for i in 0..segs { - let (a, b) = (pts[i], pts[(i + 1) % n]); - let k = (((b.x - a.x).abs() / max_du).ceil() as usize).clamp(1, MAX_SUB); - for j in 1..=k { - let q = a.lerp(b, j as f64 / k as f64); - if closed && i == segs - 1 && j == k { - break; - } - dense.push(q); - } - } - let mapped: Vec = dense.into_iter().map(f).collect(); - subs.push(SubPath::polyline(&mapped, closed)); - }; - for e in els { - match e { - PathEl::MoveTo(q) => { - finish(&mut cur, false, &mut subs); - cur.push(q); - } - PathEl::LineTo(q) => cur.push(q), - PathEl::ClosePath => { - if cur.len() > 1 && cur[0].distance(cur[cur.len() - 1]) < 1e-9 { - cur.pop(); - } - finish(&mut cur, true, &mut subs); - } - _ => {} + let mapped: Vec = dense.into_iter().map(f).filter(|q| q.is_finite()).collect(); + if mapped.len() >= 2 { + subs.push(SubPath::polyline(&mapped, sp.closed)); } } - finish(&mut cur, false, &mut subs); PathData::new(subs) } +/// `sp` flattened with `flat_tol` and its chords subdivided so none is longer than `max_du` along +/// x, in art space: the points the chord route maps. `None` below two points. +fn densified(sp: &SubPath, flat_tol: f64, max_du: f64) -> Option> { + let mut bp = BezPath::new(); + sp.to_bezpath_into(&mut bp); + let mut pts = vec![]; + kurbo::flatten(bp.iter(), flat_tol.max(1e-4), |e| { + if let PathEl::MoveTo(q) | PathEl::LineTo(q) = e { + pts.push(q); + } + }); + if sp.closed && pts.len() > 1 && pts.first()?.distance(*pts.last()?) < 1e-9 { + pts.pop(); + } + if pts.len() < 2 { + return None; + } + let segs = if sp.closed { pts.len() } else { pts.len() - 1 }; + let mut dense = vec![*pts.first()?]; + for (i, (&a, &b)) in pts.iter().zip(pts.iter().cycle().skip(1)).take(segs).enumerate() { + let k = (((b.x - a.x).abs() / max_du).ceil() as usize).clamp(1, MAX_SUB); + for j in 1..=k { + if sp.closed && i == segs - 1 && j == k { + break; + } + dense.push(a.lerp(b, j as f64 / k as f64)); + } + } + Some(dense) +} + +/// Times an art segment is halved at most while looking for cubics that fit it. +const FIT_DEPTH: u32 = 12; +/// Parameter step of the finite differences that stand in for the bend's derivative. +const FIT_DT: f64 = 1e-6; +/// Sections a fitted piece is checked at the ends of (the ends themselves are exact). +const FIT_CHECKS: usize = 8; +/// Share of the flattening tolerance the fitted curves hold to. The chords were exact at their +/// points and a few hundredths off between them, so a straight edge bends about as closely. +const FIT_SHARE: f64 = 0.25; +/// Tolerance paths are flattened to before art is laid along them. +const TRACK_TOL: f64 = 0.05; + +/// The distance (document space) fitted curves keep to the bent art, for flattening tolerance +/// `doc_tol`: never below [`TRACK_TOL`], since following the flattened path more closely than it +/// follows the real one only traces its chords. +fn fit_tol(doc_tol: f64) -> f64 { + (doc_tol * FIT_SHARE).max(TRACK_TOL) +} + +/// `sp` through `f` as cubics within `tol` (document space), one or more per art segment so its +/// anchors, corners included, stay anchors. `None` when that takes more than `most` anchors, when +/// a piece still does not fit after [`FIT_DEPTH`] halvings, or when `f` cannot place a point. +/// +/// Each piece is the cubic with the bent piece's ends and their derivatives, which is the piece +/// itself where the bend is affine and converges fast where it is not. It is checked against the +/// bend at the same parameters, so the distance measured is never less than the true one. The +/// halving is our own rather than kurbo's `fit_to_bezpath`, which halves until the floats run out +/// on a map that never fits; the depth and the anchor count bound this one. +fn fitted(sp: &SubPath, f: &dyn Fn(Point) -> Point, tol: f64, most: usize) -> Option { + if !(tol.is_finite() && tol > 0.0) { + return None; + } + let start = f(sp.anchors.first()?.p); + if !start.is_finite() { + return None; + } + let mut bp = BezPath::new(); + bp.move_to(start); + // Pieces allowed: an open subpath's first anchor is one more, a closed one's last piece ends on it. + let mut room = if sp.closed { most } else { most.checked_sub(1)? }; + for i in 0..sp.segment_count() { + let c = sp.segment(i); + let line = sp.segment_is_line(i); + // A line's handles sit on its ends, which stalls its parameter there; thirds keep it even. + let c = if line { CubicBez::new(c.p0, c.p0.lerp(c.p3, 1.0 / 3.0), c.p0.lerp(c.p3, 2.0 / 3.0), c.p3) } else { c }; + let at = |t: f64| Some(f(c.eval(t))).filter(|q| q.is_finite()); + fit_into(&at, (0.0, 1.0), line, tol, FIT_DEPTH, &mut bp, &mut room)?; + } + if sp.closed { + bp.close_path(); + } + // The last piece ends on the first anchor's image, so a closed subpath merges it back in; the + // count is checked again for a map that jumps right there and keeps the two apart. + PathData::from_bezpath(&bp).subpaths.into_iter().next().filter(|s| s.anchors.len() <= most) +} + +/// Pieces for parameters `t0..t1` of the bent segment `at` onto `bp`, which ends at `at(t0)`: +/// halved until each is within `tol`, at most `depth` times and `room` pieces. A `line` that is +/// still straight within `tol` stays a line. +fn fit_into( + at: &dyn Fn(f64) -> Option, + (t0, t1): (f64, f64), + line: bool, + tol: f64, + depth: u32, + bp: &mut BezPath, + room: &mut usize, +) -> Option<()> { + let span = t1 - t0; + let (p0, p3) = (at(t0)?, at(t1)?); + // Derivatives read from inside the piece, so a kink at either end (a corner, a turn of the + // track) stays one. + let d0 = (at(t0 + FIT_DT)? - p0) * (span / FIT_DT); + let d1 = (p3 - at(t1 - FIT_DT)?) * (span / FIT_DT); + let c = CubicBez::new(p0, p0 + d0 / 3.0, p3 - d1 / 3.0, p3); + let chord = kurbo::Line::new(p0, p3); + let (mut curve_fits, mut line_fits) = (c.is_finite(), line); + for k in 1..FIT_CHECKS { + if !(curve_fits || line_fits) { + break; + } + let u = k as f64 / FIT_CHECKS as f64; + let q = at(t0 + span * u)?; + curve_fits &= q.distance(c.eval(u)) <= tol; + line_fits &= chord.nearest(q, 1e-9).distance_sq <= tol * tol; + } + if line_fits || curve_fits { + *room = room.checked_sub(1)?; + if line_fits { + bp.line_to(p3); + } else { + bp.curve_to(c.p1, c.p2, p3); + } + return Some(()); + } + let depth = depth.checked_sub(1)?; + let mid = t0 + span / 2.0; + fit_into(at, (t0, mid), line, tol, depth, bp, room)?; + fit_into(at, (mid, t1), line, tol, depth, bp, room) +} + /// Art turned so it runs left → right, flipped as requested; returns it with its bounds. fn oriented(art: &Node, dir: Direction, flip_along: bool, flip_across: bool) -> Option<(Node, Rect)> { let mut a = art.clone(); @@ -281,7 +389,7 @@ fn bend(t: &Track, art: &Node, b: Rect, along: AlongMap, cross: f64) -> Option 1e-9 { len / tw } else { 1.0 }; let max_du = MAX_SEG / (2.0 * k * s.max(1.0)); - let warp = |f: &dyn Fn(Point) -> Point| warp_node(art, f, flat_tol, max_du, k); + let warp = |f: &dyn Fn(Point) -> Point| warp_node(art, f, flat_tol, max_du, flat_tol * k, k); // Art point → (distance along from the left edge, stretched to `len`, and offset across). let along = move |q: Point| { let (x, y) = local(q); @@ -686,7 +794,7 @@ pub(crate) fn pattern(pb: &PatternBrush, bp: &BezPath, weight: f64) -> Vec let outer_tile = outer.as_ref().map(Corner::Art).or(pb.outer_source.map(Corner::Source)); let inner_tile = inner.as_ref().map(Corner::Art).or(pb.inner_source.map(Corner::Source)); let mut out = Budget::default(); - for t in tracks(bp, 0.05) { + for t in tracks(bp, TRACK_TOL) { if out.full() { break; } @@ -921,4 +1029,108 @@ mod tests { let moved = bend(&straight, &circle, b, along, cross).expect("the straight run still draws something"); assert_eq!(anchors(&moved), 4, "the straight run keeps the tile's curves"); } + + /// A 4-anchor circle tile filling `b`. + fn circle_tile(b: Rect) -> Node { + Node::path( + NodeId(0), + vectorcraft_geom::shapes::ellipse(b), + Appearance::basic(vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK), vectorcraft_color::Paint::None, 0.0), + ) + } + + /// `per` points along each segment of `sp`, through `f`. + fn traced(sp: &SubPath, f: &dyn Fn(Point) -> Point, per: usize) -> Vec { + (0..sp.segment_count()) + .flat_map(|i| { + let c = sp.segment(i); + (0..per).map(move |j| f(c.eval(j as f64 / per as f64))) + }) + .collect() + } + + /// How far apart two closed outlines get (Hausdorff distance, each taken as a polygon). + fn apart(a: &[Point], b: &[Point]) -> f64 { + let to = |q: Point, pts: &[Point]| { + pts.iter() + .zip(pts.iter().cycle().skip(1)) + .map(|(&a, &b)| { + let ab = b - a; + let t = ((q - a).dot(ab) / ab.hypot2().max(1e-18)).clamp(0.0, 1.0); + q.distance(a + ab * t) + }) + .fold(f64::MAX, f64::min) + }; + let one_way = |a: &[Point], b: &[Point]| a.iter().map(|&q| to(q, b)).fold(0.0, f64::max); + one_way(a, b).max(one_way(b, a)) + } + + /// #3926: on a bend the tile is fitted with cubics instead of flattened into chords. A circle + /// tile bent round a circle stays a handful of smooth curves, closer to the bent art than the + /// chords were, in a small fraction of their anchors. + #[test] + fn a_circle_tile_bent_round_a_circle_stays_a_few_curves() { + let round = vectorcraft_geom::shapes::ellipse(Rect::new(0.0, 0.0, 400.0, 400.0)).to_bezpath(); + let t = tracks(&round, 0.05).remove(0); + let b = Rect::new(0.0, -20.0, 40.0, 20.0); + let along = AlongMap::linear(b.width(), 100.0, 140.0); + let tile = circle_tile(b); + let NodeKind::Path { path: art, .. } = &tile.kind else { panic!("the tile is a path") }; + let art = &art.subpaths[0]; + + let bent = bend(&t, &tile, b, along, 1.0).expect("the tile is drawn"); + let NodeKind::Path { path, .. } = &bent.kind else { panic!("a bent path is a path") }; + assert_eq!(path.subpaths.len(), 1); + let sp = &path.subpaths[0]; + assert!(sp.closed, "still a closed outline"); + let n = sp.anchors.len(); + assert!((4..=16).contains(&n), "a few anchors, the tile's own four among them: {n}"); + assert!(sp.anchors.iter().all(|a| a.has_in() && a.has_out()), "every anchor keeps both handles"); + assert!(sp.anchors.first().map(|a| a.p) != sp.anchors.last().map(|a| a.p), "closed without a duplicate anchor"); + + // The same map `bend` uses, at scale 1, and the tolerance it fits to. + let (cy, x0) = (b.center().y, b.x0); + let f = |p: Point| t.map(along.at(p.x - x0), p.y - cy); + let tol = tolerance(b.height().max(b.width())); + let exact = traced(art, &f, 1000); + let chords: Vec = densified(art, tol, MAX_SEG).expect("the tile flattens").into_iter().map(f).collect(); + let curves = traced(sp, &|p| p, 200); + let (e_curves, e_chords) = (apart(&curves, &exact), apart(&chords, &exact)); + // Checked at eight points a piece, so a little room between them. + assert!(e_curves <= fit_tol(tol) * 1.5, "the curves follow the bent art within {}: {e_curves:.4}", fit_tol(tol)); + assert!(e_curves < e_chords, "closer than the chords were: {e_curves:.4} against {e_chords:.4}"); + assert!(chords.len() >= 4 * n, "far fewer anchors than the {} chords took: {n}", chords.len()); + } + + /// Fitting is bounded however badly the map behaves: where it gives points that are not finite + /// the tile falls back to chords with those points left out (or to nothing), and where it never + /// fits (a map that jumps everywhere) the halving stops at its depth and anchor count. Either + /// way the call comes back promptly with finite geometry. + #[test] + fn a_map_that_misbehaves_still_returns_promptly_and_finite() { + let b = Rect::new(0.0, -20.0, 40.0, 20.0); + let tile = circle_tile(b); + let finite = |n: &Node| match &n.kind { + NodeKind::Path { path, .. } => { + path.subpaths.iter().flat_map(|s| &s.anchors).all(|a| a.p.is_finite() && a.h_in.is_finite() && a.h_out.is_finite()) + } + _ => false, + }; + let maps: [&dyn Fn(Point) -> Point; 4] = [ + &|p| if p.x > 25.0 { Point::new(f64::NAN, p.y) } else { p }, + &|p| if p.y > 10.0 { Point::new(f64::INFINITY, p.y) } else { p + Vec2::new(p.x.sin(), 0.0) }, + &|p| Point::new(p.x, p.y + if (p.x * 1e3).sin() > 0.0 { 5.0 } else { 0.0 }), + &|_| Point::new(f64::NAN, f64::NAN), + ]; + for (i, f) in maps.iter().enumerate() { + let t0 = std::time::Instant::now(); + let out = warp_node(&tile, f, 0.25, 1.5, 0.25, 1.0); + assert!(t0.elapsed() < std::time::Duration::from_secs(2), "map {i} took {:?}", t0.elapsed()); + match (i, &out) { + (3, out) => assert!(out.is_none(), "a map that places nothing draws nothing"), + (_, Some(n)) => assert!(finite(n), "map {i} drew non-finite geometry"), + (_, None) => panic!("map {i} places most points, so something is drawn"), + } + } + } } diff --git a/crates/doc/src/blend.rs b/crates/doc/src/blend.rs index 69ad127819..ced9472a74 100644 --- a/crates/doc/src/blend.rs +++ b/crates/doc/src/blend.rs @@ -196,7 +196,11 @@ pub fn lerp_paint(a: &Paint, b: &Paint, t: f32) -> Paint { /// so dashes open out of a solid line; patterns of different lengths repeat to a common one. fn lerp_dash(x: Option<&Dash>, y: Option<&Dash>, t: f64) -> Option { let solid_like = |d: &Dash| Dash { - pattern: d.pattern.chunks(2).flat_map(|c| [c.iter().sum::(), 0.0]).take(d.pattern.len().max(2)).collect(), + // An odd pattern repeats twice per period, so pair up the doubled one to keep every gap closed. + pattern: if d.pattern.len() % 2 == 1 { d.pattern.repeat(2) } else { d.pattern.clone() } + .chunks(2) + .flat_map(|c| [c.iter().sum::(), 0.0]) + .collect(), offset: d.offset, align_corners: d.align_corners, }; @@ -1423,6 +1427,12 @@ mod tests { assert_eq!(p.at(0.5), (1.0, 1.0)); } + #[test] + fn odd_dash_blends_to_solid_with_closed_gaps() { + let d = lerp_dash(Some(&Dash { pattern: vec![2.0, 3.0, 4.0], ..Default::default() }), None, 1.0).unwrap(); + assert!(d.pattern.iter().skip(1).step_by(2).all(|g| *g == 0.0), "{:?}", d.pattern); + } + #[test] fn copied_steps_get_new_members() { let rect = |x: f64| Arc::new(Node::path(NodeId(7), shapes::rectangle(Rect::new(x, 0.0, x + 10.0, 10.0)), Appearance::default())); diff --git a/crates/doc/src/cmyk.rs b/crates/doc/src/cmyk.rs index cfaad0a943..3915b239ed 100644 --- a/crates/doc/src/cmyk.rs +++ b/crates/doc/src/cmyk.rs @@ -125,7 +125,7 @@ pub fn oversized_tiff(bytes: &[u8]) -> Option<(u32, u32)> { } /// The color type of TIFF `bytes` and its decoder; `None` for [`oversized_tiff`] images too. -fn tiff(bytes: &[u8]) -> Option<(tiff::ColorType, tiff::decoder::Decoder>)> { +pub(crate) fn tiff(bytes: &[u8]) -> Option<(tiff::ColorType, tiff::decoder::Decoder>)> { if !is_tiff(bytes) || oversized_tiff(bytes).is_some() { return None; } diff --git a/crates/doc/src/compound_shape.rs b/crates/doc/src/compound_shape.rs new file mode 100644 index 0000000000..3b36ff86dd --- /dev/null +++ b/crates/doc/src/compound_shape.rs @@ -0,0 +1,76 @@ +//! Compound shapes (Pathfinder panel › Make Compound Shape): a group whose members each have a +//! shape mode. It draws as the one area the modes make, from the backmost member up, painted with +//! the group's own appearance; the members stay editable. Evaluated in `vectorcraft-effects`. + +use serde::{Deserialize, Deserializer, Serialize}; + +use crate::{Node, NodeKind}; + +/// How a compound shape's member combines with the area of the members below it. The backmost +/// member's mode does not matter: it starts the area. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize)] +#[serde(rename_all = "camelCase")] +pub enum ShapeMode { + /// Adds the member's area. + #[default] + Add, + /// Takes the member's area away. + Subtract, + /// Keeps only what the member's area overlaps. + Intersect, + /// Keeps where exactly one of the area and the member's area is. + Exclude, +} + +impl ShapeMode { + /// Every mode, in the Pathfinder panel's order. + pub const ALL: [ShapeMode; 4] = [ShapeMode::Add, ShapeMode::Subtract, ShapeMode::Intersect, ShapeMode::Exclude]; + + /// The mode's name in commands and files. + pub fn name(self) -> &'static str { + match self { + ShapeMode::Add => "add", + ShapeMode::Subtract => "subtract", + ShapeMode::Intersect => "intersect", + ShapeMode::Exclude => "exclude", + } + } + + /// The mode named `s` ([`ShapeMode::name`]). + pub fn parse(s: &str) -> Option { + Self::ALL.into_iter().find(|m| m.name() == s) + } +} + +/// Files are untrusted: a mode that isn't one of the names reads as Add. +impl<'de> Deserialize<'de> for ShapeMode { + fn deserialize>(d: D) -> Result { + let v = serde_json::Value::deserialize(d)?; + Ok(v.as_str().and_then(ShapeMode::parse).unwrap_or_default()) + } +} + +impl Node { + /// Is this a compound shape? Only a group that doesn't clip can be one: the mark on anything + /// else (from a file) is ignored. + pub fn is_compound_shape(&self) -> bool { + matches!(self.kind, NodeKind::Group { clip: false, .. }) && self.extras().compound_shape + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn modes_read_back_and_unknown_ones_are_add() { + for m in ShapeMode::ALL { + let v = serde_json::to_value(m).unwrap(); + assert_eq!(v, serde_json::json!(m.name())); + assert_eq!(serde_json::from_value::(v).unwrap(), m); + } + for v in [serde_json::json!("divide"), serde_json::json!(3), serde_json::json!(null), serde_json::json!({"a": [1]})] { + assert_eq!(serde_json::from_value::(v).unwrap(), ShapeMode::Add); + } + } +} diff --git a/crates/doc/src/inks.rs b/crates/doc/src/inks.rs index 8235dc4d20..696b274134 100644 --- a/crates/doc/src/inks.rs +++ b/crates/doc/src/inks.rs @@ -109,9 +109,9 @@ fn visit_paint(p: &mut Paint, f: &mut ColorVisitor) { } } -/// Visit every colour of a node tree (fills, strokes, gradient stops, text runs, mesh points, not -/// opacity masks) with its swatch link and tint. Mesh points have no link: changes to it are -/// dropped. +/// Visit every colour of a node tree (fills, strokes, gradient stops, text runs, mesh points, an +/// image's colorize color, not opacity masks) with its swatch link and tint. Mesh points have no +/// link: changes to it are dropped. pub fn visit_node_colors(n: &mut Node, f: &mut ColorVisitor) { for it in &mut n.appearance.items { match it { @@ -119,6 +119,9 @@ pub fn visit_node_colors(n: &mut Node, f: &mut ColorVisitor) { AppearanceItem::Stroke(l) => visit_paint(&mut l.paint, f), } } + if let Some(p) = n.extras.0.as_deref_mut().and_then(|e| e.colorize.as_deref_mut()) { + visit_paint(p, f); + } match &mut n.kind { NodeKind::Text(t) => { for r in &mut t.runs { diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 91ede3df9d..b6a9a60efc 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -11,6 +11,7 @@ pub mod blend; pub mod cancel; pub mod clipnest; pub mod cmyk; +pub mod compound_shape; pub mod corners; pub mod depth; pub mod dimension; @@ -42,7 +43,7 @@ pub mod overprint; pub mod pattern; pub mod perspective; mod pixels; -pub use pixels::MAX_RASTER_ALLOC; +pub use pixels::{GraySource, MAX_RASTER_ALLOC}; pub mod placed_document; pub mod plugin_data; pub mod profiles; @@ -76,6 +77,7 @@ pub use appearance::{ StrokeAlign, StrokeLayer, WidthProfile, }; pub use assets::ExportAsset; +pub use compound_shape::ShapeMode; pub use corners::LiveCorners; pub use depth::{MAX_DEPTH, MAX_SYMBOL_NODES}; pub use graph::{ diff --git a/crates/doc/src/live.rs b/crates/doc/src/live.rs index 650361374c..6a29b5b9ef 100644 --- a/crates/doc/src/live.rs +++ b/crates/doc/src/live.rs @@ -221,6 +221,25 @@ mod tests { assert!(matches!(m.color_at(0, 0, 0.5, 0.5).0, Color::Rgb { .. })); } + /// #3232: the Appearance highlight lightens each point towards white in its own model, so a + /// CMYK mesh stays CMYK (K shrinks with the other inks) and a grey one stays grey. + #[test] + fn mesh_highlight_keeps_each_points_model() { + let square = shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)); + let ink = Color::Cmyk { c: 0.0, m: 0.4, y: 0.6, k: 0.1 }; + let m = GradientMesh::for_path(&square, 2, 2, ink, MeshAppearance::ToCenter, 50.0).unwrap(); + assert_eq!(m.points[0].color, ink, "corners stay"); + let centre = m.points[m.idx(1, 1)].color; + let Color::Cmyk { c, m: mg, y, k } = centre else { panic!("{centre:?}") }; + assert!(c.abs() < 1e-6 && (mg - 0.2).abs() < 1e-6 && (y - 0.3).abs() < 1e-6 && (k - 0.05).abs() < 1e-6, "{c} {mg} {y} {k}"); + assert!(matches!(m.color_at(0, 0, 0.5, 0.5).0, Color::Cmyk { .. }), "patches mix in CMYK"); + let m = GradientMesh::for_path(&square, 2, 2, Color::gray(0.8), MeshAppearance::ToEdge, 100.0).unwrap(); + assert_eq!((m.points[0].color, m.points[m.idx(1, 1)].color), (Color::gray(0.0), Color::gray(0.8))); + // RGB lightens in RGB as before. + let m = GradientMesh::for_path(&square, 2, 2, Color::rgb(1.0, 0.0, 0.0), MeshAppearance::ToCenter, 100.0).unwrap(); + assert_eq!(m.points[m.idx(1, 1)].color.to_hex(), "#ffffff"); + } + /// Alt-clicking a point of a mesh from a file with fewer points than its rows and columns need /// deletes nothing (it indexed past the points, a panic). #[test] diff --git a/crates/doc/src/live/mesh.rs b/crates/doc/src/live/mesh.rs index 783e325562..dbbfc66bdd 100644 --- a/crates/doc/src/live/mesh.rs +++ b/crates/doc/src/live/mesh.rs @@ -267,7 +267,8 @@ impl GradientMesh { } /// Create Gradient Mesh → Appearance: lighten the points towards white, to the centre or to - /// the edges, by at most `highlight` %. + /// the edges, by at most `highlight` %. Each point lightens towards white in its own colour + /// model (paper white, no ink, for CMYK), so a CMYK or grey mesh keeps its inks (#3232). pub fn highlight(&mut self, appearance: MeshAppearance, highlight: f64) { let h = (highlight / 100.0).clamp(0.0, 1.0) as f32; let (rows, cols) = (self.rows as usize, self.cols as usize); @@ -282,7 +283,8 @@ impl GradientMesh { }; if w > 0.0 { let i = self.idx(r, c); - self.points[i].color = lerp_color(&self.points[i].color, &Color::WHITE, w); + let color = self.points[i].color; + self.points[i].color = lerp_color(&color, &Color::WHITE.in_model(color.model()), w); } } } diff --git a/crates/doc/src/mem.rs b/crates/doc/src/mem.rs index 771b0b7fb6..a971a383b5 100644 --- a/crates/doc/src/mem.rs +++ b/crates/doc/src/mem.rs @@ -250,7 +250,7 @@ fn node_bytes(n: &Node, other: Option<&Node>) -> usize { if let Some(e) = n.extras_box() { b += ALLOC + size_of::(); b += boxed(&e.mask) + boxed(&e.graph) + boxed(&e.shaper) + boxed(&e.attrs) + boxed(&e.slice) + boxed(&e.perspective); - b += boxed(&e.dimension) + boxed(&e.live_paint_gaps); + b += boxed(&e.dimension) + boxed(&e.live_paint_gaps) + boxed(&e.colorize); b += e.trace.as_ref().map_or(0, |t| ALLOC + size_of::() + json_bytes(t)); b += e.intertwine.as_deref().map_or(0, |a| ALLOC + size_of::() + path_bytes(a)); b += e.objects_on_path.as_deref().map_or(0, |o| { diff --git a/crates/doc/src/node/extras.rs b/crates/doc/src/node/extras.rs index 2d8ad8c9c0..633f9b6967 100644 --- a/crates/doc/src/node/extras.rs +++ b/crates/doc/src/node/extras.rs @@ -49,6 +49,15 @@ pub struct NodeExtras { /// Object › Objects on Path: the group's path and the objects attached to it (see /// [`crate::objects_on_path`]). pub objects_on_path: Option>, + /// A grayscale or 1-bit image's fill color (`paint.setFill` on the image): a solid paint that + /// colorizes it. Each pixel is drawn in this color, as opaque as the pixel is dark, so white + /// pixels are transparent. `None`: the image shows its own pixels. + pub colorize: Option>, + /// Pathfinder panel › Make Compound Shape: this group is a compound shape + /// ([`Node::is_compound_shape`], [`crate::compound_shape`]). + pub compound_shape: bool, + /// As a member of a compound shape, how this object combines with the members below it. + pub shape_mode: crate::ShapeMode, } /// No extras: what [`Node::extras`] gives for a node without any. @@ -69,6 +78,9 @@ pub(super) static NO_EXTRAS: NodeExtras = NodeExtras { intertwine: None, live_paint_gaps: None, objects_on_path: None, + colorize: None, + compound_shape: false, + shape_mode: crate::ShapeMode::Add, }; /// A node's [`NodeExtras`], if it has any ([`Node::extras`]). Extras that are all unset equal diff --git a/crates/doc/src/node/ops.rs b/crates/doc/src/node/ops.rs index e02958a8dd..cdbdeec27a 100644 --- a/crates/doc/src/node/ops.rs +++ b/crates/doc/src/node/ops.rs @@ -127,6 +127,7 @@ impl Node { NodeKind::Layer { .. } => "Layer", NodeKind::Group { clip: true, .. } => "Clip Group", NodeKind::Group { .. } if self.extras().objects_on_path.is_some() => "Objects on Path", + NodeKind::Group { .. } if self.extras().compound_shape => "Compound Shape", NodeKind::Group { .. } => "Group", NodeKind::Path { live: Some(l), .. } => l.label(), NodeKind::Path { guide: true, .. } => "Guide", @@ -545,9 +546,16 @@ impl Node { /// item) stands in for the topmost fill or stroke when it is of the proxy's kind. Otherwise /// type objects paint their runs (the first run speaks for all) in text space, fitted to the /// layout bounds; everything else paints its fill or stroke in the document, fitted to the - /// geometric bounds. Strokes fit the box grown by half their weight. + /// geometric bounds. Strokes fit the box grown by half their weight. A colorized image shows + /// its colorize paint as its fill. pub fn proxy_paint(&self, stroke: bool, item: Option) -> Option<(&vectorcraft_color::Paint, Affine, Rect)> { let item = self.appearance.item_of_kind(item, !stroke); + if item.is_none() + && !stroke + && let Some(c) = self.extras().colorize.as_deref() + { + return Some((c, Affine::IDENTITY, self.geometric_bounds().unwrap_or(Rect::ZERO))); + } if item.is_none() && let NodeKind::Text(t) = &self.kind { diff --git a/crates/doc/src/node/tests.rs b/crates/doc/src/node/tests.rs index 0565c9e079..dc241841fa 100644 --- a/crates/doc/src/node/tests.rs +++ b/crates/doc/src/node/tests.rs @@ -19,6 +19,8 @@ fn extras_are_written_flat_in_order() { e.slice = Some(Box::default()); e.perspective = Some(Box::new(crate::PerspectiveAttachment::new("left", 1.0))); e.live_paint_gaps = Some(Box::default()); + e.compound_shape = true; + e.shape_mode = crate::ShapeMode::Exclude; } /// The top-level keys of a JSON object, in the order written. struct Keys(Vec); @@ -61,8 +63,11 @@ fn extras_are_written_flat_in_order() { "bbox_angle", "perspective", "live_paint_gaps", + "compound_shape", + "shape_mode", ]; assert_eq!(keys, order); + assert_eq!(v["shape_mode"], "exclude"); assert_eq!(serde_json::from_value::(v).unwrap(), n); let plain = Node::path(NodeId(9), shapes::rectangle(Rect::new(0.0, 0.0, 4.0, 2.0)), Appearance::default_art()); let back: Node = serde_json::from_value(serde_json::to_value(&plain).unwrap()).unwrap(); diff --git a/crates/doc/src/node/wire.rs b/crates/doc/src/node/wire.rs index 84d0b220eb..76d4c3c14a 100644 --- a/crates/doc/src/node/wire.rs +++ b/crates/doc/src/node/wire.rs @@ -5,6 +5,12 @@ use super::kind::NodeKind; use super::opacity::{Knockout, OpacityMask}; use super::{Appearance, BlendMode, Deserialize, Node, PathData, Serialize, one, yes}; +/// Field `name` of a [`Node`] written as `v`, or skipped. A function of its own, so the long field +/// list stays one straight run of calls. +fn write_field(st: &mut S, skip: bool, name: &'static str, v: &T) -> Result<(), S::Error> { + if skip { st.skip_field(name) } else { st.serialize_field(name, v) } +} + /// How a [`Node`] is written: the flat field list of the file format, in its order, borrowed from /// the node and its extras (nothing is copied). The node reads back through `NodeWire`. impl Serialize for Node { @@ -42,16 +48,15 @@ impl Serialize for Node { e.intertwine.is_none(), e.live_paint_gaps.is_none(), e.objects_on_path.is_none(), + e.colorize.is_none(), + is_default(&e.compound_shape), + is_default(&e.shape_mode), ]; let mut st = s.serialize_struct("Node", skips.iter().filter(|s| !**s).count())?; let mut skip = skips.into_iter(); macro_rules! field { ($name:literal, $v:expr) => { - if skip.next().unwrap_or(false) { - st.skip_field($name)?; - } else { - st.serialize_field($name, $v)?; - } + write_field(&mut st, skip.next().unwrap_or(false), $name, $v)?; }; } field!("id", &self.id); @@ -82,6 +87,9 @@ impl Serialize for Node { field!("intertwine", &e.intertwine); field!("live_paint_gaps", &e.live_paint_gaps); field!("objects_on_path", &e.objects_on_path); + field!("colorize", &e.colorize); + field!("compound_shape", &e.compound_shape); + field!("shape_mode", &e.shape_mode); st.end() } } @@ -182,6 +190,12 @@ pub(super) struct NodeWire { live_paint_gaps: Option>, #[serde(default)] objects_on_path: Option>, + #[serde(default)] + colorize: Option>, + #[serde(default)] + compound_shape: bool, + #[serde(default)] + shape_mode: crate::ShapeMode, } impl From for Node { @@ -203,6 +217,9 @@ impl From for Node { intertwine: w.intertwine, live_paint_gaps: w.live_paint_gaps, objects_on_path: w.objects_on_path, + colorize: w.colorize, + compound_shape: w.compound_shape, + shape_mode: w.shape_mode, }; Node { id: w.id, diff --git a/crates/doc/src/pixels.rs b/crates/doc/src/pixels.rs index 306c8360e8..2264e66ce0 100644 --- a/crates/doc/src/pixels.rs +++ b/crates/doc/src/pixels.rs @@ -62,6 +62,61 @@ impl ImageBlob { } } +/// How a grayscale image's file stores its pixels ([`ImageBlob::gray_source`]). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct GraySource { + /// One bit a pixel: black and white only. + pub one_bit: bool, + /// The file has an alpha channel. + pub alpha: bool, +} + +impl ImageBlob { + /// Whether the image's file stores grayscale or 1-bit pixels (the images a fill color + /// colorizes), and how; `None` for color images and data that isn't an image. Reads only its + /// header. + pub fn gray_source(&self) -> Option { + let gray = |one_bit: bool, alpha: bool| Some(GraySource { one_bit, alpha }); + if let Some((kind, _)) = crate::cmyk::tiff(&self.bytes) { + return match kind { + tiff::ColorType::Gray(bits) => gray(bits == 1, false), + tiff::ColorType::GrayA(bits) => gray(bits == 1, true), + _ => None, + }; + } + if crate::cmyk::jpeg_components(&self.bytes) == Some(1) { + return gray(false, false); + } + use image::{ExtendedColorType as E, ImageDecoder as _}; + let reader = image::ImageReader::new(Cursor::new(self.bytes.as_slice())).with_guessed_format().ok()?; + match reader.into_decoder().ok()?.original_color_type() { + E::L1 => gray(true, false), + E::La1 => gray(true, true), + E::L2 | E::L4 | E::L8 | E::L16 => gray(false, false), + E::La2 | E::La4 | E::La8 | E::La16 => gray(false, true), + _ => None, + } + } + + /// How much of a colorize paint each pixel shows, row by row from the top: how dark the pixel + /// is (255 less its Rec. 709 luma) scaled by its alpha, so white and transparent pixels are 0. + /// Returns the width, the height and one byte a pixel; `None` when the image can't be decoded + /// within [`MAX_RASTER_ALLOC`]. + pub fn coverage(&self) -> Option<(u32, u32, Vec)> { + let img = rgba_within(&self.bytes, MAX_RASTER_ALLOC)?; + let (w, h) = img.dimensions(); + let cover = img + .pixels() + .map(|p| { + let [r, g, b, a] = p.0; + let luma = 0.2126 * r as f32 + 0.7152 * g as f32 + 0.0722 * b as f32; + ((255.0 - luma).clamp(0.0, 255.0) * a as f32 / 255.0).round() as u8 + }) + .collect(); + Some((w, h, cover)) + } +} + impl ImageBlob { /// The colour around pixel (`x`, `y`) (pixel space): the alpha-weighted average of the `size` × /// `size` pixels centred on it, clipped to the image, as straight RGBA. `None` outside the @@ -298,4 +353,66 @@ mod tests { assert!(b.map_rgb(|c| c).is_none(), "nothing changed"); assert!(ImageBlob::png(vec![1, 2, 3]).map_rgb(|c| c).is_none(), "undecodable"); } + + /// An uncompressed 1-bit TIFF, BlackIsZero, of `w` × `h` pixels: `rows` holds each row's bits, + /// padded to a byte, most significant bit first. + fn bilevel_tiff(w: u16, h: u16, rows: &[u8]) -> Vec { + // Tag, type (3 short, 4 long) and value of each entry, in tag order. + let data_at = 8 + 2 + 9 * 12 + 4; + let entries: [(u16, u16, u32); 9] = [ + (256, 3, w.into()), + (257, 3, h.into()), + (258, 3, 1), + (259, 3, 1), + (262, 3, 1), + (273, 4, data_at), + (277, 3, 1), + (278, 3, h.into()), + (279, 4, rows.len() as u32), + ]; + let mut out = b"II*\0".to_vec(); + out.extend_from_slice(&8u32.to_le_bytes()); + out.extend_from_slice(&(entries.len() as u16).to_le_bytes()); + for (tag, kind, value) in entries { + out.extend_from_slice(&tag.to_le_bytes()); + out.extend_from_slice(&kind.to_le_bytes()); + out.extend_from_slice(&1u32.to_le_bytes()); + out.extend_from_slice(&value.to_le_bytes()); + } + out.extend_from_slice(&0u32.to_le_bytes()); + out.extend_from_slice(rows); + out + } + + fn png_of(img: image::DynamicImage) -> ImageBlob { + let mut png = Vec::new(); + img.write_to(&mut Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + ImageBlob::png(png) + } + + #[test] + fn grayscale_and_1_bit_files_are_told_from_color_ones() { + let gray = |one_bit, alpha| Some(GraySource { one_bit, alpha }); + let l8 = png_of(image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(2, 1, vec![0, 255]).unwrap())); + assert_eq!(l8.gray_source(), gray(false, false)); + let la8 = png_of(image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(1, 1, vec![0, 128]).unwrap())); + assert_eq!(la8.gray_source(), gray(false, true)); + let mut jpeg = Vec::new(); + jpeg_encoder::Encoder::new(&mut jpeg, 90).encode(&[0, 255, 0, 255], 2, 2, jpeg_encoder::ColorType::Luma).unwrap(); + assert_eq!(ImageBlob::new("image/jpeg", jpeg).gray_source(), gray(false, false)); + // Black, white; white, black. + let tif = ImageBlob::new("image/tiff", bilevel_tiff(2, 2, &[0b0100_0000, 0b1000_0000])); + assert_eq!(tif.gray_source(), gray(true, false)); + assert_eq!(tif.coverage(), Some((2, 2, vec![255, 0, 0, 255])), "black covers, white doesn't"); + // Color images and data that isn't an image. + assert_eq!(blob(&[[0, 0, 0, 255], [9, 9, 9, 255]], 2, 1).gray_source(), None); + assert_eq!(ImageBlob::png(vec![1, 2, 3]).gray_source(), None); + } + + #[test] + fn coverage_is_darkness_times_alpha() { + let la8 = png_of(image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(4, 1, vec![0, 255, 255, 255, 51, 255, 0, 128]).unwrap())); + assert_eq!(la8.coverage(), Some((4, 1, vec![255, 0, 204, 128]))); + assert_eq!(ImageBlob::png(vec![1, 2, 3]).coverage(), None); + } } diff --git a/crates/doc/src/swatches.rs b/crates/doc/src/swatches.rs index 692fa868c7..95978bd8d2 100644 --- a/crates/doc/src/swatches.rs +++ b/crates/doc/src/swatches.rs @@ -229,13 +229,14 @@ fn item_paint_mut(it: &mut AppearanceItem) -> &mut Paint { } } -/// The paints a node holds itself (not its children): appearance items, then text runs. +/// The paints a node holds itself (not its children): appearance items, then text runs, then an +/// image's colorize paint. pub fn node_paints(n: &Node) -> impl Iterator { let runs = match &n.kind { NodeKind::Text(t) => t.runs.as_slice(), _ => &[], }; - n.appearance.items.iter().map(item_paint).chain(runs.iter().flat_map(|r| [&r.style.fill, &r.style.stroke])) + n.appearance.items.iter().map(item_paint).chain(runs.iter().flat_map(|r| [&r.style.fill, &r.style.stroke])).chain(n.extras().colorize.as_deref()) } /// Mutable [`node_paints`], in the same order. @@ -244,7 +245,8 @@ pub fn node_paints_mut(n: &mut Node) -> impl Iterator { NodeKind::Text(t) => t.runs.as_mut_slice(), _ => &mut [], }; - n.appearance.items.iter_mut().map(item_paint_mut).chain(runs.iter_mut().flat_map(|r| [&mut r.style.fill, &mut r.style.stroke])) + let colorize = n.extras.0.as_deref_mut().and_then(|e| e.colorize.as_deref_mut()); + n.appearance.items.iter_mut().map(item_paint_mut).chain(runs.iter_mut().flat_map(|r| [&mut r.style.fill, &mut r.style.stroke])).chain(colorize) } /// `n` with `f` applied to its subtree's linkable colours, or `None` when nothing changed (then diff --git a/crates/effects/src/catalog.rs b/crates/effects/src/catalog.rs index e000b930f4..d10d931d65 100644 --- a/crates/effects/src/catalog.rs +++ b/crates/effects/src/catalog.rs @@ -42,6 +42,20 @@ pub fn is_length(id: &str, key: &str, relative: bool) -> bool { catalog_index().get(id).is_some_and(|info| info.lengths.keys(relative).any(|k| k == key)) } +/// The range in points that distance parameter `key` of effect `id` is kept within, as its +/// parameter documentation gives it (`{maxRadius: pt 4..127 (8), …}`); `None` when it gives none. +pub fn length_range(id: &str, key: &str) -> Option> { + let doc = catalog_index().get(id)?.params; + let starts = |at: usize| doc.get(..at).and_then(|s| s.chars().last()).is_some_and(|c| c == '{' || c == ' '); + let rest = doc.match_indices(key).map(|(at, _)| at).filter(|at| starts(*at)).find_map(|at| { + let rest = doc.get(at + key.len()..)?; + rest.strip_prefix(": pt ").or_else(|| rest.strip_prefix("?: pt ")) + })?; + let (lo, hi) = rest.split_whitespace().next()?.split_once("..")?; + let (lo, hi) = (lo.parse::().ok()?, hi.trim_end_matches(',').parse::().ok()?); + (lo.is_finite() && hi.is_finite() && lo <= hi).then_some(lo..=hi) +} + /// The distance parameters of effect `id` (none for unknown effects). fn lengths_of(id: &str) -> Lengths { let always = |always| Lengths { always, absolute: &[] }; diff --git a/crates/effects/src/geometry.rs b/crates/effects/src/geometry.rs index a4cb2e1d87..5420982013 100644 --- a/crates/effects/src/geometry.rs +++ b/crates/effects/src/geometry.rs @@ -114,16 +114,67 @@ pub fn apply_geometry_with(effects: &[Effect], path: &PathData, bounds: Rect, ct apply_geometry_within(effects, path, bounds, ctx, Budget::EFFECTS) } +/// Does effect `e` safely commute with pure translation when it is terminal? +/// Only positive offsets with round joins commute exactly with pure translations for non-zero fills (#4145). +fn is_terminal_offset_eligible(e: &Effect) -> bool { + if e.id != "path.offsetPath" { + return false; + } + let p = merged_params(&e.id, &e.params); + util::join(&p, "joins") == vectorcraft_pathops::Join::Round && util::num(&p, "offset", 10.0) >= 0.0 +} + +/// Optimize a list of visible geometry effects: move pure-translation Transform effects with +/// copies after a terminal Offset Path effect when the effective style is safe (NonZero fill and +/// no stroke), so that the offset path is evaluated once on the base path rather than on dozens +/// of overlapping copies, avoiding combinatorial explosions in the planar sweep (#4145). +pub(crate) fn optimize_geometry_effects<'a>(effects: &[&'a Effect], style_safe: bool) -> Vec<&'a Effect> { + let mut out: Vec<&'a Effect> = effects.to_vec(); + if !style_safe || out.len() < 2 { + return out; + } + let mut changed = true; + while changed { + changed = false; + for i in 0..out.len().saturating_sub(1) { + let e1 = out[i]; + if e1.id == "distort.transform" { + let p1 = merged_params(&e1.id, &e1.params); + if let Some((_, copies)) = crate::distort::transform_move(&p1) + && copies > 0 + && is_terminal_offset_eligible(out[i + 1]) + && out.get(i + 2..).is_some_and(|tail| tail.iter().all(|e| e.id == "distort.transform")) + { + out.swap(i, i + 1); + changed = true; + } + } + } + } + out +} + /// [`apply_geometry_with`] whose effects keep to `budget`, raised to what `path` costs where that /// is more. pub(crate) fn apply_geometry_within(effects: &[Effect], path: &PathData, bounds: Rect, ctx: &GeomContext, budget: Budget) -> PathData { // `budget` raised to what `path` costs, measured once, and only for a path that has geometry // effects. + let has_stroke = match (ctx.item, ctx.appearance) { + (Some(idx), Some(app)) => match app.items.get(idx) { + Some(AppearanceItem::Stroke(s)) => !s.paint.is_none() && s.width > 0.0, + Some(AppearanceItem::Fill(_)) => false, + None => ctx.stroke.is_some_and(|s| !s.paint.is_none() && s.width > 0.0), + }, + _ => ctx.stroke.is_some_and(|s| !s.paint.is_none() && s.width > 0.0), + }; + let style_safe = ctx.rule == FillRule::NonZero && !has_stroke; + let visible_fx: Vec<&Effect> = effects.iter().filter(|e| e.visible && is_geometry(&e.id)).collect(); + let fx = optimize_geometry_effects(&visible_fx, style_safe); let mut limit = None; let mut cur = path.clone(); let mut b = bounds; let mut first = true; - for e in effects.iter().filter(|e| e.visible && is_geometry(&e.id)) { + for e in fx { if !first { b = cur.bounds().unwrap_or(b); } diff --git a/crates/effects/src/group.rs b/crates/effects/src/group.rs index ad59278507..cad97ca562 100644 --- a/crates/effects/src/group.rs +++ b/crates/effects/src/group.rs @@ -7,6 +7,10 @@ //! result keeps the appearance of the object whose paint it takes. Trap ([`crate::trap`]) keeps the //! children and adds its traps above them. //! +//! **Compound shapes** ([`compound_shape_area`]): a compound shape draws as the one area its +//! members' shape modes make, painted by its own appearance as a group's own fills and strokes +//! paint its members. +//! //! **Container appearance** ([`evaluate_container`]): a group's or layer's own fills and strokes //! paint every member's geometry, below or above the members as its contents slot says //! ([`Appearance::contents_at`]); its geometry effects reshape the members as one piece; its raster @@ -16,7 +20,7 @@ use std::sync::Arc; use serde_json::Value; use vectorcraft_doc::color::{Color, Paint}; -use vectorcraft_doc::{Appearance, AppearanceItem, Document, Node, NodeId, NodeKind, StrokeLayer}; +use vectorcraft_doc::{Appearance, AppearanceItem, Document, Node, NodeId, NodeKind, ShapeMode, StrokeLayer}; use vectorcraft_geom::{FillRule, PathData, Rect}; use vectorcraft_pathops::{self as po, PathfinderOp}; @@ -45,10 +49,11 @@ fn op_of(id: &str) -> Option { PATHFINDER_EFFECTS.iter().find(|e| e.0 == id).map(|e| e.2) } -/// Does `n` (a group or layer) carry a visible Pathfinder effect? +/// Does `n` (a group or layer) carry a visible Pathfinder effect, or is it a compound shape? pub fn has_pathfinder(n: &Node) -> bool { - matches!(n.kind, NodeKind::Group { clip: false, .. } | NodeKind::Layer { .. }) - && n.appearance.effects.iter().any(|e| e.visible && is_pathfinder(&e.id)) + n.is_compound_shape() + || (matches!(n.kind, NodeKind::Group { clip: false, .. } | NodeKind::Layer { .. }) + && n.appearance.effects.iter().any(|e| e.visible && is_pathfinder(&e.id))) } /// Converts objects that aren't paths (e.g. text) to outline art, if possible. The paths and @@ -62,11 +67,15 @@ fn leaves(n: &Node, hook: Option, out: &mut Vec) { } match &n.kind { NodeKind::Path { guide: false, .. } | NodeKind::Compound { .. } => out.push(n.clone()), - NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } => { - for c in children { - leaves(c, hook, out); + // A compound shape takes part as its area, styled like it. + NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } => match compound_shape_art(n, hook) { + Some(art) => out.push(art), + None => { + for c in children { + leaves(c, hook, out); + } } - } + }, _ => { // Every path of the outline art, at any depth, takes the object's opacity and blend // mode. @@ -91,6 +100,63 @@ fn geometry(n: &Node) -> Option<(PathData, FillRule)> { } } +/// The operation that combines a compound shape's member in `mode` with the area below it. +fn shape_op(mode: ShapeMode) -> po::BoolOp { + match mode { + ShapeMode::Add => po::BoolOp::Union, + ShapeMode::Subtract => po::BoolOp::Difference, + ShapeMode::Intersect => po::BoolOp::Intersect, + ShapeMode::Exclude => po::BoolOp::Xor, + } +} + +/// The area compound shape `n` draws: each visible member's shape (a group's leaves together, type +/// as its outlines through `hook`, open paths closed) combined with the area of the members below +/// it by the member's shape mode; the backmost member starts the area. `None` when `n` is not a +/// compound shape, or its members are past a live Pathfinder's budget ([`PATHFINDER_MAX_SEGMENTS`], +/// [`PATHFINDER_MAX_OVERLAPS`]). +pub fn compound_shape_area(n: &Node, hook: Option) -> Option { + if !n.is_compound_shape() { + return None; + } + let mut all: Vec = vec![]; + // Each member that has a shape: its operation and how many of the leaves are its. + let mut members: Vec<(po::BoolOp, usize)> = vec![]; + for c in n.children()? { + let before = all.len(); + leaves(c, hook, &mut all); + if all.len() > before { + members.push((shape_op(c.extras().shape_mode), all.len() - before)); + } + } + if !within_budget(&all) { + return None; + } + if all.is_empty() { + return Some(PathData::default()); + } + let parts: Vec<(PathData, FillRule)> = all.iter().map(|l| geometry(l).unwrap_or_default()).collect(); + let refs: Vec<(&PathData, FillRule)> = parts.iter().map(|(p, r)| (p, *r)).collect(); + Some(po::boolean_n(&refs, |inside| { + let (mut start, mut area) = (0, false); + for (k, (op, count)) in members.iter().enumerate() { + let here = inside.get(start..start + count).is_some_and(|flags| flags.contains(&true)); + start += count; + area = if k == 0 { here } else { op.apply(area, here) }; + } + area + })) +} + +/// Compound shape `n` as one path of its area ([`compound_shape_area`]) with its appearance, +/// opacity and blend mode: how it takes part in a Pathfinder operation. +pub fn compound_shape_art(n: &Node, hook: Option) -> Option { + let area = compound_shape_area(n, hook)?; + let mut art = Node::path(n.id, area, Appearance { items: n.appearance.items.clone(), ..Default::default() }); + (art.opacity, art.blend) = (n.opacity, n.blend); + Some(art) +} + /// A result path styled like `src` (its appearance, opacity and blend mode). fn styled(src: &Node, path: PathData, outline: bool) -> Node { let mut appearance = Appearance { items: src.appearance.items.clone(), ..Default::default() }; @@ -196,7 +262,16 @@ pub fn pathfinder_children(group: &Node, hook: Option) -> Option] = group.children()?; - let mut stack: Vec> = source.to_vec(); + let mut stack: Vec> = if group.is_compound_shape() { + // The group's own appearance paints the area ([`evaluate_container`]), so the art has none. + match compound_shape_area(group, hook) { + Some(area) if area.is_empty() => vec![], + Some(area) => vec![Arc::new(Node::path(group.id, area, Appearance::default()))], + None => return Some(source.to_vec()), + } + } else { + source.to_vec() + }; for e in group.appearance.effects.iter().filter(|e| e.visible) { if e.id == crate::trap::TRAP { let mut lv = vec![]; @@ -375,6 +450,13 @@ pub fn member_shapes(doc: Option<&Document>, n: &Node) -> Vec<(PathData, FillRul } match &n.kind { NodeKind::Path { guide: false, .. } | NodeKind::Compound { .. } => out.extend(crate::reshape::leaf_geometry(n)), + NodeKind::Group { .. } if n.is_compound_shape() => { + let hook: &dyn Fn(&Node) -> Option = &crate::outline_text; + match compound_shape_area(n, Some(hook)) { + Some(area) => out.push((area, FillRule::NonZero)), + None => members(doc, n, out), + } + } NodeKind::Text(t) => { let (_, all) = crate::reshape::glyph_outlines(t); if !all.elements().is_empty() { @@ -454,6 +536,8 @@ pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option { if let Some(ch) = m.children_mut() { *ch = result; } + // The area is art now: drawn again, it is no compound shape of its own. + m.extras_mut().compound_shape = false; } if !fx.is_empty() { m = crate::reshape::outlined_members(doc, &m); diff --git a/crates/effects/src/group/tests.rs b/crates/effects/src/group/tests.rs index c3bf4bfe3f..7c9f649c7a 100644 --- a/crates/effects/src/group/tests.rs +++ b/crates/effects/src/group/tests.rs @@ -347,3 +347,72 @@ fn pathfinder_on_many_stacked_bars_still_runs() { let out = pathfinder_children(&g, None).unwrap(); assert_eq!(out.len(), 1); } + +/// Two overlapping squares (0–10 and 5–15 by 10 high) as a compound shape, the front one in `mode`. +fn compound_shape(mode: ShapeMode) -> Node { + let mut front = (*sq(2, 5.0, Color::rgb(0.0, 0.0, 1.0))).clone(); + front.extras_mut().shape_mode = mode; + let mut g = Node::group(NodeId(10), vec![sq(1, 0.0, Color::rgb(1.0, 0.0, 0.0)), Arc::new(front)]); + g.extras_mut().compound_shape = true; + g.appearance = Appearance::basic(Paint::solid(Color::rgb(0.0, 1.0, 0.0)), Paint::None, 0.0).into(); + g +} + +/// A compound shape draws the area its members' modes make, one unpainted path that its own +/// appearance paints; evaluated, it is plain art painted with that appearance. +#[test] +fn compound_shapes_draw_the_area_their_shape_modes_make() { + for (mode, want) in [(ShapeMode::Add, 150.0), (ShapeMode::Subtract, 50.0), (ShapeMode::Intersect, 50.0), (ShapeMode::Exclude, 100.0)] { + let g = compound_shape(mode); + assert!(has_pathfinder(&g), "{mode:?}"); + let area_path = compound_shape_area(&g, None).unwrap(); + assert!((po::area(&area_path, FillRule::NonZero).abs() - want).abs() < 0.01, "{mode:?}"); + let out = pathfinder_children(&g, None).unwrap(); + assert_eq!(out.len(), 1, "{mode:?}"); + assert!(out[0].appearance.items.is_empty(), "the group's own appearance paints it"); + let art = evaluate_container(None, &g).unwrap(); + assert!(!art.is_compound_shape(), "evaluated, it is art"); + let painted: Vec<&Arc> = art.children().unwrap().iter().filter(|c| !c.appearance.items.is_empty()).collect(); + assert_eq!(painted.len(), 1); + assert_eq!(painted[0].appearance.fill_paint().color(), Some(Color::rgb(0.0, 1.0, 0.0)), "{mode:?}"); + assert!((area(painted[0]) - want).abs() < 0.01, "{mode:?}"); + } + // The backmost member's mode doesn't change the area. + let mut g = compound_shape(ShapeMode::Add); + if let Some(ch) = g.children_mut() { + let mut back = (*ch[0]).clone(); + back.extras_mut().shape_mode = ShapeMode::Subtract; + ch[0] = Arc::new(back); + } + assert!((po::area(&compound_shape_area(&g, None).unwrap(), FillRule::NonZero).abs() - 150.0).abs() < 0.01); + // Hidden members take no part; the mark on a clip group is ignored. + let mut g = compound_shape(ShapeMode::Subtract); + if let Some(ch) = g.children_mut() { + let mut front = (*ch[1]).clone(); + front.visible = false; + ch[1] = Arc::new(front); + } + assert!((po::area(&compound_shape_area(&g, None).unwrap(), FillRule::NonZero).abs() - 100.0).abs() < 0.01); + let mut clip = compound_shape(ShapeMode::Add); + clip.kind = NodeKind::Group { children: clip.children().unwrap().clone(), clip: true }; + assert!(!clip.is_compound_shape() && compound_shape_area(&clip, None).is_none()); +} + +/// A compound shape inside another (and inside an Effect › Pathfinder group) takes part as its area, +/// styled like it. +#[test] +fn nested_compound_shapes_take_part_as_their_area() { + let inner = compound_shape(ShapeMode::Subtract); + let mut cutter = (*sq(3, 2.0, Color::BLACK)).clone(); + cutter.extras_mut().shape_mode = ShapeMode::Intersect; + let mut outer = Node::group(NodeId(20), vec![Arc::new(inner.clone()), Arc::new(cutter)]); + outer.extras_mut().compound_shape = true; + // (0–5 of the inner area) ∩ (2–12) = 2–5 by 10 high. + assert!((po::area(&compound_shape_area(&outer, None).unwrap(), FillRule::NonZero).abs() - 30.0).abs() < 0.01); + let mut effect = Node::group(NodeId(30), vec![Arc::new(inner)]); + effect.appearance.effects.push(Effect { id: "pathfinder.add".into(), params: serde_json::json!({}), visible: true }); + let out = pathfinder_children(&effect, None).unwrap(); + assert_eq!(out.len(), 1); + assert!((area(&out[0]) - 50.0).abs() < 0.01); + assert_eq!(out[0].appearance.fill_paint().color(), Some(Color::rgb(0.0, 1.0, 0.0)), "styled like the compound shape"); +} diff --git a/crates/effects/src/lib.rs b/crates/effects/src/lib.rs index e3055da0bc..a732e2dfff 100644 --- a/crates/effects/src/lib.rs +++ b/crates/effects/src/lib.rs @@ -69,8 +69,8 @@ pub use adjust::{ pub use bake::{StrokeArt, bake_appearance, bake_document, expand_art, expand_leaf, fresh_ids, needs_bake}; pub use clip::clip_outline; pub use group::{ - OutlineHook, PATHFINDER_EFFECTS, evaluate_container, has_container_appearance, has_pathfinder, is_pathfinder, member_shapes, paints, - pathfinder_children, + OutlineHook, PATHFINDER_EFFECTS, compound_shape_area, compound_shape_art, evaluate_container, has_container_appearance, has_pathfinder, + is_pathfinder, member_shapes, paints, pathfinder_children, }; pub use lighting_presets::{LIGHTING_PRESETS, LightingPreset, lighting_preset_params, matching_lighting_preset}; pub use live::{expand_live, expand_live_deep, expanded_live_group, text_outliner}; @@ -94,7 +94,7 @@ mod catalog; mod geometry; mod params; -pub use catalog::{EffectInfo, Lengths, WARP_STYLES, effect_catalog, effect_info, is_length, plugin_effects}; +pub use catalog::{EffectInfo, Lengths, WARP_STYLES, effect_catalog, effect_info, is_length, length_range, plugin_effects}; pub(crate) use geometry::{Budget, apply_one}; pub use geometry::{GeomContext, apply_geometry, apply_geometry_bez, apply_geometry_with}; #[cfg(test)] diff --git a/crates/effects/src/reshape.rs b/crates/effects/src/reshape.rs index 8cab92a699..0d912b5318 100644 --- a/crates/effects/src/reshape.rs +++ b/crates/effects/src/reshape.rs @@ -431,6 +431,22 @@ pub(crate) fn reshape_leaves_within(art: &mut Node, fx: &[&Effect], budget: Budg if fx.is_empty() { return; } + let mut leaves_safe = true; + for_each_leaf(art, &mut |leaf| { + if !leaves_safe { + return; + } + if let Some((_, rule)) = leaf_geometry(leaf) { + let has_stroke = leaf.appearance.stroke().is_some_and(|s| !s.paint.is_none() && s.width > 0.0); + if rule != FillRule::NonZero || has_stroke { + leaves_safe = false; + } + } + }); + let art_stroke = art.appearance.stroke().is_some_and(|s| !s.paint.is_none() && s.width > 0.0); + let style_safe = leaves_safe && !art_stroke; + let opt_fx = crate::geometry::optimize_geometry_effects(fx, style_safe); + let fx = opt_fx.as_slice(); let seed = art.id.0; // The placed gradients of type's outlines in `art` (`outline_text`) move and scale with the // pieces, from the outlines' bounds before the effects to their bounds after them. diff --git a/crates/effects/src/tests.rs b/crates/effects/src/tests.rs index 3996794ace..198da329e8 100644 --- a/crates/effects/src/tests.rs +++ b/crates/effects/src/tests.rs @@ -438,6 +438,93 @@ fn three_max_detail_roughens_stay_within_the_effect_budget() { assert_ne!(out, apply_geometry(&[rough], &rect, rect.bounds().unwrap()), "more than one Roughen applies"); } +#[test] +fn transform_copies_before_offset_path_evaluates_without_ram_spike() { + let effects = [ + fx("distort.transform", json!({"moveH": -0.66, "moveV": 0.66, "copies": 30})), + fx("path.offsetPath", json!({"offset": 10.0, "joins": "round"})), + ]; + let path = shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)); + let start = std::time::Instant::now(); + let out = apply_geometry(&effects, &path, path.bounds().unwrap()); + let elapsed = start.elapsed(); + assert!(elapsed < std::time::Duration::from_secs(2), "elapsed: {:?}", elapsed); + assert_eq!(out.subpaths.len(), 31); +} + +#[test] +fn reshape_leaves_within_optimizes_transform_before_terminal_offset_path() { + use std::sync::Arc; + use vectorcraft_doc::{Appearance, Node, NodeId}; + + let id = NodeId(10); + let leaf = |x: f64| Arc::new(Node::path(id, shapes::rectangle(Rect::new(x, 0.0, x + 20.0, 20.0)), Appearance::default())); + let mut art = Node::group(id, (0..5).map(|k| leaf(k as f64 * 30.0)).collect()); + let transform = fx("distort.transform", json!({"moveH": 2.0, "moveV": 2.0, "copies": 10})); + let offset = fx("path.offsetPath", json!({"offset": 4.0, "joins": "round"})); + + let start = std::time::Instant::now(); + crate::reshape::reshape_leaves_within(&mut art, &[&transform, &offset], Budget::EFFECTS); + let elapsed = start.elapsed(); + assert!(elapsed < std::time::Duration::from_secs(2)); + + let children = art.children().unwrap(); + assert_eq!(children.len(), 5); + for c in children { + let (p, _) = crate::reshape::leaf_geometry(c).unwrap(); + // Base rectangle offset once, then copied 10 times -> 11 subpaths + assert_eq!(p.subpaths.len(), 11); + } +} + +#[test] +fn reshape_leaves_within_preserves_order_when_not_terminal_or_not_style_safe() { + use std::sync::Arc; + use vectorcraft_doc::{Appearance, Node, NodeId, NodeKind}; + + let id = NodeId(11); + // 1. EvenOdd fill rule: preserving order causes Transform copies to union in Offset Path into 1 subpath. + let mut leaf = Node::path(id, shapes::rectangle(Rect::new(0.0, 0.0, 20.0, 20.0)), Appearance::default()); + if let NodeKind::Path { rule, .. } = &mut leaf.kind { + *rule = FillRule::EvenOdd; + } + let mut art_evenodd = Node::group(id, vec![Arc::new(leaf)]); + let transform = fx("distort.transform", json!({"moveH": 2.0, "moveV": 2.0, "copies": 2})); + let offset = fx("path.offsetPath", json!({"offset": 4.0})); + crate::reshape::reshape_leaves_within(&mut art_evenodd, &[&transform, &offset], Budget::EFFECTS); + let p = art_evenodd.children().unwrap()[0].path_data().unwrap(); + assert_eq!(p.subpaths.len(), 1, "EvenOdd does not swap; copies union into 1 outer subpath"); + + // 2. Non-terminal Offset Path: followed by Round Corners, must preserve order. + let leaf_round = Arc::new(Node::path(id, shapes::rectangle(Rect::new(0.0, 0.0, 20.0, 20.0)), Appearance::default())); + let mut art_round = Node::group(id, vec![leaf_round]); + let round_corners = fx("stylize.roundCorners", json!({"radius": 2.0})); + crate::reshape::reshape_leaves_within(&mut art_round, &[&transform, &offset, &round_corners], Budget::EFFECTS); + let p = art_round.children().unwrap()[0].path_data().unwrap(); + assert_eq!(p.subpaths.len(), 1, "Non-terminal Offset Path does not swap; copies union into 1 outer subpath"); + + // 3. Non-round join (e.g. miter): preserving order is required as corners differ (#4145). + let leaf_miter = Arc::new(Node::path(id, shapes::rectangle(Rect::new(0.0, 0.0, 20.0, 20.0)), Appearance::default())); + let mut art_miter = Node::group(id, vec![leaf_miter]); + let offset_miter = fx("path.offsetPath", json!({"offset": 4.0, "joins": "miter"})); + crate::reshape::reshape_leaves_within(&mut art_miter, &[&transform, &offset_miter], Budget::EFFECTS); + let p = art_miter.children().unwrap()[0].path_data().unwrap(); + assert_eq!(p.subpaths.len(), 1, "Miter join does not swap; copies union into 1 outer subpath"); +} + +#[test] +fn consecutive_transforms_before_terminal_offset_path_all_move_after() { + let t1 = fx("distort.transform", json!({"moveH": 1.0, "moveV": 0.0, "copies": 2})); + let t2 = fx("distort.transform", json!({"moveH": 0.0, "moveV": 1.0, "copies": 3})); + let offset = fx("path.offsetPath", json!({"offset": 4.0, "joins": "round"})); + + let opt = crate::geometry::optimize_geometry_effects(&[&t1, &t2, &offset], true); + assert_eq!(opt.len(), 3); + assert_eq!(opt[0].id, "path.offsetPath"); + assert_eq!(opt[1].id, "distort.transform"); + assert_eq!(opt[2].id, "distort.transform"); +} + #[test] fn transform_copies_stop_before_they_overflow() { let out = run("distort.transform", json!({"scaleH": 100000, "scaleV": 100000, "copies": 1000}), &square()); @@ -1120,3 +1207,17 @@ fn a_repeat_of_a_symbol_whose_art_is_a_repeat_shares_the_instance_budget() { let small = Node::new(NodeId(0), NodeKind::Repeat(RepeatSpec::mirror(vec![instance("Small")], 90.0, 5.0))); assert_eq!(expand_live(Some(&d), &small).len(), 2); } + +#[test] +fn a_distance_parameters_range_comes_from_its_documentation() { + assert_eq!(length_range("pixelate.colorHalftone", "maxRadius"), Some(4.0..=127.0)); + // The effect applies the range's floor to a radius below it. + assert_eq!( + crate::pixel::parse("pixelate.colorHalftone", &json!({"maxRadius": 1})), + crate::pixel::parse("pixelate.colorHalftone", &json!({"maxRadius": 4})) + ); + // A distance documented without a range, and unknown effects and parameters, have none. + assert_eq!(length_range("path.offsetPath", "offset"), None); + assert_eq!(length_range("pixelate.colorHalftone", "channel1"), None); + assert_eq!(length_range("no.such", "maxRadius"), None); +} diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index e9f2f29993..061d293b9f 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -10,6 +10,7 @@ pub mod clipboard; mod colorcmds; pub mod colormgmt; pub mod colortheme; +mod compoundshape; pub(crate) mod create; mod css; mod cut; @@ -249,6 +250,7 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(xform::specs()); v.extend(effectcmd::specs()); v.extend(pathops::specs()); + v.extend(compoundshape::specs()); v.extend(typecmd::specs()); v.extend(menucmds::specs()); v.extend(live::specs()); @@ -378,6 +380,15 @@ pub(crate) fn check_switches(p: &Value, keys: &[&str], cmd: &str) -> Result<()> pub(crate) fn str_param<'a>(p: &'a Value, key: &str) -> Option<&'a str> { p.get(key).and_then(Value::as_str) } +/// The string `p` gives for `key`, or `None` when `p` leaves it out or gives null. Any other +/// value, such as `5`, is an error: "`{key}` must be a string". +pub(crate) fn text_param<'a>(p: &'a Value, key: &str, cmd: &str) -> Result> { + match p.get(key) { + None | Some(Value::Null) => Ok(None), + Some(Value::String(v)) => Ok(Some(v)), + Some(_) => Err(bad(cmd, format!("`{key}` must be a string"))), + } +} pub(crate) fn id_param(p: &Value, key: &str) -> Option { p.get(key).and_then(Value::as_u64).map(NodeId) } @@ -514,26 +525,30 @@ pub(crate) fn ok() -> Result { } /// Leaves whose appearance a paint command changes: groups and layers expand to their contents, -/// and compound paths own their children's appearance, so a member stands for its compound path -/// (#3692), which is listed once. +/// and compound paths and compound shapes own their members' appearance, so a member stands for +/// its compound path (#3692) or compound shape, which is listed once. pub(crate) fn leaf_targets(s: &Session, ids: &[NodeId]) -> Result> { use vectorcraft_doc::NodeKind; let d = &s.doc()?.doc; - let compound = |id: NodeId| d.parent_of(id).filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. }))); + let owns = |n: &vectorcraft_doc::Node| matches!(n.kind, NodeKind::Compound { .. }) || n.is_compound_shape(); + let compound = |id: NodeId| d.parent_of(id).filter(|p| d.node(*p).is_some_and(owns)); let mut out = vec![]; for id in ids { let Some(n) = d.node(*id) else { continue }; match &n.kind { - NodeKind::Group { .. } | NodeKind::Layer { .. } => n.walk(&mut |c| { - if !c.is_container() || matches!(c.kind, NodeKind::Compound { .. }) { + NodeKind::Group { .. } | NodeKind::Layer { .. } if !n.is_compound_shape() => n.walk(&mut |c| { + if !c.is_container() || owns(c) { out.push(c.id) } }), _ => out.push(compound(*id).unwrap_or(*id)), } } - let comp: Vec = out.iter().filter(|id| matches!(d.node(**id).map(|n| &n.kind), Some(NodeKind::Compound { .. }))).copied().collect(); - out.retain(|id| !comp.iter().any(|c| d.parent_of(*id) == Some(*c))); + let comp: std::collections::HashSet = out.iter().filter(|id| d.node(**id).is_some_and(owns)).copied().collect(); + if !comp.is_empty() { + // A compound shape's members lie at any depth in it. + out.retain(|id| !d.ancestry(*id).is_some_and(|up| up.iter().rev().skip(1).any(|a| comp.contains(a)))); + } let mut seen = std::collections::HashSet::new(); out.retain(|id| seen.insert(*id)); Ok(out) @@ -581,6 +596,9 @@ pub use opacitymask::TransparencyInfo; /// Eyedropper Options (`Prefs::eyedropper`). pub use xform::{AppearanceAttrs, EyedropperAttrs, EyedropperOptions, FillAttrs, StrokeAttrs}; +/// The shape modes of the selected compound-shape members (the Pathfinder panel lights theirs). +pub use compoundshape::selected_member_modes; + /// Pathfinder Options (`Prefs::pathfinder`). pub use pathops::{PATHFINDER_PRECISION_RANGE, PathfinderOptions}; diff --git a/crates/engine/src/cmd/buildcmds/trace.rs b/crates/engine/src/cmd/buildcmds/trace.rs index 8d72568e83..308e300ec7 100644 --- a/crates/engine/src/cmd/buildcmds/trace.rs +++ b/crates/engine/src/cmd/buildcmds/trace.rs @@ -377,8 +377,11 @@ fn grouped(d: &mut Document, nodes: Vec, parents: &[Option]) -> Vec struct TraceInputs { target: NodeId, image: Box, - /// The settings traced with, as JSON, the library's colours in. + /// The settings traced with, as JSON. params: Value, + /// Document Library: the library's colours, which the JSON leaves out + /// ([`tr::TraceParams::swatches`]). + swatches: Vec<[u8; 3]>, } /// What `imageTrace.make` and `imageTrace.makeAndExpand` take from the session before they trace. @@ -431,7 +434,7 @@ fn prepare(s: &Session, c: &str, p: &Value) -> Result { let bytes = Arc::clone(&blob.bytes); let library = trace_library(c, s, &mut params)?; let traced_with = serde_json::to_value(¶ms).map_err(|e| EngineError::Other(e.to_string()))?; - let inputs = TraceInputs { target, image, params: traced_with }; + let inputs = TraceInputs { target, image, params: traced_with, swatches: params.swatches.clone() }; Ok(Prepared { inputs, trace: params, view, params_json, preset_label, library, bytes }) } @@ -544,7 +547,7 @@ pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result traced, _ => trace_now(&inputs, &trace, &bytes, &|_, _| true)?, }; - let TraceInputs { target, image: img, params: _ } = inputs; + let TraceInputs { target, image: img, .. } = inputs; let warnings = trace_warnings((img.width, img.height), raster, res.worked_at); // Pixel space of the decoded raster → the image object's pixel space → document. let sx = img.width.max(1) as f64 / raster.0.max(1) as f64; diff --git a/crates/engine/src/cmd/colormgmt.rs b/crates/engine/src/cmd/colormgmt.rs index b1ad12800e..0cf1a0ec7e 100644 --- a/crates/engine/src/cmd/colormgmt.rs +++ b/crates/engine/src/cmd/colormgmt.rs @@ -645,6 +645,7 @@ fn set_spot(s: &mut Session, p: &Value) -> Result { } if sw.spot != spot { let n = name.clone(); + let colorized_ok = super::paint::check_colorized(&s.doc()?.doc).is_ok(); s.edit("Swatch Options", |d, _| { if let Some(w) = d.swatch_mut(&n) { w.spot = spot; @@ -652,7 +653,7 @@ fn set_spot(s: &mut Session, p: &Value) -> Result { w.global = true; } } - Ok(()) + super::paint::check_colorized_kept(colorized_ok, d).map_err(|e| bad(C, e)) })?; } Ok(json!({"name": name, "spot": spot})) diff --git a/crates/engine/src/cmd/compoundshape.rs b/crates/engine/src/cmd/compoundshape.rs new file mode 100644 index 0000000000..7c5aa3f5bb --- /dev/null +++ b/crates/engine/src/cmd/compoundshape.rs @@ -0,0 +1,256 @@ +//! Pathfinder panel › compound shapes (`object.compoundShape.*`): Make Compound Shape (what +//! Alt-clicking a Shape Mode button does), a member's shape mode, Release and Expand Compound +//! Shape. A compound shape is a group marked so ([`Node::is_compound_shape`]) whose members each +//! have a [`ShapeMode`]; `vectorcraft-effects` draws it as the area they make +//! ([`effects::compound_shape_area`]). + +use std::sync::Arc; + +use serde_json::{Value, json}; +use vectorcraft_doc::{Document, Node, NodeId, NodeKind, ShapeMode}; +use vectorcraft_render::effects; + +use super::edit::{roots_of, selected_roots}; +use super::pathops::{pf_leaves, shape_node, style_of}; +use super::{CommandSpec, EngineError, Result, Session, bad, cmd, has_multi}; + +const MODE_NAMES: [&str; 4] = ["add", "subtract", "intersect", "exclude"]; + +pub fn specs() -> Vec { + vec![ + cmd!( + "object.compoundShape.make", + "Make Compound Shape", + ["Window", "Pathfinder"], + None, + "{ids?: [id…] (selected first; default: the selection), mode?: \"add\"|\"subtract\"|\"intersect\"|\"exclude\" (default add; Alt-clicking a Shape Mode button gives its mode)} the two or more selected objects (paths, compound paths, groups, compound shapes, type) become the members of one compound shape, each with the shape mode, in their stacking order where the frontmost was: it draws as the area they make from the backmost up (open paths closed), painted with the appearance and transparency of the topmost member in Add, Intersect or Exclude mode (with every member in Subtract, the backmost), and the members stay editable (Direct Selection, Layers panel, isolation mode) → {id}", + has_multi, + make + ), + cmd!( + "object.compoundShape.setMode", + "Shape Mode", + ["Window", "Pathfinder"], + None, + "{mode: \"add\"|\"subtract\"|\"intersect\"|\"exclude\", ids?: [id…] (selected first; default: the selection)} the members of compound shapes that the selected objects are or are in take the shape mode (what clicking a Shape Mode button does with members selected); the backmost member's mode doesn't change the shape → {ids}", + has_member, + set_mode + ), + cmd!( + "object.compoundShape.release", + "Release Compound Shape", + ["Window", "Pathfinder"], + None, + "{ids?: [id…] (selected first; default: the selection)} the selected compound shapes (and those holding the selected objects) become their members again, as they were before Make Compound Shape, selected → {ids}", + has_compound_shape, + release + ), + cmd!( + "object.compoundShape.expand", + "Expand Compound Shape", + ["Window", "Pathfinder"], + None, + "{ids?: [id…] (selected first; default: the selection)} the selected compound shapes (and those holding the selected objects) become the path, or compound path, of the area they draw, painted as they are, selected → {ids}", + has_compound_shape, + expand + ), + ] +} + +/// The innermost compound shape holding `id` (not `id` itself), with the member of it that `id` is +/// or is in. +fn holder(d: &Document, id: NodeId) -> Option<(NodeId, NodeId)> { + let up = d.ancestry(id)?; + up.windows(2).rev().find_map(|w| match w { + [shape, member] if d.node(*shape).is_some_and(Node::is_compound_shape) => Some((*shape, *member)), + _ => None, + }) +} + +/// The compound shape `id` is or is in (the innermost). +fn shape_of(d: &Document, id: NodeId) -> Option { + if d.node(id)?.is_compound_shape() { Some(id) } else { holder(d, id).map(|(shape, _)| shape) } +} + +/// The compound shapes the selection is or is in, outermost only, in paint order. +fn selected_shapes(s: &Session) -> Result> { + let st = s.doc()?; + let mut shapes: Vec = vec![]; + for id in st.selection.in_paint_order(&st.doc) { + if let Some(shape) = shape_of(&st.doc, id).filter(|shape| !shapes.contains(shape)) { + shapes.push(shape); + } + } + Ok(roots_of(&st.doc, shapes)) +} + +/// The members of compound shapes that the selected objects are or are in. +fn selected_members(s: &Session) -> Result> { + let st = s.doc()?; + let mut members: Vec = vec![]; + for id in &st.selection.objects { + if let Some((_, member)) = holder(&st.doc, *id).filter(|(_, m)| !members.contains(m)) { + members.push(member); + } + } + Ok(members) +} + +/// The shape modes of the compound-shape members the selection is or is in (none when it is in +/// none): the Pathfinder panel lights the Shape Mode button they share. +pub fn selected_member_modes(s: &Session) -> Vec { + let Some(st) = s.active() else { return vec![] }; + let members = selected_members(s).unwrap_or_default(); + members.iter().filter_map(|id| st.doc.node(*id)).map(|n| n.extras().shape_mode).collect() +} + +/// The selection is or is in a compound shape. +fn has_compound_shape(s: &Session) -> std::result::Result<(), String> { + let st = s.active().ok_or("no document open")?; + if st.selection.objects.iter().any(|id| shape_of(&st.doc, *id).is_some()) { Ok(()) } else { Err("select a compound shape".into()) } +} + +/// The selection is or is in a member of a compound shape. +fn has_member(s: &Session) -> std::result::Result<(), String> { + let st = s.active().ok_or("no document open")?; + if st.selection.objects.iter().any(|id| holder(&st.doc, *id).is_some()) { Ok(()) } else { Err("select members of a compound shape".into()) } +} + +/// The `mode` param: one of [`MODE_NAMES`], or `default` when it is missing (`None`: required). +fn mode_param(p: &Value, cmd: &str, default: Option) -> Result { + match super::object::choice(p, cmd, "mode", &MODE_NAMES)? { + Some(name) => ShapeMode::parse(name), + None => default, + } + .ok_or_else(|| bad(cmd, format!("`mode` must be one of {}", MODE_NAMES.join(", ")))) +} + +fn ids_json(ids: &[NodeId]) -> Value { + json!({ "ids": ids.iter().map(|i| i.0).collect::>() }) +} + +fn make(s: &mut Session, p: &Value) -> Result { + const C: &str = "object.compoundShape.make"; + let mode = mode_param(p, C, Some(ShapeMode::Add))?; + let roots = selected_roots(s)?; + if roots.len() < 2 { + return Err(bad(C, "select at least two objects")); + } + let d = &s.doc()?.doc; + let mut members = Vec::with_capacity(roots.len()); + for id in &roots { + let n = d.node(*id).ok_or(EngineError::NoNode(*id))?; + if !matches!(n.kind, NodeKind::Path { guide: false, .. } | NodeKind::Compound { .. } | NodeKind::Group { .. } | NodeKind::Text(_)) { + return Err(bad(C, "compound shapes take paths, compound paths, groups, compound shapes and type")); + } + members.push(n); + } + // The paint and transparency of the topmost member in Add, Intersect or Exclude mode: as they + // all have `mode`, the topmost, or the backmost when they all subtract. + let order: Vec<&Node> = if mode == ShapeMode::Subtract { members } else { members.into_iter().rev().collect() }; + let style = order.into_iter().find_map(|n| { + let mut lv = vec![]; + pf_leaves(n, &mut lv); + lv.last().map(style_of) + }); + let id = s.edit("Make Compound Shape", |d, sel| { + let gid = d.alloc_id(); + let id = d.wrap(&roots, |children| { + let children = children + .into_iter() + .map(|c| { + let mut c = Arc::unwrap_or_clone(c); + c.extras_mut().shape_mode = mode; + Arc::new(c) + }) + .collect(); + let mut g = Node::group(gid, children); + g.extras_mut().compound_shape = true; + if let Some(style) = &style { + style.apply(&mut g); + } + g + })?; + sel.set([id]); + Ok(id) + })?; + Ok(json!({ "id": id.0 })) +} + +fn set_mode(s: &mut Session, p: &Value) -> Result { + const C: &str = "object.compoundShape.setMode"; + let mode = mode_param(p, C, None)?; + let members = selected_members(s)?; + if members.is_empty() { + return Err(bad(C, "select members of a compound shape")); + } + // Members already in the mode leave the document and its undo history as they are. + let d = &s.doc()?.doc; + if members.iter().all(|id| d.node(*id).is_some_and(|n| n.extras().shape_mode == mode)) { + return Ok(ids_json(&members)); + } + s.edit("Shape Mode", |d, _| { + for id in &members { + d.node_mut(*id).ok_or(EngineError::NoNode(*id))?.extras_mut().shape_mode = mode; + } + Ok(()) + })?; + Ok(ids_json(&members)) +} + +fn release(s: &mut Session, _: &Value) -> Result { + let shapes = selected_shapes(s)?; + if shapes.is_empty() { + return Err(bad("object.compoundShape.release", "select a compound shape")); + } + let ids = s.edit("Release Compound Shape", |d, sel| { + let (mut items, mut released) = (vec![], vec![]); + for id in &shapes { + let members = d.node(*id).and_then(Node::children).ok_or(EngineError::NoNode(*id))?; + let out: Vec = members + .iter() + .map(|c| { + let mut c = (**c).clone(); + c.extras_mut().shape_mode = ShapeMode::Add; + released.push(c.id); + c + }) + .collect(); + items.push((*id, out)); + } + d.insert_beside(items, true)?; + sel.set(released.iter().copied()); + Ok(released) + })?; + Ok(ids_json(&ids)) +} + +fn expand(s: &mut Session, _: &Value) -> Result { + const LABEL: &str = "Expand Compound Shape"; + let shapes = selected_shapes(s)?; + if shapes.is_empty() { + return Err(bad("object.compoundShape.expand", "select a compound shape")); + } + let ids = s.edit(LABEL, |d, sel| { + let (mut items, mut made) = (vec![], vec![]); + for id in &shapes { + let shape = d.node(*id).cloned().ok_or(EngineError::NoNode(*id))?; + let area = effects::compound_shape_area(&shape, effects::text_outliner()) + .ok_or_else(|| EngineError::Other("the compound shape is too complex to expand".into()))?; + if area.is_empty() { + return Err(EngineError::Other(format!("{LABEL} produced an empty result"))); + } + let mut n = shape_node(d, area, None); + let mut appearance = (*shape.appearance).clone(); + appearance.contents_index = None; + n.appearance = appearance.into(); + (n.opacity, n.blend, n.name) = (shape.opacity, shape.blend, shape.name.clone()); + made.push(n.id); + items.push((*id, vec![n])); + } + d.insert_beside(items, true)?; + sel.set(made.iter().copied()); + Ok(made) + })?; + Ok(ids_json(&ids)) +} diff --git a/crates/engine/src/cmd/draw2/commands.rs b/crates/engine/src/cmd/draw2/commands.rs index 6926a38778..ddfa302e7a 100644 --- a/crates/engine/src/cmd/draw2/commands.rs +++ b/crates/engine/src/cmd/draw2/commands.rs @@ -92,7 +92,7 @@ pub fn specs() -> Vec { "Eraser", [], None, - "{points: [[x,y]…], size?: pt (10), angle?: ° (0), roundness?: % (100, kept within 1–100)} erase the stroke of an elliptical tip from paths (selected, or all) → {ids}. The tip is `size` across its long axis, which runs at `angle` counter-clockwise from horizontal; its short axis is `roundness` percent of the long one", + "{points: [[x,y]…] or [[x,y,pressure]…] (pen pressure 0..1), size?: pt (10), sizeMode?: \"fixed\" (default) | \"pressure\" (Eraser Tool Options' Size set to Pressure: the tip is size − sizeVariation across where the pen presses lightest and size + sizeVariation where it presses hardest, as path.blob), sizeVariation?: pt (0), angle?: ° (0), roundness?: % (100, kept within 1–100)} erase the stroke of an elliptical tip from paths (selected, or all) → {ids}. The tip is `size` across its long axis, which runs at `angle` counter-clockwise from horizontal; its short axis is `roundness` percent of the long one", has_doc, erase_region ), @@ -128,7 +128,7 @@ pub fn specs() -> Vec { "Blob Brush", [], None, - "{points: [[x,y]…], size?: pt (10), fidelity?: pt (0.01–100; the brush follows the stroke fitted at this tolerance as path.freehand fits a Pencil stroke, and a higher value gives a smoother shape; without it the brush follows every point), merge?: true, mergeOnlySelection?: bool (false: merge with any touching same-color blob; true: only with selected ones), keepSelected?: bool (false: the drawn or merged path is not selected, and the rest of the selection stays; true: it is selected)} filled brush shape, merged with the topmost touching same-color blob and the touching ones next to it in stacking order in its group or layer → {id}", + "{points: [[x,y]…] or [[x,y,pressure]…] (pen pressure 0..1), size?: pt (10), sizeMode?: \"fixed\" (default) | \"pressure\" (Blob Brush Tool Options' Size set to Pressure: the brush is size − sizeVariation wide at the lightest pen pressure and size + sizeVariation at the heaviest, at least 0.1 pt; a stroke without pressure keeps the size), sizeVariation?: pt (0), fidelity?: pt (0.01–100; the brush follows the stroke fitted at this tolerance as path.freehand fits a Pencil stroke, and a higher value gives a smoother shape; without it the brush follows every point), merge?: true, mergeOnlySelection?: bool (false: merge with any touching same-color blob; true: only with selected ones), keepSelected?: bool (false: the drawn or merged path is not selected, and the rest of the selection stays; true: it is selected)} filled brush shape, merged with the topmost touching same-color blob and the touching ones next to it in stacking order in its group or layer → {id}", has_doc, blob ), diff --git a/crates/engine/src/cmd/draw2/common.rs b/crates/engine/src/cmd/draw2/common.rs index b8c598a2d6..760105dcfb 100644 --- a/crates/engine/src/cmd/draw2/common.rs +++ b/crates/engine/src/cmd/draw2/common.rs @@ -1,7 +1,8 @@ use super::{ Appearance, Arc, Beside, Cap, Color, Document, EngineError, FillRule, Join, Node, NodeId, NodeKind, Paint, PathData, Point, PressureProfile, - Rect, Result, Selection, Session, SubPath, Value, Vec2, bad, index, json, po, + Rect, Result, Selection, Session, SubPath, Value, Vec2, bad, index, json, number_or, po, }; +use vectorcraft_doc::{LineCap, LineJoin, StrokeLayer, WidthProfile}; // ---------- helpers ---------- @@ -64,6 +65,36 @@ pub(super) fn stroke_pressure(samples: &[(Point, Option)]) -> Option 1e-9 { s / at } else { 0.0 }, p))) } +/// Blob Brush and Eraser Tool Options' Size set to Pressure (`sizeMode: "pressure"`, with +/// `sizeVariation` in points): the stroke's pen pressure along it and the variation, `None` for +/// Fixed (the default), no variation or a stroke without pressure (a mouse), which keeps the size. +pub(super) fn size_pressure(p: &Value, samples: &[(Point, Option)], cmd: &str) -> Result> { + match p.get("sizeMode").filter(|v| !v.is_null()).map(|v| v.as_str().ok_or(v)) { + None | Some(Ok("fixed")) => Ok(None), + Some(Ok("pressure")) => { + let variation = number_or(p, "sizeVariation", 0.0, cmd)?; + if !(variation.is_finite() && variation >= 0.0) { + return Err(bad(cmd, "sizeVariation must be 0 or more")); + } + Ok(stroke_pressure(samples).filter(|_| variation > 0.0).map(|prof| (prof, variation))) + } + Some(Ok(other)) => Err(bad(cmd, format!("sizeMode is \"fixed\" or \"pressure\", not `{other}`"))), + Some(Err(other)) => Err(bad(cmd, format!("sizeMode is \"fixed\" or \"pressure\", not {other}"))), + } +} + +/// The area a stroke along `spine` covers with Size set to Pressure: as wide at each point as +/// [`vectorcraft_tools::draw2::pressure_size`] gives for the pressure `prof` records there, with +/// round ends and joins, its overlaps united into one outline. +pub(super) fn pressure_region(spine: &PathData, size: f64, variation: f64, prof: &PressureProfile) -> Result { + let widest = size + variation; + let width = |t: f64| vectorcraft_tools::draw2::pressure_size(size, variation, prof.at(t)) / widest; + let profile = WidthProfile { points: prof.points.iter().map(|&(t, _)| (t, width(t), width(t))).collect() }; + let round = StrokeLayer { cap: LineCap::Round, join: LineJoin::Round, ..StrokeLayer::new(Paint::None, widest) }; + let outline = PathData::from_bezpath(&vectorcraft_render::width_outline(&spine.to_bezpath(), widest, &profile, &round, 0.05)); + po::try_unite_all(&[(&outline, FillRule::NonZero)]).map_err(|e| EngineError::Other(e.to_string())) +} + /// The length of a subpath. pub(super) fn subpath_len(sp: &SubPath) -> f64 { use kurbo::ParamCurveArclen; diff --git a/crates/engine/src/cmd/draw2/cut.rs b/crates/engine/src/cmd/draw2/cut.rs index e3a566f170..d9be52764e 100644 --- a/crates/engine/src/cmd/draw2/cut.rs +++ b/crates/engine/src/cmd/draw2/cut.rs @@ -1,6 +1,6 @@ use super::common::{ - dist_to_polyline, fill_targets, ids_json, path_mut, path_of, points_param, poly_bounds, replace_with_pieces, sibling_with, target_paths, - usize_opt, + dist_to_polyline, fill_targets, ids_json, path_mut, path_of, points_param, poly_bounds, pressure_region, replace_with_pieces, samples_param, + sibling_with, size_pressure, target_paths, usize_opt, }; use super::{ Anchor, AnchorKind, Beside, BezPath, BoolOp, Cap, EngineError, FillRule, Join, NodeId, ParamCurve, PathData, Point, Result, Session, SubPath, @@ -264,30 +264,47 @@ pub(super) fn knife(s: &mut Session, p: &Value) -> Result { pub(super) fn erase_region(s: &mut Session, p: &Value) -> Result { const C: &str = "path.eraseRegion"; - let pts = points_param(p, "points", C)?; + let samples = samples_param(p, "points", C)?; let size = number_or(p, "size", 10.0, C)?; if !(size.is_finite() && size > 0.0) { return Err(bad(C, "size must be positive")); } let angle = number_or(p, "angle", 0.0, C)?; let roundness = number_or(p, "roundness", 100.0, C)?; + let pressure = size_pressure(p, &samples, C)?; + let pts: Vec = samples.into_iter().map(|(pt, _)| pt).collect(); let r = size / 2.0; - // The tip's short axis: an open path is sampled at least every half of it. - let short = size * roundness.clamp(1.0, 100.0) / 100.0; + // The tip's short axis (its narrowest with Pressure): an open path is sampled at least every half of it. + let narrowest = pressure.as_ref().map_or(size, |(_, v)| vectorcraft_tools::draw2::pressure_size(size, *v, 0.0)); + let short = narrowest * roundness.clamp(1.0, 100.0) / 100.0; let st = s.doc()?; - let region = eraser_area(&pts, size, angle, roundness); // A point is under the tip when, with the tip squashed back into a circle, it is within the // circle's radius of the squashed drag. - let squash = eraser_tip(angle, roundness).inverse(); + let stretch = eraser_tip(angle, roundness); + let squash = stretch.inverse(); let round: Vec = pts.iter().map(|q| squash * *q).collect(); + // With Size set to Pressure the tip is as wide as the pen pressed: the area is the squashed + // drag outlined at those widths, stretched back, and a point is under it when the area holds it. + let pressed = match (&pressure, round.len() > 1) { + (Some((prof, v)), true) => Some(pressure_region(&PathData::single(SubPath::polyline(&round, false)), size, *v, prof)?.transformed(stretch)), + (Some((prof, v)), false) => Some(eraser_area(&pts, vectorcraft_tools::draw2::pressure_size(size, *v, prof.at(0.0)), angle, roundness)), + (None, _) => None, + }; + let reach = pressure.as_ref().map_or(r, |(_, v)| (size + v) / 2.0); + let region = pressed.clone().unwrap_or_else(|| eraser_area(&pts, size, angle, roundness)); + let outline = pressed.map(|pd| pd.to_bezpath()); + let under = |q: Point| match &outline { + Some(bp) => fill_contains(bp, FillRule::NonZero, q), + None => dist_to_polyline(&round, squash * q) <= r, + }; let mut plan: Vec<(NodeId, Vec)> = vec![]; - for (id, pd, rule) in fill_targets(&st.doc, &st.selection, poly_bounds(&pts, r))? { + for (id, pd, rule) in fill_targets(&st.doc, &st.selection, poly_bounds(&pts, reach))? { if pd.is_closed() { if po::area(&po::boolean(&pd, rule, ®ion, FillRule::NonZero, BoolOp::Intersect), FillRule::NonZero) <= 1e-6 { continue; } plan.push((id, components(&po::boolean(&pd, rule, ®ion, FillRule::NonZero, BoolOp::Difference)))); - } else if let Some(pieces) = erase_outline(&pd, short / 2.0, &|q| dist_to_polyline(&round, squash * q) <= r) { + } else if let Some(pieces) = erase_outline(&pd, short / 2.0, &under) { plan.push((id, pieces)); } } diff --git a/crates/engine/src/cmd/draw2/freehand.rs b/crates/engine/src/cmd/draw2/freehand.rs index c03eded58c..4a1e6d931e 100644 --- a/crates/engine/src/cmd/draw2/freehand.rs +++ b/crates/engine/src/cmd/draw2/freehand.rs @@ -1,6 +1,6 @@ use super::common::{ - brush_region, path_kind, path_mut, path_of, points_param, poly_bounds, samples_param, stroke_paint, stroke_pressure, subpath_len, target_paths, - within_input_bound, + brush_region, path_kind, path_mut, path_of, poly_bounds, pressure_region, samples_param, size_pressure, stroke_paint, stroke_pressure, + subpath_len, target_paths, within_input_bound, }; use super::{ Anchor, Appearance, BTreeSet, BoolOp, Cap, Color, Document, EngineError, FillRule, Join, NewArt, Node, NodeId, NodeKind, Paint, PathData, Point, @@ -602,11 +602,15 @@ fn adjacent_to_topmost(doc: &Document, touched: &[NodeId], paint: &Paint) -> Vec pub(super) fn blob(s: &mut Session, p: &Value) -> Result { const C: &str = "path.blob"; - let pts = points_param(p, "points", C)?; + let samples = samples_param(p, "points", C)?; let size = number_or(p, "size", 10.0, C)?; if !(size.is_finite() && size > 0.0) { return Err(bad(C, "size must be positive")); } + let pressure = size_pressure(p, &samples, C)?; + let pts: Vec = samples.into_iter().map(|(pt, _)| pt).collect(); + // The widest the brush gets: the area merges look in. + let reach = pressure.as_ref().map_or(size, |(_, v)| size + v); // With `fidelity` (pt), the brush follows the stroke fitted by [`fit_freehand`], as a Pencil // stroke is fitted. Without it, or when the fitted stroke has no length (a short stroke back to // its start), the brush follows every point. @@ -614,11 +618,31 @@ pub(super) fn blob(s: &mut Session, p: &Value) -> Result { None | Some(Value::Null) => None, Some(_) => Some(number_or(p, "fidelity", 0.0, C)?.clamp(vectorcraft_tools::draw2::MIN_FIDELITY, 100.0)), }; - let fitted = fidelity - .filter(|_| pts.len() > 1) - .map(|tol| po::outline_stroke(&PathData::single(fit_freehand(&pts, tol, false)), size, Cap::Round, Join::Round, 4.0)) - .filter(|r| !r.is_empty()); - let region = fitted.unwrap_or_else(|| brush_region(&pts, size)); + let spine = |tol: Option| match tol { + Some(tol) => PathData::single(fit_freehand(&pts, tol, false)), + None => PathData::single(SubPath::polyline(&pts, false)), + }; + let region = match (&pressure, pts.len() > 1) { + (Some((prof, variation)), true) => { + let fitted = match fidelity { + Some(tol) => Some(pressure_region(&spine(Some(tol)), size, *variation, prof)?).filter(|r| !r.is_empty()), + None => None, + }; + match fitted { + Some(r) => r, + None => pressure_region(&spine(None), size, *variation, prof)?, + } + } + // A click: one dab as wide as the pen pressed. + (Some((prof, variation)), false) => brush_region(&pts, vectorcraft_tools::draw2::pressure_size(size, *variation, prof.at(0.0))), + (None, _) => { + let fitted = fidelity + .filter(|_| pts.len() > 1) + .map(|tol| po::outline_stroke(&spine(Some(tol)), size, Cap::Round, Join::Round, 4.0)) + .filter(|r| !r.is_empty()); + fitted.unwrap_or_else(|| brush_region(&pts, size)) + } + }; if region.is_empty() { return Err(EngineError::Other("empty brush stroke".into())); } @@ -638,7 +662,7 @@ pub(super) fn blob(s: &mut Session, p: &Value) -> Result { let all = Selection::default(); let from = if only_selection { &st.selection } else { &all }; // A fitted stroke can curve outside the points' bounds, so the area also takes in the shape. - let area = region.control_bounds().map_or_else(|| poly_bounds(&pts, size), |b| b.union(poly_bounds(&pts, size))); + let area = region.control_bounds().map_or_else(|| poly_bounds(&pts, reach), |b| b.union(poly_bounds(&pts, reach))); for id in target_paths(&st.doc, from, area) { let Some(n) = st.doc.node(id) else { continue }; if !blob_match(n, &paint) { diff --git a/crates/engine/src/cmd/effectcmd/tests.rs b/crates/engine/src/cmd/effectcmd/tests.rs index c23c578d06..e5279391ac 100644 --- a/crates/engine/src/cmd/effectcmd/tests.rs +++ b/crates/engine/src/cmd/effectcmd/tests.rs @@ -68,7 +68,7 @@ fn solid_effects_apply_save_edit_export_expand_and_undo() { assert!(s.execute("effect.setParams", &json!({"index": 0, "params": {"bevel": "nope"}, "ids": [id.0], "item": null})).is_err()); let svg = s.execute("document.serialize", &json!({"format": "svg"})).unwrap(); let svg = svg["data"].as_str().or_else(|| svg["text"].as_str()).map(str::to_string).unwrap_or_else(|| svg.to_string()); - assert!(svg.matches("= 2, "{effect}: exported as vector faces"); + assert!(vectorcraft_testkit::svg_shapes(&svg) >= 2, "{effect}: exported as vector faces"); s.execute("effect.expandAppearance", &json!({"ids": [id.0]})).unwrap(); assert!(matches!(node(&s, id).kind, NodeKind::Group { .. }), "{effect}"); assert!(!effects::has_solid(&node(&s, id))); diff --git a/crates/engine/src/cmd/fileio.rs b/crates/engine/src/cmd/fileio.rs index 6893c6f845..c8cb7218a7 100644 --- a/crates/engine/src/cmd/fileio.rs +++ b/crates/engine/src/cmd/fileio.rs @@ -36,6 +36,7 @@ pub(crate) use load::{MAX_RASTER_ALLOC, size_note}; mod metafile; mod naming; mod native; +mod pcxread; pub mod pdf; mod pdfimport; pub mod pngtext; @@ -192,6 +193,9 @@ mod tests_psd; #[cfg(test)] mod tests_psdread; +#[cfg(test)] +mod tests_pcxread; + #[cfg(test)] mod tests_epsimport; diff --git a/crates/engine/src/cmd/fileio/formats.rs b/crates/engine/src/cmd/fileio/formats.rs index fbf9efe925..f727215341 100644 --- a/crates/engine/src/cmd/fileio/formats.rs +++ b/crates/engine/src/cmd/fileio/formats.rs @@ -489,6 +489,8 @@ pub const FORMATS: &[Format] = &[ reader("psb", "PSB", &["psb"], "image/x-psb", true), // PostScript programs, read as EPS files are; Print to PostScript writes them, exports don't. reader("ps", "PostScript", &["ps"], "application/postscript", false), + // ZSoft PCX images, read by `pcxread` and stored as PNG; exports don't write them. + reader("pcx", "PCX", &["pcx"], "image/x-pcx", true), ]; /// Every extension `document.open` reads (the "All readable files" filter of open dialogs). @@ -512,6 +514,7 @@ pub const OPEN_EXTS: &[&str] = &[ "vda", "icb", "vst", + "pcx", "psd", "psb", "vctemplate", @@ -528,10 +531,10 @@ pub const OPEN_EXTS: &[&str] = &[ /// Extensions in [`OPEN_EXTS`] the packaging declares no type for: Photoshop documents belong to /// raster editors, so Finder and file managers don't offer a vector app for them, and there is no -/// `.epsf`, `.ps` or Targa type (File › Open and Place still read them all). On Linux the desktop -/// entry's EPS type (shared-mime-info's) also covers `.epsf`, so file managers offer VectorCraft -/// for it. -pub const UNASSOCIATED_EXTS: &[&str] = &["psd", "psb", "epsf", "ps", "tga", "vda", "icb", "vst"]; +/// `.epsf`, `.ps`, Targa or PCX type (File › Open and Place still read them all). On Linux the +/// desktop entry's EPS type (shared-mime-info's) also covers `.epsf`, so file managers offer +/// VectorCraft for it. +pub const UNASSOCIATED_EXTS: &[&str] = &["psd", "psb", "epsf", "ps", "tga", "vda", "icb", "vst", "pcx"]; /// The extension that picks each writable format when exporting (the format's first; PNG-8 shares /// `.png` with PNG, so `.png` comes once), in [`FORMATS`] order. @@ -577,6 +580,7 @@ pub const PLACE_EXTS: &[&str] = &[ "vda", "icb", "vst", + "pcx", "psd", "psb", "vctemplate", diff --git a/crates/engine/src/cmd/fileio/load.rs b/crates/engine/src/cmd/fileio/load.rs index ecb1c30993..c1ebdf7233 100644 --- a/crates/engine/src/cmd/fileio/load.rs +++ b/crates/engine/src/cmd/fileio/load.rs @@ -197,6 +197,13 @@ fn from_editing_data_alone(bytes: &[u8], opts: &LoadOptions) -> Option bool { + let mut art = false; + doc.walk(|n| art |= !n.is_layer()); + !art +} + /// Is `e` the error of a file whose pages are only a placeholder /// ([`vectorcraft_pdf::PdfError::PlaceholderOnly`])? pub(crate) fn is_placeholder(e: &EngineError) -> bool { @@ -272,8 +279,13 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result restore_or_import(editing, || match super::pdfimport::import(bytes, opts, format.id != "pdf") { Ok(r) => { // Pages of text alone: the editing copy alone where it reads, as for a file - // saved without its PDF part (#1387: else the page, which is the art). - let alone = r.only_text.then(|| from_editing_data_alone(bytes, opts)).flatten().and_then(|read| read.ok()); + // saved without its PDF part (#1387: else the page, which is the art). So too + // pages that draw nothing at all: there is no page art to check the layers + // against, and the empty page would lose all of it. + let alone = (r.only_text || draws_nothing(&r.document)) + .then(|| from_editing_data_alone(bytes, opts)) + .flatten() + .and_then(|read| read.ok()); let (doc, warnings, read) = match alone { Some((doc, warnings)) => (doc, warnings, true), None => through_editing_data(bytes, opts, r.document, r.warnings, r.user_unit), @@ -561,6 +573,8 @@ pub(crate) fn size_note(bytes: &[u8]) -> Option { /// too ([`vectorcraft_doc::cmyk::group3_tiff_rgba`]). /// Grayscale TIFFs with an alpha channel or other extra channels, which the decoder can't read /// either, become RGBA too, whether they store their channels together or one plane per channel. +/// A PCX file is recognized by its header ([`super::pcxread::is_pcx`]) and read by +/// [`super::pcxread::decode`], which refuses an image past [`MAX_RASTER_ALLOC`] before decoding. /// A Targa file, which starts with no signature, is recognized by its header /// ([`super::tgaread::is_targa`]) and becomes RGBA with the transparency it stores /// ([`super::tgaread::fix_alpha`]). An image stored as PNG whose decoded samples, or whose pixels @@ -580,6 +594,9 @@ pub fn raster_image(bytes: &[u8]) -> Result { if reader.format().is_none() && super::tgaread::is_targa(bytes) { reader.set_format(image::ImageFormat::Tga); } + if reader.format().is_none() && super::pcxread::is_pcx(bytes) { + return as_png(super::pcxread::decode(bytes, MAX_RASTER_ALLOC).map_err(err)?, ppi); + } let mut limits = image::Limits::default(); limits.max_alloc = Some(MAX_RASTER_ALLOC); reader.limits(limits); diff --git a/crates/engine/src/cmd/fileio/pcxread.rs b/crates/engine/src/cmd/fileio/pcxread.rs new file mode 100644 index 0000000000..aabbbc2642 --- /dev/null +++ b/crates/engine/src/cmd/fileio/pcxread.rs @@ -0,0 +1,166 @@ +//! Reading PCX files (`.pcx`) for File › Open and File › Place, from the ZSoft PCX Technical +//! Reference Manual (release 5). [`is_pcx`] recognizes a file by the first fields of its 128-byte +//! header, and [`decode`] reads its run-length encoded scan lines into RGBA pixels: 1-bit with two +//! colors; 1-bit in two to four planes and 4-bit with up to 16 colors; 2-bit CGA pictures in the +//! four colors their CGA palette settings pick; 8-bit with the +//! 256-color palette after the image data (gray levels without one); and 24-bit color in three +//! 8-bit planes. The file is untrusted: every read is checked. + +/// The size of the header, after which the image data starts. +const HEADER: usize = 128; + +/// The message for a file whose header or image data ends early. +const TRUNCATED: &str = "the PCX file is cut short"; + +/// The message for a header whose window or line length can't hold its image. +const DAMAGED: &str = "the PCX file's header is damaged"; + +/// The 16 colors of the EGA palette, which files of versions 0 and 3 use instead of the header's. +const EGA: [[u8; 3]; 16] = [ + [0x00, 0x00, 0x00], + [0x00, 0x00, 0xaa], + [0x00, 0xaa, 0x00], + [0x00, 0xaa, 0xaa], + [0xaa, 0x00, 0x00], + [0xaa, 0x00, 0xaa], + [0xaa, 0x55, 0x00], + [0xaa, 0xaa, 0xaa], + [0x55, 0x55, 0x55], + [0x55, 0x55, 0xff], + [0x55, 0xff, 0x55], + [0x55, 0xff, 0xff], + [0xff, 0x55, 0x55], + [0xff, 0x55, 0xff], + [0xff, 0xff, 0x55], + [0xff, 0xff, 0xff], +]; + +/// Does `bytes` start with a PCX header? The manufacturer byte is `0x0A`, the version 0, 2, 3, 4 +/// or 5, the encoding 1 (run-length) and the bits per pixel of each plane 1, 2, 4 or 8. +pub(super) fn is_pcx(bytes: &[u8]) -> bool { + matches!(bytes, [0x0a, 0 | 2 | 3 | 4 | 5, 1, 1 | 2 | 4 | 8, ..]) +} + +/// The resolution in the header's HDpi and VDpi fields; `None` when either is 0 or the header is +/// cut short. +pub(super) fn resolution(bytes: &[u8]) -> Option<(f64, f64)> { + let le = |at: usize| Some(u16::from_le_bytes([*bytes.get(at)?, *bytes.get(at + 1)?])); + let (x, y) = (le(12)?, le(14)?); + (x > 0 && y > 0).then(|| (f64::from(x), f64::from(y))) +} + +/// The pixels of PCX file `bytes`, which [`is_pcx`] accepts, refused when they or the decoded +/// scan lines take more than `max_alloc` bytes (the pixels counted as RGBA) before anything is +/// decoded. +pub(super) fn decode(bytes: &[u8], max_alloc: u64) -> Result { + let head = bytes.get(..HEADER).ok_or(TRUNCATED)?; + let le = |at: usize| usize::from(u16::from_le_bytes([head[at], head[at + 1]])); + let (version, bits, planes) = (head[1], head[3], head[65]); + let (x_min, y_min, x_max, y_max) = (le(4), le(6), le(8), le(10)); + let line = le(66); + if !matches!((bits, planes), (1, 1..=4) | (2 | 4, 1) | (8, 1 | 3)) { + return Err(format!("PCX files with {bits}-bit pixels in {planes} planes can't be read")); + } + if x_max < x_min || y_max < y_min { + return Err(DAMAGED.into()); + } + let (w, h) = (x_max - x_min + 1, y_max - y_min + 1); + // Each plane's line holds the row's pixels, padded to an even number of bytes. + if line * 8 < w * usize::from(bits) { + return Err(DAMAGED.into()); + } + let scan = line * usize::from(planes); + let rgba = w as u64 * h as u64 * 4; + if rgba > max_alloc || scan as u64 * h as u64 > max_alloc { + return Err(format!("an image of {w} × {h} pixels is too large to draw")); + } + // An 8-bit image's 256-color palette is its last 769 bytes, `0x0C` and then the colors; the + // image data ends before it. A `0x0C` there is image data instead when the image data runs to + // the end of the file. + let candidate = bytes.len().checked_sub(769).filter(|at| *at >= HEADER && (bits, planes) == (8, 1) && bytes.get(*at) == Some(&0x0c)); + let body = bytes.get(HEADER..).unwrap_or_default(); + let (tail, decoded) = match candidate { + Some(at) => match unpack(body, scan * h) { + Ok((data, used)) if used == body.len() => (None, Ok((data, used))), + _ => (Some(at), unpack(bytes.get(HEADER..at).unwrap_or_default(), scan * h)), + }, + None => (None, unpack(body, scan * h)), + }; + let (data, used) = decoded?; + // A palette marker right after the image data with fewer than 768 colors after it is a palette + // cut short. + let after = bytes.get(HEADER + used..).unwrap_or_default(); + if tail.is_none() && (bits, planes) == (8, 1) && after.first() == Some(&0x0c) && after.len() < 769 { + return Err(TRUNCATED.into()); + } + let palette: Vec<[u8; 3]> = match (bits, planes) { + (8, 1) => match tail.and_then(|at| bytes.get(at + 1..)) { + Some(colors) => colors.as_chunks::<3>().0.to_vec(), + None => (0..=255).map(|v| [v; 3]).collect(), + }, + // A 1-bit image takes the header palette's first two colors; versions without a palette, + // and headers whose two colors are the same (left unset), give black and white. + (1, 1) if matches!(version, 0 | 3) || head[16..19] == head[19..22] => vec![[0; 3], [255; 3]], + // A 2-bit image is a CGA picture, whose header holds CGA palette settings instead of colors. + (2, 1) => cga(head[16], head[19]), + _ if matches!(version, 0 | 3) => EGA.to_vec(), + _ => head[16..64].as_chunks::<3>().0.to_vec(), + }; + let mut img = image::RgbaImage::new(w as u32, h as u32); + for (y, row) in data.chunks_exact(scan).enumerate() { + let plane = |p: usize| row.get(p * line..(p + 1) * line).unwrap_or_default(); + for x in 0..w { + let rgb = if bits == 8 && planes == 3 { + [0, 1, 2].map(|p| plane(p).get(x).copied().unwrap_or(0)) + } else { + // Plane p gives bits p × bits and up of the color index. + let index = (0..usize::from(planes)).fold(0, |index, p| { + let at = x * usize::from(bits); + let byte = plane(p).get(at / 8).copied().unwrap_or(0); + let value = (byte >> (8 - usize::from(bits) - at % 8)) & (0xff >> (8 - bits)); + index | usize::from(value) << (p * usize::from(bits)) + }); + palette.get(index).copied().unwrap_or([0; 3]) + }; + img.put_pixel(x as u32, y as u32, image::Rgba([rgb[0], rgb[1], rgb[2], 255])); + } + } + Ok(img) +} + +/// The four colors of a CGA picture from header bytes 16 and 19. The top four bits of `background` +/// are the EGA color of index 0. The top three bits of `settings` are the color burst, palette and +/// intensity bits (C, P, I), which pick the other three: with color burst on (C = 0), P = 0 gives +/// green, red and brown and P = 1 gives cyan, magenta and light gray; with it off (C = 1) they are +/// cyan, red and light gray. I = 1 gives the bright version of each (brown becomes yellow). +fn cga(background: u8, settings: u8) -> Vec<[u8; 3]> { + let foreground: [usize; 3] = match settings >> 6 { + 0 => [2, 4, 6], + 1 => [3, 5, 7], + _ => [3, 4, 7], + }; + let bright = if settings & 0x20 != 0 { 8 } else { 0 }; + let ega = |i: usize| EGA.get(i).copied().unwrap_or([0; 3]); + let mut colors = vec![ega(usize::from(background >> 4))]; + colors.extend(foreground.map(|i| ega(i + bright))); + colors +} + +/// `len` bytes of run-length encoded image data: a byte with its top two bits set repeats the +/// next byte as many times as its other six bits count, and any other byte stands for itself. +/// Runs may cross the end of a scan line. Also returns how many bytes of `data` were read. +fn unpack(data: &[u8], len: usize) -> Result<(Vec, usize), String> { + let mut out = Vec::with_capacity(len); + let mut bytes = data.iter(); + while out.len() < len { + let &b = bytes.next().ok_or(TRUNCATED)?; + if b & 0xc0 == 0xc0 { + let &v = bytes.next().ok_or(TRUNCATED)?; + let n = usize::from(b & 0x3f).min(len - out.len()); + out.resize(out.len() + n, v); + } else { + out.push(b); + } + } + Ok((out, data.len() - bytes.len())) +} diff --git a/crates/engine/src/cmd/fileio/ppi.rs b/crates/engine/src/cmd/fileio/ppi.rs index 1c04db9c88..61b7417567 100644 --- a/crates/engine/src/cmd/fileio/ppi.rs +++ b/crates/engine/src/cmd/fileio/ppi.rs @@ -1,5 +1,6 @@ //! Image resolution metadata (pixels per inch): PNG `pHYs`, JPEG JFIF density or EXIF, TIFF and -//! WebP EXIF resolution tags, BMP pixels per metre, a Photoshop document's ResolutionInfo. Place +//! WebP EXIF resolution tags, BMP pixels per metre, a Photoshop document's ResolutionInfo, a PCX +//! header's HDpi and VDpi. Place //! sizes an image by it (72 ppi when the file has none); images converted to PNG on import keep it //! as a `pHYs` chunk. @@ -21,6 +22,8 @@ pub fn resolution(bytes: &[u8]) -> Option<(f64, f64)> { bmp(bytes) } else if super::psdread::is_psd(bytes) { super::psdread::resolution(bytes) + } else if super::pcxread::is_pcx(bytes) { + super::pcxread::resolution(bytes) } else { None }; diff --git a/crates/engine/src/cmd/fileio/tests_aiimport.rs b/crates/engine/src/cmd/fileio/tests_aiimport.rs index 3f0dce5c15..acf7d43b17 100644 --- a/crates/engine/src/cmd/fileio/tests_aiimport.rs +++ b/crates/engine/src/cmd/fileio/tests_aiimport.rs @@ -535,6 +535,47 @@ fn an_ai_file_whose_pdf_part_is_only_text_still_opens_from_editing_data_that_rea check_sample(&s); } +#[test] +fn an_ai_file_whose_pdf_part_is_cropped_to_its_art_opens_from_its_layers() { + // A 400 × 200 pt artboard with two red bars across (100, 50)–(300, 150). The PDF part's page + // is that art's box, 200 × 100 pt (the editing data's bounding box), not the artboard. + let red = "0 1 1 0 1 0 0 Xa\n"; + let art = ai::layer("Art", &format!("{red}{}f\n{red}{}f\n", ai::rect(100.0, 50.0, 180.0, 150.0), ai::rect(220.0, 50.0, 300.0, 150.0))); + let data = ai::editing_data_in([100.0, 50.0, 300.0, 150.0], [0.0, 0.0, 400.0, 200.0], &art); + let page = "1 0 0 rg 0 0 80 100 re f 120 0 80 100 re f"; + let mut s = Session::new(); + let r = open(&mut s, "cropped.ai", &ai::ai(&compressed(data.as_bytes()), page), json!({})).unwrap(); + assert!(!r["warnings"].to_string().contains("weren't read"), "{r}"); + let doc = &s.doc().unwrap().doc; + assert_eq!(names(&doc.layers), ["Art"]); + assert_eq!(doc.artboards.len(), 1); + assert_eq!(doc.artboards[0].rect, vectorcraft_geom::Rect::new(0.0, 0.0, 400.0, 200.0), "the file's artboard, not its page"); + let bars = doc.layers[0].children().unwrap(); + assert_eq!(bars.len(), 2); + let b = bars[0].geometric_bounds().unwrap(); + assert!((b.x0 - 100.0).abs() < 0.01 && (b.y0 - 50.0).abs() < 0.01, "where the artboard has it: {b:?}"); +} + +#[test] +fn an_ai_file_whose_pdf_part_draws_nothing_opens_from_its_editing_data() { + // A PDF-compatible `.ai` whose PDF part is a page with nothing on it (no notice text either), + // with or without the boxes that say where its art is: its editing data is the art. + for boxed in ["", "/ArtBox [0 0 200 100] /TrimBox [0 0 200 100]"] { + let mut s = Session::new(); + let r = open(&mut s, "blank.ai", &ai::ai_with(&compressed(&ai::sample_data()), "", boxed), json!({})).unwrap(); + assert_eq!(r["warnings"], json!([]), "{boxed:?}: {r}"); + check_sample(&s); + // The PDF part alone, as asked: its empty page. + open(&mut s, "blank.ai", &ai::ai_with(&compressed(&ai::sample_data()), "", boxed), json!({"editingData": false})).unwrap(); + let layers = &s.doc().unwrap().doc.layers; + assert!(layers.iter().all(|l| l.children().is_none_or(|c| c.is_empty())), "{boxed:?}"); + } + // Editing data that can't be read leaves the empty page, as before. + let mut s = Session::new(); + open(&mut s, "blank.ai", &ai::ai(b"%AI24_ZStandard_Data\0\0\0\0\0\0\0\0", ""), json!({})).unwrap(); + assert_ne!(names(&s.doc().unwrap().doc.layers), ["Art", "Hidden"]); +} + #[test] fn editing_data_false_opens_only_what_the_page_prints() { let mut s = Session::new(); diff --git a/crates/engine/src/cmd/fileio/tests_dxf.rs b/crates/engine/src/cmd/fileio/tests_dxf.rs index 6bea6dad72..eec800d74a 100644 --- a/crates/engine/src/cmd/fileio/tests_dxf.rs +++ b/crates/engine/src/cmd/fileio/tests_dxf.rs @@ -101,7 +101,7 @@ fn selected_only_exports_the_selection_in_its_layers() { // Other formats take it too. s.execute("select.set", &json!({"ids": [line]})).unwrap(); let svg = s.execute("document.serialize", &json!({"format": "svg", "selectedOnly": true})).unwrap()["text"].as_str().unwrap().to_string(); - assert_eq!((svg.matches(" Vec { + let mut f = vec![0x0a, version, 1, bits]; + for v in [x0, 0, x0.wrapping_add(w).wrapping_sub(1), h.wrapping_sub(1), dpi, dpi] { + f.extend(v.to_le_bytes()); + } + let mut palette = [0; 48]; + for (i, c) in colors.iter().take(16).enumerate() { + palette[i * 3..i * 3 + 3].copy_from_slice(c); + } + f.extend(palette); + f.extend([0, planes]); + f.extend(line.to_le_bytes()); + f.extend(1u16.to_le_bytes()); + f.resize(128, 0); + f.extend(data); + f +} + +/// `raw` run-length encoded as the manual describes: runs of up to 63 bytes, and single bytes with +/// their top two bits set written as runs of one. +fn rle(raw: &[u8]) -> Vec { + let mut out = vec![]; + let mut i = 0; + while i < raw.len() { + let n = raw[i..].iter().take(63).take_while(|b| **b == raw[i]).count(); + if n > 1 || raw[i] >= 0xc0 { + out.extend([0xc0 | n as u8, raw[i]]); + } else { + out.push(raw[i]); + } + i += n; + } + out +} + +/// The pixels `raster_image` stores for `f`, row by row. +fn pixels(f: &[u8]) -> Vec<[u8; 4]> { + let img = raster_image(f).unwrap(); + image::load_from_memory(&img.blob.bytes).unwrap().to_rgba8().pixels().map(|p| p.0).collect() +} + +/// The 16 colors of a header palette: entry `i` is (16 i, 255 − 16 i, i). +fn header_colors() -> Vec<[u8; 3]> { + (0..16u8).map(|i| [i * 16, 255 - i * 16, i]).collect() +} + +fn opaque([r, g, b]: [u8; 3]) -> [u8; 4] { + [r, g, b, 255] +} + +#[test] +fn every_depth_and_plane_layout_reads() { + let colors = header_colors(); + let (white, black) = ([255; 4], [0, 0, 0, 255]); + + // 1 bit, three pixels in a two-byte line: 101 and 010, in the header palette's first two colors + // (here inverted: white, then black). + let bits = rle(&[0b1010_0000, 0, 0b0100_0000, 0]); + let f = pcx(5, 1, 1, 0, (3, 2), 2, 0, &[[255; 3], [0; 3]], &bits); + assert_eq!(pixels(&f), [black, white, black, white, black, white]); + let f = pcx(5, 1, 1, 0, (3, 2), 2, 0, &colors, &bits); + let (zero, one) = (opaque(colors[0]), opaque(colors[1])); + assert_eq!(pixels(&f), [one, zero, one, zero, one, zero]); + // Black and white when the palette is left unset or the version has none. + for (version, palette) in [(5, &[][..]), (3, &colors[..])] { + let f = pcx(version, 1, 1, 0, (3, 2), 2, 0, palette, &bits); + assert_eq!(pixels(&f), [white, black, white, black, white, black], "version {version}"); + } + + // 1 bit in four planes: plane p gives bit p of the index; indices 5 and 10. + let planes = rle(&[0x80, 0, 0x40, 0, 0x80, 0, 0x40, 0]); + let f = pcx(5, 1, 4, 0, (2, 1), 2, 0, &colors, &planes); + assert_eq!(pixels(&f), [opaque(colors[5]), opaque(colors[10])], "the header palette"); + // Versions 0 and 3 have no palette in their header: the EGA colors. + for version in [0, 3] { + let f = pcx(version, 1, 4, 0, (2, 1), 2, 0, &colors, &planes); + assert_eq!(pixels(&f), [[0xaa, 0, 0xaa, 255], [0x55, 0xff, 0x55, 255]], "version {version}"); + } + // Two planes give four colors, three give eight: index 3 and 6 (planes 1 and 2). + let f = pcx(5, 1, 3, 0, (2, 1), 2, 0, &colors, &rle(&[0x80, 0, 0xc0, 0, 0x40, 0])); + assert_eq!(pixels(&f), [opaque(colors[3]), opaque(colors[6])]); + + // 2 bits: indices 0 to 3 in one byte, the first pixel in the top bits, in the CGA colors that + // header bytes 16 (the background, in its top four bits) and 19 (C, P and I) pick. + let cga = |background: u8, settings: u8| { + let f = pcx(5, 2, 1, 0, (4, 1), 2, 0, &[[background, 0, 0], [settings, 0, 0]], &rle(&[0b0001_1011, 0])); + pixels(&f) + }; + let (blue, cyan, magenta, light_gray) = ([0, 0, 0xaa, 255], [0, 0xaa, 0xaa, 255], [0xaa, 0, 0xaa, 255], [0xaa; 3]); + assert_eq!(cga(0x10, 0b0100_0000), [blue, cyan, magenta, opaque(light_gray)], "P = 1, dim"); + let (light_green, light_red, yellow) = ([0x55, 0xff, 0x55, 255], [0xff, 0x55, 0x55, 255], [0xff, 0xff, 0x55, 255]); + assert_eq!(cga(0x0f, 0b0011_1111), [black, light_green, light_red, yellow], "P = 0, bright; low bits ignored"); + assert_eq!(cga(0xf0, 0b1010_0000), [white, [0x55, 0xff, 0xff, 255], light_red, white], "C = 1, bright"); + assert_eq!(cga(0, 0)[1..], [[0, 0xaa, 0, 255], [0xaa, 0, 0, 255], [0xaa, 0x55, 0, 255]], "P = 0, dim"); + + // 4 bits: indices 15, 1 and 7. + let f = pcx(5, 4, 1, 0, (3, 1), 2, 0, &colors, &rle(&[0xf1, 0x70])); + assert_eq!(pixels(&f), [opaque(colors[15]), opaque(colors[1]), opaque(colors[7])]); + + // 8 bits with the 256-color palette after the image data, from a window that starts at x 10: + // entry i is (i, 255 − i, 7). + let mut f = pcx(5, 8, 1, 10, (2, 2), 2, 0, &[], &rle(&[0, 1, 254, 255])); + f.push(0x0c); + f.extend((0..=255u8).flat_map(|i| [i, 255 - i, 7])); + assert_eq!(pixels(&f), [[0, 255, 7, 255], [1, 254, 7, 255], [254, 1, 7, 255], [255, 0, 7, 255]]); + // Without it, the index is a gray level. + let f = pcx(5, 8, 1, 0, (2, 2), 2, 0, &[], &rle(&[0, 1, 254, 255])); + assert_eq!(pixels(&f), [[0, 0, 0, 255], [1, 1, 1, 255], [254, 254, 254, 255], [255; 4]]); + // A gray level 12 769 bytes before the end of image data that runs to the end of the file. + let mut levels = vec![1; 1000]; + levels[231] = 0x0c; + let f = pcx(5, 8, 1, 0, (1000, 1), 1000, 0, &[], &levels); + assert_eq!(f.len() - 769, 128 + 231); + let read = pixels(&f); + assert_eq!((read.len(), read[231], read[232]), (1000, [12, 12, 12, 255], [1, 1, 1, 255])); + // A run may cross the end of a scan line. + let f = pcx(5, 8, 1, 0, (2, 2), 2, 0, &[], &[0xc4, 9]); + assert_eq!(pixels(&f), [[9, 9, 9, 255]; 4]); + + // 24 bits: each line holds its red, green and blue planes in turn; the padding byte is skipped. + let f = pcx(5, 8, 3, 0, (1, 2), 2, 0, &[], &rle(&[10, 0, 30, 0, 50, 0, 20, 0, 40, 0, 60, 0])); + assert_eq!(pixels(&f), [[10, 30, 50, 255], [20, 40, 60, 255]]); +} + +#[test] +fn pcx_files_open_place_and_paste_at_their_resolution() { + use crate::cmd::clipboard::{PASTE_ORDER, file_flavour}; + let b64 = vectorcraft_format::base64_encode; + let f = pcx(5, 8, 3, 0, (2, 1), 2, 144, &[], &rle(&[10, 20, 30, 40, 50, 60])); + assert_eq!(ppi::resolution(&f), Some((144.0, 144.0))); + assert_eq!(ppi::resolution(&pcx(5, 8, 3, 0, (2, 1), 2, 0, &[], &[])), None, "no resolution"); + + let mut s = Session::new(); + let r = s.execute("document.open", &json!({"name": "art.pcx", "dataBase64": b64(&f)})).unwrap(); + assert_eq!((&r["format"], &r["warnings"]), (&json!("pcx"), &json!([])), "{r}"); + assert_eq!(s.doc().unwrap().doc.artboards[0].rect.size(), vectorcraft_geom::Size::new(1.0, 0.5), "2 × 1 px at 144 ppi"); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let r = s.execute("file.place", &json!({"name": "ART.PCX", "dataBase64": b64(&f)})).unwrap(); + assert_eq!((&r["format"], r["ids"].as_array().map(Vec::len)), (&json!("pcx"), Some(1)), "{r}"); + + // Copied in a file manager, a PCX file pastes as a bitmap. + assert_eq!(file_flavour("art.pcx", &f, &PASTE_ORDER), Some("image/x-pcx")); + let r = s.execute("clipboard.importImage", &json!({"mime": "image/x-pcx", "dataBase64": b64(&f)})).unwrap(); + assert_eq!((&r["count"], &r["pixelWidth"], &r["pixelHeight"]), (&json!(1), &json!(2), &json!(1)), "{r}"); + // Glass's Load Texture… reads it too. + assert!(texture_image(&f).is_ok()); + + // The dialogs list PCX; the desktop packaging doesn't associate it; nothing writes it. + assert!(OPEN_EXTS.contains(&"pcx") && PLACE_EXTS.contains(&"pcx") && UNASSOCIATED_EXTS.contains(&"pcx")); + let filter = ("PCX", &["pcx"][..]); + assert!(open_filters().any(|f| f == filter) && place_filters().any(|f| f == filter)); + let r = s.execute("document.formats", &json!({})).unwrap(); + let pcx_format = r["formats"].as_array().unwrap().iter().find(|f| f["id"] == "pcx").unwrap().clone(); + assert_eq!((pcx_format["read"].as_bool(), pcx_format["write"].as_bool()), (Some(true), Some(false))); + assert_eq!(format_for_name("a.pcx").map(|f| f.id), Some("pcx")); +} + +#[test] +fn damaged_and_unsupported_files_are_refused_with_a_message() { + let message = |f: &[u8]| raster_image(f).err().expect("refused").to_string(); + let gray = pcx(5, 8, 1, 0, (2, 2), 2, 0, &[], &[1, 2, 3, 4]); + + // A header or image data cut short. + assert_eq!(message(&gray[..60]), "the PCX file is cut short"); + assert_eq!(message(&gray[..131]), "the PCX file is cut short"); + assert_eq!(message(&pcx(5, 8, 1, 0, (2, 2), 2, 0, &[], &[1, 0xc2])), "the PCX file is cut short", "a run without its byte"); + // The palette after the image data isn't read as pixels the image data lacks. + let mut short = pcx(5, 8, 1, 0, (2, 2), 2, 0, &[], &[1, 2, 3]); + short.push(0x0c); + short.extend([7; 768]); + assert_eq!(message(&short), "the PCX file is cut short", "three pixels and a palette"); + // A palette marker after the image data with fewer than 768 colors after it. + let mut cut_palette = gray.clone(); + cut_palette.push(0x0c); + cut_palette.extend([7; 767]); + assert_eq!(message(&cut_palette), "the PCX file is cut short", "a palette cut short"); + assert_eq!(message(&[&gray[..], &[0x0c]].concat()), "the PCX file is cut short", "a marker alone"); + let mut s = Session::new(); + let e = s.execute("document.open", &json!({"name": "a.pcx", "dataBase64": vectorcraft_format::base64_encode(&gray[..131])})); + assert!(e.expect_err("refused").to_string().contains("the PCX file is cut short")); + + // Planes and depths the manual doesn't define. + assert_eq!(message(&pcx(5, 8, 2, 0, (2, 2), 2, 0, &[], &[])), "PCX files with 8-bit pixels in 2 planes can't be read"); + assert_eq!(message(&pcx(5, 4, 3, 0, (2, 2), 2, 0, &[], &[])), "PCX files with 4-bit pixels in 3 planes can't be read"); + assert_eq!(message(&pcx(5, 1, 5, 0, (2, 2), 2, 0, &[], &[])), "PCX files with 1-bit pixels in 5 planes can't be read"); + + // A window that ends before it starts, and lines too short for the width. + let mut backwards = gray.clone(); + backwards[8..10].copy_from_slice(&0u16.to_le_bytes()); + backwards[4..6].copy_from_slice(&5u16.to_le_bytes()); + assert_eq!(message(&backwards), "the PCX file's header is damaged"); + assert_eq!(message(&pcx(5, 8, 1, 0, (3, 1), 2, 0, &[], &[1, 2, 3, 4])), "the PCX file's header is damaged"); + assert_eq!(message(&pcx(5, 1, 1, 0, (17, 1), 2, 0, &[], &[0; 4])), "the PCX file's header is damaged"); + + // Past the allowance, from the header: the pixels as RGBA, and the scan lines of a narrow image + // with long lines. + let huge = pcx(5, 1, 1, 0, (0, 0), 8192, 0, &[], &[]); + assert_eq!(message(&huge), "an image of 65536 × 65536 pixels is too large to draw"); + let long = pcx(5, 8, 3, 0, (1, 0), 65535, 0, &[], &[]); + assert_eq!(message(&long), "an image of 1 × 65536 pixels is too large to draw"); + assert!(decode(&long, 1 << 20).is_err()); + + // Headers with values the manual doesn't define aren't PCX files. + assert!(is_pcx(&gray)); + for bad in [[0x0a, 1, 1, 8], [0x0a, 6, 1, 8], [0x0a, 5, 0, 8], [0x0a, 5, 1, 3], [0x0b, 5, 1, 8]] { + assert!(!is_pcx(&bad), "{bad:?}"); + } +} diff --git a/crates/engine/src/cmd/fileio/tests_svg.rs b/crates/engine/src/cmd/fileio/tests_svg.rs index f9b8316e86..73ee604a98 100644 --- a/crates/engine/src/cmd/fileio/tests_svg.rs +++ b/crates/engine/src/cmd/fileio/tests_svg.rs @@ -50,7 +50,7 @@ fn every_option_changes_the_output() { changed(&mut s, json!({"svg": {"styling": "css"}}), &|o| o.contains("